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