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 * UartClkFreq is 3 and newer. We always use it then (it's only valid if 892 * it isn't 0, but if it is 0, we want to use 0 to have the kernel 893 * guess). 894 */ 895 if (spcr->Header.Revision <= 2) 896 xo = 0; 897 else 898 xo = spcr->UartClkFreq; 899 900 /* 901 * PreciseBaudrate, when non-zero, is to be preferred. It's only valid, 902 * though, for rev 4 and newer. So when it's 0 or the version is too 903 * old, we do the old-style table lookup. Otherwise we believe it. 904 */ 905 if (spcr->Header.Revision <= 3 || spcr->PreciseBaudrate == 0) 906 br = acpi_uart_baud(spcr->BaudRate); 907 else 908 br = spcr->PreciseBaudrate; 909 910 if (io != -1) { 911 asprintf(&val, "db:%d,dt:%s,io:%#x,pa:%s,br:%d,xo=%d", 912 db, dt, io, pa, br, xo); 913 } else if (pv != 0xffff && pd != 0xffff) { 914 asprintf(&val, "db:%d,dt:%s,pv:%#x,pd:%#x,pa:%s,br:%d,xo=%d", 915 db, dt, pv, pd, pa, br, xo); 916 } else { 917 asprintf(&val, "db:%d,dt:%s,mm:%#jx,rs:%d,rw:%d,pa:%s,br:%d,xo=%d", 918 db, dt, mm, rs, rw, pa, br, xo); 919 } 920 env_setenv("hw.uart.console", EV_VOLATILE, val, NULL, NULL); 921 free(val); 922 923 return (RB_SERIAL); 924 } 925 926 927 /* 928 * Parse ConOut (the list of consoles active) and see if we can find a serial 929 * port and/or a video port. It would be nice to also walk the ACPI DSDT to map 930 * the UID for the serial port to a port since there's no standard mapping. Also 931 * check for ConIn as well. This will be enough to determine if we have serial, 932 * and if we don't, we default to video. If there's a dual-console situation 933 * with only ConIn defined, this will currently fail. 934 */ 935 int 936 parse_uefi_con_out(void) 937 { 938 int how, rv; 939 int vid_seen = 0, com_seen = 0, seen = 0; 940 size_t sz; 941 char buf[4096], *ep; 942 EFI_DEVICE_PATH *node; 943 ACPI_HID_DEVICE_PATH *acpi; 944 UART_DEVICE_PATH *uart; 945 bool pci_pending; 946 947 /* 948 * A SPCR in the ACPI fixed tables documents a serial port used for the 949 * console. It may mirror a video console, or may be stand alone. If it 950 * is present, we return RB_SERIAL and will use it for the kernel. 951 */ 952 how = check_acpi_spcr(); 953 sz = sizeof(buf); 954 rv = efi_global_getenv("ConOut", buf, &sz); 955 if (rv != EFI_SUCCESS) 956 rv = efi_global_getenv("ConOutDev", buf, &sz); 957 if (rv != EFI_SUCCESS) 958 rv = efi_global_getenv("ConIn", buf, &sz); 959 if (rv != EFI_SUCCESS) { 960 /* 961 * If we don't have any Con* variable use both. If we have GOP 962 * make video primary, otherwise set serial primary. In either 963 * case, try to use both the 'efi' console which will use the 964 * GOP, if present and serial. If there's an EFI BIOS that omits 965 * this, but has a serial port redirect, we'll unavioidably get 966 * doubled characters, but we'll be right in all the other more 967 * common cases. 968 */ 969 if (efi_has_gop()) 970 how |= RB_MULTIPLE; 971 else 972 how |= RB_MULTIPLE | RB_SERIAL; 973 setenv("console", "efi,comconsole", 1); 974 goto out; 975 } 976 ep = buf + sz; 977 node = (EFI_DEVICE_PATH *)buf; 978 while ((char *)node < ep) { 979 if (IsDevicePathEndType(node)) { 980 if (pci_pending && vid_seen == 0) 981 vid_seen = ++seen; 982 } 983 pci_pending = false; 984 if (DevicePathType(node) == ACPI_DEVICE_PATH && 985 (DevicePathSubType(node) == ACPI_DP || 986 DevicePathSubType(node) == ACPI_EXTENDED_DP)) { 987 /* Check for Serial node */ 988 acpi = (void *)node; 989 if (EISA_ID_TO_NUM(acpi->HID) == 0x501) { 990 setenv_int("efi_8250_uid", acpi->UID); 991 com_seen = ++seen; 992 } 993 } else if (DevicePathType(node) == MESSAGING_DEVICE_PATH && 994 DevicePathSubType(node) == MSG_UART_DP) { 995 com_seen = ++seen; 996 uart = (void *)node; 997 setenv_int("efi_com_speed", uart->BaudRate); 998 } else if (DevicePathType(node) == ACPI_DEVICE_PATH && 999 DevicePathSubType(node) == ACPI_ADR_DP) { 1000 /* Check for AcpiAdr() Node for video */ 1001 vid_seen = ++seen; 1002 } else if (DevicePathType(node) == HARDWARE_DEVICE_PATH && 1003 DevicePathSubType(node) == HW_PCI_DP) { 1004 /* 1005 * Note, vmware fusion has a funky console device 1006 * PciRoot(0x0)/Pci(0xf,0x0) 1007 * which we can only detect at the end since we also 1008 * have to cope with: 1009 * PciRoot(0x0)/Pci(0x1f,0x0)/Serial(0x1) 1010 * so only match it if it's last. 1011 */ 1012 pci_pending = true; 1013 } 1014 node = NextDevicePathNode(node); 1015 } 1016 1017 /* 1018 * Truth table for RB_MULTIPLE | RB_SERIAL 1019 * Value Result 1020 * 0 Use only video console 1021 * RB_SERIAL Use only serial console 1022 * RB_MULTIPLE Use both video and serial console 1023 * (but video is primary so gets rc messages) 1024 * both Use both video and serial console 1025 * (but serial is primary so gets rc messages) 1026 * 1027 * Try to honor this as best we can. If only one of serial / video 1028 * found, then use that. Otherwise, use the first one we found. 1029 * This also implies if we found nothing, default to video. 1030 */ 1031 how = 0; 1032 if (vid_seen && com_seen) { 1033 how |= RB_MULTIPLE; 1034 if (com_seen < vid_seen) 1035 how |= RB_SERIAL; 1036 } else if (com_seen) 1037 how |= RB_SERIAL; 1038 out: 1039 return (how); 1040 } 1041 1042 void 1043 parse_loader_efi_config(EFI_HANDLE h, const char *env_fn) 1044 { 1045 pdinfo_t *dp; 1046 struct stat st; 1047 int fd = -1; 1048 char *env = NULL; 1049 1050 dp = efiblk_get_pdinfo_by_handle(h); 1051 if (dp == NULL) 1052 return; 1053 set_currdev_pdinfo(dp); 1054 if (stat(env_fn, &st) != 0) 1055 return; 1056 fd = open(env_fn, O_RDONLY); 1057 if (fd == -1) 1058 return; 1059 env = malloc(st.st_size + 1); 1060 if (env == NULL) 1061 goto out; 1062 if (read(fd, env, st.st_size) != st.st_size) 1063 goto out; 1064 env[st.st_size] = '\0'; 1065 boot_parse_cmdline(env); 1066 out: 1067 free(env); 1068 close(fd); 1069 } 1070 1071 static void 1072 read_loader_env(const char *name, char *def_fn, bool once) 1073 { 1074 UINTN len; 1075 char *fn, *freeme = NULL; 1076 1077 len = 0; 1078 fn = def_fn; 1079 if (efi_freebsd_getenv(name, NULL, &len) == EFI_BUFFER_TOO_SMALL) { 1080 freeme = fn = malloc(len + 1); 1081 if (fn != NULL) { 1082 if (efi_freebsd_getenv(name, fn, &len) != EFI_SUCCESS) { 1083 free(fn); 1084 fn = NULL; 1085 printf( 1086 "Can't fetch FreeBSD::%s we know is there\n", name); 1087 } else { 1088 /* 1089 * if tagged as 'once' delete the env variable so we 1090 * only use it once. 1091 */ 1092 if (once) 1093 efi_freebsd_delenv(name); 1094 /* 1095 * We malloced 1 more than len above, then redid the call. 1096 * so now we have room at the end of the string to NUL terminate 1097 * it here, even if the typical idium would have '- 1' here to 1098 * not overflow. len should be the same on return both times. 1099 */ 1100 fn[len] = '\0'; 1101 } 1102 } else { 1103 printf( 1104 "Can't allocate %d bytes to fetch FreeBSD::%s env var\n", 1105 len, name); 1106 } 1107 } 1108 if (fn) { 1109 printf(" Reading loader env vars from %s\n", fn); 1110 parse_loader_efi_config(boot_img->DeviceHandle, fn); 1111 } 1112 } 1113 1114 caddr_t 1115 ptov(uintptr_t x) 1116 { 1117 return ((caddr_t)x); 1118 } 1119 1120 static void 1121 acpi_detect(void) 1122 { 1123 char buf[24]; 1124 int revision; 1125 1126 feature_enable(FEATURE_EARLY_ACPI); 1127 if ((rsdp = efi_get_table(&acpi20)) == NULL) 1128 if ((rsdp = efi_get_table(&acpi)) == NULL) 1129 return; 1130 1131 sprintf(buf, "0x%016"PRIxPTR, (uintptr_t)rsdp); 1132 setenv("acpi.rsdp", buf, 1); 1133 revision = rsdp->Revision; 1134 if (revision == 0) 1135 revision = 1; 1136 sprintf(buf, "%d", revision); 1137 setenv("acpi.revision", buf, 1); 1138 strncpy(buf, rsdp->OemId, sizeof(rsdp->OemId)); 1139 buf[sizeof(rsdp->OemId)] = '\0'; 1140 setenv("acpi.oem", buf, 1); 1141 sprintf(buf, "0x%016x", rsdp->RsdtPhysicalAddress); 1142 setenv("acpi.rsdt", buf, 1); 1143 if (revision >= 2) { 1144 /* XXX extended checksum? */ 1145 sprintf(buf, "0x%016llx", 1146 (unsigned long long)rsdp->XsdtPhysicalAddress); 1147 setenv("acpi.xsdt", buf, 1); 1148 sprintf(buf, "%d", rsdp->Length); 1149 setenv("acpi.xsdt_length", buf, 1); 1150 } 1151 } 1152 1153 EFI_STATUS 1154 main(int argc, CHAR16 *argv[]) 1155 { 1156 EFI_GUID *guid; 1157 int howto, i, uhowto; 1158 UINTN k; 1159 bool has_kbd, is_last; 1160 char *s; 1161 EFI_DEVICE_PATH *imgpath; 1162 CHAR16 *text; 1163 EFI_STATUS rv; 1164 size_t sz, bosz = 0, bisz = 0; 1165 UINT16 boot_order[100]; 1166 char boot_info[4096]; 1167 char buf[32]; 1168 bool uefi_boot_mgr; 1169 1170 archsw.arch_autoload = efi_autoload; 1171 archsw.arch_getdev = efi_getdev; 1172 archsw.arch_copyin = efi_copyin; 1173 archsw.arch_copyout = efi_copyout; 1174 #if defined(__amd64__) || defined(__i386__) 1175 archsw.arch_hypervisor = x86_hypervisor; 1176 #endif 1177 archsw.arch_readin = efi_readin; 1178 archsw.arch_zfs_probe = efi_zfs_probe; 1179 1180 #if !defined(__arm__) 1181 for (k = 0; k < ST->NumberOfTableEntries; k++) { 1182 guid = &ST->ConfigurationTable[k].VendorGuid; 1183 if (!memcmp(guid, &smbios, sizeof(EFI_GUID)) || 1184 !memcmp(guid, &smbios3, sizeof(EFI_GUID))) { 1185 char buf[40]; 1186 1187 snprintf(buf, sizeof(buf), "%p", 1188 ST->ConfigurationTable[k].VendorTable); 1189 setenv("hint.smbios.0.mem", buf, 1); 1190 smbios_detect(ST->ConfigurationTable[k].VendorTable); 1191 break; 1192 } 1193 } 1194 #endif 1195 1196 /* Get our loaded image protocol interface structure. */ 1197 (void) OpenProtocolByHandle(IH, &imgid, (void **)&boot_img); 1198 1199 /* Report the RSDP early. */ 1200 acpi_detect(); 1201 1202 /* 1203 * Chicken-and-egg problem; we want to have console output early, but 1204 * some console attributes may depend on reading from eg. the boot 1205 * device, which we can't do yet. We can use printf() etc. once this is 1206 * done. So, we set it to the efi console, then call console init. This 1207 * gets us printf early, but also primes the pump for all future console 1208 * changes to take effect, regardless of where they come from. 1209 */ 1210 setenv("console", "efi", 1); 1211 uhowto = parse_uefi_con_out(); 1212 #if defined(__riscv) 1213 /* 1214 * This workaround likely is papering over a real issue 1215 */ 1216 if ((uhowto & RB_SERIAL) != 0) 1217 setenv("console", "comconsole", 1); 1218 #endif 1219 cons_probe(); 1220 1221 /* Set up currdev variable to have hooks in place. */ 1222 env_setenv("currdev", EV_VOLATILE, "", gen_setcurrdev, env_nounset); 1223 1224 /* Init the time source */ 1225 efi_time_init(); 1226 1227 /* 1228 * Initialise the block cache. Set the upper limit. 1229 */ 1230 bcache_init(32768, 512); 1231 1232 /* 1233 * Scan the BLOCK IO MEDIA handles then 1234 * march through the device switch probing for things. 1235 */ 1236 i = efipart_inithandles(); 1237 if (i != 0 && i != ENOENT) { 1238 printf("efipart_inithandles failed with ERRNO %d, expect " 1239 "failures\n", i); 1240 } 1241 1242 devinit(); 1243 1244 /* 1245 * Detect console settings two different ways: one via the command 1246 * args (eg -h) or via the UEFI ConOut variable. 1247 */ 1248 has_kbd = has_keyboard(); 1249 howto = parse_args(argc, argv); 1250 if (!has_kbd && (howto & RB_PROBE)) 1251 howto |= RB_SERIAL | RB_MULTIPLE; 1252 howto &= ~RB_PROBE; 1253 1254 /* 1255 * Read additional environment variables from the boot device's 1256 * "LoaderEnv" file. Any boot loader environment variable may be set 1257 * there, which are subtly different than loader.conf variables. Only 1258 * the 'simple' ones may be set so things like foo_load="YES" won't work 1259 * for two reasons. First, the parser is simplistic and doesn't grok 1260 * quotes. Second, because the variables that cause an action to happen 1261 * are parsed by the lua, 4th or whatever code that's not yet 1262 * loaded. This is relative to the root directory when loader.efi is 1263 * loaded off the UFS root drive (when chain booted), or from the ESP 1264 * when directly loaded by the BIOS. 1265 * 1266 * We also read in NextLoaderEnv if it was specified. This allows next boot 1267 * functionality to be implemented and to override anything in LoaderEnv. 1268 */ 1269 read_loader_env("LoaderEnv", "/efi/freebsd/loader.env", false); 1270 read_loader_env("NextLoaderEnv", NULL, true); 1271 1272 /* 1273 * We now have two notions of console. howto should be viewed as 1274 * overrides. If console is already set, don't set it again. 1275 */ 1276 #define VIDEO_ONLY 0 1277 #define SERIAL_ONLY RB_SERIAL 1278 #define VID_SER_BOTH RB_MULTIPLE 1279 #define SER_VID_BOTH (RB_SERIAL | RB_MULTIPLE) 1280 #define CON_MASK (RB_SERIAL | RB_MULTIPLE) 1281 if (strcmp(getenv("console"), "efi") == 0) { 1282 if ((howto & CON_MASK) == 0) { 1283 /* No override, uhowto is controlling and efi cons is perfect */ 1284 howto = howto | (uhowto & CON_MASK); 1285 } else if ((howto & CON_MASK) == (uhowto & CON_MASK)) { 1286 /* override matches what UEFI told us, efi console is perfect */ 1287 } else if ((uhowto & (CON_MASK)) != 0) { 1288 /* 1289 * We detected a serial console on ConOut. All possible 1290 * overrides include serial. We can't really override what efi 1291 * gives us, so we use it knowing it's the best choice. 1292 */ 1293 /* Do nothing */ 1294 } else { 1295 /* 1296 * We detected some kind of serial in the override, but ConOut 1297 * has no serial, so we have to sort out which case it really is. 1298 */ 1299 switch (howto & CON_MASK) { 1300 case SERIAL_ONLY: 1301 setenv("console", "comconsole", 1); 1302 break; 1303 case VID_SER_BOTH: 1304 setenv("console", "efi comconsole", 1); 1305 break; 1306 case SER_VID_BOTH: 1307 setenv("console", "comconsole efi", 1); 1308 break; 1309 /* case VIDEO_ONLY can't happen -- it's the first if above */ 1310 } 1311 } 1312 } 1313 1314 /* 1315 * howto is set now how we want to export the flags to the kernel, so 1316 * set the env based on it. 1317 */ 1318 boot_howto_to_env(howto); 1319 1320 if (efi_copy_init()) 1321 return (EFI_BUFFER_TOO_SMALL); 1322 1323 if ((s = getenv("fail_timeout")) != NULL) 1324 fail_timeout = strtol(s, NULL, 10); 1325 1326 printf("%s\n", bootprog_info); 1327 printf(" Command line arguments:"); 1328 for (i = 0; i < argc; i++) 1329 printf(" %S", argv[i]); 1330 printf("\n"); 1331 1332 printf(" Image base: 0x%lx\n", (unsigned long)boot_img->ImageBase); 1333 printf(" EFI version: %d.%02d\n", ST->Hdr.Revision >> 16, 1334 ST->Hdr.Revision & 0xffff); 1335 printf(" EFI Firmware: %S (rev %d.%02d)\n", ST->FirmwareVendor, 1336 ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff); 1337 printf(" Console: %s (%#x)\n", getenv("console"), howto); 1338 1339 /* Determine the devpath of our image so we can prefer it. */ 1340 text = efi_devpath_name(boot_img->FilePath); 1341 if (text != NULL) { 1342 printf(" Load Path: %S\n", text); 1343 efi_setenv_freebsd_wcs("LoaderPath", text); 1344 efi_free_devpath_name(text); 1345 } 1346 1347 rv = OpenProtocolByHandle(boot_img->DeviceHandle, &devid, 1348 (void **)&imgpath); 1349 if (rv == EFI_SUCCESS) { 1350 text = efi_devpath_name(imgpath); 1351 if (text != NULL) { 1352 printf(" Load Device: %S\n", text); 1353 efi_setenv_freebsd_wcs("LoaderDev", text); 1354 efi_free_devpath_name(text); 1355 } 1356 } 1357 1358 if (getenv("uefi_ignore_boot_mgr") != NULL) { 1359 printf(" Ignoring UEFI boot manager\n"); 1360 uefi_boot_mgr = false; 1361 } else { 1362 uefi_boot_mgr = true; 1363 boot_current = 0; 1364 sz = sizeof(boot_current); 1365 rv = efi_global_getenv("BootCurrent", &boot_current, &sz); 1366 if (rv == EFI_SUCCESS) 1367 printf(" BootCurrent: %04x\n", boot_current); 1368 else { 1369 boot_current = 0xffff; 1370 uefi_boot_mgr = false; 1371 } 1372 1373 sz = sizeof(boot_order); 1374 rv = efi_global_getenv("BootOrder", &boot_order, &sz); 1375 if (rv == EFI_SUCCESS) { 1376 printf(" BootOrder:"); 1377 for (i = 0; i < sz / sizeof(boot_order[0]); i++) 1378 printf(" %04x%s", boot_order[i], 1379 boot_order[i] == boot_current ? "[*]" : ""); 1380 printf("\n"); 1381 is_last = boot_order[(sz / sizeof(boot_order[0])) - 1] == boot_current; 1382 bosz = sz; 1383 } else if (uefi_boot_mgr) { 1384 /* 1385 * u-boot doesn't set BootOrder, but otherwise participates in the 1386 * boot manager protocol. So we fake it here and don't consider it 1387 * a failure. 1388 */ 1389 bosz = sizeof(boot_order[0]); 1390 boot_order[0] = boot_current; 1391 is_last = true; 1392 } 1393 } 1394 1395 /* 1396 * Next, find the boot info structure the UEFI boot manager is 1397 * supposed to setup. We need this so we can walk through it to 1398 * find where we are in the booting process and what to try to 1399 * boot next. 1400 */ 1401 if (uefi_boot_mgr) { 1402 snprintf(buf, sizeof(buf), "Boot%04X", boot_current); 1403 sz = sizeof(boot_info); 1404 rv = efi_global_getenv(buf, &boot_info, &sz); 1405 if (rv == EFI_SUCCESS) 1406 bisz = sz; 1407 else 1408 uefi_boot_mgr = false; 1409 } 1410 1411 /* 1412 * Disable the watchdog timer. By default the boot manager sets 1413 * the timer to 5 minutes before invoking a boot option. If we 1414 * want to return to the boot manager, we have to disable the 1415 * watchdog timer and since we're an interactive program, we don't 1416 * want to wait until the user types "quit". The timer may have 1417 * fired by then. We don't care if this fails. It does not prevent 1418 * normal functioning in any way... 1419 */ 1420 BS->SetWatchdogTimer(0, 0, 0, NULL); 1421 1422 /* 1423 * Initialize the trusted/forbidden certificates from UEFI. 1424 * They will be later used to verify the manifest(s), 1425 * which should contain hashes of verified files. 1426 * This needs to be initialized before any configuration files 1427 * are loaded. 1428 */ 1429 #ifdef EFI_SECUREBOOT 1430 ve_efi_init(); 1431 #endif 1432 1433 /* 1434 * Try and find a good currdev based on the image that was booted. 1435 * It might be desirable here to have a short pause to allow falling 1436 * through to the boot loader instead of returning instantly to follow 1437 * the boot protocol and also allow an escape hatch for users wishing 1438 * to try something different. 1439 */ 1440 if (find_currdev(uefi_boot_mgr, is_last, boot_info, bisz) != 0) 1441 if (uefi_boot_mgr && 1442 !interactive_interrupt("Failed to find bootable partition")) 1443 return (EFI_NOT_FOUND); 1444 1445 autoload_font(false); /* Set up the font list for console. */ 1446 efi_init_environment(); 1447 1448 interact(); /* doesn't return */ 1449 1450 return (EFI_SUCCESS); /* keep compiler happy */ 1451 } 1452 1453 COMMAND_SET(efi_seed_entropy, "efi-seed-entropy", "try to get entropy from the EFI RNG", command_seed_entropy); 1454 1455 static int 1456 command_seed_entropy(int argc, char *argv[]) 1457 { 1458 EFI_STATUS status; 1459 EFI_RNG_PROTOCOL *rng; 1460 unsigned int size_efi = RANDOM_FORTUNA_DEFPOOLSIZE * RANDOM_FORTUNA_NPOOLS; 1461 unsigned int size = RANDOM_FORTUNA_DEFPOOLSIZE * RANDOM_FORTUNA_NPOOLS; 1462 void *buf_efi; 1463 void *buf; 1464 1465 if (argc > 1) { 1466 size_efi = strtol(argv[1], NULL, 0); 1467 1468 /* Don't *compress* the entropy we get from EFI. */ 1469 if (size_efi > size) 1470 size = size_efi; 1471 1472 /* 1473 * If the amount of entropy we get from EFI is less than the 1474 * size of a single Fortuna pool -- i.e. not enough to ensure 1475 * that Fortuna is safely seeded -- don't expand it since we 1476 * don't want to trick Fortuna into thinking that it has been 1477 * safely seeded when it has not. 1478 */ 1479 if (size_efi < RANDOM_FORTUNA_DEFPOOLSIZE) 1480 size = size_efi; 1481 } 1482 1483 status = BS->LocateProtocol(&rng_guid, NULL, (VOID **)&rng); 1484 if (status != EFI_SUCCESS) { 1485 command_errmsg = "RNG protocol not found"; 1486 return (CMD_ERROR); 1487 } 1488 1489 if ((buf = malloc(size)) == NULL) { 1490 command_errmsg = "out of memory"; 1491 return (CMD_ERROR); 1492 } 1493 1494 if ((buf_efi = malloc(size_efi)) == NULL) { 1495 free(buf); 1496 command_errmsg = "out of memory"; 1497 return (CMD_ERROR); 1498 } 1499 1500 TSENTER2("rng->GetRNG"); 1501 status = rng->GetRNG(rng, NULL, size_efi, (UINT8 *)buf_efi); 1502 TSEXIT(); 1503 if (status != EFI_SUCCESS) { 1504 free(buf_efi); 1505 free(buf); 1506 command_errmsg = "GetRNG failed"; 1507 return (CMD_ERROR); 1508 } 1509 if (size_efi < size) 1510 pkcs5v2_genkey_raw(buf, size, "", 0, buf_efi, size_efi, 1); 1511 else 1512 memcpy(buf, buf_efi, size); 1513 1514 if (file_addbuf("efi_rng_seed", "boot_entropy_platform", size, buf) != 0) { 1515 free(buf_efi); 1516 free(buf); 1517 return (CMD_ERROR); 1518 } 1519 1520 explicit_bzero(buf_efi, size_efi); 1521 free(buf_efi); 1522 free(buf); 1523 return (CMD_OK); 1524 } 1525 1526 COMMAND_SET(poweroff, "poweroff", "power off the system", command_poweroff); 1527 1528 static int 1529 command_poweroff(int argc __unused, char *argv[] __unused) 1530 { 1531 int i; 1532 1533 for (i = 0; devsw[i] != NULL; ++i) 1534 if (devsw[i]->dv_cleanup != NULL) 1535 (devsw[i]->dv_cleanup)(); 1536 1537 RS->ResetSystem(EfiResetShutdown, EFI_SUCCESS, 0, NULL); 1538 1539 /* NOTREACHED */ 1540 return (CMD_ERROR); 1541 } 1542 1543 COMMAND_SET(reboot, "reboot", "reboot the system", command_reboot); 1544 1545 static int 1546 command_reboot(int argc, char *argv[]) 1547 { 1548 int i; 1549 1550 for (i = 0; devsw[i] != NULL; ++i) 1551 if (devsw[i]->dv_cleanup != NULL) 1552 (devsw[i]->dv_cleanup)(); 1553 1554 RS->ResetSystem(EfiResetCold, EFI_SUCCESS, 0, NULL); 1555 1556 /* NOTREACHED */ 1557 return (CMD_ERROR); 1558 } 1559 1560 COMMAND_SET(memmap, "memmap", "print memory map", command_memmap); 1561 1562 static int 1563 command_memmap(int argc __unused, char *argv[] __unused) 1564 { 1565 UINTN sz; 1566 EFI_MEMORY_DESCRIPTOR *map, *p; 1567 UINTN key, dsz; 1568 UINT32 dver; 1569 EFI_STATUS status; 1570 int i, ndesc; 1571 char line[80]; 1572 1573 sz = 0; 1574 status = BS->GetMemoryMap(&sz, 0, &key, &dsz, &dver); 1575 if (status != EFI_BUFFER_TOO_SMALL) { 1576 printf("Can't determine memory map size\n"); 1577 return (CMD_ERROR); 1578 } 1579 map = malloc(sz); 1580 status = BS->GetMemoryMap(&sz, map, &key, &dsz, &dver); 1581 if (EFI_ERROR(status)) { 1582 printf("Can't read memory map\n"); 1583 return (CMD_ERROR); 1584 } 1585 1586 ndesc = sz / dsz; 1587 snprintf(line, sizeof(line), "%23s %12s %12s %8s %4s\n", 1588 "Type", "Physical", "Virtual", "#Pages", "Attr"); 1589 pager_open(); 1590 if (pager_output(line)) { 1591 pager_close(); 1592 return (CMD_OK); 1593 } 1594 1595 for (i = 0, p = map; i < ndesc; 1596 i++, p = NextMemoryDescriptor(p, dsz)) { 1597 snprintf(line, sizeof(line), "%23s %012jx %012jx %08jx ", 1598 efi_memory_type(p->Type), (uintmax_t)p->PhysicalStart, 1599 (uintmax_t)p->VirtualStart, (uintmax_t)p->NumberOfPages); 1600 if (pager_output(line)) 1601 break; 1602 1603 if (p->Attribute & EFI_MEMORY_UC) 1604 printf("UC "); 1605 if (p->Attribute & EFI_MEMORY_WC) 1606 printf("WC "); 1607 if (p->Attribute & EFI_MEMORY_WT) 1608 printf("WT "); 1609 if (p->Attribute & EFI_MEMORY_WB) 1610 printf("WB "); 1611 if (p->Attribute & EFI_MEMORY_UCE) 1612 printf("UCE "); 1613 if (p->Attribute & EFI_MEMORY_WP) 1614 printf("WP "); 1615 if (p->Attribute & EFI_MEMORY_RP) 1616 printf("RP "); 1617 if (p->Attribute & EFI_MEMORY_XP) 1618 printf("XP "); 1619 if (p->Attribute & EFI_MEMORY_NV) 1620 printf("NV "); 1621 if (p->Attribute & EFI_MEMORY_MORE_RELIABLE) 1622 printf("MR "); 1623 if (p->Attribute & EFI_MEMORY_RO) 1624 printf("RO "); 1625 if (pager_output("\n")) 1626 break; 1627 } 1628 1629 pager_close(); 1630 return (CMD_OK); 1631 } 1632 1633 COMMAND_SET(configuration, "configuration", "print configuration tables", 1634 command_configuration); 1635 1636 static int 1637 command_configuration(int argc, char *argv[]) 1638 { 1639 UINTN i; 1640 char *name; 1641 1642 printf("NumberOfTableEntries=%lu\n", 1643 (unsigned long)ST->NumberOfTableEntries); 1644 1645 for (i = 0; i < ST->NumberOfTableEntries; i++) { 1646 EFI_GUID *guid; 1647 1648 printf(" "); 1649 guid = &ST->ConfigurationTable[i].VendorGuid; 1650 1651 if (efi_guid_to_name(guid, &name) == true) { 1652 printf(name); 1653 free(name); 1654 } else { 1655 printf("Error while translating UUID to name"); 1656 } 1657 printf(" at %p\n", ST->ConfigurationTable[i].VendorTable); 1658 } 1659 1660 return (CMD_OK); 1661 } 1662 1663 1664 COMMAND_SET(mode, "mode", "change or display EFI text modes", command_mode); 1665 1666 static int 1667 command_mode(int argc, char *argv[]) 1668 { 1669 UINTN cols, rows; 1670 unsigned int mode; 1671 int i; 1672 char *cp; 1673 EFI_STATUS status; 1674 SIMPLE_TEXT_OUTPUT_INTERFACE *conout; 1675 1676 conout = ST->ConOut; 1677 1678 if (argc > 1) { 1679 mode = strtol(argv[1], &cp, 0); 1680 if (cp[0] != '\0') { 1681 printf("Invalid mode\n"); 1682 return (CMD_ERROR); 1683 } 1684 status = conout->QueryMode(conout, mode, &cols, &rows); 1685 if (EFI_ERROR(status)) { 1686 printf("invalid mode %d\n", mode); 1687 return (CMD_ERROR); 1688 } 1689 status = conout->SetMode(conout, mode); 1690 if (EFI_ERROR(status)) { 1691 printf("couldn't set mode %d\n", mode); 1692 return (CMD_ERROR); 1693 } 1694 (void) cons_update_mode(true); 1695 return (CMD_OK); 1696 } 1697 1698 printf("Current mode: %d\n", conout->Mode->Mode); 1699 for (i = 0; i <= conout->Mode->MaxMode; i++) { 1700 status = conout->QueryMode(conout, i, &cols, &rows); 1701 if (EFI_ERROR(status)) 1702 continue; 1703 printf("Mode %d: %u columns, %u rows\n", i, (unsigned)cols, 1704 (unsigned)rows); 1705 } 1706 1707 if (i != 0) 1708 printf("Select a mode with the command \"mode <number>\"\n"); 1709 1710 return (CMD_OK); 1711 } 1712 1713 COMMAND_SET(lsefi, "lsefi", "list EFI handles", command_lsefi); 1714 1715 static void 1716 lsefi_print_handle_info(EFI_HANDLE handle) 1717 { 1718 EFI_DEVICE_PATH *devpath; 1719 EFI_DEVICE_PATH *imagepath; 1720 CHAR16 *dp_name; 1721 1722 imagepath = efi_lookup_image_devpath(handle); 1723 if (imagepath != NULL) { 1724 dp_name = efi_devpath_name(imagepath); 1725 printf("Handle for image %S", dp_name); 1726 efi_free_devpath_name(dp_name); 1727 return; 1728 } 1729 devpath = efi_lookup_devpath(handle); 1730 if (devpath != NULL) { 1731 dp_name = efi_devpath_name(devpath); 1732 printf("Handle for device %S", dp_name); 1733 efi_free_devpath_name(dp_name); 1734 return; 1735 } 1736 printf("Handle %p", handle); 1737 } 1738 1739 static int 1740 command_lsefi(int argc __unused, char *argv[] __unused) 1741 { 1742 char *name; 1743 EFI_HANDLE *buffer = NULL; 1744 EFI_HANDLE handle; 1745 UINTN bufsz = 0, i, j; 1746 EFI_STATUS status; 1747 int ret = 0; 1748 1749 status = BS->LocateHandle(AllHandles, NULL, NULL, &bufsz, buffer); 1750 if (status != EFI_BUFFER_TOO_SMALL) { 1751 snprintf(command_errbuf, sizeof (command_errbuf), 1752 "unexpected error: %lld", (long long)status); 1753 return (CMD_ERROR); 1754 } 1755 if ((buffer = malloc(bufsz)) == NULL) { 1756 sprintf(command_errbuf, "out of memory"); 1757 return (CMD_ERROR); 1758 } 1759 1760 status = BS->LocateHandle(AllHandles, NULL, NULL, &bufsz, buffer); 1761 if (EFI_ERROR(status)) { 1762 free(buffer); 1763 snprintf(command_errbuf, sizeof (command_errbuf), 1764 "LocateHandle() error: %lld", (long long)status); 1765 return (CMD_ERROR); 1766 } 1767 1768 pager_open(); 1769 for (i = 0; i < (bufsz / sizeof (EFI_HANDLE)); i++) { 1770 UINTN nproto = 0; 1771 EFI_GUID **protocols = NULL; 1772 1773 handle = buffer[i]; 1774 lsefi_print_handle_info(handle); 1775 if (pager_output("\n")) 1776 break; 1777 /* device path */ 1778 1779 status = BS->ProtocolsPerHandle(handle, &protocols, &nproto); 1780 if (EFI_ERROR(status)) { 1781 snprintf(command_errbuf, sizeof (command_errbuf), 1782 "ProtocolsPerHandle() error: %lld", 1783 (long long)status); 1784 continue; 1785 } 1786 1787 for (j = 0; j < nproto; j++) { 1788 if (efi_guid_to_name(protocols[j], &name) == true) { 1789 printf(" %s", name); 1790 free(name); 1791 } else { 1792 printf("Error while translating UUID to name"); 1793 } 1794 if ((ret = pager_output("\n")) != 0) 1795 break; 1796 } 1797 BS->FreePool(protocols); 1798 if (ret != 0) 1799 break; 1800 } 1801 pager_close(); 1802 free(buffer); 1803 return (CMD_OK); 1804 } 1805 1806 #ifdef LOADER_FDT_SUPPORT 1807 extern int command_fdt_internal(int argc, char *argv[]); 1808 1809 /* 1810 * Since proper fdt command handling function is defined in fdt_loader_cmd.c, 1811 * and declaring it as extern is in contradiction with COMMAND_SET() macro 1812 * (which uses static pointer), we're defining wrapper function, which 1813 * calls the proper fdt handling routine. 1814 */ 1815 static int 1816 command_fdt(int argc, char *argv[]) 1817 { 1818 1819 return (command_fdt_internal(argc, argv)); 1820 } 1821 1822 COMMAND_SET(fdt, "fdt", "flattened device tree handling", command_fdt); 1823 #endif 1824 1825 /* 1826 * Chain load another efi loader. 1827 */ 1828 static int 1829 command_chain(int argc, char *argv[]) 1830 { 1831 EFI_GUID LoadedImageGUID = LOADED_IMAGE_PROTOCOL; 1832 EFI_HANDLE loaderhandle; 1833 EFI_LOADED_IMAGE *loaded_image; 1834 EFI_STATUS status; 1835 struct stat st; 1836 struct devdesc *dev; 1837 char *name, *path; 1838 void *buf; 1839 int fd; 1840 1841 if (argc < 2) { 1842 command_errmsg = "wrong number of arguments"; 1843 return (CMD_ERROR); 1844 } 1845 1846 name = argv[1]; 1847 1848 if ((fd = open(name, O_RDONLY)) < 0) { 1849 command_errmsg = "no such file"; 1850 return (CMD_ERROR); 1851 } 1852 1853 #ifdef LOADER_VERIEXEC 1854 if (verify_file(fd, name, 0, VE_MUST, __func__) < 0) { 1855 sprintf(command_errbuf, "can't verify: %s", name); 1856 close(fd); 1857 return (CMD_ERROR); 1858 } 1859 #endif 1860 1861 if (fstat(fd, &st) < -1) { 1862 command_errmsg = "stat failed"; 1863 close(fd); 1864 return (CMD_ERROR); 1865 } 1866 1867 status = BS->AllocatePool(EfiLoaderCode, (UINTN)st.st_size, &buf); 1868 if (status != EFI_SUCCESS) { 1869 command_errmsg = "failed to allocate buffer"; 1870 close(fd); 1871 return (CMD_ERROR); 1872 } 1873 if (read(fd, buf, st.st_size) != st.st_size) { 1874 command_errmsg = "error while reading the file"; 1875 (void)BS->FreePool(buf); 1876 close(fd); 1877 return (CMD_ERROR); 1878 } 1879 close(fd); 1880 status = BS->LoadImage(FALSE, IH, NULL, buf, st.st_size, &loaderhandle); 1881 (void)BS->FreePool(buf); 1882 if (status != EFI_SUCCESS) { 1883 command_errmsg = "LoadImage failed"; 1884 return (CMD_ERROR); 1885 } 1886 status = OpenProtocolByHandle(loaderhandle, &LoadedImageGUID, 1887 (void **)&loaded_image); 1888 1889 if (argc > 2) { 1890 int i, len = 0; 1891 CHAR16 *argp; 1892 1893 for (i = 2; i < argc; i++) 1894 len += strlen(argv[i]) + 1; 1895 1896 len *= sizeof (*argp); 1897 loaded_image->LoadOptions = argp = malloc (len); 1898 loaded_image->LoadOptionsSize = len; 1899 for (i = 2; i < argc; i++) { 1900 char *ptr = argv[i]; 1901 while (*ptr) 1902 *(argp++) = *(ptr++); 1903 *(argp++) = ' '; 1904 } 1905 *(--argv) = 0; 1906 } 1907 1908 if (efi_getdev((void **)&dev, name, (const char **)&path) == 0) { 1909 #ifdef EFI_ZFS_BOOT 1910 struct zfs_devdesc *z_dev; 1911 #endif 1912 struct disk_devdesc *d_dev; 1913 pdinfo_t *hd, *pd; 1914 1915 switch (dev->d_dev->dv_type) { 1916 #ifdef EFI_ZFS_BOOT 1917 case DEVT_ZFS: 1918 z_dev = (struct zfs_devdesc *)dev; 1919 loaded_image->DeviceHandle = 1920 efizfs_get_handle_by_guid(z_dev->pool_guid); 1921 break; 1922 #endif 1923 case DEVT_NET: 1924 loaded_image->DeviceHandle = 1925 efi_find_handle(dev->d_dev, dev->d_unit); 1926 break; 1927 default: 1928 hd = efiblk_get_pdinfo(dev); 1929 if (STAILQ_EMPTY(&hd->pd_part)) { 1930 loaded_image->DeviceHandle = hd->pd_handle; 1931 break; 1932 } 1933 d_dev = (struct disk_devdesc *)dev; 1934 STAILQ_FOREACH(pd, &hd->pd_part, pd_link) { 1935 /* 1936 * d_partition should be 255 1937 */ 1938 if (pd->pd_unit == (uint32_t)d_dev->d_slice) { 1939 loaded_image->DeviceHandle = 1940 pd->pd_handle; 1941 break; 1942 } 1943 } 1944 break; 1945 } 1946 } 1947 1948 dev_cleanup(); 1949 status = BS->StartImage(loaderhandle, NULL, NULL); 1950 if (status != EFI_SUCCESS) { 1951 command_errmsg = "StartImage failed"; 1952 free(loaded_image->LoadOptions); 1953 loaded_image->LoadOptions = NULL; 1954 status = BS->UnloadImage(loaded_image); 1955 return (CMD_ERROR); 1956 } 1957 1958 return (CMD_ERROR); /* not reached */ 1959 } 1960 1961 COMMAND_SET(chain, "chain", "chain load file", command_chain); 1962 1963 extern struct in_addr servip; 1964 static int 1965 command_netserver(int argc, char *argv[]) 1966 { 1967 char *proto; 1968 n_long rootaddr; 1969 1970 if (argc > 2) { 1971 command_errmsg = "wrong number of arguments"; 1972 return (CMD_ERROR); 1973 } 1974 if (argc < 2) { 1975 proto = netproto == NET_TFTP ? "tftp://" : "nfs://"; 1976 printf("Netserver URI: %s%s%s\n", proto, intoa(rootip.s_addr), 1977 rootpath); 1978 return (CMD_OK); 1979 } 1980 if (argc == 2) { 1981 strncpy(rootpath, argv[1], sizeof(rootpath)); 1982 rootpath[sizeof(rootpath) -1] = '\0'; 1983 if ((rootaddr = net_parse_rootpath()) != INADDR_NONE) 1984 servip.s_addr = rootip.s_addr = rootaddr; 1985 return (CMD_OK); 1986 } 1987 return (CMD_ERROR); /* not reached */ 1988 1989 } 1990 1991 COMMAND_SET(netserver, "netserver", "change or display netserver URI", 1992 command_netserver); 1993