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