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>
51 #include <bootstrap.h>
56 #include "loader_efi.h"
58 struct arch_switch archsw; /* MI/MD interface boundary */
60 EFI_GUID acpi = ACPI_TABLE_GUID;
61 EFI_GUID acpi20 = ACPI_20_TABLE_GUID;
62 EFI_GUID devid = DEVICE_PATH_PROTOCOL;
63 EFI_GUID imgid = LOADED_IMAGE_PROTOCOL;
64 EFI_GUID mps = MPS_TABLE_GUID;
65 EFI_GUID netid = EFI_SIMPLE_NETWORK_PROTOCOL;
66 EFI_GUID smbios = SMBIOS_TABLE_GUID;
67 EFI_GUID smbios3 = SMBIOS3_TABLE_GUID;
68 EFI_GUID dxe = DXE_SERVICES_TABLE_GUID;
69 EFI_GUID hoblist = HOB_LIST_TABLE_GUID;
70 EFI_GUID lzmadecomp = LZMA_DECOMPRESSION_GUID;
71 EFI_GUID mpcore = ARM_MP_CORE_INFO_TABLE_GUID;
72 EFI_GUID esrt = ESRT_TABLE_GUID;
73 EFI_GUID memtype = MEMORY_TYPE_INFORMATION_TABLE_GUID;
74 EFI_GUID debugimg = DEBUG_IMAGE_INFO_TABLE_GUID;
75 EFI_GUID fdtdtb = FDT_TABLE_GUID;
76 EFI_GUID inputid = SIMPLE_TEXT_INPUT_PROTOCOL;
79 * Number of seconds to wait for a keystroke before exiting with failure
80 * in the event no currdev is found. -2 means always break, -1 means
81 * never break, 0 means poll once and then reboot, > 0 means wait for
82 * that many seconds. "fail_timeout" can be set in the environment as
85 static int fail_timeout = 5;
88 * Current boot variable
93 * Image that we booted from.
95 EFI_LOADED_IMAGE *boot_img;
101 EFI_DEVICE_PATH *path;
102 EFI_HANDLE *hin, *hin_end, *walker;
107 * Find all the handles that support the SIMPLE_TEXT_INPUT_PROTOCOL and
108 * do the typical dance to get the right sized buffer.
112 status = BS->LocateHandle(ByProtocol, &inputid, 0, &sz, 0);
113 if (status == EFI_BUFFER_TOO_SMALL) {
114 hin = (EFI_HANDLE *)malloc(sz);
115 status = BS->LocateHandle(ByProtocol, &inputid, 0, &sz,
117 if (EFI_ERROR(status))
120 if (EFI_ERROR(status))
124 * Look at each of the handles. If it supports the device path protocol,
125 * use it to get the device path for this handle. Then see if that
126 * device path matches either the USB device path for keyboards or the
127 * legacy device path for keyboards.
129 hin_end = &hin[sz / sizeof(*hin)];
130 for (walker = hin; walker < hin_end; walker++) {
131 status = OpenProtocolByHandle(*walker, &devid, (void **)&path);
132 if (EFI_ERROR(status))
135 while (!IsDevicePathEnd(path)) {
137 * Check for the ACPI keyboard node. All PNP3xx nodes
138 * are keyboards of different flavors. Note: It is
139 * unclear of there's always a keyboard node when
140 * there's a keyboard controller, or if there's only one
141 * when a keyboard is detected at boot.
143 if (DevicePathType(path) == ACPI_DEVICE_PATH &&
144 (DevicePathSubType(path) == ACPI_DP ||
145 DevicePathSubType(path) == ACPI_EXTENDED_DP)) {
146 ACPI_HID_DEVICE_PATH *acpi;
148 acpi = (ACPI_HID_DEVICE_PATH *)(void *)path;
149 if ((EISA_ID_TO_NUM(acpi->HID) & 0xff00) == 0x300 &&
150 (acpi->HID & 0xffff) == PNP_EISA_ID_CONST) {
155 * Check for USB keyboard node, if present. Unlike a
156 * PS/2 keyboard, these definitely only appear when
157 * connected to the system.
159 } else if (DevicePathType(path) == MESSAGING_DEVICE_PATH &&
160 DevicePathSubType(path) == MSG_USB_CLASS_DP) {
161 USB_CLASS_DEVICE_PATH *usb;
163 usb = (USB_CLASS_DEVICE_PATH *)(void *)path;
164 if (usb->DeviceClass == 3 && /* HID */
165 usb->DeviceSubClass == 1 && /* Boot devices */
166 usb->DeviceProtocol == 1) { /* Boot keyboards */
171 path = NextDevicePathNode(path);
180 set_currdev(const char *devname)
184 * Don't execute hooks here; we may need to try setting these more than
185 * once here if we're probing for the ZFS pool we're supposed to boot.
186 * The currdev hook is intended to just validate user input anyways,
187 * while the loaddev hook makes it immutable once we've determined what
188 * the proper currdev is.
190 env_setenv("currdev", EV_VOLATILE | EV_NOHOOK, devname, efi_setcurrdev,
192 env_setenv("loaddev", EV_VOLATILE | EV_NOHOOK, devname, env_noset,
197 set_currdev_devdesc(struct devdesc *currdev)
201 devname = efi_fmtdev(currdev);
202 printf("Setting currdev to %s\n", devname);
203 set_currdev(devname);
207 set_currdev_devsw(struct devsw *dev, int unit)
209 struct devdesc currdev;
212 currdev.d_unit = unit;
214 set_currdev_devdesc(&currdev);
218 set_currdev_pdinfo(pdinfo_t *dp)
222 * Disks are special: they have partitions. if the parent
223 * pointer is non-null, we're a partition not a full disk
224 * and we need to adjust currdev appropriately.
226 if (dp->pd_devsw->dv_type == DEVT_DISK) {
227 struct disk_devdesc currdev;
229 currdev.dd.d_dev = dp->pd_devsw;
230 if (dp->pd_parent == NULL) {
231 currdev.dd.d_unit = dp->pd_unit;
232 currdev.d_slice = D_SLICENONE;
233 currdev.d_partition = D_PARTNONE;
235 currdev.dd.d_unit = dp->pd_parent->pd_unit;
236 currdev.d_slice = dp->pd_unit;
237 currdev.d_partition = D_PARTISGPT; /* XXX Assumes GPT */
239 set_currdev_devdesc((struct devdesc *)&currdev);
241 set_currdev_devsw(dp->pd_devsw, dp->pd_unit);
246 sanity_check_currdev(void)
250 return (stat(PATH_DEFAULTS_LOADER_CONF, &st) == 0 ||
251 #ifdef PATH_BOOTABLE_TOKEN
252 stat(PATH_BOOTABLE_TOKEN, &st) == 0 || /* non-standard layout */
254 stat(PATH_KERNEL, &st) == 0);
259 probe_zfs_currdev(uint64_t guid)
262 struct zfs_devdesc currdev;
264 currdev.dd.d_dev = &zfs_dev;
265 currdev.dd.d_unit = 0;
266 currdev.pool_guid = guid;
267 currdev.root_guid = 0;
268 set_currdev_devdesc((struct devdesc *)&currdev);
269 devname = efi_fmtdev(&currdev);
270 init_zfs_bootenv(devname);
272 return (sanity_check_currdev());
277 try_as_currdev(pdinfo_t *hd, pdinfo_t *pp)
283 * If there's a zpool on this device, try it as a ZFS
284 * filesystem, which has somewhat different setup than all
285 * other types of fs due to imperfect loader integration.
286 * This all stems from ZFS being both a device (zpool) and
287 * a filesystem, plus the boot env feature.
289 if (efizfs_get_guid_by_handle(pp->pd_handle, &guid))
290 return (probe_zfs_currdev(guid));
293 * All other filesystems just need the pdinfo
294 * initialized in the standard way.
296 set_currdev_pdinfo(pp);
297 return (sanity_check_currdev());
301 * Sometimes we get filenames that are all upper case
302 * and/or have backslashes in them. Filter all this out
303 * if it looks like we need to do so.
317 #define SIZE(dp, edp) (size_t)((intptr_t)(void *)edp - (intptr_t)(void *)dp)
319 enum { BOOT_INFO_OK = 0, BAD_CHOICE = 1, NOT_SPECIFIC = 2 };
321 match_boot_info(char *boot_info, size_t bisz)
327 EFI_DEVICE_PATH *dp, *edp, *first_dp, *last_dp;
331 FILEPATH_DEVICE_PATH *fp;
336 * FreeBSD encodes it's boot loading path into the boot loader
337 * BootXXXX variable. We look for the last one in the path
338 * and use that to load the kernel. However, if we only fine
339 * one DEVICE_PATH, then there's nothing specific and we should
342 * In an ideal world, we'd look at the image handle we were
343 * passed, match up with the loader we are and then return the
344 * next one in the path. This would be most flexible and cover
345 * many chain booting scenarios where you need to use this
346 * boot loader to get to the next boot loader. However, that
347 * doesn't work. We rarely have the path to the image booted
348 * (just the device) so we can't count on that. So, we do the
349 * enxt best thing, we look through the device path(s) passed
350 * in the BootXXXX varaible. If there's only one, we return
351 * NOT_SPECIFIC. Otherwise, we look at the last one and try to
352 * load that. If we can, we return BOOT_INFO_OK. Otherwise we
353 * return BAD_CHOICE for the caller to sort out.
355 if (bisz < sizeof(attr) + sizeof(fplen) + sizeof(CHAR16))
359 memcpy(&attr, walker, sizeof(attr));
360 walker += sizeof(attr);
361 memcpy(&fplen, walker, sizeof(fplen));
362 walker += sizeof(fplen);
363 descr = (CHAR16 *)(intptr_t)walker;
364 len = ucs2len(descr);
365 walker += (len + 1) * sizeof(CHAR16);
366 last_dp = first_dp = dp = (EFI_DEVICE_PATH *)walker;
367 edp = (EFI_DEVICE_PATH *)(walker + fplen);
368 if ((char *)edp > ep)
370 while (dp < edp && SIZE(dp, edp) > sizeof(EFI_DEVICE_PATH)) {
371 text = efi_devpath_name(dp);
373 printf(" BootInfo Path: %S\n", text);
374 efi_free_devpath_name(text);
377 dp = (EFI_DEVICE_PATH *)((char *)dp + efi_devpath_length(dp));
381 * If there's only one item in the list, then nothing was
382 * specified. Or if the last path doesn't have a media
383 * path in it. Those show up as various VenHw() nodes
384 * which are basically opaque to us. Don't count those
385 * as something specifc.
387 if (last_dp == first_dp) {
388 printf("Ignoring Boot%04x: Only one DP found\n", boot_current);
391 if (efi_devpath_to_media_path(last_dp) == NULL) {
392 printf("Ignoring Boot%04x: No Media Path\n", boot_current);
397 * OK. At this point we either have a good path or a bad one.
400 pp = efiblk_get_pdinfo_by_device_path(last_dp);
402 printf("Ignoring Boot%04x: Device Path not found\n", boot_current);
405 set_currdev_pdinfo(pp);
406 if (!sanity_check_currdev()) {
407 printf("Ignoring Boot%04x: sanity check failed\n", boot_current);
412 * OK. We've found a device that matches, next we need to check the last
413 * component of the path. If it's a file, then we set the default kernel
414 * to that. Otherwise, just use this as the default root.
416 * Reminder: we're running very early, before we've parsed the defaults
417 * file, so we may need to have a hack override.
419 dp = efi_devpath_last_node(last_dp);
420 if (DevicePathType(dp) != MEDIA_DEVICE_PATH ||
421 DevicePathSubType(dp) != MEDIA_FILEPATH_DP) {
422 printf("Using Boot%04x for root partition\n", boot_current);
423 return (BOOT_INFO_OK); /* use currdir, default kernel */
425 fp = (FILEPATH_DEVICE_PATH *)dp;
426 ucs2_to_utf8(fp->PathName, &kernel);
427 if (kernel == NULL) {
428 printf("Not using Boot%04x: can't decode kernel\n", boot_current);
431 if (*kernel == '\\' || isupper(*kernel))
433 if (stat(kernel, &st) != 0) {
435 printf("Not using Boot%04x: can't find %s\n", boot_current,
439 setenv("kernel", kernel, 1);
441 text = efi_devpath_name(last_dp);
443 printf("Using Boot%04x %S + %s\n", boot_current, text,
445 efi_free_devpath_name(text);
448 return (BOOT_INFO_OK);
452 * Look at the passed-in boot_info, if any. If we find it then we need
453 * to see if we can find ourselves in the boot chain. If we can, and
454 * there's another specified thing to boot next, assume that the file
455 * is loaded from / and use that for the root filesystem. If can't
456 * find the specified thing, we must fail the boot. If we're last on
457 * the list, then we fallback to looking for the first available /
458 * candidate (ZFS, if there's a bootable zpool, otherwise a UFS
459 * partition that has either /boot/defaults/loader.conf on it or
460 * /boot/kernel/kernel (the default kernel) that we can use.
462 * We always fail if we can't find the right thing. However, as
463 * a concession to buggy UEFI implementations, like u-boot, if
464 * we have determined that the host is violating the UEFI boot
465 * manager protocol, we'll signal the rest of the program that
466 * a drop to the OK boot loader prompt is possible.
469 find_currdev(bool do_bootmgr, bool is_last,
470 char *boot_info, size_t boot_info_sz)
473 EFI_DEVICE_PATH *devpath, *copy;
483 * First choice: if rootdev is already set, use that, even if
486 rootdev = getenv("rootdev");
487 if (rootdev != NULL) {
488 printf(" Setting currdev to configured rootdev %s\n",
490 set_currdev(rootdev);
495 * Second choice: If uefi_rootdev is set, translate that UEFI device
496 * path to the loader's internal name and use that.
499 rootdev = getenv("uefi_rootdev");
502 devpath = efi_name_to_devpath(rootdev);
505 dp = efiblk_get_pdinfo_by_device_path(devpath);
506 efi_devpath_free(devpath);
509 printf(" Setting currdev to UEFI path %s\n",
511 set_currdev_pdinfo(dp);
516 * Third choice: If we can find out image boot_info, and there's
517 * a follow-on boot image in that boot_info, use that. In this
518 * case root will be the partition specified in that image and
519 * we'll load the kernel specified by the file path. Should there
520 * not be a filepath, we use the default. This filepath overrides
524 rv = match_boot_info(boot_info, boot_info_sz);
526 case BOOT_INFO_OK: /* We found it */
528 case BAD_CHOICE: /* specified file not found -> error */
529 /* XXX do we want to have an escape hatch for last in boot order? */
531 } /* Nothing specified, try normal match */
536 * Did efi_zfs_probe() detect the boot pool? If so, use the zpool
537 * it found, if it's sane. ZFS is the only thing that looks for
538 * disks and pools to boot. This may change in the future, however,
539 * if we allow specifying which pool to boot from via UEFI variables
540 * rather than the bootenv stuff that FreeBSD uses today.
542 if (pool_guid != 0) {
543 printf("Trying ZFS pool\n");
544 if (probe_zfs_currdev(pool_guid))
547 #endif /* EFI_ZFS_BOOT */
550 * Try to find the block device by its handle based on the
551 * image we're booting. If we can't find a sane partition,
552 * search all the other partitions of the disk. We do not
553 * search other disks because it's a violation of the UEFI
554 * boot protocol to do so. We fail and let UEFI go on to
555 * the next candidate.
557 dp = efiblk_get_pdinfo_by_handle(boot_img->DeviceHandle);
559 text = efi_devpath_name(dp->pd_devpath);
561 printf("Trying ESP: %S\n", text);
562 efi_free_devpath_name(text);
564 set_currdev_pdinfo(dp);
565 if (sanity_check_currdev())
567 if (dp->pd_parent != NULL) {
568 pdinfo_t *espdp = dp;
570 STAILQ_FOREACH(pp, &dp->pd_part, pd_link) {
571 /* Already tried the ESP */
575 * Roll up the ZFS special case
576 * for those partitions that have
579 text = efi_devpath_name(pp->pd_devpath);
581 printf("Trying: %S\n", text);
582 efi_free_devpath_name(text);
584 if (try_as_currdev(dp, pp))
591 * Try the device handle from our loaded image first. If that
592 * fails, use the device path from the loaded image and see if
593 * any of the nodes in that path match one of the enumerated
594 * handles. Currently, this handle list is only for netboot.
596 if (efi_handle_lookup(boot_img->DeviceHandle, &dev, &unit, &extra) == 0) {
597 set_currdev_devsw(dev, unit);
598 if (sanity_check_currdev())
603 devpath = efi_lookup_image_devpath(IH);
604 while (devpath != NULL) {
605 h = efi_devpath_handle(devpath);
612 if (efi_handle_lookup(h, &dev, &unit, &extra) == 0) {
613 set_currdev_devsw(dev, unit);
614 if (sanity_check_currdev())
618 devpath = efi_lookup_devpath(h);
619 if (devpath != NULL) {
620 copy = efi_devpath_trim(devpath);
630 interactive_interrupt(const char *msg)
632 time_t now, then, last;
635 now = then = getsecs();
637 if (fail_timeout == -2) /* Always break to OK */
639 if (fail_timeout == -1) /* Never break to OK */
643 printf("press any key to interrupt reboot in %d seconds\r",
644 fail_timeout - (int)(now - then));
648 /* XXX no pause or timeout wait for char */
652 } while (now - then < fail_timeout);
657 parse_args(int argc, CHAR16 *argv[])
664 * Parse the args to set the console settings, etc
665 * boot1.efi passes these in, if it can read /boot.config or /boot/config
666 * or iPXE may be setup to pass these in. Or the optional argument in the
667 * boot environment was used to pass these arguments in (in which case
668 * neither /boot.config nor /boot/config are consulted).
670 * Loop through the args, and for each one that contains an '=' that is
671 * not the first character, add it to the environment. This allows
672 * loader and kernel env vars to be passed on the command line. Convert
673 * args from UCS-2 to ASCII (16 to 8 bit) as they are copied (though this
674 * method is flawed for non-ASCII characters).
677 for (i = 1; i < argc; i++) {
678 cpy16to8(argv[i], var, sizeof(var));
679 howto |= boot_parse_arg(var);
686 setenv_int(const char *key, int val)
690 snprintf(buf, sizeof(buf), "%d", val);
695 * Parse ConOut (the list of consoles active) and see if we can find a
696 * serial port and/or a video port. It would be nice to also walk the
697 * ACPI name space to map the UID for the serial port to a port. The
698 * latter is especially hard.
701 parse_uefi_con_out(void)
704 int vid_seen = 0, com_seen = 0, seen = 0;
707 EFI_DEVICE_PATH *node;
708 ACPI_HID_DEVICE_PATH *acpi;
709 UART_DEVICE_PATH *uart;
714 rv = efi_global_getenv("ConOut", buf, &sz);
715 if (rv != EFI_SUCCESS) {
716 /* If we don't have any ConOut default to serial */
721 node = (EFI_DEVICE_PATH *)buf;
722 while ((char *)node < ep) {
724 if (DevicePathType(node) == ACPI_DEVICE_PATH &&
725 (DevicePathSubType(node) == ACPI_DP ||
726 DevicePathSubType(node) == ACPI_EXTENDED_DP)) {
727 /* Check for Serial node */
729 if (EISA_ID_TO_NUM(acpi->HID) == 0x501) {
730 setenv_int("efi_8250_uid", acpi->UID);
733 } else if (DevicePathType(node) == MESSAGING_DEVICE_PATH &&
734 DevicePathSubType(node) == MSG_UART_DP) {
737 setenv_int("efi_com_speed", uart->BaudRate);
738 } else if (DevicePathType(node) == ACPI_DEVICE_PATH &&
739 DevicePathSubType(node) == ACPI_ADR_DP) {
740 /* Check for AcpiAdr() Node for video */
742 } else if (DevicePathType(node) == HARDWARE_DEVICE_PATH &&
743 DevicePathSubType(node) == HW_PCI_DP) {
745 * Note, vmware fusion has a funky console device
746 * PciRoot(0x0)/Pci(0xf,0x0)
747 * which we can only detect at the end since we also
749 * PciRoot(0x0)/Pci(0x1f,0x0)/Serial(0x1)
750 * so only match it if it's last.
754 node = NextDevicePathNode(node);
756 if (pci_pending && vid_seen == 0)
760 * Truth table for RB_MULTIPLE | RB_SERIAL
762 * 0 Use only video console
763 * RB_SERIAL Use only serial console
764 * RB_MULTIPLE Use both video and serial console
765 * (but video is primary so gets rc messages)
766 * both Use both video and serial console
767 * (but serial is primary so gets rc messages)
769 * Try to honor this as best we can. If only one of serial / video
770 * found, then use that. Otherwise, use the first one we found.
771 * This also implies if we found nothing, default to video.
774 if (vid_seen && com_seen) {
776 if (com_seen < vid_seen)
785 parse_loader_efi_config(EFI_HANDLE h, const char *env_fn)
792 dp = efiblk_get_pdinfo_by_handle(h);
795 set_currdev_pdinfo(dp);
796 if (stat(env_fn, &st) != 0)
798 fd = open(env_fn, O_RDONLY);
801 env = malloc(st.st_size + 1);
804 if (read(fd, env, st.st_size) != st.st_size)
806 env[st.st_size] = '\0';
807 boot_parse_cmdline(env);
814 read_loader_env(const char *name, char *def_fn, bool once)
817 char *fn, *freeme = NULL;
821 if (efi_freebsd_getenv(name, NULL, &len) == EFI_BUFFER_TOO_SMALL) {
822 freeme = fn = malloc(len + 1);
824 if (efi_freebsd_getenv(name, fn, &len) != EFI_SUCCESS) {
828 "Can't fetch FreeBSD::%s we know is there\n", name);
831 * if tagged as 'once' delete the env variable so we
835 efi_freebsd_delenv(name);
837 * We malloced 1 more than len above, then redid the call.
838 * so now we have room at the end of the string to NUL terminate
839 * it here, even if the typical idium would have '- 1' here to
840 * not overflow. len should be the same on return both times.
846 "Can't allocate %d bytes to fetch FreeBSD::%s env var\n",
851 printf(" Reading loader env vars from %s\n", fn);
852 parse_loader_efi_config(boot_img->DeviceHandle, fn);
863 main(int argc, CHAR16 *argv[])
866 int howto, i, uhowto;
868 bool has_kbd, is_last;
870 EFI_DEVICE_PATH *imgpath;
873 size_t sz, bosz = 0, bisz = 0;
874 UINT16 boot_order[100];
875 char boot_info[4096];
879 archsw.arch_autoload = efi_autoload;
880 archsw.arch_getdev = efi_getdev;
881 archsw.arch_copyin = efi_copyin;
882 archsw.arch_copyout = efi_copyout;
884 archsw.arch_hypervisor = x86_hypervisor;
886 archsw.arch_readin = efi_readin;
887 archsw.arch_zfs_probe = efi_zfs_probe;
889 /* Get our loaded image protocol interface structure. */
890 (void) OpenProtocolByHandle(IH, &imgid, (void **)&boot_img);
893 * Chicken-and-egg problem; we want to have console output early, but
894 * some console attributes may depend on reading from eg. the boot
895 * device, which we can't do yet. We can use printf() etc. once this is
896 * done. So, we set it to the efi console, then call console init. This
897 * gets us printf early, but also primes the pump for all future console
898 * changes to take effect, regardless of where they come from.
900 setenv("console", "efi", 1);
901 uhowto = parse_uefi_con_out();
902 #if defined(__aarch64__) || defined(__arm__)
903 if ((uhowto & RB_SERIAL) != 0)
904 setenv("console", "comconsole", 1);
908 /* Init the time source */
912 * Initialise the block cache. Set the upper limit.
914 bcache_init(32768, 512);
917 * Scan the BLOCK IO MEDIA handles then
918 * march through the device switch probing for things.
920 i = efipart_inithandles();
921 if (i != 0 && i != ENOENT) {
922 printf("efipart_inithandles failed with ERRNO %d, expect "
926 for (i = 0; devsw[i] != NULL; i++)
927 if (devsw[i]->dv_init != NULL)
928 (devsw[i]->dv_init)();
931 * Detect console settings two different ways: one via the command
932 * args (eg -h) or via the UEFI ConOut variable.
934 has_kbd = has_keyboard();
935 howto = parse_args(argc, argv);
936 if (!has_kbd && (howto & RB_PROBE))
937 howto |= RB_SERIAL | RB_MULTIPLE;
941 * Read additional environment variables from the boot device's
942 * "LoaderEnv" file. Any boot loader environment variable may be set
943 * there, which are subtly different than loader.conf variables. Only
944 * the 'simple' ones may be set so things like foo_load="YES" won't work
945 * for two reasons. First, the parser is simplistic and doesn't grok
946 * quotes. Second, because the variables that cause an action to happen
947 * are parsed by the lua, 4th or whatever code that's not yet
948 * loaded. This is relative to the root directory when loader.efi is
949 * loaded off the UFS root drive (when chain booted), or from the ESP
950 * when directly loaded by the BIOS.
952 * We also read in NextLoaderEnv if it was specified. This allows next boot
953 * functionality to be implemented and to override anything in LoaderEnv.
955 read_loader_env("LoaderEnv", "/efi/freebsd/loader.env", false);
956 read_loader_env("NextLoaderEnv", NULL, true);
959 * We now have two notions of console. howto should be viewed as
960 * overrides. If console is already set, don't set it again.
963 #define SERIAL_ONLY RB_SERIAL
964 #define VID_SER_BOTH RB_MULTIPLE
965 #define SER_VID_BOTH (RB_SERIAL | RB_MULTIPLE)
966 #define CON_MASK (RB_SERIAL | RB_MULTIPLE)
967 if (strcmp(getenv("console"), "efi") == 0) {
968 if ((howto & CON_MASK) == 0) {
969 /* No override, uhowto is controlling and efi cons is perfect */
970 howto = howto | (uhowto & CON_MASK);
971 } else if ((howto & CON_MASK) == (uhowto & CON_MASK)) {
972 /* override matches what UEFI told us, efi console is perfect */
973 } else if ((uhowto & (CON_MASK)) != 0) {
975 * We detected a serial console on ConOut. All possible
976 * overrides include serial. We can't really override what efi
977 * gives us, so we use it knowing it's the best choice.
982 * We detected some kind of serial in the override, but ConOut
983 * has no serial, so we have to sort out which case it really is.
985 switch (howto & CON_MASK) {
987 setenv("console", "comconsole", 1);
990 setenv("console", "efi comconsole", 1);
993 setenv("console", "comconsole efi", 1);
995 /* case VIDEO_ONLY can't happen -- it's the first if above */
1001 * howto is set now how we want to export the flags to the kernel, so
1002 * set the env based on it.
1004 boot_howto_to_env(howto);
1006 if (efi_copy_init()) {
1007 printf("failed to allocate staging area\n");
1008 return (EFI_BUFFER_TOO_SMALL);
1011 if ((s = getenv("fail_timeout")) != NULL)
1012 fail_timeout = strtol(s, NULL, 10);
1014 printf("%s\n", bootprog_info);
1015 printf(" Command line arguments:");
1016 for (i = 0; i < argc; i++)
1017 printf(" %S", argv[i]);
1020 printf(" Image base: 0x%lx\n", (unsigned long)boot_img->ImageBase);
1021 printf(" EFI version: %d.%02d\n", ST->Hdr.Revision >> 16,
1022 ST->Hdr.Revision & 0xffff);
1023 printf(" EFI Firmware: %S (rev %d.%02d)\n", ST->FirmwareVendor,
1024 ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff);
1025 printf(" Console: %s (%#x)\n", getenv("console"), howto);
1027 /* Determine the devpath of our image so we can prefer it. */
1028 text = efi_devpath_name(boot_img->FilePath);
1030 printf(" Load Path: %S\n", text);
1031 efi_setenv_freebsd_wcs("LoaderPath", text);
1032 efi_free_devpath_name(text);
1035 rv = OpenProtocolByHandle(boot_img->DeviceHandle, &devid,
1037 if (rv == EFI_SUCCESS) {
1038 text = efi_devpath_name(imgpath);
1040 printf(" Load Device: %S\n", text);
1041 efi_setenv_freebsd_wcs("LoaderDev", text);
1042 efi_free_devpath_name(text);
1046 if (getenv("uefi_ignore_boot_mgr") != NULL) {
1047 printf(" Ignoring UEFI boot manager\n");
1048 uefi_boot_mgr = false;
1050 uefi_boot_mgr = true;
1052 sz = sizeof(boot_current);
1053 rv = efi_global_getenv("BootCurrent", &boot_current, &sz);
1054 if (rv == EFI_SUCCESS)
1055 printf(" BootCurrent: %04x\n", boot_current);
1057 boot_current = 0xffff;
1058 uefi_boot_mgr = false;
1061 sz = sizeof(boot_order);
1062 rv = efi_global_getenv("BootOrder", &boot_order, &sz);
1063 if (rv == EFI_SUCCESS) {
1064 printf(" BootOrder:");
1065 for (i = 0; i < sz / sizeof(boot_order[0]); i++)
1066 printf(" %04x%s", boot_order[i],
1067 boot_order[i] == boot_current ? "[*]" : "");
1069 is_last = boot_order[(sz / sizeof(boot_order[0])) - 1] == boot_current;
1071 } else if (uefi_boot_mgr) {
1073 * u-boot doesn't set BootOrder, but otherwise participates in the
1074 * boot manager protocol. So we fake it here and don't consider it
1077 bosz = sizeof(boot_order[0]);
1078 boot_order[0] = boot_current;
1084 * Next, find the boot info structure the UEFI boot manager is
1085 * supposed to setup. We need this so we can walk through it to
1086 * find where we are in the booting process and what to try to
1089 if (uefi_boot_mgr) {
1090 snprintf(buf, sizeof(buf), "Boot%04X", boot_current);
1091 sz = sizeof(boot_info);
1092 rv = efi_global_getenv(buf, &boot_info, &sz);
1093 if (rv == EFI_SUCCESS)
1096 uefi_boot_mgr = false;
1100 * Disable the watchdog timer. By default the boot manager sets
1101 * the timer to 5 minutes before invoking a boot option. If we
1102 * want to return to the boot manager, we have to disable the
1103 * watchdog timer and since we're an interactive program, we don't
1104 * want to wait until the user types "quit". The timer may have
1105 * fired by then. We don't care if this fails. It does not prevent
1106 * normal functioning in any way...
1108 BS->SetWatchdogTimer(0, 0, 0, NULL);
1111 * Initialize the trusted/forbidden certificates from UEFI.
1112 * They will be later used to verify the manifest(s),
1113 * which should contain hashes of verified files.
1114 * This needs to be initialized before any configuration files
1117 #ifdef EFI_SECUREBOOT
1122 * Try and find a good currdev based on the image that was booted.
1123 * It might be desirable here to have a short pause to allow falling
1124 * through to the boot loader instead of returning instantly to follow
1125 * the boot protocol and also allow an escape hatch for users wishing
1126 * to try something different.
1128 if (find_currdev(uefi_boot_mgr, is_last, boot_info, bisz) != 0)
1129 if (uefi_boot_mgr &&
1130 !interactive_interrupt("Failed to find bootable partition"))
1131 return (EFI_NOT_FOUND);
1133 efi_init_environment();
1135 #if !defined(__arm__)
1136 for (k = 0; k < ST->NumberOfTableEntries; k++) {
1137 guid = &ST->ConfigurationTable[k].VendorGuid;
1138 if (!memcmp(guid, &smbios, sizeof(EFI_GUID))) {
1141 snprintf(buf, sizeof(buf), "%p",
1142 ST->ConfigurationTable[k].VendorTable);
1143 setenv("hint.smbios.0.mem", buf, 1);
1144 smbios_detect(ST->ConfigurationTable[k].VendorTable);
1150 interact(); /* doesn't return */
1152 return (EFI_SUCCESS); /* keep compiler happy */
1155 COMMAND_SET(poweroff, "poweroff", "power off the system", command_poweroff);
1158 command_poweroff(int argc __unused, char *argv[] __unused)
1162 for (i = 0; devsw[i] != NULL; ++i)
1163 if (devsw[i]->dv_cleanup != NULL)
1164 (devsw[i]->dv_cleanup)();
1166 RS->ResetSystem(EfiResetShutdown, EFI_SUCCESS, 0, NULL);
1172 COMMAND_SET(reboot, "reboot", "reboot the system", command_reboot);
1175 command_reboot(int argc, char *argv[])
1179 for (i = 0; devsw[i] != NULL; ++i)
1180 if (devsw[i]->dv_cleanup != NULL)
1181 (devsw[i]->dv_cleanup)();
1183 RS->ResetSystem(EfiResetCold, EFI_SUCCESS, 0, NULL);
1189 COMMAND_SET(quit, "quit", "exit the loader", command_quit);
1192 command_quit(int argc, char *argv[])
1198 COMMAND_SET(memmap, "memmap", "print memory map", command_memmap);
1201 command_memmap(int argc __unused, char *argv[] __unused)
1204 EFI_MEMORY_DESCRIPTOR *map, *p;
1212 status = BS->GetMemoryMap(&sz, 0, &key, &dsz, &dver);
1213 if (status != EFI_BUFFER_TOO_SMALL) {
1214 printf("Can't determine memory map size\n");
1218 status = BS->GetMemoryMap(&sz, map, &key, &dsz, &dver);
1219 if (EFI_ERROR(status)) {
1220 printf("Can't read memory map\n");
1225 snprintf(line, sizeof(line), "%23s %12s %12s %8s %4s\n",
1226 "Type", "Physical", "Virtual", "#Pages", "Attr");
1228 if (pager_output(line)) {
1233 for (i = 0, p = map; i < ndesc;
1234 i++, p = NextMemoryDescriptor(p, dsz)) {
1235 snprintf(line, sizeof(line), "%23s %012jx %012jx %08jx ",
1236 efi_memory_type(p->Type), (uintmax_t)p->PhysicalStart,
1237 (uintmax_t)p->VirtualStart, (uintmax_t)p->NumberOfPages);
1238 if (pager_output(line))
1241 if (p->Attribute & EFI_MEMORY_UC)
1243 if (p->Attribute & EFI_MEMORY_WC)
1245 if (p->Attribute & EFI_MEMORY_WT)
1247 if (p->Attribute & EFI_MEMORY_WB)
1249 if (p->Attribute & EFI_MEMORY_UCE)
1251 if (p->Attribute & EFI_MEMORY_WP)
1253 if (p->Attribute & EFI_MEMORY_RP)
1255 if (p->Attribute & EFI_MEMORY_XP)
1257 if (p->Attribute & EFI_MEMORY_NV)
1259 if (p->Attribute & EFI_MEMORY_MORE_RELIABLE)
1261 if (p->Attribute & EFI_MEMORY_RO)
1263 if (pager_output("\n"))
1271 COMMAND_SET(configuration, "configuration", "print configuration tables",
1272 command_configuration);
1275 command_configuration(int argc, char *argv[])
1280 printf("NumberOfTableEntries=%lu\n",
1281 (unsigned long)ST->NumberOfTableEntries);
1283 for (i = 0; i < ST->NumberOfTableEntries; i++) {
1287 guid = &ST->ConfigurationTable[i].VendorGuid;
1289 if (efi_guid_to_name(guid, &name) == true) {
1293 printf("Error while translating UUID to name");
1295 printf(" at %p\n", ST->ConfigurationTable[i].VendorTable);
1302 COMMAND_SET(mode, "mode", "change or display EFI text modes", command_mode);
1305 command_mode(int argc, char *argv[])
1312 SIMPLE_TEXT_OUTPUT_INTERFACE *conout;
1314 conout = ST->ConOut;
1317 mode = strtol(argv[1], &cp, 0);
1318 if (cp[0] != '\0') {
1319 printf("Invalid mode\n");
1322 status = conout->QueryMode(conout, mode, &cols, &rows);
1323 if (EFI_ERROR(status)) {
1324 printf("invalid mode %d\n", mode);
1327 status = conout->SetMode(conout, mode);
1328 if (EFI_ERROR(status)) {
1329 printf("couldn't set mode %d\n", mode);
1332 (void) efi_cons_update_mode();
1336 printf("Current mode: %d\n", conout->Mode->Mode);
1337 for (i = 0; i <= conout->Mode->MaxMode; i++) {
1338 status = conout->QueryMode(conout, i, &cols, &rows);
1339 if (EFI_ERROR(status))
1341 printf("Mode %d: %u columns, %u rows\n", i, (unsigned)cols,
1346 printf("Select a mode with the command \"mode <number>\"\n");
1351 COMMAND_SET(lsefi, "lsefi", "list EFI handles", command_lsefi);
1354 command_lsefi(int argc __unused, char *argv[] __unused)
1357 EFI_HANDLE *buffer = NULL;
1359 UINTN bufsz = 0, i, j;
1363 status = BS->LocateHandle(AllHandles, NULL, NULL, &bufsz, buffer);
1364 if (status != EFI_BUFFER_TOO_SMALL) {
1365 snprintf(command_errbuf, sizeof (command_errbuf),
1366 "unexpected error: %lld", (long long)status);
1369 if ((buffer = malloc(bufsz)) == NULL) {
1370 sprintf(command_errbuf, "out of memory");
1374 status = BS->LocateHandle(AllHandles, NULL, NULL, &bufsz, buffer);
1375 if (EFI_ERROR(status)) {
1377 snprintf(command_errbuf, sizeof (command_errbuf),
1378 "LocateHandle() error: %lld", (long long)status);
1383 for (i = 0; i < (bufsz / sizeof (EFI_HANDLE)); i++) {
1385 EFI_GUID **protocols = NULL;
1388 printf("Handle %p", handle);
1389 if (pager_output("\n"))
1393 status = BS->ProtocolsPerHandle(handle, &protocols, &nproto);
1394 if (EFI_ERROR(status)) {
1395 snprintf(command_errbuf, sizeof (command_errbuf),
1396 "ProtocolsPerHandle() error: %lld",
1401 for (j = 0; j < nproto; j++) {
1402 if (efi_guid_to_name(protocols[j], &name) == true) {
1403 printf(" %s", name);
1406 printf("Error while translating UUID to name");
1408 if ((ret = pager_output("\n")) != 0)
1411 BS->FreePool(protocols);
1420 #ifdef LOADER_FDT_SUPPORT
1421 extern int command_fdt_internal(int argc, char *argv[]);
1424 * Since proper fdt command handling function is defined in fdt_loader_cmd.c,
1425 * and declaring it as extern is in contradiction with COMMAND_SET() macro
1426 * (which uses static pointer), we're defining wrapper function, which
1427 * calls the proper fdt handling routine.
1430 command_fdt(int argc, char *argv[])
1433 return (command_fdt_internal(argc, argv));
1436 COMMAND_SET(fdt, "fdt", "flattened device tree handling", command_fdt);
1440 * Chain load another efi loader.
1443 command_chain(int argc, char *argv[])
1445 EFI_GUID LoadedImageGUID = LOADED_IMAGE_PROTOCOL;
1446 EFI_HANDLE loaderhandle;
1447 EFI_LOADED_IMAGE *loaded_image;
1450 struct devdesc *dev;
1456 command_errmsg = "wrong number of arguments";
1462 if ((fd = open(name, O_RDONLY)) < 0) {
1463 command_errmsg = "no such file";
1467 #ifdef LOADER_VERIEXEC
1468 if (verify_file(fd, name, 0, VE_MUST, __func__) < 0) {
1469 sprintf(command_errbuf, "can't verify: %s", name);
1475 if (fstat(fd, &st) < -1) {
1476 command_errmsg = "stat failed";
1481 status = BS->AllocatePool(EfiLoaderCode, (UINTN)st.st_size, &buf);
1482 if (status != EFI_SUCCESS) {
1483 command_errmsg = "failed to allocate buffer";
1487 if (read(fd, buf, st.st_size) != st.st_size) {
1488 command_errmsg = "error while reading the file";
1489 (void)BS->FreePool(buf);
1494 status = BS->LoadImage(FALSE, IH, NULL, buf, st.st_size, &loaderhandle);
1495 (void)BS->FreePool(buf);
1496 if (status != EFI_SUCCESS) {
1497 command_errmsg = "LoadImage failed";
1500 status = OpenProtocolByHandle(loaderhandle, &LoadedImageGUID,
1501 (void **)&loaded_image);
1507 for (i = 2; i < argc; i++)
1508 len += strlen(argv[i]) + 1;
1510 len *= sizeof (*argp);
1511 loaded_image->LoadOptions = argp = malloc (len);
1512 loaded_image->LoadOptionsSize = len;
1513 for (i = 2; i < argc; i++) {
1514 char *ptr = argv[i];
1516 *(argp++) = *(ptr++);
1522 if (efi_getdev((void **)&dev, name, (const char **)&path) == 0) {
1524 struct zfs_devdesc *z_dev;
1526 struct disk_devdesc *d_dev;
1529 switch (dev->d_dev->dv_type) {
1532 z_dev = (struct zfs_devdesc *)dev;
1533 loaded_image->DeviceHandle =
1534 efizfs_get_handle_by_guid(z_dev->pool_guid);
1538 loaded_image->DeviceHandle =
1539 efi_find_handle(dev->d_dev, dev->d_unit);
1542 hd = efiblk_get_pdinfo(dev);
1543 if (STAILQ_EMPTY(&hd->pd_part)) {
1544 loaded_image->DeviceHandle = hd->pd_handle;
1547 d_dev = (struct disk_devdesc *)dev;
1548 STAILQ_FOREACH(pd, &hd->pd_part, pd_link) {
1550 * d_partition should be 255
1552 if (pd->pd_unit == (uint32_t)d_dev->d_slice) {
1553 loaded_image->DeviceHandle =
1563 status = BS->StartImage(loaderhandle, NULL, NULL);
1564 if (status != EFI_SUCCESS) {
1565 command_errmsg = "StartImage failed";
1566 free(loaded_image->LoadOptions);
1567 loaded_image->LoadOptions = NULL;
1568 status = BS->UnloadImage(loaded_image);
1572 return (CMD_ERROR); /* not reached */
1575 COMMAND_SET(chain, "chain", "chain load file", command_chain);