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