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>
40 #include <sys/zfs_bootenv.h>
43 #include <netinet/in.h>
44 #include <netinet/in_systm.h>
59 #include <bootstrap.h>
63 #include "framebuffer.h"
65 #include "loader_efi.h"
67 struct arch_switch archsw; /* MI/MD interface boundary */
69 EFI_GUID acpi = ACPI_TABLE_GUID;
70 EFI_GUID acpi20 = ACPI_20_TABLE_GUID;
71 EFI_GUID devid = DEVICE_PATH_PROTOCOL;
72 EFI_GUID imgid = LOADED_IMAGE_PROTOCOL;
73 EFI_GUID mps = MPS_TABLE_GUID;
74 EFI_GUID netid = EFI_SIMPLE_NETWORK_PROTOCOL;
75 EFI_GUID smbios = SMBIOS_TABLE_GUID;
76 EFI_GUID smbios3 = SMBIOS3_TABLE_GUID;
77 EFI_GUID dxe = DXE_SERVICES_TABLE_GUID;
78 EFI_GUID hoblist = HOB_LIST_TABLE_GUID;
79 EFI_GUID lzmadecomp = LZMA_DECOMPRESSION_GUID;
80 EFI_GUID mpcore = ARM_MP_CORE_INFO_TABLE_GUID;
81 EFI_GUID esrt = ESRT_TABLE_GUID;
82 EFI_GUID memtype = MEMORY_TYPE_INFORMATION_TABLE_GUID;
83 EFI_GUID debugimg = DEBUG_IMAGE_INFO_TABLE_GUID;
84 EFI_GUID fdtdtb = FDT_TABLE_GUID;
85 EFI_GUID inputid = SIMPLE_TEXT_INPUT_PROTOCOL;
88 * Number of seconds to wait for a keystroke before exiting with failure
89 * in the event no currdev is found. -2 means always break, -1 means
90 * never break, 0 means poll once and then reboot, > 0 means wait for
91 * that many seconds. "fail_timeout" can be set in the environment as
94 static int fail_timeout = 5;
97 * Current boot variable
102 * Image that we booted from.
104 EFI_LOADED_IMAGE *boot_img;
110 EFI_DEVICE_PATH *path;
111 EFI_HANDLE *hin, *hin_end, *walker;
116 * Find all the handles that support the SIMPLE_TEXT_INPUT_PROTOCOL and
117 * do the typical dance to get the right sized buffer.
121 status = BS->LocateHandle(ByProtocol, &inputid, 0, &sz, 0);
122 if (status == EFI_BUFFER_TOO_SMALL) {
123 hin = (EFI_HANDLE *)malloc(sz);
124 status = BS->LocateHandle(ByProtocol, &inputid, 0, &sz,
126 if (EFI_ERROR(status))
129 if (EFI_ERROR(status))
133 * Look at each of the handles. If it supports the device path protocol,
134 * use it to get the device path for this handle. Then see if that
135 * device path matches either the USB device path for keyboards or the
136 * legacy device path for keyboards.
138 hin_end = &hin[sz / sizeof(*hin)];
139 for (walker = hin; walker < hin_end; walker++) {
140 status = OpenProtocolByHandle(*walker, &devid, (void **)&path);
141 if (EFI_ERROR(status))
144 while (!IsDevicePathEnd(path)) {
146 * Check for the ACPI keyboard node. All PNP3xx nodes
147 * are keyboards of different flavors. Note: It is
148 * unclear of there's always a keyboard node when
149 * there's a keyboard controller, or if there's only one
150 * when a keyboard is detected at boot.
152 if (DevicePathType(path) == ACPI_DEVICE_PATH &&
153 (DevicePathSubType(path) == ACPI_DP ||
154 DevicePathSubType(path) == ACPI_EXTENDED_DP)) {
155 ACPI_HID_DEVICE_PATH *acpi;
157 acpi = (ACPI_HID_DEVICE_PATH *)(void *)path;
158 if ((EISA_ID_TO_NUM(acpi->HID) & 0xff00) == 0x300 &&
159 (acpi->HID & 0xffff) == PNP_EISA_ID_CONST) {
164 * Check for USB keyboard node, if present. Unlike a
165 * PS/2 keyboard, these definitely only appear when
166 * connected to the system.
168 } else if (DevicePathType(path) == MESSAGING_DEVICE_PATH &&
169 DevicePathSubType(path) == MSG_USB_CLASS_DP) {
170 USB_CLASS_DEVICE_PATH *usb;
172 usb = (USB_CLASS_DEVICE_PATH *)(void *)path;
173 if (usb->DeviceClass == 3 && /* HID */
174 usb->DeviceSubClass == 1 && /* Boot devices */
175 usb->DeviceProtocol == 1) { /* Boot keyboards */
180 path = NextDevicePathNode(path);
189 set_currdev_devdesc(struct devdesc *currdev)
193 devname = devformat(currdev);
194 printf("Setting currdev to %s\n", devname);
195 set_currdev(devname);
199 set_currdev_devsw(struct devsw *dev, int unit)
201 struct devdesc currdev;
204 currdev.d_unit = unit;
206 set_currdev_devdesc(&currdev);
210 set_currdev_pdinfo(pdinfo_t *dp)
214 * Disks are special: they have partitions. if the parent
215 * pointer is non-null, we're a partition not a full disk
216 * and we need to adjust currdev appropriately.
218 if (dp->pd_devsw->dv_type == DEVT_DISK) {
219 struct disk_devdesc currdev;
221 currdev.dd.d_dev = dp->pd_devsw;
222 if (dp->pd_parent == NULL) {
223 currdev.dd.d_unit = dp->pd_unit;
224 currdev.d_slice = D_SLICENONE;
225 currdev.d_partition = D_PARTNONE;
227 currdev.dd.d_unit = dp->pd_parent->pd_unit;
228 currdev.d_slice = dp->pd_unit;
229 currdev.d_partition = D_PARTISGPT; /* XXX Assumes GPT */
231 set_currdev_devdesc((struct devdesc *)&currdev);
233 set_currdev_devsw(dp->pd_devsw, dp->pd_unit);
238 sanity_check_currdev(void)
242 return (stat(PATH_DEFAULTS_LOADER_CONF, &st) == 0 ||
243 #ifdef PATH_BOOTABLE_TOKEN
244 stat(PATH_BOOTABLE_TOKEN, &st) == 0 || /* non-standard layout */
246 stat(PATH_KERNEL, &st) == 0);
251 probe_zfs_currdev(uint64_t guid)
254 struct zfs_devdesc currdev;
258 currdev.dd.d_dev = &zfs_dev;
259 currdev.dd.d_unit = 0;
260 currdev.pool_guid = guid;
261 currdev.root_guid = 0;
262 set_currdev_devdesc((struct devdesc *)&currdev);
263 devname = devformat(&currdev.dd);
264 init_zfs_boot_options(devname);
266 bootable = sanity_check_currdev();
268 buf = malloc(VDEV_PAD_SIZE);
270 if (zfs_get_bootonce(&currdev, OS_BOOTONCE, buf,
271 VDEV_PAD_SIZE) == 0) {
272 printf("zfs bootonce: %s\n", buf);
274 setenv("zfs-bootonce", buf, 1);
277 (void) zfs_attach_nvstore(&currdev);
286 probe_md_currdev(void)
288 extern struct devsw md_dev;
291 set_currdev_devsw(&md_dev, 0);
292 rv = sanity_check_currdev();
294 printf("MD not present\n");
300 try_as_currdev(pdinfo_t *hd, pdinfo_t *pp)
306 * If there's a zpool on this device, try it as a ZFS
307 * filesystem, which has somewhat different setup than all
308 * other types of fs due to imperfect loader integration.
309 * This all stems from ZFS being both a device (zpool) and
310 * a filesystem, plus the boot env feature.
312 if (efizfs_get_guid_by_handle(pp->pd_handle, &guid))
313 return (probe_zfs_currdev(guid));
316 * All other filesystems just need the pdinfo
317 * initialized in the standard way.
319 set_currdev_pdinfo(pp);
320 return (sanity_check_currdev());
324 * Sometimes we get filenames that are all upper case
325 * and/or have backslashes in them. Filter all this out
326 * if it looks like we need to do so.
340 #define SIZE(dp, edp) (size_t)((intptr_t)(void *)edp - (intptr_t)(void *)dp)
342 enum { BOOT_INFO_OK = 0, BAD_CHOICE = 1, NOT_SPECIFIC = 2 };
344 match_boot_info(char *boot_info, size_t bisz)
350 EFI_DEVICE_PATH *dp, *edp, *first_dp, *last_dp;
354 FILEPATH_DEVICE_PATH *fp;
359 * FreeBSD encodes its boot loading path into the boot loader
360 * BootXXXX variable. We look for the last one in the path
361 * and use that to load the kernel. However, if we only find
362 * one DEVICE_PATH, then there's nothing specific and we should
365 * In an ideal world, we'd look at the image handle we were
366 * passed, match up with the loader we are and then return the
367 * next one in the path. This would be most flexible and cover
368 * many chain booting scenarios where you need to use this
369 * boot loader to get to the next boot loader. However, that
370 * doesn't work. We rarely have the path to the image booted
371 * (just the device) so we can't count on that. So, we do the
372 * next best thing: we look through the device path(s) passed
373 * in the BootXXXX variable. If there's only one, we return
374 * NOT_SPECIFIC. Otherwise, we look at the last one and try to
375 * load that. If we can, we return BOOT_INFO_OK. Otherwise we
376 * return BAD_CHOICE for the caller to sort out.
378 if (bisz < sizeof(attr) + sizeof(fplen) + sizeof(CHAR16))
382 memcpy(&attr, walker, sizeof(attr));
383 walker += sizeof(attr);
384 memcpy(&fplen, walker, sizeof(fplen));
385 walker += sizeof(fplen);
386 descr = (CHAR16 *)(intptr_t)walker;
387 len = ucs2len(descr);
388 walker += (len + 1) * sizeof(CHAR16);
389 last_dp = first_dp = dp = (EFI_DEVICE_PATH *)walker;
390 edp = (EFI_DEVICE_PATH *)(walker + fplen);
391 if ((char *)edp > ep)
393 while (dp < edp && SIZE(dp, edp) > sizeof(EFI_DEVICE_PATH)) {
394 text = efi_devpath_name(dp);
396 printf(" BootInfo Path: %S\n", text);
397 efi_free_devpath_name(text);
400 dp = (EFI_DEVICE_PATH *)((char *)dp + efi_devpath_length(dp));
404 * If there's only one item in the list, then nothing was
405 * specified. Or if the last path doesn't have a media
406 * path in it. Those show up as various VenHw() nodes
407 * which are basically opaque to us. Don't count those
408 * as something specifc.
410 if (last_dp == first_dp) {
411 printf("Ignoring Boot%04x: Only one DP found\n", boot_current);
414 if (efi_devpath_to_media_path(last_dp) == NULL) {
415 printf("Ignoring Boot%04x: No Media Path\n", boot_current);
420 * OK. At this point we either have a good path or a bad one.
423 pp = efiblk_get_pdinfo_by_device_path(last_dp);
425 printf("Ignoring Boot%04x: Device Path not found\n", boot_current);
428 set_currdev_pdinfo(pp);
429 if (!sanity_check_currdev()) {
430 printf("Ignoring Boot%04x: sanity check failed\n", boot_current);
435 * OK. We've found a device that matches, next we need to check the last
436 * component of the path. If it's a file, then we set the default kernel
437 * to that. Otherwise, just use this as the default root.
439 * Reminder: we're running very early, before we've parsed the defaults
440 * file, so we may need to have a hack override.
442 dp = efi_devpath_last_node(last_dp);
443 if (DevicePathType(dp) != MEDIA_DEVICE_PATH ||
444 DevicePathSubType(dp) != MEDIA_FILEPATH_DP) {
445 printf("Using Boot%04x for root partition\n", boot_current);
446 return (BOOT_INFO_OK); /* use currdir, default kernel */
448 fp = (FILEPATH_DEVICE_PATH *)dp;
449 ucs2_to_utf8(fp->PathName, &kernel);
450 if (kernel == NULL) {
451 printf("Not using Boot%04x: can't decode kernel\n", boot_current);
454 if (*kernel == '\\' || isupper(*kernel))
456 if (stat(kernel, &st) != 0) {
458 printf("Not using Boot%04x: can't find %s\n", boot_current,
462 setenv("kernel", kernel, 1);
464 text = efi_devpath_name(last_dp);
466 printf("Using Boot%04x %S + %s\n", boot_current, text,
468 efi_free_devpath_name(text);
471 return (BOOT_INFO_OK);
475 * Look at the passed-in boot_info, if any. If we find it then we need
476 * to see if we can find ourselves in the boot chain. If we can, and
477 * there's another specified thing to boot next, assume that the file
478 * is loaded from / and use that for the root filesystem. If can't
479 * find the specified thing, we must fail the boot. If we're last on
480 * the list, then we fallback to looking for the first available /
481 * candidate (ZFS, if there's a bootable zpool, otherwise a UFS
482 * partition that has either /boot/defaults/loader.conf on it or
483 * /boot/kernel/kernel (the default kernel) that we can use.
485 * We always fail if we can't find the right thing. However, as
486 * a concession to buggy UEFI implementations, like u-boot, if
487 * we have determined that the host is violating the UEFI boot
488 * manager protocol, we'll signal the rest of the program that
489 * a drop to the OK boot loader prompt is possible.
492 find_currdev(bool do_bootmgr, bool is_last,
493 char *boot_info, size_t boot_info_sz)
496 EFI_DEVICE_PATH *devpath, *copy;
506 * First choice: if rootdev is already set, use that, even if
509 rootdev = getenv("rootdev");
510 if (rootdev != NULL) {
511 printf(" Setting currdev to configured rootdev %s\n",
513 set_currdev(rootdev);
518 * Second choice: If uefi_rootdev is set, translate that UEFI device
519 * path to the loader's internal name and use that.
522 rootdev = getenv("uefi_rootdev");
525 devpath = efi_name_to_devpath(rootdev);
528 dp = efiblk_get_pdinfo_by_device_path(devpath);
529 efi_devpath_free(devpath);
532 printf(" Setting currdev to UEFI path %s\n",
534 set_currdev_pdinfo(dp);
539 * Third choice: If we can find out image boot_info, and there's
540 * a follow-on boot image in that boot_info, use that. In this
541 * case root will be the partition specified in that image and
542 * we'll load the kernel specified by the file path. Should there
543 * not be a filepath, we use the default. This filepath overrides
547 rv = match_boot_info(boot_info, boot_info_sz);
549 case BOOT_INFO_OK: /* We found it */
551 case BAD_CHOICE: /* specified file not found -> error */
552 /* XXX do we want to have an escape hatch for last in boot order? */
554 } /* Nothing specified, try normal match */
559 * Did efi_zfs_probe() detect the boot pool? If so, use the zpool
560 * it found, if it's sane. ZFS is the only thing that looks for
561 * disks and pools to boot. This may change in the future, however,
562 * if we allow specifying which pool to boot from via UEFI variables
563 * rather than the bootenv stuff that FreeBSD uses today.
565 if (pool_guid != 0) {
566 printf("Trying ZFS pool\n");
567 if (probe_zfs_currdev(pool_guid))
570 #endif /* EFI_ZFS_BOOT */
574 * If there is an embedded MD, try to use that.
576 printf("Trying MD\n");
577 if (probe_md_currdev())
579 #endif /* MD_IMAGE_SIZE */
582 * Try to find the block device by its handle based on the
583 * image we're booting. If we can't find a sane partition,
584 * search all the other partitions of the disk. We do not
585 * search other disks because it's a violation of the UEFI
586 * boot protocol to do so. We fail and let UEFI go on to
587 * the next candidate.
589 dp = efiblk_get_pdinfo_by_handle(boot_img->DeviceHandle);
591 text = efi_devpath_name(dp->pd_devpath);
593 printf("Trying ESP: %S\n", text);
594 efi_free_devpath_name(text);
596 set_currdev_pdinfo(dp);
597 if (sanity_check_currdev())
599 if (dp->pd_parent != NULL) {
600 pdinfo_t *espdp = dp;
602 STAILQ_FOREACH(pp, &dp->pd_part, pd_link) {
603 /* Already tried the ESP */
607 * Roll up the ZFS special case
608 * for those partitions that have
611 text = efi_devpath_name(pp->pd_devpath);
613 printf("Trying: %S\n", text);
614 efi_free_devpath_name(text);
616 if (try_as_currdev(dp, pp))
623 * Try the device handle from our loaded image first. If that
624 * fails, use the device path from the loaded image and see if
625 * any of the nodes in that path match one of the enumerated
626 * handles. Currently, this handle list is only for netboot.
628 if (efi_handle_lookup(boot_img->DeviceHandle, &dev, &unit, &extra) == 0) {
629 set_currdev_devsw(dev, unit);
630 if (sanity_check_currdev())
635 devpath = efi_lookup_image_devpath(IH);
636 while (devpath != NULL) {
637 h = efi_devpath_handle(devpath);
644 if (efi_handle_lookup(h, &dev, &unit, &extra) == 0) {
645 set_currdev_devsw(dev, unit);
646 if (sanity_check_currdev())
650 devpath = efi_lookup_devpath(h);
651 if (devpath != NULL) {
652 copy = efi_devpath_trim(devpath);
662 interactive_interrupt(const char *msg)
664 time_t now, then, last;
667 now = then = getsecs();
669 if (fail_timeout == -2) /* Always break to OK */
671 if (fail_timeout == -1) /* Never break to OK */
675 printf("press any key to interrupt reboot in %d seconds\r",
676 fail_timeout - (int)(now - then));
680 /* XXX no pause or timeout wait for char */
684 } while (now - then < fail_timeout);
689 parse_args(int argc, CHAR16 *argv[])
695 * Parse the args to set the console settings, etc
696 * boot1.efi passes these in, if it can read /boot.config or /boot/config
697 * or iPXE may be setup to pass these in. Or the optional argument in the
698 * boot environment was used to pass these arguments in (in which case
699 * neither /boot.config nor /boot/config are consulted).
701 * Loop through the args, and for each one that contains an '=' that is
702 * not the first character, add it to the environment. This allows
703 * loader and kernel env vars to be passed on the command line. Convert
704 * args from UCS-2 to ASCII (16 to 8 bit) as they are copied (though this
705 * method is flawed for non-ASCII characters).
708 for (i = 0; i < argc; i++) {
709 cpy16to8(argv[i], var, sizeof(var));
710 howto |= boot_parse_arg(var);
717 setenv_int(const char *key, int val)
721 snprintf(buf, sizeof(buf), "%d", val);
726 * Parse ConOut (the list of consoles active) and see if we can find a
727 * serial port and/or a video port. It would be nice to also walk the
728 * ACPI name space to map the UID for the serial port to a port. The
729 * latter is especially hard.
732 parse_uefi_con_out(void)
735 int vid_seen = 0, com_seen = 0, seen = 0;
738 EFI_DEVICE_PATH *node;
739 ACPI_HID_DEVICE_PATH *acpi;
740 UART_DEVICE_PATH *uart;
745 rv = efi_global_getenv("ConOut", buf, &sz);
746 if (rv != EFI_SUCCESS)
747 rv = efi_global_getenv("ConOutDev", buf, &sz);
748 if (rv != EFI_SUCCESS) {
750 * If we don't have any ConOut default to both. If we have GOP
751 * make video primary, otherwise just make serial primary. In
752 * either case, try to use both the 'efi' console which will use
753 * the GOP, if present and serial. If there's an EFI BIOS that
754 * omits this, but has a serial port redirect, we'll
755 * unavioidably get doubled characters (but we'll be right in
756 * all the other more common cases).
761 how = RB_MULTIPLE | RB_SERIAL;
762 setenv("console", "efi,comconsole", 1);
766 node = (EFI_DEVICE_PATH *)buf;
767 while ((char *)node < ep) {
768 if (IsDevicePathEndType(node)) {
769 if (pci_pending && vid_seen == 0)
773 if (DevicePathType(node) == ACPI_DEVICE_PATH &&
774 (DevicePathSubType(node) == ACPI_DP ||
775 DevicePathSubType(node) == ACPI_EXTENDED_DP)) {
776 /* Check for Serial node */
778 if (EISA_ID_TO_NUM(acpi->HID) == 0x501) {
779 setenv_int("efi_8250_uid", acpi->UID);
782 } else if (DevicePathType(node) == MESSAGING_DEVICE_PATH &&
783 DevicePathSubType(node) == MSG_UART_DP) {
786 setenv_int("efi_com_speed", uart->BaudRate);
787 } else if (DevicePathType(node) == ACPI_DEVICE_PATH &&
788 DevicePathSubType(node) == ACPI_ADR_DP) {
789 /* Check for AcpiAdr() Node for video */
791 } else if (DevicePathType(node) == HARDWARE_DEVICE_PATH &&
792 DevicePathSubType(node) == HW_PCI_DP) {
794 * Note, vmware fusion has a funky console device
795 * PciRoot(0x0)/Pci(0xf,0x0)
796 * which we can only detect at the end since we also
798 * PciRoot(0x0)/Pci(0x1f,0x0)/Serial(0x1)
799 * so only match it if it's last.
803 node = NextDevicePathNode(node);
807 * Truth table for RB_MULTIPLE | RB_SERIAL
809 * 0 Use only video console
810 * RB_SERIAL Use only serial console
811 * RB_MULTIPLE Use both video and serial console
812 * (but video is primary so gets rc messages)
813 * both Use both video and serial console
814 * (but serial is primary so gets rc messages)
816 * Try to honor this as best we can. If only one of serial / video
817 * found, then use that. Otherwise, use the first one we found.
818 * This also implies if we found nothing, default to video.
821 if (vid_seen && com_seen) {
823 if (com_seen < vid_seen)
832 parse_loader_efi_config(EFI_HANDLE h, const char *env_fn)
839 dp = efiblk_get_pdinfo_by_handle(h);
842 set_currdev_pdinfo(dp);
843 if (stat(env_fn, &st) != 0)
845 fd = open(env_fn, O_RDONLY);
848 env = malloc(st.st_size + 1);
851 if (read(fd, env, st.st_size) != st.st_size)
853 env[st.st_size] = '\0';
854 boot_parse_cmdline(env);
861 read_loader_env(const char *name, char *def_fn, bool once)
864 char *fn, *freeme = NULL;
868 if (efi_freebsd_getenv(name, NULL, &len) == EFI_BUFFER_TOO_SMALL) {
869 freeme = fn = malloc(len + 1);
871 if (efi_freebsd_getenv(name, fn, &len) != EFI_SUCCESS) {
875 "Can't fetch FreeBSD::%s we know is there\n", name);
878 * if tagged as 'once' delete the env variable so we
882 efi_freebsd_delenv(name);
884 * We malloced 1 more than len above, then redid the call.
885 * so now we have room at the end of the string to NUL terminate
886 * it here, even if the typical idium would have '- 1' here to
887 * not overflow. len should be the same on return both times.
893 "Can't allocate %d bytes to fetch FreeBSD::%s env var\n",
898 printf(" Reading loader env vars from %s\n", fn);
899 parse_loader_efi_config(boot_img->DeviceHandle, fn);
910 main(int argc, CHAR16 *argv[])
913 int howto, i, uhowto;
915 bool has_kbd, is_last;
917 EFI_DEVICE_PATH *imgpath;
920 size_t sz, bosz = 0, bisz = 0;
921 UINT16 boot_order[100];
922 char boot_info[4096];
926 archsw.arch_autoload = efi_autoload;
927 archsw.arch_getdev = efi_getdev;
928 archsw.arch_copyin = efi_copyin;
929 archsw.arch_copyout = efi_copyout;
931 archsw.arch_hypervisor = x86_hypervisor;
933 archsw.arch_readin = efi_readin;
934 archsw.arch_zfs_probe = efi_zfs_probe;
936 /* Get our loaded image protocol interface structure. */
937 (void) OpenProtocolByHandle(IH, &imgid, (void **)&boot_img);
940 * Chicken-and-egg problem; we want to have console output early, but
941 * some console attributes may depend on reading from eg. the boot
942 * device, which we can't do yet. We can use printf() etc. once this is
943 * done. So, we set it to the efi console, then call console init. This
944 * gets us printf early, but also primes the pump for all future console
945 * changes to take effect, regardless of where they come from.
947 setenv("console", "efi", 1);
948 uhowto = parse_uefi_con_out();
951 * This workaround likely is papering over a real issue
953 if ((uhowto & RB_SERIAL) != 0)
954 setenv("console", "comconsole", 1);
958 /* Set up currdev variable to have hooks in place. */
959 env_setenv("currdev", EV_VOLATILE, "", gen_setcurrdev, env_nounset);
961 /* Init the time source */
965 * Initialise the block cache. Set the upper limit.
967 bcache_init(32768, 512);
970 * Scan the BLOCK IO MEDIA handles then
971 * march through the device switch probing for things.
973 i = efipart_inithandles();
974 if (i != 0 && i != ENOENT) {
975 printf("efipart_inithandles failed with ERRNO %d, expect "
982 * Detect console settings two different ways: one via the command
983 * args (eg -h) or via the UEFI ConOut variable.
985 has_kbd = has_keyboard();
986 howto = parse_args(argc, argv);
987 if (!has_kbd && (howto & RB_PROBE))
988 howto |= RB_SERIAL | RB_MULTIPLE;
992 * Read additional environment variables from the boot device's
993 * "LoaderEnv" file. Any boot loader environment variable may be set
994 * there, which are subtly different than loader.conf variables. Only
995 * the 'simple' ones may be set so things like foo_load="YES" won't work
996 * for two reasons. First, the parser is simplistic and doesn't grok
997 * quotes. Second, because the variables that cause an action to happen
998 * are parsed by the lua, 4th or whatever code that's not yet
999 * loaded. This is relative to the root directory when loader.efi is
1000 * loaded off the UFS root drive (when chain booted), or from the ESP
1001 * when directly loaded by the BIOS.
1003 * We also read in NextLoaderEnv if it was specified. This allows next boot
1004 * functionality to be implemented and to override anything in LoaderEnv.
1006 read_loader_env("LoaderEnv", "/efi/freebsd/loader.env", false);
1007 read_loader_env("NextLoaderEnv", NULL, true);
1010 * We now have two notions of console. howto should be viewed as
1011 * overrides. If console is already set, don't set it again.
1013 #define VIDEO_ONLY 0
1014 #define SERIAL_ONLY RB_SERIAL
1015 #define VID_SER_BOTH RB_MULTIPLE
1016 #define SER_VID_BOTH (RB_SERIAL | RB_MULTIPLE)
1017 #define CON_MASK (RB_SERIAL | RB_MULTIPLE)
1018 if (strcmp(getenv("console"), "efi") == 0) {
1019 if ((howto & CON_MASK) == 0) {
1020 /* No override, uhowto is controlling and efi cons is perfect */
1021 howto = howto | (uhowto & CON_MASK);
1022 } else if ((howto & CON_MASK) == (uhowto & CON_MASK)) {
1023 /* override matches what UEFI told us, efi console is perfect */
1024 } else if ((uhowto & (CON_MASK)) != 0) {
1026 * We detected a serial console on ConOut. All possible
1027 * overrides include serial. We can't really override what efi
1028 * gives us, so we use it knowing it's the best choice.
1033 * We detected some kind of serial in the override, but ConOut
1034 * has no serial, so we have to sort out which case it really is.
1036 switch (howto & CON_MASK) {
1038 setenv("console", "comconsole", 1);
1041 setenv("console", "efi comconsole", 1);
1044 setenv("console", "comconsole efi", 1);
1046 /* case VIDEO_ONLY can't happen -- it's the first if above */
1052 * howto is set now how we want to export the flags to the kernel, so
1053 * set the env based on it.
1055 boot_howto_to_env(howto);
1057 if (efi_copy_init()) {
1058 printf("failed to allocate staging area\n");
1059 return (EFI_BUFFER_TOO_SMALL);
1062 if ((s = getenv("fail_timeout")) != NULL)
1063 fail_timeout = strtol(s, NULL, 10);
1065 printf("%s\n", bootprog_info);
1066 printf(" Command line arguments:");
1067 for (i = 0; i < argc; i++)
1068 printf(" %S", argv[i]);
1071 printf(" Image base: 0x%lx\n", (unsigned long)boot_img->ImageBase);
1072 printf(" EFI version: %d.%02d\n", ST->Hdr.Revision >> 16,
1073 ST->Hdr.Revision & 0xffff);
1074 printf(" EFI Firmware: %S (rev %d.%02d)\n", ST->FirmwareVendor,
1075 ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff);
1076 printf(" Console: %s (%#x)\n", getenv("console"), howto);
1078 /* Determine the devpath of our image so we can prefer it. */
1079 text = efi_devpath_name(boot_img->FilePath);
1081 printf(" Load Path: %S\n", text);
1082 efi_setenv_freebsd_wcs("LoaderPath", text);
1083 efi_free_devpath_name(text);
1086 rv = OpenProtocolByHandle(boot_img->DeviceHandle, &devid,
1088 if (rv == EFI_SUCCESS) {
1089 text = efi_devpath_name(imgpath);
1091 printf(" Load Device: %S\n", text);
1092 efi_setenv_freebsd_wcs("LoaderDev", text);
1093 efi_free_devpath_name(text);
1097 if (getenv("uefi_ignore_boot_mgr") != NULL) {
1098 printf(" Ignoring UEFI boot manager\n");
1099 uefi_boot_mgr = false;
1101 uefi_boot_mgr = true;
1103 sz = sizeof(boot_current);
1104 rv = efi_global_getenv("BootCurrent", &boot_current, &sz);
1105 if (rv == EFI_SUCCESS)
1106 printf(" BootCurrent: %04x\n", boot_current);
1108 boot_current = 0xffff;
1109 uefi_boot_mgr = false;
1112 sz = sizeof(boot_order);
1113 rv = efi_global_getenv("BootOrder", &boot_order, &sz);
1114 if (rv == EFI_SUCCESS) {
1115 printf(" BootOrder:");
1116 for (i = 0; i < sz / sizeof(boot_order[0]); i++)
1117 printf(" %04x%s", boot_order[i],
1118 boot_order[i] == boot_current ? "[*]" : "");
1120 is_last = boot_order[(sz / sizeof(boot_order[0])) - 1] == boot_current;
1122 } else if (uefi_boot_mgr) {
1124 * u-boot doesn't set BootOrder, but otherwise participates in the
1125 * boot manager protocol. So we fake it here and don't consider it
1128 bosz = sizeof(boot_order[0]);
1129 boot_order[0] = boot_current;
1135 * Next, find the boot info structure the UEFI boot manager is
1136 * supposed to setup. We need this so we can walk through it to
1137 * find where we are in the booting process and what to try to
1140 if (uefi_boot_mgr) {
1141 snprintf(buf, sizeof(buf), "Boot%04X", boot_current);
1142 sz = sizeof(boot_info);
1143 rv = efi_global_getenv(buf, &boot_info, &sz);
1144 if (rv == EFI_SUCCESS)
1147 uefi_boot_mgr = false;
1151 * Disable the watchdog timer. By default the boot manager sets
1152 * the timer to 5 minutes before invoking a boot option. If we
1153 * want to return to the boot manager, we have to disable the
1154 * watchdog timer and since we're an interactive program, we don't
1155 * want to wait until the user types "quit". The timer may have
1156 * fired by then. We don't care if this fails. It does not prevent
1157 * normal functioning in any way...
1159 BS->SetWatchdogTimer(0, 0, 0, NULL);
1162 * Initialize the trusted/forbidden certificates from UEFI.
1163 * They will be later used to verify the manifest(s),
1164 * which should contain hashes of verified files.
1165 * This needs to be initialized before any configuration files
1168 #ifdef EFI_SECUREBOOT
1173 * Try and find a good currdev based on the image that was booted.
1174 * It might be desirable here to have a short pause to allow falling
1175 * through to the boot loader instead of returning instantly to follow
1176 * the boot protocol and also allow an escape hatch for users wishing
1177 * to try something different.
1179 if (find_currdev(uefi_boot_mgr, is_last, boot_info, bisz) != 0)
1180 if (uefi_boot_mgr &&
1181 !interactive_interrupt("Failed to find bootable partition"))
1182 return (EFI_NOT_FOUND);
1184 autoload_font(false); /* Set up the font list for console. */
1185 efi_init_environment();
1187 #if !defined(__arm__)
1188 for (k = 0; k < ST->NumberOfTableEntries; k++) {
1189 guid = &ST->ConfigurationTable[k].VendorGuid;
1190 if (!memcmp(guid, &smbios, sizeof(EFI_GUID)) ||
1191 !memcmp(guid, &smbios3, sizeof(EFI_GUID))) {
1194 snprintf(buf, sizeof(buf), "%p",
1195 ST->ConfigurationTable[k].VendorTable);
1196 setenv("hint.smbios.0.mem", buf, 1);
1197 smbios_detect(ST->ConfigurationTable[k].VendorTable);
1203 interact(); /* doesn't return */
1205 return (EFI_SUCCESS); /* keep compiler happy */
1208 COMMAND_SET(efi_seed_entropy, "efi-seed-entropy", "try to get entropy from the EFI RNG", command_seed_entropy);
1211 command_seed_entropy(int argc, char *argv[])
1214 EFI_RNG_PROTOCOL *rng;
1215 unsigned int size = 2048;
1219 size = strtol(argv[1], NULL, 0);
1222 status = BS->LocateProtocol(&rng_guid, NULL, (VOID **)&rng);
1223 if (status != EFI_SUCCESS) {
1224 command_errmsg = "RNG protocol not found";
1228 if ((buf = malloc(size)) == NULL) {
1229 command_errmsg = "out of memory";
1233 status = rng->GetRNG(rng, NULL, size, (UINT8 *)buf);
1234 if (status != EFI_SUCCESS) {
1236 command_errmsg = "GetRNG failed";
1240 if (file_addbuf("efi_rng_seed", "boot_entropy_platform", size, buf) != 0) {
1249 COMMAND_SET(poweroff, "poweroff", "power off the system", command_poweroff);
1252 command_poweroff(int argc __unused, char *argv[] __unused)
1256 for (i = 0; devsw[i] != NULL; ++i)
1257 if (devsw[i]->dv_cleanup != NULL)
1258 (devsw[i]->dv_cleanup)();
1260 RS->ResetSystem(EfiResetShutdown, EFI_SUCCESS, 0, NULL);
1266 COMMAND_SET(reboot, "reboot", "reboot the system", command_reboot);
1269 command_reboot(int argc, char *argv[])
1273 for (i = 0; devsw[i] != NULL; ++i)
1274 if (devsw[i]->dv_cleanup != NULL)
1275 (devsw[i]->dv_cleanup)();
1277 RS->ResetSystem(EfiResetCold, EFI_SUCCESS, 0, NULL);
1283 COMMAND_SET(memmap, "memmap", "print memory map", command_memmap);
1286 command_memmap(int argc __unused, char *argv[] __unused)
1289 EFI_MEMORY_DESCRIPTOR *map, *p;
1297 status = BS->GetMemoryMap(&sz, 0, &key, &dsz, &dver);
1298 if (status != EFI_BUFFER_TOO_SMALL) {
1299 printf("Can't determine memory map size\n");
1303 status = BS->GetMemoryMap(&sz, map, &key, &dsz, &dver);
1304 if (EFI_ERROR(status)) {
1305 printf("Can't read memory map\n");
1310 snprintf(line, sizeof(line), "%23s %12s %12s %8s %4s\n",
1311 "Type", "Physical", "Virtual", "#Pages", "Attr");
1313 if (pager_output(line)) {
1318 for (i = 0, p = map; i < ndesc;
1319 i++, p = NextMemoryDescriptor(p, dsz)) {
1320 snprintf(line, sizeof(line), "%23s %012jx %012jx %08jx ",
1321 efi_memory_type(p->Type), (uintmax_t)p->PhysicalStart,
1322 (uintmax_t)p->VirtualStart, (uintmax_t)p->NumberOfPages);
1323 if (pager_output(line))
1326 if (p->Attribute & EFI_MEMORY_UC)
1328 if (p->Attribute & EFI_MEMORY_WC)
1330 if (p->Attribute & EFI_MEMORY_WT)
1332 if (p->Attribute & EFI_MEMORY_WB)
1334 if (p->Attribute & EFI_MEMORY_UCE)
1336 if (p->Attribute & EFI_MEMORY_WP)
1338 if (p->Attribute & EFI_MEMORY_RP)
1340 if (p->Attribute & EFI_MEMORY_XP)
1342 if (p->Attribute & EFI_MEMORY_NV)
1344 if (p->Attribute & EFI_MEMORY_MORE_RELIABLE)
1346 if (p->Attribute & EFI_MEMORY_RO)
1348 if (pager_output("\n"))
1356 COMMAND_SET(configuration, "configuration", "print configuration tables",
1357 command_configuration);
1360 command_configuration(int argc, char *argv[])
1365 printf("NumberOfTableEntries=%lu\n",
1366 (unsigned long)ST->NumberOfTableEntries);
1368 for (i = 0; i < ST->NumberOfTableEntries; i++) {
1372 guid = &ST->ConfigurationTable[i].VendorGuid;
1374 if (efi_guid_to_name(guid, &name) == true) {
1378 printf("Error while translating UUID to name");
1380 printf(" at %p\n", ST->ConfigurationTable[i].VendorTable);
1387 COMMAND_SET(mode, "mode", "change or display EFI text modes", command_mode);
1390 command_mode(int argc, char *argv[])
1397 SIMPLE_TEXT_OUTPUT_INTERFACE *conout;
1399 conout = ST->ConOut;
1402 mode = strtol(argv[1], &cp, 0);
1403 if (cp[0] != '\0') {
1404 printf("Invalid mode\n");
1407 status = conout->QueryMode(conout, mode, &cols, &rows);
1408 if (EFI_ERROR(status)) {
1409 printf("invalid mode %d\n", mode);
1412 status = conout->SetMode(conout, mode);
1413 if (EFI_ERROR(status)) {
1414 printf("couldn't set mode %d\n", mode);
1417 (void) cons_update_mode(true);
1421 printf("Current mode: %d\n", conout->Mode->Mode);
1422 for (i = 0; i <= conout->Mode->MaxMode; i++) {
1423 status = conout->QueryMode(conout, i, &cols, &rows);
1424 if (EFI_ERROR(status))
1426 printf("Mode %d: %u columns, %u rows\n", i, (unsigned)cols,
1431 printf("Select a mode with the command \"mode <number>\"\n");
1436 COMMAND_SET(lsefi, "lsefi", "list EFI handles", command_lsefi);
1439 lsefi_print_handle_info(EFI_HANDLE handle)
1441 EFI_DEVICE_PATH *devpath;
1442 EFI_DEVICE_PATH *imagepath;
1445 imagepath = efi_lookup_image_devpath(handle);
1446 if (imagepath != NULL) {
1447 dp_name = efi_devpath_name(imagepath);
1448 printf("Handle for image %S", dp_name);
1449 efi_free_devpath_name(dp_name);
1452 devpath = efi_lookup_devpath(handle);
1453 if (devpath != NULL) {
1454 dp_name = efi_devpath_name(devpath);
1455 printf("Handle for device %S", dp_name);
1456 efi_free_devpath_name(dp_name);
1459 printf("Handle %p", handle);
1463 command_lsefi(int argc __unused, char *argv[] __unused)
1466 EFI_HANDLE *buffer = NULL;
1468 UINTN bufsz = 0, i, j;
1472 status = BS->LocateHandle(AllHandles, NULL, NULL, &bufsz, buffer);
1473 if (status != EFI_BUFFER_TOO_SMALL) {
1474 snprintf(command_errbuf, sizeof (command_errbuf),
1475 "unexpected error: %lld", (long long)status);
1478 if ((buffer = malloc(bufsz)) == NULL) {
1479 sprintf(command_errbuf, "out of memory");
1483 status = BS->LocateHandle(AllHandles, NULL, NULL, &bufsz, buffer);
1484 if (EFI_ERROR(status)) {
1486 snprintf(command_errbuf, sizeof (command_errbuf),
1487 "LocateHandle() error: %lld", (long long)status);
1492 for (i = 0; i < (bufsz / sizeof (EFI_HANDLE)); i++) {
1494 EFI_GUID **protocols = NULL;
1497 lsefi_print_handle_info(handle);
1498 if (pager_output("\n"))
1502 status = BS->ProtocolsPerHandle(handle, &protocols, &nproto);
1503 if (EFI_ERROR(status)) {
1504 snprintf(command_errbuf, sizeof (command_errbuf),
1505 "ProtocolsPerHandle() error: %lld",
1510 for (j = 0; j < nproto; j++) {
1511 if (efi_guid_to_name(protocols[j], &name) == true) {
1512 printf(" %s", name);
1515 printf("Error while translating UUID to name");
1517 if ((ret = pager_output("\n")) != 0)
1520 BS->FreePool(protocols);
1529 #ifdef LOADER_FDT_SUPPORT
1530 extern int command_fdt_internal(int argc, char *argv[]);
1533 * Since proper fdt command handling function is defined in fdt_loader_cmd.c,
1534 * and declaring it as extern is in contradiction with COMMAND_SET() macro
1535 * (which uses static pointer), we're defining wrapper function, which
1536 * calls the proper fdt handling routine.
1539 command_fdt(int argc, char *argv[])
1542 return (command_fdt_internal(argc, argv));
1545 COMMAND_SET(fdt, "fdt", "flattened device tree handling", command_fdt);
1549 * Chain load another efi loader.
1552 command_chain(int argc, char *argv[])
1554 EFI_GUID LoadedImageGUID = LOADED_IMAGE_PROTOCOL;
1555 EFI_HANDLE loaderhandle;
1556 EFI_LOADED_IMAGE *loaded_image;
1559 struct devdesc *dev;
1565 command_errmsg = "wrong number of arguments";
1571 if ((fd = open(name, O_RDONLY)) < 0) {
1572 command_errmsg = "no such file";
1576 #ifdef LOADER_VERIEXEC
1577 if (verify_file(fd, name, 0, VE_MUST, __func__) < 0) {
1578 sprintf(command_errbuf, "can't verify: %s", name);
1584 if (fstat(fd, &st) < -1) {
1585 command_errmsg = "stat failed";
1590 status = BS->AllocatePool(EfiLoaderCode, (UINTN)st.st_size, &buf);
1591 if (status != EFI_SUCCESS) {
1592 command_errmsg = "failed to allocate buffer";
1596 if (read(fd, buf, st.st_size) != st.st_size) {
1597 command_errmsg = "error while reading the file";
1598 (void)BS->FreePool(buf);
1603 status = BS->LoadImage(FALSE, IH, NULL, buf, st.st_size, &loaderhandle);
1604 (void)BS->FreePool(buf);
1605 if (status != EFI_SUCCESS) {
1606 command_errmsg = "LoadImage failed";
1609 status = OpenProtocolByHandle(loaderhandle, &LoadedImageGUID,
1610 (void **)&loaded_image);
1616 for (i = 2; i < argc; i++)
1617 len += strlen(argv[i]) + 1;
1619 len *= sizeof (*argp);
1620 loaded_image->LoadOptions = argp = malloc (len);
1621 loaded_image->LoadOptionsSize = len;
1622 for (i = 2; i < argc; i++) {
1623 char *ptr = argv[i];
1625 *(argp++) = *(ptr++);
1631 if (efi_getdev((void **)&dev, name, (const char **)&path) == 0) {
1633 struct zfs_devdesc *z_dev;
1635 struct disk_devdesc *d_dev;
1638 switch (dev->d_dev->dv_type) {
1641 z_dev = (struct zfs_devdesc *)dev;
1642 loaded_image->DeviceHandle =
1643 efizfs_get_handle_by_guid(z_dev->pool_guid);
1647 loaded_image->DeviceHandle =
1648 efi_find_handle(dev->d_dev, dev->d_unit);
1651 hd = efiblk_get_pdinfo(dev);
1652 if (STAILQ_EMPTY(&hd->pd_part)) {
1653 loaded_image->DeviceHandle = hd->pd_handle;
1656 d_dev = (struct disk_devdesc *)dev;
1657 STAILQ_FOREACH(pd, &hd->pd_part, pd_link) {
1659 * d_partition should be 255
1661 if (pd->pd_unit == (uint32_t)d_dev->d_slice) {
1662 loaded_image->DeviceHandle =
1672 status = BS->StartImage(loaderhandle, NULL, NULL);
1673 if (status != EFI_SUCCESS) {
1674 command_errmsg = "StartImage failed";
1675 free(loaded_image->LoadOptions);
1676 loaded_image->LoadOptions = NULL;
1677 status = BS->UnloadImage(loaded_image);
1681 return (CMD_ERROR); /* not reached */
1684 COMMAND_SET(chain, "chain", "chain load file", command_chain);
1686 extern struct in_addr servip;
1688 command_netserver(int argc, char *argv[])
1694 command_errmsg = "wrong number of arguments";
1698 proto = netproto == NET_TFTP ? "tftp://" : "nfs://";
1699 printf("Netserver URI: %s%s%s\n", proto, intoa(rootip.s_addr),
1704 strncpy(rootpath, argv[1], sizeof(rootpath));
1705 rootpath[sizeof(rootpath) -1] = '\0';
1706 if ((rootaddr = net_parse_rootpath()) != INADDR_NONE)
1707 servip.s_addr = rootip.s_addr = rootaddr;
1710 return (CMD_ERROR); /* not reached */
1714 COMMAND_SET(netserver, "netserver", "change or display netserver URI",