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