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 <stand.h> 31 32 #include <sys/disk.h> 33 #include <sys/param.h> 34 #include <sys/reboot.h> 35 #include <sys/boot.h> 36 #ifdef EFI_ZFS_BOOT 37 #include <sys/zfs_bootenv.h> 38 #endif 39 #include <paths.h> 40 #include <netinet/in.h> 41 #include <netinet/in_systm.h> 42 #include <stdint.h> 43 #include <string.h> 44 #include <setjmp.h> 45 #include <disk.h> 46 #include <dev_net.h> 47 #include <net.h> 48 49 #include <efi.h> 50 #include <efilib.h> 51 #include <efichar.h> 52 #include <efirng.h> 53 54 #include <uuid.h> 55 56 #include <bootstrap.h> 57 #include <smbios.h> 58 59 #include "efizfs.h" 60 #include "framebuffer.h" 61 62 #include "platform/acfreebsd.h" 63 #include "acconfig.h" 64 #define ACPI_SYSTEM_XFACE 65 #include "actypes.h" 66 #include "actbl.h" 67 68 #include "loader_efi.h" 69 70 struct arch_switch archsw; /* MI/MD interface boundary */ 71 72 EFI_GUID acpi = ACPI_TABLE_GUID; 73 EFI_GUID acpi20 = ACPI_20_TABLE_GUID; 74 EFI_GUID devid = DEVICE_PATH_PROTOCOL; 75 EFI_GUID imgid = LOADED_IMAGE_PROTOCOL; 76 EFI_GUID mps = MPS_TABLE_GUID; 77 EFI_GUID netid = EFI_SIMPLE_NETWORK_PROTOCOL; 78 EFI_GUID smbios = SMBIOS_TABLE_GUID; 79 EFI_GUID smbios3 = SMBIOS3_TABLE_GUID; 80 EFI_GUID dxe = DXE_SERVICES_TABLE_GUID; 81 EFI_GUID hoblist = HOB_LIST_TABLE_GUID; 82 EFI_GUID lzmadecomp = LZMA_DECOMPRESSION_GUID; 83 EFI_GUID mpcore = ARM_MP_CORE_INFO_TABLE_GUID; 84 EFI_GUID esrt = ESRT_TABLE_GUID; 85 EFI_GUID memtype = MEMORY_TYPE_INFORMATION_TABLE_GUID; 86 EFI_GUID debugimg = DEBUG_IMAGE_INFO_TABLE_GUID; 87 EFI_GUID fdtdtb = FDT_TABLE_GUID; 88 EFI_GUID inputid = SIMPLE_TEXT_INPUT_PROTOCOL; 89 90 /* 91 * Number of seconds to wait for a keystroke before exiting with failure 92 * in the event no currdev is found. -2 means always break, -1 means 93 * never break, 0 means poll once and then reboot, > 0 means wait for 94 * that many seconds. "fail_timeout" can be set in the environment as 95 * well. 96 */ 97 static int fail_timeout = 5; 98 99 /* 100 * Current boot variable 101 */ 102 UINT16 boot_current; 103 104 /* 105 * Image that we booted from. 106 */ 107 EFI_LOADED_IMAGE *boot_img; 108 109 static bool 110 has_keyboard(void) 111 { 112 EFI_STATUS status; 113 EFI_DEVICE_PATH *path; 114 EFI_HANDLE *hin, *hin_end, *walker; 115 UINTN sz; 116 bool retval = false; 117 118 /* 119 * Find all the handles that support the SIMPLE_TEXT_INPUT_PROTOCOL and 120 * do the typical dance to get the right sized buffer. 121 */ 122 sz = 0; 123 hin = NULL; 124 status = BS->LocateHandle(ByProtocol, &inputid, 0, &sz, 0); 125 if (status == EFI_BUFFER_TOO_SMALL) { 126 hin = (EFI_HANDLE *)malloc(sz); 127 status = BS->LocateHandle(ByProtocol, &inputid, 0, &sz, 128 hin); 129 if (EFI_ERROR(status)) 130 free(hin); 131 } 132 if (EFI_ERROR(status)) 133 return retval; 134 135 /* 136 * Look at each of the handles. If it supports the device path protocol, 137 * use it to get the device path for this handle. Then see if that 138 * device path matches either the USB device path for keyboards or the 139 * legacy device path for keyboards. 140 */ 141 hin_end = &hin[sz / sizeof(*hin)]; 142 for (walker = hin; walker < hin_end; walker++) { 143 status = OpenProtocolByHandle(*walker, &devid, (void **)&path); 144 if (EFI_ERROR(status)) 145 continue; 146 147 while (!IsDevicePathEnd(path)) { 148 /* 149 * Check for the ACPI keyboard node. All PNP3xx nodes 150 * are keyboards of different flavors. Note: It is 151 * unclear of there's always a keyboard node when 152 * there's a keyboard controller, or if there's only one 153 * when a keyboard is detected at boot. 154 */ 155 if (DevicePathType(path) == ACPI_DEVICE_PATH && 156 (DevicePathSubType(path) == ACPI_DP || 157 DevicePathSubType(path) == ACPI_EXTENDED_DP)) { 158 ACPI_HID_DEVICE_PATH *acpi; 159 160 acpi = (ACPI_HID_DEVICE_PATH *)(void *)path; 161 if ((EISA_ID_TO_NUM(acpi->HID) & 0xff00) == 0x300 && 162 (acpi->HID & 0xffff) == PNP_EISA_ID_CONST) { 163 retval = true; 164 goto out; 165 } 166 /* 167 * Check for USB keyboard node, if present. Unlike a 168 * PS/2 keyboard, these definitely only appear when 169 * connected to the system. 170 */ 171 } else if (DevicePathType(path) == MESSAGING_DEVICE_PATH && 172 DevicePathSubType(path) == MSG_USB_CLASS_DP) { 173 USB_CLASS_DEVICE_PATH *usb; 174 175 usb = (USB_CLASS_DEVICE_PATH *)(void *)path; 176 if (usb->DeviceClass == 3 && /* HID */ 177 usb->DeviceSubClass == 1 && /* Boot devices */ 178 usb->DeviceProtocol == 1) { /* Boot keyboards */ 179 retval = true; 180 goto out; 181 } 182 } 183 path = NextDevicePathNode(path); 184 } 185 } 186 out: 187 free(hin); 188 return retval; 189 } 190 191 static void 192 set_currdev_devdesc(struct devdesc *currdev) 193 { 194 const char *devname; 195 196 devname = devformat(currdev); 197 printf("Setting currdev to %s\n", devname); 198 set_currdev(devname); 199 } 200 201 static void 202 set_currdev_devsw(struct devsw *dev, int unit) 203 { 204 struct devdesc currdev; 205 206 currdev.d_dev = dev; 207 currdev.d_unit = unit; 208 209 set_currdev_devdesc(&currdev); 210 } 211 212 static void 213 set_currdev_pdinfo(pdinfo_t *dp) 214 { 215 216 /* 217 * Disks are special: they have partitions. if the parent 218 * pointer is non-null, we're a partition not a full disk 219 * and we need to adjust currdev appropriately. 220 */ 221 if (dp->pd_devsw->dv_type == DEVT_DISK) { 222 struct disk_devdesc currdev; 223 224 currdev.dd.d_dev = dp->pd_devsw; 225 if (dp->pd_parent == NULL) { 226 currdev.dd.d_unit = dp->pd_unit; 227 currdev.d_slice = D_SLICENONE; 228 currdev.d_partition = D_PARTNONE; 229 } else { 230 currdev.dd.d_unit = dp->pd_parent->pd_unit; 231 currdev.d_slice = dp->pd_unit; 232 currdev.d_partition = D_PARTISGPT; /* XXX Assumes GPT */ 233 } 234 set_currdev_devdesc((struct devdesc *)&currdev); 235 } else { 236 set_currdev_devsw(dp->pd_devsw, dp->pd_unit); 237 } 238 } 239 240 static bool 241 sanity_check_currdev(void) 242 { 243 struct stat st; 244 245 return (stat(PATH_DEFAULTS_LOADER_CONF, &st) == 0 || 246 #ifdef PATH_BOOTABLE_TOKEN 247 stat(PATH_BOOTABLE_TOKEN, &st) == 0 || /* non-standard layout */ 248 #endif 249 stat(PATH_KERNEL, &st) == 0); 250 } 251 252 #ifdef EFI_ZFS_BOOT 253 static bool 254 probe_zfs_currdev(uint64_t guid) 255 { 256 char buf[VDEV_PAD_SIZE]; 257 char *devname; 258 struct zfs_devdesc currdev; 259 260 currdev.dd.d_dev = &zfs_dev; 261 currdev.dd.d_unit = 0; 262 currdev.pool_guid = guid; 263 currdev.root_guid = 0; 264 devname = devformat(&currdev.dd); 265 set_currdev(devname); 266 printf("Setting currdev to %s\n", devname); 267 init_zfs_boot_options(devname); 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 return (sanity_check_currdev()); 277 } 278 #endif 279 280 #ifdef MD_IMAGE_SIZE 281 extern struct devsw md_dev; 282 283 static bool 284 probe_md_currdev(void) 285 { 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. Also check for ConIn as well. This will 727 * be enough to determine if we have serial, and if we don't, we default 728 * to video. If there's a dual-console situation with ConIn, this will 729 * currently fail. 730 */ 731 int 732 parse_uefi_con_out(void) 733 { 734 int how, rv; 735 int vid_seen = 0, com_seen = 0, seen = 0; 736 size_t sz; 737 char buf[4096], *ep; 738 EFI_DEVICE_PATH *node; 739 ACPI_HID_DEVICE_PATH *acpi; 740 UART_DEVICE_PATH *uart; 741 bool pci_pending; 742 743 how = 0; 744 sz = sizeof(buf); 745 rv = efi_global_getenv("ConOut", buf, &sz); 746 if (rv != EFI_SUCCESS) 747 rv = efi_global_getenv("ConOutDev", buf, &sz); 748 if (rv != EFI_SUCCESS) 749 rv = efi_global_getenv("ConIn", buf, &sz); 750 if (rv != EFI_SUCCESS) { 751 /* 752 * If we don't have any ConOut default to both. If we have GOP 753 * make video primary, otherwise just make serial primary. In 754 * either case, try to use both the 'efi' console which will use 755 * the GOP, if present and serial. If there's an EFI BIOS that 756 * omits this, but has a serial port redirect, we'll 757 * unavioidably get doubled characters (but we'll be right in 758 * all the other more common cases). 759 */ 760 if (efi_has_gop()) 761 how = RB_MULTIPLE; 762 else 763 how = RB_MULTIPLE | RB_SERIAL; 764 setenv("console", "efi,comconsole", 1); 765 goto out; 766 } 767 ep = buf + sz; 768 node = (EFI_DEVICE_PATH *)buf; 769 while ((char *)node < ep) { 770 if (IsDevicePathEndType(node)) { 771 if (pci_pending && vid_seen == 0) 772 vid_seen = ++seen; 773 } 774 pci_pending = false; 775 if (DevicePathType(node) == ACPI_DEVICE_PATH && 776 (DevicePathSubType(node) == ACPI_DP || 777 DevicePathSubType(node) == ACPI_EXTENDED_DP)) { 778 /* Check for Serial node */ 779 acpi = (void *)node; 780 if (EISA_ID_TO_NUM(acpi->HID) == 0x501) { 781 setenv_int("efi_8250_uid", acpi->UID); 782 com_seen = ++seen; 783 } 784 } else if (DevicePathType(node) == MESSAGING_DEVICE_PATH && 785 DevicePathSubType(node) == MSG_UART_DP) { 786 com_seen = ++seen; 787 uart = (void *)node; 788 setenv_int("efi_com_speed", uart->BaudRate); 789 } else if (DevicePathType(node) == ACPI_DEVICE_PATH && 790 DevicePathSubType(node) == ACPI_ADR_DP) { 791 /* Check for AcpiAdr() Node for video */ 792 vid_seen = ++seen; 793 } else if (DevicePathType(node) == HARDWARE_DEVICE_PATH && 794 DevicePathSubType(node) == HW_PCI_DP) { 795 /* 796 * Note, vmware fusion has a funky console device 797 * PciRoot(0x0)/Pci(0xf,0x0) 798 * which we can only detect at the end since we also 799 * have to cope with: 800 * PciRoot(0x0)/Pci(0x1f,0x0)/Serial(0x1) 801 * so only match it if it's last. 802 */ 803 pci_pending = true; 804 } 805 node = NextDevicePathNode(node); 806 } 807 808 /* 809 * Truth table for RB_MULTIPLE | RB_SERIAL 810 * Value Result 811 * 0 Use only video console 812 * RB_SERIAL Use only serial console 813 * RB_MULTIPLE Use both video and serial console 814 * (but video is primary so gets rc messages) 815 * both Use both video and serial console 816 * (but serial is primary so gets rc messages) 817 * 818 * Try to honor this as best we can. If only one of serial / video 819 * found, then use that. Otherwise, use the first one we found. 820 * This also implies if we found nothing, default to video. 821 */ 822 how = 0; 823 if (vid_seen && com_seen) { 824 how |= RB_MULTIPLE; 825 if (com_seen < vid_seen) 826 how |= RB_SERIAL; 827 } else if (com_seen) 828 how |= RB_SERIAL; 829 out: 830 return (how); 831 } 832 833 void 834 parse_loader_efi_config(EFI_HANDLE h, const char *env_fn) 835 { 836 pdinfo_t *dp; 837 struct stat st; 838 int fd = -1; 839 char *env = NULL; 840 841 dp = efiblk_get_pdinfo_by_handle(h); 842 if (dp == NULL) 843 return; 844 set_currdev_pdinfo(dp); 845 if (stat(env_fn, &st) != 0) 846 return; 847 fd = open(env_fn, O_RDONLY); 848 if (fd == -1) 849 return; 850 env = malloc(st.st_size + 1); 851 if (env == NULL) 852 goto out; 853 if (read(fd, env, st.st_size) != st.st_size) 854 goto out; 855 env[st.st_size] = '\0'; 856 boot_parse_cmdline(env); 857 out: 858 free(env); 859 close(fd); 860 } 861 862 static void 863 read_loader_env(const char *name, char *def_fn, bool once) 864 { 865 UINTN len; 866 char *fn, *freeme = NULL; 867 868 len = 0; 869 fn = def_fn; 870 if (efi_freebsd_getenv(name, NULL, &len) == EFI_BUFFER_TOO_SMALL) { 871 freeme = fn = malloc(len + 1); 872 if (fn != NULL) { 873 if (efi_freebsd_getenv(name, fn, &len) != EFI_SUCCESS) { 874 free(fn); 875 fn = NULL; 876 printf( 877 "Can't fetch FreeBSD::%s we know is there\n", name); 878 } else { 879 /* 880 * if tagged as 'once' delete the env variable so we 881 * only use it once. 882 */ 883 if (once) 884 efi_freebsd_delenv(name); 885 /* 886 * We malloced 1 more than len above, then redid the call. 887 * so now we have room at the end of the string to NUL terminate 888 * it here, even if the typical idium would have '- 1' here to 889 * not overflow. len should be the same on return both times. 890 */ 891 fn[len] = '\0'; 892 } 893 } else { 894 printf( 895 "Can't allocate %d bytes to fetch FreeBSD::%s env var\n", 896 len, name); 897 } 898 } 899 if (fn) { 900 printf(" Reading loader env vars from %s\n", fn); 901 parse_loader_efi_config(boot_img->DeviceHandle, fn); 902 } 903 } 904 905 caddr_t 906 ptov(uintptr_t x) 907 { 908 return ((caddr_t)x); 909 } 910 911 static void 912 acpi_detect(void) 913 { 914 ACPI_TABLE_RSDP *rsdp; 915 char buf[24]; 916 int revision; 917 918 feature_enable(FEATURE_EARLY_ACPI); 919 if ((rsdp = efi_get_table(&acpi20)) == NULL) 920 if ((rsdp = efi_get_table(&acpi)) == NULL) 921 return; 922 923 sprintf(buf, "0x%016llx", (unsigned long long)rsdp); 924 setenv("acpi.rsdp", buf, 1); 925 revision = rsdp->Revision; 926 if (revision == 0) 927 revision = 1; 928 sprintf(buf, "%d", revision); 929 setenv("acpi.revision", buf, 1); 930 strncpy(buf, rsdp->OemId, sizeof(rsdp->OemId)); 931 buf[sizeof(rsdp->OemId)] = '\0'; 932 setenv("acpi.oem", buf, 1); 933 sprintf(buf, "0x%016x", rsdp->RsdtPhysicalAddress); 934 setenv("acpi.rsdt", buf, 1); 935 if (revision >= 2) { 936 /* XXX extended checksum? */ 937 sprintf(buf, "0x%016llx", 938 (unsigned long long)rsdp->XsdtPhysicalAddress); 939 setenv("acpi.xsdt", buf, 1); 940 sprintf(buf, "%d", rsdp->Length); 941 setenv("acpi.xsdt_length", buf, 1); 942 } 943 } 944 945 EFI_STATUS 946 main(int argc, CHAR16 *argv[]) 947 { 948 EFI_GUID *guid; 949 int howto, i, uhowto; 950 UINTN k; 951 bool has_kbd, is_last; 952 char *s; 953 EFI_DEVICE_PATH *imgpath; 954 CHAR16 *text; 955 EFI_STATUS rv; 956 size_t sz, bosz = 0, bisz = 0; 957 UINT16 boot_order[100]; 958 char boot_info[4096]; 959 char buf[32]; 960 bool uefi_boot_mgr; 961 962 archsw.arch_autoload = efi_autoload; 963 archsw.arch_getdev = efi_getdev; 964 archsw.arch_copyin = efi_copyin; 965 archsw.arch_copyout = efi_copyout; 966 #ifdef __amd64__ 967 archsw.arch_hypervisor = x86_hypervisor; 968 #endif 969 archsw.arch_readin = efi_readin; 970 archsw.arch_zfs_probe = efi_zfs_probe; 971 972 #if !defined(__arm__) 973 for (k = 0; k < ST->NumberOfTableEntries; k++) { 974 guid = &ST->ConfigurationTable[k].VendorGuid; 975 if (!memcmp(guid, &smbios, sizeof(EFI_GUID)) || 976 !memcmp(guid, &smbios3, sizeof(EFI_GUID))) { 977 char buf[40]; 978 979 snprintf(buf, sizeof(buf), "%p", 980 ST->ConfigurationTable[k].VendorTable); 981 setenv("hint.smbios.0.mem", buf, 1); 982 smbios_detect(ST->ConfigurationTable[k].VendorTable); 983 break; 984 } 985 } 986 #endif 987 988 /* Get our loaded image protocol interface structure. */ 989 (void) OpenProtocolByHandle(IH, &imgid, (void **)&boot_img); 990 991 /* Report the RSDP early. */ 992 acpi_detect(); 993 994 /* 995 * Chicken-and-egg problem; we want to have console output early, but 996 * some console attributes may depend on reading from eg. the boot 997 * device, which we can't do yet. We can use printf() etc. once this is 998 * done. So, we set it to the efi console, then call console init. This 999 * gets us printf early, but also primes the pump for all future console 1000 * changes to take effect, regardless of where they come from. 1001 */ 1002 setenv("console", "efi", 1); 1003 uhowto = parse_uefi_con_out(); 1004 #if defined(__riscv) 1005 /* 1006 * This workaround likely is papering over a real issue 1007 */ 1008 if ((uhowto & RB_SERIAL) != 0) 1009 setenv("console", "comconsole", 1); 1010 #endif 1011 cons_probe(); 1012 1013 /* Set up currdev variable to have hooks in place. */ 1014 env_setenv("currdev", EV_VOLATILE, "", gen_setcurrdev, env_nounset); 1015 1016 /* Init the time source */ 1017 efi_time_init(); 1018 1019 /* 1020 * Initialise the block cache. Set the upper limit. 1021 */ 1022 bcache_init(32768, 512); 1023 1024 /* 1025 * Scan the BLOCK IO MEDIA handles then 1026 * march through the device switch probing for things. 1027 */ 1028 i = efipart_inithandles(); 1029 if (i != 0 && i != ENOENT) { 1030 printf("efipart_inithandles failed with ERRNO %d, expect " 1031 "failures\n", i); 1032 } 1033 1034 devinit(); 1035 1036 /* 1037 * Detect console settings two different ways: one via the command 1038 * args (eg -h) or via the UEFI ConOut variable. 1039 */ 1040 has_kbd = has_keyboard(); 1041 howto = parse_args(argc, argv); 1042 if (!has_kbd && (howto & RB_PROBE)) 1043 howto |= RB_SERIAL | RB_MULTIPLE; 1044 howto &= ~RB_PROBE; 1045 1046 /* 1047 * Read additional environment variables from the boot device's 1048 * "LoaderEnv" file. Any boot loader environment variable may be set 1049 * there, which are subtly different than loader.conf variables. Only 1050 * the 'simple' ones may be set so things like foo_load="YES" won't work 1051 * for two reasons. First, the parser is simplistic and doesn't grok 1052 * quotes. Second, because the variables that cause an action to happen 1053 * are parsed by the lua, 4th or whatever code that's not yet 1054 * loaded. This is relative to the root directory when loader.efi is 1055 * loaded off the UFS root drive (when chain booted), or from the ESP 1056 * when directly loaded by the BIOS. 1057 * 1058 * We also read in NextLoaderEnv if it was specified. This allows next boot 1059 * functionality to be implemented and to override anything in LoaderEnv. 1060 */ 1061 read_loader_env("LoaderEnv", "/efi/freebsd/loader.env", false); 1062 read_loader_env("NextLoaderEnv", NULL, true); 1063 1064 /* 1065 * We now have two notions of console. howto should be viewed as 1066 * overrides. If console is already set, don't set it again. 1067 */ 1068 #define VIDEO_ONLY 0 1069 #define SERIAL_ONLY RB_SERIAL 1070 #define VID_SER_BOTH RB_MULTIPLE 1071 #define SER_VID_BOTH (RB_SERIAL | RB_MULTIPLE) 1072 #define CON_MASK (RB_SERIAL | RB_MULTIPLE) 1073 if (strcmp(getenv("console"), "efi") == 0) { 1074 if ((howto & CON_MASK) == 0) { 1075 /* No override, uhowto is controlling and efi cons is perfect */ 1076 howto = howto | (uhowto & CON_MASK); 1077 } else if ((howto & CON_MASK) == (uhowto & CON_MASK)) { 1078 /* override matches what UEFI told us, efi console is perfect */ 1079 } else if ((uhowto & (CON_MASK)) != 0) { 1080 /* 1081 * We detected a serial console on ConOut. All possible 1082 * overrides include serial. We can't really override what efi 1083 * gives us, so we use it knowing it's the best choice. 1084 */ 1085 /* Do nothing */ 1086 } else { 1087 /* 1088 * We detected some kind of serial in the override, but ConOut 1089 * has no serial, so we have to sort out which case it really is. 1090 */ 1091 switch (howto & CON_MASK) { 1092 case SERIAL_ONLY: 1093 setenv("console", "comconsole", 1); 1094 break; 1095 case VID_SER_BOTH: 1096 setenv("console", "efi comconsole", 1); 1097 break; 1098 case SER_VID_BOTH: 1099 setenv("console", "comconsole efi", 1); 1100 break; 1101 /* case VIDEO_ONLY can't happen -- it's the first if above */ 1102 } 1103 } 1104 } 1105 1106 /* 1107 * howto is set now how we want to export the flags to the kernel, so 1108 * set the env based on it. 1109 */ 1110 boot_howto_to_env(howto); 1111 1112 if (efi_copy_init()) 1113 return (EFI_BUFFER_TOO_SMALL); 1114 1115 if ((s = getenv("fail_timeout")) != NULL) 1116 fail_timeout = strtol(s, NULL, 10); 1117 1118 printf("%s\n", bootprog_info); 1119 printf(" Command line arguments:"); 1120 for (i = 0; i < argc; i++) 1121 printf(" %S", argv[i]); 1122 printf("\n"); 1123 1124 printf(" Image base: 0x%lx\n", (unsigned long)boot_img->ImageBase); 1125 printf(" EFI version: %d.%02d\n", ST->Hdr.Revision >> 16, 1126 ST->Hdr.Revision & 0xffff); 1127 printf(" EFI Firmware: %S (rev %d.%02d)\n", ST->FirmwareVendor, 1128 ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff); 1129 printf(" Console: %s (%#x)\n", getenv("console"), howto); 1130 1131 /* Determine the devpath of our image so we can prefer it. */ 1132 text = efi_devpath_name(boot_img->FilePath); 1133 if (text != NULL) { 1134 printf(" Load Path: %S\n", text); 1135 efi_setenv_freebsd_wcs("LoaderPath", text); 1136 efi_free_devpath_name(text); 1137 } 1138 1139 rv = OpenProtocolByHandle(boot_img->DeviceHandle, &devid, 1140 (void **)&imgpath); 1141 if (rv == EFI_SUCCESS) { 1142 text = efi_devpath_name(imgpath); 1143 if (text != NULL) { 1144 printf(" Load Device: %S\n", text); 1145 efi_setenv_freebsd_wcs("LoaderDev", text); 1146 efi_free_devpath_name(text); 1147 } 1148 } 1149 1150 if (getenv("uefi_ignore_boot_mgr") != NULL) { 1151 printf(" Ignoring UEFI boot manager\n"); 1152 uefi_boot_mgr = false; 1153 } else { 1154 uefi_boot_mgr = true; 1155 boot_current = 0; 1156 sz = sizeof(boot_current); 1157 rv = efi_global_getenv("BootCurrent", &boot_current, &sz); 1158 if (rv == EFI_SUCCESS) 1159 printf(" BootCurrent: %04x\n", boot_current); 1160 else { 1161 boot_current = 0xffff; 1162 uefi_boot_mgr = false; 1163 } 1164 1165 sz = sizeof(boot_order); 1166 rv = efi_global_getenv("BootOrder", &boot_order, &sz); 1167 if (rv == EFI_SUCCESS) { 1168 printf(" BootOrder:"); 1169 for (i = 0; i < sz / sizeof(boot_order[0]); i++) 1170 printf(" %04x%s", boot_order[i], 1171 boot_order[i] == boot_current ? "[*]" : ""); 1172 printf("\n"); 1173 is_last = boot_order[(sz / sizeof(boot_order[0])) - 1] == boot_current; 1174 bosz = sz; 1175 } else if (uefi_boot_mgr) { 1176 /* 1177 * u-boot doesn't set BootOrder, but otherwise participates in the 1178 * boot manager protocol. So we fake it here and don't consider it 1179 * a failure. 1180 */ 1181 bosz = sizeof(boot_order[0]); 1182 boot_order[0] = boot_current; 1183 is_last = true; 1184 } 1185 } 1186 1187 /* 1188 * Next, find the boot info structure the UEFI boot manager is 1189 * supposed to setup. We need this so we can walk through it to 1190 * find where we are in the booting process and what to try to 1191 * boot next. 1192 */ 1193 if (uefi_boot_mgr) { 1194 snprintf(buf, sizeof(buf), "Boot%04X", boot_current); 1195 sz = sizeof(boot_info); 1196 rv = efi_global_getenv(buf, &boot_info, &sz); 1197 if (rv == EFI_SUCCESS) 1198 bisz = sz; 1199 else 1200 uefi_boot_mgr = false; 1201 } 1202 1203 /* 1204 * Disable the watchdog timer. By default the boot manager sets 1205 * the timer to 5 minutes before invoking a boot option. If we 1206 * want to return to the boot manager, we have to disable the 1207 * watchdog timer and since we're an interactive program, we don't 1208 * want to wait until the user types "quit". The timer may have 1209 * fired by then. We don't care if this fails. It does not prevent 1210 * normal functioning in any way... 1211 */ 1212 BS->SetWatchdogTimer(0, 0, 0, NULL); 1213 1214 /* 1215 * Initialize the trusted/forbidden certificates from UEFI. 1216 * They will be later used to verify the manifest(s), 1217 * which should contain hashes of verified files. 1218 * This needs to be initialized before any configuration files 1219 * are loaded. 1220 */ 1221 #ifdef EFI_SECUREBOOT 1222 ve_efi_init(); 1223 #endif 1224 1225 /* 1226 * Try and find a good currdev based on the image that was booted. 1227 * It might be desirable here to have a short pause to allow falling 1228 * through to the boot loader instead of returning instantly to follow 1229 * the boot protocol and also allow an escape hatch for users wishing 1230 * to try something different. 1231 */ 1232 if (find_currdev(uefi_boot_mgr, is_last, boot_info, bisz) != 0) 1233 if (uefi_boot_mgr && 1234 !interactive_interrupt("Failed to find bootable partition")) 1235 return (EFI_NOT_FOUND); 1236 1237 autoload_font(false); /* Set up the font list for console. */ 1238 efi_init_environment(); 1239 1240 interact(); /* doesn't return */ 1241 1242 return (EFI_SUCCESS); /* keep compiler happy */ 1243 } 1244 1245 COMMAND_SET(efi_seed_entropy, "efi-seed-entropy", "try to get entropy from the EFI RNG", command_seed_entropy); 1246 1247 static int 1248 command_seed_entropy(int argc, char *argv[]) 1249 { 1250 EFI_STATUS status; 1251 EFI_RNG_PROTOCOL *rng; 1252 unsigned int size = 2048; 1253 void *buf; 1254 1255 if (argc > 1) { 1256 size = strtol(argv[1], NULL, 0); 1257 } 1258 1259 status = BS->LocateProtocol(&rng_guid, NULL, (VOID **)&rng); 1260 if (status != EFI_SUCCESS) { 1261 command_errmsg = "RNG protocol not found"; 1262 return (CMD_ERROR); 1263 } 1264 1265 if ((buf = malloc(size)) == NULL) { 1266 command_errmsg = "out of memory"; 1267 return (CMD_ERROR); 1268 } 1269 1270 status = rng->GetRNG(rng, NULL, size, (UINT8 *)buf); 1271 if (status != EFI_SUCCESS) { 1272 free(buf); 1273 command_errmsg = "GetRNG failed"; 1274 return (CMD_ERROR); 1275 } 1276 1277 if (file_addbuf("efi_rng_seed", "boot_entropy_platform", size, buf) != 0) { 1278 free(buf); 1279 return (CMD_ERROR); 1280 } 1281 1282 free(buf); 1283 return (CMD_OK); 1284 } 1285 1286 COMMAND_SET(poweroff, "poweroff", "power off the system", command_poweroff); 1287 1288 static int 1289 command_poweroff(int argc __unused, char *argv[] __unused) 1290 { 1291 int i; 1292 1293 for (i = 0; devsw[i] != NULL; ++i) 1294 if (devsw[i]->dv_cleanup != NULL) 1295 (devsw[i]->dv_cleanup)(); 1296 1297 RS->ResetSystem(EfiResetShutdown, EFI_SUCCESS, 0, NULL); 1298 1299 /* NOTREACHED */ 1300 return (CMD_ERROR); 1301 } 1302 1303 COMMAND_SET(reboot, "reboot", "reboot the system", command_reboot); 1304 1305 static int 1306 command_reboot(int argc, char *argv[]) 1307 { 1308 int i; 1309 1310 for (i = 0; devsw[i] != NULL; ++i) 1311 if (devsw[i]->dv_cleanup != NULL) 1312 (devsw[i]->dv_cleanup)(); 1313 1314 RS->ResetSystem(EfiResetCold, EFI_SUCCESS, 0, NULL); 1315 1316 /* NOTREACHED */ 1317 return (CMD_ERROR); 1318 } 1319 1320 COMMAND_SET(memmap, "memmap", "print memory map", command_memmap); 1321 1322 static int 1323 command_memmap(int argc __unused, char *argv[] __unused) 1324 { 1325 UINTN sz; 1326 EFI_MEMORY_DESCRIPTOR *map, *p; 1327 UINTN key, dsz; 1328 UINT32 dver; 1329 EFI_STATUS status; 1330 int i, ndesc; 1331 char line[80]; 1332 1333 sz = 0; 1334 status = BS->GetMemoryMap(&sz, 0, &key, &dsz, &dver); 1335 if (status != EFI_BUFFER_TOO_SMALL) { 1336 printf("Can't determine memory map size\n"); 1337 return (CMD_ERROR); 1338 } 1339 map = malloc(sz); 1340 status = BS->GetMemoryMap(&sz, map, &key, &dsz, &dver); 1341 if (EFI_ERROR(status)) { 1342 printf("Can't read memory map\n"); 1343 return (CMD_ERROR); 1344 } 1345 1346 ndesc = sz / dsz; 1347 snprintf(line, sizeof(line), "%23s %12s %12s %8s %4s\n", 1348 "Type", "Physical", "Virtual", "#Pages", "Attr"); 1349 pager_open(); 1350 if (pager_output(line)) { 1351 pager_close(); 1352 return (CMD_OK); 1353 } 1354 1355 for (i = 0, p = map; i < ndesc; 1356 i++, p = NextMemoryDescriptor(p, dsz)) { 1357 snprintf(line, sizeof(line), "%23s %012jx %012jx %08jx ", 1358 efi_memory_type(p->Type), (uintmax_t)p->PhysicalStart, 1359 (uintmax_t)p->VirtualStart, (uintmax_t)p->NumberOfPages); 1360 if (pager_output(line)) 1361 break; 1362 1363 if (p->Attribute & EFI_MEMORY_UC) 1364 printf("UC "); 1365 if (p->Attribute & EFI_MEMORY_WC) 1366 printf("WC "); 1367 if (p->Attribute & EFI_MEMORY_WT) 1368 printf("WT "); 1369 if (p->Attribute & EFI_MEMORY_WB) 1370 printf("WB "); 1371 if (p->Attribute & EFI_MEMORY_UCE) 1372 printf("UCE "); 1373 if (p->Attribute & EFI_MEMORY_WP) 1374 printf("WP "); 1375 if (p->Attribute & EFI_MEMORY_RP) 1376 printf("RP "); 1377 if (p->Attribute & EFI_MEMORY_XP) 1378 printf("XP "); 1379 if (p->Attribute & EFI_MEMORY_NV) 1380 printf("NV "); 1381 if (p->Attribute & EFI_MEMORY_MORE_RELIABLE) 1382 printf("MR "); 1383 if (p->Attribute & EFI_MEMORY_RO) 1384 printf("RO "); 1385 if (pager_output("\n")) 1386 break; 1387 } 1388 1389 pager_close(); 1390 return (CMD_OK); 1391 } 1392 1393 COMMAND_SET(configuration, "configuration", "print configuration tables", 1394 command_configuration); 1395 1396 static int 1397 command_configuration(int argc, char *argv[]) 1398 { 1399 UINTN i; 1400 char *name; 1401 1402 printf("NumberOfTableEntries=%lu\n", 1403 (unsigned long)ST->NumberOfTableEntries); 1404 1405 for (i = 0; i < ST->NumberOfTableEntries; i++) { 1406 EFI_GUID *guid; 1407 1408 printf(" "); 1409 guid = &ST->ConfigurationTable[i].VendorGuid; 1410 1411 if (efi_guid_to_name(guid, &name) == true) { 1412 printf(name); 1413 free(name); 1414 } else { 1415 printf("Error while translating UUID to name"); 1416 } 1417 printf(" at %p\n", ST->ConfigurationTable[i].VendorTable); 1418 } 1419 1420 return (CMD_OK); 1421 } 1422 1423 1424 COMMAND_SET(mode, "mode", "change or display EFI text modes", command_mode); 1425 1426 static int 1427 command_mode(int argc, char *argv[]) 1428 { 1429 UINTN cols, rows; 1430 unsigned int mode; 1431 int i; 1432 char *cp; 1433 EFI_STATUS status; 1434 SIMPLE_TEXT_OUTPUT_INTERFACE *conout; 1435 1436 conout = ST->ConOut; 1437 1438 if (argc > 1) { 1439 mode = strtol(argv[1], &cp, 0); 1440 if (cp[0] != '\0') { 1441 printf("Invalid mode\n"); 1442 return (CMD_ERROR); 1443 } 1444 status = conout->QueryMode(conout, mode, &cols, &rows); 1445 if (EFI_ERROR(status)) { 1446 printf("invalid mode %d\n", mode); 1447 return (CMD_ERROR); 1448 } 1449 status = conout->SetMode(conout, mode); 1450 if (EFI_ERROR(status)) { 1451 printf("couldn't set mode %d\n", mode); 1452 return (CMD_ERROR); 1453 } 1454 (void) cons_update_mode(true); 1455 return (CMD_OK); 1456 } 1457 1458 printf("Current mode: %d\n", conout->Mode->Mode); 1459 for (i = 0; i <= conout->Mode->MaxMode; i++) { 1460 status = conout->QueryMode(conout, i, &cols, &rows); 1461 if (EFI_ERROR(status)) 1462 continue; 1463 printf("Mode %d: %u columns, %u rows\n", i, (unsigned)cols, 1464 (unsigned)rows); 1465 } 1466 1467 if (i != 0) 1468 printf("Select a mode with the command \"mode <number>\"\n"); 1469 1470 return (CMD_OK); 1471 } 1472 1473 COMMAND_SET(lsefi, "lsefi", "list EFI handles", command_lsefi); 1474 1475 static void 1476 lsefi_print_handle_info(EFI_HANDLE handle) 1477 { 1478 EFI_DEVICE_PATH *devpath; 1479 EFI_DEVICE_PATH *imagepath; 1480 CHAR16 *dp_name; 1481 1482 imagepath = efi_lookup_image_devpath(handle); 1483 if (imagepath != NULL) { 1484 dp_name = efi_devpath_name(imagepath); 1485 printf("Handle for image %S", dp_name); 1486 efi_free_devpath_name(dp_name); 1487 return; 1488 } 1489 devpath = efi_lookup_devpath(handle); 1490 if (devpath != NULL) { 1491 dp_name = efi_devpath_name(devpath); 1492 printf("Handle for device %S", dp_name); 1493 efi_free_devpath_name(dp_name); 1494 return; 1495 } 1496 printf("Handle %p", handle); 1497 } 1498 1499 static int 1500 command_lsefi(int argc __unused, char *argv[] __unused) 1501 { 1502 char *name; 1503 EFI_HANDLE *buffer = NULL; 1504 EFI_HANDLE handle; 1505 UINTN bufsz = 0, i, j; 1506 EFI_STATUS status; 1507 int ret = 0; 1508 1509 status = BS->LocateHandle(AllHandles, NULL, NULL, &bufsz, buffer); 1510 if (status != EFI_BUFFER_TOO_SMALL) { 1511 snprintf(command_errbuf, sizeof (command_errbuf), 1512 "unexpected error: %lld", (long long)status); 1513 return (CMD_ERROR); 1514 } 1515 if ((buffer = malloc(bufsz)) == NULL) { 1516 sprintf(command_errbuf, "out of memory"); 1517 return (CMD_ERROR); 1518 } 1519 1520 status = BS->LocateHandle(AllHandles, NULL, NULL, &bufsz, buffer); 1521 if (EFI_ERROR(status)) { 1522 free(buffer); 1523 snprintf(command_errbuf, sizeof (command_errbuf), 1524 "LocateHandle() error: %lld", (long long)status); 1525 return (CMD_ERROR); 1526 } 1527 1528 pager_open(); 1529 for (i = 0; i < (bufsz / sizeof (EFI_HANDLE)); i++) { 1530 UINTN nproto = 0; 1531 EFI_GUID **protocols = NULL; 1532 1533 handle = buffer[i]; 1534 lsefi_print_handle_info(handle); 1535 if (pager_output("\n")) 1536 break; 1537 /* device path */ 1538 1539 status = BS->ProtocolsPerHandle(handle, &protocols, &nproto); 1540 if (EFI_ERROR(status)) { 1541 snprintf(command_errbuf, sizeof (command_errbuf), 1542 "ProtocolsPerHandle() error: %lld", 1543 (long long)status); 1544 continue; 1545 } 1546 1547 for (j = 0; j < nproto; j++) { 1548 if (efi_guid_to_name(protocols[j], &name) == true) { 1549 printf(" %s", name); 1550 free(name); 1551 } else { 1552 printf("Error while translating UUID to name"); 1553 } 1554 if ((ret = pager_output("\n")) != 0) 1555 break; 1556 } 1557 BS->FreePool(protocols); 1558 if (ret != 0) 1559 break; 1560 } 1561 pager_close(); 1562 free(buffer); 1563 return (CMD_OK); 1564 } 1565 1566 #ifdef LOADER_FDT_SUPPORT 1567 extern int command_fdt_internal(int argc, char *argv[]); 1568 1569 /* 1570 * Since proper fdt command handling function is defined in fdt_loader_cmd.c, 1571 * and declaring it as extern is in contradiction with COMMAND_SET() macro 1572 * (which uses static pointer), we're defining wrapper function, which 1573 * calls the proper fdt handling routine. 1574 */ 1575 static int 1576 command_fdt(int argc, char *argv[]) 1577 { 1578 1579 return (command_fdt_internal(argc, argv)); 1580 } 1581 1582 COMMAND_SET(fdt, "fdt", "flattened device tree handling", command_fdt); 1583 #endif 1584 1585 /* 1586 * Chain load another efi loader. 1587 */ 1588 static int 1589 command_chain(int argc, char *argv[]) 1590 { 1591 EFI_GUID LoadedImageGUID = LOADED_IMAGE_PROTOCOL; 1592 EFI_HANDLE loaderhandle; 1593 EFI_LOADED_IMAGE *loaded_image; 1594 EFI_STATUS status; 1595 struct stat st; 1596 struct devdesc *dev; 1597 char *name, *path; 1598 void *buf; 1599 int fd; 1600 1601 if (argc < 2) { 1602 command_errmsg = "wrong number of arguments"; 1603 return (CMD_ERROR); 1604 } 1605 1606 name = argv[1]; 1607 1608 if ((fd = open(name, O_RDONLY)) < 0) { 1609 command_errmsg = "no such file"; 1610 return (CMD_ERROR); 1611 } 1612 1613 #ifdef LOADER_VERIEXEC 1614 if (verify_file(fd, name, 0, VE_MUST, __func__) < 0) { 1615 sprintf(command_errbuf, "can't verify: %s", name); 1616 close(fd); 1617 return (CMD_ERROR); 1618 } 1619 #endif 1620 1621 if (fstat(fd, &st) < -1) { 1622 command_errmsg = "stat failed"; 1623 close(fd); 1624 return (CMD_ERROR); 1625 } 1626 1627 status = BS->AllocatePool(EfiLoaderCode, (UINTN)st.st_size, &buf); 1628 if (status != EFI_SUCCESS) { 1629 command_errmsg = "failed to allocate buffer"; 1630 close(fd); 1631 return (CMD_ERROR); 1632 } 1633 if (read(fd, buf, st.st_size) != st.st_size) { 1634 command_errmsg = "error while reading the file"; 1635 (void)BS->FreePool(buf); 1636 close(fd); 1637 return (CMD_ERROR); 1638 } 1639 close(fd); 1640 status = BS->LoadImage(FALSE, IH, NULL, buf, st.st_size, &loaderhandle); 1641 (void)BS->FreePool(buf); 1642 if (status != EFI_SUCCESS) { 1643 command_errmsg = "LoadImage failed"; 1644 return (CMD_ERROR); 1645 } 1646 status = OpenProtocolByHandle(loaderhandle, &LoadedImageGUID, 1647 (void **)&loaded_image); 1648 1649 if (argc > 2) { 1650 int i, len = 0; 1651 CHAR16 *argp; 1652 1653 for (i = 2; i < argc; i++) 1654 len += strlen(argv[i]) + 1; 1655 1656 len *= sizeof (*argp); 1657 loaded_image->LoadOptions = argp = malloc (len); 1658 loaded_image->LoadOptionsSize = len; 1659 for (i = 2; i < argc; i++) { 1660 char *ptr = argv[i]; 1661 while (*ptr) 1662 *(argp++) = *(ptr++); 1663 *(argp++) = ' '; 1664 } 1665 *(--argv) = 0; 1666 } 1667 1668 if (efi_getdev((void **)&dev, name, (const char **)&path) == 0) { 1669 #ifdef EFI_ZFS_BOOT 1670 struct zfs_devdesc *z_dev; 1671 #endif 1672 struct disk_devdesc *d_dev; 1673 pdinfo_t *hd, *pd; 1674 1675 switch (dev->d_dev->dv_type) { 1676 #ifdef EFI_ZFS_BOOT 1677 case DEVT_ZFS: 1678 z_dev = (struct zfs_devdesc *)dev; 1679 loaded_image->DeviceHandle = 1680 efizfs_get_handle_by_guid(z_dev->pool_guid); 1681 break; 1682 #endif 1683 case DEVT_NET: 1684 loaded_image->DeviceHandle = 1685 efi_find_handle(dev->d_dev, dev->d_unit); 1686 break; 1687 default: 1688 hd = efiblk_get_pdinfo(dev); 1689 if (STAILQ_EMPTY(&hd->pd_part)) { 1690 loaded_image->DeviceHandle = hd->pd_handle; 1691 break; 1692 } 1693 d_dev = (struct disk_devdesc *)dev; 1694 STAILQ_FOREACH(pd, &hd->pd_part, pd_link) { 1695 /* 1696 * d_partition should be 255 1697 */ 1698 if (pd->pd_unit == (uint32_t)d_dev->d_slice) { 1699 loaded_image->DeviceHandle = 1700 pd->pd_handle; 1701 break; 1702 } 1703 } 1704 break; 1705 } 1706 } 1707 1708 dev_cleanup(); 1709 status = BS->StartImage(loaderhandle, NULL, NULL); 1710 if (status != EFI_SUCCESS) { 1711 command_errmsg = "StartImage failed"; 1712 free(loaded_image->LoadOptions); 1713 loaded_image->LoadOptions = NULL; 1714 status = BS->UnloadImage(loaded_image); 1715 return (CMD_ERROR); 1716 } 1717 1718 return (CMD_ERROR); /* not reached */ 1719 } 1720 1721 COMMAND_SET(chain, "chain", "chain load file", command_chain); 1722 1723 extern struct in_addr servip; 1724 static int 1725 command_netserver(int argc, char *argv[]) 1726 { 1727 char *proto; 1728 n_long rootaddr; 1729 1730 if (argc > 2) { 1731 command_errmsg = "wrong number of arguments"; 1732 return (CMD_ERROR); 1733 } 1734 if (argc < 2) { 1735 proto = netproto == NET_TFTP ? "tftp://" : "nfs://"; 1736 printf("Netserver URI: %s%s%s\n", proto, intoa(rootip.s_addr), 1737 rootpath); 1738 return (CMD_OK); 1739 } 1740 if (argc == 2) { 1741 strncpy(rootpath, argv[1], sizeof(rootpath)); 1742 rootpath[sizeof(rootpath) -1] = '\0'; 1743 if ((rootaddr = net_parse_rootpath()) != INADDR_NONE) 1744 servip.s_addr = rootip.s_addr = rootaddr; 1745 return (CMD_OK); 1746 } 1747 return (CMD_ERROR); /* not reached */ 1748 1749 } 1750 1751 COMMAND_SET(netserver, "netserver", "change or display netserver URI", 1752 command_netserver); 1753