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