2 * Copyright (c) 1998 Robert Nordier
4 * Copyright (c) 2001 Robert Drehmel
6 * Copyright (c) 2014 Nathan Whitehorn
8 * Copyright (c) 2015 Eric McCorkle
11 * Redistribution and use in source and binary forms are freely
12 * permitted provided that the above copyright notice and this
13 * paragraph and the following disclaimer are duplicated in all
16 * This software is provided "AS IS" and without any express or
17 * implied warranties, including, without limitation, the implied
18 * warranties of merchantability and fitness for a particular
22 #include <sys/cdefs.h>
23 __FBSDID("$FreeBSD$");
25 #include <sys/param.h>
26 #include <machine/elf.h>
27 #include <machine/stdarg.h>
31 #include <eficonsctl.h>
34 #include "boot_module.h"
37 static void efi_panic(EFI_STATUS s, const char *fmt, ...) __dead2 __printflike(2, 3);
39 static const boot_module_t *boot_modules[] =
49 #define NUM_BOOT_MODULES nitems(boot_modules)
50 /* The initial number of handles used to query EFI for partitions. */
51 #define NUM_HANDLES_INIT 24
53 static EFI_GUID BlockIoProtocolGUID = BLOCK_IO_PROTOCOL;
54 static EFI_GUID DevicePathGUID = DEVICE_PATH_PROTOCOL;
55 static EFI_GUID LoadedImageGUID = LOADED_IMAGE_PROTOCOL;
56 static EFI_GUID ConsoleControlGUID = EFI_CONSOLE_CONTROL_PROTOCOL_GUID;
57 static EFI_GUID FreeBSDBootVarGUID = FREEBSD_BOOT_VAR_GUID;
58 static EFI_GUID GlobalBootVarGUID = UEFI_BOOT_VAR_GUID;
61 * Provide Malloc / Free backed by EFIs AllocatePool / FreePool which ensures
62 * memory is correctly aligned avoiding EFI_INVALID_PARAMETER returns from
66 Malloc(size_t len, const char *file __unused, int line __unused)
70 if (BS->AllocatePool(EfiLoaderData, len, &out) == EFI_SUCCESS)
77 Free(void *buf, const char *file __unused, int line __unused)
80 (void)BS->FreePool(buf);
84 efi_getenv(EFI_GUID *g, const char *v, void *data, size_t *len)
93 if (utf8_to_ucs2(v, &uv, &ul) != 0)
94 return (EFI_OUT_OF_RESOURCES);
96 rv = RS->GetVariable(uv, g, &attr, &dl, data);
97 if (rv == EFI_SUCCESS)
104 efi_setenv_freebsd_wcs(const char *varname, CHAR16 *valstr)
110 if (utf8_to_ucs2(varname, &var, &len) != 0)
111 return (EFI_OUT_OF_RESOURCES);
112 rv = RS->SetVariable(var, &FreeBSDBootVarGUID,
113 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
114 (ucs2len(valstr) + 1) * sizeof(efi_char), valstr);
120 * nodes_match returns TRUE if the imgpath isn't NULL and the nodes match,
124 nodes_match(EFI_DEVICE_PATH *imgpath, EFI_DEVICE_PATH *devpath)
128 if (imgpath == NULL || imgpath->Type != devpath->Type ||
129 imgpath->SubType != devpath->SubType)
132 len = DevicePathNodeLength(imgpath);
133 if (len != DevicePathNodeLength(devpath))
136 return (memcmp(imgpath, devpath, (size_t)len) == 0);
140 * device_paths_match returns TRUE if the imgpath isn't NULL and all nodes
141 * in imgpath and devpath match up to their respective occurrences of a
142 * media node, FALSE otherwise.
145 device_paths_match(EFI_DEVICE_PATH *imgpath, EFI_DEVICE_PATH *devpath)
151 while (!IsDevicePathEnd(imgpath) && !IsDevicePathEnd(devpath)) {
152 if (IsDevicePathType(imgpath, MEDIA_DEVICE_PATH) &&
153 IsDevicePathType(devpath, MEDIA_DEVICE_PATH))
156 if (!nodes_match(imgpath, devpath))
159 imgpath = NextDevicePathNode(imgpath);
160 devpath = NextDevicePathNode(devpath);
167 * devpath_last returns the last non-path end node in devpath.
169 static EFI_DEVICE_PATH *
170 devpath_last(EFI_DEVICE_PATH *devpath)
173 while (!IsDevicePathEnd(NextDevicePathNode(devpath)))
174 devpath = NextDevicePathNode(devpath);
180 * load_loader attempts to load the loader image data.
182 * It tries each module and its respective devices, identified by mod->probe,
183 * in order until a successful load occurs at which point it returns EFI_SUCCESS
184 * and EFI_NOT_FOUND otherwise.
186 * Only devices which have preferred matching the preferred parameter are tried.
189 load_loader(const boot_module_t **modp, dev_info_t **devinfop, void **bufp,
190 size_t *bufsize, BOOLEAN preferred)
194 const boot_module_t *mod;
196 for (i = 0; i < NUM_BOOT_MODULES; i++) {
197 mod = boot_modules[i];
198 for (dev = mod->devices(); dev != NULL; dev = dev->next) {
199 if (dev->preferred != preferred)
202 if (mod->load(PATH_LOADER_EFI, dev, bufp, bufsize) ==
206 return (EFI_SUCCESS);
211 return (EFI_NOT_FOUND);
215 * try_boot only returns if it fails to load the loader. If it succeeds
216 * it simply boots, otherwise it returns the status of last EFI call.
221 size_t bufsize, loadersize, cmdsize;
222 void *buf, *loaderbuf;
225 const boot_module_t *mod;
226 EFI_HANDLE loaderhandle;
227 EFI_LOADED_IMAGE *loaded_image;
230 status = load_loader(&mod, &dev, &loaderbuf, &loadersize, TRUE);
231 if (status != EFI_SUCCESS) {
232 status = load_loader(&mod, &dev, &loaderbuf, &loadersize,
234 if (status != EFI_SUCCESS) {
235 printf("Failed to load '%s'\n", PATH_LOADER_EFI);
241 * Read in and parse the command line from /boot.config or /boot/config,
242 * if present. We'll pass it the next stage via a simple ASCII
243 * string. loader.efi has a hack for ASCII strings, so we'll use that to
244 * keep the size down here. We only try to read the alternate file if
245 * we get EFI_NOT_FOUND because all other errors mean that the boot_module
246 * had troubles with the filesystem. We could return early, but we'll let
247 * loading the actual kernel sort all that out. Since these files are
248 * optional, we don't report errors in trying to read them.
252 status = mod->load(PATH_DOTCONFIG, dev, &buf, &bufsize);
253 if (status == EFI_NOT_FOUND)
254 status = mod->load(PATH_CONFIG, dev, &buf, &bufsize);
255 if (status == EFI_SUCCESS) {
256 cmdsize = bufsize + 1;
257 cmd = malloc(cmdsize);
260 memcpy(cmd, buf, bufsize);
266 if ((status = BS->LoadImage(TRUE, IH, devpath_last(dev->devpath),
267 loaderbuf, loadersize, &loaderhandle)) != EFI_SUCCESS) {
268 printf("Failed to load image provided by %s, size: %zu, (%lu)\n",
269 mod->name, loadersize, EFI_ERROR_CODE(status));
273 if ((status = BS->HandleProtocol(loaderhandle, &LoadedImageGUID,
274 (VOID**)&loaded_image)) != EFI_SUCCESS) {
275 printf("Failed to query LoadedImage provided by %s (%lu)\n",
276 mod->name, EFI_ERROR_CODE(status));
281 printf(" command args: %s\n", cmd);
283 loaded_image->DeviceHandle = dev->devhandle;
284 loaded_image->LoadOptionsSize = cmdsize;
285 loaded_image->LoadOptions = cmd;
287 DPRINTF("Starting '%s' in 5 seconds...", PATH_LOADER_EFI);
299 if ((status = BS->StartImage(loaderhandle, NULL, NULL)) !=
301 printf("Failed to start image provided by %s (%lu)\n",
302 mod->name, EFI_ERROR_CODE(status));
303 loaded_image->LoadOptionsSize = 0;
304 loaded_image->LoadOptions = NULL;
312 if (loaderbuf != NULL)
319 * probe_handle determines if the passed handle represents a logical partition
320 * if it does it uses each module in order to probe it and if successful it
321 * returns EFI_SUCCESS.
324 probe_handle(EFI_HANDLE h, EFI_DEVICE_PATH *imgpath, BOOLEAN *preferred)
328 EFI_DEVICE_PATH *devpath;
332 /* Figure out if we're dealing with an actual partition. */
333 status = BS->HandleProtocol(h, &DevicePathGUID, (void **)&devpath);
334 if (status == EFI_UNSUPPORTED)
337 if (status != EFI_SUCCESS) {
338 DPRINTF("\nFailed to query DevicePath (%lu)\n",
339 EFI_ERROR_CODE(status));
344 CHAR16 *text = efi_devpath_name(devpath);
345 DPRINTF("probing: %S\n", text);
346 efi_free_devpath_name(text);
349 status = BS->HandleProtocol(h, &BlockIoProtocolGUID, (void **)&blkio);
350 if (status == EFI_UNSUPPORTED)
353 if (status != EFI_SUCCESS) {
354 DPRINTF("\nFailed to query BlockIoProtocol (%lu)\n",
355 EFI_ERROR_CODE(status));
359 if (!blkio->Media->LogicalPartition)
360 return (EFI_UNSUPPORTED);
362 *preferred = device_paths_match(imgpath, devpath);
364 /* Run through each module, see if it can load this partition */
365 for (i = 0; i < NUM_BOOT_MODULES; i++) {
366 devinfo = malloc(sizeof(*devinfo));
367 if (devinfo == NULL) {
368 DPRINTF("\nFailed to allocate devinfo\n");
371 devinfo->dev = blkio;
372 devinfo->devpath = devpath;
373 devinfo->devhandle = h;
374 devinfo->devdata = NULL;
375 devinfo->preferred = *preferred;
376 devinfo->next = NULL;
378 status = boot_modules[i]->probe(devinfo);
379 if (status == EFI_SUCCESS)
380 return (EFI_SUCCESS);
384 return (EFI_UNSUPPORTED);
388 * probe_handle_status calls probe_handle and outputs the returned status
392 probe_handle_status(EFI_HANDLE h, EFI_DEVICE_PATH *imgpath)
398 status = probe_handle(h, imgpath, &preferred);
402 case EFI_UNSUPPORTED:
404 DPRINTF(" not supported\n");
409 DPRINTF(" supported (preferred)\n");
412 DPRINTF(" supported\n");
417 DPRINTF(" error (%lu)\n", EFI_ERROR_CODE(status));
424 efi_main(EFI_HANDLE Ximage, EFI_SYSTEM_TABLE *Xsystab)
427 EFI_LOADED_IMAGE *img;
428 EFI_DEVICE_PATH *imgpath;
430 EFI_CONSOLE_CONTROL_PROTOCOL *ConsoleControl = NULL;
431 SIMPLE_TEXT_OUTPUT_INTERFACE *conout = NULL;
432 UINTN i, max_dim, best_mode, cols, rows, hsize, nhandles;
436 UINT16 boot_order[100];
438 /* Basic initialization*/
441 BS = ST->BootServices;
442 RS = ST->RuntimeServices;
444 /* Set up the console, so printf works. */
445 status = BS->LocateProtocol(&ConsoleControlGUID, NULL,
446 (VOID **)&ConsoleControl);
447 if (status == EFI_SUCCESS)
448 (void)ConsoleControl->SetMode(ConsoleControl,
449 EfiConsoleControlScreenText);
451 * Reset the console and find the best text mode.
454 conout->Reset(conout, TRUE);
455 max_dim = best_mode = 0;
456 for (i = 0; i < conout->Mode->MaxMode; i++) {
457 status = conout->QueryMode(conout, i, &cols, &rows);
458 if (EFI_ERROR(status))
460 if (cols * rows > max_dim) {
461 max_dim = cols * rows;
466 conout->SetMode(conout, best_mode);
467 conout->EnableCursor(conout, TRUE);
468 conout->ClearScreen(conout);
470 printf("\n>> FreeBSD EFI boot block\n");
471 printf(" Loader path: %s\n\n", PATH_LOADER_EFI);
472 printf(" Initializing modules:");
473 for (i = 0; i < NUM_BOOT_MODULES; i++) {
474 printf(" %s", boot_modules[i]->name);
475 if (boot_modules[i]->init != NULL)
476 boot_modules[i]->init();
480 /* Determine the devpath of our image so we can prefer it. */
481 status = BS->HandleProtocol(IH, &LoadedImageGUID, (VOID**)&img);
483 if (status == EFI_SUCCESS) {
484 text = efi_devpath_name(img->FilePath);
486 printf(" Load Path: %S\n", text);
487 efi_setenv_freebsd_wcs("Boot1Path", text);
488 efi_free_devpath_name(text);
491 status = BS->HandleProtocol(img->DeviceHandle, &DevicePathGUID,
493 if (status != EFI_SUCCESS) {
494 DPRINTF("Failed to get image DevicePath (%lu)\n",
495 EFI_ERROR_CODE(status));
497 text = efi_devpath_name(imgpath);
499 printf(" Load Device: %S\n", text);
500 efi_setenv_freebsd_wcs("Boot1Dev", text);
501 efi_free_devpath_name(text);
507 sz = sizeof(boot_current);
508 efi_getenv(&GlobalBootVarGUID, "BootCurrent", &boot_current, &sz);
509 printf(" BootCurrent: %04x\n", boot_current);
511 sz = sizeof(boot_order);
512 efi_getenv(&GlobalBootVarGUID, "BootOrder", &boot_order, &sz);
513 printf(" BootOrder:");
514 for (i = 0; i < sz / sizeof(boot_order[0]); i++)
515 printf(" %04x", boot_order[i]);
520 * For testing failover scenarios, it's nice to be able to fail fast.
521 * Define TEST_FAILURE to create a boot1.efi that always fails after
522 * reporting the boot manager protocol details.
524 BS->Exit(IH, EFI_OUT_OF_RESOURCES, 0, NULL);
527 /* Get all the device handles */
528 hsize = (UINTN)NUM_HANDLES_INIT * sizeof(EFI_HANDLE);
529 handles = malloc(hsize);
531 printf("Failed to allocate %d handles\n", NUM_HANDLES_INIT);
533 status = BS->LocateHandle(ByProtocol, &BlockIoProtocolGUID, NULL,
538 case EFI_BUFFER_TOO_SMALL:
540 handles = malloc(hsize);
542 efi_panic(EFI_OUT_OF_RESOURCES, "Failed to allocate %d handles\n",
544 status = BS->LocateHandle(ByProtocol, &BlockIoProtocolGUID,
545 NULL, &hsize, handles);
546 if (status != EFI_SUCCESS)
547 efi_panic(status, "Failed to get device handles\n");
550 efi_panic(status, "Failed to get device handles\n");
554 /* Scan all partitions, probing with all modules. */
555 nhandles = hsize / sizeof(*handles);
556 printf(" Probing %zu block devices...", nhandles);
559 for (i = 0; i < nhandles; i++)
560 probe_handle_status(handles[i], imgpath);
563 /* Status summary. */
564 for (i = 0; i < NUM_BOOT_MODULES; i++) {
566 boot_modules[i]->status();
571 /* If we get here, we're out of luck... */
572 efi_panic(EFI_LOAD_ERROR, "No bootable partitions found!");
576 * add_device adds a device to the passed devinfo list.
579 add_device(dev_info_t **devinfop, dev_info_t *devinfo)
583 if (*devinfop == NULL) {
588 for (dev = *devinfop; dev->next != NULL; dev = dev->next)
595 * OK. We totally give up. Exit back to EFI with a sensible status so
596 * it can try the next option on the list.
599 efi_panic(EFI_STATUS s, const char *fmt, ...)
609 BS->Exit(IH, s, 0, NULL);
620 ST->ConOut->OutputString(ST->ConOut, buf);
624 ST->ConOut->OutputString(ST->ConOut, buf);