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 backed by EFIs AllocatePool / FreePool which ensures
60 * memory is correctly aligned avoiding EFI_INVALID_PARAMETER returns from
64 Malloc(size_t len, const char *file __unused, int line __unused)
68 if (BS->AllocatePool(EfiLoaderData, len, &out) == EFI_SUCCESS)
75 Free(void *buf, const char *file __unused, int line __unused)
78 (void)BS->FreePool(buf);
82 * nodes_match returns TRUE if the imgpath isn't NULL and the nodes match,
86 nodes_match(EFI_DEVICE_PATH *imgpath, EFI_DEVICE_PATH *devpath)
90 if (imgpath == NULL || imgpath->Type != devpath->Type ||
91 imgpath->SubType != devpath->SubType)
94 len = DevicePathNodeLength(imgpath);
95 if (len != DevicePathNodeLength(devpath))
98 return (memcmp(imgpath, devpath, (size_t)len) == 0);
102 * device_paths_match returns TRUE if the imgpath isn't NULL and all nodes
103 * in imgpath and devpath match up to their respective occurrences of a
104 * media node, FALSE otherwise.
107 device_paths_match(EFI_DEVICE_PATH *imgpath, EFI_DEVICE_PATH *devpath)
113 while (!IsDevicePathEnd(imgpath) && !IsDevicePathEnd(devpath)) {
114 if (IsDevicePathType(imgpath, MEDIA_DEVICE_PATH) &&
115 IsDevicePathType(devpath, MEDIA_DEVICE_PATH))
118 if (!nodes_match(imgpath, devpath))
121 imgpath = NextDevicePathNode(imgpath);
122 devpath = NextDevicePathNode(devpath);
129 * devpath_last returns the last non-path end node in devpath.
131 static EFI_DEVICE_PATH *
132 devpath_last(EFI_DEVICE_PATH *devpath)
135 while (!IsDevicePathEnd(NextDevicePathNode(devpath)))
136 devpath = NextDevicePathNode(devpath);
142 * load_loader attempts to load the loader image data.
144 * It tries each module and its respective devices, identified by mod->probe,
145 * in order until a successful load occurs at which point it returns EFI_SUCCESS
146 * and EFI_NOT_FOUND otherwise.
148 * Only devices which have preferred matching the preferred parameter are tried.
151 load_loader(const boot_module_t **modp, dev_info_t **devinfop, void **bufp,
152 size_t *bufsize, BOOLEAN preferred)
156 const boot_module_t *mod;
158 for (i = 0; i < NUM_BOOT_MODULES; i++) {
159 mod = boot_modules[i];
160 for (dev = mod->devices(); dev != NULL; dev = dev->next) {
161 if (dev->preferred != preferred)
164 if (mod->load(PATH_LOADER_EFI, dev, bufp, bufsize) ==
168 return (EFI_SUCCESS);
173 return (EFI_NOT_FOUND);
177 * try_boot only returns if it fails to load the loader. If it succeeds
178 * it simply boots, otherwise it returns the status of last EFI call.
183 size_t bufsize, loadersize, cmdsize;
184 void *buf, *loaderbuf;
187 const boot_module_t *mod;
188 EFI_HANDLE loaderhandle;
189 EFI_LOADED_IMAGE *loaded_image;
192 status = load_loader(&mod, &dev, &loaderbuf, &loadersize, TRUE);
193 if (status != EFI_SUCCESS) {
194 status = load_loader(&mod, &dev, &loaderbuf, &loadersize,
196 if (status != EFI_SUCCESS) {
197 printf("Failed to load '%s'\n", PATH_LOADER_EFI);
203 * Read in and parse the command line from /boot.config or /boot/config,
204 * if present. We'll pass it the next stage via a simple ASCII
205 * string. loader.efi has a hack for ASCII strings, so we'll use that to
206 * keep the size down here. We only try to read the alternate file if
207 * we get EFI_NOT_FOUND because all other errors mean that the boot_module
208 * had troubles with the filesystem. We could return early, but we'll let
209 * loading the actual kernel sort all that out. Since these files are
210 * optional, we don't report errors in trying to read them.
214 status = mod->load(PATH_DOTCONFIG, dev, &buf, &bufsize);
215 if (status == EFI_NOT_FOUND)
216 status = mod->load(PATH_CONFIG, dev, &buf, &bufsize);
217 if (status == EFI_SUCCESS) {
218 cmdsize = bufsize + 1;
219 cmd = malloc(cmdsize);
222 memcpy(cmd, buf, bufsize);
228 if ((status = BS->LoadImage(TRUE, IH, devpath_last(dev->devpath),
229 loaderbuf, loadersize, &loaderhandle)) != EFI_SUCCESS) {
230 printf("Failed to load image provided by %s, size: %zu, (%lu)\n",
231 mod->name, loadersize, EFI_ERROR_CODE(status));
235 if ((status = BS->HandleProtocol(loaderhandle, &LoadedImageGUID,
236 (VOID**)&loaded_image)) != EFI_SUCCESS) {
237 printf("Failed to query LoadedImage provided by %s (%lu)\n",
238 mod->name, EFI_ERROR_CODE(status));
243 printf(" command args: %s\n", cmd);
245 loaded_image->DeviceHandle = dev->devhandle;
246 loaded_image->LoadOptionsSize = cmdsize;
247 loaded_image->LoadOptions = cmd;
249 DPRINTF("Starting '%s' in 5 seconds...", PATH_LOADER_EFI);
261 if ((status = BS->StartImage(loaderhandle, NULL, NULL)) !=
263 printf("Failed to start image provided by %s (%lu)\n",
264 mod->name, EFI_ERROR_CODE(status));
265 loaded_image->LoadOptionsSize = 0;
266 loaded_image->LoadOptions = NULL;
274 if (loaderbuf != NULL)
281 * probe_handle determines if the passed handle represents a logical partition
282 * if it does it uses each module in order to probe it and if successful it
283 * returns EFI_SUCCESS.
286 probe_handle(EFI_HANDLE h, EFI_DEVICE_PATH *imgpath, BOOLEAN *preferred)
290 EFI_DEVICE_PATH *devpath;
294 /* Figure out if we're dealing with an actual partition. */
295 status = BS->HandleProtocol(h, &DevicePathGUID, (void **)&devpath);
296 if (status == EFI_UNSUPPORTED)
299 if (status != EFI_SUCCESS) {
300 DPRINTF("\nFailed to query DevicePath (%lu)\n",
301 EFI_ERROR_CODE(status));
306 CHAR16 *text = efi_devpath_name(devpath);
307 DPRINTF("probing: %S\n", text);
308 efi_free_devpath_name(text);
311 status = BS->HandleProtocol(h, &BlockIoProtocolGUID, (void **)&blkio);
312 if (status == EFI_UNSUPPORTED)
315 if (status != EFI_SUCCESS) {
316 DPRINTF("\nFailed to query BlockIoProtocol (%lu)\n",
317 EFI_ERROR_CODE(status));
321 if (!blkio->Media->LogicalPartition)
322 return (EFI_UNSUPPORTED);
324 *preferred = device_paths_match(imgpath, devpath);
326 /* Run through each module, see if it can load this partition */
327 for (i = 0; i < NUM_BOOT_MODULES; i++) {
328 devinfo = malloc(sizeof(*devinfo));
329 if (devinfo == NULL) {
330 DPRINTF("\nFailed to allocate devinfo\n");
333 devinfo->dev = blkio;
334 devinfo->devpath = devpath;
335 devinfo->devhandle = h;
336 devinfo->devdata = NULL;
337 devinfo->preferred = *preferred;
338 devinfo->next = NULL;
340 status = boot_modules[i]->probe(devinfo);
341 if (status == EFI_SUCCESS)
342 return (EFI_SUCCESS);
346 return (EFI_UNSUPPORTED);
350 * probe_handle_status calls probe_handle and outputs the returned status
354 probe_handle_status(EFI_HANDLE h, EFI_DEVICE_PATH *imgpath)
360 status = probe_handle(h, imgpath, &preferred);
364 case EFI_UNSUPPORTED:
366 DPRINTF(" not supported\n");
371 DPRINTF(" supported (preferred)\n");
374 DPRINTF(" supported\n");
379 DPRINTF(" error (%lu)\n", EFI_ERROR_CODE(status));
386 efi_main(EFI_HANDLE Ximage, EFI_SYSTEM_TABLE *Xsystab)
389 EFI_LOADED_IMAGE *img;
390 EFI_DEVICE_PATH *imgpath;
392 EFI_CONSOLE_CONTROL_PROTOCOL *ConsoleControl = NULL;
393 SIMPLE_TEXT_OUTPUT_INTERFACE *conout = NULL;
394 UINTN i, hsize, nhandles;
398 UINT16 boot_order[100];
400 /* Basic initialization*/
403 BS = ST->BootServices;
404 RS = ST->RuntimeServices;
406 /* Set up the console, so printf works. */
407 status = BS->LocateProtocol(&ConsoleControlGUID, NULL,
408 (VOID **)&ConsoleControl);
409 if (status == EFI_SUCCESS)
410 (void)ConsoleControl->SetMode(ConsoleControl,
411 EfiConsoleControlScreenText);
413 * Reset the console enable the cursor. Later we'll choose a better
414 * console size through GOP/UGA.
417 conout->Reset(conout, TRUE);
418 /* Explicitly set conout to mode 0, 80x25 */
419 conout->SetMode(conout, 0);
420 conout->EnableCursor(conout, TRUE);
421 conout->ClearScreen(conout);
423 printf("\n>> FreeBSD EFI boot block\n");
424 printf(" Loader path: %s\n\n", PATH_LOADER_EFI);
425 printf(" Initializing modules:");
426 for (i = 0; i < NUM_BOOT_MODULES; i++) {
427 printf(" %s", boot_modules[i]->name);
428 if (boot_modules[i]->init != NULL)
429 boot_modules[i]->init();
433 /* Determine the devpath of our image so we can prefer it. */
434 status = BS->HandleProtocol(IH, &LoadedImageGUID, (VOID**)&img);
436 if (status == EFI_SUCCESS) {
437 text = efi_devpath_name(img->FilePath);
439 printf(" Load Path: %S\n", text);
440 efi_setenv_freebsd_wcs("Boot1Path", text);
441 efi_free_devpath_name(text);
444 status = BS->HandleProtocol(img->DeviceHandle, &DevicePathGUID,
446 if (status != EFI_SUCCESS) {
447 DPRINTF("Failed to get image DevicePath (%lu)\n",
448 EFI_ERROR_CODE(status));
450 text = efi_devpath_name(imgpath);
452 printf(" Load Device: %S\n", text);
453 efi_setenv_freebsd_wcs("Boot1Dev", text);
454 efi_free_devpath_name(text);
460 sz = sizeof(boot_current);
461 if (efi_global_getenv("BootCurrent", &boot_current, &sz) == EFI_SUCCESS) {
462 printf(" BootCurrent: %04x\n", boot_current);
464 sz = sizeof(boot_order);
465 if (efi_global_getenv("BootOrder", &boot_order, &sz) == EFI_SUCCESS) {
466 printf(" BootOrder:");
467 for (i = 0; i < sz / sizeof(boot_order[0]); i++)
468 printf(" %04x%s", boot_order[i],
469 boot_order[i] == boot_current ? "[*]" : "");
476 * For testing failover scenarios, it's nice to be able to fail fast.
477 * Define TEST_FAILURE to create a boot1.efi that always fails after
478 * reporting the boot manager protocol details.
480 BS->Exit(IH, EFI_OUT_OF_RESOURCES, 0, NULL);
483 /* Get all the device handles */
484 hsize = (UINTN)NUM_HANDLES_INIT * sizeof(EFI_HANDLE);
485 handles = malloc(hsize);
487 printf("Failed to allocate %d handles\n", NUM_HANDLES_INIT);
489 status = BS->LocateHandle(ByProtocol, &BlockIoProtocolGUID, NULL,
494 case EFI_BUFFER_TOO_SMALL:
496 handles = malloc(hsize);
498 efi_panic(EFI_OUT_OF_RESOURCES, "Failed to allocate %d handles\n",
500 status = BS->LocateHandle(ByProtocol, &BlockIoProtocolGUID,
501 NULL, &hsize, handles);
502 if (status != EFI_SUCCESS)
503 efi_panic(status, "Failed to get device handles\n");
506 efi_panic(status, "Failed to get device handles\n");
510 /* Scan all partitions, probing with all modules. */
511 nhandles = hsize / sizeof(*handles);
512 printf(" Probing %zu block devices...", nhandles);
515 for (i = 0; i < nhandles; i++)
516 probe_handle_status(handles[i], imgpath);
519 /* Status summary. */
520 for (i = 0; i < NUM_BOOT_MODULES; i++) {
522 boot_modules[i]->status();
527 /* If we get here, we're out of luck... */
528 efi_panic(EFI_LOAD_ERROR, "No bootable partitions found!");
532 * add_device adds a device to the passed devinfo list.
535 add_device(dev_info_t **devinfop, dev_info_t *devinfo)
539 if (*devinfop == NULL) {
544 for (dev = *devinfop; dev->next != NULL; dev = dev->next)
551 * OK. We totally give up. Exit back to EFI with a sensible status so
552 * it can try the next option on the list.
555 efi_panic(EFI_STATUS s, const char *fmt, ...)
565 BS->Exit(IH, s, 0, NULL);
576 ST->ConOut->OutputString(ST->ConOut, buf);
580 ST->ConOut->OutputString(ST->ConOut, buf);