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