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