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