xref: /freebsd/usr.sbin/bhyve/bhyverun.c (revision 273c26a3c3bea87a241d6879abd4f991db180bf0)
1 /*-
2  * Copyright (c) 2011 NetApp, Inc.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD$
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <sys/types.h>
33 #include <sys/mman.h>
34 #include <sys/time.h>
35 
36 #include <machine/atomic.h>
37 #include <machine/segments.h>
38 
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <err.h>
43 #include <libgen.h>
44 #include <unistd.h>
45 #include <assert.h>
46 #include <errno.h>
47 #include <pthread.h>
48 #include <pthread_np.h>
49 #include <sysexits.h>
50 #include <stdbool.h>
51 
52 #include <machine/vmm.h>
53 #include <vmmapi.h>
54 
55 #include "bhyverun.h"
56 #include "acpi.h"
57 #include "atkbdc.h"
58 #include "inout.h"
59 #include "dbgport.h"
60 #include "fwctl.h"
61 #include "ioapic.h"
62 #include "mem.h"
63 #include "mevent.h"
64 #include "mptbl.h"
65 #include "pci_emul.h"
66 #include "pci_irq.h"
67 #include "pci_lpc.h"
68 #include "smbiostbl.h"
69 #include "xmsr.h"
70 #include "spinup_ap.h"
71 #include "rtc.h"
72 
73 #define GUEST_NIO_PORT		0x488	/* guest upcalls via i/o port */
74 
75 #define MB		(1024UL * 1024)
76 #define GB		(1024UL * MB)
77 
78 typedef int (*vmexit_handler_t)(struct vmctx *, struct vm_exit *, int *vcpu);
79 extern int vmexit_task_switch(struct vmctx *, struct vm_exit *, int *vcpu);
80 
81 char *vmname;
82 
83 int guest_ncpus;
84 char *guest_uuid_str;
85 
86 static int guest_vmexit_on_hlt, guest_vmexit_on_pause;
87 static int virtio_msix = 1;
88 static int x2apic_mode = 0;	/* default is xAPIC */
89 
90 static int strictio;
91 static int strictmsr = 1;
92 
93 static int acpi;
94 
95 static char *progname;
96 static const int BSP = 0;
97 
98 static cpuset_t cpumask;
99 
100 static void vm_loop(struct vmctx *ctx, int vcpu, uint64_t rip);
101 
102 static struct vm_exit vmexit[VM_MAXCPU];
103 
104 struct bhyvestats {
105         uint64_t        vmexit_bogus;
106 	uint64_t	vmexit_reqidle;
107         uint64_t        vmexit_hlt;
108         uint64_t        vmexit_pause;
109         uint64_t        vmexit_mtrap;
110         uint64_t        vmexit_inst_emul;
111         uint64_t        cpu_switch_rotate;
112         uint64_t        cpu_switch_direct;
113 } stats;
114 
115 struct mt_vmm_info {
116 	pthread_t	mt_thr;
117 	struct vmctx	*mt_ctx;
118 	int		mt_vcpu;
119 } mt_vmm_info[VM_MAXCPU];
120 
121 static cpuset_t *vcpumap[VM_MAXCPU] = { NULL };
122 
123 static void
124 usage(int code)
125 {
126 
127         fprintf(stderr,
128                 "Usage: %s [-abehuwxACHPSWY] [-c vcpus] [-g <gdb port>] [-l <lpc>]\n"
129 		"       %*s [-m mem] [-p vcpu:hostcpu] [-s <pci>] [-U uuid] <vm>\n"
130 		"       -a: local apic is in xAPIC mode (deprecated)\n"
131 		"       -A: create ACPI tables\n"
132 		"       -c: # cpus (default 1)\n"
133 		"       -C: include guest memory in core file\n"
134 		"       -e: exit on unhandled I/O access\n"
135 		"       -g: gdb port\n"
136 		"       -h: help\n"
137 		"       -H: vmexit from the guest on hlt\n"
138 		"       -l: LPC device configuration\n"
139 		"       -m: memory size in MB\n"
140 		"       -p: pin 'vcpu' to 'hostcpu'\n"
141 		"       -P: vmexit from the guest on pause\n"
142 		"       -s: <slot,driver,configinfo> PCI slot config\n"
143 		"       -S: guest memory cannot be swapped\n"
144 		"       -u: RTC keeps UTC time\n"
145 		"       -U: uuid\n"
146 		"       -w: ignore unimplemented MSRs\n"
147 		"       -W: force virtio to use single-vector MSI\n"
148 		"       -x: local apic is in x2APIC mode\n"
149 		"       -Y: disable MPtable generation\n",
150 		progname, (int)strlen(progname), "");
151 
152 	exit(code);
153 }
154 
155 static int
156 pincpu_parse(const char *opt)
157 {
158 	int vcpu, pcpu;
159 
160 	if (sscanf(opt, "%d:%d", &vcpu, &pcpu) != 2) {
161 		fprintf(stderr, "invalid format: %s\n", opt);
162 		return (-1);
163 	}
164 
165 	if (vcpu < 0 || vcpu >= VM_MAXCPU) {
166 		fprintf(stderr, "vcpu '%d' outside valid range from 0 to %d\n",
167 		    vcpu, VM_MAXCPU - 1);
168 		return (-1);
169 	}
170 
171 	if (pcpu < 0 || pcpu >= CPU_SETSIZE) {
172 		fprintf(stderr, "hostcpu '%d' outside valid range from "
173 		    "0 to %d\n", pcpu, CPU_SETSIZE - 1);
174 		return (-1);
175 	}
176 
177 	if (vcpumap[vcpu] == NULL) {
178 		if ((vcpumap[vcpu] = malloc(sizeof(cpuset_t))) == NULL) {
179 			perror("malloc");
180 			return (-1);
181 		}
182 		CPU_ZERO(vcpumap[vcpu]);
183 	}
184 	CPU_SET(pcpu, vcpumap[vcpu]);
185 	return (0);
186 }
187 
188 void
189 vm_inject_fault(void *arg, int vcpu, int vector, int errcode_valid,
190     int errcode)
191 {
192 	struct vmctx *ctx;
193 	int error, restart_instruction;
194 
195 	ctx = arg;
196 	restart_instruction = 1;
197 
198 	error = vm_inject_exception(ctx, vcpu, vector, errcode_valid, errcode,
199 	    restart_instruction);
200 	assert(error == 0);
201 }
202 
203 void *
204 paddr_guest2host(struct vmctx *ctx, uintptr_t gaddr, size_t len)
205 {
206 
207 	return (vm_map_gpa(ctx, gaddr, len));
208 }
209 
210 int
211 fbsdrun_vmexit_on_pause(void)
212 {
213 
214 	return (guest_vmexit_on_pause);
215 }
216 
217 int
218 fbsdrun_vmexit_on_hlt(void)
219 {
220 
221 	return (guest_vmexit_on_hlt);
222 }
223 
224 int
225 fbsdrun_virtio_msix(void)
226 {
227 
228 	return (virtio_msix);
229 }
230 
231 static void *
232 fbsdrun_start_thread(void *param)
233 {
234 	char tname[MAXCOMLEN + 1];
235 	struct mt_vmm_info *mtp;
236 	int vcpu;
237 
238 	mtp = param;
239 	vcpu = mtp->mt_vcpu;
240 
241 	snprintf(tname, sizeof(tname), "vcpu %d", vcpu);
242 	pthread_set_name_np(mtp->mt_thr, tname);
243 
244 	vm_loop(mtp->mt_ctx, vcpu, vmexit[vcpu].rip);
245 
246 	/* not reached */
247 	exit(1);
248 	return (NULL);
249 }
250 
251 void
252 fbsdrun_addcpu(struct vmctx *ctx, int fromcpu, int newcpu, uint64_t rip)
253 {
254 	int error;
255 
256 	assert(fromcpu == BSP);
257 
258 	/*
259 	 * The 'newcpu' must be activated in the context of 'fromcpu'. If
260 	 * vm_activate_cpu() is delayed until newcpu's pthread starts running
261 	 * then vmm.ko is out-of-sync with bhyve and this can create a race
262 	 * with vm_suspend().
263 	 */
264 	error = vm_activate_cpu(ctx, newcpu);
265 	if (error != 0)
266 		err(EX_OSERR, "could not activate CPU %d", newcpu);
267 
268 	CPU_SET_ATOMIC(newcpu, &cpumask);
269 
270 	/*
271 	 * Set up the vmexit struct to allow execution to start
272 	 * at the given RIP
273 	 */
274 	vmexit[newcpu].rip = rip;
275 	vmexit[newcpu].inst_length = 0;
276 
277 	mt_vmm_info[newcpu].mt_ctx = ctx;
278 	mt_vmm_info[newcpu].mt_vcpu = newcpu;
279 
280 	error = pthread_create(&mt_vmm_info[newcpu].mt_thr, NULL,
281 	    fbsdrun_start_thread, &mt_vmm_info[newcpu]);
282 	assert(error == 0);
283 }
284 
285 static int
286 fbsdrun_deletecpu(struct vmctx *ctx, int vcpu)
287 {
288 
289 	if (!CPU_ISSET(vcpu, &cpumask)) {
290 		fprintf(stderr, "Attempting to delete unknown cpu %d\n", vcpu);
291 		exit(1);
292 	}
293 
294 	CPU_CLR_ATOMIC(vcpu, &cpumask);
295 	return (CPU_EMPTY(&cpumask));
296 }
297 
298 static int
299 vmexit_handle_notify(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu,
300 		     uint32_t eax)
301 {
302 #if BHYVE_DEBUG
303 	/*
304 	 * put guest-driven debug here
305 	 */
306 #endif
307         return (VMEXIT_CONTINUE);
308 }
309 
310 static int
311 vmexit_inout(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
312 {
313 	int error;
314 	int bytes, port, in, out;
315 	int vcpu;
316 
317 	vcpu = *pvcpu;
318 
319 	port = vme->u.inout.port;
320 	bytes = vme->u.inout.bytes;
321 	in = vme->u.inout.in;
322 	out = !in;
323 
324         /* Extra-special case of host notifications */
325         if (out && port == GUEST_NIO_PORT) {
326                 error = vmexit_handle_notify(ctx, vme, pvcpu, vme->u.inout.eax);
327 		return (error);
328 	}
329 
330 	error = emulate_inout(ctx, vcpu, vme, strictio);
331 	if (error) {
332 		fprintf(stderr, "Unhandled %s%c 0x%04x at 0x%lx\n",
333 		    in ? "in" : "out",
334 		    bytes == 1 ? 'b' : (bytes == 2 ? 'w' : 'l'),
335 		    port, vmexit->rip);
336 		return (VMEXIT_ABORT);
337 	} else {
338 		return (VMEXIT_CONTINUE);
339 	}
340 }
341 
342 static int
343 vmexit_rdmsr(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
344 {
345 	uint64_t val;
346 	uint32_t eax, edx;
347 	int error;
348 
349 	val = 0;
350 	error = emulate_rdmsr(ctx, *pvcpu, vme->u.msr.code, &val);
351 	if (error != 0) {
352 		fprintf(stderr, "rdmsr to register %#x on vcpu %d\n",
353 		    vme->u.msr.code, *pvcpu);
354 		if (strictmsr) {
355 			vm_inject_gp(ctx, *pvcpu);
356 			return (VMEXIT_CONTINUE);
357 		}
358 	}
359 
360 	eax = val;
361 	error = vm_set_register(ctx, *pvcpu, VM_REG_GUEST_RAX, eax);
362 	assert(error == 0);
363 
364 	edx = val >> 32;
365 	error = vm_set_register(ctx, *pvcpu, VM_REG_GUEST_RDX, edx);
366 	assert(error == 0);
367 
368 	return (VMEXIT_CONTINUE);
369 }
370 
371 static int
372 vmexit_wrmsr(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
373 {
374 	int error;
375 
376 	error = emulate_wrmsr(ctx, *pvcpu, vme->u.msr.code, vme->u.msr.wval);
377 	if (error != 0) {
378 		fprintf(stderr, "wrmsr to register %#x(%#lx) on vcpu %d\n",
379 		    vme->u.msr.code, vme->u.msr.wval, *pvcpu);
380 		if (strictmsr) {
381 			vm_inject_gp(ctx, *pvcpu);
382 			return (VMEXIT_CONTINUE);
383 		}
384 	}
385 	return (VMEXIT_CONTINUE);
386 }
387 
388 static int
389 vmexit_spinup_ap(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
390 {
391 
392 	(void)spinup_ap(ctx, *pvcpu,
393 		    vme->u.spinup_ap.vcpu, vme->u.spinup_ap.rip);
394 
395 	return (VMEXIT_CONTINUE);
396 }
397 
398 #define	DEBUG_EPT_MISCONFIG
399 #ifdef DEBUG_EPT_MISCONFIG
400 #define	EXIT_REASON_EPT_MISCONFIG	49
401 #define	VMCS_GUEST_PHYSICAL_ADDRESS	0x00002400
402 #define	VMCS_IDENT(x)			((x) | 0x80000000)
403 
404 static uint64_t ept_misconfig_gpa, ept_misconfig_pte[4];
405 static int ept_misconfig_ptenum;
406 #endif
407 
408 static int
409 vmexit_vmx(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
410 {
411 
412 	fprintf(stderr, "vm exit[%d]\n", *pvcpu);
413 	fprintf(stderr, "\treason\t\tVMX\n");
414 	fprintf(stderr, "\trip\t\t0x%016lx\n", vmexit->rip);
415 	fprintf(stderr, "\tinst_length\t%d\n", vmexit->inst_length);
416 	fprintf(stderr, "\tstatus\t\t%d\n", vmexit->u.vmx.status);
417 	fprintf(stderr, "\texit_reason\t%u\n", vmexit->u.vmx.exit_reason);
418 	fprintf(stderr, "\tqualification\t0x%016lx\n",
419 	    vmexit->u.vmx.exit_qualification);
420 	fprintf(stderr, "\tinst_type\t\t%d\n", vmexit->u.vmx.inst_type);
421 	fprintf(stderr, "\tinst_error\t\t%d\n", vmexit->u.vmx.inst_error);
422 #ifdef DEBUG_EPT_MISCONFIG
423 	if (vmexit->u.vmx.exit_reason == EXIT_REASON_EPT_MISCONFIG) {
424 		vm_get_register(ctx, *pvcpu,
425 		    VMCS_IDENT(VMCS_GUEST_PHYSICAL_ADDRESS),
426 		    &ept_misconfig_gpa);
427 		vm_get_gpa_pmap(ctx, ept_misconfig_gpa, ept_misconfig_pte,
428 		    &ept_misconfig_ptenum);
429 		fprintf(stderr, "\tEPT misconfiguration:\n");
430 		fprintf(stderr, "\t\tGPA: %#lx\n", ept_misconfig_gpa);
431 		fprintf(stderr, "\t\tPTE(%d): %#lx %#lx %#lx %#lx\n",
432 		    ept_misconfig_ptenum, ept_misconfig_pte[0],
433 		    ept_misconfig_pte[1], ept_misconfig_pte[2],
434 		    ept_misconfig_pte[3]);
435 	}
436 #endif	/* DEBUG_EPT_MISCONFIG */
437 	return (VMEXIT_ABORT);
438 }
439 
440 static int
441 vmexit_svm(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
442 {
443 
444 	fprintf(stderr, "vm exit[%d]\n", *pvcpu);
445 	fprintf(stderr, "\treason\t\tSVM\n");
446 	fprintf(stderr, "\trip\t\t0x%016lx\n", vmexit->rip);
447 	fprintf(stderr, "\tinst_length\t%d\n", vmexit->inst_length);
448 	fprintf(stderr, "\texitcode\t%#lx\n", vmexit->u.svm.exitcode);
449 	fprintf(stderr, "\texitinfo1\t%#lx\n", vmexit->u.svm.exitinfo1);
450 	fprintf(stderr, "\texitinfo2\t%#lx\n", vmexit->u.svm.exitinfo2);
451 	return (VMEXIT_ABORT);
452 }
453 
454 static int
455 vmexit_bogus(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
456 {
457 
458 	assert(vmexit->inst_length == 0);
459 
460 	stats.vmexit_bogus++;
461 
462 	return (VMEXIT_CONTINUE);
463 }
464 
465 static int
466 vmexit_reqidle(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
467 {
468 
469 	assert(vmexit->inst_length == 0);
470 
471 	stats.vmexit_reqidle++;
472 
473 	return (VMEXIT_CONTINUE);
474 }
475 
476 static int
477 vmexit_hlt(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
478 {
479 
480 	stats.vmexit_hlt++;
481 
482 	/*
483 	 * Just continue execution with the next instruction. We use
484 	 * the HLT VM exit as a way to be friendly with the host
485 	 * scheduler.
486 	 */
487 	return (VMEXIT_CONTINUE);
488 }
489 
490 static int
491 vmexit_pause(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
492 {
493 
494 	stats.vmexit_pause++;
495 
496 	return (VMEXIT_CONTINUE);
497 }
498 
499 static int
500 vmexit_mtrap(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
501 {
502 
503 	assert(vmexit->inst_length == 0);
504 
505 	stats.vmexit_mtrap++;
506 
507 	return (VMEXIT_CONTINUE);
508 }
509 
510 static int
511 vmexit_inst_emul(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
512 {
513 	int err, i;
514 	struct vie *vie;
515 
516 	stats.vmexit_inst_emul++;
517 
518 	vie = &vmexit->u.inst_emul.vie;
519 	err = emulate_mem(ctx, *pvcpu, vmexit->u.inst_emul.gpa,
520 	    vie, &vmexit->u.inst_emul.paging);
521 
522 	if (err) {
523 		if (err == ESRCH) {
524 			fprintf(stderr, "Unhandled memory access to 0x%lx\n",
525 			    vmexit->u.inst_emul.gpa);
526 		}
527 
528 		fprintf(stderr, "Failed to emulate instruction [");
529 		for (i = 0; i < vie->num_valid; i++) {
530 			fprintf(stderr, "0x%02x%s", vie->inst[i],
531 			    i != (vie->num_valid - 1) ? " " : "");
532 		}
533 		fprintf(stderr, "] at 0x%lx\n", vmexit->rip);
534 		return (VMEXIT_ABORT);
535 	}
536 
537 	return (VMEXIT_CONTINUE);
538 }
539 
540 static pthread_mutex_t resetcpu_mtx = PTHREAD_MUTEX_INITIALIZER;
541 static pthread_cond_t resetcpu_cond = PTHREAD_COND_INITIALIZER;
542 
543 static int
544 vmexit_suspend(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
545 {
546 	enum vm_suspend_how how;
547 
548 	how = vmexit->u.suspended.how;
549 
550 	fbsdrun_deletecpu(ctx, *pvcpu);
551 
552 	if (*pvcpu != BSP) {
553 		pthread_mutex_lock(&resetcpu_mtx);
554 		pthread_cond_signal(&resetcpu_cond);
555 		pthread_mutex_unlock(&resetcpu_mtx);
556 		pthread_exit(NULL);
557 	}
558 
559 	pthread_mutex_lock(&resetcpu_mtx);
560 	while (!CPU_EMPTY(&cpumask)) {
561 		pthread_cond_wait(&resetcpu_cond, &resetcpu_mtx);
562 	}
563 	pthread_mutex_unlock(&resetcpu_mtx);
564 
565 	switch (how) {
566 	case VM_SUSPEND_RESET:
567 		exit(0);
568 	case VM_SUSPEND_POWEROFF:
569 		exit(1);
570 	case VM_SUSPEND_HALT:
571 		exit(2);
572 	case VM_SUSPEND_TRIPLEFAULT:
573 		exit(3);
574 	default:
575 		fprintf(stderr, "vmexit_suspend: invalid reason %d\n", how);
576 		exit(100);
577 	}
578 	return (0);	/* NOTREACHED */
579 }
580 
581 static vmexit_handler_t handler[VM_EXITCODE_MAX] = {
582 	[VM_EXITCODE_INOUT]  = vmexit_inout,
583 	[VM_EXITCODE_INOUT_STR]  = vmexit_inout,
584 	[VM_EXITCODE_VMX]    = vmexit_vmx,
585 	[VM_EXITCODE_SVM]    = vmexit_svm,
586 	[VM_EXITCODE_BOGUS]  = vmexit_bogus,
587 	[VM_EXITCODE_REQIDLE] = vmexit_reqidle,
588 	[VM_EXITCODE_RDMSR]  = vmexit_rdmsr,
589 	[VM_EXITCODE_WRMSR]  = vmexit_wrmsr,
590 	[VM_EXITCODE_MTRAP]  = vmexit_mtrap,
591 	[VM_EXITCODE_INST_EMUL] = vmexit_inst_emul,
592 	[VM_EXITCODE_SPINUP_AP] = vmexit_spinup_ap,
593 	[VM_EXITCODE_SUSPENDED] = vmexit_suspend,
594 	[VM_EXITCODE_TASK_SWITCH] = vmexit_task_switch,
595 };
596 
597 static void
598 vm_loop(struct vmctx *ctx, int vcpu, uint64_t startrip)
599 {
600 	int error, rc;
601 	enum vm_exitcode exitcode;
602 	cpuset_t active_cpus;
603 
604 	if (vcpumap[vcpu] != NULL) {
605 		error = pthread_setaffinity_np(pthread_self(),
606 		    sizeof(cpuset_t), vcpumap[vcpu]);
607 		assert(error == 0);
608 	}
609 
610 	error = vm_active_cpus(ctx, &active_cpus);
611 	assert(CPU_ISSET(vcpu, &active_cpus));
612 
613 	error = vm_set_register(ctx, vcpu, VM_REG_GUEST_RIP, startrip);
614 	assert(error == 0);
615 
616 	while (1) {
617 		error = vm_run(ctx, vcpu, &vmexit[vcpu]);
618 		if (error != 0)
619 			break;
620 
621 		exitcode = vmexit[vcpu].exitcode;
622 		if (exitcode >= VM_EXITCODE_MAX || handler[exitcode] == NULL) {
623 			fprintf(stderr, "vm_loop: unexpected exitcode 0x%x\n",
624 			    exitcode);
625 			exit(1);
626 		}
627 
628 		rc = (*handler[exitcode])(ctx, &vmexit[vcpu], &vcpu);
629 
630 		switch (rc) {
631 		case VMEXIT_CONTINUE:
632 			break;
633 		case VMEXIT_ABORT:
634 			abort();
635 		default:
636 			exit(1);
637 		}
638 	}
639 	fprintf(stderr, "vm_run error %d, errno %d\n", error, errno);
640 }
641 
642 static int
643 num_vcpus_allowed(struct vmctx *ctx)
644 {
645 	int tmp, error;
646 
647 	error = vm_get_capability(ctx, BSP, VM_CAP_UNRESTRICTED_GUEST, &tmp);
648 
649 	/*
650 	 * The guest is allowed to spinup more than one processor only if the
651 	 * UNRESTRICTED_GUEST capability is available.
652 	 */
653 	if (error == 0)
654 		return (VM_MAXCPU);
655 	else
656 		return (1);
657 }
658 
659 void
660 fbsdrun_set_capabilities(struct vmctx *ctx, int cpu)
661 {
662 	int err, tmp;
663 
664 	if (fbsdrun_vmexit_on_hlt()) {
665 		err = vm_get_capability(ctx, cpu, VM_CAP_HALT_EXIT, &tmp);
666 		if (err < 0) {
667 			fprintf(stderr, "VM exit on HLT not supported\n");
668 			exit(1);
669 		}
670 		vm_set_capability(ctx, cpu, VM_CAP_HALT_EXIT, 1);
671 		if (cpu == BSP)
672 			handler[VM_EXITCODE_HLT] = vmexit_hlt;
673 	}
674 
675         if (fbsdrun_vmexit_on_pause()) {
676 		/*
677 		 * pause exit support required for this mode
678 		 */
679 		err = vm_get_capability(ctx, cpu, VM_CAP_PAUSE_EXIT, &tmp);
680 		if (err < 0) {
681 			fprintf(stderr,
682 			    "SMP mux requested, no pause support\n");
683 			exit(1);
684 		}
685 		vm_set_capability(ctx, cpu, VM_CAP_PAUSE_EXIT, 1);
686 		if (cpu == BSP)
687 			handler[VM_EXITCODE_PAUSE] = vmexit_pause;
688         }
689 
690 	if (x2apic_mode)
691 		err = vm_set_x2apic_state(ctx, cpu, X2APIC_ENABLED);
692 	else
693 		err = vm_set_x2apic_state(ctx, cpu, X2APIC_DISABLED);
694 
695 	if (err) {
696 		fprintf(stderr, "Unable to set x2apic state (%d)\n", err);
697 		exit(1);
698 	}
699 
700 	vm_set_capability(ctx, cpu, VM_CAP_ENABLE_INVPCID, 1);
701 }
702 
703 static struct vmctx *
704 do_open(const char *vmname)
705 {
706 	struct vmctx *ctx;
707 	int error;
708 	bool reinit, romboot;
709 
710 	reinit = romboot = false;
711 
712 	if (lpc_bootrom())
713 		romboot = true;
714 
715 	error = vm_create(vmname);
716 	if (error) {
717 		if (errno == EEXIST) {
718 			if (romboot) {
719 				reinit = true;
720 			} else {
721 				/*
722 				 * The virtual machine has been setup by the
723 				 * userspace bootloader.
724 				 */
725 			}
726 		} else {
727 			perror("vm_create");
728 			exit(1);
729 		}
730 	} else {
731 		if (!romboot) {
732 			/*
733 			 * If the virtual machine was just created then a
734 			 * bootrom must be configured to boot it.
735 			 */
736 			fprintf(stderr, "virtual machine cannot be booted\n");
737 			exit(1);
738 		}
739 	}
740 
741 	ctx = vm_open(vmname);
742 	if (ctx == NULL) {
743 		perror("vm_open");
744 		exit(1);
745 	}
746 
747 	if (reinit) {
748 		error = vm_reinit(ctx);
749 		if (error) {
750 			perror("vm_reinit");
751 			exit(1);
752 		}
753 	}
754 	return (ctx);
755 }
756 
757 int
758 main(int argc, char *argv[])
759 {
760 	int c, error, gdb_port, err, bvmcons;
761 	int max_vcpus, mptgen, memflags;
762 	int rtc_localtime;
763 	struct vmctx *ctx;
764 	uint64_t rip;
765 	size_t memsize;
766 	char *optstr;
767 
768 	bvmcons = 0;
769 	progname = basename(argv[0]);
770 	gdb_port = 0;
771 	guest_ncpus = 1;
772 	memsize = 256 * MB;
773 	mptgen = 1;
774 	rtc_localtime = 1;
775 	memflags = 0;
776 
777 	optstr = "abehuwxACHIPSWYp:g:c:s:m:l:U:";
778 	while ((c = getopt(argc, argv, optstr)) != -1) {
779 		switch (c) {
780 		case 'a':
781 			x2apic_mode = 0;
782 			break;
783 		case 'A':
784 			acpi = 1;
785 			break;
786 		case 'b':
787 			bvmcons = 1;
788 			break;
789 		case 'p':
790                         if (pincpu_parse(optarg) != 0) {
791                             errx(EX_USAGE, "invalid vcpu pinning "
792                                  "configuration '%s'", optarg);
793                         }
794 			break;
795                 case 'c':
796 			guest_ncpus = atoi(optarg);
797 			break;
798 		case 'C':
799 			memflags |= VM_MEM_F_INCORE;
800 			break;
801 		case 'g':
802 			gdb_port = atoi(optarg);
803 			break;
804 		case 'l':
805 			if (lpc_device_parse(optarg) != 0) {
806 				errx(EX_USAGE, "invalid lpc device "
807 				    "configuration '%s'", optarg);
808 			}
809 			break;
810 		case 's':
811 			if (pci_parse_slot(optarg) != 0)
812 				exit(1);
813 			else
814 				break;
815 		case 'S':
816 			memflags |= VM_MEM_F_WIRED;
817 			break;
818                 case 'm':
819 			error = vm_parse_memsize(optarg, &memsize);
820 			if (error)
821 				errx(EX_USAGE, "invalid memsize '%s'", optarg);
822 			break;
823 		case 'H':
824 			guest_vmexit_on_hlt = 1;
825 			break;
826 		case 'I':
827 			/*
828 			 * The "-I" option was used to add an ioapic to the
829 			 * virtual machine.
830 			 *
831 			 * An ioapic is now provided unconditionally for each
832 			 * virtual machine and this option is now deprecated.
833 			 */
834 			break;
835 		case 'P':
836 			guest_vmexit_on_pause = 1;
837 			break;
838 		case 'e':
839 			strictio = 1;
840 			break;
841 		case 'u':
842 			rtc_localtime = 0;
843 			break;
844 		case 'U':
845 			guest_uuid_str = optarg;
846 			break;
847 		case 'w':
848 			strictmsr = 0;
849 			break;
850 		case 'W':
851 			virtio_msix = 0;
852 			break;
853 		case 'x':
854 			x2apic_mode = 1;
855 			break;
856 		case 'Y':
857 			mptgen = 0;
858 			break;
859 		case 'h':
860 			usage(0);
861 		default:
862 			usage(1);
863 		}
864 	}
865 	argc -= optind;
866 	argv += optind;
867 
868 	if (argc != 1)
869 		usage(1);
870 
871 	vmname = argv[0];
872 	ctx = do_open(vmname);
873 
874 	if (guest_ncpus < 1) {
875 		fprintf(stderr, "Invalid guest vCPUs (%d)\n", guest_ncpus);
876 		exit(1);
877 	}
878 
879 	max_vcpus = num_vcpus_allowed(ctx);
880 	if (guest_ncpus > max_vcpus) {
881 		fprintf(stderr, "%d vCPUs requested but only %d available\n",
882 			guest_ncpus, max_vcpus);
883 		exit(1);
884 	}
885 
886 	fbsdrun_set_capabilities(ctx, BSP);
887 
888 	vm_set_memflags(ctx, memflags);
889 	err = vm_setup_memory(ctx, memsize, VM_MMAP_ALL);
890 	if (err) {
891 		fprintf(stderr, "Unable to setup memory (%d)\n", errno);
892 		exit(1);
893 	}
894 
895 	error = init_msr();
896 	if (error) {
897 		fprintf(stderr, "init_msr error %d", error);
898 		exit(1);
899 	}
900 
901 	init_mem();
902 	init_inout();
903 	atkbdc_init(ctx);
904 	pci_irq_init(ctx);
905 	ioapic_init(ctx);
906 
907 	rtc_init(ctx, rtc_localtime);
908 	sci_init(ctx);
909 
910 	/*
911 	 * Exit if a device emulation finds an error in it's initilization
912 	 */
913 	if (init_pci(ctx) != 0)
914 		exit(1);
915 
916 	if (gdb_port != 0)
917 		init_dbgport(gdb_port);
918 
919 	if (bvmcons)
920 		init_bvmcons();
921 
922 	if (lpc_bootrom()) {
923 		if (vm_set_capability(ctx, BSP, VM_CAP_UNRESTRICTED_GUEST, 1)) {
924 			fprintf(stderr, "ROM boot failed: unrestricted guest "
925 			    "capability not available\n");
926 			exit(1);
927 		}
928 		error = vcpu_reset(ctx, BSP);
929 		assert(error == 0);
930 	}
931 
932 	error = vm_get_register(ctx, BSP, VM_REG_GUEST_RIP, &rip);
933 	assert(error == 0);
934 
935 	/*
936 	 * build the guest tables, MP etc.
937 	 */
938 	if (mptgen) {
939 		error = mptable_build(ctx, guest_ncpus);
940 		if (error)
941 			exit(1);
942 	}
943 
944 	error = smbios_build(ctx);
945 	assert(error == 0);
946 
947 	if (acpi) {
948 		error = acpi_build(ctx, guest_ncpus);
949 		assert(error == 0);
950 	}
951 
952 	if (lpc_bootrom())
953 		fwctl_init();
954 
955 	/*
956 	 * Change the proc title to include the VM name.
957 	 */
958 	setproctitle("%s", vmname);
959 
960 	/*
961 	 * Add CPU 0
962 	 */
963 	fbsdrun_addcpu(ctx, BSP, BSP, rip);
964 
965 	/*
966 	 * Head off to the main event dispatch loop
967 	 */
968 	mevent_dispatch();
969 
970 	exit(1);
971 }
972