xref: /freebsd/sys/x86/xen/pv.c (revision 73ae25c174b515616050496dea764a943796efef)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-NetBSD
3  *
4  * Copyright (c) 2004 Christian Limpach.
5  * Copyright (c) 2004-2006,2008 Kip Macy
6  * Copyright (c) 2008 The NetBSD Foundation, Inc.
7  * Copyright (c) 2013 Roger Pau Monné <roger.pau@citrix.com>
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34 
35 #include "opt_ddb.h"
36 #include "opt_kstack_pages.h"
37 
38 #include <sys/param.h>
39 #include <sys/bus.h>
40 #include <sys/kernel.h>
41 #include <sys/reboot.h>
42 #include <sys/systm.h>
43 #include <sys/malloc.h>
44 #include <sys/linker.h>
45 #include <sys/lock.h>
46 #include <sys/rwlock.h>
47 #include <sys/boot.h>
48 #include <sys/ctype.h>
49 #include <sys/mutex.h>
50 #include <sys/smp.h>
51 #include <sys/efi.h>
52 
53 #include <vm/vm.h>
54 #include <vm/vm_extern.h>
55 #include <vm/vm_kern.h>
56 #include <vm/vm_page.h>
57 #include <vm/vm_map.h>
58 #include <vm/vm_object.h>
59 #include <vm/vm_pager.h>
60 #include <vm/vm_param.h>
61 
62 #include <machine/_inttypes.h>
63 #include <machine/intr_machdep.h>
64 #include <x86/apicvar.h>
65 #include <x86/init.h>
66 #include <machine/pc/bios.h>
67 #include <machine/smp.h>
68 #include <machine/intr_machdep.h>
69 #include <machine/md_var.h>
70 #include <machine/metadata.h>
71 #include <machine/cpu.h>
72 
73 #include <xen/xen-os.h>
74 #include <xen/hvm.h>
75 #include <xen/hypervisor.h>
76 #include <xen/xenstore/xenstorevar.h>
77 #include <xen/xen_pv.h>
78 
79 #include <contrib/xen/arch-x86/cpuid.h>
80 #include <contrib/xen/arch-x86/hvm/start_info.h>
81 #include <contrib/xen/vcpu.h>
82 
83 #include <dev/xen/timer/timer.h>
84 
85 #ifdef DDB
86 #include <ddb/ddb.h>
87 #endif
88 
89 /* Native initial function */
90 extern u_int64_t hammer_time(u_int64_t, u_int64_t);
91 /* Xen initial function */
92 uint64_t hammer_time_xen(vm_paddr_t);
93 
94 #define MAX_E820_ENTRIES	128
95 
96 /*--------------------------- Forward Declarations ---------------------------*/
97 static caddr_t xen_pvh_parse_preload_data(uint64_t);
98 static void pvh_parse_memmap(caddr_t, vm_paddr_t *, int *);
99 
100 /*---------------------------- Extern Declarations ---------------------------*/
101 /*
102  * Placed by the linker at the end of the bss section, which is the last
103  * section loaded by Xen before loading the symtab and strtab.
104  */
105 extern uint32_t end;
106 
107 /*-------------------------------- Global Data -------------------------------*/
108 struct init_ops xen_pvh_init_ops = {
109 	.parse_preload_data		= xen_pvh_parse_preload_data,
110 	.early_clock_source_init	= xen_clock_init,
111 	.early_delay			= xen_delay,
112 	.parse_memmap			= pvh_parse_memmap,
113 };
114 
115 static struct bios_smap xen_smap[MAX_E820_ENTRIES];
116 
117 static struct hvm_start_info *start_info;
118 
119 /*-------------------------------- Xen PV init -------------------------------*/
120 
121 static int
122 isxen(void)
123 {
124 	static int xen = -1;
125 	uint32_t base;
126 	u_int regs[4];
127 
128 	if (xen != -1)
129 		return (xen);
130 
131 	/*
132 	 * The full code for identifying which hypervisor we're running under
133 	 * is in sys/x86/x86/identcpu.c and runs later in the boot process;
134 	 * this is sufficient to distinguish Xen PVH booting from non-Xen PVH
135 	 * and skip some very early Xen-specific code in the non-Xen case.
136 	 */
137 	xen = 0;
138 	for (base = 0x40000000; base < 0x40010000; base += 0x100) {
139 		do_cpuid(base, regs);
140 		if (regs[1] == XEN_CPUID_SIGNATURE_EBX &&
141 		    regs[2] == XEN_CPUID_SIGNATURE_ECX &&
142 		    regs[3] == XEN_CPUID_SIGNATURE_EDX) {
143 			xen = 1;
144 			break;
145 		}
146 	}
147 	return (xen);
148 }
149 
150 #define CRASH(...) do {					\
151 	if (isxen()) {					\
152 		xc_printf(__VA_ARGS__);			\
153 		HYPERVISOR_shutdown(SHUTDOWN_crash);	\
154 	} else {					\
155 		halt();					\
156 	}						\
157 } while (0)
158 
159 uint64_t
160 hammer_time_xen(vm_paddr_t start_info_paddr)
161 {
162 	struct hvm_modlist_entry *mod;
163 	struct xen_add_to_physmap xatp;
164 	uint64_t physfree;
165 	char *kenv;
166 	int rc;
167 
168 	if (isxen()) {
169 		xen_domain_type = XEN_HVM_DOMAIN;
170 		vm_guest = VM_GUEST_XEN;
171 		rc = xen_hvm_init_hypercall_stubs(XEN_HVM_INIT_EARLY);
172 		if (rc) {
173 			xc_printf("ERROR: failed to initialize hypercall page: %d\n",
174 			    rc);
175 			HYPERVISOR_shutdown(SHUTDOWN_crash);
176 		}
177 	}
178 
179 	start_info = (struct hvm_start_info *)(start_info_paddr + KERNBASE);
180 	if (start_info->magic != XEN_HVM_START_MAGIC_VALUE) {
181 		CRASH("Unknown magic value in start_info struct: %#x\n",
182 		    start_info->magic);
183 	}
184 
185 	/*
186 	 * Select the higher address to use as physfree: either after
187 	 * start_info, after the kernel, after the memory map or after any of
188 	 * the modules.  We assume enough memory to be available after the
189 	 * selected address for the needs of very early memory allocations.
190 	 */
191 	physfree = roundup2(start_info_paddr + sizeof(struct hvm_start_info),
192 	    PAGE_SIZE);
193 	physfree = MAX(roundup2((vm_paddr_t)_end - KERNBASE, PAGE_SIZE),
194 	    physfree);
195 
196 	if (start_info->memmap_paddr != 0)
197 		physfree = MAX(roundup2(start_info->memmap_paddr +
198 		    start_info->memmap_entries *
199 		    sizeof(struct hvm_memmap_table_entry), PAGE_SIZE),
200 		    physfree);
201 
202 	if (start_info->modlist_paddr != 0) {
203 		unsigned int i;
204 
205 		if (start_info->nr_modules == 0) {
206 			CRASH(
207 			    "ERROR: modlist_paddr != 0 but nr_modules == 0\n");
208 		}
209 		mod = (struct hvm_modlist_entry *)
210 		    (start_info->modlist_paddr + KERNBASE);
211 		for (i = 0; i < start_info->nr_modules; i++)
212 			physfree = MAX(roundup2(mod[i].paddr + mod[i].size,
213 			    PAGE_SIZE), physfree);
214 	}
215 
216 	if (isxen()) {
217 		xatp.domid = DOMID_SELF;
218 		xatp.idx = 0;
219 		xatp.space = XENMAPSPACE_shared_info;
220 		xatp.gpfn = atop(physfree);
221 		if (HYPERVISOR_memory_op(XENMEM_add_to_physmap, &xatp)) {
222 			xc_printf("ERROR: failed to setup shared_info page\n");
223 			HYPERVISOR_shutdown(SHUTDOWN_crash);
224 		}
225 		HYPERVISOR_shared_info = (shared_info_t *)(physfree + KERNBASE);
226 		physfree += PAGE_SIZE;
227 	}
228 
229 	/*
230 	 * Init a static kenv using a free page. The contents will be filled
231 	 * from the parse_preload_data hook.
232 	 */
233 	kenv = (void *)(physfree + KERNBASE);
234 	physfree += PAGE_SIZE;
235 	bzero_early(kenv, PAGE_SIZE);
236 	init_static_kenv(kenv, PAGE_SIZE);
237 
238 	/* Set the hooks for early functions that diverge from bare metal */
239 	init_ops = xen_pvh_init_ops;
240 	hvm_start_flags = start_info->flags;
241 
242 	/* Now we can jump into the native init function */
243 	return (hammer_time(0, physfree));
244 }
245 
246 /*-------------------------------- PV specific -------------------------------*/
247 
248 /*
249  * When booted as a PVH guest FreeBSD needs to avoid using the RSDP address
250  * hint provided by the loader because it points to the native set of ACPI
251  * tables instead of the ones crafted by Xen. The acpi.rsdp env variable is
252  * removed from kenv if present, and a new acpi.rsdp is added to kenv that
253  * points to the address of the Xen crafted RSDP.
254  */
255 static bool reject_option(const char *option)
256 {
257 	static const char *reject[] = {
258 		"acpi.rsdp",
259 	};
260 	unsigned int i;
261 
262 	for (i = 0; i < nitems(reject); i++)
263 		if (strncmp(option, reject[i], strlen(reject[i])) == 0)
264 			return (true);
265 
266 	return (false);
267 }
268 
269 static void
270 xen_pvh_set_env(char *env, bool (*filter)(const char *))
271 {
272 	char *option;
273 
274 	if (env == NULL)
275 		return;
276 
277 	option = env;
278 	while (*option != 0) {
279 		char *value;
280 
281 		if (filter != NULL && filter(option)) {
282 			option += strlen(option) + 1;
283 			continue;
284 		}
285 
286 		value = option;
287 		option = strsep(&value, "=");
288 		if (kern_setenv(option, value) != 0 && isxen())
289 			xc_printf("unable to add kenv %s=%s\n", option, value);
290 		option = value + strlen(value) + 1;
291 	}
292 }
293 
294 #ifdef DDB
295 /*
296  * The way Xen loads the symtab is different from the native boot loader,
297  * because it's tailored for NetBSD. So we have to adapt and use the same
298  * method as NetBSD. Portions of the code below have been picked from NetBSD:
299  * sys/kern/kern_ksyms.c CVS Revision 1.71.
300  */
301 static void
302 xen_pvh_parse_symtab(void)
303 {
304 	Elf_Ehdr *ehdr;
305 	Elf_Shdr *shdr;
306 	int i, j;
307 
308 	ehdr = (Elf_Ehdr *)(&end + 1);
309 	if (memcmp(ehdr->e_ident, ELFMAG, SELFMAG) ||
310 	    ehdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||
311 	    ehdr->e_version > 1) {
312 		if (isxen())
313 			xc_printf("Unable to load ELF symtab: invalid symbol table\n");
314 		return;
315 	}
316 
317 	shdr = (Elf_Shdr *)((uint8_t *)ehdr + ehdr->e_shoff);
318 	/* Find the symbol table and the corresponding string table. */
319 	for (i = 1; i < ehdr->e_shnum; i++) {
320 		if (shdr[i].sh_type != SHT_SYMTAB)
321 			continue;
322 		if (shdr[i].sh_offset == 0)
323 			continue;
324 		ksymtab = (uintptr_t)((uint8_t *)ehdr + shdr[i].sh_offset);
325 		ksymtab_size = shdr[i].sh_size;
326 		j = shdr[i].sh_link;
327 		if (shdr[j].sh_offset == 0)
328 			continue; /* Can this happen? */
329 		kstrtab = (uintptr_t)((uint8_t *)ehdr + shdr[j].sh_offset);
330 		break;
331 	}
332 
333 	if ((ksymtab == 0 || kstrtab == 0) && isxen())
334 		xc_printf(
335     "Unable to load ELF symtab: could not find symtab or strtab\n");
336 }
337 #endif
338 
339 static void
340 fixup_console(caddr_t kmdp)
341 {
342 	struct xen_platform_op op = {
343 		.cmd = XENPF_get_dom0_console,
344 	};
345 	xenpf_dom0_console_t *console = &op.u.dom0_console;
346 	union {
347 		struct efi_fb efi;
348 		struct vbe_fb vbe;
349 	} *fb = NULL;
350 	int size;
351 
352 	size = HYPERVISOR_platform_op(&op);
353 	if (size < 0) {
354 		xc_printf("Failed to get dom0 video console info: %d\n", size);
355 		return;
356 	}
357 
358 	switch (console->video_type) {
359 	case XEN_VGATYPE_VESA_LFB:
360 		fb = (__typeof__ (fb))preload_search_info(kmdp,
361 		    MODINFO_METADATA | MODINFOMD_VBE_FB);
362 
363 		if (fb == NULL) {
364 			xc_printf("No VBE FB in kernel metadata\n");
365 			return;
366 		}
367 
368 		_Static_assert(offsetof(struct vbe_fb, fb_bpp) ==
369 		    offsetof(struct efi_fb, fb_mask_reserved) +
370 		    sizeof(fb->efi.fb_mask_reserved),
371 		    "Bad structure overlay\n");
372 		fb->vbe.fb_bpp = console->u.vesa_lfb.bits_per_pixel;
373 		/* FALLTHROUGH */
374 	case XEN_VGATYPE_EFI_LFB:
375 		if (fb == NULL) {
376 			fb = (__typeof__ (fb))preload_search_info(kmdp,
377 			    MODINFO_METADATA | MODINFOMD_EFI_FB);
378 			if (fb == NULL) {
379 				xc_printf("No EFI FB in kernel metadata\n");
380 				return;
381 			}
382 		}
383 
384 		fb->efi.fb_addr = console->u.vesa_lfb.lfb_base;
385 		if (size >
386 		    offsetof(xenpf_dom0_console_t, u.vesa_lfb.ext_lfb_base))
387 			fb->efi.fb_addr |=
388 			    (uint64_t)console->u.vesa_lfb.ext_lfb_base << 32;
389 		fb->efi.fb_size = console->u.vesa_lfb.lfb_size << 16;
390 		fb->efi.fb_height = console->u.vesa_lfb.height;
391 		fb->efi.fb_width = console->u.vesa_lfb.width;
392 		fb->efi.fb_stride = (console->u.vesa_lfb.bytes_per_line << 3) /
393 		    console->u.vesa_lfb.bits_per_pixel;
394 #define FBMASK(c) \
395     ((~0u << console->u.vesa_lfb.c ## _pos) & \
396     (~0u >> (32 - console->u.vesa_lfb.c ## _pos - \
397     console->u.vesa_lfb.c ## _size)))
398 		fb->efi.fb_mask_red = FBMASK(red);
399 		fb->efi.fb_mask_green = FBMASK(green);
400 		fb->efi.fb_mask_blue = FBMASK(blue);
401 		fb->efi.fb_mask_reserved = FBMASK(rsvd);
402 #undef FBMASK
403 		break;
404 
405 	default:
406 		xc_printf("Video console type unsupported\n");
407 		return;
408 	}
409 }
410 
411 static caddr_t
412 xen_pvh_parse_preload_data(uint64_t modulep)
413 {
414 	caddr_t kmdp;
415 	vm_ooffset_t off;
416 	vm_paddr_t metadata;
417 	char *envp;
418 	char acpi_rsdp[19];
419 
420 	if (start_info->modlist_paddr != 0) {
421 		struct hvm_modlist_entry *mod;
422 		const char *cmdline;
423 
424 		mod = (struct hvm_modlist_entry *)
425 		    (start_info->modlist_paddr + KERNBASE);
426 		cmdline = mod[0].cmdline_paddr ?
427 		    (const char *)(mod[0].cmdline_paddr + KERNBASE) : NULL;
428 
429 		if (strcmp(cmdline, "header") == 0) {
430 			struct xen_header *header;
431 
432 			header = (struct xen_header *)(mod[0].paddr + KERNBASE);
433 
434 			if ((header->flags & XENHEADER_HAS_MODULEP_OFFSET) !=
435 			    XENHEADER_HAS_MODULEP_OFFSET) {
436 				xc_printf("Unable to load module metadata\n");
437 				HYPERVISOR_shutdown(SHUTDOWN_crash);
438 			}
439 
440 			preload_metadata = (caddr_t)(mod[0].paddr +
441 			    header->modulep_offset + KERNBASE);
442 
443 			kmdp = preload_search_by_type("elf kernel");
444 			if (kmdp == NULL)
445 				kmdp = preload_search_by_type("elf64 kernel");
446 			if (kmdp == NULL) {
447 				xc_printf("Unable to find kernel\n");
448 				HYPERVISOR_shutdown(SHUTDOWN_crash);
449 			}
450 
451 			/*
452 			 * Xen has relocated the metadata and the modules, so
453 			 * we need to recalculate it's position. This is done
454 			 * by saving the original modulep address and then
455 			 * calculating the offset from the real modulep
456 			 * position.
457 			 */
458 			metadata = MD_FETCH(kmdp, MODINFOMD_MODULEP,
459 			    vm_paddr_t);
460 			off = mod[0].paddr + header->modulep_offset - metadata +
461 			    KERNBASE;
462 		} else {
463 			preload_metadata = (caddr_t)(mod[0].paddr + KERNBASE);
464 
465 			kmdp = preload_search_by_type("elf kernel");
466 			if (kmdp == NULL)
467 				kmdp = preload_search_by_type("elf64 kernel");
468 			if (kmdp == NULL) {
469 				xc_printf("Unable to find kernel\n");
470 				HYPERVISOR_shutdown(SHUTDOWN_crash);
471 			}
472 
473 			metadata = MD_FETCH(kmdp, MODINFOMD_MODULEP, vm_paddr_t);
474 			off = mod[0].paddr + KERNBASE - metadata;
475 		}
476 
477 		preload_bootstrap_relocate(off);
478 
479 		boothowto = MD_FETCH(kmdp, MODINFOMD_HOWTO, int);
480 		envp = MD_FETCH(kmdp, MODINFOMD_ENVP, char *);
481 		if (envp != NULL)
482 			envp += off;
483 		xen_pvh_set_env(envp, reject_option);
484 
485 		if (MD_FETCH(kmdp, MODINFOMD_EFI_MAP, void *) != NULL)
486 		    strlcpy(bootmethod, "UEFI", sizeof(bootmethod));
487 		else
488 		    strlcpy(bootmethod, "BIOS", sizeof(bootmethod));
489 
490 		fixup_console(kmdp);
491 	} else {
492 		/* Parse the extra boot information given by Xen */
493 		if (start_info->cmdline_paddr != 0)
494 			boot_parse_cmdline_delim(
495 			    (char *)(start_info->cmdline_paddr + KERNBASE),
496 			    ", \t\n");
497 		kmdp = NULL;
498 		strlcpy(bootmethod, "PVH", sizeof(bootmethod));
499 	}
500 
501 	boothowto |= boot_env_to_howto();
502 
503 	snprintf(acpi_rsdp, sizeof(acpi_rsdp), "%#" PRIx64,
504 	    start_info->rsdp_paddr);
505 	kern_setenv("acpi.rsdp", acpi_rsdp);
506 
507 #ifdef DDB
508 	xen_pvh_parse_symtab();
509 #endif
510 	return (kmdp);
511 }
512 
513 static void
514 pvh_parse_memmap_start_info(caddr_t kmdp, vm_paddr_t *physmap,
515     int *physmap_idx)
516 {
517 	const struct hvm_memmap_table_entry * entries;
518 	size_t nentries;
519 	size_t i;
520 
521 	/* Extract from HVM start_info. */
522 	entries = (struct hvm_memmap_table_entry *)(start_info->memmap_paddr + KERNBASE);
523 	nentries = start_info->memmap_entries;
524 
525 	/* Convert into E820 format and handle one by one. */
526 	for (i = 0; i < nentries; i++) {
527 		struct bios_smap entry;
528 
529 		entry.base = entries[i].addr;
530 		entry.length = entries[i].size;
531 
532 		/*
533 		 * Luckily for us, the XEN_HVM_MEMMAP_TYPE_* values exactly
534 		 * match the SMAP_TYPE_* values so we don't need to translate
535 		 * anything here.
536 		 */
537 		entry.type = entries[i].type;
538 
539 		bios_add_smap_entries(&entry, 1, physmap, physmap_idx);
540 	}
541 }
542 
543 static void
544 xen_pvh_parse_memmap(caddr_t kmdp, vm_paddr_t *physmap, int *physmap_idx)
545 {
546 	struct xen_memory_map memmap;
547 	u_int32_t size;
548 	int rc;
549 
550 	/* We should only reach here if we're running under Xen. */
551 	KASSERT(isxen(), ("xen_pvh_parse_memmap reached when !Xen"));
552 
553 	/* Fetch the E820 map from Xen */
554 	memmap.nr_entries = MAX_E820_ENTRIES;
555 	set_xen_guest_handle(memmap.buffer, xen_smap);
556 	rc = HYPERVISOR_memory_op(XENMEM_memory_map, &memmap);
557 	if (rc) {
558 		xc_printf("ERROR: unable to fetch Xen E820 memory map: %d\n",
559 		    rc);
560 		HYPERVISOR_shutdown(SHUTDOWN_crash);
561 	}
562 
563 	size = memmap.nr_entries * sizeof(xen_smap[0]);
564 
565 	bios_add_smap_entries(xen_smap, size, physmap, physmap_idx);
566 }
567 
568 static void
569 pvh_parse_memmap(caddr_t kmdp, vm_paddr_t *physmap, int *physmap_idx)
570 {
571 
572 	/*
573 	 * If version >= 1 and memmap_paddr != 0, use the memory map provided
574 	 * in the start_info structure; if not, we're running under legacy
575 	 * Xen and need to use the Xen hypercall.
576 	 */
577 	if ((start_info->version >= 1) && (start_info->memmap_paddr != 0))
578 		pvh_parse_memmap_start_info(kmdp, physmap, physmap_idx);
579 	else
580 		xen_pvh_parse_memmap(kmdp, physmap, physmap_idx);
581 }
582