]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - stand/efi/boot1/boot1.c
loader: support com.delphix:removing
[FreeBSD/FreeBSD.git] / stand / efi / boot1 / boot1.c
1 /*-
2  * Copyright (c) 1998 Robert Nordier
3  * All rights reserved.
4  * Copyright (c) 2001 Robert Drehmel
5  * All rights reserved.
6  * Copyright (c) 2014 Nathan Whitehorn
7  * All rights reserved.
8  * Copyright (c) 2015 Eric McCorkle
9  * All rights reserved.
10  *
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
14  * such forms.
15  *
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
19  * purpose.
20  */
21
22 #include <sys/cdefs.h>
23 __FBSDID("$FreeBSD$");
24
25 #include <sys/param.h>
26 #include <machine/elf.h>
27 #include <machine/stdarg.h>
28 #include <stand.h>
29
30 #include <efi.h>
31 #include <eficonsctl.h>
32 #include <efichar.h>
33
34 #include "boot_module.h"
35 #include "paths.h"
36
37 static void efi_panic(EFI_STATUS s, const char *fmt, ...) __dead2 __printflike(2, 3);
38
39 static const boot_module_t *boot_modules[] =
40 {
41 #ifdef EFI_ZFS_BOOT
42         &zfs_module,
43 #endif
44 #ifdef EFI_UFS_BOOT
45         &ufs_module
46 #endif
47 };
48
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
52
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
58 /*
59  * Provide Malloc / Free / Calloc backed by EFIs AllocatePool / FreePool which ensures
60  * memory is correctly aligned avoiding EFI_INVALID_PARAMETER returns from
61  * EFI methods.
62  */
63
64 void *
65 Malloc(size_t len, const char *file __unused, int line __unused)
66 {
67         void *out;
68
69         if (BS->AllocatePool(EfiLoaderData, len, &out) == EFI_SUCCESS)
70                 return (out);
71
72         return (NULL);
73 }
74
75 void
76 Free(void *buf, const char *file __unused, int line __unused)
77 {
78         if (buf != NULL)
79                 (void)BS->FreePool(buf);
80 }
81
82 void *
83 Calloc(size_t n1, size_t n2, const char *file, int line)
84 {
85         size_t bytes;
86         void *res;
87
88         bytes = n1 * n2;
89         if ((res = Malloc(bytes, file, line)) != NULL)
90                 bzero(res, bytes);
91
92         return (res);
93 }
94
95 /*
96  * nodes_match returns TRUE if the imgpath isn't NULL and the nodes match,
97  * FALSE otherwise.
98  */
99 static BOOLEAN
100 nodes_match(EFI_DEVICE_PATH *imgpath, EFI_DEVICE_PATH *devpath)
101 {
102         size_t len;
103
104         if (imgpath == NULL || imgpath->Type != devpath->Type ||
105             imgpath->SubType != devpath->SubType)
106                 return (FALSE);
107
108         len = DevicePathNodeLength(imgpath);
109         if (len != DevicePathNodeLength(devpath))
110                 return (FALSE);
111
112         return (memcmp(imgpath, devpath, (size_t)len) == 0);
113 }
114
115 /*
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.
119  */
120 static BOOLEAN
121 device_paths_match(EFI_DEVICE_PATH *imgpath, EFI_DEVICE_PATH *devpath)
122 {
123
124         if (imgpath == NULL)
125                 return (FALSE);
126
127         while (!IsDevicePathEnd(imgpath) && !IsDevicePathEnd(devpath)) {
128                 if (IsDevicePathType(imgpath, MEDIA_DEVICE_PATH) &&
129                     IsDevicePathType(devpath, MEDIA_DEVICE_PATH))
130                         return (TRUE);
131
132                 if (!nodes_match(imgpath, devpath))
133                         return (FALSE);
134
135                 imgpath = NextDevicePathNode(imgpath);
136                 devpath = NextDevicePathNode(devpath);
137         }
138
139         return (FALSE);
140 }
141
142 /*
143  * devpath_last returns the last non-path end node in devpath.
144  */
145 static EFI_DEVICE_PATH *
146 devpath_last(EFI_DEVICE_PATH *devpath)
147 {
148
149         while (!IsDevicePathEnd(NextDevicePathNode(devpath)))
150                 devpath = NextDevicePathNode(devpath);
151
152         return (devpath);
153 }
154
155 /*
156  * load_loader attempts to load the loader image data.
157  *
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.
161  *
162  * Only devices which have preferred matching the preferred parameter are tried.
163  */
164 static EFI_STATUS
165 load_loader(const boot_module_t **modp, dev_info_t **devinfop, void **bufp,
166     size_t *bufsize, BOOLEAN preferred)
167 {
168         UINTN i;
169         dev_info_t *dev;
170         const boot_module_t *mod;
171
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)
176                                 continue;
177
178                         if (mod->load(PATH_LOADER_EFI, dev, bufp, bufsize) ==
179                             EFI_SUCCESS) {
180                                 *devinfop = dev;
181                                 *modp = mod;
182                                 return (EFI_SUCCESS);
183                         }
184                 }
185         }
186
187         return (EFI_NOT_FOUND);
188 }
189
190 /*
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.
193  */
194 static EFI_STATUS
195 try_boot(void)
196 {
197         size_t bufsize, loadersize, cmdsize;
198         void *buf, *loaderbuf;
199         char *cmd;
200         dev_info_t *dev;
201         const boot_module_t *mod;
202         EFI_HANDLE loaderhandle;
203         EFI_LOADED_IMAGE *loaded_image;
204         EFI_STATUS status;
205
206         status = load_loader(&mod, &dev, &loaderbuf, &loadersize, TRUE);
207         if (status != EFI_SUCCESS) {
208                 status = load_loader(&mod, &dev, &loaderbuf, &loadersize,
209                     FALSE);
210                 if (status != EFI_SUCCESS) {
211                         printf("Failed to load '%s'\n", PATH_LOADER_EFI);
212                         return (status);
213                 }
214         }
215
216         /*
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.
225          */
226         cmd = NULL;
227         cmdsize = 0;
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);
234                 if (cmd == NULL)
235                         goto errout;
236                 memcpy(cmd, buf, bufsize);
237                 cmd[bufsize] = '\0';
238                 free(buf);
239                 buf = NULL;
240         }
241
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));
246                 goto errout;
247         }
248
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));
253                 goto errout;
254         }
255
256         if (cmd != NULL)
257                 printf("    command args: %s\n", cmd);
258
259         loaded_image->DeviceHandle = dev->devhandle;
260         loaded_image->LoadOptionsSize = cmdsize;
261         loaded_image->LoadOptions = cmd;
262
263         DPRINTF("Starting '%s' in 5 seconds...", PATH_LOADER_EFI);
264         DSTALL(1000000);
265         DPRINTF(".");
266         DSTALL(1000000);
267         DPRINTF(".");
268         DSTALL(1000000);
269         DPRINTF(".");
270         DSTALL(1000000);
271         DPRINTF(".");
272         DSTALL(1000000);
273         DPRINTF(".\n");
274
275         if ((status = BS->StartImage(loaderhandle, NULL, NULL)) !=
276             EFI_SUCCESS) {
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;
281         }
282
283 errout:
284         if (cmd != NULL)
285                 free(cmd);
286         if (buf != NULL)
287                 free(buf);
288         if (loaderbuf != NULL)
289                 free(loaderbuf);
290
291         return (status);
292 }
293
294 /*
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.
298  */
299 static EFI_STATUS
300 probe_handle(EFI_HANDLE h, EFI_DEVICE_PATH *imgpath, BOOLEAN *preferred)
301 {
302         dev_info_t *devinfo;
303         EFI_BLOCK_IO *blkio;
304         EFI_DEVICE_PATH *devpath;
305         EFI_STATUS status;
306         UINTN i;
307
308         /* Figure out if we're dealing with an actual partition. */
309         status = BS->HandleProtocol(h, &DevicePathGUID, (void **)&devpath);
310         if (status == EFI_UNSUPPORTED)
311                 return (status);
312
313         if (status != EFI_SUCCESS) {
314                 DPRINTF("\nFailed to query DevicePath (%lu)\n",
315                     EFI_ERROR_CODE(status));
316                 return (status);
317         }
318 #ifdef EFI_DEBUG
319         {
320                 CHAR16 *text = efi_devpath_name(devpath);
321                 DPRINTF("probing: %S\n", text);
322                 efi_free_devpath_name(text);
323         }
324 #endif
325         status = BS->HandleProtocol(h, &BlockIoProtocolGUID, (void **)&blkio);
326         if (status == EFI_UNSUPPORTED)
327                 return (status);
328
329         if (status != EFI_SUCCESS) {
330                 DPRINTF("\nFailed to query BlockIoProtocol (%lu)\n",
331                     EFI_ERROR_CODE(status));
332                 return (status);
333         }
334
335         if (!blkio->Media->LogicalPartition)
336                 return (EFI_UNSUPPORTED);
337
338         *preferred = device_paths_match(imgpath, devpath);
339
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");
345                         continue;
346                 }
347                 devinfo->dev = blkio;
348                 devinfo->devpath = devpath;
349                 devinfo->devhandle = h;
350                 devinfo->devdata = NULL;
351                 devinfo->preferred = *preferred;
352                 devinfo->next = NULL;
353
354                 status = boot_modules[i]->probe(devinfo);
355                 if (status == EFI_SUCCESS)
356                         return (EFI_SUCCESS);
357                 free(devinfo);
358         }
359
360         return (EFI_UNSUPPORTED);
361 }
362
363 /*
364  * probe_handle_status calls probe_handle and outputs the returned status
365  * of the call.
366  */
367 static void
368 probe_handle_status(EFI_HANDLE h, EFI_DEVICE_PATH *imgpath)
369 {
370         EFI_STATUS status;
371         BOOLEAN preferred;
372
373         preferred = FALSE;
374         status = probe_handle(h, imgpath, &preferred);
375         
376         DPRINTF("probe: ");
377         switch (status) {
378         case EFI_UNSUPPORTED:
379                 printf(".");
380                 DPRINTF(" not supported\n");
381                 break;
382         case EFI_SUCCESS:
383                 if (preferred) {
384                         printf("%c", '*');
385                         DPRINTF(" supported (preferred)\n");
386                 } else {
387                         printf("%c", '+');
388                         DPRINTF(" supported\n");
389                 }
390                 break;
391         default:
392                 printf("x");
393                 DPRINTF(" error (%lu)\n", EFI_ERROR_CODE(status));
394                 break;
395         }
396         DSTALL(500000);
397 }
398
399 EFI_STATUS
400 efi_main(EFI_HANDLE Ximage, EFI_SYSTEM_TABLE *Xsystab)
401 {
402         EFI_HANDLE *handles;
403         EFI_LOADED_IMAGE *img;
404         EFI_DEVICE_PATH *imgpath;
405         EFI_STATUS status;
406         EFI_CONSOLE_CONTROL_PROTOCOL *ConsoleControl = NULL;
407         SIMPLE_TEXT_OUTPUT_INTERFACE *conout = NULL;
408         UINTN i, hsize, nhandles;
409         CHAR16 *text;
410         UINT16 boot_current;
411         size_t sz;
412         UINT16 boot_order[100];
413
414         /* Basic initialization*/
415         ST = Xsystab;
416         IH = Ximage;
417         BS = ST->BootServices;
418         RS = ST->RuntimeServices;
419
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);
426         /*
427          * Reset the console enable the cursor. Later we'll choose a better
428          * console size through GOP/UGA.
429          */
430         conout = ST->ConOut;
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);
436
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();
444         }
445         putchar('\n');
446
447         /* Determine the devpath of our image so we can prefer it. */
448         status = BS->HandleProtocol(IH, &LoadedImageGUID, (VOID**)&img);
449         imgpath = NULL;
450         if (status == EFI_SUCCESS) {
451                 text = efi_devpath_name(img->FilePath);
452                 if (text != NULL) {
453                         printf("   Load Path: %S\n", text);
454                         efi_setenv_freebsd_wcs("Boot1Path", text);
455                         efi_free_devpath_name(text);
456                 }
457
458                 status = BS->HandleProtocol(img->DeviceHandle, &DevicePathGUID,
459                     (void **)&imgpath);
460                 if (status != EFI_SUCCESS) {
461                         DPRINTF("Failed to get image DevicePath (%lu)\n",
462                             EFI_ERROR_CODE(status));
463                 } else {
464                         text = efi_devpath_name(imgpath);
465                         if (text != NULL) {
466                                 printf("   Load Device: %S\n", text);
467                                 efi_setenv_freebsd_wcs("Boot1Dev", text);
468                                 efi_free_devpath_name(text);
469                         }
470                 }
471         }
472
473         boot_current = 0;
474         sz = sizeof(boot_current);
475         if (efi_global_getenv("BootCurrent", &boot_current, &sz) == EFI_SUCCESS) {
476                 printf("   BootCurrent: %04x\n", boot_current);
477
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 ? "[*]" : "");
484                         printf("\n");
485                 }
486         }
487
488 #ifdef TEST_FAILURE
489         /*
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.
493          */
494         BS->Exit(IH, EFI_OUT_OF_RESOURCES, 0, NULL);
495 #endif
496
497         /* Get all the device handles */
498         hsize = (UINTN)NUM_HANDLES_INIT * sizeof(EFI_HANDLE);
499         handles = malloc(hsize);
500         if (handles == NULL)
501                 printf("Failed to allocate %d handles\n", NUM_HANDLES_INIT);
502
503         status = BS->LocateHandle(ByProtocol, &BlockIoProtocolGUID, NULL,
504             &hsize, handles);
505         switch (status) {
506         case EFI_SUCCESS:
507                 break;
508         case EFI_BUFFER_TOO_SMALL:
509                 free(handles);
510                 handles = malloc(hsize);
511                 if (handles == NULL)
512                         efi_panic(EFI_OUT_OF_RESOURCES, "Failed to allocate %d handles\n",
513                             NUM_HANDLES_INIT);
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");
518                 break;
519         default:
520                 efi_panic(status, "Failed to get device handles\n");
521                 break;
522         }
523
524         /* Scan all partitions, probing with all modules. */
525         nhandles = hsize / sizeof(*handles);
526         printf("   Probing %zu block devices...", nhandles);
527         DPRINTF("\n");
528
529         for (i = 0; i < nhandles; i++)
530                 probe_handle_status(handles[i], imgpath);
531         printf(" done\n");
532
533         /* Status summary. */
534         for (i = 0; i < NUM_BOOT_MODULES; i++) {
535                 printf("    ");
536                 boot_modules[i]->status();
537         }
538
539         try_boot();
540
541         /* If we get here, we're out of luck... */
542         efi_panic(EFI_LOAD_ERROR, "No bootable partitions found!");
543 }
544
545 /*
546  * add_device adds a device to the passed devinfo list.
547  */
548 void
549 add_device(dev_info_t **devinfop, dev_info_t *devinfo)
550 {
551         dev_info_t *dev;
552
553         if (*devinfop == NULL) {
554                 *devinfop = devinfo;
555                 return;
556         }
557
558         for (dev = *devinfop; dev->next != NULL; dev = dev->next)
559                 ;
560
561         dev->next = devinfo;
562 }
563
564 /*
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.
567  */
568 static void
569 efi_panic(EFI_STATUS s, const char *fmt, ...)
570 {
571         va_list ap;
572
573         printf("panic: ");
574         va_start(ap, fmt);
575         vprintf(fmt, ap);
576         va_end(ap);
577         printf("\n");
578
579         BS->Exit(IH, s, 0, NULL);
580 }
581
582 void
583 putchar(int c)
584 {
585         CHAR16 buf[2];
586
587         if (c == '\n') {
588                 buf[0] = '\r';
589                 buf[1] = 0;
590                 ST->ConOut->OutputString(ST->ConOut, buf);
591         }
592         buf[0] = c;
593         buf[1] = 0;
594         ST->ConOut->OutputString(ST->ConOut, buf);
595 }