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