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 !memcmp(guid, &smbios3, sizeof(EFI_GUID))) { 1192 char buf[40]; 1193 1194 snprintf(buf, sizeof(buf), "%p", 1195 ST->ConfigurationTable[k].VendorTable); 1196 setenv("hint.smbios.0.mem", buf, 1); 1197 smbios_detect(ST->ConfigurationTable[k].VendorTable); 1198 break; 1199 } 1200 } 1201 #endif 1202 1203 interact(); /* doesn't return */ 1204 1205 return (EFI_SUCCESS); /* keep compiler happy */ 1206 } 1207 1208 COMMAND_SET(efi_seed_entropy, "efi-seed-entropy", "try to get entropy from the EFI RNG", command_seed_entropy); 1209 1210 static int 1211 command_seed_entropy(int argc, char *argv[]) 1212 { 1213 EFI_STATUS status; 1214 EFI_RNG_PROTOCOL *rng; 1215 unsigned int size = 2048; 1216 void *buf; 1217 1218 if (argc > 1) { 1219 size = strtol(argv[1], NULL, 0); 1220 } 1221 1222 status = BS->LocateProtocol(&rng_guid, NULL, (VOID **)&rng); 1223 if (status != EFI_SUCCESS) { 1224 command_errmsg = "RNG protocol not found"; 1225 return (CMD_ERROR); 1226 } 1227 1228 if ((buf = malloc(size)) == NULL) { 1229 command_errmsg = "out of memory"; 1230 return (CMD_ERROR); 1231 } 1232 1233 status = rng->GetRNG(rng, NULL, size, (UINT8 *)buf); 1234 if (status != EFI_SUCCESS) { 1235 free(buf); 1236 command_errmsg = "GetRNG failed"; 1237 return (CMD_ERROR); 1238 } 1239 1240 if (file_addbuf("efi_rng_seed", "boot_entropy_platform", size, buf) != 0) { 1241 free(buf); 1242 return (CMD_ERROR); 1243 } 1244 1245 free(buf); 1246 return (CMD_OK); 1247 } 1248 1249 COMMAND_SET(poweroff, "poweroff", "power off the system", command_poweroff); 1250 1251 static int 1252 command_poweroff(int argc __unused, char *argv[] __unused) 1253 { 1254 int i; 1255 1256 for (i = 0; devsw[i] != NULL; ++i) 1257 if (devsw[i]->dv_cleanup != NULL) 1258 (devsw[i]->dv_cleanup)(); 1259 1260 RS->ResetSystem(EfiResetShutdown, EFI_SUCCESS, 0, NULL); 1261 1262 /* NOTREACHED */ 1263 return (CMD_ERROR); 1264 } 1265 1266 COMMAND_SET(reboot, "reboot", "reboot the system", command_reboot); 1267 1268 static int 1269 command_reboot(int argc, char *argv[]) 1270 { 1271 int i; 1272 1273 for (i = 0; devsw[i] != NULL; ++i) 1274 if (devsw[i]->dv_cleanup != NULL) 1275 (devsw[i]->dv_cleanup)(); 1276 1277 RS->ResetSystem(EfiResetCold, EFI_SUCCESS, 0, NULL); 1278 1279 /* NOTREACHED */ 1280 return (CMD_ERROR); 1281 } 1282 1283 COMMAND_SET(memmap, "memmap", "print memory map", command_memmap); 1284 1285 static int 1286 command_memmap(int argc __unused, char *argv[] __unused) 1287 { 1288 UINTN sz; 1289 EFI_MEMORY_DESCRIPTOR *map, *p; 1290 UINTN key, dsz; 1291 UINT32 dver; 1292 EFI_STATUS status; 1293 int i, ndesc; 1294 char line[80]; 1295 1296 sz = 0; 1297 status = BS->GetMemoryMap(&sz, 0, &key, &dsz, &dver); 1298 if (status != EFI_BUFFER_TOO_SMALL) { 1299 printf("Can't determine memory map size\n"); 1300 return (CMD_ERROR); 1301 } 1302 map = malloc(sz); 1303 status = BS->GetMemoryMap(&sz, map, &key, &dsz, &dver); 1304 if (EFI_ERROR(status)) { 1305 printf("Can't read memory map\n"); 1306 return (CMD_ERROR); 1307 } 1308 1309 ndesc = sz / dsz; 1310 snprintf(line, sizeof(line), "%23s %12s %12s %8s %4s\n", 1311 "Type", "Physical", "Virtual", "#Pages", "Attr"); 1312 pager_open(); 1313 if (pager_output(line)) { 1314 pager_close(); 1315 return (CMD_OK); 1316 } 1317 1318 for (i = 0, p = map; i < ndesc; 1319 i++, p = NextMemoryDescriptor(p, dsz)) { 1320 snprintf(line, sizeof(line), "%23s %012jx %012jx %08jx ", 1321 efi_memory_type(p->Type), (uintmax_t)p->PhysicalStart, 1322 (uintmax_t)p->VirtualStart, (uintmax_t)p->NumberOfPages); 1323 if (pager_output(line)) 1324 break; 1325 1326 if (p->Attribute & EFI_MEMORY_UC) 1327 printf("UC "); 1328 if (p->Attribute & EFI_MEMORY_WC) 1329 printf("WC "); 1330 if (p->Attribute & EFI_MEMORY_WT) 1331 printf("WT "); 1332 if (p->Attribute & EFI_MEMORY_WB) 1333 printf("WB "); 1334 if (p->Attribute & EFI_MEMORY_UCE) 1335 printf("UCE "); 1336 if (p->Attribute & EFI_MEMORY_WP) 1337 printf("WP "); 1338 if (p->Attribute & EFI_MEMORY_RP) 1339 printf("RP "); 1340 if (p->Attribute & EFI_MEMORY_XP) 1341 printf("XP "); 1342 if (p->Attribute & EFI_MEMORY_NV) 1343 printf("NV "); 1344 if (p->Attribute & EFI_MEMORY_MORE_RELIABLE) 1345 printf("MR "); 1346 if (p->Attribute & EFI_MEMORY_RO) 1347 printf("RO "); 1348 if (pager_output("\n")) 1349 break; 1350 } 1351 1352 pager_close(); 1353 return (CMD_OK); 1354 } 1355 1356 COMMAND_SET(configuration, "configuration", "print configuration tables", 1357 command_configuration); 1358 1359 static int 1360 command_configuration(int argc, char *argv[]) 1361 { 1362 UINTN i; 1363 char *name; 1364 1365 printf("NumberOfTableEntries=%lu\n", 1366 (unsigned long)ST->NumberOfTableEntries); 1367 1368 for (i = 0; i < ST->NumberOfTableEntries; i++) { 1369 EFI_GUID *guid; 1370 1371 printf(" "); 1372 guid = &ST->ConfigurationTable[i].VendorGuid; 1373 1374 if (efi_guid_to_name(guid, &name) == true) { 1375 printf(name); 1376 free(name); 1377 } else { 1378 printf("Error while translating UUID to name"); 1379 } 1380 printf(" at %p\n", ST->ConfigurationTable[i].VendorTable); 1381 } 1382 1383 return (CMD_OK); 1384 } 1385 1386 1387 COMMAND_SET(mode, "mode", "change or display EFI text modes", command_mode); 1388 1389 static int 1390 command_mode(int argc, char *argv[]) 1391 { 1392 UINTN cols, rows; 1393 unsigned int mode; 1394 int i; 1395 char *cp; 1396 EFI_STATUS status; 1397 SIMPLE_TEXT_OUTPUT_INTERFACE *conout; 1398 1399 conout = ST->ConOut; 1400 1401 if (argc > 1) { 1402 mode = strtol(argv[1], &cp, 0); 1403 if (cp[0] != '\0') { 1404 printf("Invalid mode\n"); 1405 return (CMD_ERROR); 1406 } 1407 status = conout->QueryMode(conout, mode, &cols, &rows); 1408 if (EFI_ERROR(status)) { 1409 printf("invalid mode %d\n", mode); 1410 return (CMD_ERROR); 1411 } 1412 status = conout->SetMode(conout, mode); 1413 if (EFI_ERROR(status)) { 1414 printf("couldn't set mode %d\n", mode); 1415 return (CMD_ERROR); 1416 } 1417 (void) cons_update_mode(true); 1418 return (CMD_OK); 1419 } 1420 1421 printf("Current mode: %d\n", conout->Mode->Mode); 1422 for (i = 0; i <= conout->Mode->MaxMode; i++) { 1423 status = conout->QueryMode(conout, i, &cols, &rows); 1424 if (EFI_ERROR(status)) 1425 continue; 1426 printf("Mode %d: %u columns, %u rows\n", i, (unsigned)cols, 1427 (unsigned)rows); 1428 } 1429 1430 if (i != 0) 1431 printf("Select a mode with the command \"mode <number>\"\n"); 1432 1433 return (CMD_OK); 1434 } 1435 1436 COMMAND_SET(lsefi, "lsefi", "list EFI handles", command_lsefi); 1437 1438 static void 1439 lsefi_print_handle_info(EFI_HANDLE handle) 1440 { 1441 EFI_DEVICE_PATH *devpath; 1442 EFI_DEVICE_PATH *imagepath; 1443 CHAR16 *dp_name; 1444 1445 imagepath = efi_lookup_image_devpath(handle); 1446 if (imagepath != NULL) { 1447 dp_name = efi_devpath_name(imagepath); 1448 printf("Handle for image %S", dp_name); 1449 efi_free_devpath_name(dp_name); 1450 return; 1451 } 1452 devpath = efi_lookup_devpath(handle); 1453 if (devpath != NULL) { 1454 dp_name = efi_devpath_name(devpath); 1455 printf("Handle for device %S", dp_name); 1456 efi_free_devpath_name(dp_name); 1457 return; 1458 } 1459 printf("Handle %p", handle); 1460 } 1461 1462 static int 1463 command_lsefi(int argc __unused, char *argv[] __unused) 1464 { 1465 char *name; 1466 EFI_HANDLE *buffer = NULL; 1467 EFI_HANDLE handle; 1468 UINTN bufsz = 0, i, j; 1469 EFI_STATUS status; 1470 int ret = 0; 1471 1472 status = BS->LocateHandle(AllHandles, NULL, NULL, &bufsz, buffer); 1473 if (status != EFI_BUFFER_TOO_SMALL) { 1474 snprintf(command_errbuf, sizeof (command_errbuf), 1475 "unexpected error: %lld", (long long)status); 1476 return (CMD_ERROR); 1477 } 1478 if ((buffer = malloc(bufsz)) == NULL) { 1479 sprintf(command_errbuf, "out of memory"); 1480 return (CMD_ERROR); 1481 } 1482 1483 status = BS->LocateHandle(AllHandles, NULL, NULL, &bufsz, buffer); 1484 if (EFI_ERROR(status)) { 1485 free(buffer); 1486 snprintf(command_errbuf, sizeof (command_errbuf), 1487 "LocateHandle() error: %lld", (long long)status); 1488 return (CMD_ERROR); 1489 } 1490 1491 pager_open(); 1492 for (i = 0; i < (bufsz / sizeof (EFI_HANDLE)); i++) { 1493 UINTN nproto = 0; 1494 EFI_GUID **protocols = NULL; 1495 1496 handle = buffer[i]; 1497 lsefi_print_handle_info(handle); 1498 if (pager_output("\n")) 1499 break; 1500 /* device path */ 1501 1502 status = BS->ProtocolsPerHandle(handle, &protocols, &nproto); 1503 if (EFI_ERROR(status)) { 1504 snprintf(command_errbuf, sizeof (command_errbuf), 1505 "ProtocolsPerHandle() error: %lld", 1506 (long long)status); 1507 continue; 1508 } 1509 1510 for (j = 0; j < nproto; j++) { 1511 if (efi_guid_to_name(protocols[j], &name) == true) { 1512 printf(" %s", name); 1513 free(name); 1514 } else { 1515 printf("Error while translating UUID to name"); 1516 } 1517 if ((ret = pager_output("\n")) != 0) 1518 break; 1519 } 1520 BS->FreePool(protocols); 1521 if (ret != 0) 1522 break; 1523 } 1524 pager_close(); 1525 free(buffer); 1526 return (CMD_OK); 1527 } 1528 1529 #ifdef LOADER_FDT_SUPPORT 1530 extern int command_fdt_internal(int argc, char *argv[]); 1531 1532 /* 1533 * Since proper fdt command handling function is defined in fdt_loader_cmd.c, 1534 * and declaring it as extern is in contradiction with COMMAND_SET() macro 1535 * (which uses static pointer), we're defining wrapper function, which 1536 * calls the proper fdt handling routine. 1537 */ 1538 static int 1539 command_fdt(int argc, char *argv[]) 1540 { 1541 1542 return (command_fdt_internal(argc, argv)); 1543 } 1544 1545 COMMAND_SET(fdt, "fdt", "flattened device tree handling", command_fdt); 1546 #endif 1547 1548 /* 1549 * Chain load another efi loader. 1550 */ 1551 static int 1552 command_chain(int argc, char *argv[]) 1553 { 1554 EFI_GUID LoadedImageGUID = LOADED_IMAGE_PROTOCOL; 1555 EFI_HANDLE loaderhandle; 1556 EFI_LOADED_IMAGE *loaded_image; 1557 EFI_STATUS status; 1558 struct stat st; 1559 struct devdesc *dev; 1560 char *name, *path; 1561 void *buf; 1562 int fd; 1563 1564 if (argc < 2) { 1565 command_errmsg = "wrong number of arguments"; 1566 return (CMD_ERROR); 1567 } 1568 1569 name = argv[1]; 1570 1571 if ((fd = open(name, O_RDONLY)) < 0) { 1572 command_errmsg = "no such file"; 1573 return (CMD_ERROR); 1574 } 1575 1576 #ifdef LOADER_VERIEXEC 1577 if (verify_file(fd, name, 0, VE_MUST, __func__) < 0) { 1578 sprintf(command_errbuf, "can't verify: %s", name); 1579 close(fd); 1580 return (CMD_ERROR); 1581 } 1582 #endif 1583 1584 if (fstat(fd, &st) < -1) { 1585 command_errmsg = "stat failed"; 1586 close(fd); 1587 return (CMD_ERROR); 1588 } 1589 1590 status = BS->AllocatePool(EfiLoaderCode, (UINTN)st.st_size, &buf); 1591 if (status != EFI_SUCCESS) { 1592 command_errmsg = "failed to allocate buffer"; 1593 close(fd); 1594 return (CMD_ERROR); 1595 } 1596 if (read(fd, buf, st.st_size) != st.st_size) { 1597 command_errmsg = "error while reading the file"; 1598 (void)BS->FreePool(buf); 1599 close(fd); 1600 return (CMD_ERROR); 1601 } 1602 close(fd); 1603 status = BS->LoadImage(FALSE, IH, NULL, buf, st.st_size, &loaderhandle); 1604 (void)BS->FreePool(buf); 1605 if (status != EFI_SUCCESS) { 1606 command_errmsg = "LoadImage failed"; 1607 return (CMD_ERROR); 1608 } 1609 status = OpenProtocolByHandle(loaderhandle, &LoadedImageGUID, 1610 (void **)&loaded_image); 1611 1612 if (argc > 2) { 1613 int i, len = 0; 1614 CHAR16 *argp; 1615 1616 for (i = 2; i < argc; i++) 1617 len += strlen(argv[i]) + 1; 1618 1619 len *= sizeof (*argp); 1620 loaded_image->LoadOptions = argp = malloc (len); 1621 loaded_image->LoadOptionsSize = len; 1622 for (i = 2; i < argc; i++) { 1623 char *ptr = argv[i]; 1624 while (*ptr) 1625 *(argp++) = *(ptr++); 1626 *(argp++) = ' '; 1627 } 1628 *(--argv) = 0; 1629 } 1630 1631 if (efi_getdev((void **)&dev, name, (const char **)&path) == 0) { 1632 #ifdef EFI_ZFS_BOOT 1633 struct zfs_devdesc *z_dev; 1634 #endif 1635 struct disk_devdesc *d_dev; 1636 pdinfo_t *hd, *pd; 1637 1638 switch (dev->d_dev->dv_type) { 1639 #ifdef EFI_ZFS_BOOT 1640 case DEVT_ZFS: 1641 z_dev = (struct zfs_devdesc *)dev; 1642 loaded_image->DeviceHandle = 1643 efizfs_get_handle_by_guid(z_dev->pool_guid); 1644 break; 1645 #endif 1646 case DEVT_NET: 1647 loaded_image->DeviceHandle = 1648 efi_find_handle(dev->d_dev, dev->d_unit); 1649 break; 1650 default: 1651 hd = efiblk_get_pdinfo(dev); 1652 if (STAILQ_EMPTY(&hd->pd_part)) { 1653 loaded_image->DeviceHandle = hd->pd_handle; 1654 break; 1655 } 1656 d_dev = (struct disk_devdesc *)dev; 1657 STAILQ_FOREACH(pd, &hd->pd_part, pd_link) { 1658 /* 1659 * d_partition should be 255 1660 */ 1661 if (pd->pd_unit == (uint32_t)d_dev->d_slice) { 1662 loaded_image->DeviceHandle = 1663 pd->pd_handle; 1664 break; 1665 } 1666 } 1667 break; 1668 } 1669 } 1670 1671 dev_cleanup(); 1672 status = BS->StartImage(loaderhandle, NULL, NULL); 1673 if (status != EFI_SUCCESS) { 1674 command_errmsg = "StartImage failed"; 1675 free(loaded_image->LoadOptions); 1676 loaded_image->LoadOptions = NULL; 1677 status = BS->UnloadImage(loaded_image); 1678 return (CMD_ERROR); 1679 } 1680 1681 return (CMD_ERROR); /* not reached */ 1682 } 1683 1684 COMMAND_SET(chain, "chain", "chain load file", command_chain); 1685 1686 extern struct in_addr servip; 1687 static int 1688 command_netserver(int argc, char *argv[]) 1689 { 1690 char *proto; 1691 n_long rootaddr; 1692 1693 if (argc > 2) { 1694 command_errmsg = "wrong number of arguments"; 1695 return (CMD_ERROR); 1696 } 1697 if (argc < 2) { 1698 proto = netproto == NET_TFTP ? "tftp://" : "nfs://"; 1699 printf("Netserver URI: %s%s%s\n", proto, intoa(rootip.s_addr), 1700 rootpath); 1701 return (CMD_OK); 1702 } 1703 if (argc == 2) { 1704 strncpy(rootpath, argv[1], sizeof(rootpath)); 1705 rootpath[sizeof(rootpath) -1] = '\0'; 1706 if ((rootaddr = net_parse_rootpath()) != INADDR_NONE) 1707 servip.s_addr = rootip.s_addr = rootaddr; 1708 return (CMD_OK); 1709 } 1710 return (CMD_ERROR); /* not reached */ 1711 1712 } 1713 1714 COMMAND_SET(netserver, "netserver", "change or display netserver URI", 1715 command_netserver); 1716