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 64 #include "loader_efi.h" 65 66 struct arch_switch archsw; /* MI/MD interface boundary */ 67 68 EFI_GUID acpi = ACPI_TABLE_GUID; 69 EFI_GUID acpi20 = ACPI_20_TABLE_GUID; 70 EFI_GUID devid = DEVICE_PATH_PROTOCOL; 71 EFI_GUID imgid = LOADED_IMAGE_PROTOCOL; 72 EFI_GUID mps = MPS_TABLE_GUID; 73 EFI_GUID netid = EFI_SIMPLE_NETWORK_PROTOCOL; 74 EFI_GUID smbios = SMBIOS_TABLE_GUID; 75 EFI_GUID smbios3 = SMBIOS3_TABLE_GUID; 76 EFI_GUID dxe = DXE_SERVICES_TABLE_GUID; 77 EFI_GUID hoblist = HOB_LIST_TABLE_GUID; 78 EFI_GUID lzmadecomp = LZMA_DECOMPRESSION_GUID; 79 EFI_GUID mpcore = ARM_MP_CORE_INFO_TABLE_GUID; 80 EFI_GUID esrt = ESRT_TABLE_GUID; 81 EFI_GUID memtype = MEMORY_TYPE_INFORMATION_TABLE_GUID; 82 EFI_GUID debugimg = DEBUG_IMAGE_INFO_TABLE_GUID; 83 EFI_GUID fdtdtb = FDT_TABLE_GUID; 84 EFI_GUID inputid = SIMPLE_TEXT_INPUT_PROTOCOL; 85 86 /* 87 * Number of seconds to wait for a keystroke before exiting with failure 88 * in the event no currdev is found. -2 means always break, -1 means 89 * never break, 0 means poll once and then reboot, > 0 means wait for 90 * that many seconds. "fail_timeout" can be set in the environment as 91 * well. 92 */ 93 static int fail_timeout = 5; 94 95 /* 96 * Current boot variable 97 */ 98 UINT16 boot_current; 99 100 /* 101 * Image that we booted from. 102 */ 103 EFI_LOADED_IMAGE *boot_img; 104 105 static bool 106 has_keyboard(void) 107 { 108 EFI_STATUS status; 109 EFI_DEVICE_PATH *path; 110 EFI_HANDLE *hin, *hin_end, *walker; 111 UINTN sz; 112 bool retval = false; 113 114 /* 115 * Find all the handles that support the SIMPLE_TEXT_INPUT_PROTOCOL and 116 * do the typical dance to get the right sized buffer. 117 */ 118 sz = 0; 119 hin = NULL; 120 status = BS->LocateHandle(ByProtocol, &inputid, 0, &sz, 0); 121 if (status == EFI_BUFFER_TOO_SMALL) { 122 hin = (EFI_HANDLE *)malloc(sz); 123 status = BS->LocateHandle(ByProtocol, &inputid, 0, &sz, 124 hin); 125 if (EFI_ERROR(status)) 126 free(hin); 127 } 128 if (EFI_ERROR(status)) 129 return retval; 130 131 /* 132 * Look at each of the handles. If it supports the device path protocol, 133 * use it to get the device path for this handle. Then see if that 134 * device path matches either the USB device path for keyboards or the 135 * legacy device path for keyboards. 136 */ 137 hin_end = &hin[sz / sizeof(*hin)]; 138 for (walker = hin; walker < hin_end; walker++) { 139 status = OpenProtocolByHandle(*walker, &devid, (void **)&path); 140 if (EFI_ERROR(status)) 141 continue; 142 143 while (!IsDevicePathEnd(path)) { 144 /* 145 * Check for the ACPI keyboard node. All PNP3xx nodes 146 * are keyboards of different flavors. Note: It is 147 * unclear of there's always a keyboard node when 148 * there's a keyboard controller, or if there's only one 149 * when a keyboard is detected at boot. 150 */ 151 if (DevicePathType(path) == ACPI_DEVICE_PATH && 152 (DevicePathSubType(path) == ACPI_DP || 153 DevicePathSubType(path) == ACPI_EXTENDED_DP)) { 154 ACPI_HID_DEVICE_PATH *acpi; 155 156 acpi = (ACPI_HID_DEVICE_PATH *)(void *)path; 157 if ((EISA_ID_TO_NUM(acpi->HID) & 0xff00) == 0x300 && 158 (acpi->HID & 0xffff) == PNP_EISA_ID_CONST) { 159 retval = true; 160 goto out; 161 } 162 /* 163 * Check for USB keyboard node, if present. Unlike a 164 * PS/2 keyboard, these definitely only appear when 165 * connected to the system. 166 */ 167 } else if (DevicePathType(path) == MESSAGING_DEVICE_PATH && 168 DevicePathSubType(path) == MSG_USB_CLASS_DP) { 169 USB_CLASS_DEVICE_PATH *usb; 170 171 usb = (USB_CLASS_DEVICE_PATH *)(void *)path; 172 if (usb->DeviceClass == 3 && /* HID */ 173 usb->DeviceSubClass == 1 && /* Boot devices */ 174 usb->DeviceProtocol == 1) { /* Boot keyboards */ 175 retval = true; 176 goto out; 177 } 178 } 179 path = NextDevicePathNode(path); 180 } 181 } 182 out: 183 free(hin); 184 return retval; 185 } 186 187 static void 188 set_currdev(const char *devname) 189 { 190 191 env_setenv("currdev", EV_VOLATILE, devname, efi_setcurrdev, 192 env_nounset); 193 /* 194 * Don't execute hook here; the loaddev hook makes it immutable 195 * once we've determined what the proper currdev is. 196 */ 197 env_setenv("loaddev", EV_VOLATILE | EV_NOHOOK, devname, env_noset, 198 env_nounset); 199 } 200 201 static void 202 set_currdev_devdesc(struct devdesc *currdev) 203 { 204 const char *devname; 205 206 devname = devformat(currdev); 207 printf("Setting currdev to %s\n", devname); 208 set_currdev(devname); 209 } 210 211 static void 212 set_currdev_devsw(struct devsw *dev, int unit) 213 { 214 struct devdesc currdev; 215 216 currdev.d_dev = dev; 217 currdev.d_unit = unit; 218 219 set_currdev_devdesc(&currdev); 220 } 221 222 static void 223 set_currdev_pdinfo(pdinfo_t *dp) 224 { 225 226 /* 227 * Disks are special: they have partitions. if the parent 228 * pointer is non-null, we're a partition not a full disk 229 * and we need to adjust currdev appropriately. 230 */ 231 if (dp->pd_devsw->dv_type == DEVT_DISK) { 232 struct disk_devdesc currdev; 233 234 currdev.dd.d_dev = dp->pd_devsw; 235 if (dp->pd_parent == NULL) { 236 currdev.dd.d_unit = dp->pd_unit; 237 currdev.d_slice = D_SLICENONE; 238 currdev.d_partition = D_PARTNONE; 239 } else { 240 currdev.dd.d_unit = dp->pd_parent->pd_unit; 241 currdev.d_slice = dp->pd_unit; 242 currdev.d_partition = D_PARTISGPT; /* XXX Assumes GPT */ 243 } 244 set_currdev_devdesc((struct devdesc *)&currdev); 245 } else { 246 set_currdev_devsw(dp->pd_devsw, dp->pd_unit); 247 } 248 } 249 250 static bool 251 sanity_check_currdev(void) 252 { 253 struct stat st; 254 255 return (stat(PATH_DEFAULTS_LOADER_CONF, &st) == 0 || 256 #ifdef PATH_BOOTABLE_TOKEN 257 stat(PATH_BOOTABLE_TOKEN, &st) == 0 || /* non-standard layout */ 258 #endif 259 stat(PATH_KERNEL, &st) == 0); 260 } 261 262 #ifdef EFI_ZFS_BOOT 263 static bool 264 probe_zfs_currdev(uint64_t guid) 265 { 266 char *devname; 267 struct zfs_devdesc currdev; 268 char *buf = NULL; 269 bool rv; 270 271 currdev.dd.d_dev = &zfs_dev; 272 currdev.dd.d_unit = 0; 273 currdev.pool_guid = guid; 274 currdev.root_guid = 0; 275 set_currdev_devdesc((struct devdesc *)&currdev); 276 devname = devformat(&currdev.dd); 277 init_zfs_boot_options(devname); 278 279 rv = sanity_check_currdev(); 280 if (rv) { 281 buf = malloc(VDEV_PAD_SIZE); 282 if (buf != NULL) { 283 if (zfs_get_bootonce(&currdev, OS_BOOTONCE, buf, 284 VDEV_PAD_SIZE) == 0) { 285 printf("zfs bootonce: %s\n", buf); 286 set_currdev(buf); 287 setenv("zfs-bootonce", buf, 1); 288 } 289 free(buf); 290 (void) zfs_attach_nvstore(&currdev); 291 } 292 } 293 return (rv); 294 } 295 #endif 296 297 #ifdef MD_IMAGE_SIZE 298 static bool 299 probe_md_currdev(void) 300 { 301 extern struct devsw md_dev; 302 bool rv; 303 304 set_currdev_devsw(&md_dev, 0); 305 rv = sanity_check_currdev(); 306 if (!rv) 307 printf("MD not present\n"); 308 return (rv); 309 } 310 #endif 311 312 static bool 313 try_as_currdev(pdinfo_t *hd, pdinfo_t *pp) 314 { 315 uint64_t guid; 316 317 #ifdef EFI_ZFS_BOOT 318 /* 319 * If there's a zpool on this device, try it as a ZFS 320 * filesystem, which has somewhat different setup than all 321 * other types of fs due to imperfect loader integration. 322 * This all stems from ZFS being both a device (zpool) and 323 * a filesystem, plus the boot env feature. 324 */ 325 if (efizfs_get_guid_by_handle(pp->pd_handle, &guid)) 326 return (probe_zfs_currdev(guid)); 327 #endif 328 /* 329 * All other filesystems just need the pdinfo 330 * initialized in the standard way. 331 */ 332 set_currdev_pdinfo(pp); 333 return (sanity_check_currdev()); 334 } 335 336 /* 337 * Sometimes we get filenames that are all upper case 338 * and/or have backslashes in them. Filter all this out 339 * if it looks like we need to do so. 340 */ 341 static void 342 fix_dosisms(char *p) 343 { 344 while (*p) { 345 if (isupper(*p)) 346 *p = tolower(*p); 347 else if (*p == '\\') 348 *p = '/'; 349 p++; 350 } 351 } 352 353 #define SIZE(dp, edp) (size_t)((intptr_t)(void *)edp - (intptr_t)(void *)dp) 354 355 enum { BOOT_INFO_OK = 0, BAD_CHOICE = 1, NOT_SPECIFIC = 2 }; 356 static int 357 match_boot_info(char *boot_info, size_t bisz) 358 { 359 uint32_t attr; 360 uint16_t fplen; 361 size_t len; 362 char *walker, *ep; 363 EFI_DEVICE_PATH *dp, *edp, *first_dp, *last_dp; 364 pdinfo_t *pp; 365 CHAR16 *descr; 366 char *kernel = NULL; 367 FILEPATH_DEVICE_PATH *fp; 368 struct stat st; 369 CHAR16 *text; 370 371 /* 372 * FreeBSD encodes its boot loading path into the boot loader 373 * BootXXXX variable. We look for the last one in the path 374 * and use that to load the kernel. However, if we only find 375 * one DEVICE_PATH, then there's nothing specific and we should 376 * fall back. 377 * 378 * In an ideal world, we'd look at the image handle we were 379 * passed, match up with the loader we are and then return the 380 * next one in the path. This would be most flexible and cover 381 * many chain booting scenarios where you need to use this 382 * boot loader to get to the next boot loader. However, that 383 * doesn't work. We rarely have the path to the image booted 384 * (just the device) so we can't count on that. So, we do the 385 * next best thing: we look through the device path(s) passed 386 * in the BootXXXX variable. If there's only one, we return 387 * NOT_SPECIFIC. Otherwise, we look at the last one and try to 388 * load that. If we can, we return BOOT_INFO_OK. Otherwise we 389 * return BAD_CHOICE for the caller to sort out. 390 */ 391 if (bisz < sizeof(attr) + sizeof(fplen) + sizeof(CHAR16)) 392 return NOT_SPECIFIC; 393 walker = boot_info; 394 ep = walker + bisz; 395 memcpy(&attr, walker, sizeof(attr)); 396 walker += sizeof(attr); 397 memcpy(&fplen, walker, sizeof(fplen)); 398 walker += sizeof(fplen); 399 descr = (CHAR16 *)(intptr_t)walker; 400 len = ucs2len(descr); 401 walker += (len + 1) * sizeof(CHAR16); 402 last_dp = first_dp = dp = (EFI_DEVICE_PATH *)walker; 403 edp = (EFI_DEVICE_PATH *)(walker + fplen); 404 if ((char *)edp > ep) 405 return NOT_SPECIFIC; 406 while (dp < edp && SIZE(dp, edp) > sizeof(EFI_DEVICE_PATH)) { 407 text = efi_devpath_name(dp); 408 if (text != NULL) { 409 printf(" BootInfo Path: %S\n", text); 410 efi_free_devpath_name(text); 411 } 412 last_dp = dp; 413 dp = (EFI_DEVICE_PATH *)((char *)dp + efi_devpath_length(dp)); 414 } 415 416 /* 417 * If there's only one item in the list, then nothing was 418 * specified. Or if the last path doesn't have a media 419 * path in it. Those show up as various VenHw() nodes 420 * which are basically opaque to us. Don't count those 421 * as something specifc. 422 */ 423 if (last_dp == first_dp) { 424 printf("Ignoring Boot%04x: Only one DP found\n", boot_current); 425 return NOT_SPECIFIC; 426 } 427 if (efi_devpath_to_media_path(last_dp) == NULL) { 428 printf("Ignoring Boot%04x: No Media Path\n", boot_current); 429 return NOT_SPECIFIC; 430 } 431 432 /* 433 * OK. At this point we either have a good path or a bad one. 434 * Let's check. 435 */ 436 pp = efiblk_get_pdinfo_by_device_path(last_dp); 437 if (pp == NULL) { 438 printf("Ignoring Boot%04x: Device Path not found\n", boot_current); 439 return BAD_CHOICE; 440 } 441 set_currdev_pdinfo(pp); 442 if (!sanity_check_currdev()) { 443 printf("Ignoring Boot%04x: sanity check failed\n", boot_current); 444 return BAD_CHOICE; 445 } 446 447 /* 448 * OK. We've found a device that matches, next we need to check the last 449 * component of the path. If it's a file, then we set the default kernel 450 * to that. Otherwise, just use this as the default root. 451 * 452 * Reminder: we're running very early, before we've parsed the defaults 453 * file, so we may need to have a hack override. 454 */ 455 dp = efi_devpath_last_node(last_dp); 456 if (DevicePathType(dp) != MEDIA_DEVICE_PATH || 457 DevicePathSubType(dp) != MEDIA_FILEPATH_DP) { 458 printf("Using Boot%04x for root partition\n", boot_current); 459 return (BOOT_INFO_OK); /* use currdir, default kernel */ 460 } 461 fp = (FILEPATH_DEVICE_PATH *)dp; 462 ucs2_to_utf8(fp->PathName, &kernel); 463 if (kernel == NULL) { 464 printf("Not using Boot%04x: can't decode kernel\n", boot_current); 465 return (BAD_CHOICE); 466 } 467 if (*kernel == '\\' || isupper(*kernel)) 468 fix_dosisms(kernel); 469 if (stat(kernel, &st) != 0) { 470 free(kernel); 471 printf("Not using Boot%04x: can't find %s\n", boot_current, 472 kernel); 473 return (BAD_CHOICE); 474 } 475 setenv("kernel", kernel, 1); 476 free(kernel); 477 text = efi_devpath_name(last_dp); 478 if (text) { 479 printf("Using Boot%04x %S + %s\n", boot_current, text, 480 kernel); 481 efi_free_devpath_name(text); 482 } 483 484 return (BOOT_INFO_OK); 485 } 486 487 /* 488 * Look at the passed-in boot_info, if any. If we find it then we need 489 * to see if we can find ourselves in the boot chain. If we can, and 490 * there's another specified thing to boot next, assume that the file 491 * is loaded from / and use that for the root filesystem. If can't 492 * find the specified thing, we must fail the boot. If we're last on 493 * the list, then we fallback to looking for the first available / 494 * candidate (ZFS, if there's a bootable zpool, otherwise a UFS 495 * partition that has either /boot/defaults/loader.conf on it or 496 * /boot/kernel/kernel (the default kernel) that we can use. 497 * 498 * We always fail if we can't find the right thing. However, as 499 * a concession to buggy UEFI implementations, like u-boot, if 500 * we have determined that the host is violating the UEFI boot 501 * manager protocol, we'll signal the rest of the program that 502 * a drop to the OK boot loader prompt is possible. 503 */ 504 static int 505 find_currdev(bool do_bootmgr, bool is_last, 506 char *boot_info, size_t boot_info_sz) 507 { 508 pdinfo_t *dp, *pp; 509 EFI_DEVICE_PATH *devpath, *copy; 510 EFI_HANDLE h; 511 CHAR16 *text; 512 struct devsw *dev; 513 int unit; 514 uint64_t extra; 515 int rv; 516 char *rootdev; 517 518 /* 519 * First choice: if rootdev is already set, use that, even if 520 * it's wrong. 521 */ 522 rootdev = getenv("rootdev"); 523 if (rootdev != NULL) { 524 printf(" Setting currdev to configured rootdev %s\n", 525 rootdev); 526 set_currdev(rootdev); 527 return (0); 528 } 529 530 /* 531 * Second choice: If uefi_rootdev is set, translate that UEFI device 532 * path to the loader's internal name and use that. 533 */ 534 do { 535 rootdev = getenv("uefi_rootdev"); 536 if (rootdev == NULL) 537 break; 538 devpath = efi_name_to_devpath(rootdev); 539 if (devpath == NULL) 540 break; 541 dp = efiblk_get_pdinfo_by_device_path(devpath); 542 efi_devpath_free(devpath); 543 if (dp == NULL) 544 break; 545 printf(" Setting currdev to UEFI path %s\n", 546 rootdev); 547 set_currdev_pdinfo(dp); 548 return (0); 549 } while (0); 550 551 /* 552 * Third choice: If we can find out image boot_info, and there's 553 * a follow-on boot image in that boot_info, use that. In this 554 * case root will be the partition specified in that image and 555 * we'll load the kernel specified by the file path. Should there 556 * not be a filepath, we use the default. This filepath overrides 557 * loader.conf. 558 */ 559 if (do_bootmgr) { 560 rv = match_boot_info(boot_info, boot_info_sz); 561 switch (rv) { 562 case BOOT_INFO_OK: /* We found it */ 563 return (0); 564 case BAD_CHOICE: /* specified file not found -> error */ 565 /* XXX do we want to have an escape hatch for last in boot order? */ 566 return (ENOENT); 567 } /* Nothing specified, try normal match */ 568 } 569 570 #ifdef EFI_ZFS_BOOT 571 /* 572 * Did efi_zfs_probe() detect the boot pool? If so, use the zpool 573 * it found, if it's sane. ZFS is the only thing that looks for 574 * disks and pools to boot. This may change in the future, however, 575 * if we allow specifying which pool to boot from via UEFI variables 576 * rather than the bootenv stuff that FreeBSD uses today. 577 */ 578 if (pool_guid != 0) { 579 printf("Trying ZFS pool\n"); 580 if (probe_zfs_currdev(pool_guid)) 581 return (0); 582 } 583 #endif /* EFI_ZFS_BOOT */ 584 585 #ifdef MD_IMAGE_SIZE 586 /* 587 * If there is an embedded MD, try to use that. 588 */ 589 printf("Trying MD\n"); 590 if (probe_md_currdev()) 591 return (0); 592 #endif /* MD_IMAGE_SIZE */ 593 594 /* 595 * Try to find the block device by its handle based on the 596 * image we're booting. If we can't find a sane partition, 597 * search all the other partitions of the disk. We do not 598 * search other disks because it's a violation of the UEFI 599 * boot protocol to do so. We fail and let UEFI go on to 600 * the next candidate. 601 */ 602 dp = efiblk_get_pdinfo_by_handle(boot_img->DeviceHandle); 603 if (dp != NULL) { 604 text = efi_devpath_name(dp->pd_devpath); 605 if (text != NULL) { 606 printf("Trying ESP: %S\n", text); 607 efi_free_devpath_name(text); 608 } 609 set_currdev_pdinfo(dp); 610 if (sanity_check_currdev()) 611 return (0); 612 if (dp->pd_parent != NULL) { 613 pdinfo_t *espdp = dp; 614 dp = dp->pd_parent; 615 STAILQ_FOREACH(pp, &dp->pd_part, pd_link) { 616 /* Already tried the ESP */ 617 if (espdp == pp) 618 continue; 619 /* 620 * Roll up the ZFS special case 621 * for those partitions that have 622 * zpools on them. 623 */ 624 text = efi_devpath_name(pp->pd_devpath); 625 if (text != NULL) { 626 printf("Trying: %S\n", text); 627 efi_free_devpath_name(text); 628 } 629 if (try_as_currdev(dp, pp)) 630 return (0); 631 } 632 } 633 } 634 635 /* 636 * Try the device handle from our loaded image first. If that 637 * fails, use the device path from the loaded image and see if 638 * any of the nodes in that path match one of the enumerated 639 * handles. Currently, this handle list is only for netboot. 640 */ 641 if (efi_handle_lookup(boot_img->DeviceHandle, &dev, &unit, &extra) == 0) { 642 set_currdev_devsw(dev, unit); 643 if (sanity_check_currdev()) 644 return (0); 645 } 646 647 copy = NULL; 648 devpath = efi_lookup_image_devpath(IH); 649 while (devpath != NULL) { 650 h = efi_devpath_handle(devpath); 651 if (h == NULL) 652 break; 653 654 free(copy); 655 copy = NULL; 656 657 if (efi_handle_lookup(h, &dev, &unit, &extra) == 0) { 658 set_currdev_devsw(dev, unit); 659 if (sanity_check_currdev()) 660 return (0); 661 } 662 663 devpath = efi_lookup_devpath(h); 664 if (devpath != NULL) { 665 copy = efi_devpath_trim(devpath); 666 devpath = copy; 667 } 668 } 669 free(copy); 670 671 return (ENOENT); 672 } 673 674 static bool 675 interactive_interrupt(const char *msg) 676 { 677 time_t now, then, last; 678 679 last = 0; 680 now = then = getsecs(); 681 printf("%s\n", msg); 682 if (fail_timeout == -2) /* Always break to OK */ 683 return (true); 684 if (fail_timeout == -1) /* Never break to OK */ 685 return (false); 686 do { 687 if (last != now) { 688 printf("press any key to interrupt reboot in %d seconds\r", 689 fail_timeout - (int)(now - then)); 690 last = now; 691 } 692 693 /* XXX no pause or timeout wait for char */ 694 if (ischar()) 695 return (true); 696 now = getsecs(); 697 } while (now - then < fail_timeout); 698 return (false); 699 } 700 701 static int 702 parse_args(int argc, CHAR16 *argv[]) 703 { 704 int i, j, howto; 705 bool vargood; 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 = 1; 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 /* If we don't have any ConOut default to serial */ 764 how = RB_SERIAL; 765 goto out; 766 } 767 ep = buf + sz; 768 node = (EFI_DEVICE_PATH *)buf; 769 while ((char *)node < ep) { 770 if (IsDevicePathEndType(node)) { 771 if (pci_pending && vid_seen == 0) 772 vid_seen = ++seen; 773 } 774 pci_pending = false; 775 if (DevicePathType(node) == ACPI_DEVICE_PATH && 776 (DevicePathSubType(node) == ACPI_DP || 777 DevicePathSubType(node) == ACPI_EXTENDED_DP)) { 778 /* Check for Serial node */ 779 acpi = (void *)node; 780 if (EISA_ID_TO_NUM(acpi->HID) == 0x501) { 781 setenv_int("efi_8250_uid", acpi->UID); 782 com_seen = ++seen; 783 } 784 } else if (DevicePathType(node) == MESSAGING_DEVICE_PATH && 785 DevicePathSubType(node) == MSG_UART_DP) { 786 com_seen = ++seen; 787 uart = (void *)node; 788 setenv_int("efi_com_speed", uart->BaudRate); 789 } else if (DevicePathType(node) == ACPI_DEVICE_PATH && 790 DevicePathSubType(node) == ACPI_ADR_DP) { 791 /* Check for AcpiAdr() Node for video */ 792 vid_seen = ++seen; 793 } else if (DevicePathType(node) == HARDWARE_DEVICE_PATH && 794 DevicePathSubType(node) == HW_PCI_DP) { 795 /* 796 * Note, vmware fusion has a funky console device 797 * PciRoot(0x0)/Pci(0xf,0x0) 798 * which we can only detect at the end since we also 799 * have to cope with: 800 * PciRoot(0x0)/Pci(0x1f,0x0)/Serial(0x1) 801 * so only match it if it's last. 802 */ 803 pci_pending = true; 804 } 805 node = NextDevicePathNode(node); 806 } 807 808 /* 809 * Truth table for RB_MULTIPLE | RB_SERIAL 810 * Value Result 811 * 0 Use only video console 812 * RB_SERIAL Use only serial console 813 * RB_MULTIPLE Use both video and serial console 814 * (but video is primary so gets rc messages) 815 * both Use both video and serial console 816 * (but serial is primary so gets rc messages) 817 * 818 * Try to honor this as best we can. If only one of serial / video 819 * found, then use that. Otherwise, use the first one we found. 820 * This also implies if we found nothing, default to video. 821 */ 822 how = 0; 823 if (vid_seen && com_seen) { 824 how |= RB_MULTIPLE; 825 if (com_seen < vid_seen) 826 how |= RB_SERIAL; 827 } else if (com_seen) 828 how |= RB_SERIAL; 829 out: 830 return (how); 831 } 832 833 void 834 parse_loader_efi_config(EFI_HANDLE h, const char *env_fn) 835 { 836 pdinfo_t *dp; 837 struct stat st; 838 int fd = -1; 839 char *env = NULL; 840 841 dp = efiblk_get_pdinfo_by_handle(h); 842 if (dp == NULL) 843 return; 844 set_currdev_pdinfo(dp); 845 if (stat(env_fn, &st) != 0) 846 return; 847 fd = open(env_fn, O_RDONLY); 848 if (fd == -1) 849 return; 850 env = malloc(st.st_size + 1); 851 if (env == NULL) 852 goto out; 853 if (read(fd, env, st.st_size) != st.st_size) 854 goto out; 855 env[st.st_size] = '\0'; 856 boot_parse_cmdline(env); 857 out: 858 free(env); 859 close(fd); 860 } 861 862 static void 863 read_loader_env(const char *name, char *def_fn, bool once) 864 { 865 UINTN len; 866 char *fn, *freeme = NULL; 867 868 len = 0; 869 fn = def_fn; 870 if (efi_freebsd_getenv(name, NULL, &len) == EFI_BUFFER_TOO_SMALL) { 871 freeme = fn = malloc(len + 1); 872 if (fn != NULL) { 873 if (efi_freebsd_getenv(name, fn, &len) != EFI_SUCCESS) { 874 free(fn); 875 fn = NULL; 876 printf( 877 "Can't fetch FreeBSD::%s we know is there\n", name); 878 } else { 879 /* 880 * if tagged as 'once' delete the env variable so we 881 * only use it once. 882 */ 883 if (once) 884 efi_freebsd_delenv(name); 885 /* 886 * We malloced 1 more than len above, then redid the call. 887 * so now we have room at the end of the string to NUL terminate 888 * it here, even if the typical idium would have '- 1' here to 889 * not overflow. len should be the same on return both times. 890 */ 891 fn[len] = '\0'; 892 } 893 } else { 894 printf( 895 "Can't allocate %d bytes to fetch FreeBSD::%s env var\n", 896 len, name); 897 } 898 } 899 if (fn) { 900 printf(" Reading loader env vars from %s\n", fn); 901 parse_loader_efi_config(boot_img->DeviceHandle, fn); 902 } 903 } 904 905 caddr_t 906 ptov(uintptr_t x) 907 { 908 return ((caddr_t)x); 909 } 910 911 EFI_STATUS 912 main(int argc, CHAR16 *argv[]) 913 { 914 EFI_GUID *guid; 915 int howto, i, uhowto; 916 UINTN k; 917 bool has_kbd, is_last; 918 char *s; 919 EFI_DEVICE_PATH *imgpath; 920 CHAR16 *text; 921 EFI_STATUS rv; 922 size_t sz, bosz = 0, bisz = 0; 923 UINT16 boot_order[100]; 924 char boot_info[4096]; 925 char buf[32]; 926 bool uefi_boot_mgr; 927 928 archsw.arch_autoload = efi_autoload; 929 archsw.arch_getdev = efi_getdev; 930 archsw.arch_copyin = efi_copyin; 931 archsw.arch_copyout = efi_copyout; 932 #ifdef __amd64__ 933 archsw.arch_hypervisor = x86_hypervisor; 934 #endif 935 archsw.arch_readin = efi_readin; 936 archsw.arch_zfs_probe = efi_zfs_probe; 937 938 /* Get our loaded image protocol interface structure. */ 939 (void) OpenProtocolByHandle(IH, &imgid, (void **)&boot_img); 940 941 /* 942 * Chicken-and-egg problem; we want to have console output early, but 943 * some console attributes may depend on reading from eg. the boot 944 * device, which we can't do yet. We can use printf() etc. once this is 945 * done. So, we set it to the efi console, then call console init. This 946 * gets us printf early, but also primes the pump for all future console 947 * changes to take effect, regardless of where they come from. 948 */ 949 setenv("console", "efi", 1); 950 uhowto = parse_uefi_con_out(); 951 #if defined(__riscv) 952 if ((uhowto & RB_SERIAL) != 0) 953 setenv("console", "comconsole", 1); 954 #endif 955 cons_probe(); 956 957 /* Set up currdev variable to have hooks in place. */ 958 env_setenv("currdev", EV_VOLATILE, "", efi_setcurrdev, env_nounset); 959 960 /* Init the time source */ 961 efi_time_init(); 962 963 /* 964 * Initialise the block cache. Set the upper limit. 965 */ 966 bcache_init(32768, 512); 967 968 /* 969 * Scan the BLOCK IO MEDIA handles then 970 * march through the device switch probing for things. 971 */ 972 i = efipart_inithandles(); 973 if (i != 0 && i != ENOENT) { 974 printf("efipart_inithandles failed with ERRNO %d, expect " 975 "failures\n", i); 976 } 977 978 for (i = 0; devsw[i] != NULL; i++) 979 if (devsw[i]->dv_init != NULL) 980 (devsw[i]->dv_init)(); 981 982 /* 983 * Detect console settings two different ways: one via the command 984 * args (eg -h) or via the UEFI ConOut variable. 985 */ 986 has_kbd = has_keyboard(); 987 howto = parse_args(argc, argv); 988 if (!has_kbd && (howto & RB_PROBE)) 989 howto |= RB_SERIAL | RB_MULTIPLE; 990 howto &= ~RB_PROBE; 991 992 /* 993 * Read additional environment variables from the boot device's 994 * "LoaderEnv" file. Any boot loader environment variable may be set 995 * there, which are subtly different than loader.conf variables. Only 996 * the 'simple' ones may be set so things like foo_load="YES" won't work 997 * for two reasons. First, the parser is simplistic and doesn't grok 998 * quotes. Second, because the variables that cause an action to happen 999 * are parsed by the lua, 4th or whatever code that's not yet 1000 * loaded. This is relative to the root directory when loader.efi is 1001 * loaded off the UFS root drive (when chain booted), or from the ESP 1002 * when directly loaded by the BIOS. 1003 * 1004 * We also read in NextLoaderEnv if it was specified. This allows next boot 1005 * functionality to be implemented and to override anything in LoaderEnv. 1006 */ 1007 read_loader_env("LoaderEnv", "/efi/freebsd/loader.env", false); 1008 read_loader_env("NextLoaderEnv", NULL, true); 1009 1010 /* 1011 * We now have two notions of console. howto should be viewed as 1012 * overrides. If console is already set, don't set it again. 1013 */ 1014 #define VIDEO_ONLY 0 1015 #define SERIAL_ONLY RB_SERIAL 1016 #define VID_SER_BOTH RB_MULTIPLE 1017 #define SER_VID_BOTH (RB_SERIAL | RB_MULTIPLE) 1018 #define CON_MASK (RB_SERIAL | RB_MULTIPLE) 1019 if (strcmp(getenv("console"), "efi") == 0) { 1020 if ((howto & CON_MASK) == 0) { 1021 /* No override, uhowto is controlling and efi cons is perfect */ 1022 howto = howto | (uhowto & CON_MASK); 1023 } else if ((howto & CON_MASK) == (uhowto & CON_MASK)) { 1024 /* override matches what UEFI told us, efi console is perfect */ 1025 } else if ((uhowto & (CON_MASK)) != 0) { 1026 /* 1027 * We detected a serial console on ConOut. All possible 1028 * overrides include serial. We can't really override what efi 1029 * gives us, so we use it knowing it's the best choice. 1030 */ 1031 /* Do nothing */ 1032 } else { 1033 /* 1034 * We detected some kind of serial in the override, but ConOut 1035 * has no serial, so we have to sort out which case it really is. 1036 */ 1037 switch (howto & CON_MASK) { 1038 case SERIAL_ONLY: 1039 setenv("console", "comconsole", 1); 1040 break; 1041 case VID_SER_BOTH: 1042 setenv("console", "efi comconsole", 1); 1043 break; 1044 case SER_VID_BOTH: 1045 setenv("console", "comconsole efi", 1); 1046 break; 1047 /* case VIDEO_ONLY can't happen -- it's the first if above */ 1048 } 1049 } 1050 } 1051 1052 /* 1053 * howto is set now how we want to export the flags to the kernel, so 1054 * set the env based on it. 1055 */ 1056 boot_howto_to_env(howto); 1057 1058 if (efi_copy_init()) { 1059 printf("failed to allocate staging area\n"); 1060 return (EFI_BUFFER_TOO_SMALL); 1061 } 1062 1063 if ((s = getenv("fail_timeout")) != NULL) 1064 fail_timeout = strtol(s, NULL, 10); 1065 1066 printf("%s\n", bootprog_info); 1067 printf(" Command line arguments:"); 1068 for (i = 0; i < argc; i++) 1069 printf(" %S", argv[i]); 1070 printf("\n"); 1071 1072 printf(" Image base: 0x%lx\n", (unsigned long)boot_img->ImageBase); 1073 printf(" EFI version: %d.%02d\n", ST->Hdr.Revision >> 16, 1074 ST->Hdr.Revision & 0xffff); 1075 printf(" EFI Firmware: %S (rev %d.%02d)\n", ST->FirmwareVendor, 1076 ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff); 1077 printf(" Console: %s (%#x)\n", getenv("console"), howto); 1078 1079 /* Determine the devpath of our image so we can prefer it. */ 1080 text = efi_devpath_name(boot_img->FilePath); 1081 if (text != NULL) { 1082 printf(" Load Path: %S\n", text); 1083 efi_setenv_freebsd_wcs("LoaderPath", text); 1084 efi_free_devpath_name(text); 1085 } 1086 1087 rv = OpenProtocolByHandle(boot_img->DeviceHandle, &devid, 1088 (void **)&imgpath); 1089 if (rv == EFI_SUCCESS) { 1090 text = efi_devpath_name(imgpath); 1091 if (text != NULL) { 1092 printf(" Load Device: %S\n", text); 1093 efi_setenv_freebsd_wcs("LoaderDev", text); 1094 efi_free_devpath_name(text); 1095 } 1096 } 1097 1098 if (getenv("uefi_ignore_boot_mgr") != NULL) { 1099 printf(" Ignoring UEFI boot manager\n"); 1100 uefi_boot_mgr = false; 1101 } else { 1102 uefi_boot_mgr = true; 1103 boot_current = 0; 1104 sz = sizeof(boot_current); 1105 rv = efi_global_getenv("BootCurrent", &boot_current, &sz); 1106 if (rv == EFI_SUCCESS) 1107 printf(" BootCurrent: %04x\n", boot_current); 1108 else { 1109 boot_current = 0xffff; 1110 uefi_boot_mgr = false; 1111 } 1112 1113 sz = sizeof(boot_order); 1114 rv = efi_global_getenv("BootOrder", &boot_order, &sz); 1115 if (rv == EFI_SUCCESS) { 1116 printf(" BootOrder:"); 1117 for (i = 0; i < sz / sizeof(boot_order[0]); i++) 1118 printf(" %04x%s", boot_order[i], 1119 boot_order[i] == boot_current ? "[*]" : ""); 1120 printf("\n"); 1121 is_last = boot_order[(sz / sizeof(boot_order[0])) - 1] == boot_current; 1122 bosz = sz; 1123 } else if (uefi_boot_mgr) { 1124 /* 1125 * u-boot doesn't set BootOrder, but otherwise participates in the 1126 * boot manager protocol. So we fake it here and don't consider it 1127 * a failure. 1128 */ 1129 bosz = sizeof(boot_order[0]); 1130 boot_order[0] = boot_current; 1131 is_last = true; 1132 } 1133 } 1134 1135 /* 1136 * Next, find the boot info structure the UEFI boot manager is 1137 * supposed to setup. We need this so we can walk through it to 1138 * find where we are in the booting process and what to try to 1139 * boot next. 1140 */ 1141 if (uefi_boot_mgr) { 1142 snprintf(buf, sizeof(buf), "Boot%04X", boot_current); 1143 sz = sizeof(boot_info); 1144 rv = efi_global_getenv(buf, &boot_info, &sz); 1145 if (rv == EFI_SUCCESS) 1146 bisz = sz; 1147 else 1148 uefi_boot_mgr = false; 1149 } 1150 1151 /* 1152 * Disable the watchdog timer. By default the boot manager sets 1153 * the timer to 5 minutes before invoking a boot option. If we 1154 * want to return to the boot manager, we have to disable the 1155 * watchdog timer and since we're an interactive program, we don't 1156 * want to wait until the user types "quit". The timer may have 1157 * fired by then. We don't care if this fails. It does not prevent 1158 * normal functioning in any way... 1159 */ 1160 BS->SetWatchdogTimer(0, 0, 0, NULL); 1161 1162 /* 1163 * Initialize the trusted/forbidden certificates from UEFI. 1164 * They will be later used to verify the manifest(s), 1165 * which should contain hashes of verified files. 1166 * This needs to be initialized before any configuration files 1167 * are loaded. 1168 */ 1169 #ifdef EFI_SECUREBOOT 1170 ve_efi_init(); 1171 #endif 1172 1173 /* 1174 * Try and find a good currdev based on the image that was booted. 1175 * It might be desirable here to have a short pause to allow falling 1176 * through to the boot loader instead of returning instantly to follow 1177 * the boot protocol and also allow an escape hatch for users wishing 1178 * to try something different. 1179 */ 1180 if (find_currdev(uefi_boot_mgr, is_last, boot_info, bisz) != 0) 1181 if (uefi_boot_mgr && 1182 !interactive_interrupt("Failed to find bootable partition")) 1183 return (EFI_NOT_FOUND); 1184 1185 autoload_font(false); /* Set up the font list for console. */ 1186 efi_init_environment(); 1187 1188 #if !defined(__arm__) 1189 for (k = 0; k < ST->NumberOfTableEntries; k++) { 1190 guid = &ST->ConfigurationTable[k].VendorGuid; 1191 if (!memcmp(guid, &smbios, 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