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