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