main.c 43.8 KB
Newer Older
Rui Paulo's avatar
Rui Paulo committed
1
2
3
4
5
/*-
 * Copyright (c) 2008-2010 Rui Paulo
 * Copyright (c) 2006 Marcel Moolenaar
 * All rights reserved.
 *
6
 * Copyright (c) 2016-2019 Netflix, Inc. written by M. Warner Losh
Warner Losh's avatar
Warner Losh committed
7
 * 
Rui Paulo's avatar
Rui Paulo committed
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

33
34
#include <stand.h>

35
#include <sys/disk.h>
Steven Hartland's avatar
Steven Hartland committed
36
#include <sys/param.h>
37
#include <sys/reboot.h>
38
#include <sys/boot.h>
Toomas Soome's avatar
Toomas Soome committed
39
#ifdef EFI_ZFS_BOOT
40
#include <sys/zfs_bootenv.h>
Toomas Soome's avatar
Toomas Soome committed
41
#endif
42
#include <paths.h>
43
44
#include <netinet/in.h>
#include <netinet/in_systm.h>
45
#include <stdint.h>
Rui Paulo's avatar
Rui Paulo committed
46
47
#include <string.h>
#include <setjmp.h>
48
#include <disk.h>
49
50
#include <dev_net.h>
#include <net.h>
Rui Paulo's avatar
Rui Paulo committed
51
52
53

#include <efi.h>
#include <efilib.h>
54
#include <efichar.h>
Rui Paulo's avatar
Rui Paulo committed
55

56
57
#include <uuid.h>

Rui Paulo's avatar
Rui Paulo committed
58
#include <bootstrap.h>
Rui Paulo's avatar
Rui Paulo committed
59
60
#include <smbios.h>

Warner Losh's avatar
Warner Losh committed
61
#include "efizfs.h"
Steven Hartland's avatar
Steven Hartland committed
62

63
#include "loader_efi.h"
Rui Paulo's avatar
Rui Paulo committed
64
65
66
67
68
69
70
71
72
73

struct arch_switch archsw;	/* MI/MD interface boundary */

EFI_GUID acpi = ACPI_TABLE_GUID;
EFI_GUID acpi20 = ACPI_20_TABLE_GUID;
EFI_GUID devid = DEVICE_PATH_PROTOCOL;
EFI_GUID imgid = LOADED_IMAGE_PROTOCOL;
EFI_GUID mps = MPS_TABLE_GUID;
EFI_GUID netid = EFI_SIMPLE_NETWORK_PROTOCOL;
EFI_GUID smbios = SMBIOS_TABLE_GUID;
Ed Maste's avatar
Ed Maste committed
74
EFI_GUID smbios3 = SMBIOS3_TABLE_GUID;
75
76
EFI_GUID dxe = DXE_SERVICES_TABLE_GUID;
EFI_GUID hoblist = HOB_LIST_TABLE_GUID;
Ed Maste's avatar
Ed Maste committed
77
78
79
EFI_GUID lzmadecomp = LZMA_DECOMPRESSION_GUID;
EFI_GUID mpcore = ARM_MP_CORE_INFO_TABLE_GUID;
EFI_GUID esrt = ESRT_TABLE_GUID;
80
81
EFI_GUID memtype = MEMORY_TYPE_INFORMATION_TABLE_GUID;
EFI_GUID debugimg = DEBUG_IMAGE_INFO_TABLE_GUID;
82
EFI_GUID fdtdtb = FDT_TABLE_GUID;
83
EFI_GUID inputid = SIMPLE_TEXT_INPUT_PROTOCOL;
Rui Paulo's avatar
Rui Paulo committed
84

Warner Losh's avatar
Warner Losh committed
85
86
87
88
89
90
91
92
93
/*
 * Number of seconds to wait for a keystroke before exiting with failure
 * in the event no currdev is found. -2 means always break, -1 means
 * never break, 0 means poll once and then reboot, > 0 means wait for
 * that many seconds. "fail_timeout" can be set in the environment as
 * well.
 */
static int fail_timeout = 5;

94
95
96
97
98
/*
 * Current boot variable
 */
UINT16 boot_current;

99
100
101
102
103
/*
 * Image that we booted from.
 */
EFI_LOADED_IMAGE *boot_img;

Warner Losh's avatar
Warner Losh committed
104
static bool
105
106
107
108
109
110
has_keyboard(void)
{
	EFI_STATUS status;
	EFI_DEVICE_PATH *path;
	EFI_HANDLE *hin, *hin_end, *walker;
	UINTN sz;
Warner Losh's avatar
Warner Losh committed
111
	bool retval = false;
Warner Losh's avatar
Warner Losh committed
112

113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
	/*
	 * Find all the handles that support the SIMPLE_TEXT_INPUT_PROTOCOL and
	 * do the typical dance to get the right sized buffer.
	 */
	sz = 0;
	hin = NULL;
	status = BS->LocateHandle(ByProtocol, &inputid, 0, &sz, 0);
	if (status == EFI_BUFFER_TOO_SMALL) {
		hin = (EFI_HANDLE *)malloc(sz);
		status = BS->LocateHandle(ByProtocol, &inputid, 0, &sz,
		    hin);
		if (EFI_ERROR(status))
			free(hin);
	}
	if (EFI_ERROR(status))
		return retval;

	/*
	 * Look at each of the handles. If it supports the device path protocol,
	 * use it to get the device path for this handle. Then see if that
	 * device path matches either the USB device path for keyboards or the
	 * legacy device path for keyboards.
	 */
	hin_end = &hin[sz / sizeof(*hin)];
	for (walker = hin; walker < hin_end; walker++) {
138
		status = OpenProtocolByHandle(*walker, &devid, (void **)&path);
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
		if (EFI_ERROR(status))
			continue;

		while (!IsDevicePathEnd(path)) {
			/*
			 * Check for the ACPI keyboard node. All PNP3xx nodes
			 * are keyboards of different flavors. Note: It is
			 * unclear of there's always a keyboard node when
			 * there's a keyboard controller, or if there's only one
			 * when a keyboard is detected at boot.
			 */
			if (DevicePathType(path) == ACPI_DEVICE_PATH &&
			    (DevicePathSubType(path) == ACPI_DP ||
				DevicePathSubType(path) == ACPI_EXTENDED_DP)) {
				ACPI_HID_DEVICE_PATH  *acpi;

				acpi = (ACPI_HID_DEVICE_PATH *)(void *)path;
				if ((EISA_ID_TO_NUM(acpi->HID) & 0xff00) == 0x300 &&
				    (acpi->HID & 0xffff) == PNP_EISA_ID_CONST) {
Warner Losh's avatar
Warner Losh committed
158
					retval = true;
159
160
161
162
163
164
165
166
167
168
					goto out;
				}
			/*
			 * Check for USB keyboard node, if present. Unlike a
			 * PS/2 keyboard, these definitely only appear when
			 * connected to the system.
			 */
			} else if (DevicePathType(path) == MESSAGING_DEVICE_PATH &&
			    DevicePathSubType(path) == MSG_USB_CLASS_DP) {
				USB_CLASS_DEVICE_PATH *usb;
Warner Losh's avatar
Warner Losh committed
169

170
171
172
173
				usb = (USB_CLASS_DEVICE_PATH *)(void *)path;
				if (usb->DeviceClass == 3 && /* HID */
				    usb->DeviceSubClass == 1 && /* Boot devices */
				    usb->DeviceProtocol == 1) { /* Boot keyboards */
Warner Losh's avatar
Warner Losh committed
174
					retval = true;
175
176
177
178
179
180
181
182
183
184
185
					goto out;
				}
			}
			path = NextDevicePathNode(path);
		}
	}
out:
	free(hin);
	return retval;
}

186
187
188
189
static void
set_currdev(const char *devname)
{

190
191
192
193
194
195
196
197
198
199
200
	/*
	 * Don't execute hooks here; we may need to try setting these more than
	 * once here if we're probing for the ZFS pool we're supposed to boot.
	 * The currdev hook is intended to just validate user input anyways,
	 * while the loaddev hook makes it immutable once we've determined what
	 * the proper currdev is.
	 */
	env_setenv("currdev", EV_VOLATILE | EV_NOHOOK, devname, efi_setcurrdev,
	    env_nounset);
	env_setenv("loaddev", EV_VOLATILE | EV_NOHOOK, devname, env_noset,
	    env_nounset);
201
202
}

203
static void
Warner Losh's avatar
Warner Losh committed
204
205
206
207
208
209
set_currdev_devdesc(struct devdesc *currdev)
{
	const char *devname;

	devname = efi_fmtdev(currdev);
	printf("Setting currdev to %s\n", devname);
210
	set_currdev(devname);
Warner Losh's avatar
Warner Losh committed
211
212
213
214
}

static void
set_currdev_devsw(struct devsw *dev, int unit)
215
216
217
218
219
{
	struct devdesc currdev;

	currdev.d_dev = dev;
	currdev.d_unit = unit;
Warner Losh's avatar
Warner Losh committed
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238

	set_currdev_devdesc(&currdev);
}

static void
set_currdev_pdinfo(pdinfo_t *dp)
{

	/*
	 * Disks are special: they have partitions. if the parent
	 * pointer is non-null, we're a partition not a full disk
	 * and we need to adjust currdev appropriately.
	 */
	if (dp->pd_devsw->dv_type == DEVT_DISK) {
		struct disk_devdesc currdev;

		currdev.dd.d_dev = dp->pd_devsw;
		if (dp->pd_parent == NULL) {
			currdev.dd.d_unit = dp->pd_unit;
239
240
			currdev.d_slice = D_SLICENONE;
			currdev.d_partition = D_PARTNONE;
Warner Losh's avatar
Warner Losh committed
241
242
243
		} else {
			currdev.dd.d_unit = dp->pd_parent->pd_unit;
			currdev.d_slice = dp->pd_unit;
244
			currdev.d_partition = D_PARTISGPT; /* XXX Assumes GPT */
Warner Losh's avatar
Warner Losh committed
245
246
247
248
249
250
251
252
253
254
255
256
		}
		set_currdev_devdesc((struct devdesc *)&currdev);
	} else {
		set_currdev_devsw(dp->pd_devsw, dp->pd_unit);
	}
}

static bool
sanity_check_currdev(void)
{
	struct stat st;

257
	return (stat(PATH_DEFAULTS_LOADER_CONF, &st) == 0 ||
258
259
260
#ifdef PATH_BOOTABLE_TOKEN
	    stat(PATH_BOOTABLE_TOKEN, &st) == 0 || /* non-standard layout */
#endif
261
	    stat(PATH_KERNEL, &st) == 0);
Warner Losh's avatar
Warner Losh committed
262
263
264
265
266
267
268
269
}

#ifdef EFI_ZFS_BOOT
static bool
probe_zfs_currdev(uint64_t guid)
{
	char *devname;
	struct zfs_devdesc currdev;
270
271
	char *buf = NULL;
	bool rv;
Warner Losh's avatar
Warner Losh committed
272
273
274
275
276
277

	currdev.dd.d_dev = &zfs_dev;
	currdev.dd.d_unit = 0;
	currdev.pool_guid = guid;
	currdev.root_guid = 0;
	set_currdev_devdesc((struct devdesc *)&currdev);
278
	devname = efi_fmtdev(&currdev);
279
	init_zfs_boot_options(devname);
280

281
282
283
284
	rv = sanity_check_currdev();
	if (rv) {
		buf = malloc(VDEV_PAD_SIZE);
		if (buf != NULL) {
285
286
287
			if (zfs_get_bootonce(&currdev, OS_BOOTONCE, buf,
			    VDEV_PAD_SIZE) == 0) {
				printf("zfs bootonce: %s\n", buf);
288
				set_currdev(buf);
289
				setenv("zfs-bootonce", buf, 1);
290
291
			}
			free(buf);
292
			(void) zfs_attach_nvstore(&currdev);
293
294
295
		}
	}
	return (rv);
Warner Losh's avatar
Warner Losh committed
296
297
298
}
#endif

299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
#ifdef MD_IMAGE_SIZE
static bool
probe_md_currdev(void)
{
	extern struct devsw md_dev;
	bool rv;

	set_currdev_devsw(&md_dev, 0);
	rv = sanity_check_currdev();
	if (!rv)
		printf("MD not present\n");
	return (rv);
}
#endif

Warner Losh's avatar
Warner Losh committed
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
static bool
try_as_currdev(pdinfo_t *hd, pdinfo_t *pp)
{
	uint64_t guid;

#ifdef EFI_ZFS_BOOT
	/*
	 * If there's a zpool on this device, try it as a ZFS
	 * filesystem, which has somewhat different setup than all
	 * other types of fs due to imperfect loader integration.
	 * This all stems from ZFS being both a device (zpool) and
	 * a filesystem, plus the boot env feature.
	 */
	if (efizfs_get_guid_by_handle(pp->pd_handle, &guid))
		return (probe_zfs_currdev(guid));
#endif
	/*
	 * All other filesystems just need the pdinfo
	 * initialized in the standard way.
	 */
	set_currdev_pdinfo(pp);
	return (sanity_check_currdev());
336
337
}

338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
/*
 * Sometimes we get filenames that are all upper case
 * and/or have backslashes in them. Filter all this out
 * if it looks like we need to do so.
 */
static void
fix_dosisms(char *p)
{
	while (*p) {
		if (isupper(*p))
			*p = tolower(*p);
		else if (*p == '\\')
			*p = '/';
		p++;
	}
}

Warner Losh's avatar
Warner Losh committed
355
356
#define SIZE(dp, edp) (size_t)((intptr_t)(void *)edp - (intptr_t)(void *)dp)

357
358
enum { BOOT_INFO_OK = 0, BAD_CHOICE = 1, NOT_SPECIFIC = 2  };
static int
359
match_boot_info(char *boot_info, size_t bisz)
360
361
362
363
364
365
366
367
368
369
370
{
	uint32_t attr;
	uint16_t fplen;
	size_t len;
	char *walker, *ep;
	EFI_DEVICE_PATH *dp, *edp, *first_dp, *last_dp;
	pdinfo_t *pp;
	CHAR16 *descr;
	char *kernel = NULL;
	FILEPATH_DEVICE_PATH  *fp;
	struct stat st;
Warner Losh's avatar
Warner Losh committed
371
	CHAR16 *text;
372
373

	/*
374
	 * FreeBSD encodes its boot loading path into the boot loader
375
	 * BootXXXX variable. We look for the last one in the path
376
	 * and use that to load the kernel. However, if we only find
377
378
379
380
381
382
383
384
385
386
	 * one DEVICE_PATH, then there's nothing specific and we should
	 * fall back.
	 *
	 * In an ideal world, we'd look at the image handle we were
	 * passed, match up with the loader we are and then return the
	 * next one in the path. This would be most flexible and cover
	 * many chain booting scenarios where you need to use this
	 * boot loader to get to the next boot loader. However, that
	 * doesn't work. We rarely have the path to the image booted
	 * (just the device) so we can't count on that. So, we do the
387
388
	 * next best thing: we look through the device path(s) passed
	 * in the BootXXXX variable. If there's only one, we return
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
	 * NOT_SPECIFIC. Otherwise, we look at the last one and try to
	 * load that. If we can, we return BOOT_INFO_OK. Otherwise we
	 * return BAD_CHOICE for the caller to sort out.
	 */
	if (bisz < sizeof(attr) + sizeof(fplen) + sizeof(CHAR16))
		return NOT_SPECIFIC;
	walker = boot_info;
	ep = walker + bisz;
	memcpy(&attr, walker, sizeof(attr));
	walker += sizeof(attr);
	memcpy(&fplen, walker, sizeof(fplen));
	walker += sizeof(fplen);
	descr = (CHAR16 *)(intptr_t)walker;
	len = ucs2len(descr);
	walker += (len + 1) * sizeof(CHAR16);
	last_dp = first_dp = dp = (EFI_DEVICE_PATH *)walker;
	edp = (EFI_DEVICE_PATH *)(walker + fplen);
	if ((char *)edp > ep)
		return NOT_SPECIFIC;
Warner Losh's avatar
Warner Losh committed
408
	while (dp < edp && SIZE(dp, edp) > sizeof(EFI_DEVICE_PATH)) {
Warner Losh's avatar
Warner Losh committed
409
410
411
412
413
		text = efi_devpath_name(dp);
		if (text != NULL) {
			printf("   BootInfo Path: %S\n", text);
			efi_free_devpath_name(text);
		}
414
415
416
417
418
419
		last_dp = dp;
		dp = (EFI_DEVICE_PATH *)((char *)dp + efi_devpath_length(dp));
	}

	/*
	 * If there's only one item in the list, then nothing was
420
421
422
423
	 * specified. Or if the last path doesn't have a media
	 * path in it. Those show up as various VenHw() nodes
	 * which are basically opaque to us. Don't count those
	 * as something specifc.
424
	 */
Warner Losh's avatar
Warner Losh committed
425
	if (last_dp == first_dp) {
426
		printf("Ignoring Boot%04x: Only one DP found\n", boot_current);
427
		return NOT_SPECIFIC;
Warner Losh's avatar
Warner Losh committed
428
	}
429
430
	if (efi_devpath_to_media_path(last_dp) == NULL) {
		printf("Ignoring Boot%04x: No Media Path\n", boot_current);
431
		return NOT_SPECIFIC;
Warner Losh's avatar
Warner Losh committed
432
	}
433
434
435
436
437
438

	/*
	 * OK. At this point we either have a good path or a bad one.
	 * Let's check.
	 */
	pp = efiblk_get_pdinfo_by_device_path(last_dp);
Warner Losh's avatar
Warner Losh committed
439
	if (pp == NULL) {
440
		printf("Ignoring Boot%04x: Device Path not found\n", boot_current);
441
		return BAD_CHOICE;
Warner Losh's avatar
Warner Losh committed
442
	}
443
	set_currdev_pdinfo(pp);
Warner Losh's avatar
Warner Losh committed
444
	if (!sanity_check_currdev()) {
445
		printf("Ignoring Boot%04x: sanity check failed\n", boot_current);
446
		return BAD_CHOICE;
Warner Losh's avatar
Warner Losh committed
447
	}
448
449
450
451
452
453
454
455
456
457
458

	/*
	 * OK. We've found a device that matches, next we need to check the last
	 * component of the path. If it's a file, then we set the default kernel
	 * to that. Otherwise, just use this as the default root.
	 *
	 * Reminder: we're running very early, before we've parsed the defaults
	 * file, so we may need to have a hack override.
	 */
	dp = efi_devpath_last_node(last_dp);
	if (DevicePathType(dp) !=  MEDIA_DEVICE_PATH ||
Warner Losh's avatar
Warner Losh committed
459
	    DevicePathSubType(dp) != MEDIA_FILEPATH_DP) {
460
		printf("Using Boot%04x for root partition\n", boot_current);
461
		return (BOOT_INFO_OK);		/* use currdir, default kernel */
Warner Losh's avatar
Warner Losh committed
462
	}
463
464
	fp = (FILEPATH_DEVICE_PATH *)dp;
	ucs2_to_utf8(fp->PathName, &kernel);
Warner Losh's avatar
Warner Losh committed
465
	if (kernel == NULL) {
466
		printf("Not using Boot%04x: can't decode kernel\n", boot_current);
467
		return (BAD_CHOICE);
Warner Losh's avatar
Warner Losh committed
468
	}
469
470
471
472
	if (*kernel == '\\' || isupper(*kernel))
		fix_dosisms(kernel);
	if (stat(kernel, &st) != 0) {
		free(kernel);
473
474
		printf("Not using Boot%04x: can't find %s\n", boot_current,
		    kernel);
475
476
477
478
		return (BAD_CHOICE);
	}
	setenv("kernel", kernel, 1);
	free(kernel);
Warner Losh's avatar
Warner Losh committed
479
480
	text = efi_devpath_name(last_dp);
	if (text) {
481
		printf("Using Boot%04x %S + %s\n", boot_current, text,
482
		    kernel);
Warner Losh's avatar
Warner Losh committed
483
484
		efi_free_devpath_name(text);
	}
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505

	return (BOOT_INFO_OK);
}

/*
 * Look at the passed-in boot_info, if any. If we find it then we need
 * to see if we can find ourselves in the boot chain. If we can, and
 * there's another specified thing to boot next, assume that the file
 * is loaded from / and use that for the root filesystem. If can't
 * find the specified thing, we must fail the boot. If we're last on
 * the list, then we fallback to looking for the first available /
 * candidate (ZFS, if there's a bootable zpool, otherwise a UFS
 * partition that has either /boot/defaults/loader.conf on it or
 * /boot/kernel/kernel (the default kernel) that we can use.
 *
 * We always fail if we can't find the right thing. However, as
 * a concession to buggy UEFI implementations, like u-boot, if
 * we have determined that the host is violating the UEFI boot
 * manager protocol, we'll signal the rest of the program that
 * a drop to the OK boot loader prompt is possible.
 */
506
static int
507
find_currdev(bool do_bootmgr, bool is_last,
508
    char *boot_info, size_t boot_info_sz)
509
{
510
	pdinfo_t *dp, *pp;
511
512
	EFI_DEVICE_PATH *devpath, *copy;
	EFI_HANDLE h;
Warner Losh's avatar
Warner Losh committed
513
	CHAR16 *text;
514
515
516
	struct devsw *dev;
	int unit;
	uint64_t extra;
517
	int rv;
518
519
	char *rootdev;

520
521
522
523
	/*
	 * First choice: if rootdev is already set, use that, even if
	 * it's wrong.
	 */
524
525
	rootdev = getenv("rootdev");
	if (rootdev != NULL) {
Warner Losh's avatar
Warner Losh committed
526
527
		printf("    Setting currdev to configured rootdev %s\n",
		    rootdev);
528
529
530
		set_currdev(rootdev);
		return (0);
	}
531

532
	/*
Warner Losh's avatar
Warner Losh committed
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
	 * Second choice: If uefi_rootdev is set, translate that UEFI device
	 * path to the loader's internal name and use that.
	 */
	do {
		rootdev = getenv("uefi_rootdev");
		if (rootdev == NULL)
			break;
		devpath = efi_name_to_devpath(rootdev);
		if (devpath == NULL)
			break;
		dp = efiblk_get_pdinfo_by_device_path(devpath);
		efi_devpath_free(devpath);
		if (dp == NULL)
			break;
		printf("    Setting currdev to UEFI path %s\n",
		    rootdev);
		set_currdev_pdinfo(dp);
		return (0);
	} while (0);

	/*
	 * Third choice: If we can find out image boot_info, and there's
555
556
557
558
559
560
561
	 * a follow-on boot image in that boot_info, use that. In this
	 * case root will be the partition specified in that image and
	 * we'll load the kernel specified by the file path. Should there
	 * not be a filepath, we use the default. This filepath overrides
	 * loader.conf.
	 */
	if (do_bootmgr) {
562
		rv = match_boot_info(boot_info, boot_info_sz);
563
564
565
566
567
568
569
570
571
		switch (rv) {
		case BOOT_INFO_OK:	/* We found it */
			return (0);
		case BAD_CHOICE:	/* specified file not found -> error */
			/* XXX do we want to have an escape hatch for last in boot order? */
			return (ENOENT);
		} /* Nothing specified, try normal match */
	}

572
#ifdef EFI_ZFS_BOOT
Warner Losh's avatar
Warner Losh committed
573
574
575
576
577
578
579
	/*
	 * Did efi_zfs_probe() detect the boot pool? If so, use the zpool
	 * it found, if it's sane. ZFS is the only thing that looks for
	 * disks and pools to boot. This may change in the future, however,
	 * if we allow specifying which pool to boot from via UEFI variables
	 * rather than the bootenv stuff that FreeBSD uses today.
	 */
580
	if (pool_guid != 0) {
Warner Losh's avatar
Warner Losh committed
581
582
		printf("Trying ZFS pool\n");
		if (probe_zfs_currdev(pool_guid))
583
584
			return (0);
	}
Warner Losh's avatar
Warner Losh committed
585
#endif /* EFI_ZFS_BOOT */
586

587
588
589
590
591
592
593
594
595
#ifdef MD_IMAGE_SIZE
	/*
	 * If there is an embedded MD, try to use that.
	 */
	printf("Trying MD\n");
	if (probe_md_currdev())
		return (0);
#endif /* MD_IMAGE_SIZE */

Warner Losh's avatar
Warner Losh committed
596
597
598
599
600
601
602
603
	/*
	 * Try to find the block device by its handle based on the
	 * image we're booting. If we can't find a sane partition,
	 * search all the other partitions of the disk. We do not
	 * search other disks because it's a violation of the UEFI
	 * boot protocol to do so. We fail and let UEFI go on to
	 * the next candidate.
	 */
604
	dp = efiblk_get_pdinfo_by_handle(boot_img->DeviceHandle);
Warner Losh's avatar
Warner Losh committed
605
606
607
608
609
	if (dp != NULL) {
		text = efi_devpath_name(dp->pd_devpath);
		if (text != NULL) {
			printf("Trying ESP: %S\n", text);
			efi_free_devpath_name(text);
610
		}
Warner Losh's avatar
Warner Losh committed
611
612
		set_currdev_pdinfo(dp);
		if (sanity_check_currdev())
613
			return (0);
Warner Losh's avatar
Warner Losh committed
614
		if (dp->pd_parent != NULL) {
Warner Losh's avatar
Warner Losh committed
615
			pdinfo_t *espdp = dp;
Warner Losh's avatar
Warner Losh committed
616
617
			dp = dp->pd_parent;
			STAILQ_FOREACH(pp, &dp->pd_part, pd_link) {
Warner Losh's avatar
Warner Losh committed
618
619
620
				/* Already tried the ESP */
				if (espdp == pp)
					continue;
Warner Losh's avatar
Warner Losh committed
621
622
623
				/*
				 * Roll up the ZFS special case
				 * for those partitions that have
624
				 * zpools on them.
Warner Losh's avatar
Warner Losh committed
625
				 */
Warner Losh's avatar
Warner Losh committed
626
627
628
629
630
				text = efi_devpath_name(pp->pd_devpath);
				if (text != NULL) {
					printf("Trying: %S\n", text);
					efi_free_devpath_name(text);
				}
Warner Losh's avatar
Warner Losh committed
631
632
633
				if (try_as_currdev(dp, pp))
					return (0);
			}
634
635
		}
	}
636
637
638
639
640

	/*
	 * Try the device handle from our loaded image first.  If that
	 * fails, use the device path from the loaded image and see if
	 * any of the nodes in that path match one of the enumerated
Warner Losh's avatar
Warner Losh committed
641
	 * handles. Currently, this handle list is only for netboot.
642
	 */
643
	if (efi_handle_lookup(boot_img->DeviceHandle, &dev, &unit, &extra) == 0) {
Warner Losh's avatar
Warner Losh committed
644
645
646
		set_currdev_devsw(dev, unit);
		if (sanity_check_currdev())
			return (0);
647
	}
648
649
650
651
652
653
654
655

	copy = NULL;
	devpath = efi_lookup_image_devpath(IH);
	while (devpath != NULL) {
		h = efi_devpath_handle(devpath);
		if (h == NULL)
			break;

656
657
658
		free(copy);
		copy = NULL;

659
		if (efi_handle_lookup(h, &dev, &unit, &extra) == 0) {
Warner Losh's avatar
Warner Losh committed
660
661
662
			set_currdev_devsw(dev, unit);
			if (sanity_check_currdev())
				return (0);
663
		}
664
665
666
667
668
669
670

		devpath = efi_lookup_devpath(h);
		if (devpath != NULL) {
			copy = efi_devpath_trim(devpath);
			devpath = copy;
		}
	}
671
	free(copy);
672
673
674
675

	return (ENOENT);
}

Warner Losh's avatar
Warner Losh committed
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
static bool
interactive_interrupt(const char *msg)
{
	time_t now, then, last;

	last = 0;
	now = then = getsecs();
	printf("%s\n", msg);
	if (fail_timeout == -2)		/* Always break to OK */
		return (true);
	if (fail_timeout == -1)		/* Never break to OK */
		return (false);
	do {
		if (last != now) {
			printf("press any key to interrupt reboot in %d seconds\r",
			    fail_timeout - (int)(now - then));
			last = now;
		}

		/* XXX no pause or timeout wait for char */
		if (ischar())
			return (true);
		now = getsecs();
	} while (now - then < fail_timeout);
	return (false);
}

703
704
static int
parse_args(int argc, CHAR16 *argv[])
Rui Paulo's avatar
Rui Paulo committed
705
{
706
707
	int i, j, howto;
	bool vargood;
708
	char var[128];
709

710
	/*
711
712
	 * Parse the args to set the console settings, etc
	 * boot1.efi passes these in, if it can read /boot.config or /boot/config
Warner Losh's avatar
Warner Losh committed
713
714
715
	 * or iPXE may be setup to pass these in. Or the optional argument in the
	 * boot environment was used to pass these arguments in (in which case
	 * neither /boot.config nor /boot/config are consulted).
716
	 *
717
718
719
	 * Loop through the args, and for each one that contains an '=' that is
	 * not the first character, add it to the environment.  This allows
	 * loader and kernel env vars to be passed on the command line.  Convert
Warner Losh's avatar
Warner Losh committed
720
721
	 * args from UCS-2 to ASCII (16 to 8 bit) as they are copied (though this
	 * method is flawed for non-ASCII characters).
722
	 */
723
	howto = 0;
724
	for (i = 1; i < argc; i++) {
725
726
		cpy16to8(argv[i], var, sizeof(var));
		howto |= boot_parse_arg(var);
727
	}
728

729
730
731
	return (howto);
}

732
733
734
735
736
737
738
739
740
static void
setenv_int(const char *key, int val)
{
	char buf[20];

	snprintf(buf, sizeof(buf), "%d", val);
	setenv(key, buf, 1);
}

741
742
743
744
745
746
/*
 * Parse ConOut (the list of consoles active) and see if we can find a
 * serial port and/or a video port. It would be nice to also walk the
 * ACPI name space to map the UID for the serial port to a port. The
 * latter is especially hard.
 */
747
int
748
749
750
751
752
753
754
755
756
757
758
759
760
761
parse_uefi_con_out(void)
{
	int how, rv;
	int vid_seen = 0, com_seen = 0, seen = 0;
	size_t sz;
	char buf[4096], *ep;
	EFI_DEVICE_PATH *node;
	ACPI_HID_DEVICE_PATH  *acpi;
	UART_DEVICE_PATH  *uart;
	bool pci_pending;

	how = 0;
	sz = sizeof(buf);
	rv = efi_global_getenv("ConOut", buf, &sz);
762
763
	if (rv != EFI_SUCCESS)
		rv = efi_global_getenv("ConOutDev", buf, &sz);
764
765
766
	if (rv != EFI_SUCCESS) {
		/* If we don't have any ConOut default to serial */
		how = RB_SERIAL;
767
		goto out;
768
	}
769
770
	ep = buf + sz;
	node = (EFI_DEVICE_PATH *)buf;
Warner Losh's avatar
Warner Losh committed
771
	while ((char *)node < ep) {
Warner Losh's avatar
Warner Losh committed
772
773
774
775
		if (IsDevicePathEndType(node)) {
			if (pci_pending && vid_seen == 0)
				vid_seen = ++seen;
		}
776
777
		pci_pending = false;
		if (DevicePathType(node) == ACPI_DEVICE_PATH &&
778
779
		    (DevicePathSubType(node) == ACPI_DP ||
		    DevicePathSubType(node) == ACPI_EXTENDED_DP)) {
780
781
			/* Check for Serial node */
			acpi = (void *)node;
782
783
			if (EISA_ID_TO_NUM(acpi->HID) == 0x501) {
				setenv_int("efi_8250_uid", acpi->UID);
784
				com_seen = ++seen;
785
			}
786
787
		} else if (DevicePathType(node) == MESSAGING_DEVICE_PATH &&
		    DevicePathSubType(node) == MSG_UART_DP) {
788
			com_seen = ++seen;
789
			uart = (void *)node;
790
			setenv_int("efi_com_speed", uart->BaudRate);
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
		} else if (DevicePathType(node) == ACPI_DEVICE_PATH &&
		    DevicePathSubType(node) == ACPI_ADR_DP) {
			/* Check for AcpiAdr() Node for video */
			vid_seen = ++seen;
		} else if (DevicePathType(node) == HARDWARE_DEVICE_PATH &&
		    DevicePathSubType(node) == HW_PCI_DP) {
			/*
			 * Note, vmware fusion has a funky console device
			 *	PciRoot(0x0)/Pci(0xf,0x0)
			 * which we can only detect at the end since we also
			 * have to cope with:
			 *	PciRoot(0x0)/Pci(0x1f,0x0)/Serial(0x1)
			 * so only match it if it's last.
			 */
			pci_pending = true;
		}
807
		node = NextDevicePathNode(node);
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
	}

	/*
	 * Truth table for RB_MULTIPLE | RB_SERIAL
	 * Value		Result
	 * 0			Use only video console
	 * RB_SERIAL		Use only serial console
	 * RB_MULTIPLE		Use both video and serial console
	 *			(but video is primary so gets rc messages)
	 * both			Use both video and serial console
	 *			(but serial is primary so gets rc messages)
	 *
	 * Try to honor this as best we can. If only one of serial / video
	 * found, then use that. Otherwise, use the first one we found.
	 * This also implies if we found nothing, default to video.
	 */
	how = 0;
	if (vid_seen && com_seen) {
		how |= RB_MULTIPLE;
		if (com_seen < vid_seen)
			how |= RB_SERIAL;
	} else if (com_seen)
		how |= RB_SERIAL;
out:
	return (how);
}
834

835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
void
parse_loader_efi_config(EFI_HANDLE h, const char *env_fn)
{
	pdinfo_t *dp;
	struct stat st;
	int fd = -1;
	char *env = NULL;

	dp = efiblk_get_pdinfo_by_handle(h);
	if (dp == NULL)
		return;
	set_currdev_pdinfo(dp);
	if (stat(env_fn, &st) != 0)
		return;
	fd = open(env_fn, O_RDONLY);
	if (fd == -1)
		return;
	env = malloc(st.st_size + 1);
	if (env == NULL)
		goto out;
	if (read(fd, env, st.st_size) != st.st_size)
		goto out;
	env[st.st_size] = '\0';
	boot_parse_cmdline(env);
out:
	free(env);
	close(fd);
}

static void
read_loader_env(const char *name, char *def_fn, bool once)
{
	UINTN len;
	char *fn, *freeme = NULL;

	len = 0;
	fn = def_fn;
	if (efi_freebsd_getenv(name, NULL, &len) == EFI_BUFFER_TOO_SMALL) {
		freeme = fn = malloc(len + 1);
		if (fn != NULL) {
			if (efi_freebsd_getenv(name, fn, &len) != EFI_SUCCESS) {
				free(fn);
				fn = NULL;
				printf(
			    "Can't fetch FreeBSD::%s we know is there\n", name);
			} else {
				/*
				 * if tagged as 'once' delete the env variable so we
				 * only use it once.
				 */
				if (once)
					efi_freebsd_delenv(name);
				/*
				 * We malloced 1 more than len above, then redid the call.
				 * so now we have room at the end of the string to NUL terminate
				 * it here, even if the typical idium would have '- 1' here to
				 * not overflow. len should be the same on return both times.
				 */
				fn[len] = '\0';
			}
		} else {
			printf(
		    "Can't allocate %d bytes to fetch FreeBSD::%s env var\n",
			    len, name);
		}
	}
	if (fn) {
		printf("    Reading loader env vars from %s\n", fn);
		parse_loader_efi_config(boot_img->DeviceHandle, fn);
	}
}

Warner Losh's avatar
Warner Losh committed
907
908
909
910
911
caddr_t
ptov(uintptr_t x)
{
	return ((caddr_t)x);
}
912

913
914
915
916
EFI_STATUS
main(int argc, CHAR16 *argv[])
{
	EFI_GUID *guid;
917
	int howto, i, uhowto;
918
	UINTN k;
919
	bool has_kbd, is_last;
920
921
922
	char *s;
	EFI_DEVICE_PATH *imgpath;
	CHAR16 *text;
923
924
	EFI_STATUS rv;
	size_t sz, bosz = 0, bisz = 0;
925
	UINT16 boot_order[100];
926
927
928
	char boot_info[4096];
	char buf[32];
	bool uefi_boot_mgr;
929

Colin Percival's avatar
Colin Percival committed
930
931
	tslog_init();

932
933
934
935
	archsw.arch_autoload = efi_autoload;
	archsw.arch_getdev = efi_getdev;
	archsw.arch_copyin = efi_copyin;
	archsw.arch_copyout = efi_copyout;
936
#ifdef __amd64__
937
	archsw.arch_hypervisor = x86_hypervisor;
938
#endif
939
940
941
942
	archsw.arch_readin = efi_readin;
	archsw.arch_zfs_probe = efi_zfs_probe;

        /* Get our loaded image protocol interface structure. */
943
	(void) OpenProtocolByHandle(IH, &imgid, (void **)&boot_img);
944

945
946
947
948
949
950
951
952
953
	/*
	 * Chicken-and-egg problem; we want to have console output early, but
	 * some console attributes may depend on reading from eg. the boot
	 * device, which we can't do yet.  We can use printf() etc. once this is
	 * done. So, we set it to the efi console, then call console init. This
	 * gets us printf early, but also primes the pump for all future console
	 * changes to take effect, regardless of where they come from.
	 */
	setenv("console", "efi", 1);
954
	uhowto = parse_uefi_con_out();
955
#if defined(__aarch64__) || defined(__arm__) || defined(__riscv)
956
957
958
	if ((uhowto & RB_SERIAL) != 0)
		setenv("console", "comconsole", 1);
#endif
959
960
	cons_probe();

961
962
963
964
965
966
967
968
	/* Init the time source */
	efi_time_init();

	/*
	 * Initialise the block cache. Set the upper limit.
	 */
	bcache_init(32768, 512);

969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
	/*
	 * Scan the BLOCK IO MEDIA handles then
	 * march through the device switch probing for things.
	 */
	i = efipart_inithandles();
	if (i != 0 && i != ENOENT) {
		printf("efipart_inithandles failed with ERRNO %d, expect "
		    "failures\n", i);
	}

	for (i = 0; devsw[i] != NULL; i++)
		if (devsw[i]->dv_init != NULL)
			(devsw[i]->dv_init)();

	/*
	 * Detect console settings two different ways: one via the command
	 * args (eg -h) or via the UEFI ConOut variable.
	 */
	has_kbd = has_keyboard();
988
989
990
991
	howto = parse_args(argc, argv);
	if (!has_kbd && (howto & RB_PROBE))
		howto |= RB_SERIAL | RB_MULTIPLE;
	howto &= ~RB_PROBE;
Warner Losh's avatar
Warner Losh committed
992

993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
	/*
	 * Read additional environment variables from the boot device's
	 * "LoaderEnv" file. Any boot loader environment variable may be set
	 * there, which are subtly different than loader.conf variables. Only
	 * the 'simple' ones may be set so things like foo_load="YES" won't work
	 * for two reasons.  First, the parser is simplistic and doesn't grok
	 * quotes.  Second, because the variables that cause an action to happen
	 * are parsed by the lua, 4th or whatever code that's not yet
	 * loaded. This is relative to the root directory when loader.efi is
	 * loaded off the UFS root drive (when chain booted), or from the ESP
	 * when directly loaded by the BIOS.
	 *
	 * We also read in NextLoaderEnv if it was specified. This allows next boot
	 * functionality to be implemented and to override anything in LoaderEnv.
	 */
	read_loader_env("LoaderEnv", "/efi/freebsd/loader.env", false);
	read_loader_env("NextLoaderEnv", NULL, true);

Warner Losh's avatar
Warner Losh committed
1011
	/*
1012
	 * We now have two notions of console. howto should be viewed as
1013
	 * overrides. If console is already set, don't set it again.
Warner Losh's avatar
Warner Losh committed
1014
	 */
1015
1016
1017
1018
1019
#define	VIDEO_ONLY	0
#define	SERIAL_ONLY	RB_SERIAL
#define	VID_SER_BOTH	RB_MULTIPLE
#define	SER_VID_BOTH	(RB_SERIAL | RB_MULTIPLE)
#define	CON_MASK	(RB_SERIAL | RB_MULTIPLE)
1020
	if (strcmp(getenv("console"), "efi") == 0) {
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
		if ((howto & CON_MASK) == 0) {
			/* No override, uhowto is controlling and efi cons is perfect */
			howto = howto | (uhowto & CON_MASK);
		} else if ((howto & CON_MASK) == (uhowto & CON_MASK)) {
			/* override matches what UEFI told us, efi console is perfect */
		} else if ((uhowto & (CON_MASK)) != 0) {
			/*
			 * We detected a serial console on ConOut. All possible
			 * overrides include serial. We can't really override what efi
			 * gives us, so we use it knowing it's the best choice.
			 */
1032
			/* Do nothing */
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
		} else {
			/*
			 * We detected some kind of serial in the override, but ConOut
			 * has no serial, so we have to sort out which case it really is.
			 */
			switch (howto & CON_MASK) {
			case SERIAL_ONLY:
				setenv("console", "comconsole", 1);
				break;
			case VID_SER_BOTH:
				setenv("console", "efi comconsole", 1);
				break;
			case SER_VID_BOTH:
				setenv("console", "comconsole efi", 1);
				break;
				/* case VIDEO_ONLY can't happen -- it's the first if above */
			}
1050
1051
		}
	}
Warner Losh's avatar
Warner Losh committed
1052

1053
1054
1055
1056
1057
	/*
	 * howto is set now how we want to export the flags to the kernel, so
	 * set the env based on it.
	 */
	boot_howto_to_env(howto);
1058

1059
	if (efi_copy_init()) {
1060
1061
1062
1063
		printf("failed to allocate staging area\n");
		return (EFI_BUFFER_TOO_SMALL);
	}

Warner Losh's avatar
Warner Losh committed
1064
1065
1066
	if ((s = getenv("fail_timeout")) != NULL)
		fail_timeout = strtol(s, NULL, 10);

Warner Losh's avatar
Warner Losh committed
1067
1068
	printf("%s\n", bootprog_info);
	printf("   Command line arguments:");
Warner Losh's avatar
Warner Losh committed
1069
1070
	for (i = 0; i < argc; i++)
		printf(" %S", argv[i]);
Steven Hartland's avatar
Steven Hartland committed
1071
1072
	printf("\n");

1073
	printf("   Image base: 0x%lx\n", (unsigned long)boot_img->ImageBase);
Warner Losh's avatar
Warner Losh committed
1074
	printf("   EFI version: %d.%02d\n", ST->Hdr.Revision >> 16,
Rui Paulo's avatar
Rui Paulo committed
1075
	    ST->Hdr.Revision & 0xffff);
Warner Losh's avatar
Warner Losh committed
1076
	printf("   EFI Firmware: %S (rev %d.%02d)\n", ST->FirmwareVendor,
1077
	    ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff);
1078
1079
	printf("   Console: %s (%#x)\n", getenv("console"), howto);

Warner Losh's avatar
Warner Losh committed
1080
	/* Determine the devpath of our image so we can prefer it. */
1081
	text = efi_devpath_name(boot_img->FilePath);
1082
1083
1084
1085
1086
1087
	if (text != NULL) {
		printf("   Load Path: %S\n", text);
		efi_setenv_freebsd_wcs("LoaderPath", text);
		efi_free_devpath_name(text);
	}

1088
1089
	rv = OpenProtocolByHandle(boot_img->DeviceHandle, &devid,
	    (void **)&imgpath);
1090
	if (rv == EFI_SUCCESS) {
1091
1092
1093
1094
1095
1096
1097
1098
		text = efi_devpath_name(imgpath);
		if (text != NULL) {
			printf("   Load Device: %S\n", text);
			efi_setenv_freebsd_wcs("LoaderDev", text);
			efi_free_devpath_name(text);
		}
	}

1099
1100
	if (getenv("uefi_ignore_boot_mgr") != NULL) {
		printf("    Ignoring UEFI boot manager\n");
1101
		uefi_boot_mgr = false;
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
	} else {
		uefi_boot_mgr = true;
		boot_current = 0;
		sz = sizeof(boot_current);
		rv = efi_global_getenv("BootCurrent", &boot_current, &sz);
		if (rv == EFI_SUCCESS)
			printf("   BootCurrent: %04x\n", boot_current);
		else {
			boot_current = 0xffff;
			uefi_boot_mgr = false;
		}
1113

1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
		sz = sizeof(boot_order);
		rv = efi_global_getenv("BootOrder", &boot_order, &sz);
		if (rv == EFI_SUCCESS) {
			printf("   BootOrder:");
			for (i = 0; i < sz / sizeof(boot_order[0]); i++)
				printf(" %04x%s", boot_order[i],
				    boot_order[i] == boot_current ? "[*]" : "");
			printf("\n");
			is_last = boot_order[(sz / sizeof(boot_order[0])) - 1] == boot_current;
			bosz = sz;
		} else if (uefi_boot_mgr) {
			/*
			 * u-boot doesn't set BootOrder, but otherwise participates in the
			 * boot manager protocol. So we fake it here and don't consider it
			 * a failure.
			 */
			bosz = sizeof(boot_order[0]);
			boot_order[0] = boot_current;
			is_last = true;
		}
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
	}

	/*
	 * Next, find the boot info structure the UEFI boot manager is
	 * supposed to setup. We need this so we can walk through it to
	 * find where we are in the booting process and what to try to
	 * boot next.
	 */
	if (uefi_boot_mgr) {
		snprintf(buf, sizeof(buf), "Boot%04X", boot_current);
		sz = sizeof(boot_info);
		rv = efi_global_getenv(buf, &boot_info, &sz);
		if (rv == EFI_SUCCESS)
			bisz = sz;
		else
			uefi_boot_mgr = false;
	}
1151

Rui Paulo's avatar
Rui Paulo committed
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
	/*
	 * Disable the watchdog timer. By default the boot manager sets
	 * the timer to 5 minutes before invoking a boot option. If we
	 * want to return to the boot manager, we have to disable the
	 * watchdog timer and since we're an interactive program, we don't
	 * want to wait until the user types "quit". The timer may have
	 * fired by then. We don't care if this fails. It does not prevent
	 * normal functioning in any way...
	 */
	BS->SetWatchdogTimer(0, 0, 0, NULL);

1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
	/*
	 * Initialize the trusted/forbidden certificates from UEFI.
	 * They will be later used to verify the manifest(s),
	 * which should contain hashes of verified files.
	 * This needs to be initialized before any configuration files
	 * are loaded.
	 */
#ifdef EFI_SECUREBOOT
	ve_efi_init();
#endif

Warner Losh's avatar
Warner Losh committed
1174
1175
1176
1177
1178
1179
1180
	/*
	 * Try and find a good currdev based on the image that was booted.
	 * It might be desirable here to have a short pause to allow falling
	 * through to the boot loader instead of returning instantly to follow
	 * the boot protocol and also allow an escape hatch for users wishing
	 * to try something different.
	 */
1181
	if (find_currdev(uefi_boot_mgr, is_last, boot_info, bisz) != 0)
1182
1183
		if (uefi_boot_mgr &&
		    !interactive_interrupt("Failed to find bootable partition"))
Warner Losh's avatar
Warner Losh committed
1184
			return (EFI_NOT_FOUND);
Steven Hartland's avatar
Steven Hartland committed
1185

1186
	autoload_font(false);	/* Set up the font list for console. */
1187
	efi_init_environment();
1188

1189
#if !defined(__arm__)
1190
1191
	for (k = 0; k < ST->NumberOfTableEntries; k++) {
		guid = &ST->ConfigurationTable[k].VendorGuid;
Rui Paulo's avatar
Rui Paulo committed
1192
		if (!memcmp(guid, &smbios, sizeof(EFI_GUID))) {
1193
1194
			char buf[40];

1195
1196
1197
			snprintf(buf, sizeof(buf), "%p",
			    ST->ConfigurationTable[k].VendorTable);
			setenv("hint.smbios.0.mem", buf, 1);
1198
			smbios_detect(ST->ConfigurationTable[k].VendorTable);
Rui Paulo's avatar
Rui Paulo committed
1199
1200
1201
			break;
		}
	}
1202
#endif
Rui Paulo's avatar
Rui Paulo committed
1203

1204
	interact();			/* doesn't return */
Rui Paulo's avatar
Rui Paulo committed
1205
1206
1207
1208

	return (EFI_SUCCESS);		/* keep compiler happy */
}

1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
COMMAND_SET(poweroff, "poweroff", "power off the system", command_poweroff);

static int
command_poweroff(int argc __unused, char *argv[] __unused)
{
	int i;

	for (i = 0; devsw[i] != NULL; ++i)
		if (devsw[i]->dv_cleanup != NULL)
			(devsw[i]->dv_cleanup)();

	RS->ResetSystem(EfiResetShutdown, EFI_SUCCESS, 0, NULL);

	/* NOTREACHED */
	return (CMD_ERROR);
}

Rui Paulo's avatar
Rui Paulo committed
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
COMMAND_SET(reboot, "reboot", "reboot the system", command_reboot);

static int
command_reboot(int argc, char *argv[])
{
	int i;

	for (i = 0; devsw[i] != NULL; ++i)
		if (devsw[i]->dv_cleanup != NULL)
			(devsw[i]->dv_cleanup)();

1237
	RS->ResetSystem(EfiResetCold, EFI_SUCCESS, 0, NULL);
Rui Paulo's avatar
Rui Paulo committed
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254

	/* NOTREACHED */
	return (CMD_ERROR);
}

COMMAND_SET(quit, "quit", "exit the loader", command_quit);

static int
command_quit(int argc, char *argv[])
{
	exit(0);
	return (CMD_OK);
}

COMMAND_SET(memmap, "memmap", "print memory map", command_memmap);

static int
1255
command_memmap(int argc __unused, char *argv[] __unused)
Rui Paulo's avatar
Rui Paulo committed
1256
1257
1258
1259
1260
1261
1262
{
	UINTN sz;
	EFI_MEMORY_DESCRIPTOR *map, *p;
	UINTN key, dsz;
	UINT32 dver;
	EFI_STATUS status;
	int i, ndesc;
1263
	char line[80];
Rui Paulo's avatar
Rui Paulo committed
1264
1265
1266
1267
1268

	sz = 0;
	status = BS->GetMemoryMap(&sz, 0, &key, &dsz, &dver);
	if (status != EFI_BUFFER_TOO_SMALL) {
		printf("Can't determine memory map size\n");
Ed Maste's avatar
Ed Maste committed
1269
		return (CMD_ERROR);
Rui Paulo's avatar
Rui Paulo committed
1270
1271
1272
1273
1274
	}
	map = malloc(sz);
	status = BS->GetMemoryMap(&sz, map, &key, &dsz, &dver);
	if (EFI_ERROR(status)) {
		printf("Can't read memory map\n");
Ed Maste's avatar
Ed Maste committed
1275
		return (CMD_ERROR);
Rui Paulo's avatar
Rui Paulo committed
1276
1277
1278
	}

	ndesc = sz / dsz;
1279
	snprintf(line, sizeof(line), "%23s %12s %12s %8s %4s\n",
Ed Maste's avatar
Ed Maste committed
1280
	    "Type", "Physical", "Virtual", "#Pages", "Attr");
1281
1282
1283
1284
1285
	pager_open();
	if (pager_output(line)) {
		pager_close();
		return (CMD_OK);
	}
1286

Rui Paulo's avatar
Rui Paulo committed
1287
1288
	for (i = 0, p = map; i < ndesc;
	     i++, p = NextMemoryDescriptor(p, dsz)) {
1289
1290
1291
1292
1293
1294
		snprintf(line, sizeof(line), "%23s %012jx %012jx %08jx ",
		    efi_memory_type(p->Type), (uintmax_t)p->PhysicalStart,
		    (uintmax_t)p->VirtualStart, (uintmax_t)p->NumberOfPages);
		if (pager_output(line))
			break;

Ed Maste's avatar
Ed Maste committed
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
		if (p->Attribute & EFI_MEMORY_UC)
			printf("UC ");
		if (p->Attribute & EFI_MEMORY_WC)
			printf("WC ");
		if (p->Attribute & EFI_MEMORY_WT)
			printf("WT ");
		if (p->Attribute & EFI_MEMORY_WB)
			printf("WB ");
		if (p->Attribute & EFI_MEMORY_UCE)
			printf("UCE ");
		if (p->Attribute & EFI_MEMORY_WP)
			printf("WP ");
		if (p->Attribute & EFI_MEMORY_RP)
			printf("RP ");
		if (p->Attribute & EFI_MEMORY_XP)
			printf("XP ");
1311
1312
1313
1314
1315
1316
		if (p->Attribute & EFI_MEMORY_NV)
			printf("NV ");
		if (p->Attribute & EFI_MEMORY_MORE_RELIABLE)
			printf("MR ");
		if (p->Attribute & EFI_MEMORY_RO)
			printf("RO ");
1317
1318
		if (pager_output("\n"))
			break;
Rui Paulo's avatar
Rui Paulo committed
1319
1320
	}

1321
	pager_close();
Ed Maste's avatar
Ed Maste committed
1322
	return (CMD_OK);
Rui Paulo's avatar
Rui Paulo committed
1323
1324
}

Ed Maste's avatar
Ed Maste committed
1325
1326
COMMAND_SET(configuration, "configuration", "print configuration tables",
    command_configuration);
Rui Paulo's avatar
Rui Paulo committed
1327
1328
1329
1330

static int
command_configuration(int argc, char *argv[])
{
1331
	UINTN i;
1332
	char *name;
Rui Paulo's avatar
Rui Paulo committed
1333

1334
	printf("NumberOfTableEntries=%lu\n",
1335
		(unsigned long)ST->NumberOfTableEntries);
1336

Rui Paulo's avatar
Rui Paulo committed
1337
1338
1339
1340
1341
	for (i = 0; i < ST->NumberOfTableEntries; i++) {
		EFI_GUID *guid;

		printf("  ");
		guid = &ST->ConfigurationTable[i].VendorGuid;
1342
1343
1344
1345
1346
1347
1348
1349

		if (efi_guid_to_name(guid, &name) == true) {
			printf(name);
			free(name);
		} else {
			printf("Error while translating UUID to name");
		}
		printf(" at %p\n", ST->ConfigurationTable[i].VendorTable);
Rui Paulo's avatar
Rui Paulo committed
1350
1351
	}

Ed Maste's avatar
Ed Maste committed
1352
	return (CMD_OK);
Ed Maste's avatar