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