xref: /freebsd/usr.sbin/bhyve/bhyverun.c (revision b0d29bc47dba79f6f38e67eabadfb4b32ffd9390)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2011 NetApp, Inc.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  * $FreeBSD$
29  */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 #include <sys/types.h>
35 #ifndef WITHOUT_CAPSICUM
36 #include <sys/capsicum.h>
37 #endif
38 #include <sys/mman.h>
39 #include <sys/time.h>
40 
41 #include <amd64/vmm/intel/vmcs.h>
42 
43 #include <machine/atomic.h>
44 #include <machine/segments.h>
45 
46 #ifndef WITHOUT_CAPSICUM
47 #include <capsicum_helpers.h>
48 #endif
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <err.h>
53 #include <errno.h>
54 #include <libgen.h>
55 #include <unistd.h>
56 #include <assert.h>
57 #include <pthread.h>
58 #include <pthread_np.h>
59 #include <sysexits.h>
60 #include <stdbool.h>
61 #include <stdint.h>
62 
63 #include <machine/vmm.h>
64 #ifndef WITHOUT_CAPSICUM
65 #include <machine/vmm_dev.h>
66 #endif
67 #include <vmmapi.h>
68 
69 #include "bhyverun.h"
70 #include "acpi.h"
71 #include "atkbdc.h"
72 #include "inout.h"
73 #include "dbgport.h"
74 #include "fwctl.h"
75 #include "gdb.h"
76 #include "ioapic.h"
77 #include "mem.h"
78 #include "mevent.h"
79 #include "mptbl.h"
80 #include "pci_emul.h"
81 #include "pci_irq.h"
82 #include "pci_lpc.h"
83 #include "smbiostbl.h"
84 #include "xmsr.h"
85 #include "spinup_ap.h"
86 #include "rtc.h"
87 
88 #define GUEST_NIO_PORT		0x488	/* guest upcalls via i/o port */
89 
90 #define MB		(1024UL * 1024)
91 #define GB		(1024UL * MB)
92 
93 static const char * const vmx_exit_reason_desc[] = {
94 	[EXIT_REASON_EXCEPTION] = "Exception or non-maskable interrupt (NMI)",
95 	[EXIT_REASON_EXT_INTR] = "External interrupt",
96 	[EXIT_REASON_TRIPLE_FAULT] = "Triple fault",
97 	[EXIT_REASON_INIT] = "INIT signal",
98 	[EXIT_REASON_SIPI] = "Start-up IPI (SIPI)",
99 	[EXIT_REASON_IO_SMI] = "I/O system-management interrupt (SMI)",
100 	[EXIT_REASON_SMI] = "Other SMI",
101 	[EXIT_REASON_INTR_WINDOW] = "Interrupt window",
102 	[EXIT_REASON_NMI_WINDOW] = "NMI window",
103 	[EXIT_REASON_TASK_SWITCH] = "Task switch",
104 	[EXIT_REASON_CPUID] = "CPUID",
105 	[EXIT_REASON_GETSEC] = "GETSEC",
106 	[EXIT_REASON_HLT] = "HLT",
107 	[EXIT_REASON_INVD] = "INVD",
108 	[EXIT_REASON_INVLPG] = "INVLPG",
109 	[EXIT_REASON_RDPMC] = "RDPMC",
110 	[EXIT_REASON_RDTSC] = "RDTSC",
111 	[EXIT_REASON_RSM] = "RSM",
112 	[EXIT_REASON_VMCALL] = "VMCALL",
113 	[EXIT_REASON_VMCLEAR] = "VMCLEAR",
114 	[EXIT_REASON_VMLAUNCH] = "VMLAUNCH",
115 	[EXIT_REASON_VMPTRLD] = "VMPTRLD",
116 	[EXIT_REASON_VMPTRST] = "VMPTRST",
117 	[EXIT_REASON_VMREAD] = "VMREAD",
118 	[EXIT_REASON_VMRESUME] = "VMRESUME",
119 	[EXIT_REASON_VMWRITE] = "VMWRITE",
120 	[EXIT_REASON_VMXOFF] = "VMXOFF",
121 	[EXIT_REASON_VMXON] = "VMXON",
122 	[EXIT_REASON_CR_ACCESS] = "Control-register accesses",
123 	[EXIT_REASON_DR_ACCESS] = "MOV DR",
124 	[EXIT_REASON_INOUT] = "I/O instruction",
125 	[EXIT_REASON_RDMSR] = "RDMSR",
126 	[EXIT_REASON_WRMSR] = "WRMSR",
127 	[EXIT_REASON_INVAL_VMCS] =
128 	    "VM-entry failure due to invalid guest state",
129 	[EXIT_REASON_INVAL_MSR] = "VM-entry failure due to MSR loading",
130 	[EXIT_REASON_MWAIT] = "MWAIT",
131 	[EXIT_REASON_MTF] = "Monitor trap flag",
132 	[EXIT_REASON_MONITOR] = "MONITOR",
133 	[EXIT_REASON_PAUSE] = "PAUSE",
134 	[EXIT_REASON_MCE_DURING_ENTRY] =
135 	    "VM-entry failure due to machine-check event",
136 	[EXIT_REASON_TPR] = "TPR below threshold",
137 	[EXIT_REASON_APIC_ACCESS] = "APIC access",
138 	[EXIT_REASON_VIRTUALIZED_EOI] = "Virtualized EOI",
139 	[EXIT_REASON_GDTR_IDTR] = "Access to GDTR or IDTR",
140 	[EXIT_REASON_LDTR_TR] = "Access to LDTR or TR",
141 	[EXIT_REASON_EPT_FAULT] = "EPT violation",
142 	[EXIT_REASON_EPT_MISCONFIG] = "EPT misconfiguration",
143 	[EXIT_REASON_INVEPT] = "INVEPT",
144 	[EXIT_REASON_RDTSCP] = "RDTSCP",
145 	[EXIT_REASON_VMX_PREEMPT] = "VMX-preemption timer expired",
146 	[EXIT_REASON_INVVPID] = "INVVPID",
147 	[EXIT_REASON_WBINVD] = "WBINVD",
148 	[EXIT_REASON_XSETBV] = "XSETBV",
149 	[EXIT_REASON_APIC_WRITE] = "APIC write",
150 	[EXIT_REASON_RDRAND] = "RDRAND",
151 	[EXIT_REASON_INVPCID] = "INVPCID",
152 	[EXIT_REASON_VMFUNC] = "VMFUNC",
153 	[EXIT_REASON_ENCLS] = "ENCLS",
154 	[EXIT_REASON_RDSEED] = "RDSEED",
155 	[EXIT_REASON_PM_LOG_FULL] = "Page-modification log full",
156 	[EXIT_REASON_XSAVES] = "XSAVES",
157 	[EXIT_REASON_XRSTORS] = "XRSTORS"
158 };
159 
160 typedef int (*vmexit_handler_t)(struct vmctx *, struct vm_exit *, int *vcpu);
161 extern int vmexit_task_switch(struct vmctx *, struct vm_exit *, int *vcpu);
162 
163 char *vmname;
164 
165 int guest_ncpus;
166 uint16_t cores, maxcpus, sockets, threads;
167 
168 char *guest_uuid_str;
169 
170 int raw_stdio = 0;
171 
172 static int gdb_port = 0;
173 static int guest_vmexit_on_hlt, guest_vmexit_on_pause;
174 static int virtio_msix = 1;
175 static int x2apic_mode = 0;	/* default is xAPIC */
176 
177 static int strictio;
178 static int strictmsr = 1;
179 
180 static int acpi;
181 
182 static char *progname;
183 static const int BSP = 0;
184 
185 static cpuset_t cpumask;
186 
187 static void vm_loop(struct vmctx *ctx, int vcpu, uint64_t rip);
188 
189 static struct vm_exit vmexit[VM_MAXCPU];
190 
191 struct bhyvestats {
192 	uint64_t	vmexit_bogus;
193 	uint64_t	vmexit_reqidle;
194 	uint64_t	vmexit_hlt;
195 	uint64_t	vmexit_pause;
196 	uint64_t	vmexit_mtrap;
197 	uint64_t	vmexit_inst_emul;
198 	uint64_t	cpu_switch_rotate;
199 	uint64_t	cpu_switch_direct;
200 } stats;
201 
202 struct mt_vmm_info {
203 	pthread_t	mt_thr;
204 	struct vmctx	*mt_ctx;
205 	int		mt_vcpu;
206 } mt_vmm_info[VM_MAXCPU];
207 
208 static cpuset_t *vcpumap[VM_MAXCPU] = { NULL };
209 
210 static void
211 usage(int code)
212 {
213 
214         fprintf(stderr,
215 		"Usage: %s [-abehuwxACHPSWY]\n"
216 		"       %*s [-c [[cpus=]numcpus][,sockets=n][,cores=n][,threads=n]]\n"
217 		"       %*s [-g <gdb port>] [-l <lpc>]\n"
218 		"       %*s [-m mem] [-p vcpu:hostcpu] [-s <pci>] [-U uuid] <vm>\n"
219 		"       -a: local apic is in xAPIC mode (deprecated)\n"
220 		"       -A: create ACPI tables\n"
221 		"       -c: number of cpus and/or topology specification\n"
222 		"       -C: include guest memory in core file\n"
223 		"       -e: exit on unhandled I/O access\n"
224 		"       -g: gdb port\n"
225 		"       -h: help\n"
226 		"       -H: vmexit from the guest on hlt\n"
227 		"       -l: LPC device configuration\n"
228 		"       -m: memory size in MB\n"
229 		"       -p: pin 'vcpu' to 'hostcpu'\n"
230 		"       -P: vmexit from the guest on pause\n"
231 		"       -s: <slot,driver,configinfo> PCI slot config\n"
232 		"       -S: guest memory cannot be swapped\n"
233 		"       -u: RTC keeps UTC time\n"
234 		"       -U: uuid\n"
235 		"       -w: ignore unimplemented MSRs\n"
236 		"       -W: force virtio to use single-vector MSI\n"
237 		"       -x: local apic is in x2APIC mode\n"
238 		"       -Y: disable MPtable generation\n",
239 		progname, (int)strlen(progname), "", (int)strlen(progname), "",
240 		(int)strlen(progname), "");
241 
242 	exit(code);
243 }
244 
245 /*
246  * XXX This parser is known to have the following issues:
247  * 1.  It accepts null key=value tokens ",,".
248  * 2.  It accepts whitespace after = and before value.
249  * 3.  Values out of range of INT are silently wrapped.
250  * 4.  It doesn't check non-final values.
251  * 5.  The apparently bogus limits of UINT16_MAX are for future expansion.
252  *
253  * The acceptance of a null specification ('-c ""') is by design to match the
254  * manual page syntax specification, this results in a topology of 1 vCPU.
255  */
256 static int
257 topology_parse(const char *opt)
258 {
259 	uint64_t ncpus;
260 	int c, chk, n, s, t, tmp;
261 	char *cp, *str;
262 	bool ns, scts;
263 
264 	c = 1, n = 1, s = 1, t = 1;
265 	ns = false, scts = false;
266 	str = strdup(opt);
267 	if (str == NULL)
268 		goto out;
269 
270 	while ((cp = strsep(&str, ",")) != NULL) {
271 		if (sscanf(cp, "%i%n", &tmp, &chk) == 1) {
272 			n = tmp;
273 			ns = true;
274 		} else if (sscanf(cp, "cpus=%i%n", &tmp, &chk) == 1) {
275 			n = tmp;
276 			ns = true;
277 		} else if (sscanf(cp, "sockets=%i%n", &tmp, &chk) == 1) {
278 			s = tmp;
279 			scts = true;
280 		} else if (sscanf(cp, "cores=%i%n", &tmp, &chk) == 1) {
281 			c = tmp;
282 			scts = true;
283 		} else if (sscanf(cp, "threads=%i%n", &tmp, &chk) == 1) {
284 			t = tmp;
285 			scts = true;
286 #ifdef notyet  /* Do not expose this until vmm.ko implements it */
287 		} else if (sscanf(cp, "maxcpus=%i%n", &tmp, &chk) == 1) {
288 			m = tmp;
289 #endif
290 		/* Skip the empty argument case from -c "" */
291 		} else if (cp[0] == '\0')
292 			continue;
293 		else
294 			goto out;
295 		/* Any trailing garbage causes an error */
296 		if (cp[chk] != '\0')
297 			goto out;
298 	}
299 	free(str);
300 	str = NULL;
301 
302 	/*
303 	 * Range check 1 <= n <= UINT16_MAX all values
304 	 */
305 	if (n < 1 || s < 1 || c < 1 || t < 1 ||
306 	    n > UINT16_MAX || s > UINT16_MAX || c > UINT16_MAX  ||
307 	    t > UINT16_MAX)
308 		return (-1);
309 
310 	/* If only the cpus was specified, use that as sockets */
311 	if (!scts)
312 		s = n;
313 	/*
314 	 * Compute sockets * cores * threads avoiding overflow
315 	 * The range check above insures these are 16 bit values
316 	 * If n was specified check it against computed ncpus
317 	 */
318 	ncpus = (uint64_t)s * c * t;
319 	if (ncpus > UINT16_MAX || (ns && n != ncpus))
320 		return (-1);
321 
322 	guest_ncpus = ncpus;
323 	sockets = s;
324 	cores = c;
325 	threads = t;
326 	return(0);
327 
328 out:
329 	free(str);
330 	return (-1);
331 }
332 
333 static int
334 pincpu_parse(const char *opt)
335 {
336 	int vcpu, pcpu;
337 
338 	if (sscanf(opt, "%d:%d", &vcpu, &pcpu) != 2) {
339 		fprintf(stderr, "invalid format: %s\n", opt);
340 		return (-1);
341 	}
342 
343 	if (vcpu < 0 || vcpu >= VM_MAXCPU) {
344 		fprintf(stderr, "vcpu '%d' outside valid range from 0 to %d\n",
345 		    vcpu, VM_MAXCPU - 1);
346 		return (-1);
347 	}
348 
349 	if (pcpu < 0 || pcpu >= CPU_SETSIZE) {
350 		fprintf(stderr, "hostcpu '%d' outside valid range from "
351 		    "0 to %d\n", pcpu, CPU_SETSIZE - 1);
352 		return (-1);
353 	}
354 
355 	if (vcpumap[vcpu] == NULL) {
356 		if ((vcpumap[vcpu] = malloc(sizeof(cpuset_t))) == NULL) {
357 			perror("malloc");
358 			return (-1);
359 		}
360 		CPU_ZERO(vcpumap[vcpu]);
361 	}
362 	CPU_SET(pcpu, vcpumap[vcpu]);
363 	return (0);
364 }
365 
366 void
367 vm_inject_fault(void *arg, int vcpu, int vector, int errcode_valid,
368     int errcode)
369 {
370 	struct vmctx *ctx;
371 	int error, restart_instruction;
372 
373 	ctx = arg;
374 	restart_instruction = 1;
375 
376 	error = vm_inject_exception(ctx, vcpu, vector, errcode_valid, errcode,
377 	    restart_instruction);
378 	assert(error == 0);
379 }
380 
381 void *
382 paddr_guest2host(struct vmctx *ctx, uintptr_t gaddr, size_t len)
383 {
384 
385 	return (vm_map_gpa(ctx, gaddr, len));
386 }
387 
388 int
389 fbsdrun_vmexit_on_pause(void)
390 {
391 
392 	return (guest_vmexit_on_pause);
393 }
394 
395 int
396 fbsdrun_vmexit_on_hlt(void)
397 {
398 
399 	return (guest_vmexit_on_hlt);
400 }
401 
402 int
403 fbsdrun_virtio_msix(void)
404 {
405 
406 	return (virtio_msix);
407 }
408 
409 static void *
410 fbsdrun_start_thread(void *param)
411 {
412 	char tname[MAXCOMLEN + 1];
413 	struct mt_vmm_info *mtp;
414 	int vcpu;
415 
416 	mtp = param;
417 	vcpu = mtp->mt_vcpu;
418 
419 	snprintf(tname, sizeof(tname), "vcpu %d", vcpu);
420 	pthread_set_name_np(mtp->mt_thr, tname);
421 
422 	if (gdb_port != 0)
423 		gdb_cpu_add(vcpu);
424 
425 	vm_loop(mtp->mt_ctx, vcpu, vmexit[vcpu].rip);
426 
427 	/* not reached */
428 	exit(1);
429 	return (NULL);
430 }
431 
432 void
433 fbsdrun_addcpu(struct vmctx *ctx, int fromcpu, int newcpu, uint64_t rip)
434 {
435 	int error;
436 
437 	assert(fromcpu == BSP);
438 
439 	/*
440 	 * The 'newcpu' must be activated in the context of 'fromcpu'. If
441 	 * vm_activate_cpu() is delayed until newcpu's pthread starts running
442 	 * then vmm.ko is out-of-sync with bhyve and this can create a race
443 	 * with vm_suspend().
444 	 */
445 	error = vm_activate_cpu(ctx, newcpu);
446 	if (error != 0)
447 		err(EX_OSERR, "could not activate CPU %d", newcpu);
448 
449 	CPU_SET_ATOMIC(newcpu, &cpumask);
450 
451 	/*
452 	 * Set up the vmexit struct to allow execution to start
453 	 * at the given RIP
454 	 */
455 	vmexit[newcpu].rip = rip;
456 	vmexit[newcpu].inst_length = 0;
457 
458 	mt_vmm_info[newcpu].mt_ctx = ctx;
459 	mt_vmm_info[newcpu].mt_vcpu = newcpu;
460 
461 	error = pthread_create(&mt_vmm_info[newcpu].mt_thr, NULL,
462 	    fbsdrun_start_thread, &mt_vmm_info[newcpu]);
463 	assert(error == 0);
464 }
465 
466 static int
467 fbsdrun_deletecpu(struct vmctx *ctx, int vcpu)
468 {
469 
470 	if (!CPU_ISSET(vcpu, &cpumask)) {
471 		fprintf(stderr, "Attempting to delete unknown cpu %d\n", vcpu);
472 		exit(4);
473 	}
474 
475 	CPU_CLR_ATOMIC(vcpu, &cpumask);
476 	return (CPU_EMPTY(&cpumask));
477 }
478 
479 static int
480 vmexit_handle_notify(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu,
481 		     uint32_t eax)
482 {
483 #if BHYVE_DEBUG
484 	/*
485 	 * put guest-driven debug here
486 	 */
487 #endif
488 	return (VMEXIT_CONTINUE);
489 }
490 
491 static int
492 vmexit_inout(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
493 {
494 	int error;
495 	int bytes, port, in, out;
496 	int vcpu;
497 
498 	vcpu = *pvcpu;
499 
500 	port = vme->u.inout.port;
501 	bytes = vme->u.inout.bytes;
502 	in = vme->u.inout.in;
503 	out = !in;
504 
505         /* Extra-special case of host notifications */
506         if (out && port == GUEST_NIO_PORT) {
507                 error = vmexit_handle_notify(ctx, vme, pvcpu, vme->u.inout.eax);
508 		return (error);
509 	}
510 
511 	error = emulate_inout(ctx, vcpu, vme, strictio);
512 	if (error) {
513 		fprintf(stderr, "Unhandled %s%c 0x%04x at 0x%lx\n",
514 		    in ? "in" : "out",
515 		    bytes == 1 ? 'b' : (bytes == 2 ? 'w' : 'l'),
516 		    port, vmexit->rip);
517 		return (VMEXIT_ABORT);
518 	} else {
519 		return (VMEXIT_CONTINUE);
520 	}
521 }
522 
523 static int
524 vmexit_rdmsr(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
525 {
526 	uint64_t val;
527 	uint32_t eax, edx;
528 	int error;
529 
530 	val = 0;
531 	error = emulate_rdmsr(ctx, *pvcpu, vme->u.msr.code, &val);
532 	if (error != 0) {
533 		fprintf(stderr, "rdmsr to register %#x on vcpu %d\n",
534 		    vme->u.msr.code, *pvcpu);
535 		if (strictmsr) {
536 			vm_inject_gp(ctx, *pvcpu);
537 			return (VMEXIT_CONTINUE);
538 		}
539 	}
540 
541 	eax = val;
542 	error = vm_set_register(ctx, *pvcpu, VM_REG_GUEST_RAX, eax);
543 	assert(error == 0);
544 
545 	edx = val >> 32;
546 	error = vm_set_register(ctx, *pvcpu, VM_REG_GUEST_RDX, edx);
547 	assert(error == 0);
548 
549 	return (VMEXIT_CONTINUE);
550 }
551 
552 static int
553 vmexit_wrmsr(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
554 {
555 	int error;
556 
557 	error = emulate_wrmsr(ctx, *pvcpu, vme->u.msr.code, vme->u.msr.wval);
558 	if (error != 0) {
559 		fprintf(stderr, "wrmsr to register %#x(%#lx) on vcpu %d\n",
560 		    vme->u.msr.code, vme->u.msr.wval, *pvcpu);
561 		if (strictmsr) {
562 			vm_inject_gp(ctx, *pvcpu);
563 			return (VMEXIT_CONTINUE);
564 		}
565 	}
566 	return (VMEXIT_CONTINUE);
567 }
568 
569 static int
570 vmexit_spinup_ap(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
571 {
572 
573 	(void)spinup_ap(ctx, *pvcpu,
574 		    vme->u.spinup_ap.vcpu, vme->u.spinup_ap.rip);
575 
576 	return (VMEXIT_CONTINUE);
577 }
578 
579 #define	DEBUG_EPT_MISCONFIG
580 #ifdef DEBUG_EPT_MISCONFIG
581 #define	VMCS_GUEST_PHYSICAL_ADDRESS	0x00002400
582 
583 static uint64_t ept_misconfig_gpa, ept_misconfig_pte[4];
584 static int ept_misconfig_ptenum;
585 #endif
586 
587 static const char *
588 vmexit_vmx_desc(uint32_t exit_reason)
589 {
590 
591 	if (exit_reason >= nitems(vmx_exit_reason_desc) ||
592 	    vmx_exit_reason_desc[exit_reason] == NULL)
593 		return ("Unknown");
594 	return (vmx_exit_reason_desc[exit_reason]);
595 }
596 
597 static int
598 vmexit_vmx(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
599 {
600 
601 	fprintf(stderr, "vm exit[%d]\n", *pvcpu);
602 	fprintf(stderr, "\treason\t\tVMX\n");
603 	fprintf(stderr, "\trip\t\t0x%016lx\n", vmexit->rip);
604 	fprintf(stderr, "\tinst_length\t%d\n", vmexit->inst_length);
605 	fprintf(stderr, "\tstatus\t\t%d\n", vmexit->u.vmx.status);
606 	fprintf(stderr, "\texit_reason\t%u (%s)\n", vmexit->u.vmx.exit_reason,
607 	    vmexit_vmx_desc(vmexit->u.vmx.exit_reason));
608 	fprintf(stderr, "\tqualification\t0x%016lx\n",
609 	    vmexit->u.vmx.exit_qualification);
610 	fprintf(stderr, "\tinst_type\t\t%d\n", vmexit->u.vmx.inst_type);
611 	fprintf(stderr, "\tinst_error\t\t%d\n", vmexit->u.vmx.inst_error);
612 #ifdef DEBUG_EPT_MISCONFIG
613 	if (vmexit->u.vmx.exit_reason == EXIT_REASON_EPT_MISCONFIG) {
614 		vm_get_register(ctx, *pvcpu,
615 		    VMCS_IDENT(VMCS_GUEST_PHYSICAL_ADDRESS),
616 		    &ept_misconfig_gpa);
617 		vm_get_gpa_pmap(ctx, ept_misconfig_gpa, ept_misconfig_pte,
618 		    &ept_misconfig_ptenum);
619 		fprintf(stderr, "\tEPT misconfiguration:\n");
620 		fprintf(stderr, "\t\tGPA: %#lx\n", ept_misconfig_gpa);
621 		fprintf(stderr, "\t\tPTE(%d): %#lx %#lx %#lx %#lx\n",
622 		    ept_misconfig_ptenum, ept_misconfig_pte[0],
623 		    ept_misconfig_pte[1], ept_misconfig_pte[2],
624 		    ept_misconfig_pte[3]);
625 	}
626 #endif	/* DEBUG_EPT_MISCONFIG */
627 	return (VMEXIT_ABORT);
628 }
629 
630 static int
631 vmexit_svm(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
632 {
633 
634 	fprintf(stderr, "vm exit[%d]\n", *pvcpu);
635 	fprintf(stderr, "\treason\t\tSVM\n");
636 	fprintf(stderr, "\trip\t\t0x%016lx\n", vmexit->rip);
637 	fprintf(stderr, "\tinst_length\t%d\n", vmexit->inst_length);
638 	fprintf(stderr, "\texitcode\t%#lx\n", vmexit->u.svm.exitcode);
639 	fprintf(stderr, "\texitinfo1\t%#lx\n", vmexit->u.svm.exitinfo1);
640 	fprintf(stderr, "\texitinfo2\t%#lx\n", vmexit->u.svm.exitinfo2);
641 	return (VMEXIT_ABORT);
642 }
643 
644 static int
645 vmexit_bogus(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
646 {
647 
648 	assert(vmexit->inst_length == 0);
649 
650 	stats.vmexit_bogus++;
651 
652 	return (VMEXIT_CONTINUE);
653 }
654 
655 static int
656 vmexit_reqidle(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
657 {
658 
659 	assert(vmexit->inst_length == 0);
660 
661 	stats.vmexit_reqidle++;
662 
663 	return (VMEXIT_CONTINUE);
664 }
665 
666 static int
667 vmexit_hlt(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
668 {
669 
670 	stats.vmexit_hlt++;
671 
672 	/*
673 	 * Just continue execution with the next instruction. We use
674 	 * the HLT VM exit as a way to be friendly with the host
675 	 * scheduler.
676 	 */
677 	return (VMEXIT_CONTINUE);
678 }
679 
680 static int
681 vmexit_pause(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
682 {
683 
684 	stats.vmexit_pause++;
685 
686 	return (VMEXIT_CONTINUE);
687 }
688 
689 static int
690 vmexit_mtrap(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
691 {
692 
693 	assert(vmexit->inst_length == 0);
694 
695 	stats.vmexit_mtrap++;
696 
697 	if (gdb_port == 0) {
698 		fprintf(stderr, "vm_loop: unexpected VMEXIT_MTRAP\n");
699 		exit(4);
700 	}
701 	gdb_cpu_mtrap(*pvcpu);
702 	return (VMEXIT_CONTINUE);
703 }
704 
705 static int
706 vmexit_inst_emul(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
707 {
708 	int err, i;
709 	struct vie *vie;
710 
711 	stats.vmexit_inst_emul++;
712 
713 	vie = &vmexit->u.inst_emul.vie;
714 	err = emulate_mem(ctx, *pvcpu, vmexit->u.inst_emul.gpa,
715 	    vie, &vmexit->u.inst_emul.paging);
716 
717 	if (err) {
718 		if (err == ESRCH) {
719 			fprintf(stderr, "Unhandled memory access to 0x%lx\n",
720 			    vmexit->u.inst_emul.gpa);
721 		}
722 
723 		fprintf(stderr, "Failed to emulate instruction [");
724 		for (i = 0; i < vie->num_valid; i++) {
725 			fprintf(stderr, "0x%02x%s", vie->inst[i],
726 			    i != (vie->num_valid - 1) ? " " : "");
727 		}
728 		fprintf(stderr, "] at 0x%lx\n", vmexit->rip);
729 		return (VMEXIT_ABORT);
730 	}
731 
732 	return (VMEXIT_CONTINUE);
733 }
734 
735 static pthread_mutex_t resetcpu_mtx = PTHREAD_MUTEX_INITIALIZER;
736 static pthread_cond_t resetcpu_cond = PTHREAD_COND_INITIALIZER;
737 
738 static int
739 vmexit_suspend(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
740 {
741 	enum vm_suspend_how how;
742 
743 	how = vmexit->u.suspended.how;
744 
745 	fbsdrun_deletecpu(ctx, *pvcpu);
746 
747 	if (*pvcpu != BSP) {
748 		pthread_mutex_lock(&resetcpu_mtx);
749 		pthread_cond_signal(&resetcpu_cond);
750 		pthread_mutex_unlock(&resetcpu_mtx);
751 		pthread_exit(NULL);
752 	}
753 
754 	pthread_mutex_lock(&resetcpu_mtx);
755 	while (!CPU_EMPTY(&cpumask)) {
756 		pthread_cond_wait(&resetcpu_cond, &resetcpu_mtx);
757 	}
758 	pthread_mutex_unlock(&resetcpu_mtx);
759 
760 	switch (how) {
761 	case VM_SUSPEND_RESET:
762 		exit(0);
763 	case VM_SUSPEND_POWEROFF:
764 		exit(1);
765 	case VM_SUSPEND_HALT:
766 		exit(2);
767 	case VM_SUSPEND_TRIPLEFAULT:
768 		exit(3);
769 	default:
770 		fprintf(stderr, "vmexit_suspend: invalid reason %d\n", how);
771 		exit(100);
772 	}
773 	return (0);	/* NOTREACHED */
774 }
775 
776 static int
777 vmexit_debug(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
778 {
779 
780 	if (gdb_port == 0) {
781 		fprintf(stderr, "vm_loop: unexpected VMEXIT_DEBUG\n");
782 		exit(4);
783 	}
784 	gdb_cpu_suspend(*pvcpu);
785 	return (VMEXIT_CONTINUE);
786 }
787 
788 static int
789 vmexit_breakpoint(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
790 {
791 
792 	if (gdb_port == 0) {
793 		fprintf(stderr, "vm_loop: unexpected VMEXIT_DEBUG\n");
794 		exit(4);
795 	}
796 	gdb_cpu_breakpoint(*pvcpu, vmexit);
797 	return (VMEXIT_CONTINUE);
798 }
799 
800 static vmexit_handler_t handler[VM_EXITCODE_MAX] = {
801 	[VM_EXITCODE_INOUT]  = vmexit_inout,
802 	[VM_EXITCODE_INOUT_STR]  = vmexit_inout,
803 	[VM_EXITCODE_VMX]    = vmexit_vmx,
804 	[VM_EXITCODE_SVM]    = vmexit_svm,
805 	[VM_EXITCODE_BOGUS]  = vmexit_bogus,
806 	[VM_EXITCODE_REQIDLE] = vmexit_reqidle,
807 	[VM_EXITCODE_RDMSR]  = vmexit_rdmsr,
808 	[VM_EXITCODE_WRMSR]  = vmexit_wrmsr,
809 	[VM_EXITCODE_MTRAP]  = vmexit_mtrap,
810 	[VM_EXITCODE_INST_EMUL] = vmexit_inst_emul,
811 	[VM_EXITCODE_SPINUP_AP] = vmexit_spinup_ap,
812 	[VM_EXITCODE_SUSPENDED] = vmexit_suspend,
813 	[VM_EXITCODE_TASK_SWITCH] = vmexit_task_switch,
814 	[VM_EXITCODE_DEBUG] = vmexit_debug,
815 	[VM_EXITCODE_BPT] = vmexit_breakpoint,
816 };
817 
818 static void
819 vm_loop(struct vmctx *ctx, int vcpu, uint64_t startrip)
820 {
821 	int error, rc;
822 	enum vm_exitcode exitcode;
823 	cpuset_t active_cpus;
824 
825 	if (vcpumap[vcpu] != NULL) {
826 		error = pthread_setaffinity_np(pthread_self(),
827 		    sizeof(cpuset_t), vcpumap[vcpu]);
828 		assert(error == 0);
829 	}
830 
831 	error = vm_active_cpus(ctx, &active_cpus);
832 	assert(CPU_ISSET(vcpu, &active_cpus));
833 
834 	error = vm_set_register(ctx, vcpu, VM_REG_GUEST_RIP, startrip);
835 	assert(error == 0);
836 
837 	while (1) {
838 		error = vm_run(ctx, vcpu, &vmexit[vcpu]);
839 		if (error != 0)
840 			break;
841 
842 		exitcode = vmexit[vcpu].exitcode;
843 		if (exitcode >= VM_EXITCODE_MAX || handler[exitcode] == NULL) {
844 			fprintf(stderr, "vm_loop: unexpected exitcode 0x%x\n",
845 			    exitcode);
846 			exit(4);
847 		}
848 
849 		rc = (*handler[exitcode])(ctx, &vmexit[vcpu], &vcpu);
850 
851 		switch (rc) {
852 		case VMEXIT_CONTINUE:
853 			break;
854 		case VMEXIT_ABORT:
855 			abort();
856 		default:
857 			exit(4);
858 		}
859 	}
860 	fprintf(stderr, "vm_run error %d, errno %d\n", error, errno);
861 }
862 
863 static int
864 num_vcpus_allowed(struct vmctx *ctx)
865 {
866 	int tmp, error;
867 
868 	error = vm_get_capability(ctx, BSP, VM_CAP_UNRESTRICTED_GUEST, &tmp);
869 
870 	/*
871 	 * The guest is allowed to spinup more than one processor only if the
872 	 * UNRESTRICTED_GUEST capability is available.
873 	 */
874 	if (error == 0)
875 		return (VM_MAXCPU);
876 	else
877 		return (1);
878 }
879 
880 void
881 fbsdrun_set_capabilities(struct vmctx *ctx, int cpu)
882 {
883 	int err, tmp;
884 
885 	if (fbsdrun_vmexit_on_hlt()) {
886 		err = vm_get_capability(ctx, cpu, VM_CAP_HALT_EXIT, &tmp);
887 		if (err < 0) {
888 			fprintf(stderr, "VM exit on HLT not supported\n");
889 			exit(4);
890 		}
891 		vm_set_capability(ctx, cpu, VM_CAP_HALT_EXIT, 1);
892 		if (cpu == BSP)
893 			handler[VM_EXITCODE_HLT] = vmexit_hlt;
894 	}
895 
896         if (fbsdrun_vmexit_on_pause()) {
897 		/*
898 		 * pause exit support required for this mode
899 		 */
900 		err = vm_get_capability(ctx, cpu, VM_CAP_PAUSE_EXIT, &tmp);
901 		if (err < 0) {
902 			fprintf(stderr,
903 			    "SMP mux requested, no pause support\n");
904 			exit(4);
905 		}
906 		vm_set_capability(ctx, cpu, VM_CAP_PAUSE_EXIT, 1);
907 		if (cpu == BSP)
908 			handler[VM_EXITCODE_PAUSE] = vmexit_pause;
909         }
910 
911 	if (x2apic_mode)
912 		err = vm_set_x2apic_state(ctx, cpu, X2APIC_ENABLED);
913 	else
914 		err = vm_set_x2apic_state(ctx, cpu, X2APIC_DISABLED);
915 
916 	if (err) {
917 		fprintf(stderr, "Unable to set x2apic state (%d)\n", err);
918 		exit(4);
919 	}
920 
921 	vm_set_capability(ctx, cpu, VM_CAP_ENABLE_INVPCID, 1);
922 }
923 
924 static struct vmctx *
925 do_open(const char *vmname)
926 {
927 	struct vmctx *ctx;
928 	int error;
929 	bool reinit, romboot;
930 #ifndef WITHOUT_CAPSICUM
931 	cap_rights_t rights;
932 	const cap_ioctl_t *cmds;
933 	size_t ncmds;
934 #endif
935 
936 	reinit = romboot = false;
937 
938 	if (lpc_bootrom())
939 		romboot = true;
940 
941 	error = vm_create(vmname);
942 	if (error) {
943 		if (errno == EEXIST) {
944 			if (romboot) {
945 				reinit = true;
946 			} else {
947 				/*
948 				 * The virtual machine has been setup by the
949 				 * userspace bootloader.
950 				 */
951 			}
952 		} else {
953 			perror("vm_create");
954 			exit(4);
955 		}
956 	} else {
957 		if (!romboot) {
958 			/*
959 			 * If the virtual machine was just created then a
960 			 * bootrom must be configured to boot it.
961 			 */
962 			fprintf(stderr, "virtual machine cannot be booted\n");
963 			exit(4);
964 		}
965 	}
966 
967 	ctx = vm_open(vmname);
968 	if (ctx == NULL) {
969 		perror("vm_open");
970 		exit(4);
971 	}
972 
973 #ifndef WITHOUT_CAPSICUM
974 	cap_rights_init(&rights, CAP_IOCTL, CAP_MMAP_RW);
975 	if (caph_rights_limit(vm_get_device_fd(ctx), &rights) == -1)
976 		errx(EX_OSERR, "Unable to apply rights for sandbox");
977 	vm_get_ioctls(&ncmds);
978 	cmds = vm_get_ioctls(NULL);
979 	if (cmds == NULL)
980 		errx(EX_OSERR, "out of memory");
981 	if (caph_ioctls_limit(vm_get_device_fd(ctx), cmds, ncmds) == -1)
982 		errx(EX_OSERR, "Unable to apply rights for sandbox");
983 	free((cap_ioctl_t *)cmds);
984 #endif
985 
986 	if (reinit) {
987 		error = vm_reinit(ctx);
988 		if (error) {
989 			perror("vm_reinit");
990 			exit(4);
991 		}
992 	}
993 	error = vm_set_topology(ctx, sockets, cores, threads, maxcpus);
994 	if (error)
995 		errx(EX_OSERR, "vm_set_topology");
996 	return (ctx);
997 }
998 
999 int
1000 main(int argc, char *argv[])
1001 {
1002 	int c, error, dbg_port, err, bvmcons;
1003 	int max_vcpus, mptgen, memflags;
1004 	int rtc_localtime;
1005 	bool gdb_stop;
1006 	struct vmctx *ctx;
1007 	uint64_t rip;
1008 	size_t memsize;
1009 	char *optstr;
1010 
1011 	bvmcons = 0;
1012 	progname = basename(argv[0]);
1013 	dbg_port = 0;
1014 	gdb_stop = false;
1015 	guest_ncpus = 1;
1016 	sockets = cores = threads = 1;
1017 	maxcpus = 0;
1018 	memsize = 256 * MB;
1019 	mptgen = 1;
1020 	rtc_localtime = 1;
1021 	memflags = 0;
1022 
1023 	optstr = "abehuwxACHIPSWYp:g:G:c:s:m:l:U:";
1024 	while ((c = getopt(argc, argv, optstr)) != -1) {
1025 		switch (c) {
1026 		case 'a':
1027 			x2apic_mode = 0;
1028 			break;
1029 		case 'A':
1030 			acpi = 1;
1031 			break;
1032 		case 'b':
1033 			bvmcons = 1;
1034 			break;
1035 		case 'p':
1036                         if (pincpu_parse(optarg) != 0) {
1037                             errx(EX_USAGE, "invalid vcpu pinning "
1038                                  "configuration '%s'", optarg);
1039                         }
1040 			break;
1041                 case 'c':
1042 			if (topology_parse(optarg) != 0) {
1043 			    errx(EX_USAGE, "invalid cpu topology "
1044 				"'%s'", optarg);
1045 			}
1046 			break;
1047 		case 'C':
1048 			memflags |= VM_MEM_F_INCORE;
1049 			break;
1050 		case 'g':
1051 			dbg_port = atoi(optarg);
1052 			break;
1053 		case 'G':
1054 			if (optarg[0] == 'w') {
1055 				gdb_stop = true;
1056 				optarg++;
1057 			}
1058 			gdb_port = atoi(optarg);
1059 			break;
1060 		case 'l':
1061 			if (strncmp(optarg, "help", strlen(optarg)) == 0) {
1062 				lpc_print_supported_devices();
1063 				exit(0);
1064 			} else if (lpc_device_parse(optarg) != 0) {
1065 				errx(EX_USAGE, "invalid lpc device "
1066 				    "configuration '%s'", optarg);
1067 			}
1068 			break;
1069 		case 's':
1070 			if (strncmp(optarg, "help", strlen(optarg)) == 0) {
1071 				pci_print_supported_devices();
1072 				exit(0);
1073 			} else if (pci_parse_slot(optarg) != 0)
1074 				exit(4);
1075 			else
1076 				break;
1077 		case 'S':
1078 			memflags |= VM_MEM_F_WIRED;
1079 			break;
1080                 case 'm':
1081 			error = vm_parse_memsize(optarg, &memsize);
1082 			if (error)
1083 				errx(EX_USAGE, "invalid memsize '%s'", optarg);
1084 			break;
1085 		case 'H':
1086 			guest_vmexit_on_hlt = 1;
1087 			break;
1088 		case 'I':
1089 			/*
1090 			 * The "-I" option was used to add an ioapic to the
1091 			 * virtual machine.
1092 			 *
1093 			 * An ioapic is now provided unconditionally for each
1094 			 * virtual machine and this option is now deprecated.
1095 			 */
1096 			break;
1097 		case 'P':
1098 			guest_vmexit_on_pause = 1;
1099 			break;
1100 		case 'e':
1101 			strictio = 1;
1102 			break;
1103 		case 'u':
1104 			rtc_localtime = 0;
1105 			break;
1106 		case 'U':
1107 			guest_uuid_str = optarg;
1108 			break;
1109 		case 'w':
1110 			strictmsr = 0;
1111 			break;
1112 		case 'W':
1113 			virtio_msix = 0;
1114 			break;
1115 		case 'x':
1116 			x2apic_mode = 1;
1117 			break;
1118 		case 'Y':
1119 			mptgen = 0;
1120 			break;
1121 		case 'h':
1122 			usage(0);
1123 		default:
1124 			usage(1);
1125 		}
1126 	}
1127 	argc -= optind;
1128 	argv += optind;
1129 
1130 	if (argc != 1)
1131 		usage(1);
1132 
1133 	vmname = argv[0];
1134 	ctx = do_open(vmname);
1135 
1136 	max_vcpus = num_vcpus_allowed(ctx);
1137 	if (guest_ncpus > max_vcpus) {
1138 		fprintf(stderr, "%d vCPUs requested but only %d available\n",
1139 			guest_ncpus, max_vcpus);
1140 		exit(4);
1141 	}
1142 
1143 	fbsdrun_set_capabilities(ctx, BSP);
1144 
1145 	vm_set_memflags(ctx, memflags);
1146 	err = vm_setup_memory(ctx, memsize, VM_MMAP_ALL);
1147 	if (err) {
1148 		fprintf(stderr, "Unable to setup memory (%d)\n", errno);
1149 		exit(4);
1150 	}
1151 
1152 	error = init_msr();
1153 	if (error) {
1154 		fprintf(stderr, "init_msr error %d", error);
1155 		exit(4);
1156 	}
1157 
1158 	init_mem();
1159 	init_inout();
1160 	atkbdc_init(ctx);
1161 	pci_irq_init(ctx);
1162 	ioapic_init(ctx);
1163 
1164 	rtc_init(ctx, rtc_localtime);
1165 	sci_init(ctx);
1166 
1167 	/*
1168 	 * Exit if a device emulation finds an error in its initilization
1169 	 */
1170 	if (init_pci(ctx) != 0) {
1171 		perror("device emulation initialization error");
1172 		exit(4);
1173 	}
1174 
1175 	if (dbg_port != 0)
1176 		init_dbgport(dbg_port);
1177 
1178 	if (gdb_port != 0)
1179 		init_gdb(ctx, gdb_port, gdb_stop);
1180 
1181 	if (bvmcons)
1182 		init_bvmcons();
1183 
1184 	if (lpc_bootrom()) {
1185 		if (vm_set_capability(ctx, BSP, VM_CAP_UNRESTRICTED_GUEST, 1)) {
1186 			fprintf(stderr, "ROM boot failed: unrestricted guest "
1187 			    "capability not available\n");
1188 			exit(4);
1189 		}
1190 		error = vcpu_reset(ctx, BSP);
1191 		assert(error == 0);
1192 	}
1193 
1194 	error = vm_get_register(ctx, BSP, VM_REG_GUEST_RIP, &rip);
1195 	assert(error == 0);
1196 
1197 	/*
1198 	 * build the guest tables, MP etc.
1199 	 */
1200 	if (mptgen) {
1201 		error = mptable_build(ctx, guest_ncpus);
1202 		if (error) {
1203 			perror("error to build the guest tables");
1204 			exit(4);
1205 		}
1206 	}
1207 
1208 	error = smbios_build(ctx);
1209 	assert(error == 0);
1210 
1211 	if (acpi) {
1212 		error = acpi_build(ctx, guest_ncpus);
1213 		assert(error == 0);
1214 	}
1215 
1216 	if (lpc_bootrom())
1217 		fwctl_init();
1218 
1219 	/*
1220 	 * Change the proc title to include the VM name.
1221 	 */
1222 	setproctitle("%s", vmname);
1223 
1224 #ifndef WITHOUT_CAPSICUM
1225 	caph_cache_catpages();
1226 
1227 	if (caph_limit_stdout() == -1 || caph_limit_stderr() == -1)
1228 		errx(EX_OSERR, "Unable to apply rights for sandbox");
1229 
1230 	if (caph_enter() == -1)
1231 		errx(EX_OSERR, "cap_enter() failed");
1232 #endif
1233 
1234 	/*
1235 	 * Add CPU 0
1236 	 */
1237 	fbsdrun_addcpu(ctx, BSP, BSP, rip);
1238 
1239 	/*
1240 	 * Head off to the main event dispatch loop
1241 	 */
1242 	mevent_dispatch();
1243 
1244 	exit(4);
1245 }
1246