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