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