xref: /freebsd/sys/x86/xen/hvm.c (revision a466cc55373fc3cf86837f09da729535b57e69a1)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2008, 2013 Citrix Systems, Inc.
5  * Copyright (c) 2012 Spectra Logic Corporation
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 #include <sys/param.h>
34 #include <sys/bus.h>
35 #include <sys/kernel.h>
36 #include <sys/malloc.h>
37 #include <sys/proc.h>
38 #include <sys/smp.h>
39 #include <sys/systm.h>
40 
41 #include <vm/vm.h>
42 #include <vm/pmap.h>
43 #include <vm/vm_param.h>
44 
45 #include <dev/pci/pcivar.h>
46 
47 #include <machine/cpufunc.h>
48 #include <machine/cpu.h>
49 #include <machine/smp.h>
50 
51 #include <x86/apicreg.h>
52 
53 #include <xen/xen-os.h>
54 #include <xen/error.h>
55 #include <xen/features.h>
56 #include <xen/gnttab.h>
57 #include <xen/hypervisor.h>
58 #include <xen/hvm.h>
59 #include <xen/xen_intr.h>
60 
61 #include <contrib/xen/arch-x86/cpuid.h>
62 #include <contrib/xen/hvm/params.h>
63 #include <contrib/xen/vcpu.h>
64 
65 /*--------------------------- Forward Declarations ---------------------------*/
66 static void xen_hvm_cpu_init(void);
67 
68 /*-------------------------------- Global Data -------------------------------*/
69 #ifdef SMP
70 struct cpu_ops xen_hvm_cpu_ops = {
71 	.cpu_init	= xen_hvm_cpu_init,
72 	.cpu_resume	= xen_hvm_cpu_init
73 };
74 #endif
75 
76 static MALLOC_DEFINE(M_XENHVM, "xen_hvm", "Xen HVM PV Support");
77 
78 /**
79  * If non-zero, the hypervisor has been configured to use a direct
80  * IDT event callback for interrupt injection.
81  */
82 int xen_vector_callback_enabled;
83 
84 /**
85  * Signal whether the vector injected for the event channel upcall requires to
86  * be EOI'ed on the local APIC.
87  */
88 bool xen_evtchn_needs_ack;
89 
90 /*------------------------------- Per-CPU Data -------------------------------*/
91 DPCPU_DEFINE(struct vcpu_info, vcpu_local_info);
92 DPCPU_DEFINE(struct vcpu_info *, vcpu_info);
93 
94 /*------------------------------ Sysctl tunables -----------------------------*/
95 int xen_disable_pv_disks = 0;
96 int xen_disable_pv_nics = 0;
97 TUNABLE_INT("hw.xen.disable_pv_disks", &xen_disable_pv_disks);
98 TUNABLE_INT("hw.xen.disable_pv_nics", &xen_disable_pv_nics);
99 
100 /*---------------------- XEN Hypervisor Probe and Setup ----------------------*/
101 
102 uint32_t xen_cpuid_base;
103 
104 static uint32_t
105 xen_hvm_cpuid_base(void)
106 {
107 	uint32_t base, regs[4];
108 
109 	for (base = 0x40000000; base < 0x40010000; base += 0x100) {
110 		do_cpuid(base, regs);
111 		if (!memcmp("XenVMMXenVMM", &regs[1], 12)
112 		    && (regs[0] - base) >= 2)
113 			return (base);
114 	}
115 	return (0);
116 }
117 
118 static void
119 hypervisor_quirks(unsigned int major, unsigned int minor)
120 {
121 #ifdef SMP
122 	if (((major < 4) || (major == 4 && minor <= 5)) &&
123 	    msix_disable_migration == -1) {
124 		/*
125 		 * Xen hypervisors prior to 4.6.0 do not properly
126 		 * handle updates to enabled MSI-X table entries,
127 		 * so disable MSI-X interrupt migration in that
128 		 * case.
129 		 */
130 		if (bootverbose)
131 			printf(
132 "Disabling MSI-X interrupt migration due to Xen hypervisor bug.\n"
133 "Set machdep.msix_disable_migration=0 to forcefully enable it.\n");
134 		msix_disable_migration = 1;
135 	}
136 #endif
137 }
138 
139 static void
140 hypervisor_version(void)
141 {
142 	uint32_t regs[4];
143 	int major, minor;
144 
145 	do_cpuid(xen_cpuid_base + 1, regs);
146 
147 	major = regs[0] >> 16;
148 	minor = regs[0] & 0xffff;
149 	printf("XEN: Hypervisor version %d.%d detected.\n", major, minor);
150 
151 	hypervisor_quirks(major, minor);
152 }
153 
154 /*
155  * Allocate and fill in the hypcall page.
156  */
157 int
158 xen_hvm_init_hypercall_stubs(enum xen_hvm_init_type init_type)
159 {
160 	uint32_t regs[4];
161 
162 	/* Legacy PVH will get here without the cpuid leaf being set. */
163 	if (xen_cpuid_base == 0)
164 		xen_cpuid_base = xen_hvm_cpuid_base();
165 	if (xen_cpuid_base == 0)
166 		return (ENXIO);
167 
168 	if (xen_domain() && init_type == XEN_HVM_INIT_LATE) {
169 		/*
170 		 * If the domain type is already set we can assume that the
171 		 * hypercall page has been populated too, so just print the
172 		 * version (and apply any quirks) and exit.
173 		 */
174 		hypervisor_version();
175 		return 0;
176 	}
177 
178 	if (init_type == XEN_HVM_INIT_LATE)
179 		hypervisor_version();
180 
181 	/*
182 	 * Find the hypercall pages.
183 	 */
184 	do_cpuid(xen_cpuid_base + 2, regs);
185 	if (regs[0] != 1)
186 		return (EINVAL);
187 
188 	wrmsr(regs[1], (init_type == XEN_HVM_INIT_EARLY)
189 	    ? (vm_paddr_t)((uintptr_t)&hypercall_page - KERNBASE)
190 	    : vtophys(&hypercall_page));
191 
192 	return (0);
193 }
194 
195 static void
196 xen_hvm_init_shared_info_page(void)
197 {
198 	struct xen_add_to_physmap xatp;
199 
200 	if (xen_pv_domain()) {
201 		/*
202 		 * Already setup in the PV case, shared_info is passed inside
203 		 * of the start_info struct at start of day.
204 		 */
205 		return;
206 	}
207 
208 	if (HYPERVISOR_shared_info == NULL) {
209 		HYPERVISOR_shared_info = malloc(PAGE_SIZE, M_XENHVM, M_NOWAIT);
210 		if (HYPERVISOR_shared_info == NULL)
211 			panic("Unable to allocate Xen shared info page");
212 	}
213 
214 	xatp.domid = DOMID_SELF;
215 	xatp.idx = 0;
216 	xatp.space = XENMAPSPACE_shared_info;
217 	xatp.gpfn = vtophys(HYPERVISOR_shared_info) >> PAGE_SHIFT;
218 	if (HYPERVISOR_memory_op(XENMEM_add_to_physmap, &xatp))
219 		panic("HYPERVISOR_memory_op failed");
220 }
221 
222 static int
223 set_percpu_callback(unsigned int vcpu)
224 {
225 	struct xen_hvm_evtchn_upcall_vector vec;
226 	int error;
227 
228 	vec.vcpu = vcpu;
229 	vec.vector = IDT_EVTCHN;
230 	error = HYPERVISOR_hvm_op(HVMOP_set_evtchn_upcall_vector, &vec);
231 
232 	return (error != 0 ? xen_translate_error(error) : 0);
233 }
234 
235 /*
236  * Tell the hypervisor how to contact us for event channel callbacks.
237  */
238 void
239 xen_hvm_set_callback(device_t dev)
240 {
241 	struct xen_hvm_param xhp;
242 	int irq;
243 
244 	if (xen_vector_callback_enabled)
245 		return;
246 
247 	xhp.domid = DOMID_SELF;
248 	xhp.index = HVM_PARAM_CALLBACK_IRQ;
249 	if (xen_feature(XENFEAT_hvm_callback_vector) != 0) {
250 		int error;
251 
252 		error = set_percpu_callback(0);
253 		if (error == 0) {
254 			xen_evtchn_needs_ack = true;
255 			/* Trick toolstack to think we are enlightened */
256 			xhp.value = 1;
257 		} else
258 			xhp.value = HVM_CALLBACK_VECTOR(IDT_EVTCHN);
259 		error = HYPERVISOR_hvm_op(HVMOP_set_param, &xhp);
260 		if (error == 0) {
261 			xen_vector_callback_enabled = 1;
262 			return;
263 		} else if (xen_evtchn_needs_ack)
264 			panic("Unable to setup fake HVM param: %d", error);
265 
266 		printf("Xen HVM callback vector registration failed (%d). "
267 		    "Falling back to emulated device interrupt\n", error);
268 	}
269 	xen_vector_callback_enabled = 0;
270 	if (dev == NULL) {
271 		/*
272 		 * Called from early boot or resume.
273 		 * xenpci will invoke us again later.
274 		 */
275 		return;
276 	}
277 
278 	irq = pci_get_irq(dev);
279 	if (irq < 16) {
280 		xhp.value = HVM_CALLBACK_GSI(irq);
281 	} else {
282 		u_int slot;
283 		u_int pin;
284 
285 		slot = pci_get_slot(dev);
286 		pin = pci_get_intpin(dev) - 1;
287 		xhp.value = HVM_CALLBACK_PCI_INTX(slot, pin);
288 	}
289 
290 	if (HYPERVISOR_hvm_op(HVMOP_set_param, &xhp) != 0)
291 		panic("Can't set evtchn callback");
292 }
293 
294 #define	XEN_MAGIC_IOPORT 0x10
295 enum {
296 	XMI_MAGIC			 = 0x49d2,
297 	XMI_UNPLUG_IDE_DISKS		 = 0x01,
298 	XMI_UNPLUG_NICS			 = 0x02,
299 	XMI_UNPLUG_IDE_EXCEPT_PRI_MASTER = 0x04
300 };
301 
302 static void
303 xen_hvm_disable_emulated_devices(void)
304 {
305 	u_short disable_devs = 0;
306 
307 	if (xen_pv_domain()) {
308 		/*
309 		 * No emulated devices in the PV case, so no need to unplug
310 		 * anything.
311 		 */
312 		if (xen_disable_pv_disks != 0 || xen_disable_pv_nics != 0)
313 			printf("PV devices cannot be disabled in PV guests\n");
314 		return;
315 	}
316 
317 	if (inw(XEN_MAGIC_IOPORT) != XMI_MAGIC)
318 		return;
319 
320 	if (xen_disable_pv_disks == 0) {
321 		if (bootverbose)
322 			printf("XEN: disabling emulated disks\n");
323 		disable_devs |= XMI_UNPLUG_IDE_DISKS;
324 	}
325 	if (xen_disable_pv_nics == 0) {
326 		if (bootverbose)
327 			printf("XEN: disabling emulated nics\n");
328 		disable_devs |= XMI_UNPLUG_NICS;
329 	}
330 
331 	if (disable_devs != 0)
332 		outw(XEN_MAGIC_IOPORT, disable_devs);
333 }
334 
335 static void
336 xen_hvm_init(enum xen_hvm_init_type init_type)
337 {
338 	int error;
339 	int i;
340 
341 	if (init_type == XEN_HVM_INIT_CANCELLED_SUSPEND)
342 		return;
343 
344 	error = xen_hvm_init_hypercall_stubs(init_type);
345 
346 	switch (init_type) {
347 	case XEN_HVM_INIT_LATE:
348 		if (error != 0)
349 			return;
350 
351 		/*
352 		 * If xen_domain_type is not set at this point
353 		 * it means we are inside a (PV)HVM guest, because
354 		 * for PVH the guest type is set much earlier
355 		 * (see hammer_time_xen).
356 		 */
357 		if (!xen_domain()) {
358 			xen_domain_type = XEN_HVM_DOMAIN;
359 			vm_guest = VM_GUEST_XEN;
360 		}
361 
362 		setup_xen_features();
363 #ifdef SMP
364 		cpu_ops = xen_hvm_cpu_ops;
365 #endif
366 		break;
367 	case XEN_HVM_INIT_RESUME:
368 		if (error != 0)
369 			panic("Unable to init Xen hypercall stubs on resume");
370 
371 		/* Clear stale vcpu_info. */
372 		CPU_FOREACH(i)
373 			DPCPU_ID_SET(i, vcpu_info, NULL);
374 		break;
375 	default:
376 		panic("Unsupported HVM initialization type");
377 	}
378 
379 	xen_vector_callback_enabled = 0;
380 	xen_evtchn_needs_ack = false;
381 	xen_hvm_set_callback(NULL);
382 
383 	/*
384 	 * On (PV)HVM domains we need to request the hypervisor to
385 	 * fill the shared info page, for PVH guest the shared_info page
386 	 * is passed inside the start_info struct and is already set, so this
387 	 * functions are no-ops.
388 	 */
389 	xen_hvm_init_shared_info_page();
390 	xen_hvm_disable_emulated_devices();
391 }
392 
393 void
394 xen_hvm_suspend(void)
395 {
396 }
397 
398 void
399 xen_hvm_resume(bool suspend_cancelled)
400 {
401 
402 	xen_hvm_init(suspend_cancelled ?
403 	    XEN_HVM_INIT_CANCELLED_SUSPEND : XEN_HVM_INIT_RESUME);
404 
405 	/* Register vcpu_info area for CPU#0. */
406 	xen_hvm_cpu_init();
407 }
408 
409 static void
410 xen_hvm_sysinit(void *arg __unused)
411 {
412 	xen_hvm_init(XEN_HVM_INIT_LATE);
413 }
414 SYSINIT(xen_hvm_init, SI_SUB_HYPERVISOR, SI_ORDER_FIRST, xen_hvm_sysinit, NULL);
415 
416 static void
417 xen_hvm_cpu_init(void)
418 {
419 	struct vcpu_register_vcpu_info info;
420 	struct vcpu_info *vcpu_info;
421 	uint32_t regs[4];
422 	int cpu, rc;
423 
424 	if (!xen_domain())
425 		return;
426 
427 	if (DPCPU_GET(vcpu_info) != NULL) {
428 		/*
429 		 * vcpu_info is already set.  We're resuming
430 		 * from a failed migration and our pre-suspend
431 		 * configuration is still valid.
432 		 */
433 		return;
434 	}
435 
436 	/*
437 	 * Set vCPU ID. If available fetch the ID from CPUID, if not just use
438 	 * the ACPI ID.
439 	 */
440 	KASSERT(xen_cpuid_base != 0, ("Invalid base Xen CPUID leaf"));
441 	cpuid_count(xen_cpuid_base + 4, 0, regs);
442 	KASSERT((regs[0] & XEN_HVM_CPUID_VCPU_ID_PRESENT) ||
443 	    !xen_pv_domain(),
444 	    ("Xen PV domain without vcpu_id in cpuid"));
445 	PCPU_SET(vcpu_id, (regs[0] & XEN_HVM_CPUID_VCPU_ID_PRESENT) ?
446 	    regs[1] : PCPU_GET(acpi_id));
447 
448 	if (xen_evtchn_needs_ack && !IS_BSP()) {
449 		/*
450 		 * Setup the per-vpcu event channel upcall vector. This is only
451 		 * required when using the new HVMOP_set_evtchn_upcall_vector
452 		 * hypercall, which allows using a different vector for each
453 		 * vCPU. Note that FreeBSD uses the same vector for all vCPUs
454 		 * because it's not dynamically allocated.
455 		 */
456 		rc = set_percpu_callback(PCPU_GET(vcpu_id));
457 		if (rc != 0)
458 			panic("Event channel upcall vector setup failed: %d",
459 			    rc);
460 	}
461 
462 	/*
463 	 * Set the vCPU info.
464 	 *
465 	 * NB: the vCPU info for vCPUs < 32 can be fetched from the shared info
466 	 * page, but in order to make sure the mapping code is correct always
467 	 * attempt to map the vCPU info at a custom place.
468 	 */
469 	vcpu_info = DPCPU_PTR(vcpu_local_info);
470 	cpu = PCPU_GET(vcpu_id);
471 	info.mfn = vtophys(vcpu_info) >> PAGE_SHIFT;
472 	info.offset = vtophys(vcpu_info) - trunc_page(vtophys(vcpu_info));
473 
474 	rc = HYPERVISOR_vcpu_op(VCPUOP_register_vcpu_info, cpu, &info);
475 	if (rc != 0)
476 		DPCPU_SET(vcpu_info, &HYPERVISOR_shared_info->vcpu_info[cpu]);
477 	else
478 		DPCPU_SET(vcpu_info, vcpu_info);
479 }
480 SYSINIT(xen_hvm_cpu_init, SI_SUB_INTR, SI_ORDER_FIRST, xen_hvm_cpu_init, NULL);
481 
482 bool
483 xen_has_iommu_maps(void)
484 {
485 	uint32_t regs[4];
486 
487 	KASSERT(xen_cpuid_base != 0, ("Invalid base Xen CPUID leaf"));
488 	cpuid_count(xen_cpuid_base + 4, 0, regs);
489 
490 	return (regs[0] & XEN_HVM_CPUID_IOMMU_MAPPINGS);
491 }
492