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