2 * Copyright (c) 2008-2010 Rui Paulo
3 * Copyright (c) 2006 Marcel Moolenaar
6 * Copyright (c) 2016-2019 Netflix, Inc. written by M. Warner Losh
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>
39 #include <sys/zfs_bootenv.h>
52 #include <bootstrap.h>
57 #include "loader_efi.h"
59 struct arch_switch archsw; /* MI/MD interface boundary */
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;
80 * Number of seconds to wait for a keystroke before exiting with failure
81 * in the event no currdev is found. -2 means always break, -1 means
82 * never break, 0 means poll once and then reboot, > 0 means wait for
83 * that many seconds. "fail_timeout" can be set in the environment as
86 static int fail_timeout = 5;
89 * Current boot variable
94 * Image that we booted from.
96 EFI_LOADED_IMAGE *boot_img;
102 EFI_DEVICE_PATH *path;
103 EFI_HANDLE *hin, *hin_end, *walker;
108 * Find all the handles that support the SIMPLE_TEXT_INPUT_PROTOCOL and
109 * do the typical dance to get the right sized buffer.
113 status = BS->LocateHandle(ByProtocol, &inputid, 0, &sz, 0);
114 if (status == EFI_BUFFER_TOO_SMALL) {
115 hin = (EFI_HANDLE *)malloc(sz);
116 status = BS->LocateHandle(ByProtocol, &inputid, 0, &sz,
118 if (EFI_ERROR(status))
121 if (EFI_ERROR(status))
125 * Look at each of the handles. If it supports the device path protocol,
126 * use it to get the device path for this handle. Then see if that
127 * device path matches either the USB device path for keyboards or the
128 * legacy device path for keyboards.
130 hin_end = &hin[sz / sizeof(*hin)];
131 for (walker = hin; walker < hin_end; walker++) {
132 status = OpenProtocolByHandle(*walker, &devid, (void **)&path);
133 if (EFI_ERROR(status))
136 while (!IsDevicePathEnd(path)) {
138 * Check for the ACPI keyboard node. All PNP3xx nodes
139 * are keyboards of different flavors. Note: It is
140 * unclear of there's always a keyboard node when
141 * there's a keyboard controller, or if there's only one
142 * when a keyboard is detected at boot.
144 if (DevicePathType(path) == ACPI_DEVICE_PATH &&
145 (DevicePathSubType(path) == ACPI_DP ||
146 DevicePathSubType(path) == ACPI_EXTENDED_DP)) {
147 ACPI_HID_DEVICE_PATH *acpi;
149 acpi = (ACPI_HID_DEVICE_PATH *)(void *)path;
150 if ((EISA_ID_TO_NUM(acpi->HID) & 0xff00) == 0x300 &&
151 (acpi->HID & 0xffff) == PNP_EISA_ID_CONST) {
156 * Check for USB keyboard node, if present. Unlike a
157 * PS/2 keyboard, these definitely only appear when
158 * connected to the system.
160 } else if (DevicePathType(path) == MESSAGING_DEVICE_PATH &&
161 DevicePathSubType(path) == MSG_USB_CLASS_DP) {
162 USB_CLASS_DEVICE_PATH *usb;
164 usb = (USB_CLASS_DEVICE_PATH *)(void *)path;
165 if (usb->DeviceClass == 3 && /* HID */
166 usb->DeviceSubClass == 1 && /* Boot devices */
167 usb->DeviceProtocol == 1) { /* Boot keyboards */
172 path = NextDevicePathNode(path);
181 set_currdev(const char *devname)
185 * Don't execute hooks here; we may need to try setting these more than
186 * once here if we're probing for the ZFS pool we're supposed to boot.
187 * The currdev hook is intended to just validate user input anyways,
188 * while the loaddev hook makes it immutable once we've determined what
189 * the proper currdev is.
191 env_setenv("currdev", EV_VOLATILE | EV_NOHOOK, devname, efi_setcurrdev,
193 env_setenv("loaddev", EV_VOLATILE | EV_NOHOOK, devname, env_noset,
198 set_currdev_devdesc(struct devdesc *currdev)
202 devname = efi_fmtdev(currdev);
203 printf("Setting currdev to %s\n", devname);
204 set_currdev(devname);
208 set_currdev_devsw(struct devsw *dev, int unit)
210 struct devdesc currdev;
213 currdev.d_unit = unit;
215 set_currdev_devdesc(&currdev);
219 set_currdev_pdinfo(pdinfo_t *dp)
223 * Disks are special: they have partitions. if the parent
224 * pointer is non-null, we're a partition not a full disk
225 * and we need to adjust currdev appropriately.
227 if (dp->pd_devsw->dv_type == DEVT_DISK) {
228 struct disk_devdesc currdev;
230 currdev.dd.d_dev = dp->pd_devsw;
231 if (dp->pd_parent == NULL) {
232 currdev.dd.d_unit = dp->pd_unit;
233 currdev.d_slice = D_SLICENONE;
234 currdev.d_partition = D_PARTNONE;
236 currdev.dd.d_unit = dp->pd_parent->pd_unit;
237 currdev.d_slice = dp->pd_unit;
238 currdev.d_partition = D_PARTISGPT; /* XXX Assumes GPT */
240 set_currdev_devdesc((struct devdesc *)&currdev);
242 set_currdev_devsw(dp->pd_devsw, dp->pd_unit);
247 sanity_check_currdev(void)
251 return (stat(PATH_DEFAULTS_LOADER_CONF, &st) == 0 ||
252 #ifdef PATH_BOOTABLE_TOKEN
253 stat(PATH_BOOTABLE_TOKEN, &st) == 0 || /* non-standard layout */
255 stat(PATH_KERNEL, &st) == 0);
260 probe_zfs_currdev(uint64_t guid)
263 struct zfs_devdesc currdev;
267 currdev.dd.d_dev = &zfs_dev;
268 currdev.dd.d_unit = 0;
269 currdev.pool_guid = guid;
270 currdev.root_guid = 0;
271 set_currdev_devdesc((struct devdesc *)&currdev);
272 devname = efi_fmtdev(&currdev);
273 init_zfs_boot_options(devname);
275 rv = sanity_check_currdev();
277 buf = malloc(VDEV_PAD_SIZE);
279 if (zfs_get_bootonce(&currdev, OS_BOOTONCE, buf,
280 VDEV_PAD_SIZE) == 0) {
281 printf("zfs bootonce: %s\n", buf);
283 setenv("zfs-bootonce", buf, 1);
286 (void) zfs_attach_nvstore(&currdev);
294 try_as_currdev(pdinfo_t *hd, pdinfo_t *pp)
300 * If there's a zpool on this device, try it as a ZFS
301 * filesystem, which has somewhat different setup than all
302 * other types of fs due to imperfect loader integration.
303 * This all stems from ZFS being both a device (zpool) and
304 * a filesystem, plus the boot env feature.
306 if (efizfs_get_guid_by_handle(pp->pd_handle, &guid))
307 return (probe_zfs_currdev(guid));
310 * All other filesystems just need the pdinfo
311 * initialized in the standard way.
313 set_currdev_pdinfo(pp);
314 return (sanity_check_currdev());
318 * Sometimes we get filenames that are all upper case
319 * and/or have backslashes in them. Filter all this out
320 * if it looks like we need to do so.
334 #define SIZE(dp, edp) (size_t)((intptr_t)(void *)edp - (intptr_t)(void *)dp)
336 enum { BOOT_INFO_OK = 0, BAD_CHOICE = 1, NOT_SPECIFIC = 2 };
338 match_boot_info(char *boot_info, size_t bisz)
344 EFI_DEVICE_PATH *dp, *edp, *first_dp, *last_dp;
348 FILEPATH_DEVICE_PATH *fp;
353 * FreeBSD encodes it's boot loading path into the boot loader
354 * BootXXXX variable. We look for the last one in the path
355 * and use that to load the kernel. However, if we only fine
356 * one DEVICE_PATH, then there's nothing specific and we should
359 * In an ideal world, we'd look at the image handle we were
360 * passed, match up with the loader we are and then return the
361 * next one in the path. This would be most flexible and cover
362 * many chain booting scenarios where you need to use this
363 * boot loader to get to the next boot loader. However, that
364 * doesn't work. We rarely have the path to the image booted
365 * (just the device) so we can't count on that. So, we do the
366 * enxt best thing, we look through the device path(s) passed
367 * in the BootXXXX varaible. If there's only one, we return
368 * NOT_SPECIFIC. Otherwise, we look at the last one and try to
369 * load that. If we can, we return BOOT_INFO_OK. Otherwise we
370 * return BAD_CHOICE for the caller to sort out.
372 if (bisz < sizeof(attr) + sizeof(fplen) + sizeof(CHAR16))
376 memcpy(&attr, walker, sizeof(attr));
377 walker += sizeof(attr);
378 memcpy(&fplen, walker, sizeof(fplen));
379 walker += sizeof(fplen);
380 descr = (CHAR16 *)(intptr_t)walker;
381 len = ucs2len(descr);
382 walker += (len + 1) * sizeof(CHAR16);
383 last_dp = first_dp = dp = (EFI_DEVICE_PATH *)walker;
384 edp = (EFI_DEVICE_PATH *)(walker + fplen);
385 if ((char *)edp > ep)
387 while (dp < edp && SIZE(dp, edp) > sizeof(EFI_DEVICE_PATH)) {
388 text = efi_devpath_name(dp);
390 printf(" BootInfo Path: %S\n", text);
391 efi_free_devpath_name(text);
394 dp = (EFI_DEVICE_PATH *)((char *)dp + efi_devpath_length(dp));
398 * If there's only one item in the list, then nothing was
399 * specified. Or if the last path doesn't have a media
400 * path in it. Those show up as various VenHw() nodes
401 * which are basically opaque to us. Don't count those
402 * as something specifc.
404 if (last_dp == first_dp) {
405 printf("Ignoring Boot%04x: Only one DP found\n", boot_current);
408 if (efi_devpath_to_media_path(last_dp) == NULL) {
409 printf("Ignoring Boot%04x: No Media Path\n", boot_current);
414 * OK. At this point we either have a good path or a bad one.
417 pp = efiblk_get_pdinfo_by_device_path(last_dp);
419 printf("Ignoring Boot%04x: Device Path not found\n", boot_current);
422 set_currdev_pdinfo(pp);
423 if (!sanity_check_currdev()) {
424 printf("Ignoring Boot%04x: sanity check failed\n", boot_current);
429 * OK. We've found a device that matches, next we need to check the last
430 * component of the path. If it's a file, then we set the default kernel
431 * to that. Otherwise, just use this as the default root.
433 * Reminder: we're running very early, before we've parsed the defaults
434 * file, so we may need to have a hack override.
436 dp = efi_devpath_last_node(last_dp);
437 if (DevicePathType(dp) != MEDIA_DEVICE_PATH ||
438 DevicePathSubType(dp) != MEDIA_FILEPATH_DP) {
439 printf("Using Boot%04x for root partition\n", boot_current);
440 return (BOOT_INFO_OK); /* use currdir, default kernel */
442 fp = (FILEPATH_DEVICE_PATH *)dp;
443 ucs2_to_utf8(fp->PathName, &kernel);
444 if (kernel == NULL) {
445 printf("Not using Boot%04x: can't decode kernel\n", boot_current);
448 if (*kernel == '\\' || isupper(*kernel))
450 if (stat(kernel, &st) != 0) {
452 printf("Not using Boot%04x: can't find %s\n", boot_current,
456 setenv("kernel", kernel, 1);
458 text = efi_devpath_name(last_dp);
460 printf("Using Boot%04x %S + %s\n", boot_current, text,
462 efi_free_devpath_name(text);
465 return (BOOT_INFO_OK);
469 * Look at the passed-in boot_info, if any. If we find it then we need
470 * to see if we can find ourselves in the boot chain. If we can, and
471 * there's another specified thing to boot next, assume that the file
472 * is loaded from / and use that for the root filesystem. If can't
473 * find the specified thing, we must fail the boot. If we're last on
474 * the list, then we fallback to looking for the first available /
475 * candidate (ZFS, if there's a bootable zpool, otherwise a UFS
476 * partition that has either /boot/defaults/loader.conf on it or
477 * /boot/kernel/kernel (the default kernel) that we can use.
479 * We always fail if we can't find the right thing. However, as
480 * a concession to buggy UEFI implementations, like u-boot, if
481 * we have determined that the host is violating the UEFI boot
482 * manager protocol, we'll signal the rest of the program that
483 * a drop to the OK boot loader prompt is possible.
486 find_currdev(bool do_bootmgr, bool is_last,
487 char *boot_info, size_t boot_info_sz)
490 EFI_DEVICE_PATH *devpath, *copy;
500 * First choice: if rootdev is already set, use that, even if
503 rootdev = getenv("rootdev");
504 if (rootdev != NULL) {
505 printf(" Setting currdev to configured rootdev %s\n",
507 set_currdev(rootdev);
512 * Second choice: If uefi_rootdev is set, translate that UEFI device
513 * path to the loader's internal name and use that.
516 rootdev = getenv("uefi_rootdev");
519 devpath = efi_name_to_devpath(rootdev);
522 dp = efiblk_get_pdinfo_by_device_path(devpath);
523 efi_devpath_free(devpath);
526 printf(" Setting currdev to UEFI path %s\n",
528 set_currdev_pdinfo(dp);
533 * Third choice: If we can find out image boot_info, and there's
534 * a follow-on boot image in that boot_info, use that. In this
535 * case root will be the partition specified in that image and
536 * we'll load the kernel specified by the file path. Should there
537 * not be a filepath, we use the default. This filepath overrides
541 rv = match_boot_info(boot_info, boot_info_sz);
543 case BOOT_INFO_OK: /* We found it */
545 case BAD_CHOICE: /* specified file not found -> error */
546 /* XXX do we want to have an escape hatch for last in boot order? */
548 } /* Nothing specified, try normal match */
553 * Did efi_zfs_probe() detect the boot pool? If so, use the zpool
554 * it found, if it's sane. ZFS is the only thing that looks for
555 * disks and pools to boot. This may change in the future, however,
556 * if we allow specifying which pool to boot from via UEFI variables
557 * rather than the bootenv stuff that FreeBSD uses today.
559 if (pool_guid != 0) {
560 printf("Trying ZFS pool\n");
561 if (probe_zfs_currdev(pool_guid))
564 #endif /* EFI_ZFS_BOOT */
567 * Try to find the block device by its handle based on the
568 * image we're booting. If we can't find a sane partition,
569 * search all the other partitions of the disk. We do not
570 * search other disks because it's a violation of the UEFI
571 * boot protocol to do so. We fail and let UEFI go on to
572 * the next candidate.
574 dp = efiblk_get_pdinfo_by_handle(boot_img->DeviceHandle);
576 text = efi_devpath_name(dp->pd_devpath);
578 printf("Trying ESP: %S\n", text);
579 efi_free_devpath_name(text);
581 set_currdev_pdinfo(dp);
582 if (sanity_check_currdev())
584 if (dp->pd_parent != NULL) {
585 pdinfo_t *espdp = dp;
587 STAILQ_FOREACH(pp, &dp->pd_part, pd_link) {
588 /* Already tried the ESP */
592 * Roll up the ZFS special case
593 * for those partitions that have
596 text = efi_devpath_name(pp->pd_devpath);
598 printf("Trying: %S\n", text);
599 efi_free_devpath_name(text);
601 if (try_as_currdev(dp, pp))
608 * Try the device handle from our loaded image first. If that
609 * fails, use the device path from the loaded image and see if
610 * any of the nodes in that path match one of the enumerated
611 * handles. Currently, this handle list is only for netboot.
613 if (efi_handle_lookup(boot_img->DeviceHandle, &dev, &unit, &extra) == 0) {
614 set_currdev_devsw(dev, unit);
615 if (sanity_check_currdev())
620 devpath = efi_lookup_image_devpath(IH);
621 while (devpath != NULL) {
622 h = efi_devpath_handle(devpath);
629 if (efi_handle_lookup(h, &dev, &unit, &extra) == 0) {
630 set_currdev_devsw(dev, unit);
631 if (sanity_check_currdev())
635 devpath = efi_lookup_devpath(h);
636 if (devpath != NULL) {
637 copy = efi_devpath_trim(devpath);
647 interactive_interrupt(const char *msg)
649 time_t now, then, last;
652 now = then = getsecs();
654 if (fail_timeout == -2) /* Always break to OK */
656 if (fail_timeout == -1) /* Never break to OK */
660 printf("press any key to interrupt reboot in %d seconds\r",
661 fail_timeout - (int)(now - then));
665 /* XXX no pause or timeout wait for char */
669 } while (now - then < fail_timeout);
674 parse_args(int argc, CHAR16 *argv[])
681 * Parse the args to set the console settings, etc
682 * boot1.efi passes these in, if it can read /boot.config or /boot/config
683 * or iPXE may be setup to pass these in. Or the optional argument in the
684 * boot environment was used to pass these arguments in (in which case
685 * neither /boot.config nor /boot/config are consulted).
687 * Loop through the args, and for each one that contains an '=' that is
688 * not the first character, add it to the environment. This allows
689 * loader and kernel env vars to be passed on the command line. Convert
690 * args from UCS-2 to ASCII (16 to 8 bit) as they are copied (though this
691 * method is flawed for non-ASCII characters).
694 for (i = 1; i < argc; i++) {
695 cpy16to8(argv[i], var, sizeof(var));
696 howto |= boot_parse_arg(var);
703 setenv_int(const char *key, int val)
707 snprintf(buf, sizeof(buf), "%d", val);
712 * Parse ConOut (the list of consoles active) and see if we can find a
713 * serial port and/or a video port. It would be nice to also walk the
714 * ACPI name space to map the UID for the serial port to a port. The
715 * latter is especially hard.
718 parse_uefi_con_out(void)
721 int vid_seen = 0, com_seen = 0, seen = 0;
724 EFI_DEVICE_PATH *node;
725 ACPI_HID_DEVICE_PATH *acpi;
726 UART_DEVICE_PATH *uart;
731 rv = efi_global_getenv("ConOut", buf, &sz);
732 if (rv != EFI_SUCCESS) {
733 /* If we don't have any ConOut default to serial */
738 node = (EFI_DEVICE_PATH *)buf;
739 while ((char *)node < ep) {
741 if (DevicePathType(node) == ACPI_DEVICE_PATH &&
742 (DevicePathSubType(node) == ACPI_DP ||
743 DevicePathSubType(node) == ACPI_EXTENDED_DP)) {
744 /* Check for Serial node */
746 if (EISA_ID_TO_NUM(acpi->HID) == 0x501) {
747 setenv_int("efi_8250_uid", acpi->UID);
750 } else if (DevicePathType(node) == MESSAGING_DEVICE_PATH &&
751 DevicePathSubType(node) == MSG_UART_DP) {
754 setenv_int("efi_com_speed", uart->BaudRate);
755 } else if (DevicePathType(node) == ACPI_DEVICE_PATH &&
756 DevicePathSubType(node) == ACPI_ADR_DP) {
757 /* Check for AcpiAdr() Node for video */
759 } else if (DevicePathType(node) == HARDWARE_DEVICE_PATH &&
760 DevicePathSubType(node) == HW_PCI_DP) {
762 * Note, vmware fusion has a funky console device
763 * PciRoot(0x0)/Pci(0xf,0x0)
764 * which we can only detect at the end since we also
766 * PciRoot(0x0)/Pci(0x1f,0x0)/Serial(0x1)
767 * so only match it if it's last.
771 node = NextDevicePathNode(node);
773 if (pci_pending && vid_seen == 0)
777 * Truth table for RB_MULTIPLE | RB_SERIAL
779 * 0 Use only video console
780 * RB_SERIAL Use only serial console
781 * RB_MULTIPLE Use both video and serial console
782 * (but video is primary so gets rc messages)
783 * both Use both video and serial console
784 * (but serial is primary so gets rc messages)
786 * Try to honor this as best we can. If only one of serial / video
787 * found, then use that. Otherwise, use the first one we found.
788 * This also implies if we found nothing, default to video.
791 if (vid_seen && com_seen) {
793 if (com_seen < vid_seen)
802 parse_loader_efi_config(EFI_HANDLE h, const char *env_fn)
809 dp = efiblk_get_pdinfo_by_handle(h);
812 set_currdev_pdinfo(dp);
813 if (stat(env_fn, &st) != 0)
815 fd = open(env_fn, O_RDONLY);
818 env = malloc(st.st_size + 1);
821 if (read(fd, env, st.st_size) != st.st_size)
823 env[st.st_size] = '\0';
824 boot_parse_cmdline(env);
831 read_loader_env(const char *name, char *def_fn, bool once)
834 char *fn, *freeme = NULL;
838 if (efi_freebsd_getenv(name, NULL, &len) == EFI_BUFFER_TOO_SMALL) {
839 freeme = fn = malloc(len + 1);
841 if (efi_freebsd_getenv(name, fn, &len) != EFI_SUCCESS) {
845 "Can't fetch FreeBSD::%s we know is there\n", name);
848 * if tagged as 'once' delete the env variable so we
852 efi_freebsd_delenv(name);
854 * We malloced 1 more than len above, then redid the call.
855 * so now we have room at the end of the string to NUL terminate
856 * it here, even if the typical idium would have '- 1' here to
857 * not overflow. len should be the same on return both times.
863 "Can't allocate %d bytes to fetch FreeBSD::%s env var\n",
868 printf(" Reading loader env vars from %s\n", fn);
869 parse_loader_efi_config(boot_img->DeviceHandle, fn);
880 main(int argc, CHAR16 *argv[])
883 int howto, i, uhowto;
885 bool has_kbd, is_last;
887 EFI_DEVICE_PATH *imgpath;
890 size_t sz, bosz = 0, bisz = 0;
891 UINT16 boot_order[100];
892 char boot_info[4096];
896 archsw.arch_autoload = efi_autoload;
897 archsw.arch_getdev = efi_getdev;
898 archsw.arch_copyin = efi_copyin;
899 archsw.arch_copyout = efi_copyout;
901 archsw.arch_hypervisor = x86_hypervisor;
903 archsw.arch_readin = efi_readin;
904 archsw.arch_zfs_probe = efi_zfs_probe;
906 /* Get our loaded image protocol interface structure. */
907 (void) OpenProtocolByHandle(IH, &imgid, (void **)&boot_img);
910 * Chicken-and-egg problem; we want to have console output early, but
911 * some console attributes may depend on reading from eg. the boot
912 * device, which we can't do yet. We can use printf() etc. once this is
913 * done. So, we set it to the efi console, then call console init. This
914 * gets us printf early, but also primes the pump for all future console
915 * changes to take effect, regardless of where they come from.
917 setenv("console", "efi", 1);
918 uhowto = parse_uefi_con_out();
919 #if defined(__aarch64__) || defined(__arm__) || defined(__riscv)
920 if ((uhowto & RB_SERIAL) != 0)
921 setenv("console", "comconsole", 1);
925 /* Init the time source */
929 * Initialise the block cache. Set the upper limit.
931 bcache_init(32768, 512);
934 * Scan the BLOCK IO MEDIA handles then
935 * march through the device switch probing for things.
937 i = efipart_inithandles();
938 if (i != 0 && i != ENOENT) {
939 printf("efipart_inithandles failed with ERRNO %d, expect "
943 for (i = 0; devsw[i] != NULL; i++)
944 if (devsw[i]->dv_init != NULL)
945 (devsw[i]->dv_init)();
948 * Detect console settings two different ways: one via the command
949 * args (eg -h) or via the UEFI ConOut variable.
951 has_kbd = has_keyboard();
952 howto = parse_args(argc, argv);
953 if (!has_kbd && (howto & RB_PROBE))
954 howto |= RB_SERIAL | RB_MULTIPLE;
958 * Read additional environment variables from the boot device's
959 * "LoaderEnv" file. Any boot loader environment variable may be set
960 * there, which are subtly different than loader.conf variables. Only
961 * the 'simple' ones may be set so things like foo_load="YES" won't work
962 * for two reasons. First, the parser is simplistic and doesn't grok
963 * quotes. Second, because the variables that cause an action to happen
964 * are parsed by the lua, 4th or whatever code that's not yet
965 * loaded. This is relative to the root directory when loader.efi is
966 * loaded off the UFS root drive (when chain booted), or from the ESP
967 * when directly loaded by the BIOS.
969 * We also read in NextLoaderEnv if it was specified. This allows next boot
970 * functionality to be implemented and to override anything in LoaderEnv.
972 read_loader_env("LoaderEnv", "/efi/freebsd/loader.env", false);
973 read_loader_env("NextLoaderEnv", NULL, true);
976 * We now have two notions of console. howto should be viewed as
977 * overrides. If console is already set, don't set it again.
980 #define SERIAL_ONLY RB_SERIAL
981 #define VID_SER_BOTH RB_MULTIPLE
982 #define SER_VID_BOTH (RB_SERIAL | RB_MULTIPLE)
983 #define CON_MASK (RB_SERIAL | RB_MULTIPLE)
984 if (strcmp(getenv("console"), "efi") == 0) {
985 if ((howto & CON_MASK) == 0) {
986 /* No override, uhowto is controlling and efi cons is perfect */
987 howto = howto | (uhowto & CON_MASK);
988 } else if ((howto & CON_MASK) == (uhowto & CON_MASK)) {
989 /* override matches what UEFI told us, efi console is perfect */
990 } else if ((uhowto & (CON_MASK)) != 0) {
992 * We detected a serial console on ConOut. All possible
993 * overrides include serial. We can't really override what efi
994 * gives us, so we use it knowing it's the best choice.
999 * We detected some kind of serial in the override, but ConOut
1000 * has no serial, so we have to sort out which case it really is.
1002 switch (howto & CON_MASK) {
1004 setenv("console", "comconsole", 1);
1007 setenv("console", "efi comconsole", 1);
1010 setenv("console", "comconsole efi", 1);
1012 /* case VIDEO_ONLY can't happen -- it's the first if above */
1018 * howto is set now how we want to export the flags to the kernel, so
1019 * set the env based on it.
1021 boot_howto_to_env(howto);
1023 if (efi_copy_init()) {
1024 printf("failed to allocate staging area\n");
1025 return (EFI_BUFFER_TOO_SMALL);
1028 if ((s = getenv("fail_timeout")) != NULL)
1029 fail_timeout = strtol(s, NULL, 10);
1031 printf("%s\n", bootprog_info);
1032 printf(" Command line arguments:");
1033 for (i = 0; i < argc; i++)
1034 printf(" %S", argv[i]);
1037 printf(" Image base: 0x%lx\n", (unsigned long)boot_img->ImageBase);
1038 printf(" EFI version: %d.%02d\n", ST->Hdr.Revision >> 16,
1039 ST->Hdr.Revision & 0xffff);
1040 printf(" EFI Firmware: %S (rev %d.%02d)\n", ST->FirmwareVendor,
1041 ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff);
1042 printf(" Console: %s (%#x)\n", getenv("console"), howto);
1044 /* Determine the devpath of our image so we can prefer it. */
1045 text = efi_devpath_name(boot_img->FilePath);
1047 printf(" Load Path: %S\n", text);
1048 efi_setenv_freebsd_wcs("LoaderPath", text);
1049 efi_free_devpath_name(text);
1052 rv = OpenProtocolByHandle(boot_img->DeviceHandle, &devid,
1054 if (rv == EFI_SUCCESS) {
1055 text = efi_devpath_name(imgpath);
1057 printf(" Load Device: %S\n", text);
1058 efi_setenv_freebsd_wcs("LoaderDev", text);
1059 efi_free_devpath_name(text);
1063 if (getenv("uefi_ignore_boot_mgr") != NULL) {
1064 printf(" Ignoring UEFI boot manager\n");
1065 uefi_boot_mgr = false;
1067 uefi_boot_mgr = true;
1069 sz = sizeof(boot_current);
1070 rv = efi_global_getenv("BootCurrent", &boot_current, &sz);
1071 if (rv == EFI_SUCCESS)
1072 printf(" BootCurrent: %04x\n", boot_current);
1074 boot_current = 0xffff;
1075 uefi_boot_mgr = false;
1078 sz = sizeof(boot_order);
1079 rv = efi_global_getenv("BootOrder", &boot_order, &sz);
1080 if (rv == EFI_SUCCESS) {
1081 printf(" BootOrder:");
1082 for (i = 0; i < sz / sizeof(boot_order[0]); i++)
1083 printf(" %04x%s", boot_order[i],
1084 boot_order[i] == boot_current ? "[*]" : "");
1086 is_last = boot_order[(sz / sizeof(boot_order[0])) - 1] == boot_current;
1088 } else if (uefi_boot_mgr) {
1090 * u-boot doesn't set BootOrder, but otherwise participates in the
1091 * boot manager protocol. So we fake it here and don't consider it
1094 bosz = sizeof(boot_order[0]);
1095 boot_order[0] = boot_current;
1101 * Next, find the boot info structure the UEFI boot manager is
1102 * supposed to setup. We need this so we can walk through it to
1103 * find where we are in the booting process and what to try to
1106 if (uefi_boot_mgr) {
1107 snprintf(buf, sizeof(buf), "Boot%04X", boot_current);
1108 sz = sizeof(boot_info);
1109 rv = efi_global_getenv(buf, &boot_info, &sz);
1110 if (rv == EFI_SUCCESS)
1113 uefi_boot_mgr = false;
1117 * Disable the watchdog timer. By default the boot manager sets
1118 * the timer to 5 minutes before invoking a boot option. If we
1119 * want to return to the boot manager, we have to disable the
1120 * watchdog timer and since we're an interactive program, we don't
1121 * want to wait until the user types "quit". The timer may have
1122 * fired by then. We don't care if this fails. It does not prevent
1123 * normal functioning in any way...
1125 BS->SetWatchdogTimer(0, 0, 0, NULL);
1128 * Initialize the trusted/forbidden certificates from UEFI.
1129 * They will be later used to verify the manifest(s),
1130 * which should contain hashes of verified files.
1131 * This needs to be initialized before any configuration files
1134 #ifdef EFI_SECUREBOOT
1139 * Try and find a good currdev based on the image that was booted.
1140 * It might be desirable here to have a short pause to allow falling
1141 * through to the boot loader instead of returning instantly to follow
1142 * the boot protocol and also allow an escape hatch for users wishing
1143 * to try something different.
1145 if (find_currdev(uefi_boot_mgr, is_last, boot_info, bisz) != 0)
1146 if (uefi_boot_mgr &&
1147 !interactive_interrupt("Failed to find bootable partition"))
1148 return (EFI_NOT_FOUND);
1150 efi_init_environment();
1152 #if !defined(__arm__)
1153 for (k = 0; k < ST->NumberOfTableEntries; k++) {
1154 guid = &ST->ConfigurationTable[k].VendorGuid;
1155 if (!memcmp(guid, &smbios, sizeof(EFI_GUID))) {
1158 snprintf(buf, sizeof(buf), "%p",
1159 ST->ConfigurationTable[k].VendorTable);
1160 setenv("hint.smbios.0.mem", buf, 1);
1161 smbios_detect(ST->ConfigurationTable[k].VendorTable);
1167 interact(); /* doesn't return */
1169 return (EFI_SUCCESS); /* keep compiler happy */
1172 COMMAND_SET(poweroff, "poweroff", "power off the system", command_poweroff);
1175 command_poweroff(int argc __unused, char *argv[] __unused)
1179 for (i = 0; devsw[i] != NULL; ++i)
1180 if (devsw[i]->dv_cleanup != NULL)
1181 (devsw[i]->dv_cleanup)();
1183 RS->ResetSystem(EfiResetShutdown, EFI_SUCCESS, 0, NULL);
1189 COMMAND_SET(reboot, "reboot", "reboot the system", command_reboot);
1192 command_reboot(int argc, char *argv[])
1196 for (i = 0; devsw[i] != NULL; ++i)
1197 if (devsw[i]->dv_cleanup != NULL)
1198 (devsw[i]->dv_cleanup)();
1200 RS->ResetSystem(EfiResetCold, EFI_SUCCESS, 0, NULL);
1206 COMMAND_SET(quit, "quit", "exit the loader", command_quit);
1209 command_quit(int argc, char *argv[])
1215 COMMAND_SET(memmap, "memmap", "print memory map", command_memmap);
1218 command_memmap(int argc __unused, char *argv[] __unused)
1221 EFI_MEMORY_DESCRIPTOR *map, *p;
1229 status = BS->GetMemoryMap(&sz, 0, &key, &dsz, &dver);
1230 if (status != EFI_BUFFER_TOO_SMALL) {
1231 printf("Can't determine memory map size\n");
1235 status = BS->GetMemoryMap(&sz, map, &key, &dsz, &dver);
1236 if (EFI_ERROR(status)) {
1237 printf("Can't read memory map\n");
1242 snprintf(line, sizeof(line), "%23s %12s %12s %8s %4s\n",
1243 "Type", "Physical", "Virtual", "#Pages", "Attr");
1245 if (pager_output(line)) {
1250 for (i = 0, p = map; i < ndesc;
1251 i++, p = NextMemoryDescriptor(p, dsz)) {
1252 snprintf(line, sizeof(line), "%23s %012jx %012jx %08jx ",
1253 efi_memory_type(p->Type), (uintmax_t)p->PhysicalStart,
1254 (uintmax_t)p->VirtualStart, (uintmax_t)p->NumberOfPages);
1255 if (pager_output(line))
1258 if (p->Attribute & EFI_MEMORY_UC)
1260 if (p->Attribute & EFI_MEMORY_WC)
1262 if (p->Attribute & EFI_MEMORY_WT)
1264 if (p->Attribute & EFI_MEMORY_WB)
1266 if (p->Attribute & EFI_MEMORY_UCE)
1268 if (p->Attribute & EFI_MEMORY_WP)
1270 if (p->Attribute & EFI_MEMORY_RP)
1272 if (p->Attribute & EFI_MEMORY_XP)
1274 if (p->Attribute & EFI_MEMORY_NV)
1276 if (p->Attribute & EFI_MEMORY_MORE_RELIABLE)
1278 if (p->Attribute & EFI_MEMORY_RO)
1280 if (pager_output("\n"))
1288 COMMAND_SET(configuration, "configuration", "print configuration tables",
1289 command_configuration);
1292 command_configuration(int argc, char *argv[])
1297 printf("NumberOfTableEntries=%lu\n",
1298 (unsigned long)ST->NumberOfTableEntries);
1300 for (i = 0; i < ST->NumberOfTableEntries; i++) {
1304 guid = &ST->ConfigurationTable[i].VendorGuid;
1306 if (efi_guid_to_name(guid, &name) == true) {
1310 printf("Error while translating UUID to name");
1312 printf(" at %p\n", ST->ConfigurationTable[i].VendorTable);
1319 COMMAND_SET(mode, "mode", "change or display EFI text modes", command_mode);
1322 command_mode(int argc, char *argv[])
1329 SIMPLE_TEXT_OUTPUT_INTERFACE *conout;
1331 conout = ST->ConOut;
1334 mode = strtol(argv[1], &cp, 0);
1335 if (cp[0] != '\0') {
1336 printf("Invalid mode\n");
1339 status = conout->QueryMode(conout, mode, &cols, &rows);
1340 if (EFI_ERROR(status)) {
1341 printf("invalid mode %d\n", mode);
1344 status = conout->SetMode(conout, mode);
1345 if (EFI_ERROR(status)) {
1346 printf("couldn't set mode %d\n", mode);
1349 (void) efi_cons_update_mode();
1353 printf("Current mode: %d\n", conout->Mode->Mode);
1354 for (i = 0; i <= conout->Mode->MaxMode; i++) {
1355 status = conout->QueryMode(conout, i, &cols, &rows);
1356 if (EFI_ERROR(status))
1358 printf("Mode %d: %u columns, %u rows\n", i, (unsigned)cols,
1363 printf("Select a mode with the command \"mode <number>\"\n");
1368 COMMAND_SET(lsefi, "lsefi", "list EFI handles", command_lsefi);
1371 command_lsefi(int argc __unused, char *argv[] __unused)
1374 EFI_HANDLE *buffer = NULL;
1376 UINTN bufsz = 0, i, j;
1380 status = BS->LocateHandle(AllHandles, NULL, NULL, &bufsz, buffer);
1381 if (status != EFI_BUFFER_TOO_SMALL) {
1382 snprintf(command_errbuf, sizeof (command_errbuf),
1383 "unexpected error: %lld", (long long)status);
1386 if ((buffer = malloc(bufsz)) == NULL) {
1387 sprintf(command_errbuf, "out of memory");
1391 status = BS->LocateHandle(AllHandles, NULL, NULL, &bufsz, buffer);
1392 if (EFI_ERROR(status)) {
1394 snprintf(command_errbuf, sizeof (command_errbuf),
1395 "LocateHandle() error: %lld", (long long)status);
1400 for (i = 0; i < (bufsz / sizeof (EFI_HANDLE)); i++) {
1402 EFI_GUID **protocols = NULL;
1405 printf("Handle %p", handle);
1406 if (pager_output("\n"))
1410 status = BS->ProtocolsPerHandle(handle, &protocols, &nproto);
1411 if (EFI_ERROR(status)) {
1412 snprintf(command_errbuf, sizeof (command_errbuf),
1413 "ProtocolsPerHandle() error: %lld",
1418 for (j = 0; j < nproto; j++) {
1419 if (efi_guid_to_name(protocols[j], &name) == true) {
1420 printf(" %s", name);
1423 printf("Error while translating UUID to name");
1425 if ((ret = pager_output("\n")) != 0)
1428 BS->FreePool(protocols);
1437 #ifdef LOADER_FDT_SUPPORT
1438 extern int command_fdt_internal(int argc, char *argv[]);
1441 * Since proper fdt command handling function is defined in fdt_loader_cmd.c,
1442 * and declaring it as extern is in contradiction with COMMAND_SET() macro
1443 * (which uses static pointer), we're defining wrapper function, which
1444 * calls the proper fdt handling routine.
1447 command_fdt(int argc, char *argv[])
1450 return (command_fdt_internal(argc, argv));
1453 COMMAND_SET(fdt, "fdt", "flattened device tree handling", command_fdt);
1457 * Chain load another efi loader.
1460 command_chain(int argc, char *argv[])
1462 EFI_GUID LoadedImageGUID = LOADED_IMAGE_PROTOCOL;
1463 EFI_HANDLE loaderhandle;
1464 EFI_LOADED_IMAGE *loaded_image;
1467 struct devdesc *dev;
1473 command_errmsg = "wrong number of arguments";
1479 if ((fd = open(name, O_RDONLY)) < 0) {
1480 command_errmsg = "no such file";
1484 #ifdef LOADER_VERIEXEC
1485 if (verify_file(fd, name, 0, VE_MUST, __func__) < 0) {
1486 sprintf(command_errbuf, "can't verify: %s", name);
1492 if (fstat(fd, &st) < -1) {
1493 command_errmsg = "stat failed";
1498 status = BS->AllocatePool(EfiLoaderCode, (UINTN)st.st_size, &buf);
1499 if (status != EFI_SUCCESS) {
1500 command_errmsg = "failed to allocate buffer";
1504 if (read(fd, buf, st.st_size) != st.st_size) {
1505 command_errmsg = "error while reading the file";
1506 (void)BS->FreePool(buf);
1511 status = BS->LoadImage(FALSE, IH, NULL, buf, st.st_size, &loaderhandle);
1512 (void)BS->FreePool(buf);
1513 if (status != EFI_SUCCESS) {
1514 command_errmsg = "LoadImage failed";
1517 status = OpenProtocolByHandle(loaderhandle, &LoadedImageGUID,
1518 (void **)&loaded_image);
1524 for (i = 2; i < argc; i++)
1525 len += strlen(argv[i]) + 1;
1527 len *= sizeof (*argp);
1528 loaded_image->LoadOptions = argp = malloc (len);
1529 loaded_image->LoadOptionsSize = len;
1530 for (i = 2; i < argc; i++) {
1531 char *ptr = argv[i];
1533 *(argp++) = *(ptr++);
1539 if (efi_getdev((void **)&dev, name, (const char **)&path) == 0) {
1541 struct zfs_devdesc *z_dev;
1543 struct disk_devdesc *d_dev;
1546 switch (dev->d_dev->dv_type) {
1549 z_dev = (struct zfs_devdesc *)dev;
1550 loaded_image->DeviceHandle =
1551 efizfs_get_handle_by_guid(z_dev->pool_guid);
1555 loaded_image->DeviceHandle =
1556 efi_find_handle(dev->d_dev, dev->d_unit);
1559 hd = efiblk_get_pdinfo(dev);
1560 if (STAILQ_EMPTY(&hd->pd_part)) {
1561 loaded_image->DeviceHandle = hd->pd_handle;
1564 d_dev = (struct disk_devdesc *)dev;
1565 STAILQ_FOREACH(pd, &hd->pd_part, pd_link) {
1567 * d_partition should be 255
1569 if (pd->pd_unit == (uint32_t)d_dev->d_slice) {
1570 loaded_image->DeviceHandle =
1580 status = BS->StartImage(loaderhandle, NULL, NULL);
1581 if (status != EFI_SUCCESS) {
1582 command_errmsg = "StartImage failed";
1583 free(loaded_image->LoadOptions);
1584 loaded_image->LoadOptions = NULL;
1585 status = BS->UnloadImage(loaded_image);
1589 return (CMD_ERROR); /* not reached */
1592 COMMAND_SET(chain, "chain", "chain load file", command_chain);