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