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