]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - stand/efi/loader/bootinfo.c
zfs: merge openzfs/zfs@c4c162c1e (master) into main
[FreeBSD/FreeBSD.git] / stand / efi / loader / bootinfo.c
1 /*-
2  * Copyright (c) 1998 Michael Smith <msmith@freebsd.org>
3  * Copyright (c) 2004, 2006 Marcel Moolenaar
4  * Copyright (c) 2014 The FreeBSD Foundation
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31
32 #include <stand.h>
33 #include <string.h>
34 #include <sys/param.h>
35 #include <sys/linker.h>
36 #include <sys/reboot.h>
37 #include <sys/boot.h>
38 #include <machine/cpufunc.h>
39 #include <machine/elf.h>
40 #include <machine/metadata.h>
41 #include <machine/psl.h>
42
43 #include <efi.h>
44 #include <efilib.h>
45
46 #include "bootstrap.h"
47 #include "loader_efi.h"
48
49 #if defined(__amd64__)
50 #include <machine/specialreg.h>
51 #endif
52
53 #include "gfx_fb.h"
54
55 #if defined(LOADER_FDT_SUPPORT)
56 #include <fdt_platform.h>
57 #endif
58
59 #ifdef LOADER_GELI_SUPPORT
60 #include "geliboot.h"
61 #endif
62
63 int bi_load(char *args, vm_offset_t *modulep, vm_offset_t *kernendp,
64     bool exit_bs);
65
66 extern EFI_SYSTEM_TABLE *ST;
67
68 static int
69 bi_getboothowto(char *kargs)
70 {
71         const char *sw, *tmp;
72         char *opts;
73         char *console;
74         int howto, speed, port;
75         char buf[50];
76
77         howto = boot_parse_cmdline(kargs);
78         howto |= boot_env_to_howto();
79
80         console = getenv("console");
81         if (console != NULL) {
82                 if (strcmp(console, "comconsole") == 0)
83                         howto |= RB_SERIAL;
84                 if (strcmp(console, "nullconsole") == 0)
85                         howto |= RB_MUTE;
86 #if defined(__i386__) || defined(__amd64__)
87                 if (strcmp(console, "efi") == 0 &&
88                     getenv("efi_8250_uid") != NULL &&
89                     getenv("hw.uart.console") == NULL) {
90                         /*
91                          * If we found a 8250 com port and com speed, we need to
92                          * tell the kernel where the serial port is, and how
93                          * fast. Ideally, we'd get the port from ACPI, but that
94                          * isn't running in the loader. Do the next best thing
95                          * by allowing it to be set by a loader.conf variable,
96                          * either a EFI specific one, or the compatible
97                          * comconsole_port if not. PCI support is needed, but
98                          * for that we'd ideally refactor the
99                          * libi386/comconsole.c code to have identical behavior.
100                          * We only try to set the port for cases where we saw
101                          * the Serial(x) node when parsing, otherwise
102                          * specialized hardware that has Uart nodes will have a
103                          * bogus address set.
104                          * But if someone specifically setup hw.uart.console,
105                          * don't override that.
106                          */
107                         speed = -1;
108                         port = -1;
109                         tmp = getenv("efi_com_speed");
110                         if (tmp != NULL)
111                                 speed = strtol(tmp, NULL, 0);
112                         tmp = getenv("efi_com_port");
113                         if (tmp == NULL)
114                                 tmp = getenv("comconsole_port");
115                         if (tmp != NULL)
116                                 port = strtol(tmp, NULL, 0);
117                         if (speed != -1 && port != -1) {
118                                 snprintf(buf, sizeof(buf), "io:%d,br:%d", port,
119                                     speed);
120                                 env_setenv("hw.uart.console", EV_VOLATILE, buf,
121                                     NULL, NULL);
122                         }
123                 }
124 #endif
125         }
126
127         return (howto);
128 }
129
130 /*
131  * Copy the environment into the load area starting at (addr).
132  * Each variable is formatted as <name>=<value>, with a single nul
133  * separating each variable, and a double nul terminating the environment.
134  */
135 static vm_offset_t
136 bi_copyenv(vm_offset_t start)
137 {
138         struct env_var *ep;
139         vm_offset_t addr, last;
140         size_t len;
141
142         addr = last = start;
143
144         /* Traverse the environment. */
145         for (ep = environ; ep != NULL; ep = ep->ev_next) {
146                 len = strlen(ep->ev_name);
147                 if ((size_t)archsw.arch_copyin(ep->ev_name, addr, len) != len)
148                         break;
149                 addr += len;
150                 if (archsw.arch_copyin("=", addr, 1) != 1)
151                         break;
152                 addr++;
153                 if (ep->ev_value != NULL) {
154                         len = strlen(ep->ev_value);
155                         if ((size_t)archsw.arch_copyin(ep->ev_value, addr, len) != len)
156                                 break;
157                         addr += len;
158                 }
159                 if (archsw.arch_copyin("", addr, 1) != 1)
160                         break;
161                 last = ++addr;
162         }
163
164         if (archsw.arch_copyin("", last++, 1) != 1)
165                 last = start;
166         return(last);
167 }
168
169 /*
170  * Copy module-related data into the load area, where it can be
171  * used as a directory for loaded modules.
172  *
173  * Module data is presented in a self-describing format.  Each datum
174  * is preceded by a 32-bit identifier and a 32-bit size field.
175  *
176  * Currently, the following data are saved:
177  *
178  * MOD_NAME     (variable)              module name (string)
179  * MOD_TYPE     (variable)              module type (string)
180  * MOD_ARGS     (variable)              module parameters (string)
181  * MOD_ADDR     sizeof(vm_offset_t)     module load address
182  * MOD_SIZE     sizeof(size_t)          module size
183  * MOD_METADATA (variable)              type-specific metadata
184  */
185 #define COPY32(v, a, c) {                                       \
186         uint32_t x = (v);                                       \
187         if (c)                                                  \
188                 archsw.arch_copyin(&x, a, sizeof(x));           \
189         a += sizeof(x);                                         \
190 }
191
192 #define MOD_STR(t, a, s, c) {                                   \
193         COPY32(t, a, c);                                        \
194         COPY32(strlen(s) + 1, a, c);                            \
195         if (c)                                                  \
196                 archsw.arch_copyin(s, a, strlen(s) + 1);        \
197         a += roundup(strlen(s) + 1, sizeof(u_long));            \
198 }
199
200 #define MOD_NAME(a, s, c)       MOD_STR(MODINFO_NAME, a, s, c)
201 #define MOD_TYPE(a, s, c)       MOD_STR(MODINFO_TYPE, a, s, c)
202 #define MOD_ARGS(a, s, c)       MOD_STR(MODINFO_ARGS, a, s, c)
203
204 #define MOD_VAR(t, a, s, c) {                                   \
205         COPY32(t, a, c);                                        \
206         COPY32(sizeof(s), a, c);                                \
207         if (c)                                                  \
208                 archsw.arch_copyin(&s, a, sizeof(s));           \
209         a += roundup(sizeof(s), sizeof(u_long));                \
210 }
211
212 #define MOD_ADDR(a, s, c)       MOD_VAR(MODINFO_ADDR, a, s, c)
213 #define MOD_SIZE(a, s, c)       MOD_VAR(MODINFO_SIZE, a, s, c)
214
215 #define MOD_METADATA(a, mm, c) {                                \
216         COPY32(MODINFO_METADATA | mm->md_type, a, c);           \
217         COPY32(mm->md_size, a, c);                              \
218         if (c)                                                  \
219                 archsw.arch_copyin(mm->md_data, a, mm->md_size);        \
220         a += roundup(mm->md_size, sizeof(u_long));              \
221 }
222
223 #define MOD_END(a, c) {                                         \
224         COPY32(MODINFO_END, a, c);                              \
225         COPY32(0, a, c);                                        \
226 }
227
228 static vm_offset_t
229 bi_copymodules(vm_offset_t addr)
230 {
231         struct preloaded_file *fp;
232         struct file_metadata *md;
233         int c;
234         uint64_t v;
235
236         c = addr != 0;
237         /* Start with the first module on the list, should be the kernel. */
238         for (fp = file_findfile(NULL, NULL); fp != NULL; fp = fp->f_next) {
239                 MOD_NAME(addr, fp->f_name, c); /* This must come first. */
240                 MOD_TYPE(addr, fp->f_type, c);
241                 if (fp->f_args)
242                         MOD_ARGS(addr, fp->f_args, c);
243                 v = fp->f_addr;
244 #if defined(__arm__)
245                 v -= __elfN(relocation_offset);
246 #endif
247                 MOD_ADDR(addr, v, c);
248                 v = fp->f_size;
249                 MOD_SIZE(addr, v, c);
250                 for (md = fp->f_metadata; md != NULL; md = md->md_next)
251                         if (!(md->md_type & MODINFOMD_NOCOPY))
252                                 MOD_METADATA(addr, md, c);
253         }
254         MOD_END(addr, c);
255         return(addr);
256 }
257
258 static EFI_STATUS
259 efi_do_vmap(EFI_MEMORY_DESCRIPTOR *mm, UINTN sz, UINTN mmsz, UINT32 mmver)
260 {
261         EFI_MEMORY_DESCRIPTOR *desc, *viter, *vmap;
262         EFI_STATUS ret;
263         int curr, ndesc, nset;
264
265         nset = 0;
266         desc = mm;
267         ndesc = sz / mmsz;
268         vmap = malloc(sz);
269         if (vmap == NULL)
270                 /* This isn't really an EFI error case, but pretend it is */
271                 return (EFI_OUT_OF_RESOURCES);
272         viter = vmap;
273         for (curr = 0; curr < ndesc;
274             curr++, desc = NextMemoryDescriptor(desc, mmsz)) {
275                 if ((desc->Attribute & EFI_MEMORY_RUNTIME) != 0) {
276                         ++nset;
277                         desc->VirtualStart = desc->PhysicalStart;
278                         *viter = *desc;
279                         viter = NextMemoryDescriptor(viter, mmsz);
280                 }
281         }
282         ret = RS->SetVirtualAddressMap(nset * mmsz, mmsz, mmver, vmap);
283         free(vmap);
284         return (ret);
285 }
286
287 static int
288 bi_load_efi_data(struct preloaded_file *kfp, bool exit_bs)
289 {
290         EFI_MEMORY_DESCRIPTOR *mm;
291         EFI_PHYSICAL_ADDRESS addr = 0;
292         EFI_STATUS status;
293         const char *efi_novmap;
294         size_t efisz;
295         UINTN efi_mapkey;
296         UINTN dsz, pages, retry, sz;
297         UINT32 mmver;
298         struct efi_map_header *efihdr;
299         bool do_vmap;
300
301 #if defined(__amd64__) || defined(__aarch64__)
302         struct efi_fb efifb;
303
304         efifb.fb_addr = gfx_state.tg_fb.fb_addr;
305         efifb.fb_size = gfx_state.tg_fb.fb_size;
306         efifb.fb_height = gfx_state.tg_fb.fb_height;
307         efifb.fb_width = gfx_state.tg_fb.fb_width;
308         efifb.fb_stride = gfx_state.tg_fb.fb_stride;
309         efifb.fb_mask_red = gfx_state.tg_fb.fb_mask_red;
310         efifb.fb_mask_green = gfx_state.tg_fb.fb_mask_green;
311         efifb.fb_mask_blue = gfx_state.tg_fb.fb_mask_blue;
312         efifb.fb_mask_reserved = gfx_state.tg_fb.fb_mask_reserved;
313
314         printf("EFI framebuffer information:\n");
315         printf("addr, size     0x%jx, 0x%jx\n", efifb.fb_addr, efifb.fb_size);
316         printf("dimensions     %d x %d\n", efifb.fb_width, efifb.fb_height);
317         printf("stride         %d\n", efifb.fb_stride);
318         printf("masks          0x%08x, 0x%08x, 0x%08x, 0x%08x\n",
319             efifb.fb_mask_red, efifb.fb_mask_green, efifb.fb_mask_blue,
320             efifb.fb_mask_reserved);
321
322         if (efifb.fb_addr != 0)
323                 file_addmetadata(kfp, MODINFOMD_EFI_FB, sizeof(efifb), &efifb);
324 #endif
325
326         do_vmap = true;
327         efi_novmap = getenv("efi_disable_vmap");
328         if (efi_novmap != NULL)
329                 do_vmap = strcasecmp(efi_novmap, "YES") != 0;
330
331         efisz = (sizeof(struct efi_map_header) + 0xf) & ~0xf;
332
333         /*
334          * Assign size of EFI_MEMORY_DESCRIPTOR to keep compatible with
335          * u-boot which doesn't fill this value when buffer for memory
336          * descriptors is too small (eg. 0 to obtain memory map size)
337          */
338         dsz = sizeof(EFI_MEMORY_DESCRIPTOR);
339
340         /*
341          * Allocate enough pages to hold the bootinfo block and the
342          * memory map EFI will return to us. The memory map has an
343          * unknown size, so we have to determine that first. Note that
344          * the AllocatePages call can itself modify the memory map, so
345          * we have to take that into account as well. The changes to
346          * the memory map are caused by splitting a range of free
347          * memory into two, so that one is marked as being loader
348          * data.
349          */
350
351         sz = 0;
352
353         /*
354          * Matthew Garrett has observed at least one system changing the
355          * memory map when calling ExitBootServices, causing it to return an
356          * error, probably because callbacks are allocating memory.
357          * So we need to retry calling it at least once.
358          */
359         for (retry = 2; retry > 0; retry--) {
360                 for (;;) {
361                         status = BS->GetMemoryMap(&sz, mm, &efi_mapkey, &dsz, &mmver);
362                         if (!EFI_ERROR(status))
363                                 break;
364
365                         if (status != EFI_BUFFER_TOO_SMALL) {
366                                 printf("%s: GetMemoryMap error %lu\n", __func__,
367                                    EFI_ERROR_CODE(status));
368                                 return (EINVAL);
369                         }
370
371                         if (addr != 0)
372                                 BS->FreePages(addr, pages);
373
374                         /* Add 10 descriptors to the size to allow for
375                          * fragmentation caused by calling AllocatePages */
376                         sz += (10 * dsz);
377                         pages = EFI_SIZE_TO_PAGES(sz + efisz);
378                         status = BS->AllocatePages(AllocateAnyPages, EfiLoaderData,
379                                         pages, &addr);
380                         if (EFI_ERROR(status)) {
381                                 printf("%s: AllocatePages error %lu\n", __func__,
382                                     EFI_ERROR_CODE(status));
383                                 return (ENOMEM);
384                         }
385
386                         /*
387                          * Read the memory map and stash it after bootinfo. Align the
388                          * memory map on a 16-byte boundary (the bootinfo block is page
389                          * aligned).
390                          */
391                         efihdr = (struct efi_map_header *)(uintptr_t)addr;
392                         mm = (void *)((uint8_t *)efihdr + efisz);
393                         sz = (EFI_PAGE_SIZE * pages) - efisz;
394                 }
395
396                 if (!exit_bs)
397                         break;
398                 status = BS->ExitBootServices(IH, efi_mapkey);
399                 if (!EFI_ERROR(status))
400                         break;
401         }
402
403         if (retry == 0) {
404                 BS->FreePages(addr, pages);
405                 printf("ExitBootServices error %lu\n", EFI_ERROR_CODE(status));
406                 return (EINVAL);
407         }
408
409         /*
410          * This may be disabled by setting efi_disable_vmap in
411          * loader.conf(5). By default we will setup the virtual
412          * map entries.
413          */
414
415         if (do_vmap)
416                 efi_do_vmap(mm, sz, dsz, mmver);
417         efihdr->memory_size = sz;
418         efihdr->descriptor_size = dsz;
419         efihdr->descriptor_version = mmver;
420         file_addmetadata(kfp, MODINFOMD_EFI_MAP, efisz + sz,
421             efihdr);
422
423         return (0);
424 }
425
426 /*
427  * Load the information expected by an amd64 kernel.
428  *
429  * - The 'boothowto' argument is constructed.
430  * - The 'bootdev' argument is constructed.
431  * - The 'bootinfo' struct is constructed, and copied into the kernel space.
432  * - The kernel environment is copied into kernel space.
433  * - Module metadata are formatted and placed in kernel space.
434  */
435 int
436 bi_load(char *args, vm_offset_t *modulep, vm_offset_t *kernendp, bool exit_bs)
437 {
438         struct preloaded_file *xp, *kfp;
439         struct devdesc *rootdev;
440         struct file_metadata *md;
441         vm_offset_t addr;
442         uint64_t kernend, module;
443         uint64_t envp;
444         vm_offset_t size;
445         char *rootdevname;
446         int howto;
447 #if defined(LOADER_FDT_SUPPORT)
448         vm_offset_t dtbp;
449         int dtb_size;
450 #endif
451 #if defined(__arm__)
452         vm_offset_t vaddr;
453         size_t i;
454         /*
455          * These metadata addreses must be converted for kernel after
456          * relocation.
457          */
458         uint32_t                mdt[] = {
459             MODINFOMD_SSYM, MODINFOMD_ESYM, MODINFOMD_KERNEND,
460             MODINFOMD_ENVP, MODINFOMD_FONT,
461 #if defined(LOADER_FDT_SUPPORT)
462             MODINFOMD_DTBP
463 #endif
464         };
465 #endif
466
467         howto = bi_getboothowto(args);
468
469         /*
470          * Allow the environment variable 'rootdev' to override the supplied
471          * device. This should perhaps go to MI code and/or have $rootdev
472          * tested/set by MI code before launching the kernel.
473          */
474         rootdevname = getenv("rootdev");
475         archsw.arch_getdev((void**)(&rootdev), rootdevname, NULL);
476         if (rootdev == NULL) {
477                 printf("Can't determine root device.\n");
478                 return(EINVAL);
479         }
480
481         /* Try reading the /etc/fstab file to select the root device */
482         getrootmount(efi_fmtdev((void *)rootdev));
483
484         addr = 0;
485         for (xp = file_findfile(NULL, NULL); xp != NULL; xp = xp->f_next) {
486                 if (addr < (xp->f_addr + xp->f_size))
487                         addr = xp->f_addr + xp->f_size;
488         }
489
490         /* Pad to a page boundary. */
491         addr = roundup(addr, PAGE_SIZE);
492
493         addr = build_font_module(addr);
494
495         /* Pad to a page boundary. */
496         addr = roundup(addr, PAGE_SIZE);
497
498         /* Copy our environment. */
499         envp = addr;
500         addr = bi_copyenv(addr);
501
502         /* Pad to a page boundary. */
503         addr = roundup(addr, PAGE_SIZE);
504
505 #if defined(LOADER_FDT_SUPPORT)
506         /* Handle device tree blob */
507         dtbp = addr;
508         dtb_size = fdt_copy(addr);
509                 
510         /* Pad to a page boundary */
511         if (dtb_size)
512                 addr += roundup(dtb_size, PAGE_SIZE);
513 #endif
514
515         kfp = file_findfile(NULL, "elf kernel");
516         if (kfp == NULL)
517                 kfp = file_findfile(NULL, "elf64 kernel");
518         if (kfp == NULL)
519                 panic("can't find kernel file");
520         kernend = 0;    /* fill it in later */
521
522         /* Figure out the size and location of the metadata. */
523         module = *modulep = addr;
524
525         file_addmetadata(kfp, MODINFOMD_HOWTO, sizeof(howto), &howto);
526         file_addmetadata(kfp, MODINFOMD_ENVP, sizeof(envp), &envp);
527 #if defined(LOADER_FDT_SUPPORT)
528         if (dtb_size)
529                 file_addmetadata(kfp, MODINFOMD_DTBP, sizeof(dtbp), &dtbp);
530         else
531                 printf("WARNING! Trying to fire up the kernel, but no "
532                     "device tree blob found!\n");
533 #endif
534         file_addmetadata(kfp, MODINFOMD_KERNEND, sizeof(kernend), &kernend);
535 #ifdef MODINFOMD_MODULEP
536         file_addmetadata(kfp, MODINFOMD_MODULEP, sizeof(module), &module);
537 #endif
538         file_addmetadata(kfp, MODINFOMD_FW_HANDLE, sizeof(ST), &ST);
539 #ifdef LOADER_GELI_SUPPORT
540         geli_export_key_metadata(kfp);
541 #endif
542         bi_load_efi_data(kfp, exit_bs);
543
544         size = bi_copymodules(0);
545         kernend = roundup(addr + size, PAGE_SIZE);
546         *kernendp = kernend;
547
548         /* patch MODINFOMD_KERNEND */
549         md = file_findmetadata(kfp, MODINFOMD_KERNEND);
550         bcopy(&kernend, md->md_data, sizeof kernend);
551
552 #if defined(__arm__)
553         *modulep -= __elfN(relocation_offset);
554
555         /* Do relocation fixup on metadata of each module. */
556         for (xp = file_findfile(NULL, NULL); xp != NULL; xp = xp->f_next) {
557                 for (i = 0; i < nitems(mdt); i++) {
558                         md = file_findmetadata(xp, mdt[i]);
559                         if (md) {
560                                 bcopy(md->md_data, &vaddr, sizeof vaddr);
561                                 vaddr -= __elfN(relocation_offset);
562                                 bcopy(&vaddr, md->md_data, sizeof vaddr);
563                         }
564                 }
565         }
566 #endif
567
568         /* Copy module list and metadata. */
569         (void)bi_copymodules(addr);
570
571         return (0);
572 }