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