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;
59 * Provide Malloc / Free / Calloc backed by EFIs AllocatePool / FreePool which ensures
60 * memory is correctly aligned avoiding EFI_INVALID_PARAMETER returns from
65 Malloc(size_t len, const char *file __unused, int line __unused)
69 if (BS->AllocatePool(EfiLoaderData, len, &out) == EFI_SUCCESS)
76 Free(void *buf, const char *file __unused, int line __unused)
79 (void)BS->FreePool(buf);
83 Calloc(size_t n1, size_t n2, const char *file, int line)
89 if ((res = Malloc(bytes, file, line)) != NULL)
96 * nodes_match returns TRUE if the imgpath isn't NULL and the nodes match,
100 nodes_match(EFI_DEVICE_PATH *imgpath, EFI_DEVICE_PATH *devpath)
104 if (imgpath == NULL || imgpath->Type != devpath->Type ||
105 imgpath->SubType != devpath->SubType)
108 len = DevicePathNodeLength(imgpath);
109 if (len != DevicePathNodeLength(devpath))
112 return (memcmp(imgpath, devpath, (size_t)len) == 0);
116 * device_paths_match returns TRUE if the imgpath isn't NULL and all nodes
117 * in imgpath and devpath match up to their respective occurrences of a
118 * media node, FALSE otherwise.
121 device_paths_match(EFI_DEVICE_PATH *imgpath, EFI_DEVICE_PATH *devpath)
127 while (!IsDevicePathEnd(imgpath) && !IsDevicePathEnd(devpath)) {
128 if (IsDevicePathType(imgpath, MEDIA_DEVICE_PATH) &&
129 IsDevicePathType(devpath, MEDIA_DEVICE_PATH))
132 if (!nodes_match(imgpath, devpath))
135 imgpath = NextDevicePathNode(imgpath);
136 devpath = NextDevicePathNode(devpath);
143 * devpath_last returns the last non-path end node in devpath.
145 static EFI_DEVICE_PATH *
146 devpath_last(EFI_DEVICE_PATH *devpath)
149 while (!IsDevicePathEnd(NextDevicePathNode(devpath)))
150 devpath = NextDevicePathNode(devpath);
156 * load_loader attempts to load the loader image data.
158 * It tries each module and its respective devices, identified by mod->probe,
159 * in order until a successful load occurs at which point it returns EFI_SUCCESS
160 * and EFI_NOT_FOUND otherwise.
162 * Only devices which have preferred matching the preferred parameter are tried.
165 load_loader(const boot_module_t **modp, dev_info_t **devinfop, void **bufp,
166 size_t *bufsize, BOOLEAN preferred)
170 const boot_module_t *mod;
172 for (i = 0; i < NUM_BOOT_MODULES; i++) {
173 mod = boot_modules[i];
174 for (dev = mod->devices(); dev != NULL; dev = dev->next) {
175 if (dev->preferred != preferred)
178 if (mod->load(PATH_LOADER_EFI, dev, bufp, bufsize) ==
182 return (EFI_SUCCESS);
187 return (EFI_NOT_FOUND);
191 * try_boot only returns if it fails to load the loader. If it succeeds
192 * it simply boots, otherwise it returns the status of last EFI call.
197 size_t bufsize, loadersize, cmdsize;
198 void *buf, *loaderbuf;
201 const boot_module_t *mod;
202 EFI_HANDLE loaderhandle;
203 EFI_LOADED_IMAGE *loaded_image;
206 status = load_loader(&mod, &dev, &loaderbuf, &loadersize, TRUE);
207 if (status != EFI_SUCCESS) {
208 status = load_loader(&mod, &dev, &loaderbuf, &loadersize,
210 if (status != EFI_SUCCESS) {
211 printf("Failed to load '%s'\n", PATH_LOADER_EFI);
217 * Read in and parse the command line from /boot.config or /boot/config,
218 * if present. We'll pass it the next stage via a simple ASCII
219 * string. loader.efi has a hack for ASCII strings, so we'll use that to
220 * keep the size down here. We only try to read the alternate file if
221 * we get EFI_NOT_FOUND because all other errors mean that the boot_module
222 * had troubles with the filesystem. We could return early, but we'll let
223 * loading the actual kernel sort all that out. Since these files are
224 * optional, we don't report errors in trying to read them.
228 status = mod->load(PATH_DOTCONFIG, dev, &buf, &bufsize);
229 if (status == EFI_NOT_FOUND)
230 status = mod->load(PATH_CONFIG, dev, &buf, &bufsize);
231 if (status == EFI_SUCCESS) {
232 cmdsize = bufsize + 1;
233 cmd = malloc(cmdsize);
236 memcpy(cmd, buf, bufsize);
242 if ((status = BS->LoadImage(TRUE, IH, devpath_last(dev->devpath),
243 loaderbuf, loadersize, &loaderhandle)) != EFI_SUCCESS) {
244 printf("Failed to load image provided by %s, size: %zu, (%lu)\n",
245 mod->name, loadersize, EFI_ERROR_CODE(status));
249 if ((status = BS->HandleProtocol(loaderhandle, &LoadedImageGUID,
250 (VOID**)&loaded_image)) != EFI_SUCCESS) {
251 printf("Failed to query LoadedImage provided by %s (%lu)\n",
252 mod->name, EFI_ERROR_CODE(status));
257 printf(" command args: %s\n", cmd);
259 loaded_image->DeviceHandle = dev->devhandle;
260 loaded_image->LoadOptionsSize = cmdsize;
261 loaded_image->LoadOptions = cmd;
263 DPRINTF("Starting '%s' in 5 seconds...", PATH_LOADER_EFI);
275 if ((status = BS->StartImage(loaderhandle, NULL, NULL)) !=
277 printf("Failed to start image provided by %s (%lu)\n",
278 mod->name, EFI_ERROR_CODE(status));
279 loaded_image->LoadOptionsSize = 0;
280 loaded_image->LoadOptions = NULL;
288 if (loaderbuf != NULL)
295 * probe_handle determines if the passed handle represents a logical partition
296 * if it does it uses each module in order to probe it and if successful it
297 * returns EFI_SUCCESS.
300 probe_handle(EFI_HANDLE h, EFI_DEVICE_PATH *imgpath, BOOLEAN *preferred)
304 EFI_DEVICE_PATH *devpath;
308 /* Figure out if we're dealing with an actual partition. */
309 status = BS->HandleProtocol(h, &DevicePathGUID, (void **)&devpath);
310 if (status == EFI_UNSUPPORTED)
313 if (status != EFI_SUCCESS) {
314 DPRINTF("\nFailed to query DevicePath (%lu)\n",
315 EFI_ERROR_CODE(status));
320 CHAR16 *text = efi_devpath_name(devpath);
321 DPRINTF("probing: %S\n", text);
322 efi_free_devpath_name(text);
325 status = BS->HandleProtocol(h, &BlockIoProtocolGUID, (void **)&blkio);
326 if (status == EFI_UNSUPPORTED)
329 if (status != EFI_SUCCESS) {
330 DPRINTF("\nFailed to query BlockIoProtocol (%lu)\n",
331 EFI_ERROR_CODE(status));
335 if (!blkio->Media->LogicalPartition)
336 return (EFI_UNSUPPORTED);
338 *preferred = device_paths_match(imgpath, devpath);
340 /* Run through each module, see if it can load this partition */
341 for (i = 0; i < NUM_BOOT_MODULES; i++) {
342 devinfo = malloc(sizeof(*devinfo));
343 if (devinfo == NULL) {
344 DPRINTF("\nFailed to allocate devinfo\n");
347 devinfo->dev = blkio;
348 devinfo->devpath = devpath;
349 devinfo->devhandle = h;
350 devinfo->devdata = NULL;
351 devinfo->preferred = *preferred;
352 devinfo->next = NULL;
354 status = boot_modules[i]->probe(devinfo);
355 if (status == EFI_SUCCESS)
356 return (EFI_SUCCESS);
360 return (EFI_UNSUPPORTED);
364 * probe_handle_status calls probe_handle and outputs the returned status
368 probe_handle_status(EFI_HANDLE h, EFI_DEVICE_PATH *imgpath)
374 status = probe_handle(h, imgpath, &preferred);
378 case EFI_UNSUPPORTED:
380 DPRINTF(" not supported\n");
385 DPRINTF(" supported (preferred)\n");
388 DPRINTF(" supported\n");
393 DPRINTF(" error (%lu)\n", EFI_ERROR_CODE(status));
400 efi_main(EFI_HANDLE Ximage, EFI_SYSTEM_TABLE *Xsystab)
403 EFI_LOADED_IMAGE *img;
404 EFI_DEVICE_PATH *imgpath;
406 EFI_CONSOLE_CONTROL_PROTOCOL *ConsoleControl = NULL;
407 SIMPLE_TEXT_OUTPUT_INTERFACE *conout = NULL;
408 UINTN i, hsize, nhandles;
412 UINT16 boot_order[100];
414 /* Basic initialization*/
417 BS = ST->BootServices;
418 RS = ST->RuntimeServices;
420 /* Set up the console, so printf works. */
421 status = BS->LocateProtocol(&ConsoleControlGUID, NULL,
422 (VOID **)&ConsoleControl);
423 if (status == EFI_SUCCESS)
424 (void)ConsoleControl->SetMode(ConsoleControl,
425 EfiConsoleControlScreenText);
427 * Reset the console enable the cursor. Later we'll choose a better
428 * console size through GOP/UGA.
431 conout->Reset(conout, TRUE);
432 /* Explicitly set conout to mode 0, 80x25 */
433 conout->SetMode(conout, 0);
434 conout->EnableCursor(conout, TRUE);
435 conout->ClearScreen(conout);
437 printf("\n>> FreeBSD EFI boot block\n");
438 printf(" Loader path: %s\n\n", PATH_LOADER_EFI);
439 printf(" Initializing modules:");
440 for (i = 0; i < NUM_BOOT_MODULES; i++) {
441 printf(" %s", boot_modules[i]->name);
442 if (boot_modules[i]->init != NULL)
443 boot_modules[i]->init();
447 /* Determine the devpath of our image so we can prefer it. */
448 status = BS->HandleProtocol(IH, &LoadedImageGUID, (VOID**)&img);
450 if (status == EFI_SUCCESS) {
451 text = efi_devpath_name(img->FilePath);
453 printf(" Load Path: %S\n", text);
454 efi_setenv_freebsd_wcs("Boot1Path", text);
455 efi_free_devpath_name(text);
458 status = BS->HandleProtocol(img->DeviceHandle, &DevicePathGUID,
460 if (status != EFI_SUCCESS) {
461 DPRINTF("Failed to get image DevicePath (%lu)\n",
462 EFI_ERROR_CODE(status));
464 text = efi_devpath_name(imgpath);
466 printf(" Load Device: %S\n", text);
467 efi_setenv_freebsd_wcs("Boot1Dev", text);
468 efi_free_devpath_name(text);
474 sz = sizeof(boot_current);
475 if (efi_global_getenv("BootCurrent", &boot_current, &sz) == EFI_SUCCESS) {
476 printf(" BootCurrent: %04x\n", boot_current);
478 sz = sizeof(boot_order);
479 if (efi_global_getenv("BootOrder", &boot_order, &sz) == EFI_SUCCESS) {
480 printf(" BootOrder:");
481 for (i = 0; i < sz / sizeof(boot_order[0]); i++)
482 printf(" %04x%s", boot_order[i],
483 boot_order[i] == boot_current ? "[*]" : "");
490 * For testing failover scenarios, it's nice to be able to fail fast.
491 * Define TEST_FAILURE to create a boot1.efi that always fails after
492 * reporting the boot manager protocol details.
494 BS->Exit(IH, EFI_OUT_OF_RESOURCES, 0, NULL);
497 /* Get all the device handles */
498 hsize = (UINTN)NUM_HANDLES_INIT * sizeof(EFI_HANDLE);
499 handles = malloc(hsize);
501 printf("Failed to allocate %d handles\n", NUM_HANDLES_INIT);
503 status = BS->LocateHandle(ByProtocol, &BlockIoProtocolGUID, NULL,
508 case EFI_BUFFER_TOO_SMALL:
510 handles = malloc(hsize);
512 efi_panic(EFI_OUT_OF_RESOURCES, "Failed to allocate %d handles\n",
514 status = BS->LocateHandle(ByProtocol, &BlockIoProtocolGUID,
515 NULL, &hsize, handles);
516 if (status != EFI_SUCCESS)
517 efi_panic(status, "Failed to get device handles\n");
520 efi_panic(status, "Failed to get device handles\n");
524 /* Scan all partitions, probing with all modules. */
525 nhandles = hsize / sizeof(*handles);
526 printf(" Probing %zu block devices...", nhandles);
529 for (i = 0; i < nhandles; i++)
530 probe_handle_status(handles[i], imgpath);
533 /* Status summary. */
534 for (i = 0; i < NUM_BOOT_MODULES; i++) {
536 boot_modules[i]->status();
541 /* If we get here, we're out of luck... */
542 efi_panic(EFI_LOAD_ERROR, "No bootable partitions found!");
546 * add_device adds a device to the passed devinfo list.
549 add_device(dev_info_t **devinfop, dev_info_t *devinfo)
553 if (*devinfop == NULL) {
558 for (dev = *devinfop; dev->next != NULL; dev = dev->next)
565 * OK. We totally give up. Exit back to EFI with a sensible status so
566 * it can try the next option on the list.
569 efi_panic(EFI_STATUS s, const char *fmt, ...)
579 BS->Exit(IH, s, 0, NULL);
590 ST->ConOut->OutputString(ST->ConOut, buf);
594 ST->ConOut->OutputString(ST->ConOut, buf);