1/*- 2 * Copyright (c) 2008-2010 Rui Paulo 3 * Copyright (c) 2006 Marcel Moolenaar 4 * All rights reserved. 5 * 6 * Copyright (c) 2016-2019 Netflix, Inc. written by M. Warner Losh 7 * 8 * Redistribution and use in source and binary forms, with or without 9 * modification, are permitted provided that the following conditions 10 * are met: 11 * 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. 17 * 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. 28 */ 29 30#include <sys/cdefs.h> 31__FBSDID("$FreeBSD$"); 32 33#include <stand.h> 34 35#include <sys/disk.h> 36#include <sys/param.h> 37#include <sys/reboot.h> 38#include <sys/boot.h> 39#include <paths.h> 40#include <netinet/in.h> 41#include <netinet/in_systm.h> 42#include <stdint.h> 43#include <string.h> 44#include <setjmp.h> 45#include <disk.h> 46#include <dev_net.h> 47#include <net.h> 48 49#include <efi.h> 50#include <efilib.h> 51#include <efichar.h> 52 53#include <uuid.h> 54 55#include <bootstrap.h> 56#include <smbios.h> 57 58#include "efizfs.h" 59 60#include "loader_efi.h" 61 62struct arch_switch archsw; /* MI/MD interface boundary */ 63 64EFI_GUID acpi = ACPI_TABLE_GUID; 65EFI_GUID acpi20 = ACPI_20_TABLE_GUID; 66EFI_GUID devid = DEVICE_PATH_PROTOCOL; 67EFI_GUID imgid = LOADED_IMAGE_PROTOCOL; 68EFI_GUID mps = MPS_TABLE_GUID; 69EFI_GUID netid = EFI_SIMPLE_NETWORK_PROTOCOL; 70EFI_GUID smbios = SMBIOS_TABLE_GUID; 71EFI_GUID smbios3 = SMBIOS3_TABLE_GUID; 72EFI_GUID dxe = DXE_SERVICES_TABLE_GUID; 73EFI_GUID hoblist = HOB_LIST_TABLE_GUID; 74EFI_GUID lzmadecomp = LZMA_DECOMPRESSION_GUID; 75EFI_GUID mpcore = ARM_MP_CORE_INFO_TABLE_GUID; 76EFI_GUID esrt = ESRT_TABLE_GUID; 77EFI_GUID memtype = MEMORY_TYPE_INFORMATION_TABLE_GUID; 78EFI_GUID debugimg = DEBUG_IMAGE_INFO_TABLE_GUID; 79EFI_GUID fdtdtb = FDT_TABLE_GUID; 80EFI_GUID inputid = SIMPLE_TEXT_INPUT_PROTOCOL; 81 82/* 83 * Number of seconds to wait for a keystroke before exiting with failure 84 * in the event no currdev is found. -2 means always break, -1 means 85 * never break, 0 means poll once and then reboot, > 0 means wait for 86 * that many seconds. "fail_timeout" can be set in the environment as 87 * well. 88 */ 89static int fail_timeout = 5; 90 91/* 92 * Current boot variable 93 */ 94UINT16 boot_current; 95 96/* 97 * Image that we booted from. 98 */ 99EFI_LOADED_IMAGE *boot_img; 100 101static bool 102has_keyboard(void) 103{ 104 EFI_STATUS status; 105 EFI_DEVICE_PATH *path; 106 EFI_HANDLE *hin, *hin_end, *walker; 107 UINTN sz; 108 bool retval = false; 109 110 /* 111 * Find all the handles that support the SIMPLE_TEXT_INPUT_PROTOCOL and 112 * do the typical dance to get the right sized buffer. 113 */ 114 sz = 0; 115 hin = NULL; 116 status = BS->LocateHandle(ByProtocol, &inputid, 0, &sz, 0); 117 if (status == EFI_BUFFER_TOO_SMALL) { 118 hin = (EFI_HANDLE *)malloc(sz); 119 status = BS->LocateHandle(ByProtocol, &inputid, 0, &sz, 120 hin); 121 if (EFI_ERROR(status)) 122 free(hin); 123 } 124 if (EFI_ERROR(status)) 125 return retval; 126 127 /* 128 * Look at each of the handles. If it supports the device path protocol, 129 * use it to get the device path for this handle. Then see if that 130 * device path matches either the USB device path for keyboards or the 131 * legacy device path for keyboards. 132 */ 133 hin_end = &hin[sz / sizeof(*hin)]; 134 for (walker = hin; walker < hin_end; walker++) { 135 status = OpenProtocolByHandle(*walker, &devid, (void **)&path); 136 if (EFI_ERROR(status)) 137 continue; 138 139 while (!IsDevicePathEnd(path)) { 140 /* 141 * Check for the ACPI keyboard node. All PNP3xx nodes 142 * are keyboards of different flavors. Note: It is 143 * unclear of there's always a keyboard node when 144 * there's a keyboard controller, or if there's only one 145 * when a keyboard is detected at boot. 146 */ 147 if (DevicePathType(path) == ACPI_DEVICE_PATH && 148 (DevicePathSubType(path) == ACPI_DP || 149 DevicePathSubType(path) == ACPI_EXTENDED_DP)) { 150 ACPI_HID_DEVICE_PATH *acpi; 151 152 acpi = (ACPI_HID_DEVICE_PATH *)(void *)path; 153 if ((EISA_ID_TO_NUM(acpi->HID) & 0xff00) == 0x300 && 154 (acpi->HID & 0xffff) == PNP_EISA_ID_CONST) { 155 retval = true; 156 goto out; 157 } 158 /* 159 * Check for USB keyboard node, if present. Unlike a 160 * PS/2 keyboard, these definitely only appear when 161 * connected to the system. 162 */ 163 } else if (DevicePathType(path) == MESSAGING_DEVICE_PATH && 164 DevicePathSubType(path) == MSG_USB_CLASS_DP) { 165 USB_CLASS_DEVICE_PATH *usb; 166 167 usb = (USB_CLASS_DEVICE_PATH *)(void *)path; 168 if (usb->DeviceClass == 3 && /* HID */ 169 usb->DeviceSubClass == 1 && /* Boot devices */ 170 usb->DeviceProtocol == 1) { /* Boot keyboards */ 171 retval = true; 172 goto out; 173 } 174 } 175 path = NextDevicePathNode(path); 176 } 177 } 178out: 179 free(hin); 180 return retval; 181} 182 183static void 184set_currdev(const char *devname) 185{ 186 187 /* 188 * Don't execute hooks here; we may need to try setting these more than 189 * once here if we're probing for the ZFS pool we're supposed to boot. 190 * The currdev hook is intended to just validate user input anyways, 191 * while the loaddev hook makes it immutable once we've determined what 192 * the proper currdev is. 193 */ 194 env_setenv("currdev", EV_VOLATILE | EV_NOHOOK, devname, efi_setcurrdev, 195 env_nounset); 196 env_setenv("loaddev", EV_VOLATILE | EV_NOHOOK, devname, env_noset, 197 env_nounset); 198} 199 200static void 201set_currdev_devdesc(struct devdesc *currdev) 202{ 203 const char *devname; 204 205 devname = efi_fmtdev(currdev); 206 printf("Setting currdev to %s\n", devname); 207 set_currdev(devname); 208} 209 210static void 211set_currdev_devsw(struct devsw *dev, int unit) 212{ 213 struct devdesc currdev; 214 215 currdev.d_dev = dev; 216 currdev.d_unit = unit; 217 218 set_currdev_devdesc(&currdev); 219} 220 221static void 222set_currdev_pdinfo(pdinfo_t *dp) 223{ 224 225 /* 226 * Disks are special: they have partitions. if the parent 227 * pointer is non-null, we're a partition not a full disk 228 * and we need to adjust currdev appropriately. 229 */ 230 if (dp->pd_devsw->dv_type == DEVT_DISK) { 231 struct disk_devdesc currdev; 232 233 currdev.dd.d_dev = dp->pd_devsw; 234 if (dp->pd_parent == NULL) { 235 currdev.dd.d_unit = dp->pd_unit; 236 currdev.d_slice = D_SLICENONE; 237 currdev.d_partition = D_PARTNONE; 238 } else { 239 currdev.dd.d_unit = dp->pd_parent->pd_unit; 240 currdev.d_slice = dp->pd_unit; 241 currdev.d_partition = D_PARTISGPT; /* XXX Assumes GPT */ 242 } 243 set_currdev_devdesc((struct devdesc *)&currdev); 244 } else { 245 set_currdev_devsw(dp->pd_devsw, dp->pd_unit); 246 } 247} 248 249static bool 250sanity_check_currdev(void) 251{ 252 struct stat st; 253 254 return (stat(PATH_DEFAULTS_LOADER_CONF, &st) == 0 || 255#ifdef PATH_BOOTABLE_TOKEN 256 stat(PATH_BOOTABLE_TOKEN, &st) == 0 || /* non-standard layout */ 257#endif 258 stat(PATH_KERNEL, &st) == 0); 259} 260 261#ifdef EFI_ZFS_BOOT 262static bool 263probe_zfs_currdev(uint64_t guid) 264{ 265 char *devname; 266 struct zfs_devdesc currdev; 267 268 currdev.dd.d_dev = &zfs_dev; 269 currdev.dd.d_unit = 0; 270 currdev.pool_guid = guid; 271 currdev.root_guid = 0; 272 set_currdev_devdesc((struct devdesc *)&currdev); 273 devname = efi_fmtdev(&currdev); 274 init_zfs_bootenv(devname); 275 276 return (sanity_check_currdev()); 277} 278#endif 279 280static bool 281try_as_currdev(pdinfo_t *hd, pdinfo_t *pp) 282{ 283 uint64_t guid; 284 285#ifdef EFI_ZFS_BOOT 286 /* 287 * If there's a zpool on this device, try it as a ZFS 288 * filesystem, which has somewhat different setup than all 289 * other types of fs due to imperfect loader integration. 290 * This all stems from ZFS being both a device (zpool) and 291 * a filesystem, plus the boot env feature. 292 */ 293 if (efizfs_get_guid_by_handle(pp->pd_handle, &guid)) 294 return (probe_zfs_currdev(guid)); 295#endif 296 /* 297 * All other filesystems just need the pdinfo 298 * initialized in the standard way. 299 */ 300 set_currdev_pdinfo(pp); 301 return (sanity_check_currdev()); 302} 303 304/* 305 * Sometimes we get filenames that are all upper case 306 * and/or have backslashes in them. Filter all this out 307 * if it looks like we need to do so. 308 */ 309static void 310fix_dosisms(char *p) 311{ 312 while (*p) { 313 if (isupper(*p)) 314 *p = tolower(*p); 315 else if (*p == '\\') 316 *p = '/'; 317 p++; 318 } 319} 320 321#define SIZE(dp, edp) (size_t)((intptr_t)(void *)edp - (intptr_t)(void *)dp) 322 323enum { BOOT_INFO_OK = 0, BAD_CHOICE = 1, NOT_SPECIFIC = 2 }; 324static int 325match_boot_info(char *boot_info, size_t bisz) 326{ 327 uint32_t attr; 328 uint16_t fplen; 329 size_t len; 330 char *walker, *ep; 331 EFI_DEVICE_PATH *dp, *edp, *first_dp, *last_dp; 332 pdinfo_t *pp; 333 CHAR16 *descr; 334 char *kernel = NULL; 335 FILEPATH_DEVICE_PATH *fp; 336 struct stat st; 337 CHAR16 *text; 338 339 /* 340 * FreeBSD encodes it's boot loading path into the boot loader 341 * BootXXXX variable. We look for the last one in the path 342 * and use that to load the kernel. However, if we only fine 343 * one DEVICE_PATH, then there's nothing specific and we should 344 * fall back. 345 * 346 * In an ideal world, we'd look at the image handle we were 347 * passed, match up with the loader we are and then return the 348 * next one in the path. This would be most flexible and cover 349 * many chain booting scenarios where you need to use this 350 * boot loader to get to the next boot loader. However, that 351 * doesn't work. We rarely have the path to the image booted 352 * (just the device) so we can't count on that. So, we do the 353 * enxt best thing, we look through the device path(s) passed 354 * in the BootXXXX varaible. If there's only one, we return 355 * NOT_SPECIFIC. Otherwise, we look at the last one and try to 356 * load that. If we can, we return BOOT_INFO_OK. Otherwise we 357 * return BAD_CHOICE for the caller to sort out. 358 */ 359 if (bisz < sizeof(attr) + sizeof(fplen) + sizeof(CHAR16)) 360 return NOT_SPECIFIC; 361 walker = boot_info; 362 ep = walker + bisz; 363 memcpy(&attr, walker, sizeof(attr)); 364 walker += sizeof(attr); 365 memcpy(&fplen, walker, sizeof(fplen)); 366 walker += sizeof(fplen); 367 descr = (CHAR16 *)(intptr_t)walker; 368 len = ucs2len(descr); 369 walker += (len + 1) * sizeof(CHAR16); 370 last_dp = first_dp = dp = (EFI_DEVICE_PATH *)walker; 371 edp = (EFI_DEVICE_PATH *)(walker + fplen); 372 if ((char *)edp > ep) 373 return NOT_SPECIFIC; 374 while (dp < edp && SIZE(dp, edp) > sizeof(EFI_DEVICE_PATH)) { 375 text = efi_devpath_name(dp); 376 if (text != NULL) { 377 printf(" BootInfo Path: %S\n", text); 378 efi_free_devpath_name(text); 379 } 380 last_dp = dp; 381 dp = (EFI_DEVICE_PATH *)((char *)dp + efi_devpath_length(dp)); 382 } 383 384 /* 385 * If there's only one item in the list, then nothing was 386 * specified. Or if the last path doesn't have a media 387 * path in it. Those show up as various VenHw() nodes 388 * which are basically opaque to us. Don't count those 389 * as something specifc. 390 */ 391 if (last_dp == first_dp) { 392 printf("Ignoring Boot%04x: Only one DP found\n", boot_current); 393 return NOT_SPECIFIC; 394 } 395 if (efi_devpath_to_media_path(last_dp) == NULL) { 396 printf("Ignoring Boot%04x: No Media Path\n", boot_current); 397 return NOT_SPECIFIC; 398 } 399 400 /* 401 * OK. At this point we either have a good path or a bad one. 402 * Let's check. 403 */ 404 pp = efiblk_get_pdinfo_by_device_path(last_dp); 405 if (pp == NULL) { 406 printf("Ignoring Boot%04x: Device Path not found\n", boot_current); 407 return BAD_CHOICE; 408 } 409 set_currdev_pdinfo(pp); 410 if (!sanity_check_currdev()) { 411 printf("Ignoring Boot%04x: sanity check failed\n", boot_current); 412 return BAD_CHOICE; 413 } 414 415 /* 416 * OK. We've found a device that matches, next we need to check the last 417 * component of the path. If it's a file, then we set the default kernel 418 * to that. Otherwise, just use this as the default root. 419 * 420 * Reminder: we're running very early, before we've parsed the defaults 421 * file, so we may need to have a hack override. 422 */ 423 dp = efi_devpath_last_node(last_dp); 424 if (DevicePathType(dp) != MEDIA_DEVICE_PATH || 425 DevicePathSubType(dp) != MEDIA_FILEPATH_DP) { 426 printf("Using Boot%04x for root partition\n", boot_current); 427 return (BOOT_INFO_OK); /* use currdir, default kernel */ 428 } 429 fp = (FILEPATH_DEVICE_PATH *)dp; 430 ucs2_to_utf8(fp->PathName, &kernel); 431 if (kernel == NULL) { 432 printf("Not using Boot%04x: can't decode kernel\n", boot_current); 433 return (BAD_CHOICE); 434 } 435 if (*kernel == '\\' || isupper(*kernel)) 436 fix_dosisms(kernel); 437 if (stat(kernel, &st) != 0) { 438 free(kernel); 439 printf("Not using Boot%04x: can't find %s\n", boot_current, 440 kernel); 441 return (BAD_CHOICE); 442 } 443 setenv("kernel", kernel, 1); 444 free(kernel); 445 text = efi_devpath_name(last_dp); 446 if (text) { 447 printf("Using Boot%04x %S + %s\n", boot_current, text, 448 kernel); 449 efi_free_devpath_name(text); 450 } 451 452 return (BOOT_INFO_OK); 453} 454 455/* 456 * Look at the passed-in boot_info, if any. If we find it then we need 457 * to see if we can find ourselves in the boot chain. If we can, and 458 * there's another specified thing to boot next, assume that the file 459 * is loaded from / and use that for the root filesystem. If can't 460 * find the specified thing, we must fail the boot. If we're last on 461 * the list, then we fallback to looking for the first available / 462 * candidate (ZFS, if there's a bootable zpool, otherwise a UFS 463 * partition that has either /boot/defaults/loader.conf on it or 464 * /boot/kernel/kernel (the default kernel) that we can use. 465 * 466 * We always fail if we can't find the right thing. However, as 467 * a concession to buggy UEFI implementations, like u-boot, if 468 * we have determined that the host is violating the UEFI boot 469 * manager protocol, we'll signal the rest of the program that 470 * a drop to the OK boot loader prompt is possible. 471 */ 472static int 473find_currdev(bool do_bootmgr, bool is_last, 474 char *boot_info, size_t boot_info_sz) 475{ 476 pdinfo_t *dp, *pp; 477 EFI_DEVICE_PATH *devpath, *copy; 478 EFI_HANDLE h; 479 CHAR16 *text; 480 struct devsw *dev; 481 int unit; 482 uint64_t extra; 483 int rv; 484 char *rootdev; 485 486 /* 487 * First choice: if rootdev is already set, use that, even if 488 * it's wrong. 489 */ 490 rootdev = getenv("rootdev"); 491 if (rootdev != NULL) { 492 printf(" Setting currdev to configured rootdev %s\n", 493 rootdev); 494 set_currdev(rootdev); 495 return (0); 496 } 497 498 /* 499 * Second choice: If uefi_rootdev is set, translate that UEFI device 500 * path to the loader's internal name and use that. 501 */ 502 do { 503 rootdev = getenv("uefi_rootdev"); 504 if (rootdev == NULL) 505 break; 506 devpath = efi_name_to_devpath(rootdev); 507 if (devpath == NULL) 508 break; 509 dp = efiblk_get_pdinfo_by_device_path(devpath); 510 efi_devpath_free(devpath); 511 if (dp == NULL) 512 break; 513 printf(" Setting currdev to UEFI path %s\n", 514 rootdev); 515 set_currdev_pdinfo(dp); 516 return (0); 517 } while (0); 518 519 /* 520 * Third choice: If we can find out image boot_info, and there's 521 * a follow-on boot image in that boot_info, use that. In this 522 * case root will be the partition specified in that image and 523 * we'll load the kernel specified by the file path. Should there 524 * not be a filepath, we use the default. This filepath overrides 525 * loader.conf. 526 */ 527 if (do_bootmgr) { 528 rv = match_boot_info(boot_info, boot_info_sz); 529 switch (rv) { 530 case BOOT_INFO_OK: /* We found it */ 531 return (0); 532 case BAD_CHOICE: /* specified file not found -> error */ 533 /* XXX do we want to have an escape hatch for last in boot order? */ 534 return (ENOENT); 535 } /* Nothing specified, try normal match */ 536 } 537 538#ifdef EFI_ZFS_BOOT 539 /* 540 * Did efi_zfs_probe() detect the boot pool? If so, use the zpool 541 * it found, if it's sane. ZFS is the only thing that looks for 542 * disks and pools to boot. This may change in the future, however, 543 * if we allow specifying which pool to boot from via UEFI variables 544 * rather than the bootenv stuff that FreeBSD uses today. 545 */ 546 if (pool_guid != 0) { 547 printf("Trying ZFS pool\n"); 548 if (probe_zfs_currdev(pool_guid)) 549 return (0); 550 } 551#endif /* EFI_ZFS_BOOT */ 552 553 /* 554 * Try to find the block device by its handle based on the 555 * image we're booting. If we can't find a sane partition, 556 * search all the other partitions of the disk. We do not 557 * search other disks because it's a violation of the UEFI 558 * boot protocol to do so. We fail and let UEFI go on to 559 * the next candidate. 560 */ 561 dp = efiblk_get_pdinfo_by_handle(boot_img->DeviceHandle); 562 if (dp != NULL) { 563 text = efi_devpath_name(dp->pd_devpath); 564 if (text != NULL) { 565 printf("Trying ESP: %S\n", text); 566 efi_free_devpath_name(text); 567 } 568 set_currdev_pdinfo(dp); 569 if (sanity_check_currdev()) 570 return (0); 571 if (dp->pd_parent != NULL) { 572 pdinfo_t *espdp = dp; 573 dp = dp->pd_parent; 574 STAILQ_FOREACH(pp, &dp->pd_part, pd_link) { 575 /* Already tried the ESP */ 576 if (espdp == pp) 577 continue; 578 /* 579 * Roll up the ZFS special case 580 * for those partitions that have 581 * zpools on them. 582 */ 583 text = efi_devpath_name(pp->pd_devpath); 584 if (text != NULL) { 585 printf("Trying: %S\n", text); 586 efi_free_devpath_name(text); 587 } 588 if (try_as_currdev(dp, pp)) 589 return (0); 590 } 591 } 592 } 593 594 /* 595 * Try the device handle from our loaded image first. If that 596 * fails, use the device path from the loaded image and see if 597 * any of the nodes in that path match one of the enumerated 598 * handles. Currently, this handle list is only for netboot. 599 */ 600 if (efi_handle_lookup(boot_img->DeviceHandle, &dev, &unit, &extra) == 0) { 601 set_currdev_devsw(dev, unit); 602 if (sanity_check_currdev()) 603 return (0); 604 } 605 606 copy = NULL; 607 devpath = efi_lookup_image_devpath(IH); 608 while (devpath != NULL) { 609 h = efi_devpath_handle(devpath); 610 if (h == NULL) 611 break; 612 613 free(copy); 614 copy = NULL; 615 616 if (efi_handle_lookup(h, &dev, &unit, &extra) == 0) { 617 set_currdev_devsw(dev, unit); 618 if (sanity_check_currdev()) 619 return (0); 620 } 621 622 devpath = efi_lookup_devpath(h); 623 if (devpath != NULL) { 624 copy = efi_devpath_trim(devpath); 625 devpath = copy; 626 } 627 } 628 free(copy); 629 630 return (ENOENT); 631} 632 633static bool 634interactive_interrupt(const char *msg) 635{ 636 time_t now, then, last; 637 638 last = 0; 639 now = then = getsecs(); 640 printf("%s\n", msg); 641 if (fail_timeout == -2) /* Always break to OK */ 642 return (true); 643 if (fail_timeout == -1) /* Never break to OK */ 644 return (false); 645 do { 646 if (last != now) { 647 printf("press any key to interrupt reboot in %d seconds\r", 648 fail_timeout - (int)(now - then)); 649 last = now; 650 } 651 652 /* XXX no pause or timeout wait for char */ 653 if (ischar()) 654 return (true); 655 now = getsecs(); 656 } while (now - then < fail_timeout); 657 return (false); 658} 659 660static int 661parse_args(int argc, CHAR16 *argv[]) 662{ 663 int i, j, howto; 664 bool vargood; 665 char var[128]; 666 667 /* 668 * Parse the args to set the console settings, etc 669 * boot1.efi passes these in, if it can read /boot.config or /boot/config 670 * or iPXE may be setup to pass these in. Or the optional argument in the 671 * boot environment was used to pass these arguments in (in which case 672 * neither /boot.config nor /boot/config are consulted). 673 * 674 * Loop through the args, and for each one that contains an '=' that is 675 * not the first character, add it to the environment. This allows 676 * loader and kernel env vars to be passed on the command line. Convert 677 * args from UCS-2 to ASCII (16 to 8 bit) as they are copied (though this 678 * method is flawed for non-ASCII characters). 679 */ 680 howto = 0; 681 for (i = 1; i < argc; i++) { 682 cpy16to8(argv[i], var, sizeof(var)); 683 howto |= boot_parse_arg(var); 684 } 685 686 return (howto); 687} 688 689static void 690setenv_int(const char *key, int val) 691{ 692 char buf[20]; 693 694 snprintf(buf, sizeof(buf), "%d", val); 695 setenv(key, buf, 1); 696} 697 698/* 699 * Parse ConOut (the list of consoles active) and see if we can find a 700 * serial port and/or a video port. It would be nice to also walk the 701 * ACPI name space to map the UID for the serial port to a port. The 702 * latter is especially hard. 703 */ 704static int 705parse_uefi_con_out(void) 706{ 707 int how, rv; 708 int vid_seen = 0, com_seen = 0, seen = 0; 709 size_t sz; 710 char buf[4096], *ep; 711 EFI_DEVICE_PATH *node; 712 ACPI_HID_DEVICE_PATH *acpi; 713 UART_DEVICE_PATH *uart; 714 bool pci_pending; 715 716 how = 0; 717 sz = sizeof(buf); 718 rv = efi_global_getenv("ConOut", buf, &sz); 719 if (rv != EFI_SUCCESS) 720 goto out; 721 ep = buf + sz; 722 node = (EFI_DEVICE_PATH *)buf; 723 while ((char *)node < ep) { 724 if (IsDevicePathEndType(node)) { 725 if (pci_pending && vid_seen == 0) 726 vid_seen = ++seen; 727 } 728 pci_pending = false; 729 if (DevicePathType(node) == ACPI_DEVICE_PATH && 730 DevicePathSubType(node) == ACPI_DP) { 731 /* Check for Serial node */ 732 acpi = (void *)node; 733 if (EISA_ID_TO_NUM(acpi->HID) == 0x501) { 734 setenv_int("efi_8250_uid", acpi->UID); 735 com_seen = ++seen; 736 } 737 } else if (DevicePathType(node) == MESSAGING_DEVICE_PATH && 738 DevicePathSubType(node) == MSG_UART_DP) { 739 740 uart = (void *)node; 741 setenv_int("efi_com_speed", uart->BaudRate); 742 } else if (DevicePathType(node) == ACPI_DEVICE_PATH && 743 DevicePathSubType(node) == ACPI_ADR_DP) { 744 /* Check for AcpiAdr() Node for video */ 745 vid_seen = ++seen; 746 } else if (DevicePathType(node) == HARDWARE_DEVICE_PATH && 747 DevicePathSubType(node) == HW_PCI_DP) { 748 /* 749 * Note, vmware fusion has a funky console device 750 * PciRoot(0x0)/Pci(0xf,0x0) 751 * which we can only detect at the end since we also 752 * have to cope with: 753 * PciRoot(0x0)/Pci(0x1f,0x0)/Serial(0x1) 754 * so only match it if it's last. 755 */ 756 pci_pending = true; 757 } 758 node = NextDevicePathNode(node); /* Skip the end node */ 759 } 760 761 /* 762 * Truth table for RB_MULTIPLE | RB_SERIAL 763 * Value Result 764 * 0 Use only video console 765 * RB_SERIAL Use only serial console 766 * RB_MULTIPLE Use both video and serial console 767 * (but video is primary so gets rc messages) 768 * both Use both video and serial console 769 * (but serial is primary so gets rc messages) 770 * 771 * Try to honor this as best we can. If only one of serial / video 772 * found, then use that. Otherwise, use the first one we found. 773 * This also implies if we found nothing, default to video. 774 */ 775 how = 0; 776 if (vid_seen && com_seen) { 777 how |= RB_MULTIPLE; 778 if (com_seen < vid_seen) 779 how |= RB_SERIAL; 780 } else if (com_seen) 781 how |= RB_SERIAL; 782out: 783 return (how); 784} 785 786void 787parse_loader_efi_config(EFI_HANDLE h, const char *env_fn) 788{ 789 pdinfo_t *dp; 790 struct stat st; 791 int fd = -1; 792 char *env = NULL; 793 794 dp = efiblk_get_pdinfo_by_handle(h); 795 if (dp == NULL) 796 return; 797 set_currdev_pdinfo(dp); 798 if (stat(env_fn, &st) != 0) 799 return; 800 fd = open(env_fn, O_RDONLY); 801 if (fd == -1) 802 return; 803 env = malloc(st.st_size + 1); 804 if (env == NULL) 805 goto out; 806 if (read(fd, env, st.st_size) != st.st_size) 807 goto out; 808 env[st.st_size] = '\0'; 809 boot_parse_cmdline(env); 810out: 811 free(env); 812 close(fd); 813} 814 815static void 816read_loader_env(const char *name, char *def_fn, bool once) 817{ 818 UINTN len; 819 char *fn, *freeme = NULL; 820 821 len = 0; 822 fn = def_fn; 823 if (efi_freebsd_getenv(name, NULL, &len) == EFI_BUFFER_TOO_SMALL) { 824 freeme = fn = malloc(len + 1); 825 if (fn != NULL) { 826 if (efi_freebsd_getenv(name, fn, &len) != EFI_SUCCESS) { 827 free(fn); 828 fn = NULL; 829 printf( 830 "Can't fetch FreeBSD::%s we know is there\n", name); 831 } else { 832 /* 833 * if tagged as 'once' delete the env variable so we 834 * only use it once. 835 */ 836 if (once) 837 efi_freebsd_delenv(name); 838 /* 839 * We malloced 1 more than len above, then redid the call. 840 * so now we have room at the end of the string to NUL terminate 841 * it here, even if the typical idium would have '- 1' here to 842 * not overflow. len should be the same on return both times. 843 */ 844 fn[len] = '\0'; 845 } 846 } else { 847 printf( 848 "Can't allocate %d bytes to fetch FreeBSD::%s env var\n", 849 len, name); 850 } 851 } 852 if (fn) { 853 printf(" Reading loader env vars from %s\n", fn); 854 parse_loader_efi_config(boot_img->DeviceHandle, fn); 855 } 856} 857 858 859 860EFI_STATUS 861main(int argc, CHAR16 *argv[]) 862{ 863 EFI_GUID *guid; 864 int howto, i, uhowto; 865 UINTN k; 866 bool has_kbd, is_last; 867 char *s; 868 EFI_DEVICE_PATH *imgpath; 869 CHAR16 *text; 870 EFI_STATUS rv; 871 size_t sz, bosz = 0, bisz = 0; 872 UINT16 boot_order[100]; 873 char boot_info[4096]; 874 char buf[32]; 875 bool uefi_boot_mgr; 876 877 archsw.arch_autoload = efi_autoload; 878 archsw.arch_getdev = efi_getdev; 879 archsw.arch_copyin = efi_copyin; 880 archsw.arch_copyout = efi_copyout; 881#ifdef __amd64__ 882 archsw.arch_hypervisor = x86_hypervisor; 883#endif 884 archsw.arch_readin = efi_readin; 885 archsw.arch_zfs_probe = efi_zfs_probe; 886 887 /* Get our loaded image protocol interface structure. */ 888 (void) OpenProtocolByHandle(IH, &imgid, (void **)&boot_img); 889 890 /* 891 * Chicken-and-egg problem; we want to have console output early, but 892 * some console attributes may depend on reading from eg. the boot 893 * device, which we can't do yet. We can use printf() etc. once this is 894 * done. So, we set it to the efi console, then call console init. This 895 * gets us printf early, but also primes the pump for all future console 896 * changes to take effect, regardless of where they come from. 897 */ 898 setenv("console", "efi", 1); 899 cons_probe(); 900 901 /* Init the time source */ 902 efi_time_init(); 903 904 /* 905 * Initialise the block cache. Set the upper limit. 906 */ 907 bcache_init(32768, 512); 908 909 /* 910 * Scan the BLOCK IO MEDIA handles then 911 * march through the device switch probing for things. 912 */ 913 i = efipart_inithandles(); 914 if (i != 0 && i != ENOENT) { 915 printf("efipart_inithandles failed with ERRNO %d, expect " 916 "failures\n", i); 917 } 918 919 for (i = 0; devsw[i] != NULL; i++) 920 if (devsw[i]->dv_init != NULL) 921 (devsw[i]->dv_init)(); 922 923 /* 924 * Detect console settings two different ways: one via the command 925 * args (eg -h) or via the UEFI ConOut variable. 926 */ 927 has_kbd = has_keyboard(); 928 howto = parse_args(argc, argv); 929 if (!has_kbd && (howto & RB_PROBE)) 930 howto |= RB_SERIAL | RB_MULTIPLE; 931 howto &= ~RB_PROBE; 932 uhowto = parse_uefi_con_out(); 933 934 /* 935 * Read additional environment variables from the boot device's 936 * "LoaderEnv" file. Any boot loader environment variable may be set 937 * there, which are subtly different than loader.conf variables. Only 938 * the 'simple' ones may be set so things like foo_load="YES" won't work 939 * for two reasons. First, the parser is simplistic and doesn't grok 940 * quotes. Second, because the variables that cause an action to happen 941 * are parsed by the lua, 4th or whatever code that's not yet 942 * loaded. This is relative to the root directory when loader.efi is 943 * loaded off the UFS root drive (when chain booted), or from the ESP 944 * when directly loaded by the BIOS. 945 * 946 * We also read in NextLoaderEnv if it was specified. This allows next boot 947 * functionality to be implemented and to override anything in LoaderEnv. 948 */ 949 read_loader_env("LoaderEnv", "/efi/freebsd/loader.env", false); 950 read_loader_env("NextLoaderEnv", NULL, true); 951 952 /* 953 * We now have two notions of console. howto should be viewed as 954 * overrides. If console is already set, don't set it again. 955 */ 956#define VIDEO_ONLY 0 957#define SERIAL_ONLY RB_SERIAL 958#define VID_SER_BOTH RB_MULTIPLE 959#define SER_VID_BOTH (RB_SERIAL | RB_MULTIPLE) 960#define CON_MASK (RB_SERIAL | RB_MULTIPLE) 961 if (strcmp(getenv("console"), "efi") == 0) { 962 if ((howto & CON_MASK) == 0) { 963 /* No override, uhowto is controlling and efi cons is perfect */ 964 howto = howto | (uhowto & CON_MASK); 965 } else if ((howto & CON_MASK) == (uhowto & CON_MASK)) { 966 /* override matches what UEFI told us, efi console is perfect */ 967 } else if ((uhowto & (CON_MASK)) != 0) { 968 /* 969 * We detected a serial console on ConOut. All possible 970 * overrides include serial. We can't really override what efi 971 * gives us, so we use it knowing it's the best choice. 972 */ 973 /* Do nothing */ 974 } else { 975 /* 976 * We detected some kind of serial in the override, but ConOut 977 * has no serial, so we have to sort out which case it really is. 978 */ 979 switch (howto & CON_MASK) { 980 case SERIAL_ONLY: 981 setenv("console", "comconsole", 1); 982 break; 983 case VID_SER_BOTH: 984 setenv("console", "efi comconsole", 1); 985 break; 986 case SER_VID_BOTH: 987 setenv("console", "comconsole efi", 1); 988 break; 989 /* case VIDEO_ONLY can't happen -- it's the first if above */ 990 } 991 } 992 } 993 994 /* 995 * howto is set now how we want to export the flags to the kernel, so 996 * set the env based on it. 997 */ 998 boot_howto_to_env(howto); 999 1000 if (efi_copy_init()) { 1001 printf("failed to allocate staging area\n"); 1002 return (EFI_BUFFER_TOO_SMALL); 1003 } 1004 1005 if ((s = getenv("fail_timeout")) != NULL) 1006 fail_timeout = strtol(s, NULL, 10); 1007 1008 printf("%s\n", bootprog_info); 1009 printf(" Command line arguments:"); 1010 for (i = 0; i < argc; i++) 1011 printf(" %S", argv[i]); 1012 printf("\n"); 1013 1014 printf(" EFI version: %d.%02d\n", ST->Hdr.Revision >> 16, 1015 ST->Hdr.Revision & 0xffff); 1016 printf(" EFI Firmware: %S (rev %d.%02d)\n", ST->FirmwareVendor, 1017 ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff); 1018 printf(" Console: %s (%#x)\n", getenv("console"), howto); 1019 1020 /* Determine the devpath of our image so we can prefer it. */ 1021 text = efi_devpath_name(boot_img->FilePath); 1022 if (text != NULL) { 1023 printf(" Load Path: %S\n", text); 1024 efi_setenv_freebsd_wcs("LoaderPath", text); 1025 efi_free_devpath_name(text); 1026 } 1027 1028 rv = OpenProtocolByHandle(boot_img->DeviceHandle, &devid, (void **)&imgpath); 1029 if (rv == EFI_SUCCESS) { 1030 text = efi_devpath_name(imgpath); 1031 if (text != NULL) { 1032 printf(" Load Device: %S\n", text); 1033 efi_setenv_freebsd_wcs("LoaderDev", text); 1034 efi_free_devpath_name(text); 1035 } 1036 } 1037 1038 if (getenv("uefi_ignore_boot_mgr") != NULL) { 1039 printf(" Ignoring UEFI boot manager\n"); 1040 uefi_boot_mgr = false; 1041 } else { 1042 uefi_boot_mgr = true; 1043 boot_current = 0; 1044 sz = sizeof(boot_current); 1045 rv = efi_global_getenv("BootCurrent", &boot_current, &sz); 1046 if (rv == EFI_SUCCESS) 1047 printf(" BootCurrent: %04x\n", boot_current); 1048 else { 1049 boot_current = 0xffff; 1050 uefi_boot_mgr = false; 1051 } 1052 1053 sz = sizeof(boot_order); 1054 rv = efi_global_getenv("BootOrder", &boot_order, &sz); 1055 if (rv == EFI_SUCCESS) { 1056 printf(" BootOrder:"); 1057 for (i = 0; i < sz / sizeof(boot_order[0]); i++) 1058 printf(" %04x%s", boot_order[i], 1059 boot_order[i] == boot_current ? "[*]" : ""); 1060 printf("\n"); 1061 is_last = boot_order[(sz / sizeof(boot_order[0])) - 1] == boot_current; 1062 bosz = sz; 1063 } else if (uefi_boot_mgr) { 1064 /* 1065 * u-boot doesn't set BootOrder, but otherwise participates in the 1066 * boot manager protocol. So we fake it here and don't consider it 1067 * a failure. 1068 */ 1069 bosz = sizeof(boot_order[0]); 1070 boot_order[0] = boot_current; 1071 is_last = true; 1072 } 1073 } 1074 1075 /* 1076 * Next, find the boot info structure the UEFI boot manager is 1077 * supposed to setup. We need this so we can walk through it to 1078 * find where we are in the booting process and what to try to 1079 * boot next. 1080 */ 1081 if (uefi_boot_mgr) { 1082 snprintf(buf, sizeof(buf), "Boot%04X", boot_current); 1083 sz = sizeof(boot_info); 1084 rv = efi_global_getenv(buf, &boot_info, &sz); 1085 if (rv == EFI_SUCCESS) 1086 bisz = sz; 1087 else 1088 uefi_boot_mgr = false; 1089 } 1090 1091 /* 1092 * Disable the watchdog timer. By default the boot manager sets 1093 * the timer to 5 minutes before invoking a boot option. If we 1094 * want to return to the boot manager, we have to disable the 1095 * watchdog timer and since we're an interactive program, we don't 1096 * want to wait until the user types "quit". The timer may have 1097 * fired by then. We don't care if this fails. It does not prevent 1098 * normal functioning in any way... 1099 */ 1100 BS->SetWatchdogTimer(0, 0, 0, NULL); 1101 1102 /* 1103 * Initialize the trusted/forbidden certificates from UEFI. 1104 * They will be later used to verify the manifest(s), 1105 * which should contain hashes of verified files. 1106 * This needs to be initialized before any configuration files 1107 * are loaded. 1108 */ 1109#ifdef EFI_SECUREBOOT 1110 ve_efi_init(); 1111#endif 1112 1113 /* 1114 * Try and find a good currdev based on the image that was booted. 1115 * It might be desirable here to have a short pause to allow falling 1116 * through to the boot loader instead of returning instantly to follow 1117 * the boot protocol and also allow an escape hatch for users wishing 1118 * to try something different. 1119 */ 1120 if (find_currdev(uefi_boot_mgr, is_last, boot_info, bisz) != 0) 1121 if (uefi_boot_mgr && 1122 !interactive_interrupt("Failed to find bootable partition")) 1123 return (EFI_NOT_FOUND); 1124 1125 efi_init_environment(); 1126 1127#if !defined(__arm__) 1128 for (k = 0; k < ST->NumberOfTableEntries; k++) { 1129 guid = &ST->ConfigurationTable[k].VendorGuid; 1130 if (!memcmp(guid, &smbios, sizeof(EFI_GUID))) { 1131 char buf[40]; 1132 1133 snprintf(buf, sizeof(buf), "%p", 1134 ST->ConfigurationTable[k].VendorTable); 1135 setenv("hint.smbios.0.mem", buf, 1); 1136 smbios_detect(ST->ConfigurationTable[k].VendorTable); 1137 break; 1138 } 1139 } 1140#endif 1141 1142 interact(); /* doesn't return */ 1143 1144 return (EFI_SUCCESS); /* keep compiler happy */ 1145} 1146 1147COMMAND_SET(poweroff, "poweroff", "power off the system", command_poweroff); 1148 1149static int 1150command_poweroff(int argc __unused, char *argv[] __unused) 1151{ 1152 int i; 1153 1154 for (i = 0; devsw[i] != NULL; ++i) 1155 if (devsw[i]->dv_cleanup != NULL) 1156 (devsw[i]->dv_cleanup)(); 1157 1158 RS->ResetSystem(EfiResetShutdown, EFI_SUCCESS, 0, NULL); 1159 1160 /* NOTREACHED */ 1161 return (CMD_ERROR); 1162} 1163 1164COMMAND_SET(reboot, "reboot", "reboot the system", command_reboot); 1165 1166static int 1167command_reboot(int argc, char *argv[]) 1168{ 1169 int i; 1170 1171 for (i = 0; devsw[i] != NULL; ++i) 1172 if (devsw[i]->dv_cleanup != NULL) 1173 (devsw[i]->dv_cleanup)(); 1174 1175 RS->ResetSystem(EfiResetCold, EFI_SUCCESS, 0, NULL); 1176 1177 /* NOTREACHED */ 1178 return (CMD_ERROR); 1179} 1180 1181COMMAND_SET(quit, "quit", "exit the loader", command_quit); 1182 1183static int 1184command_quit(int argc, char *argv[]) 1185{ 1186 exit(0); 1187 return (CMD_OK); 1188} 1189 1190COMMAND_SET(memmap, "memmap", "print memory map", command_memmap); 1191 1192static int 1193command_memmap(int argc __unused, char *argv[] __unused) 1194{ 1195 UINTN sz; 1196 EFI_MEMORY_DESCRIPTOR *map, *p; 1197 UINTN key, dsz; 1198 UINT32 dver; 1199 EFI_STATUS status; 1200 int i, ndesc; 1201 char line[80]; 1202 1203 sz = 0; 1204 status = BS->GetMemoryMap(&sz, 0, &key, &dsz, &dver); 1205 if (status != EFI_BUFFER_TOO_SMALL) { 1206 printf("Can't determine memory map size\n"); 1207 return (CMD_ERROR); 1208 } 1209 map = malloc(sz); 1210 status = BS->GetMemoryMap(&sz, map, &key, &dsz, &dver); 1211 if (EFI_ERROR(status)) { 1212 printf("Can't read memory map\n"); 1213 return (CMD_ERROR); 1214 } 1215 1216 ndesc = sz / dsz; 1217 snprintf(line, sizeof(line), "%23s %12s %12s %8s %4s\n", 1218 "Type", "Physical", "Virtual", "#Pages", "Attr"); 1219 pager_open(); 1220 if (pager_output(line)) { 1221 pager_close(); 1222 return (CMD_OK); 1223 } 1224 1225 for (i = 0, p = map; i < ndesc; 1226 i++, p = NextMemoryDescriptor(p, dsz)) { 1227 snprintf(line, sizeof(line), "%23s %012jx %012jx %08jx ", 1228 efi_memory_type(p->Type), (uintmax_t)p->PhysicalStart, 1229 (uintmax_t)p->VirtualStart, (uintmax_t)p->NumberOfPages); 1230 if (pager_output(line)) 1231 break; 1232 1233 if (p->Attribute & EFI_MEMORY_UC) 1234 printf("UC "); 1235 if (p->Attribute & EFI_MEMORY_WC) 1236 printf("WC "); 1237 if (p->Attribute & EFI_MEMORY_WT) 1238 printf("WT "); 1239 if (p->Attribute & EFI_MEMORY_WB) 1240 printf("WB "); 1241 if (p->Attribute & EFI_MEMORY_UCE) 1242 printf("UCE "); 1243 if (p->Attribute & EFI_MEMORY_WP) 1244 printf("WP "); 1245 if (p->Attribute & EFI_MEMORY_RP) 1246 printf("RP "); 1247 if (p->Attribute & EFI_MEMORY_XP) 1248 printf("XP "); 1249 if (p->Attribute & EFI_MEMORY_NV) 1250 printf("NV "); 1251 if (p->Attribute & EFI_MEMORY_MORE_RELIABLE) 1252 printf("MR "); 1253 if (p->Attribute & EFI_MEMORY_RO) 1254 printf("RO "); 1255 if (pager_output("\n")) 1256 break; 1257 } 1258 1259 pager_close(); 1260 return (CMD_OK); 1261} 1262 1263COMMAND_SET(configuration, "configuration", "print configuration tables", 1264 command_configuration); 1265 1266static int 1267command_configuration(int argc, char *argv[]) 1268{ 1269 UINTN i; 1270 char *name; 1271 1272 printf("NumberOfTableEntries=%lu\n", 1273 (unsigned long)ST->NumberOfTableEntries); 1274 1275 for (i = 0; i < ST->NumberOfTableEntries; i++) { 1276 EFI_GUID *guid; 1277 1278 printf(" "); 1279 guid = &ST->ConfigurationTable[i].VendorGuid; 1280 1281 if (efi_guid_to_name(guid, &name) == true) { 1282 printf(name); 1283 free(name); 1284 } else { 1285 printf("Error while translating UUID to name"); 1286 } 1287 printf(" at %p\n", ST->ConfigurationTable[i].VendorTable); 1288 } 1289 1290 return (CMD_OK); 1291} 1292 1293 1294COMMAND_SET(mode, "mode", "change or display EFI text modes", command_mode); 1295 1296static int 1297command_mode(int argc, char *argv[]) 1298{ 1299 UINTN cols, rows; 1300 unsigned int mode; 1301 int i; 1302 char *cp; 1303 char rowenv[8]; 1304 EFI_STATUS status; 1305 SIMPLE_TEXT_OUTPUT_INTERFACE *conout; 1306 extern void HO(void); 1307 1308 conout = ST->ConOut; 1309 1310 if (argc > 1) { 1311 mode = strtol(argv[1], &cp, 0); 1312 if (cp[0] != '\0') { 1313 printf("Invalid mode\n"); 1314 return (CMD_ERROR); 1315 } 1316 status = conout->QueryMode(conout, mode, &cols, &rows); 1317 if (EFI_ERROR(status)) { 1318 printf("invalid mode %d\n", mode); 1319 return (CMD_ERROR); 1320 } 1321 status = conout->SetMode(conout, mode); 1322 if (EFI_ERROR(status)) { 1323 printf("couldn't set mode %d\n", mode); 1324 return (CMD_ERROR); 1325 } 1326 sprintf(rowenv, "%u", (unsigned)rows); 1327 setenv("LINES", rowenv, 1); 1328 HO(); /* set cursor */ 1329 return (CMD_OK); 1330 } 1331 1332 printf("Current mode: %d\n", conout->Mode->Mode); 1333 for (i = 0; i <= conout->Mode->MaxMode; i++) { 1334 status = conout->QueryMode(conout, i, &cols, &rows); 1335 if (EFI_ERROR(status)) 1336 continue; 1337 printf("Mode %d: %u columns, %u rows\n", i, (unsigned)cols, 1338 (unsigned)rows); 1339 } 1340 1341 if (i != 0) 1342 printf("Select a mode with the command \"mode <number>\"\n"); 1343 1344 return (CMD_OK); 1345} 1346 1347COMMAND_SET(lsefi, "lsefi", "list EFI handles", command_lsefi); 1348 1349static int 1350command_lsefi(int argc __unused, char *argv[] __unused) 1351{ 1352 char *name; 1353 EFI_HANDLE *buffer = NULL; 1354 EFI_HANDLE handle; 1355 UINTN bufsz = 0, i, j; 1356 EFI_STATUS status; 1357 int ret = 0; 1358 1359 status = BS->LocateHandle(AllHandles, NULL, NULL, &bufsz, buffer); 1360 if (status != EFI_BUFFER_TOO_SMALL) { 1361 snprintf(command_errbuf, sizeof (command_errbuf), 1362 "unexpected error: %lld", (long long)status); 1363 return (CMD_ERROR); 1364 } 1365 if ((buffer = malloc(bufsz)) == NULL) { 1366 sprintf(command_errbuf, "out of memory"); 1367 return (CMD_ERROR); 1368 } 1369 1370 status = BS->LocateHandle(AllHandles, NULL, NULL, &bufsz, buffer); 1371 if (EFI_ERROR(status)) { 1372 free(buffer); 1373 snprintf(command_errbuf, sizeof (command_errbuf), 1374 "LocateHandle() error: %lld", (long long)status); 1375 return (CMD_ERROR); 1376 } 1377 1378 pager_open(); 1379 for (i = 0; i < (bufsz / sizeof (EFI_HANDLE)); i++) { 1380 UINTN nproto = 0; 1381 EFI_GUID **protocols = NULL; 1382 1383 handle = buffer[i]; 1384 printf("Handle %p", handle); 1385 if (pager_output("\n")) 1386 break; 1387 /* device path */ 1388 1389 status = BS->ProtocolsPerHandle(handle, &protocols, &nproto); 1390 if (EFI_ERROR(status)) { 1391 snprintf(command_errbuf, sizeof (command_errbuf), 1392 "ProtocolsPerHandle() error: %lld", 1393 (long long)status); 1394 continue; 1395 } 1396 1397 for (j = 0; j < nproto; j++) { 1398 if (efi_guid_to_name(protocols[j], &name) == true) { 1399 printf(" %s", name); 1400 free(name); 1401 } else { 1402 printf("Error while translating UUID to name"); 1403 } 1404 if ((ret = pager_output("\n")) != 0) 1405 break; 1406 } 1407 BS->FreePool(protocols); 1408 if (ret != 0) 1409 break; 1410 } 1411 pager_close(); 1412 free(buffer); 1413 return (CMD_OK); 1414} 1415 1416#ifdef LOADER_FDT_SUPPORT 1417extern int command_fdt_internal(int argc, char *argv[]); 1418 1419/* 1420 * Since proper fdt command handling function is defined in fdt_loader_cmd.c, 1421 * and declaring it as extern is in contradiction with COMMAND_SET() macro 1422 * (which uses static pointer), we're defining wrapper function, which 1423 * calls the proper fdt handling routine. 1424 */ 1425static int 1426command_fdt(int argc, char *argv[]) 1427{ 1428 1429 return (command_fdt_internal(argc, argv)); 1430} 1431 1432COMMAND_SET(fdt, "fdt", "flattened device tree handling", command_fdt); 1433#endif 1434 1435/* 1436 * Chain load another efi loader. 1437 */ 1438static int 1439command_chain(int argc, char *argv[]) 1440{ 1441 EFI_GUID LoadedImageGUID = LOADED_IMAGE_PROTOCOL; 1442 EFI_HANDLE loaderhandle; 1443 EFI_LOADED_IMAGE *loaded_image; 1444 EFI_STATUS status; 1445 struct stat st; 1446 struct devdesc *dev; 1447 char *name, *path; 1448 void *buf; 1449 int fd; 1450 1451 if (argc < 2) { 1452 command_errmsg = "wrong number of arguments"; 1453 return (CMD_ERROR); 1454 } 1455 1456 name = argv[1]; 1457 1458 if ((fd = open(name, O_RDONLY)) < 0) { 1459 command_errmsg = "no such file"; 1460 return (CMD_ERROR); 1461 } 1462 1463#ifdef LOADER_VERIEXEC 1464 if (verify_file(fd, name, 0, VE_MUST, __func__) < 0) { 1465 sprintf(command_errbuf, "can't verify: %s", name); 1466 close(fd); 1467 return (CMD_ERROR); 1468 } 1469#endif 1470 1471 if (fstat(fd, &st) < -1) { 1472 command_errmsg = "stat failed"; 1473 close(fd); 1474 return (CMD_ERROR); 1475 } 1476 1477 status = BS->AllocatePool(EfiLoaderCode, (UINTN)st.st_size, &buf); 1478 if (status != EFI_SUCCESS) { 1479 command_errmsg = "failed to allocate buffer"; 1480 close(fd); 1481 return (CMD_ERROR); 1482 } 1483 if (read(fd, buf, st.st_size) != st.st_size) { 1484 command_errmsg = "error while reading the file"; 1485 (void)BS->FreePool(buf); 1486 close(fd); 1487 return (CMD_ERROR); 1488 } 1489 close(fd); 1490 status = BS->LoadImage(FALSE, IH, NULL, buf, st.st_size, &loaderhandle); 1491 (void)BS->FreePool(buf); 1492 if (status != EFI_SUCCESS) { 1493 command_errmsg = "LoadImage failed"; 1494 return (CMD_ERROR); 1495 } 1496 status = OpenProtocolByHandle(loaderhandle, &LoadedImageGUID, 1497 (void **)&loaded_image); 1498 1499 if (argc > 2) { 1500 int i, len = 0; 1501 CHAR16 *argp; 1502 1503 for (i = 2; i < argc; i++) 1504 len += strlen(argv[i]) + 1; 1505 1506 len *= sizeof (*argp); 1507 loaded_image->LoadOptions = argp = malloc (len); 1508 loaded_image->LoadOptionsSize = len; 1509 for (i = 2; i < argc; i++) { 1510 char *ptr = argv[i]; 1511 while (*ptr) 1512 *(argp++) = *(ptr++); 1513 *(argp++) = ' '; 1514 } 1515 *(--argv) = 0; 1516 } 1517 1518 if (efi_getdev((void **)&dev, name, (const char **)&path) == 0) { 1519#ifdef EFI_ZFS_BOOT 1520 struct zfs_devdesc *z_dev; 1521#endif 1522 struct disk_devdesc *d_dev; 1523 pdinfo_t *hd, *pd; 1524 1525 switch (dev->d_dev->dv_type) { 1526#ifdef EFI_ZFS_BOOT 1527 case DEVT_ZFS: 1528 z_dev = (struct zfs_devdesc *)dev; 1529 loaded_image->DeviceHandle = 1530 efizfs_get_handle_by_guid(z_dev->pool_guid); 1531 break; 1532#endif 1533 case DEVT_NET: 1534 loaded_image->DeviceHandle = 1535 efi_find_handle(dev->d_dev, dev->d_unit); 1536 break; 1537 default: 1538 hd = efiblk_get_pdinfo(dev); 1539 if (STAILQ_EMPTY(&hd->pd_part)) { 1540 loaded_image->DeviceHandle = hd->pd_handle; 1541 break; 1542 } 1543 d_dev = (struct disk_devdesc *)dev; 1544 STAILQ_FOREACH(pd, &hd->pd_part, pd_link) { 1545 /* 1546 * d_partition should be 255 1547 */ 1548 if (pd->pd_unit == (uint32_t)d_dev->d_slice) { 1549 loaded_image->DeviceHandle = 1550 pd->pd_handle; 1551 break; 1552 } 1553 } 1554 break; 1555 } 1556 } 1557 1558 dev_cleanup(); 1559 status = BS->StartImage(loaderhandle, NULL, NULL); 1560 if (status != EFI_SUCCESS) { 1561 command_errmsg = "StartImage failed"; 1562 free(loaded_image->LoadOptions); 1563 loaded_image->LoadOptions = NULL; 1564 status = BS->UnloadImage(loaded_image); 1565 return (CMD_ERROR); 1566 } 1567 1568 return (CMD_ERROR); /* not reached */ 1569} 1570 1571COMMAND_SET(chain, "chain", "chain load file", command_chain); 1572 1573extern struct in_addr servip; 1574static int 1575command_netserver(int argc, char *argv[]) 1576{ 1577 char *proto; 1578 n_long rootaddr; 1579 1580 if (argc > 2) { 1581 command_errmsg = "wrong number of arguments"; 1582 return (CMD_ERROR); 1583 } 1584 if (argc < 2) { 1585 proto = netproto == NET_TFTP ? "tftp://" : "nfs://"; 1586 printf("Netserver URI: %s%s%s\n", proto, intoa(rootip.s_addr), 1587 rootpath); 1588 return (CMD_OK); 1589 } 1590 if (argc == 2) { 1591 strncpy(rootpath, argv[1], sizeof(rootpath)); 1592 rootpath[sizeof(rootpath) -1] = '\0'; 1593 if ((rootaddr = net_parse_rootpath()) != INADDR_NONE) 1594 servip.s_addr = rootip.s_addr = rootaddr; 1595 return (CMD_OK); 1596 } 1597 return (CMD_ERROR); /* not reached */ 1598 1599} 1600 1601COMMAND_SET(netserver, "netserver", "change or display netserver URI", 1602 command_netserver); 1603