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