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