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