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