xref: /freebsd/stand/efi/loader/copy.c (revision d396c67f26b079c2808002c07212d9df9818a11b)
1 /*-
2  * Copyright (c) 2013 The FreeBSD Foundation
3  * All rights reserved.
4  *
5  * This software was developed by Benno Rice under sponsorship from
6  * the FreeBSD Foundation.
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 <sys/param.h>
33 
34 #include <stand.h>
35 #include <bootstrap.h>
36 
37 #include <efi.h>
38 #include <efilib.h>
39 
40 #include "loader_efi.h"
41 
42 #define	M(x)	((x) * 1024 * 1024)
43 #define	G(x)	(1UL * (x) * 1024 * 1024 * 1024)
44 
45 extern int boot_services_gone;
46 
47 #if defined(__i386__) || defined(__amd64__)
48 #include <machine/cpufunc.h>
49 #include <machine/specialreg.h>
50 #include <machine/vmparam.h>
51 
52 /*
53  * The code is excerpted from sys/x86/x86/identcpu.c: identify_cpu(),
54  * identify_hypervisor(), and dev/hyperv/vmbus/hyperv.c: hyperv_identify().
55  */
56 #define CPUID_LEAF_HV_MAXLEAF		0x40000000
57 #define CPUID_LEAF_HV_INTERFACE		0x40000001
58 #define CPUID_LEAF_HV_FEATURES		0x40000003
59 #define CPUID_LEAF_HV_LIMITS		0x40000005
60 #define CPUID_HV_IFACE_HYPERV		0x31237648	/* HV#1 */
61 #define CPUID_HV_MSR_TIME_REFCNT	0x0002	/* MSR_HV_TIME_REF_COUNT */
62 #define CPUID_HV_MSR_HYPERCALL		0x0020
63 
64 static int
65 running_on_hyperv(void)
66 {
67 	char hv_vendor[16];
68 	uint32_t regs[4];
69 
70 	do_cpuid(1, regs);
71 	if ((regs[2] & CPUID2_HV) == 0)
72 		return (0);
73 
74 	do_cpuid(CPUID_LEAF_HV_MAXLEAF, regs);
75 	if (regs[0] < CPUID_LEAF_HV_LIMITS)
76 		return (0);
77 
78 	((uint32_t *)&hv_vendor)[0] = regs[1];
79 	((uint32_t *)&hv_vendor)[1] = regs[2];
80 	((uint32_t *)&hv_vendor)[2] = regs[3];
81 	hv_vendor[12] = '\0';
82 	if (strcmp(hv_vendor, "Microsoft Hv") != 0)
83 		return (0);
84 
85 	do_cpuid(CPUID_LEAF_HV_INTERFACE, regs);
86 	if (regs[0] != CPUID_HV_IFACE_HYPERV)
87 		return (0);
88 
89 	do_cpuid(CPUID_LEAF_HV_FEATURES, regs);
90 	if ((regs[0] & CPUID_HV_MSR_HYPERCALL) == 0)
91 		return (0);
92 	if ((regs[0] & CPUID_HV_MSR_TIME_REFCNT) == 0)
93 		return (0);
94 
95 	return (1);
96 }
97 
98 static void
99 efi_verify_staging_size(unsigned long *nr_pages)
100 {
101 	UINTN sz;
102 	EFI_MEMORY_DESCRIPTOR *map = NULL, *p;
103 	EFI_PHYSICAL_ADDRESS start, end;
104 	UINTN key, dsz;
105 	UINT32 dver;
106 	EFI_STATUS status;
107 	int i, ndesc;
108 	unsigned long available_pages = 0;
109 
110 	sz = 0;
111 
112 	for (;;) {
113 		status = BS->GetMemoryMap(&sz, map, &key, &dsz, &dver);
114 		if (!EFI_ERROR(status))
115 			break;
116 
117 		if (status != EFI_BUFFER_TOO_SMALL) {
118 			printf("Can't read memory map: %lu\n",
119 			    EFI_ERROR_CODE(status));
120 			goto out;
121 		}
122 
123 		free(map);
124 
125 		/* Allocate 10 descriptors more than the size reported,
126 		 * to allow for any fragmentation caused by calling
127 		 * malloc */
128 		map = malloc(sz + (10 * dsz));
129 		if (map == NULL) {
130 			printf("Unable to allocate memory\n");
131 			goto out;
132 		}
133 	}
134 
135 	ndesc = sz / dsz;
136 	for (i = 0, p = map; i < ndesc;
137 	     i++, p = NextMemoryDescriptor(p, dsz)) {
138 		start = p->PhysicalStart;
139 		end = start + p->NumberOfPages * EFI_PAGE_SIZE;
140 
141 		if (KERNLOAD < start || KERNLOAD >= end)
142 			continue;
143 
144 		available_pages = p->NumberOfPages -
145 			((KERNLOAD - start) >> EFI_PAGE_SHIFT);
146 		break;
147 	}
148 
149 	if (available_pages == 0) {
150 		printf("Can't find valid memory map for staging area!\n");
151 		goto out;
152 	}
153 
154 	i++;
155 	p = NextMemoryDescriptor(p, dsz);
156 
157 	for ( ; i < ndesc;
158 	     i++, p = NextMemoryDescriptor(p, dsz)) {
159 		if (p->Type != EfiConventionalMemory &&
160 		    p->Type != EfiLoaderData)
161 			break;
162 
163 		if (p->PhysicalStart != end)
164 			break;
165 
166 		end = p->PhysicalStart + p->NumberOfPages * EFI_PAGE_SIZE;
167 
168 		available_pages += p->NumberOfPages;
169 	}
170 
171 	if (*nr_pages > available_pages) {
172 		printf("Staging area's size is reduced: %ld -> %ld!\n",
173 		    *nr_pages, available_pages);
174 		*nr_pages = available_pages;
175 	}
176 out:
177 	free(map);
178 }
179 #endif /* __i386__ || __amd64__ */
180 
181 #ifndef EFI_STAGING_SIZE
182 #if defined(__arm__)
183 #define	EFI_STAGING_SIZE	M(32)
184 #else
185 #define	EFI_STAGING_SIZE	M(64)
186 #endif
187 #endif
188 
189 #if defined(__aarch64__) || defined(__amd64__) || defined(__arm__) || \
190     defined(__riscv)
191 #define	EFI_STAGING_2M_ALIGN	1
192 #else
193 #define	EFI_STAGING_2M_ALIGN	0
194 #endif
195 
196 #if defined(__amd64__)
197 #define	EFI_STAGING_SLOP	M(8)
198 #else
199 #define	EFI_STAGING_SLOP	0
200 #endif
201 
202 static u_long staging_slop = EFI_STAGING_SLOP;
203 
204 EFI_PHYSICAL_ADDRESS	staging, staging_end, staging_base;
205 int			stage_offset_set = 0;
206 ssize_t			stage_offset;
207 
208 static void
209 efi_copy_free(void)
210 {
211 	BS->FreePages(staging_base, (staging_end - staging_base) /
212 	    EFI_PAGE_SIZE);
213 	stage_offset_set = 0;
214 	stage_offset = 0;
215 }
216 
217 #ifdef __amd64__
218 int copy_staging = COPY_STAGING_AUTO;
219 
220 static int
221 command_copy_staging(int argc, char *argv[])
222 {
223 	static const char *const mode[3] = {
224 		[COPY_STAGING_ENABLE] = "enable",
225 		[COPY_STAGING_DISABLE] = "disable",
226 		[COPY_STAGING_AUTO] = "auto",
227 	};
228 	int prev, res;
229 
230 	res = CMD_OK;
231 	if (argc > 2) {
232 		res = CMD_ERROR;
233 	} else if (argc == 2) {
234 		prev = copy_staging;
235 		if (strcmp(argv[1], "enable") == 0)
236 			copy_staging = COPY_STAGING_ENABLE;
237 		else if (strcmp(argv[1], "disable") == 0)
238 			copy_staging = COPY_STAGING_DISABLE;
239 		else if (strcmp(argv[1], "auto") == 0)
240 			copy_staging = COPY_STAGING_AUTO;
241 		else {
242 			printf("usage: copy_staging enable|disable|auto\n");
243 			res = CMD_ERROR;
244 		}
245 		if (res == CMD_OK && prev != copy_staging) {
246 			printf("changed copy_staging, unloading kernel\n");
247 			unload();
248 			efi_copy_free();
249 			efi_copy_init();
250 		}
251 	} else {
252 		printf("copy staging: %s\n", mode[copy_staging]);
253 	}
254 	return (res);
255 }
256 COMMAND_SET(copy_staging, "copy_staging", "copy staging", command_copy_staging);
257 #endif
258 
259 static int
260 command_staging_slop(int argc, char *argv[])
261 {
262 	char *endp;
263 	u_long new, prev;
264 	int res;
265 
266 	res = CMD_OK;
267 	if (argc > 2) {
268 		res = CMD_ERROR;
269 	} else if (argc == 2) {
270 		new = strtoul(argv[1], &endp, 0);
271 		if (*endp != '\0') {
272 			printf("invalid slop value\n");
273 			res = CMD_ERROR;
274 		}
275 		if (res == CMD_OK && staging_slop != new) {
276 			printf("changed slop, unloading kernel\n");
277 			unload();
278 			efi_copy_free();
279 			efi_copy_init();
280 		}
281 	} else {
282 		printf("staging slop %#lx\n", staging_slop);
283 	}
284 	return (res);
285 }
286 COMMAND_SET(staging_slop, "staging_slop", "set staging slop",
287     command_staging_slop);
288 
289 #if defined(__i386__) || defined(__amd64__)
290 /*
291  * The staging area must reside in the the first 1GB or 4GB physical
292  * memory: see elf64_exec() in
293  * boot/efi/loader/arch/amd64/elf64_freebsd.c.
294  */
295 static EFI_PHYSICAL_ADDRESS
296 get_staging_max(void)
297 {
298 	EFI_PHYSICAL_ADDRESS res;
299 
300 #if defined(__i386__)
301 	res = G(1);
302 #elif defined(__amd64__)
303 	res = copy_staging == COPY_STAGING_ENABLE ? G(1) : G(4);
304 #endif
305 	return (res);
306 }
307 #define	EFI_ALLOC_METHOD	AllocateMaxAddress
308 #else
309 #define	EFI_ALLOC_METHOD	AllocateAnyPages
310 #endif
311 
312 int
313 efi_copy_init(void)
314 {
315 	EFI_STATUS	status;
316 	unsigned long nr_pages;
317 
318 	nr_pages = EFI_SIZE_TO_PAGES((EFI_STAGING_SIZE));
319 
320 #if defined(__i386__) || defined(__amd64__)
321 	/*
322 	 * We'll decrease nr_pages, if it's too big. Currently we only
323 	 * apply this to FreeBSD VM running on Hyper-V. Why? Please see
324 	 * https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=211746#c28
325 	 */
326 	if (running_on_hyperv())
327 		efi_verify_staging_size(&nr_pages);
328 
329 	staging = get_staging_max();
330 #endif
331 	status = BS->AllocatePages(EFI_ALLOC_METHOD, EfiLoaderData,
332 	    nr_pages, &staging);
333 	if (EFI_ERROR(status)) {
334 		printf("failed to allocate staging area: %lu\n",
335 		    EFI_ERROR_CODE(status));
336 		return (status);
337 	}
338 	staging_base = staging;
339 	staging_end = staging + nr_pages * EFI_PAGE_SIZE;
340 
341 #if EFI_STAGING_2M_ALIGN
342 	/*
343 	 * Round the kernel load address to a 2MiB value. This is needed
344 	 * because the kernel builds a page table based on where it has
345 	 * been loaded in physical address space. As the kernel will use
346 	 * either a 1MiB or 2MiB page for this we need to make sure it
347 	 * is correctly aligned for both cases.
348 	 */
349 	staging = roundup2(staging, M(2));
350 #endif
351 
352 	return (0);
353 }
354 
355 static bool
356 efi_check_space(vm_offset_t end)
357 {
358 	EFI_PHYSICAL_ADDRESS addr, new_base, new_staging;
359 	EFI_STATUS status;
360 	unsigned long nr_pages;
361 
362 	end = roundup2(end, EFI_PAGE_SIZE);
363 
364 	/* There is already enough space */
365 	if (end + staging_slop <= staging_end)
366 		return (true);
367 
368 	if (boot_services_gone) {
369 		if (end <= staging_end)
370 			return (true);
371 		panic("efi_check_space: cannot expand staging area "
372 		    "after boot services were exited\n");
373 	}
374 
375 	/*
376 	 * Add slop at the end:
377 	 * 1. amd64 kernel expects to do some very early allocations
378 	 *    by carving out memory after kernend.  Slop guarantees
379 	 *    that it does not ovewrite anything useful.
380 	 * 2. It seems that initial calculation of the staging size
381 	 *    could be somewhat smaller than actually copying in after
382 	 *    boot services are exited.  Slop avoids calling
383 	 *    BS->AllocatePages() when it cannot work.
384 	 */
385 	end += staging_slop;
386 
387 	nr_pages = EFI_SIZE_TO_PAGES(end - staging_end);
388 #if defined(__i386__) || defined(__amd64__)
389 	/*
390 	 * i386 needs all memory to be allocated under the 1G boundary.
391 	 * amd64 needs all memory to be allocated under the 1G or 4G boundary.
392 	 */
393 	if (end > get_staging_max())
394 		goto before_staging;
395 #endif
396 
397 	/* Try to allocate more space after the previous allocation */
398 	addr = staging_end;
399 	status = BS->AllocatePages(AllocateAddress, EfiLoaderData, nr_pages,
400 	    &addr);
401 	if (!EFI_ERROR(status)) {
402 		staging_end = staging_end + nr_pages * EFI_PAGE_SIZE;
403 		return (true);
404 	}
405 
406 before_staging:
407 	/* Try allocating space before the previous allocation */
408 	if (staging < nr_pages * EFI_PAGE_SIZE)
409 		goto expand;
410 	addr = staging - nr_pages * EFI_PAGE_SIZE;
411 #if EFI_STAGING_2M_ALIGN
412 	/* See efi_copy_init for why this is needed */
413 	addr = rounddown2(addr, M(2));
414 #endif
415 	nr_pages = EFI_SIZE_TO_PAGES(staging_base - addr);
416 	status = BS->AllocatePages(AllocateAddress, EfiLoaderData, nr_pages,
417 	    &addr);
418 	if (!EFI_ERROR(status)) {
419 		/*
420 		 * Move the old allocation and update the state so
421 		 * translation still works.
422 		 */
423 		staging_base = addr;
424 		memmove((void *)(uintptr_t)staging_base,
425 		    (void *)(uintptr_t)staging, staging_end - staging);
426 		stage_offset -= staging - staging_base;
427 		staging = staging_base;
428 		return (true);
429 	}
430 
431 expand:
432 	nr_pages = EFI_SIZE_TO_PAGES(end - (vm_offset_t)staging);
433 #if EFI_STAGING_2M_ALIGN
434 	nr_pages += M(2) / EFI_PAGE_SIZE;
435 #endif
436 #if defined(__i386__) || defined(__amd64__)
437 	new_base = get_staging_max();
438 #endif
439 	status = BS->AllocatePages(EFI_ALLOC_METHOD, EfiLoaderData,
440 	    nr_pages, &new_base);
441 	if (!EFI_ERROR(status)) {
442 #if EFI_STAGING_2M_ALIGN
443 		new_staging = roundup2(new_base, M(2));
444 #else
445 		new_staging = new_base;
446 #endif
447 		/*
448 		 * Move the old allocation and update the state so
449 		 * translation still works.
450 		 */
451 		memcpy((void *)(uintptr_t)new_staging,
452 		    (void *)(uintptr_t)staging, staging_end - staging);
453 		BS->FreePages(staging_base, (staging_end - staging_base) /
454 		    EFI_PAGE_SIZE);
455 		stage_offset -= staging - new_staging;
456 		staging = new_staging;
457 		staging_end = new_base + nr_pages * EFI_PAGE_SIZE;
458 		staging_base = new_base;
459 		return (true);
460 	}
461 
462 	printf("efi_check_space: Unable to expand staging area\n");
463 	return (false);
464 }
465 
466 void *
467 efi_translate(vm_offset_t ptr)
468 {
469 
470 	return ((void *)(ptr + stage_offset));
471 }
472 
473 ssize_t
474 efi_copyin(const void *src, vm_offset_t dest, const size_t len)
475 {
476 
477 	if (!stage_offset_set) {
478 		stage_offset = (vm_offset_t)staging - dest;
479 		stage_offset_set = 1;
480 	}
481 
482 	/* XXX: Callers do not check for failure. */
483 	if (!efi_check_space(dest + stage_offset + len)) {
484 		errno = ENOMEM;
485 		return (-1);
486 	}
487 	bcopy(src, (void *)(dest + stage_offset), len);
488 	return (len);
489 }
490 
491 ssize_t
492 efi_copyout(const vm_offset_t src, void *dest, const size_t len)
493 {
494 
495 	/* XXX: Callers do not check for failure. */
496 	if (src + stage_offset + len > staging_end) {
497 		errno = ENOMEM;
498 		return (-1);
499 	}
500 	bcopy((void *)(src + stage_offset), dest, len);
501 	return (len);
502 }
503 
504 ssize_t
505 efi_readin(readin_handle_t fd, vm_offset_t dest, const size_t len)
506 {
507 
508 	if (!stage_offset_set) {
509 		stage_offset = (vm_offset_t)staging - dest;
510 		stage_offset_set = 1;
511 	}
512 
513 	if (!efi_check_space(dest + stage_offset + len)) {
514 		errno = ENOMEM;
515 		return (-1);
516 	}
517 	return (VECTX_READ(fd, (void *)(dest + stage_offset), len));
518 }
519 
520 void
521 efi_copy_finish(void)
522 {
523 	uint64_t	*src, *dst, *last;
524 
525 	src = (uint64_t *)(uintptr_t)staging;
526 	dst = (uint64_t *)(uintptr_t)(staging - stage_offset);
527 	last = (uint64_t *)(uintptr_t)staging_end;
528 
529 	while (src < last)
530 		*dst++ = *src++;
531 }
532 
533 void
534 efi_copy_finish_nop(void)
535 {
536 }
537