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