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