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