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