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