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