xref: /freebsd/sys/x86/xen/pv.c (revision 51015e6d0f570239b0c2088dc6cf2b018928375d)
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 ret;
351 
352 	ret = HYPERVISOR_platform_op(&op);
353 	if (ret != 0) {
354 		xc_printf("Failed to get dom0 video console info\n");
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 		    ((uint64_t)console->u.vesa_lfb.ext_lfb_base << 32);
386 		fb->efi.fb_size = console->u.vesa_lfb.lfb_size << 16;
387 		fb->efi.fb_height = console->u.vesa_lfb.height;
388 		fb->efi.fb_width = console->u.vesa_lfb.width;
389 		fb->efi.fb_stride = (console->u.vesa_lfb.bytes_per_line << 3) /
390 		    console->u.vesa_lfb.bits_per_pixel;
391 #define FBMASK(c) \
392     ((~0u << console->u.vesa_lfb.c ## _pos) & \
393     (~0u >> (32 - console->u.vesa_lfb.c ## _pos - \
394     console->u.vesa_lfb.c ## _size)))
395 		fb->efi.fb_mask_red = FBMASK(red);
396 		fb->efi.fb_mask_green = FBMASK(green);
397 		fb->efi.fb_mask_blue = FBMASK(blue);
398 		fb->efi.fb_mask_reserved = FBMASK(rsvd);
399 #undef FBMASK
400 		break;
401 
402 	default:
403 		xc_printf("Video console type unsupported\n");
404 		return;
405 	}
406 }
407 
408 static caddr_t
409 xen_pvh_parse_preload_data(uint64_t modulep)
410 {
411 	caddr_t kmdp;
412 	vm_ooffset_t off;
413 	vm_paddr_t metadata;
414 	char *envp;
415 	char acpi_rsdp[19];
416 
417 	if (start_info->modlist_paddr != 0) {
418 		struct hvm_modlist_entry *mod;
419 		const char *cmdline;
420 
421 		mod = (struct hvm_modlist_entry *)
422 		    (start_info->modlist_paddr + KERNBASE);
423 		cmdline = mod[0].cmdline_paddr ?
424 		    (const char *)(mod[0].cmdline_paddr + KERNBASE) : NULL;
425 
426 		if (strcmp(cmdline, "header") == 0) {
427 			struct xen_header *header;
428 
429 			header = (struct xen_header *)(mod[0].paddr + KERNBASE);
430 
431 			if ((header->flags & XENHEADER_HAS_MODULEP_OFFSET) !=
432 			    XENHEADER_HAS_MODULEP_OFFSET) {
433 				xc_printf("Unable to load module metadata\n");
434 				HYPERVISOR_shutdown(SHUTDOWN_crash);
435 			}
436 
437 			preload_metadata = (caddr_t)(mod[0].paddr +
438 			    header->modulep_offset + KERNBASE);
439 
440 			kmdp = preload_search_by_type("elf kernel");
441 			if (kmdp == NULL)
442 				kmdp = preload_search_by_type("elf64 kernel");
443 			if (kmdp == NULL) {
444 				xc_printf("Unable to find kernel\n");
445 				HYPERVISOR_shutdown(SHUTDOWN_crash);
446 			}
447 
448 			/*
449 			 * Xen has relocated the metadata and the modules, so
450 			 * we need to recalculate it's position. This is done
451 			 * by saving the original modulep address and then
452 			 * calculating the offset from the real modulep
453 			 * position.
454 			 */
455 			metadata = MD_FETCH(kmdp, MODINFOMD_MODULEP,
456 			    vm_paddr_t);
457 			off = mod[0].paddr + header->modulep_offset - metadata +
458 			    KERNBASE;
459 		} else {
460 			preload_metadata = (caddr_t)(mod[0].paddr + KERNBASE);
461 
462 			kmdp = preload_search_by_type("elf kernel");
463 			if (kmdp == NULL)
464 				kmdp = preload_search_by_type("elf64 kernel");
465 			if (kmdp == NULL) {
466 				xc_printf("Unable to find kernel\n");
467 				HYPERVISOR_shutdown(SHUTDOWN_crash);
468 			}
469 
470 			metadata = MD_FETCH(kmdp, MODINFOMD_MODULEP, vm_paddr_t);
471 			off = mod[0].paddr + KERNBASE - metadata;
472 		}
473 
474 		preload_bootstrap_relocate(off);
475 
476 		boothowto = MD_FETCH(kmdp, MODINFOMD_HOWTO, int);
477 		envp = MD_FETCH(kmdp, MODINFOMD_ENVP, char *);
478 		if (envp != NULL)
479 			envp += off;
480 		xen_pvh_set_env(envp, reject_option);
481 
482 		if (MD_FETCH(kmdp, MODINFOMD_EFI_MAP, void *) != NULL)
483 		    strlcpy(bootmethod, "UEFI", sizeof(bootmethod));
484 		else
485 		    strlcpy(bootmethod, "BIOS", sizeof(bootmethod));
486 
487 		fixup_console(kmdp);
488 	} else {
489 		/* Parse the extra boot information given by Xen */
490 		if (start_info->cmdline_paddr != 0)
491 			boot_parse_cmdline_delim(
492 			    (char *)(start_info->cmdline_paddr + KERNBASE),
493 			    ", \t\n");
494 		kmdp = NULL;
495 		strlcpy(bootmethod, "PVH", sizeof(bootmethod));
496 	}
497 
498 	boothowto |= boot_env_to_howto();
499 
500 	snprintf(acpi_rsdp, sizeof(acpi_rsdp), "%#" PRIx64,
501 	    start_info->rsdp_paddr);
502 	kern_setenv("acpi.rsdp", acpi_rsdp);
503 
504 #ifdef DDB
505 	xen_pvh_parse_symtab();
506 #endif
507 	return (kmdp);
508 }
509 
510 static void
511 pvh_parse_memmap_start_info(caddr_t kmdp, vm_paddr_t *physmap,
512     int *physmap_idx)
513 {
514 	const struct hvm_memmap_table_entry * entries;
515 	size_t nentries;
516 	size_t i;
517 
518 	/* Extract from HVM start_info. */
519 	entries = (struct hvm_memmap_table_entry *)(start_info->memmap_paddr + KERNBASE);
520 	nentries = start_info->memmap_entries;
521 
522 	/* Convert into E820 format and handle one by one. */
523 	for (i = 0; i < nentries; i++) {
524 		struct bios_smap entry;
525 
526 		entry.base = entries[i].addr;
527 		entry.length = entries[i].size;
528 
529 		/*
530 		 * Luckily for us, the XEN_HVM_MEMMAP_TYPE_* values exactly
531 		 * match the SMAP_TYPE_* values so we don't need to translate
532 		 * anything here.
533 		 */
534 		entry.type = entries[i].type;
535 
536 		bios_add_smap_entries(&entry, 1, physmap, physmap_idx);
537 	}
538 }
539 
540 static void
541 xen_pvh_parse_memmap(caddr_t kmdp, vm_paddr_t *physmap, int *physmap_idx)
542 {
543 	struct xen_memory_map memmap;
544 	u_int32_t size;
545 	int rc;
546 
547 	/* We should only reach here if we're running under Xen. */
548 	KASSERT(isxen(), ("xen_pvh_parse_memmap reached when !Xen"));
549 
550 	/* Fetch the E820 map from Xen */
551 	memmap.nr_entries = MAX_E820_ENTRIES;
552 	set_xen_guest_handle(memmap.buffer, xen_smap);
553 	rc = HYPERVISOR_memory_op(XENMEM_memory_map, &memmap);
554 	if (rc) {
555 		xc_printf("ERROR: unable to fetch Xen E820 memory map: %d\n",
556 		    rc);
557 		HYPERVISOR_shutdown(SHUTDOWN_crash);
558 	}
559 
560 	size = memmap.nr_entries * sizeof(xen_smap[0]);
561 
562 	bios_add_smap_entries(xen_smap, size, physmap, physmap_idx);
563 }
564 
565 static void
566 pvh_parse_memmap(caddr_t kmdp, vm_paddr_t *physmap, int *physmap_idx)
567 {
568 
569 	/*
570 	 * If version >= 1 and memmap_paddr != 0, use the memory map provided
571 	 * in the start_info structure; if not, we're running under legacy
572 	 * Xen and need to use the Xen hypercall.
573 	 */
574 	if ((start_info->version >= 1) && (start_info->memmap_paddr != 0))
575 		pvh_parse_memmap_start_info(kmdp, physmap, physmap_idx);
576 	else
577 		xen_pvh_parse_memmap(kmdp, physmap, physmap_idx);
578 }
579