2 * Copyright (c) 2008-2010 Rui Paulo
3 * Copyright (c) 2006 Marcel Moolenaar
6 * Copyright (c) 2018 Netflix, Inc.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
36 #include <sys/param.h>
37 #include <sys/reboot.h>
50 #include <bootstrap.h>
55 #include "loader_efi.h"
57 struct arch_switch archsw; /* MI/MD interface boundary */
59 EFI_GUID acpi = ACPI_TABLE_GUID;
60 EFI_GUID acpi20 = ACPI_20_TABLE_GUID;
61 EFI_GUID devid = DEVICE_PATH_PROTOCOL;
62 EFI_GUID imgid = LOADED_IMAGE_PROTOCOL;
63 EFI_GUID mps = MPS_TABLE_GUID;
64 EFI_GUID netid = EFI_SIMPLE_NETWORK_PROTOCOL;
65 EFI_GUID smbios = SMBIOS_TABLE_GUID;
66 EFI_GUID smbios3 = SMBIOS3_TABLE_GUID;
67 EFI_GUID dxe = DXE_SERVICES_TABLE_GUID;
68 EFI_GUID hoblist = HOB_LIST_TABLE_GUID;
69 EFI_GUID lzmadecomp = LZMA_DECOMPRESSION_GUID;
70 EFI_GUID mpcore = ARM_MP_CORE_INFO_TABLE_GUID;
71 EFI_GUID esrt = ESRT_TABLE_GUID;
72 EFI_GUID memtype = MEMORY_TYPE_INFORMATION_TABLE_GUID;
73 EFI_GUID debugimg = DEBUG_IMAGE_INFO_TABLE_GUID;
74 EFI_GUID fdtdtb = FDT_TABLE_GUID;
75 EFI_GUID inputid = SIMPLE_TEXT_INPUT_PROTOCOL;
78 * Number of seconds to wait for a keystroke before exiting with failure
79 * in the event no currdev is found. -2 means always break, -1 means
80 * never break, 0 means poll once and then reboot, > 0 means wait for
81 * that many seconds. "fail_timeout" can be set in the environment as
84 static int fail_timeout = 5;
87 * Current boot variable
92 * Image that we booted from.
94 EFI_LOADED_IMAGE *boot_img;
100 EFI_DEVICE_PATH *path;
101 EFI_HANDLE *hin, *hin_end, *walker;
106 * Find all the handles that support the SIMPLE_TEXT_INPUT_PROTOCOL and
107 * do the typical dance to get the right sized buffer.
111 status = BS->LocateHandle(ByProtocol, &inputid, 0, &sz, 0);
112 if (status == EFI_BUFFER_TOO_SMALL) {
113 hin = (EFI_HANDLE *)malloc(sz);
114 status = BS->LocateHandle(ByProtocol, &inputid, 0, &sz,
116 if (EFI_ERROR(status))
119 if (EFI_ERROR(status))
123 * Look at each of the handles. If it supports the device path protocol,
124 * use it to get the device path for this handle. Then see if that
125 * device path matches either the USB device path for keyboards or the
126 * legacy device path for keyboards.
128 hin_end = &hin[sz / sizeof(*hin)];
129 for (walker = hin; walker < hin_end; walker++) {
130 status = OpenProtocolByHandle(*walker, &devid, (void **)&path);
131 if (EFI_ERROR(status))
134 while (!IsDevicePathEnd(path)) {
136 * Check for the ACPI keyboard node. All PNP3xx nodes
137 * are keyboards of different flavors. Note: It is
138 * unclear of there's always a keyboard node when
139 * there's a keyboard controller, or if there's only one
140 * when a keyboard is detected at boot.
142 if (DevicePathType(path) == ACPI_DEVICE_PATH &&
143 (DevicePathSubType(path) == ACPI_DP ||
144 DevicePathSubType(path) == ACPI_EXTENDED_DP)) {
145 ACPI_HID_DEVICE_PATH *acpi;
147 acpi = (ACPI_HID_DEVICE_PATH *)(void *)path;
148 if ((EISA_ID_TO_NUM(acpi->HID) & 0xff00) == 0x300 &&
149 (acpi->HID & 0xffff) == PNP_EISA_ID_CONST) {
154 * Check for USB keyboard node, if present. Unlike a
155 * PS/2 keyboard, these definitely only appear when
156 * connected to the system.
158 } else if (DevicePathType(path) == MESSAGING_DEVICE_PATH &&
159 DevicePathSubType(path) == MSG_USB_CLASS_DP) {
160 USB_CLASS_DEVICE_PATH *usb;
162 usb = (USB_CLASS_DEVICE_PATH *)(void *)path;
163 if (usb->DeviceClass == 3 && /* HID */
164 usb->DeviceSubClass == 1 && /* Boot devices */
165 usb->DeviceProtocol == 1) { /* Boot keyboards */
170 path = NextDevicePathNode(path);
179 set_currdev(const char *devname)
182 env_setenv("currdev", EV_VOLATILE, devname, efi_setcurrdev, env_nounset);
183 env_setenv("loaddev", EV_VOLATILE, devname, env_noset, env_nounset);
187 set_currdev_devdesc(struct devdesc *currdev)
191 devname = efi_fmtdev(currdev);
192 printf("Setting currdev to %s\n", devname);
193 set_currdev(devname);
197 set_currdev_devsw(struct devsw *dev, int unit)
199 struct devdesc currdev;
202 currdev.d_unit = unit;
204 set_currdev_devdesc(&currdev);
208 set_currdev_pdinfo(pdinfo_t *dp)
212 * Disks are special: they have partitions. if the parent
213 * pointer is non-null, we're a partition not a full disk
214 * and we need to adjust currdev appropriately.
216 if (dp->pd_devsw->dv_type == DEVT_DISK) {
217 struct disk_devdesc currdev;
219 currdev.dd.d_dev = dp->pd_devsw;
220 if (dp->pd_parent == NULL) {
221 currdev.dd.d_unit = dp->pd_unit;
222 currdev.d_slice = -1;
223 currdev.d_partition = -1;
225 currdev.dd.d_unit = dp->pd_parent->pd_unit;
226 currdev.d_slice = dp->pd_unit;
227 currdev.d_partition = 255; /* Assumes GPT */
229 set_currdev_devdesc((struct devdesc *)&currdev);
231 set_currdev_devsw(dp->pd_devsw, dp->pd_unit);
236 sanity_check_currdev(void)
240 return (stat("/boot/defaults/loader.conf", &st) == 0 ||
241 stat("/boot/kernel/kernel", &st) == 0);
246 probe_zfs_currdev(uint64_t guid)
249 struct zfs_devdesc currdev;
251 currdev.dd.d_dev = &zfs_dev;
252 currdev.dd.d_unit = 0;
253 currdev.pool_guid = guid;
254 currdev.root_guid = 0;
255 set_currdev_devdesc((struct devdesc *)&currdev);
256 devname = efi_fmtdev(&currdev);
257 init_zfs_bootenv(devname);
259 return (sanity_check_currdev());
264 try_as_currdev(pdinfo_t *hd, pdinfo_t *pp)
270 * If there's a zpool on this device, try it as a ZFS
271 * filesystem, which has somewhat different setup than all
272 * other types of fs due to imperfect loader integration.
273 * This all stems from ZFS being both a device (zpool) and
274 * a filesystem, plus the boot env feature.
276 if (efizfs_get_guid_by_handle(pp->pd_handle, &guid))
277 return (probe_zfs_currdev(guid));
280 * All other filesystems just need the pdinfo
281 * initialized in the standard way.
283 set_currdev_pdinfo(pp);
284 return (sanity_check_currdev());
288 * Sometimes we get filenames that are all upper case
289 * and/or have backslashes in them. Filter all this out
290 * if it looks like we need to do so.
304 #define SIZE(dp, edp) (size_t)((intptr_t)(void *)edp - (intptr_t)(void *)dp)
306 enum { BOOT_INFO_OK = 0, BAD_CHOICE = 1, NOT_SPECIFIC = 2 };
308 match_boot_info(char *boot_info, size_t bisz)
314 EFI_DEVICE_PATH *dp, *edp, *first_dp, *last_dp;
318 FILEPATH_DEVICE_PATH *fp;
323 * FreeBSD encodes it's boot loading path into the boot loader
324 * BootXXXX variable. We look for the last one in the path
325 * and use that to load the kernel. However, if we only fine
326 * one DEVICE_PATH, then there's nothing specific and we should
329 * In an ideal world, we'd look at the image handle we were
330 * passed, match up with the loader we are and then return the
331 * next one in the path. This would be most flexible and cover
332 * many chain booting scenarios where you need to use this
333 * boot loader to get to the next boot loader. However, that
334 * doesn't work. We rarely have the path to the image booted
335 * (just the device) so we can't count on that. So, we do the
336 * enxt best thing, we look through the device path(s) passed
337 * in the BootXXXX varaible. If there's only one, we return
338 * NOT_SPECIFIC. Otherwise, we look at the last one and try to
339 * load that. If we can, we return BOOT_INFO_OK. Otherwise we
340 * return BAD_CHOICE for the caller to sort out.
342 if (bisz < sizeof(attr) + sizeof(fplen) + sizeof(CHAR16))
346 memcpy(&attr, walker, sizeof(attr));
347 walker += sizeof(attr);
348 memcpy(&fplen, walker, sizeof(fplen));
349 walker += sizeof(fplen);
350 descr = (CHAR16 *)(intptr_t)walker;
351 len = ucs2len(descr);
352 walker += (len + 1) * sizeof(CHAR16);
353 last_dp = first_dp = dp = (EFI_DEVICE_PATH *)walker;
354 edp = (EFI_DEVICE_PATH *)(walker + fplen);
355 if ((char *)edp > ep)
357 while (dp < edp && SIZE(dp, edp) > sizeof(EFI_DEVICE_PATH)) {
358 text = efi_devpath_name(dp);
360 printf(" BootInfo Path: %S\n", text);
361 efi_free_devpath_name(text);
364 dp = (EFI_DEVICE_PATH *)((char *)dp + efi_devpath_length(dp));
368 * If there's only one item in the list, then nothing was
369 * specified. Or if the last path doesn't have a media
370 * path in it. Those show up as various VenHw() nodes
371 * which are basically opaque to us. Don't count those
372 * as something specifc.
374 if (last_dp == first_dp) {
375 printf("Ignoring Boot%04x: Only one DP found\n", boot_current);
378 if (efi_devpath_to_media_path(last_dp) == NULL) {
379 printf("Ignoring Boot%04x: No Media Path\n", boot_current);
384 * OK. At this point we either have a good path or a bad one.
387 pp = efiblk_get_pdinfo_by_device_path(last_dp);
389 printf("Ignoring Boot%04x: Device Path not found\n", boot_current);
392 set_currdev_pdinfo(pp);
393 if (!sanity_check_currdev()) {
394 printf("Ignoring Boot%04x: sanity check failed\n", boot_current);
399 * OK. We've found a device that matches, next we need to check the last
400 * component of the path. If it's a file, then we set the default kernel
401 * to that. Otherwise, just use this as the default root.
403 * Reminder: we're running very early, before we've parsed the defaults
404 * file, so we may need to have a hack override.
406 dp = efi_devpath_last_node(last_dp);
407 if (DevicePathType(dp) != MEDIA_DEVICE_PATH ||
408 DevicePathSubType(dp) != MEDIA_FILEPATH_DP) {
409 printf("Using Boot%04x for root partition\n", boot_current);
410 return (BOOT_INFO_OK); /* use currdir, default kernel */
412 fp = (FILEPATH_DEVICE_PATH *)dp;
413 ucs2_to_utf8(fp->PathName, &kernel);
414 if (kernel == NULL) {
415 printf("Not using Boot%04x: can't decode kernel\n", boot_current);
418 if (*kernel == '\\' || isupper(*kernel))
420 if (stat(kernel, &st) != 0) {
422 printf("Not using Boot%04x: can't find %s\n", boot_current,
426 setenv("kernel", kernel, 1);
428 text = efi_devpath_name(last_dp);
430 printf("Using Boot%04x %S + %s\n", boot_current, text,
432 efi_free_devpath_name(text);
435 return (BOOT_INFO_OK);
439 * Look at the passed-in boot_info, if any. If we find it then we need
440 * to see if we can find ourselves in the boot chain. If we can, and
441 * there's another specified thing to boot next, assume that the file
442 * is loaded from / and use that for the root filesystem. If can't
443 * find the specified thing, we must fail the boot. If we're last on
444 * the list, then we fallback to looking for the first available /
445 * candidate (ZFS, if there's a bootable zpool, otherwise a UFS
446 * partition that has either /boot/defaults/loader.conf on it or
447 * /boot/kernel/kernel (the default kernel) that we can use.
449 * We always fail if we can't find the right thing. However, as
450 * a concession to buggy UEFI implementations, like u-boot, if
451 * we have determined that the host is violating the UEFI boot
452 * manager protocol, we'll signal the rest of the program that
453 * a drop to the OK boot loader prompt is possible.
456 find_currdev(bool do_bootmgr, bool is_last,
457 char *boot_info, size_t boot_info_sz)
460 EFI_DEVICE_PATH *devpath, *copy;
470 * First choice: if rootdev is already set, use that, even if
473 rootdev = getenv("rootdev");
474 if (rootdev != NULL) {
475 printf("Setting currdev to configured rootdev %s\n", rootdev);
476 set_currdev(rootdev);
481 * Second choice: If we can find out image boot_info, and there's
482 * a follow-on boot image in that boot_info, use that. In this
483 * case root will be the partition specified in that image and
484 * we'll load the kernel specified by the file path. Should there
485 * not be a filepath, we use the default. This filepath overrides
489 rv = match_boot_info(boot_info, boot_info_sz);
491 case BOOT_INFO_OK: /* We found it */
493 case BAD_CHOICE: /* specified file not found -> error */
494 /* XXX do we want to have an escape hatch for last in boot order? */
496 } /* Nothing specified, try normal match */
501 * Did efi_zfs_probe() detect the boot pool? If so, use the zpool
502 * it found, if it's sane. ZFS is the only thing that looks for
503 * disks and pools to boot. This may change in the future, however,
504 * if we allow specifying which pool to boot from via UEFI variables
505 * rather than the bootenv stuff that FreeBSD uses today.
507 if (pool_guid != 0) {
508 printf("Trying ZFS pool\n");
509 if (probe_zfs_currdev(pool_guid))
512 #endif /* EFI_ZFS_BOOT */
515 * Try to find the block device by its handle based on the
516 * image we're booting. If we can't find a sane partition,
517 * search all the other partitions of the disk. We do not
518 * search other disks because it's a violation of the UEFI
519 * boot protocol to do so. We fail and let UEFI go on to
520 * the next candidate.
522 dp = efiblk_get_pdinfo_by_handle(boot_img->DeviceHandle);
524 text = efi_devpath_name(dp->pd_devpath);
526 printf("Trying ESP: %S\n", text);
527 efi_free_devpath_name(text);
529 set_currdev_pdinfo(dp);
530 if (sanity_check_currdev())
532 if (dp->pd_parent != NULL) {
533 pdinfo_t *espdp = dp;
535 STAILQ_FOREACH(pp, &dp->pd_part, pd_link) {
536 /* Already tried the ESP */
540 * Roll up the ZFS special case
541 * for those partitions that have
544 text = efi_devpath_name(pp->pd_devpath);
546 printf("Trying: %S\n", text);
547 efi_free_devpath_name(text);
549 if (try_as_currdev(dp, pp))
556 * Try the device handle from our loaded image first. If that
557 * fails, use the device path from the loaded image and see if
558 * any of the nodes in that path match one of the enumerated
559 * handles. Currently, this handle list is only for netboot.
561 if (efi_handle_lookup(boot_img->DeviceHandle, &dev, &unit, &extra) == 0) {
562 set_currdev_devsw(dev, unit);
563 if (sanity_check_currdev())
568 devpath = efi_lookup_image_devpath(IH);
569 while (devpath != NULL) {
570 h = efi_devpath_handle(devpath);
577 if (efi_handle_lookup(h, &dev, &unit, &extra) == 0) {
578 set_currdev_devsw(dev, unit);
579 if (sanity_check_currdev())
583 devpath = efi_lookup_devpath(h);
584 if (devpath != NULL) {
585 copy = efi_devpath_trim(devpath);
595 interactive_interrupt(const char *msg)
597 time_t now, then, last;
600 now = then = getsecs();
602 if (fail_timeout == -2) /* Always break to OK */
604 if (fail_timeout == -1) /* Never break to OK */
608 printf("press any key to interrupt reboot in %d seconds\r",
609 fail_timeout - (int)(now - then));
613 /* XXX no pause or timeout wait for char */
617 } while (now - then < fail_timeout);
622 parse_args(int argc, CHAR16 *argv[])
629 * Parse the args to set the console settings, etc
630 * boot1.efi passes these in, if it can read /boot.config or /boot/config
631 * or iPXE may be setup to pass these in. Or the optional argument in the
632 * boot environment was used to pass these arguments in (in which case
633 * neither /boot.config nor /boot/config are consulted).
635 * Loop through the args, and for each one that contains an '=' that is
636 * not the first character, add it to the environment. This allows
637 * loader and kernel env vars to be passed on the command line. Convert
638 * args from UCS-2 to ASCII (16 to 8 bit) as they are copied (though this
639 * method is flawed for non-ASCII characters).
642 for (i = 1; i < argc; i++) {
643 cpy16to8(argv[i], var, sizeof(var));
644 howto |= boot_parse_arg(var);
651 setenv_int(const char *key, int val)
655 snprintf(buf, sizeof(buf), "%d", val);
660 * Parse ConOut (the list of consoles active) and see if we can find a
661 * serial port and/or a video port. It would be nice to also walk the
662 * ACPI name space to map the UID for the serial port to a port. The
663 * latter is especially hard.
666 parse_uefi_con_out(void)
669 int vid_seen = 0, com_seen = 0, seen = 0;
672 EFI_DEVICE_PATH *node;
673 ACPI_HID_DEVICE_PATH *acpi;
674 UART_DEVICE_PATH *uart;
679 rv = efi_global_getenv("ConOut", buf, &sz);
680 if (rv != EFI_SUCCESS)
683 node = (EFI_DEVICE_PATH *)buf;
684 while ((char *)node < ep) {
686 if (DevicePathType(node) == ACPI_DEVICE_PATH &&
687 DevicePathSubType(node) == ACPI_DP) {
688 /* Check for Serial node */
690 if (EISA_ID_TO_NUM(acpi->HID) == 0x501) {
691 setenv_int("efi_8250_uid", acpi->UID);
694 } else if (DevicePathType(node) == MESSAGING_DEVICE_PATH &&
695 DevicePathSubType(node) == MSG_UART_DP) {
698 setenv_int("efi_com_speed", uart->BaudRate);
699 } else if (DevicePathType(node) == ACPI_DEVICE_PATH &&
700 DevicePathSubType(node) == ACPI_ADR_DP) {
701 /* Check for AcpiAdr() Node for video */
703 } else if (DevicePathType(node) == HARDWARE_DEVICE_PATH &&
704 DevicePathSubType(node) == HW_PCI_DP) {
706 * Note, vmware fusion has a funky console device
707 * PciRoot(0x0)/Pci(0xf,0x0)
708 * which we can only detect at the end since we also
710 * PciRoot(0x0)/Pci(0x1f,0x0)/Serial(0x1)
711 * so only match it if it's last.
715 node = NextDevicePathNode(node); /* Skip the end node */
717 if (pci_pending && vid_seen == 0)
721 * Truth table for RB_MULTIPLE | RB_SERIAL
723 * 0 Use only video console
724 * RB_SERIAL Use only serial console
725 * RB_MULTIPLE Use both video and serial console
726 * (but video is primary so gets rc messages)
727 * both Use both video and serial console
728 * (but serial is primary so gets rc messages)
730 * Try to honor this as best we can. If only one of serial / video
731 * found, then use that. Otherwise, use the first one we found.
732 * This also implies if we found nothing, default to video.
735 if (vid_seen && com_seen) {
737 if (com_seen < vid_seen)
746 main(int argc, CHAR16 *argv[])
749 int howto, i, uhowto;
751 bool has_kbd, is_last;
753 EFI_DEVICE_PATH *imgpath;
756 size_t sz, bosz = 0, bisz = 0;
757 UINT16 boot_order[100];
758 char boot_info[4096];
762 archsw.arch_autoload = efi_autoload;
763 archsw.arch_getdev = efi_getdev;
764 archsw.arch_copyin = efi_copyin;
765 archsw.arch_copyout = efi_copyout;
766 archsw.arch_readin = efi_readin;
767 archsw.arch_zfs_probe = efi_zfs_probe;
769 /* Get our loaded image protocol interface structure. */
770 (void) OpenProtocolByHandle(IH, &imgid, (void **)&boot_img);
773 * Chicken-and-egg problem; we want to have console output early, but
774 * some console attributes may depend on reading from eg. the boot
775 * device, which we can't do yet. We can use printf() etc. once this is
776 * done. So, we set it to the efi console, then call console init. This
777 * gets us printf early, but also primes the pump for all future console
778 * changes to take effect, regardless of where they come from.
780 setenv("console", "efi", 1);
783 /* Init the time source */
786 has_kbd = has_keyboard();
789 * Initialise the block cache. Set the upper limit.
791 bcache_init(32768, 512);
793 howto = parse_args(argc, argv);
794 if (!has_kbd && (howto & RB_PROBE))
795 howto |= RB_SERIAL | RB_MULTIPLE;
797 uhowto = parse_uefi_con_out();
800 * We now have two notions of console. howto should be viewed as
801 * overrides. If console is already set, don't set it again.
804 #define SERIAL_ONLY RB_SERIAL
805 #define VID_SER_BOTH RB_MULTIPLE
806 #define SER_VID_BOTH (RB_SERIAL | RB_MULTIPLE)
807 #define CON_MASK (RB_SERIAL | RB_MULTIPLE)
808 if (strcmp(getenv("console"), "efi") == 0) {
809 if ((howto & CON_MASK) == 0) {
810 /* No override, uhowto is controlling and efi cons is perfect */
811 howto = howto | (uhowto & CON_MASK);
812 } else if ((howto & CON_MASK) == (uhowto & CON_MASK)) {
813 /* override matches what UEFI told us, efi console is perfect */
814 } else if ((uhowto & (CON_MASK)) != 0) {
816 * We detected a serial console on ConOut. All possible
817 * overrides include serial. We can't really override what efi
818 * gives us, so we use it knowing it's the best choice.
823 * We detected some kind of serial in the override, but ConOut
824 * has no serial, so we have to sort out which case it really is.
826 switch (howto & CON_MASK) {
828 setenv("console", "comconsole", 1);
831 setenv("console", "efi comconsole", 1);
834 setenv("console", "comconsole efi", 1);
836 /* case VIDEO_ONLY can't happen -- it's the first if above */
842 * howto is set now how we want to export the flags to the kernel, so
843 * set the env based on it.
845 boot_howto_to_env(howto);
847 if (efi_copy_init()) {
848 printf("failed to allocate staging area\n");
849 return (EFI_BUFFER_TOO_SMALL);
852 if ((s = getenv("fail_timeout")) != NULL)
853 fail_timeout = strtol(s, NULL, 10);
856 * Scan the BLOCK IO MEDIA handles then
857 * march through the device switch probing for things.
859 i = efipart_inithandles();
860 if (i != 0 && i != ENOENT) {
861 printf("efipart_inithandles failed with ERRNO %d, expect "
865 for (i = 0; devsw[i] != NULL; i++)
866 if (devsw[i]->dv_init != NULL)
867 (devsw[i]->dv_init)();
869 printf("%s\n", bootprog_info);
870 printf(" Command line arguments:");
871 for (i = 0; i < argc; i++)
872 printf(" %S", argv[i]);
875 printf(" EFI version: %d.%02d\n", ST->Hdr.Revision >> 16,
876 ST->Hdr.Revision & 0xffff);
877 printf(" EFI Firmware: %S (rev %d.%02d)\n", ST->FirmwareVendor,
878 ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff);
879 printf(" Console: %s (%#x)\n", getenv("console"), howto);
883 /* Determine the devpath of our image so we can prefer it. */
884 text = efi_devpath_name(boot_img->FilePath);
886 printf(" Load Path: %S\n", text);
887 efi_setenv_freebsd_wcs("LoaderPath", text);
888 efi_free_devpath_name(text);
891 rv = OpenProtocolByHandle(boot_img->DeviceHandle, &devid, (void **)&imgpath);
892 if (rv == EFI_SUCCESS) {
893 text = efi_devpath_name(imgpath);
895 printf(" Load Device: %S\n", text);
896 efi_setenv_freebsd_wcs("LoaderDev", text);
897 efi_free_devpath_name(text);
901 uefi_boot_mgr = true;
903 sz = sizeof(boot_current);
904 rv = efi_global_getenv("BootCurrent", &boot_current, &sz);
905 if (rv == EFI_SUCCESS)
906 printf(" BootCurrent: %04x\n", boot_current);
908 boot_current = 0xffff;
909 uefi_boot_mgr = false;
912 sz = sizeof(boot_order);
913 rv = efi_global_getenv("BootOrder", &boot_order, &sz);
914 if (rv == EFI_SUCCESS) {
915 printf(" BootOrder:");
916 for (i = 0; i < sz / sizeof(boot_order[0]); i++)
917 printf(" %04x%s", boot_order[i],
918 boot_order[i] == boot_current ? "[*]" : "");
920 is_last = boot_order[(sz / sizeof(boot_order[0])) - 1] == boot_current;
922 } else if (uefi_boot_mgr) {
924 * u-boot doesn't set BootOrder, but otherwise participates in the
925 * boot manager protocol. So we fake it here and don't consider it
928 bosz = sizeof(boot_order[0]);
929 boot_order[0] = boot_current;
934 * Next, find the boot info structure the UEFI boot manager is
935 * supposed to setup. We need this so we can walk through it to
936 * find where we are in the booting process and what to try to
940 snprintf(buf, sizeof(buf), "Boot%04X", boot_current);
941 sz = sizeof(boot_info);
942 rv = efi_global_getenv(buf, &boot_info, &sz);
943 if (rv == EFI_SUCCESS)
946 uefi_boot_mgr = false;
950 * Disable the watchdog timer. By default the boot manager sets
951 * the timer to 5 minutes before invoking a boot option. If we
952 * want to return to the boot manager, we have to disable the
953 * watchdog timer and since we're an interactive program, we don't
954 * want to wait until the user types "quit". The timer may have
955 * fired by then. We don't care if this fails. It does not prevent
956 * normal functioning in any way...
958 BS->SetWatchdogTimer(0, 0, 0, NULL);
961 * Initialize the trusted/forbidden certificates from UEFI.
962 * They will be later used to verify the manifest(s),
963 * which should contain hashes of verified files.
964 * This needs to be initialized before any configuration files
967 #ifdef EFI_SECUREBOOT
972 * Try and find a good currdev based on the image that was booted.
973 * It might be desirable here to have a short pause to allow falling
974 * through to the boot loader instead of returning instantly to follow
975 * the boot protocol and also allow an escape hatch for users wishing
976 * to try something different.
978 if (find_currdev(uefi_boot_mgr, is_last, boot_info, bisz) != 0)
979 if (!interactive_interrupt("Failed to find bootable partition"))
980 return (EFI_NOT_FOUND);
982 efi_init_environment();
984 #if !defined(__arm__)
985 for (k = 0; k < ST->NumberOfTableEntries; k++) {
986 guid = &ST->ConfigurationTable[k].VendorGuid;
987 if (!memcmp(guid, &smbios, sizeof(EFI_GUID))) {
990 snprintf(buf, sizeof(buf), "%p",
991 ST->ConfigurationTable[k].VendorTable);
992 setenv("hint.smbios.0.mem", buf, 1);
993 smbios_detect(ST->ConfigurationTable[k].VendorTable);
999 interact(); /* doesn't return */
1001 return (EFI_SUCCESS); /* keep compiler happy */
1004 COMMAND_SET(poweroff, "poweroff", "power off the system", command_poweroff);
1007 command_poweroff(int argc __unused, char *argv[] __unused)
1011 for (i = 0; devsw[i] != NULL; ++i)
1012 if (devsw[i]->dv_cleanup != NULL)
1013 (devsw[i]->dv_cleanup)();
1015 RS->ResetSystem(EfiResetShutdown, EFI_SUCCESS, 0, NULL);
1021 COMMAND_SET(reboot, "reboot", "reboot the system", command_reboot);
1024 command_reboot(int argc, char *argv[])
1028 for (i = 0; devsw[i] != NULL; ++i)
1029 if (devsw[i]->dv_cleanup != NULL)
1030 (devsw[i]->dv_cleanup)();
1032 RS->ResetSystem(EfiResetCold, EFI_SUCCESS, 0, NULL);
1038 COMMAND_SET(quit, "quit", "exit the loader", command_quit);
1041 command_quit(int argc, char *argv[])
1047 COMMAND_SET(memmap, "memmap", "print memory map", command_memmap);
1050 command_memmap(int argc __unused, char *argv[] __unused)
1053 EFI_MEMORY_DESCRIPTOR *map, *p;
1061 status = BS->GetMemoryMap(&sz, 0, &key, &dsz, &dver);
1062 if (status != EFI_BUFFER_TOO_SMALL) {
1063 printf("Can't determine memory map size\n");
1067 status = BS->GetMemoryMap(&sz, map, &key, &dsz, &dver);
1068 if (EFI_ERROR(status)) {
1069 printf("Can't read memory map\n");
1074 snprintf(line, sizeof(line), "%23s %12s %12s %8s %4s\n",
1075 "Type", "Physical", "Virtual", "#Pages", "Attr");
1077 if (pager_output(line)) {
1082 for (i = 0, p = map; i < ndesc;
1083 i++, p = NextMemoryDescriptor(p, dsz)) {
1084 snprintf(line, sizeof(line), "%23s %012jx %012jx %08jx ",
1085 efi_memory_type(p->Type), (uintmax_t)p->PhysicalStart,
1086 (uintmax_t)p->VirtualStart, (uintmax_t)p->NumberOfPages);
1087 if (pager_output(line))
1090 if (p->Attribute & EFI_MEMORY_UC)
1092 if (p->Attribute & EFI_MEMORY_WC)
1094 if (p->Attribute & EFI_MEMORY_WT)
1096 if (p->Attribute & EFI_MEMORY_WB)
1098 if (p->Attribute & EFI_MEMORY_UCE)
1100 if (p->Attribute & EFI_MEMORY_WP)
1102 if (p->Attribute & EFI_MEMORY_RP)
1104 if (p->Attribute & EFI_MEMORY_XP)
1106 if (p->Attribute & EFI_MEMORY_NV)
1108 if (p->Attribute & EFI_MEMORY_MORE_RELIABLE)
1110 if (p->Attribute & EFI_MEMORY_RO)
1112 if (pager_output("\n"))
1120 COMMAND_SET(configuration, "configuration", "print configuration tables",
1121 command_configuration);
1124 command_configuration(int argc, char *argv[])
1129 printf("NumberOfTableEntries=%lu\n",
1130 (unsigned long)ST->NumberOfTableEntries);
1132 for (i = 0; i < ST->NumberOfTableEntries; i++) {
1136 guid = &ST->ConfigurationTable[i].VendorGuid;
1138 if (efi_guid_to_name(guid, &name) == true) {
1142 printf("Error while translating UUID to name");
1144 printf(" at %p\n", ST->ConfigurationTable[i].VendorTable);
1151 COMMAND_SET(mode, "mode", "change or display EFI text modes", command_mode);
1154 command_mode(int argc, char *argv[])
1162 SIMPLE_TEXT_OUTPUT_INTERFACE *conout;
1163 extern void HO(void);
1165 conout = ST->ConOut;
1168 mode = strtol(argv[1], &cp, 0);
1169 if (cp[0] != '\0') {
1170 printf("Invalid mode\n");
1173 status = conout->QueryMode(conout, mode, &cols, &rows);
1174 if (EFI_ERROR(status)) {
1175 printf("invalid mode %d\n", mode);
1178 status = conout->SetMode(conout, mode);
1179 if (EFI_ERROR(status)) {
1180 printf("couldn't set mode %d\n", mode);
1183 sprintf(rowenv, "%u", (unsigned)rows);
1184 setenv("LINES", rowenv, 1);
1185 HO(); /* set cursor */
1189 printf("Current mode: %d\n", conout->Mode->Mode);
1190 for (i = 0; i <= conout->Mode->MaxMode; i++) {
1191 status = conout->QueryMode(conout, i, &cols, &rows);
1192 if (EFI_ERROR(status))
1194 printf("Mode %d: %u columns, %u rows\n", i, (unsigned)cols,
1199 printf("Select a mode with the command \"mode <number>\"\n");
1204 COMMAND_SET(lsefi, "lsefi", "list EFI handles", command_lsefi);
1207 command_lsefi(int argc __unused, char *argv[] __unused)
1210 EFI_HANDLE *buffer = NULL;
1212 UINTN bufsz = 0, i, j;
1216 status = BS->LocateHandle(AllHandles, NULL, NULL, &bufsz, buffer);
1217 if (status != EFI_BUFFER_TOO_SMALL) {
1218 snprintf(command_errbuf, sizeof (command_errbuf),
1219 "unexpected error: %lld", (long long)status);
1222 if ((buffer = malloc(bufsz)) == NULL) {
1223 sprintf(command_errbuf, "out of memory");
1227 status = BS->LocateHandle(AllHandles, NULL, NULL, &bufsz, buffer);
1228 if (EFI_ERROR(status)) {
1230 snprintf(command_errbuf, sizeof (command_errbuf),
1231 "LocateHandle() error: %lld", (long long)status);
1236 for (i = 0; i < (bufsz / sizeof (EFI_HANDLE)); i++) {
1238 EFI_GUID **protocols = NULL;
1241 printf("Handle %p", handle);
1242 if (pager_output("\n"))
1246 status = BS->ProtocolsPerHandle(handle, &protocols, &nproto);
1247 if (EFI_ERROR(status)) {
1248 snprintf(command_errbuf, sizeof (command_errbuf),
1249 "ProtocolsPerHandle() error: %lld",
1254 for (j = 0; j < nproto; j++) {
1255 if (efi_guid_to_name(protocols[j], &name) == true) {
1256 printf(" %s", name);
1259 printf("Error while translating UUID to name");
1261 if ((ret = pager_output("\n")) != 0)
1264 BS->FreePool(protocols);
1273 #ifdef LOADER_FDT_SUPPORT
1274 extern int command_fdt_internal(int argc, char *argv[]);
1277 * Since proper fdt command handling function is defined in fdt_loader_cmd.c,
1278 * and declaring it as extern is in contradiction with COMMAND_SET() macro
1279 * (which uses static pointer), we're defining wrapper function, which
1280 * calls the proper fdt handling routine.
1283 command_fdt(int argc, char *argv[])
1286 return (command_fdt_internal(argc, argv));
1289 COMMAND_SET(fdt, "fdt", "flattened device tree handling", command_fdt);
1293 * Chain load another efi loader.
1296 command_chain(int argc, char *argv[])
1298 EFI_GUID LoadedImageGUID = LOADED_IMAGE_PROTOCOL;
1299 EFI_HANDLE loaderhandle;
1300 EFI_LOADED_IMAGE *loaded_image;
1303 struct devdesc *dev;
1309 command_errmsg = "wrong number of arguments";
1315 if ((fd = open(name, O_RDONLY)) < 0) {
1316 command_errmsg = "no such file";
1320 if (fstat(fd, &st) < -1) {
1321 command_errmsg = "stat failed";
1326 status = BS->AllocatePool(EfiLoaderCode, (UINTN)st.st_size, &buf);
1327 if (status != EFI_SUCCESS) {
1328 command_errmsg = "failed to allocate buffer";
1332 if (read(fd, buf, st.st_size) != st.st_size) {
1333 command_errmsg = "error while reading the file";
1334 (void)BS->FreePool(buf);
1339 status = BS->LoadImage(FALSE, IH, NULL, buf, st.st_size, &loaderhandle);
1340 (void)BS->FreePool(buf);
1341 if (status != EFI_SUCCESS) {
1342 command_errmsg = "LoadImage failed";
1345 status = OpenProtocolByHandle(loaderhandle, &LoadedImageGUID,
1346 (void **)&loaded_image);
1352 for (i = 2; i < argc; i++)
1353 len += strlen(argv[i]) + 1;
1355 len *= sizeof (*argp);
1356 loaded_image->LoadOptions = argp = malloc (len);
1357 loaded_image->LoadOptionsSize = len;
1358 for (i = 2; i < argc; i++) {
1359 char *ptr = argv[i];
1361 *(argp++) = *(ptr++);
1367 if (efi_getdev((void **)&dev, name, (const char **)&path) == 0) {
1369 struct zfs_devdesc *z_dev;
1371 struct disk_devdesc *d_dev;
1374 switch (dev->d_dev->dv_type) {
1377 z_dev = (struct zfs_devdesc *)dev;
1378 loaded_image->DeviceHandle =
1379 efizfs_get_handle_by_guid(z_dev->pool_guid);
1383 loaded_image->DeviceHandle =
1384 efi_find_handle(dev->d_dev, dev->d_unit);
1387 hd = efiblk_get_pdinfo(dev);
1388 if (STAILQ_EMPTY(&hd->pd_part)) {
1389 loaded_image->DeviceHandle = hd->pd_handle;
1392 d_dev = (struct disk_devdesc *)dev;
1393 STAILQ_FOREACH(pd, &hd->pd_part, pd_link) {
1395 * d_partition should be 255
1397 if (pd->pd_unit == (uint32_t)d_dev->d_slice) {
1398 loaded_image->DeviceHandle =
1408 status = BS->StartImage(loaderhandle, NULL, NULL);
1409 if (status != EFI_SUCCESS) {
1410 command_errmsg = "StartImage failed";
1411 free(loaded_image->LoadOptions);
1412 loaded_image->LoadOptions = NULL;
1413 status = BS->UnloadImage(loaded_image);
1417 return (CMD_ERROR); /* not reached */
1420 COMMAND_SET(chain, "chain", "chain load file", command_chain);