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