]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/amd64/vmm/vmm.c
vmm: Expose struct vcpu as an opaque type.
[FreeBSD/FreeBSD.git] / sys / amd64 / vmm / vmm.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 "opt_bhyve_snapshot.h"
35
36 #include <sys/param.h>
37 #include <sys/systm.h>
38 #include <sys/kernel.h>
39 #include <sys/module.h>
40 #include <sys/sysctl.h>
41 #include <sys/malloc.h>
42 #include <sys/pcpu.h>
43 #include <sys/lock.h>
44 #include <sys/mutex.h>
45 #include <sys/proc.h>
46 #include <sys/rwlock.h>
47 #include <sys/sched.h>
48 #include <sys/smp.h>
49 #include <sys/vnode.h>
50
51 #include <vm/vm.h>
52 #include <vm/vm_param.h>
53 #include <vm/vm_extern.h>
54 #include <vm/vm_object.h>
55 #include <vm/vm_page.h>
56 #include <vm/pmap.h>
57 #include <vm/vm_map.h>
58 #include <vm/vm_pager.h>
59 #include <vm/vm_kern.h>
60 #include <vm/vnode_pager.h>
61 #include <vm/swap_pager.h>
62 #include <vm/uma.h>
63
64 #include <machine/cpu.h>
65 #include <machine/pcb.h>
66 #include <machine/smp.h>
67 #include <machine/md_var.h>
68 #include <x86/psl.h>
69 #include <x86/apicreg.h>
70 #include <x86/ifunc.h>
71
72 #include <machine/vmm.h>
73 #include <machine/vmm_dev.h>
74 #include <machine/vmm_instruction_emul.h>
75 #include <machine/vmm_snapshot.h>
76
77 #include "vmm_ioport.h"
78 #include "vmm_ktr.h"
79 #include "vmm_host.h"
80 #include "vmm_mem.h"
81 #include "vmm_util.h"
82 #include "vatpic.h"
83 #include "vatpit.h"
84 #include "vhpet.h"
85 #include "vioapic.h"
86 #include "vlapic.h"
87 #include "vpmtmr.h"
88 #include "vrtc.h"
89 #include "vmm_stat.h"
90 #include "vmm_lapic.h"
91
92 #include "io/ppt.h"
93 #include "io/iommu.h"
94
95 struct vlapic;
96
97 /*
98  * Initialization:
99  * (a) allocated when vcpu is created
100  * (i) initialized when vcpu is created and when it is reinitialized
101  * (o) initialized the first time the vcpu is created
102  * (x) initialized before use
103  */
104 struct vcpu {
105         struct mtx      mtx;            /* (o) protects 'state' and 'hostcpu' */
106         enum vcpu_state state;          /* (o) vcpu state */
107         int             vcpuid;         /* (o) */
108         int             hostcpu;        /* (o) vcpu's host cpu */
109         int             reqidle;        /* (i) request vcpu to idle */
110         struct vm       *vm;            /* (o) */
111         void            *cookie;        /* (i) cpu-specific data */
112         struct vlapic   *vlapic;        /* (i) APIC device model */
113         enum x2apic_state x2apic_state; /* (i) APIC mode */
114         uint64_t        exitintinfo;    /* (i) events pending at VM exit */
115         int             nmi_pending;    /* (i) NMI pending */
116         int             extint_pending; /* (i) INTR pending */
117         int     exception_pending;      /* (i) exception pending */
118         int     exc_vector;             /* (x) exception collateral */
119         int     exc_errcode_valid;
120         uint32_t exc_errcode;
121         struct savefpu  *guestfpu;      /* (a,i) guest fpu state */
122         uint64_t        guest_xcr0;     /* (i) guest %xcr0 register */
123         void            *stats;         /* (a,i) statistics */
124         struct vm_exit  exitinfo;       /* (x) exit reason and collateral */
125         uint64_t        nextrip;        /* (x) next instruction to execute */
126         uint64_t        tsc_offset;     /* (o) TSC offsetting */
127 };
128
129 #define vcpu_lock_initialized(v) mtx_initialized(&((v)->mtx))
130 #define vcpu_lock_init(v)       mtx_init(&((v)->mtx), "vcpu lock", 0, MTX_SPIN)
131 #define vcpu_lock(v)            mtx_lock_spin(&((v)->mtx))
132 #define vcpu_unlock(v)          mtx_unlock_spin(&((v)->mtx))
133 #define vcpu_assert_locked(v)   mtx_assert(&((v)->mtx), MA_OWNED)
134
135 struct mem_seg {
136         size_t  len;
137         bool    sysmem;
138         struct vm_object *object;
139 };
140 #define VM_MAX_MEMSEGS  4
141
142 struct mem_map {
143         vm_paddr_t      gpa;
144         size_t          len;
145         vm_ooffset_t    segoff;
146         int             segid;
147         int             prot;
148         int             flags;
149 };
150 #define VM_MAX_MEMMAPS  8
151
152 /*
153  * Initialization:
154  * (o) initialized the first time the VM is created
155  * (i) initialized when VM is created and when it is reinitialized
156  * (x) initialized before use
157  */
158 struct vm {
159         void            *cookie;                /* (i) cpu-specific data */
160         void            *iommu;                 /* (x) iommu-specific data */
161         struct vhpet    *vhpet;                 /* (i) virtual HPET */
162         struct vioapic  *vioapic;               /* (i) virtual ioapic */
163         struct vatpic   *vatpic;                /* (i) virtual atpic */
164         struct vatpit   *vatpit;                /* (i) virtual atpit */
165         struct vpmtmr   *vpmtmr;                /* (i) virtual ACPI PM timer */
166         struct vrtc     *vrtc;                  /* (o) virtual RTC */
167         volatile cpuset_t active_cpus;          /* (i) active vcpus */
168         volatile cpuset_t debug_cpus;           /* (i) vcpus stopped for debug */
169         int             suspend;                /* (i) stop VM execution */
170         volatile cpuset_t suspended_cpus;       /* (i) suspended vcpus */
171         volatile cpuset_t halted_cpus;          /* (x) cpus in a hard halt */
172         cpuset_t        rendezvous_req_cpus;    /* (x) rendezvous requested */
173         cpuset_t        rendezvous_done_cpus;   /* (x) rendezvous finished */
174         void            *rendezvous_arg;        /* (x) rendezvous func/arg */
175         vm_rendezvous_func_t rendezvous_func;
176         struct mtx      rendezvous_mtx;         /* (o) rendezvous lock */
177         struct mem_map  mem_maps[VM_MAX_MEMMAPS]; /* (i) guest address space */
178         struct mem_seg  mem_segs[VM_MAX_MEMSEGS]; /* (o) guest memory regions */
179         struct vmspace  *vmspace;               /* (o) guest's address space */
180         char            name[VM_MAX_NAMELEN+1]; /* (o) virtual machine name */
181         struct vcpu     vcpu[VM_MAXCPU];        /* (i) guest vcpus */
182         /* The following describe the vm cpu topology */
183         uint16_t        sockets;                /* (o) num of sockets */
184         uint16_t        cores;                  /* (o) num of cores/socket */
185         uint16_t        threads;                /* (o) num of threads/core */
186         uint16_t        maxcpus;                /* (o) max pluggable cpus */
187 };
188
189 #define VMM_CTR0(vcpu, format)                                          \
190         VCPU_CTR0((vcpu)->vm, (vcpu)->vcpuid, format)
191
192 #define VMM_CTR1(vcpu, format, p1)                                      \
193         VCPU_CTR1((vcpu)->vm, (vcpu)->vcpuid, format, p1)
194
195 #define VMM_CTR2(vcpu, format, p1, p2)                                  \
196         VCPU_CTR2((vcpu)->vm, (vcpu)->vcpuid, format, p1, p2)
197
198 #define VMM_CTR3(vcpu, format, p1, p2, p3)                              \
199         VCPU_CTR3((vcpu)->vm, (vcpu)->vcpuid, format, p1, p2, p3)
200
201 #define VMM_CTR4(vcpu, format, p1, p2, p3, p4)                          \
202         VCPU_CTR4((vcpu)->vm, (vcpu)->vcpuid, format, p1, p2, p3, p4)
203
204 static int vmm_initialized;
205
206 static void     vmmops_panic(void);
207
208 static void
209 vmmops_panic(void)
210 {
211         panic("vmm_ops func called when !vmm_is_intel() && !vmm_is_svm()");
212 }
213
214 #define DEFINE_VMMOPS_IFUNC(ret_type, opname, args)                     \
215     DEFINE_IFUNC(static, ret_type, vmmops_##opname, args)               \
216     {                                                                   \
217         if (vmm_is_intel())                                             \
218                 return (vmm_ops_intel.opname);                          \
219         else if (vmm_is_svm())                                          \
220                 return (vmm_ops_amd.opname);                            \
221         else                                                            \
222                 return ((ret_type (*)args)vmmops_panic);                \
223     }
224
225 DEFINE_VMMOPS_IFUNC(int, modinit, (int ipinum))
226 DEFINE_VMMOPS_IFUNC(int, modcleanup, (void))
227 DEFINE_VMMOPS_IFUNC(void, modresume, (void))
228 DEFINE_VMMOPS_IFUNC(void *, init, (struct vm *vm, struct pmap *pmap))
229 DEFINE_VMMOPS_IFUNC(int, run, (void *vcpui, register_t rip, struct pmap *pmap,
230     struct vm_eventinfo *info))
231 DEFINE_VMMOPS_IFUNC(void, cleanup, (void *vmi))
232 DEFINE_VMMOPS_IFUNC(void *, vcpu_init, (void *vmi, struct vcpu *vcpu,
233     int vcpu_id))
234 DEFINE_VMMOPS_IFUNC(void, vcpu_cleanup, (void *vcpui))
235 DEFINE_VMMOPS_IFUNC(int, getreg, (void *vcpui, int num, uint64_t *retval))
236 DEFINE_VMMOPS_IFUNC(int, setreg, (void *vcpui, int num, uint64_t val))
237 DEFINE_VMMOPS_IFUNC(int, getdesc, (void *vcpui, int num, struct seg_desc *desc))
238 DEFINE_VMMOPS_IFUNC(int, setdesc, (void *vcpui, int num, struct seg_desc *desc))
239 DEFINE_VMMOPS_IFUNC(int, getcap, (void *vcpui, int num, int *retval))
240 DEFINE_VMMOPS_IFUNC(int, setcap, (void *vcpui, int num, int val))
241 DEFINE_VMMOPS_IFUNC(struct vmspace *, vmspace_alloc, (vm_offset_t min,
242     vm_offset_t max))
243 DEFINE_VMMOPS_IFUNC(void, vmspace_free, (struct vmspace *vmspace))
244 DEFINE_VMMOPS_IFUNC(struct vlapic *, vlapic_init, (void *vcpui))
245 DEFINE_VMMOPS_IFUNC(void, vlapic_cleanup, (struct vlapic *vlapic))
246 #ifdef BHYVE_SNAPSHOT
247 DEFINE_VMMOPS_IFUNC(int, snapshot, (void *vmi, struct vm_snapshot_meta *meta))
248 DEFINE_VMMOPS_IFUNC(int, vcpu_snapshot, (void *vcpui,
249     struct vm_snapshot_meta *meta))
250 DEFINE_VMMOPS_IFUNC(int, restore_tsc, (void *vcpui, uint64_t now))
251 #endif
252
253 #define fpu_start_emulating()   load_cr0(rcr0() | CR0_TS)
254 #define fpu_stop_emulating()    clts()
255
256 SDT_PROVIDER_DEFINE(vmm);
257
258 static MALLOC_DEFINE(M_VM, "vm", "vm");
259
260 /* statistics */
261 static VMM_STAT(VCPU_TOTAL_RUNTIME, "vcpu total runtime");
262
263 SYSCTL_NODE(_hw, OID_AUTO, vmm, CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
264     NULL);
265
266 /*
267  * Halt the guest if all vcpus are executing a HLT instruction with
268  * interrupts disabled.
269  */
270 static int halt_detection_enabled = 1;
271 SYSCTL_INT(_hw_vmm, OID_AUTO, halt_detection, CTLFLAG_RDTUN,
272     &halt_detection_enabled, 0,
273     "Halt VM if all vcpus execute HLT with interrupts disabled");
274
275 static int vmm_ipinum;
276 SYSCTL_INT(_hw_vmm, OID_AUTO, ipinum, CTLFLAG_RD, &vmm_ipinum, 0,
277     "IPI vector used for vcpu notifications");
278
279 static int trace_guest_exceptions;
280 SYSCTL_INT(_hw_vmm, OID_AUTO, trace_guest_exceptions, CTLFLAG_RDTUN,
281     &trace_guest_exceptions, 0,
282     "Trap into hypervisor on all guest exceptions and reflect them back");
283
284 static int trap_wbinvd;
285 SYSCTL_INT(_hw_vmm, OID_AUTO, trap_wbinvd, CTLFLAG_RDTUN, &trap_wbinvd, 0,
286     "WBINVD triggers a VM-exit");
287
288 static void vm_free_memmap(struct vm *vm, int ident);
289 static bool sysmem_mapping(struct vm *vm, struct mem_map *mm);
290 static void vcpu_notify_event_locked(struct vcpu *vcpu, bool lapic_intr);
291
292 #ifdef KTR
293 static const char *
294 vcpu_state2str(enum vcpu_state state)
295 {
296
297         switch (state) {
298         case VCPU_IDLE:
299                 return ("idle");
300         case VCPU_FROZEN:
301                 return ("frozen");
302         case VCPU_RUNNING:
303                 return ("running");
304         case VCPU_SLEEPING:
305                 return ("sleeping");
306         default:
307                 return ("unknown");
308         }
309 }
310 #endif
311
312 static __inline void *
313 vcpu_cookie(struct vm *vm, int i)
314 {
315         return (vm->vcpu[i].cookie);
316 }
317                 
318 static void
319 vcpu_cleanup(struct vm *vm, int i, bool destroy)
320 {
321         struct vcpu *vcpu = &vm->vcpu[i];
322
323         vmmops_vlapic_cleanup(vcpu->vlapic);
324         vmmops_vcpu_cleanup(vcpu->cookie);
325         vcpu->cookie = NULL;
326         if (destroy) {
327                 vmm_stat_free(vcpu->stats);     
328                 fpu_save_area_free(vcpu->guestfpu);
329         }
330 }
331
332 static void
333 vcpu_init(struct vm *vm, int vcpu_id, bool create)
334 {
335         struct vcpu *vcpu;
336
337         KASSERT(vcpu_id >= 0 && vcpu_id < vm->maxcpus,
338             ("vcpu_init: invalid vcpu %d", vcpu_id));
339           
340         vcpu = &vm->vcpu[vcpu_id];
341
342         if (create) {
343                 KASSERT(!vcpu_lock_initialized(vcpu), ("vcpu %d already "
344                     "initialized", vcpu_id));
345                 vcpu_lock_init(vcpu);
346                 vcpu->state = VCPU_IDLE;
347                 vcpu->hostcpu = NOCPU;
348                 vcpu->vcpuid = vcpu_id;
349                 vcpu->vm = vm;
350                 vcpu->guestfpu = fpu_save_area_alloc();
351                 vcpu->stats = vmm_stat_alloc();
352                 vcpu->tsc_offset = 0;
353         }
354
355         vcpu->cookie = vmmops_vcpu_init(vm->cookie, vcpu, vcpu_id);
356         vcpu->vlapic = vmmops_vlapic_init(vcpu->cookie);
357         vm_set_x2apic_state(vm, vcpu_id, X2APIC_DISABLED);
358         vcpu->reqidle = 0;
359         vcpu->exitintinfo = 0;
360         vcpu->nmi_pending = 0;
361         vcpu->extint_pending = 0;
362         vcpu->exception_pending = 0;
363         vcpu->guest_xcr0 = XFEATURE_ENABLED_X87;
364         fpu_save_area_reset(vcpu->guestfpu);
365         vmm_stat_init(vcpu->stats);
366 }
367
368 int
369 vcpu_trace_exceptions(struct vm *vm, int vcpuid)
370 {
371
372         return (trace_guest_exceptions);
373 }
374
375 int
376 vcpu_trap_wbinvd(struct vm *vm, int vcpuid)
377 {
378         return (trap_wbinvd);
379 }
380
381 struct vm_exit *
382 vm_exitinfo(struct vm *vm, int cpuid)
383 {
384         struct vcpu *vcpu;
385
386         if (cpuid < 0 || cpuid >= vm->maxcpus)
387                 panic("vm_exitinfo: invalid cpuid %d", cpuid);
388
389         vcpu = &vm->vcpu[cpuid];
390
391         return (&vcpu->exitinfo);
392 }
393
394 static int
395 vmm_init(void)
396 {
397         int error;
398
399         if (!vmm_is_hw_supported())
400                 return (ENXIO);
401
402         vmm_host_state_init();
403
404         vmm_ipinum = lapic_ipi_alloc(pti ? &IDTVEC(justreturn1_pti) :
405             &IDTVEC(justreturn));
406         if (vmm_ipinum < 0)
407                 vmm_ipinum = IPI_AST;
408
409         error = vmm_mem_init();
410         if (error)
411                 return (error);
412
413         vmm_resume_p = vmmops_modresume;
414
415         return (vmmops_modinit(vmm_ipinum));
416 }
417
418 static int
419 vmm_handler(module_t mod, int what, void *arg)
420 {
421         int error;
422
423         switch (what) {
424         case MOD_LOAD:
425                 if (vmm_is_hw_supported()) {
426                         vmmdev_init();
427                         error = vmm_init();
428                         if (error == 0)
429                                 vmm_initialized = 1;
430                 } else {
431                         error = ENXIO;
432                 }
433                 break;
434         case MOD_UNLOAD:
435                 if (vmm_is_hw_supported()) {
436                         error = vmmdev_cleanup();
437                         if (error == 0) {
438                                 vmm_resume_p = NULL;
439                                 iommu_cleanup();
440                                 if (vmm_ipinum != IPI_AST)
441                                         lapic_ipi_free(vmm_ipinum);
442                                 error = vmmops_modcleanup();
443                                 /*
444                                  * Something bad happened - prevent new
445                                  * VMs from being created
446                                  */
447                                 if (error)
448                                         vmm_initialized = 0;
449                         }
450                 } else {
451                         error = 0;
452                 }
453                 break;
454         default:
455                 error = 0;
456                 break;
457         }
458         return (error);
459 }
460
461 static moduledata_t vmm_kmod = {
462         "vmm",
463         vmm_handler,
464         NULL
465 };
466
467 /*
468  * vmm initialization has the following dependencies:
469  *
470  * - VT-x initialization requires smp_rendezvous() and therefore must happen
471  *   after SMP is fully functional (after SI_SUB_SMP).
472  */
473 DECLARE_MODULE(vmm, vmm_kmod, SI_SUB_SMP + 1, SI_ORDER_ANY);
474 MODULE_VERSION(vmm, 1);
475
476 static void
477 vm_init(struct vm *vm, bool create)
478 {
479         int i;
480
481         vm->cookie = vmmops_init(vm, vmspace_pmap(vm->vmspace));
482         vm->iommu = NULL;
483         vm->vioapic = vioapic_init(vm);
484         vm->vhpet = vhpet_init(vm);
485         vm->vatpic = vatpic_init(vm);
486         vm->vatpit = vatpit_init(vm);
487         vm->vpmtmr = vpmtmr_init(vm);
488         if (create)
489                 vm->vrtc = vrtc_init(vm);
490
491         CPU_ZERO(&vm->active_cpus);
492         CPU_ZERO(&vm->debug_cpus);
493
494         vm->suspend = 0;
495         CPU_ZERO(&vm->suspended_cpus);
496
497         for (i = 0; i < vm->maxcpus; i++)
498                 vcpu_init(vm, i, create);
499 }
500
501 /*
502  * The default CPU topology is a single thread per package.
503  */
504 u_int cores_per_package = 1;
505 u_int threads_per_core = 1;
506
507 int
508 vm_create(const char *name, struct vm **retvm)
509 {
510         struct vm *vm;
511         struct vmspace *vmspace;
512
513         /*
514          * If vmm.ko could not be successfully initialized then don't attempt
515          * to create the virtual machine.
516          */
517         if (!vmm_initialized)
518                 return (ENXIO);
519
520         if (name == NULL || strnlen(name, VM_MAX_NAMELEN + 1) ==
521             VM_MAX_NAMELEN + 1)
522                 return (EINVAL);
523
524         vmspace = vmmops_vmspace_alloc(0, VM_MAXUSER_ADDRESS_LA48);
525         if (vmspace == NULL)
526                 return (ENOMEM);
527
528         vm = malloc(sizeof(struct vm), M_VM, M_WAITOK | M_ZERO);
529         strcpy(vm->name, name);
530         vm->vmspace = vmspace;
531         mtx_init(&vm->rendezvous_mtx, "vm rendezvous lock", 0, MTX_DEF);
532
533         vm->sockets = 1;
534         vm->cores = cores_per_package;  /* XXX backwards compatibility */
535         vm->threads = threads_per_core; /* XXX backwards compatibility */
536         vm->maxcpus = VM_MAXCPU;        /* XXX temp to keep code working */
537
538         vm_init(vm, true);
539
540         *retvm = vm;
541         return (0);
542 }
543
544 void
545 vm_get_topology(struct vm *vm, uint16_t *sockets, uint16_t *cores,
546     uint16_t *threads, uint16_t *maxcpus)
547 {
548         *sockets = vm->sockets;
549         *cores = vm->cores;
550         *threads = vm->threads;
551         *maxcpus = vm->maxcpus;
552 }
553
554 uint16_t
555 vm_get_maxcpus(struct vm *vm)
556 {
557         return (vm->maxcpus);
558 }
559
560 int
561 vm_set_topology(struct vm *vm, uint16_t sockets, uint16_t cores,
562     uint16_t threads, uint16_t maxcpus)
563 {
564         if (maxcpus != 0)
565                 return (EINVAL);        /* XXX remove when supported */
566         if ((sockets * cores * threads) > vm->maxcpus)
567                 return (EINVAL);
568         /* XXX need to check sockets * cores * threads == vCPU, how? */
569         vm->sockets = sockets;
570         vm->cores = cores;
571         vm->threads = threads;
572         vm->maxcpus = VM_MAXCPU;        /* XXX temp to keep code working */
573         return(0);
574 }
575
576 static void
577 vm_cleanup(struct vm *vm, bool destroy)
578 {
579         struct mem_map *mm;
580         int i;
581
582         ppt_unassign_all(vm);
583
584         if (vm->iommu != NULL)
585                 iommu_destroy_domain(vm->iommu);
586
587         if (destroy)
588                 vrtc_cleanup(vm->vrtc);
589         else
590                 vrtc_reset(vm->vrtc);
591         vpmtmr_cleanup(vm->vpmtmr);
592         vatpit_cleanup(vm->vatpit);
593         vhpet_cleanup(vm->vhpet);
594         vatpic_cleanup(vm->vatpic);
595         vioapic_cleanup(vm->vioapic);
596
597         for (i = 0; i < vm->maxcpus; i++)
598                 vcpu_cleanup(vm, i, destroy);
599
600         vmmops_cleanup(vm->cookie);
601
602         /*
603          * System memory is removed from the guest address space only when
604          * the VM is destroyed. This is because the mapping remains the same
605          * across VM reset.
606          *
607          * Device memory can be relocated by the guest (e.g. using PCI BARs)
608          * so those mappings are removed on a VM reset.
609          */
610         for (i = 0; i < VM_MAX_MEMMAPS; i++) {
611                 mm = &vm->mem_maps[i];
612                 if (destroy || !sysmem_mapping(vm, mm))
613                         vm_free_memmap(vm, i);
614         }
615
616         if (destroy) {
617                 for (i = 0; i < VM_MAX_MEMSEGS; i++)
618                         vm_free_memseg(vm, i);
619
620                 vmmops_vmspace_free(vm->vmspace);
621                 vm->vmspace = NULL;
622         }
623 }
624
625 void
626 vm_destroy(struct vm *vm)
627 {
628         vm_cleanup(vm, true);
629         free(vm, M_VM);
630 }
631
632 int
633 vm_reinit(struct vm *vm)
634 {
635         int error;
636
637         /*
638          * A virtual machine can be reset only if all vcpus are suspended.
639          */
640         if (CPU_CMP(&vm->suspended_cpus, &vm->active_cpus) == 0) {
641                 vm_cleanup(vm, false);
642                 vm_init(vm, false);
643                 error = 0;
644         } else {
645                 error = EBUSY;
646         }
647
648         return (error);
649 }
650
651 const char *
652 vm_name(struct vm *vm)
653 {
654         return (vm->name);
655 }
656
657 int
658 vm_map_mmio(struct vm *vm, vm_paddr_t gpa, size_t len, vm_paddr_t hpa)
659 {
660         vm_object_t obj;
661
662         if ((obj = vmm_mmio_alloc(vm->vmspace, gpa, len, hpa)) == NULL)
663                 return (ENOMEM);
664         else
665                 return (0);
666 }
667
668 int
669 vm_unmap_mmio(struct vm *vm, vm_paddr_t gpa, size_t len)
670 {
671
672         vmm_mmio_free(vm->vmspace, gpa, len);
673         return (0);
674 }
675
676 /*
677  * Return 'true' if 'gpa' is allocated in the guest address space.
678  *
679  * This function is called in the context of a running vcpu which acts as
680  * an implicit lock on 'vm->mem_maps[]'.
681  */
682 bool
683 vm_mem_allocated(struct vm *vm, int vcpuid, vm_paddr_t gpa)
684 {
685         struct mem_map *mm;
686         int i;
687
688 #ifdef INVARIANTS
689         int hostcpu, state;
690         state = vcpu_get_state(vm, vcpuid, &hostcpu);
691         KASSERT(state == VCPU_RUNNING && hostcpu == curcpu,
692             ("%s: invalid vcpu state %d/%d", __func__, state, hostcpu));
693 #endif
694
695         for (i = 0; i < VM_MAX_MEMMAPS; i++) {
696                 mm = &vm->mem_maps[i];
697                 if (mm->len != 0 && gpa >= mm->gpa && gpa < mm->gpa + mm->len)
698                         return (true);          /* 'gpa' is sysmem or devmem */
699         }
700
701         if (ppt_is_mmio(vm, gpa))
702                 return (true);                  /* 'gpa' is pci passthru mmio */
703
704         return (false);
705 }
706
707 int
708 vm_alloc_memseg(struct vm *vm, int ident, size_t len, bool sysmem)
709 {
710         struct mem_seg *seg;
711         vm_object_t obj;
712
713         if (ident < 0 || ident >= VM_MAX_MEMSEGS)
714                 return (EINVAL);
715
716         if (len == 0 || (len & PAGE_MASK))
717                 return (EINVAL);
718
719         seg = &vm->mem_segs[ident];
720         if (seg->object != NULL) {
721                 if (seg->len == len && seg->sysmem == sysmem)
722                         return (EEXIST);
723                 else
724                         return (EINVAL);
725         }
726
727         obj = vm_object_allocate(OBJT_SWAP, len >> PAGE_SHIFT);
728         if (obj == NULL)
729                 return (ENOMEM);
730
731         seg->len = len;
732         seg->object = obj;
733         seg->sysmem = sysmem;
734         return (0);
735 }
736
737 int
738 vm_get_memseg(struct vm *vm, int ident, size_t *len, bool *sysmem,
739     vm_object_t *objptr)
740 {
741         struct mem_seg *seg;
742
743         if (ident < 0 || ident >= VM_MAX_MEMSEGS)
744                 return (EINVAL);
745
746         seg = &vm->mem_segs[ident];
747         if (len)
748                 *len = seg->len;
749         if (sysmem)
750                 *sysmem = seg->sysmem;
751         if (objptr)
752                 *objptr = seg->object;
753         return (0);
754 }
755
756 void
757 vm_free_memseg(struct vm *vm, int ident)
758 {
759         struct mem_seg *seg;
760
761         KASSERT(ident >= 0 && ident < VM_MAX_MEMSEGS,
762             ("%s: invalid memseg ident %d", __func__, ident));
763
764         seg = &vm->mem_segs[ident];
765         if (seg->object != NULL) {
766                 vm_object_deallocate(seg->object);
767                 bzero(seg, sizeof(struct mem_seg));
768         }
769 }
770
771 int
772 vm_mmap_memseg(struct vm *vm, vm_paddr_t gpa, int segid, vm_ooffset_t first,
773     size_t len, int prot, int flags)
774 {
775         struct mem_seg *seg;
776         struct mem_map *m, *map;
777         vm_ooffset_t last;
778         int i, error;
779
780         if (prot == 0 || (prot & ~(VM_PROT_ALL)) != 0)
781                 return (EINVAL);
782
783         if (flags & ~VM_MEMMAP_F_WIRED)
784                 return (EINVAL);
785
786         if (segid < 0 || segid >= VM_MAX_MEMSEGS)
787                 return (EINVAL);
788
789         seg = &vm->mem_segs[segid];
790         if (seg->object == NULL)
791                 return (EINVAL);
792
793         last = first + len;
794         if (first < 0 || first >= last || last > seg->len)
795                 return (EINVAL);
796
797         if ((gpa | first | last) & PAGE_MASK)
798                 return (EINVAL);
799
800         map = NULL;
801         for (i = 0; i < VM_MAX_MEMMAPS; i++) {
802                 m = &vm->mem_maps[i];
803                 if (m->len == 0) {
804                         map = m;
805                         break;
806                 }
807         }
808
809         if (map == NULL)
810                 return (ENOSPC);
811
812         error = vm_map_find(&vm->vmspace->vm_map, seg->object, first, &gpa,
813             len, 0, VMFS_NO_SPACE, prot, prot, 0);
814         if (error != KERN_SUCCESS)
815                 return (EFAULT);
816
817         vm_object_reference(seg->object);
818
819         if (flags & VM_MEMMAP_F_WIRED) {
820                 error = vm_map_wire(&vm->vmspace->vm_map, gpa, gpa + len,
821                     VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
822                 if (error != KERN_SUCCESS) {
823                         vm_map_remove(&vm->vmspace->vm_map, gpa, gpa + len);
824                         return (error == KERN_RESOURCE_SHORTAGE ? ENOMEM :
825                             EFAULT);
826                 }
827         }
828
829         map->gpa = gpa;
830         map->len = len;
831         map->segoff = first;
832         map->segid = segid;
833         map->prot = prot;
834         map->flags = flags;
835         return (0);
836 }
837
838 int
839 vm_munmap_memseg(struct vm *vm, vm_paddr_t gpa, size_t len)
840 {
841         struct mem_map *m;
842         int i;
843
844         for (i = 0; i < VM_MAX_MEMMAPS; i++) {
845                 m = &vm->mem_maps[i];
846                 if (m->gpa == gpa && m->len == len &&
847                     (m->flags & VM_MEMMAP_F_IOMMU) == 0) {
848                         vm_free_memmap(vm, i);
849                         return (0);
850                 }
851         }
852
853         return (EINVAL);
854 }
855
856 int
857 vm_mmap_getnext(struct vm *vm, vm_paddr_t *gpa, int *segid,
858     vm_ooffset_t *segoff, size_t *len, int *prot, int *flags)
859 {
860         struct mem_map *mm, *mmnext;
861         int i;
862
863         mmnext = NULL;
864         for (i = 0; i < VM_MAX_MEMMAPS; i++) {
865                 mm = &vm->mem_maps[i];
866                 if (mm->len == 0 || mm->gpa < *gpa)
867                         continue;
868                 if (mmnext == NULL || mm->gpa < mmnext->gpa)
869                         mmnext = mm;
870         }
871
872         if (mmnext != NULL) {
873                 *gpa = mmnext->gpa;
874                 if (segid)
875                         *segid = mmnext->segid;
876                 if (segoff)
877                         *segoff = mmnext->segoff;
878                 if (len)
879                         *len = mmnext->len;
880                 if (prot)
881                         *prot = mmnext->prot;
882                 if (flags)
883                         *flags = mmnext->flags;
884                 return (0);
885         } else {
886                 return (ENOENT);
887         }
888 }
889
890 static void
891 vm_free_memmap(struct vm *vm, int ident)
892 {
893         struct mem_map *mm;
894         int error __diagused;
895
896         mm = &vm->mem_maps[ident];
897         if (mm->len) {
898                 error = vm_map_remove(&vm->vmspace->vm_map, mm->gpa,
899                     mm->gpa + mm->len);
900                 KASSERT(error == KERN_SUCCESS, ("%s: vm_map_remove error %d",
901                     __func__, error));
902                 bzero(mm, sizeof(struct mem_map));
903         }
904 }
905
906 static __inline bool
907 sysmem_mapping(struct vm *vm, struct mem_map *mm)
908 {
909
910         if (mm->len != 0 && vm->mem_segs[mm->segid].sysmem)
911                 return (true);
912         else
913                 return (false);
914 }
915
916 vm_paddr_t
917 vmm_sysmem_maxaddr(struct vm *vm)
918 {
919         struct mem_map *mm;
920         vm_paddr_t maxaddr;
921         int i;
922
923         maxaddr = 0;
924         for (i = 0; i < VM_MAX_MEMMAPS; i++) {
925                 mm = &vm->mem_maps[i];
926                 if (sysmem_mapping(vm, mm)) {
927                         if (maxaddr < mm->gpa + mm->len)
928                                 maxaddr = mm->gpa + mm->len;
929                 }
930         }
931         return (maxaddr);
932 }
933
934 static void
935 vm_iommu_modify(struct vm *vm, bool map)
936 {
937         int i, sz;
938         vm_paddr_t gpa, hpa;
939         struct mem_map *mm;
940         void *vp, *cookie, *host_domain;
941
942         sz = PAGE_SIZE;
943         host_domain = iommu_host_domain();
944
945         for (i = 0; i < VM_MAX_MEMMAPS; i++) {
946                 mm = &vm->mem_maps[i];
947                 if (!sysmem_mapping(vm, mm))
948                         continue;
949
950                 if (map) {
951                         KASSERT((mm->flags & VM_MEMMAP_F_IOMMU) == 0,
952                             ("iommu map found invalid memmap %#lx/%#lx/%#x",
953                             mm->gpa, mm->len, mm->flags));
954                         if ((mm->flags & VM_MEMMAP_F_WIRED) == 0)
955                                 continue;
956                         mm->flags |= VM_MEMMAP_F_IOMMU;
957                 } else {
958                         if ((mm->flags & VM_MEMMAP_F_IOMMU) == 0)
959                                 continue;
960                         mm->flags &= ~VM_MEMMAP_F_IOMMU;
961                         KASSERT((mm->flags & VM_MEMMAP_F_WIRED) != 0,
962                             ("iommu unmap found invalid memmap %#lx/%#lx/%#x",
963                             mm->gpa, mm->len, mm->flags));
964                 }
965
966                 gpa = mm->gpa;
967                 while (gpa < mm->gpa + mm->len) {
968                         vp = vm_gpa_hold(vm, -1, gpa, PAGE_SIZE, VM_PROT_WRITE,
969                                          &cookie);
970                         KASSERT(vp != NULL, ("vm(%s) could not map gpa %#lx",
971                             vm_name(vm), gpa));
972
973                         vm_gpa_release(cookie);
974
975                         hpa = DMAP_TO_PHYS((uintptr_t)vp);
976                         if (map) {
977                                 iommu_create_mapping(vm->iommu, gpa, hpa, sz);
978                         } else {
979                                 iommu_remove_mapping(vm->iommu, gpa, sz);
980                         }
981
982                         gpa += PAGE_SIZE;
983                 }
984         }
985
986         /*
987          * Invalidate the cached translations associated with the domain
988          * from which pages were removed.
989          */
990         if (map)
991                 iommu_invalidate_tlb(host_domain);
992         else
993                 iommu_invalidate_tlb(vm->iommu);
994 }
995
996 #define vm_iommu_unmap(vm)      vm_iommu_modify((vm), false)
997 #define vm_iommu_map(vm)        vm_iommu_modify((vm), true)
998
999 int
1000 vm_unassign_pptdev(struct vm *vm, int bus, int slot, int func)
1001 {
1002         int error;
1003
1004         error = ppt_unassign_device(vm, bus, slot, func);
1005         if (error)
1006                 return (error);
1007
1008         if (ppt_assigned_devices(vm) == 0)
1009                 vm_iommu_unmap(vm);
1010
1011         return (0);
1012 }
1013
1014 int
1015 vm_assign_pptdev(struct vm *vm, int bus, int slot, int func)
1016 {
1017         int error;
1018         vm_paddr_t maxaddr;
1019
1020         /* Set up the IOMMU to do the 'gpa' to 'hpa' translation */
1021         if (ppt_assigned_devices(vm) == 0) {
1022                 KASSERT(vm->iommu == NULL,
1023                     ("vm_assign_pptdev: iommu must be NULL"));
1024                 maxaddr = vmm_sysmem_maxaddr(vm);
1025                 vm->iommu = iommu_create_domain(maxaddr);
1026                 if (vm->iommu == NULL)
1027                         return (ENXIO);
1028                 vm_iommu_map(vm);
1029         }
1030
1031         error = ppt_assign_device(vm, bus, slot, func);
1032         return (error);
1033 }
1034
1035 void *
1036 vm_gpa_hold(struct vm *vm, int vcpuid, vm_paddr_t gpa, size_t len, int reqprot,
1037             void **cookie)
1038 {
1039         int i, count, pageoff;
1040         struct mem_map *mm;
1041         vm_page_t m;
1042 #ifdef INVARIANTS
1043         /*
1044          * All vcpus are frozen by ioctls that modify the memory map
1045          * (e.g. VM_MMAP_MEMSEG). Therefore 'vm->memmap[]' stability is
1046          * guaranteed if at least one vcpu is in the VCPU_FROZEN state.
1047          */
1048         int state;
1049         KASSERT(vcpuid >= -1 && vcpuid < vm->maxcpus, ("%s: invalid vcpuid %d",
1050             __func__, vcpuid));
1051         for (i = 0; i < vm->maxcpus; i++) {
1052                 if (vcpuid != -1 && vcpuid != i)
1053                         continue;
1054                 state = vcpu_get_state(vm, i, NULL);
1055                 KASSERT(state == VCPU_FROZEN, ("%s: invalid vcpu state %d",
1056                     __func__, state));
1057         }
1058 #endif
1059         pageoff = gpa & PAGE_MASK;
1060         if (len > PAGE_SIZE - pageoff)
1061                 panic("vm_gpa_hold: invalid gpa/len: 0x%016lx/%lu", gpa, len);
1062
1063         count = 0;
1064         for (i = 0; i < VM_MAX_MEMMAPS; i++) {
1065                 mm = &vm->mem_maps[i];
1066                 if (gpa >= mm->gpa && gpa < mm->gpa + mm->len) {
1067                         count = vm_fault_quick_hold_pages(&vm->vmspace->vm_map,
1068                             trunc_page(gpa), PAGE_SIZE, reqprot, &m, 1);
1069                         break;
1070                 }
1071         }
1072
1073         if (count == 1) {
1074                 *cookie = m;
1075                 return ((void *)(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)) + pageoff));
1076         } else {
1077                 *cookie = NULL;
1078                 return (NULL);
1079         }
1080 }
1081
1082 void
1083 vm_gpa_release(void *cookie)
1084 {
1085         vm_page_t m = cookie;
1086
1087         vm_page_unwire(m, PQ_ACTIVE);
1088 }
1089
1090 int
1091 vm_get_register(struct vm *vm, int vcpu, int reg, uint64_t *retval)
1092 {
1093
1094         if (vcpu < 0 || vcpu >= vm->maxcpus)
1095                 return (EINVAL);
1096
1097         if (reg >= VM_REG_LAST)
1098                 return (EINVAL);
1099
1100         return (vmmops_getreg(vcpu_cookie(vm, vcpu), reg, retval));
1101 }
1102
1103 int
1104 vm_set_register(struct vm *vm, int vcpuid, int reg, uint64_t val)
1105 {
1106         struct vcpu *vcpu;
1107         int error;
1108
1109         if (vcpuid < 0 || vcpuid >= vm->maxcpus)
1110                 return (EINVAL);
1111
1112         if (reg >= VM_REG_LAST)
1113                 return (EINVAL);
1114
1115         vcpu = &vm->vcpu[vcpuid];
1116         error = vmmops_setreg(vcpu->cookie, reg, val);
1117         if (error || reg != VM_REG_GUEST_RIP)
1118                 return (error);
1119
1120         /* Set 'nextrip' to match the value of %rip */
1121         VCPU_CTR1(vm, vcpuid, "Setting nextrip to %#lx", val);
1122         vcpu->nextrip = val;
1123         return (0);
1124 }
1125
1126 static bool
1127 is_descriptor_table(int reg)
1128 {
1129
1130         switch (reg) {
1131         case VM_REG_GUEST_IDTR:
1132         case VM_REG_GUEST_GDTR:
1133                 return (true);
1134         default:
1135                 return (false);
1136         }
1137 }
1138
1139 static bool
1140 is_segment_register(int reg)
1141 {
1142
1143         switch (reg) {
1144         case VM_REG_GUEST_ES:
1145         case VM_REG_GUEST_CS:
1146         case VM_REG_GUEST_SS:
1147         case VM_REG_GUEST_DS:
1148         case VM_REG_GUEST_FS:
1149         case VM_REG_GUEST_GS:
1150         case VM_REG_GUEST_TR:
1151         case VM_REG_GUEST_LDTR:
1152                 return (true);
1153         default:
1154                 return (false);
1155         }
1156 }
1157
1158 int
1159 vm_get_seg_desc(struct vm *vm, int vcpu, int reg,
1160                 struct seg_desc *desc)
1161 {
1162
1163         if (vcpu < 0 || vcpu >= vm->maxcpus)
1164                 return (EINVAL);
1165
1166         if (!is_segment_register(reg) && !is_descriptor_table(reg))
1167                 return (EINVAL);
1168
1169         return (vmmops_getdesc(vcpu_cookie(vm, vcpu), reg, desc));
1170 }
1171
1172 int
1173 vm_set_seg_desc(struct vm *vm, int vcpu, int reg,
1174                 struct seg_desc *desc)
1175 {
1176         if (vcpu < 0 || vcpu >= vm->maxcpus)
1177                 return (EINVAL);
1178
1179         if (!is_segment_register(reg) && !is_descriptor_table(reg))
1180                 return (EINVAL);
1181
1182         return (vmmops_setdesc(vcpu_cookie(vm, vcpu), reg, desc));
1183 }
1184
1185 static void
1186 restore_guest_fpustate(struct vcpu *vcpu)
1187 {
1188
1189         /* flush host state to the pcb */
1190         fpuexit(curthread);
1191
1192         /* restore guest FPU state */
1193         fpu_stop_emulating();
1194         fpurestore(vcpu->guestfpu);
1195
1196         /* restore guest XCR0 if XSAVE is enabled in the host */
1197         if (rcr4() & CR4_XSAVE)
1198                 load_xcr(0, vcpu->guest_xcr0);
1199
1200         /*
1201          * The FPU is now "dirty" with the guest's state so turn on emulation
1202          * to trap any access to the FPU by the host.
1203          */
1204         fpu_start_emulating();
1205 }
1206
1207 static void
1208 save_guest_fpustate(struct vcpu *vcpu)
1209 {
1210
1211         if ((rcr0() & CR0_TS) == 0)
1212                 panic("fpu emulation not enabled in host!");
1213
1214         /* save guest XCR0 and restore host XCR0 */
1215         if (rcr4() & CR4_XSAVE) {
1216                 vcpu->guest_xcr0 = rxcr(0);
1217                 load_xcr(0, vmm_get_host_xcr0());
1218         }
1219
1220         /* save guest FPU state */
1221         fpu_stop_emulating();
1222         fpusave(vcpu->guestfpu);
1223         fpu_start_emulating();
1224 }
1225
1226 static VMM_STAT(VCPU_IDLE_TICKS, "number of ticks vcpu was idle");
1227
1228 static int
1229 vcpu_set_state_locked(struct vm *vm, int vcpuid, enum vcpu_state newstate,
1230     bool from_idle)
1231 {
1232         struct vcpu *vcpu;
1233         int error;
1234
1235         vcpu = &vm->vcpu[vcpuid];
1236         vcpu_assert_locked(vcpu);
1237
1238         /*
1239          * State transitions from the vmmdev_ioctl() must always begin from
1240          * the VCPU_IDLE state. This guarantees that there is only a single
1241          * ioctl() operating on a vcpu at any point.
1242          */
1243         if (from_idle) {
1244                 while (vcpu->state != VCPU_IDLE) {
1245                         vcpu->reqidle = 1;
1246                         vcpu_notify_event_locked(vcpu, false);
1247                         VCPU_CTR1(vm, vcpuid, "vcpu state change from %s to "
1248                             "idle requested", vcpu_state2str(vcpu->state));
1249                         msleep_spin(&vcpu->state, &vcpu->mtx, "vmstat", hz);
1250                 }
1251         } else {
1252                 KASSERT(vcpu->state != VCPU_IDLE, ("invalid transition from "
1253                     "vcpu idle state"));
1254         }
1255
1256         if (vcpu->state == VCPU_RUNNING) {
1257                 KASSERT(vcpu->hostcpu == curcpu, ("curcpu %d and hostcpu %d "
1258                     "mismatch for running vcpu", curcpu, vcpu->hostcpu));
1259         } else {
1260                 KASSERT(vcpu->hostcpu == NOCPU, ("Invalid hostcpu %d for a "
1261                     "vcpu that is not running", vcpu->hostcpu));
1262         }
1263
1264         /*
1265          * The following state transitions are allowed:
1266          * IDLE -> FROZEN -> IDLE
1267          * FROZEN -> RUNNING -> FROZEN
1268          * FROZEN -> SLEEPING -> FROZEN
1269          */
1270         switch (vcpu->state) {
1271         case VCPU_IDLE:
1272         case VCPU_RUNNING:
1273         case VCPU_SLEEPING:
1274                 error = (newstate != VCPU_FROZEN);
1275                 break;
1276         case VCPU_FROZEN:
1277                 error = (newstate == VCPU_FROZEN);
1278                 break;
1279         default:
1280                 error = 1;
1281                 break;
1282         }
1283
1284         if (error)
1285                 return (EBUSY);
1286
1287         VCPU_CTR2(vm, vcpuid, "vcpu state changed from %s to %s",
1288             vcpu_state2str(vcpu->state), vcpu_state2str(newstate));
1289
1290         vcpu->state = newstate;
1291         if (newstate == VCPU_RUNNING)
1292                 vcpu->hostcpu = curcpu;
1293         else
1294                 vcpu->hostcpu = NOCPU;
1295
1296         if (newstate == VCPU_IDLE)
1297                 wakeup(&vcpu->state);
1298
1299         return (0);
1300 }
1301
1302 static void
1303 vcpu_require_state(struct vm *vm, int vcpuid, enum vcpu_state newstate)
1304 {
1305         int error;
1306
1307         if ((error = vcpu_set_state(vm, vcpuid, newstate, false)) != 0)
1308                 panic("Error %d setting state to %d\n", error, newstate);
1309 }
1310
1311 static void
1312 vcpu_require_state_locked(struct vm *vm, int vcpuid, enum vcpu_state newstate)
1313 {
1314         int error;
1315
1316         if ((error = vcpu_set_state_locked(vm, vcpuid, newstate, false)) != 0)
1317                 panic("Error %d setting state to %d", error, newstate);
1318 }
1319
1320 #define RENDEZVOUS_CTR0(vm, vcpuid, fmt)                                \
1321         do {                                                            \
1322                 if (vcpuid >= 0)                                        \
1323                         VCPU_CTR0(vm, vcpuid, fmt);                     \
1324                 else                                                    \
1325                         VM_CTR0(vm, fmt);                               \
1326         } while (0)
1327
1328 static int
1329 vm_handle_rendezvous(struct vm *vm, int vcpuid)
1330 {
1331         struct thread *td;
1332         int error;
1333
1334         KASSERT(vcpuid == -1 || (vcpuid >= 0 && vcpuid < vm->maxcpus),
1335             ("vm_handle_rendezvous: invalid vcpuid %d", vcpuid));
1336
1337         error = 0;
1338         td = curthread;
1339         mtx_lock(&vm->rendezvous_mtx);
1340         while (vm->rendezvous_func != NULL) {
1341                 /* 'rendezvous_req_cpus' must be a subset of 'active_cpus' */
1342                 CPU_AND(&vm->rendezvous_req_cpus, &vm->rendezvous_req_cpus, &vm->active_cpus);
1343
1344                 if (vcpuid != -1 &&
1345                     CPU_ISSET(vcpuid, &vm->rendezvous_req_cpus) &&
1346                     !CPU_ISSET(vcpuid, &vm->rendezvous_done_cpus)) {
1347                         VCPU_CTR0(vm, vcpuid, "Calling rendezvous func");
1348                         (*vm->rendezvous_func)(vm, vcpuid, vm->rendezvous_arg);
1349                         CPU_SET(vcpuid, &vm->rendezvous_done_cpus);
1350                 }
1351                 if (CPU_CMP(&vm->rendezvous_req_cpus,
1352                     &vm->rendezvous_done_cpus) == 0) {
1353                         VCPU_CTR0(vm, vcpuid, "Rendezvous completed");
1354                         vm->rendezvous_func = NULL;
1355                         wakeup(&vm->rendezvous_func);
1356                         break;
1357                 }
1358                 RENDEZVOUS_CTR0(vm, vcpuid, "Wait for rendezvous completion");
1359                 mtx_sleep(&vm->rendezvous_func, &vm->rendezvous_mtx, 0,
1360                     "vmrndv", hz);
1361                 if ((td->td_flags & TDF_NEEDSUSPCHK) != 0) {
1362                         mtx_unlock(&vm->rendezvous_mtx);
1363                         error = thread_check_susp(td, true);
1364                         if (error != 0)
1365                                 return (error);
1366                         mtx_lock(&vm->rendezvous_mtx);
1367                 }
1368         }
1369         mtx_unlock(&vm->rendezvous_mtx);
1370         return (0);
1371 }
1372
1373 /*
1374  * Emulate a guest 'hlt' by sleeping until the vcpu is ready to run.
1375  */
1376 static int
1377 vm_handle_hlt(struct vm *vm, int vcpuid, bool intr_disabled, bool *retu)
1378 {
1379         struct vcpu *vcpu;
1380         const char *wmesg;
1381         struct thread *td;
1382         int error, t, vcpu_halted, vm_halted;
1383
1384         KASSERT(!CPU_ISSET(vcpuid, &vm->halted_cpus), ("vcpu already halted"));
1385
1386         vcpu = &vm->vcpu[vcpuid];
1387         vcpu_halted = 0;
1388         vm_halted = 0;
1389         error = 0;
1390         td = curthread;
1391
1392         vcpu_lock(vcpu);
1393         while (1) {
1394                 /*
1395                  * Do a final check for pending NMI or interrupts before
1396                  * really putting this thread to sleep. Also check for
1397                  * software events that would cause this vcpu to wakeup.
1398                  *
1399                  * These interrupts/events could have happened after the
1400                  * vcpu returned from vmmops_run() and before it acquired the
1401                  * vcpu lock above.
1402                  */
1403                 if (vm->rendezvous_func != NULL || vm->suspend || vcpu->reqidle)
1404                         break;
1405                 if (vm_nmi_pending(vm, vcpuid))
1406                         break;
1407                 if (!intr_disabled) {
1408                         if (vm_extint_pending(vm, vcpuid) ||
1409                             vlapic_pending_intr(vcpu->vlapic, NULL)) {
1410                                 break;
1411                         }
1412                 }
1413
1414                 /* Don't go to sleep if the vcpu thread needs to yield */
1415                 if (vcpu_should_yield(vm, vcpuid))
1416                         break;
1417
1418                 if (vcpu_debugged(vm, vcpuid))
1419                         break;
1420
1421                 /*
1422                  * Some Linux guests implement "halt" by having all vcpus
1423                  * execute HLT with interrupts disabled. 'halted_cpus' keeps
1424                  * track of the vcpus that have entered this state. When all
1425                  * vcpus enter the halted state the virtual machine is halted.
1426                  */
1427                 if (intr_disabled) {
1428                         wmesg = "vmhalt";
1429                         VCPU_CTR0(vm, vcpuid, "Halted");
1430                         if (!vcpu_halted && halt_detection_enabled) {
1431                                 vcpu_halted = 1;
1432                                 CPU_SET_ATOMIC(vcpuid, &vm->halted_cpus);
1433                         }
1434                         if (CPU_CMP(&vm->halted_cpus, &vm->active_cpus) == 0) {
1435                                 vm_halted = 1;
1436                                 break;
1437                         }
1438                 } else {
1439                         wmesg = "vmidle";
1440                 }
1441
1442                 t = ticks;
1443                 vcpu_require_state_locked(vm, vcpuid, VCPU_SLEEPING);
1444                 /*
1445                  * XXX msleep_spin() cannot be interrupted by signals so
1446                  * wake up periodically to check pending signals.
1447                  */
1448                 msleep_spin(vcpu, &vcpu->mtx, wmesg, hz);
1449                 vcpu_require_state_locked(vm, vcpuid, VCPU_FROZEN);
1450                 vmm_stat_incr(vm, vcpuid, VCPU_IDLE_TICKS, ticks - t);
1451                 if ((td->td_flags & TDF_NEEDSUSPCHK) != 0) {
1452                         vcpu_unlock(vcpu);
1453                         error = thread_check_susp(td, false);
1454                         if (error != 0) {
1455                                 if (vcpu_halted) {
1456                                         CPU_CLR_ATOMIC(vcpuid,
1457                                             &vm->halted_cpus);
1458                                 }
1459                                 return (error);
1460                         }
1461                         vcpu_lock(vcpu);
1462                 }
1463         }
1464
1465         if (vcpu_halted)
1466                 CPU_CLR_ATOMIC(vcpuid, &vm->halted_cpus);
1467
1468         vcpu_unlock(vcpu);
1469
1470         if (vm_halted)
1471                 vm_suspend(vm, VM_SUSPEND_HALT);
1472
1473         return (0);
1474 }
1475
1476 static int
1477 vm_handle_paging(struct vm *vm, int vcpuid, bool *retu)
1478 {
1479         int rv, ftype;
1480         struct vm_map *map;
1481         struct vcpu *vcpu;
1482         struct vm_exit *vme;
1483
1484         vcpu = &vm->vcpu[vcpuid];
1485         vme = &vcpu->exitinfo;
1486
1487         KASSERT(vme->inst_length == 0, ("%s: invalid inst_length %d",
1488             __func__, vme->inst_length));
1489
1490         ftype = vme->u.paging.fault_type;
1491         KASSERT(ftype == VM_PROT_READ ||
1492             ftype == VM_PROT_WRITE || ftype == VM_PROT_EXECUTE,
1493             ("vm_handle_paging: invalid fault_type %d", ftype));
1494
1495         if (ftype == VM_PROT_READ || ftype == VM_PROT_WRITE) {
1496                 rv = pmap_emulate_accessed_dirty(vmspace_pmap(vm->vmspace),
1497                     vme->u.paging.gpa, ftype);
1498                 if (rv == 0) {
1499                         VCPU_CTR2(vm, vcpuid, "%s bit emulation for gpa %#lx",
1500                             ftype == VM_PROT_READ ? "accessed" : "dirty",
1501                             vme->u.paging.gpa);
1502                         goto done;
1503                 }
1504         }
1505
1506         map = &vm->vmspace->vm_map;
1507         rv = vm_fault(map, vme->u.paging.gpa, ftype, VM_FAULT_NORMAL, NULL);
1508
1509         VCPU_CTR3(vm, vcpuid, "vm_handle_paging rv = %d, gpa = %#lx, "
1510             "ftype = %d", rv, vme->u.paging.gpa, ftype);
1511
1512         if (rv != KERN_SUCCESS)
1513                 return (EFAULT);
1514 done:
1515         return (0);
1516 }
1517
1518 static int
1519 vm_handle_inst_emul(struct vm *vm, int vcpuid, bool *retu)
1520 {
1521         struct vie *vie;
1522         struct vcpu *vcpu;
1523         struct vm_exit *vme;
1524         uint64_t gla, gpa, cs_base;
1525         struct vm_guest_paging *paging;
1526         mem_region_read_t mread;
1527         mem_region_write_t mwrite;
1528         enum vm_cpu_mode cpu_mode;
1529         int cs_d, error, fault;
1530
1531         vcpu = &vm->vcpu[vcpuid];
1532         vme = &vcpu->exitinfo;
1533
1534         KASSERT(vme->inst_length == 0, ("%s: invalid inst_length %d",
1535             __func__, vme->inst_length));
1536
1537         gla = vme->u.inst_emul.gla;
1538         gpa = vme->u.inst_emul.gpa;
1539         cs_base = vme->u.inst_emul.cs_base;
1540         cs_d = vme->u.inst_emul.cs_d;
1541         vie = &vme->u.inst_emul.vie;
1542         paging = &vme->u.inst_emul.paging;
1543         cpu_mode = paging->cpu_mode;
1544
1545         VCPU_CTR1(vm, vcpuid, "inst_emul fault accessing gpa %#lx", gpa);
1546
1547         /* Fetch, decode and emulate the faulting instruction */
1548         if (vie->num_valid == 0) {
1549                 error = vmm_fetch_instruction(vm, vcpuid, paging, vme->rip +
1550                     cs_base, VIE_INST_SIZE, vie, &fault);
1551         } else {
1552                 /*
1553                  * The instruction bytes have already been copied into 'vie'
1554                  */
1555                 error = fault = 0;
1556         }
1557         if (error || fault)
1558                 return (error);
1559
1560         if (vmm_decode_instruction(vm, vcpuid, gla, cpu_mode, cs_d, vie) != 0) {
1561                 VCPU_CTR1(vm, vcpuid, "Error decoding instruction at %#lx",
1562                     vme->rip + cs_base);
1563                 *retu = true;       /* dump instruction bytes in userspace */
1564                 return (0);
1565         }
1566
1567         /*
1568          * Update 'nextrip' based on the length of the emulated instruction.
1569          */
1570         vme->inst_length = vie->num_processed;
1571         vcpu->nextrip += vie->num_processed;
1572         VCPU_CTR1(vm, vcpuid, "nextrip updated to %#lx after instruction "
1573             "decoding", vcpu->nextrip);
1574
1575         /* return to userland unless this is an in-kernel emulated device */
1576         if (gpa >= DEFAULT_APIC_BASE && gpa < DEFAULT_APIC_BASE + PAGE_SIZE) {
1577                 mread = lapic_mmio_read;
1578                 mwrite = lapic_mmio_write;
1579         } else if (gpa >= VIOAPIC_BASE && gpa < VIOAPIC_BASE + VIOAPIC_SIZE) {
1580                 mread = vioapic_mmio_read;
1581                 mwrite = vioapic_mmio_write;
1582         } else if (gpa >= VHPET_BASE && gpa < VHPET_BASE + VHPET_SIZE) {
1583                 mread = vhpet_mmio_read;
1584                 mwrite = vhpet_mmio_write;
1585         } else {
1586                 *retu = true;
1587                 return (0);
1588         }
1589
1590         error = vmm_emulate_instruction(vm, vcpuid, gpa, vie, paging,
1591             mread, mwrite, retu);
1592
1593         return (error);
1594 }
1595
1596 static int
1597 vm_handle_suspend(struct vm *vm, int vcpuid, bool *retu)
1598 {
1599         int error, i;
1600         struct vcpu *vcpu;
1601         struct thread *td;
1602
1603         error = 0;
1604         vcpu = &vm->vcpu[vcpuid];
1605         td = curthread;
1606
1607         CPU_SET_ATOMIC(vcpuid, &vm->suspended_cpus);
1608
1609         /*
1610          * Wait until all 'active_cpus' have suspended themselves.
1611          *
1612          * Since a VM may be suspended at any time including when one or
1613          * more vcpus are doing a rendezvous we need to call the rendezvous
1614          * handler while we are waiting to prevent a deadlock.
1615          */
1616         vcpu_lock(vcpu);
1617         while (error == 0) {
1618                 if (CPU_CMP(&vm->suspended_cpus, &vm->active_cpus) == 0) {
1619                         VCPU_CTR0(vm, vcpuid, "All vcpus suspended");
1620                         break;
1621                 }
1622
1623                 if (vm->rendezvous_func == NULL) {
1624                         VCPU_CTR0(vm, vcpuid, "Sleeping during suspend");
1625                         vcpu_require_state_locked(vm, vcpuid, VCPU_SLEEPING);
1626                         msleep_spin(vcpu, &vcpu->mtx, "vmsusp", hz);
1627                         vcpu_require_state_locked(vm, vcpuid, VCPU_FROZEN);
1628                         if ((td->td_flags & TDF_NEEDSUSPCHK) != 0) {
1629                                 vcpu_unlock(vcpu);
1630                                 error = thread_check_susp(td, false);
1631                                 vcpu_lock(vcpu);
1632                         }
1633                 } else {
1634                         VCPU_CTR0(vm, vcpuid, "Rendezvous during suspend");
1635                         vcpu_unlock(vcpu);
1636                         error = vm_handle_rendezvous(vm, vcpuid);
1637                         vcpu_lock(vcpu);
1638                 }
1639         }
1640         vcpu_unlock(vcpu);
1641
1642         /*
1643          * Wakeup the other sleeping vcpus and return to userspace.
1644          */
1645         for (i = 0; i < vm->maxcpus; i++) {
1646                 if (CPU_ISSET(i, &vm->suspended_cpus)) {
1647                         vcpu_notify_event(vm, i, false);
1648                 }
1649         }
1650
1651         *retu = true;
1652         return (error);
1653 }
1654
1655 static int
1656 vm_handle_reqidle(struct vm *vm, int vcpuid, bool *retu)
1657 {
1658         struct vcpu *vcpu = &vm->vcpu[vcpuid];
1659
1660         vcpu_lock(vcpu);
1661         KASSERT(vcpu->reqidle, ("invalid vcpu reqidle %d", vcpu->reqidle));
1662         vcpu->reqidle = 0;
1663         vcpu_unlock(vcpu);
1664         *retu = true;
1665         return (0);
1666 }
1667
1668 int
1669 vm_suspend(struct vm *vm, enum vm_suspend_how how)
1670 {
1671         int i;
1672
1673         if (how <= VM_SUSPEND_NONE || how >= VM_SUSPEND_LAST)
1674                 return (EINVAL);
1675
1676         if (atomic_cmpset_int(&vm->suspend, 0, how) == 0) {
1677                 VM_CTR2(vm, "virtual machine already suspended %d/%d",
1678                     vm->suspend, how);
1679                 return (EALREADY);
1680         }
1681
1682         VM_CTR1(vm, "virtual machine successfully suspended %d", how);
1683
1684         /*
1685          * Notify all active vcpus that they are now suspended.
1686          */
1687         for (i = 0; i < vm->maxcpus; i++) {
1688                 if (CPU_ISSET(i, &vm->active_cpus))
1689                         vcpu_notify_event(vm, i, false);
1690         }
1691
1692         return (0);
1693 }
1694
1695 void
1696 vm_exit_suspended(struct vm *vm, int vcpuid, uint64_t rip)
1697 {
1698         struct vm_exit *vmexit;
1699
1700         KASSERT(vm->suspend > VM_SUSPEND_NONE && vm->suspend < VM_SUSPEND_LAST,
1701             ("vm_exit_suspended: invalid suspend type %d", vm->suspend));
1702
1703         vmexit = vm_exitinfo(vm, vcpuid);
1704         vmexit->rip = rip;
1705         vmexit->inst_length = 0;
1706         vmexit->exitcode = VM_EXITCODE_SUSPENDED;
1707         vmexit->u.suspended.how = vm->suspend;
1708 }
1709
1710 void
1711 vm_exit_debug(struct vm *vm, int vcpuid, uint64_t rip)
1712 {
1713         struct vm_exit *vmexit;
1714
1715         vmexit = vm_exitinfo(vm, vcpuid);
1716         vmexit->rip = rip;
1717         vmexit->inst_length = 0;
1718         vmexit->exitcode = VM_EXITCODE_DEBUG;
1719 }
1720
1721 void
1722 vm_exit_rendezvous(struct vm *vm, int vcpuid, uint64_t rip)
1723 {
1724         struct vm_exit *vmexit;
1725
1726         vmexit = vm_exitinfo(vm, vcpuid);
1727         vmexit->rip = rip;
1728         vmexit->inst_length = 0;
1729         vmexit->exitcode = VM_EXITCODE_RENDEZVOUS;
1730         vmm_stat_incr(vm, vcpuid, VMEXIT_RENDEZVOUS, 1);
1731 }
1732
1733 void
1734 vm_exit_reqidle(struct vm *vm, int vcpuid, uint64_t rip)
1735 {
1736         struct vm_exit *vmexit;
1737
1738         vmexit = vm_exitinfo(vm, vcpuid);
1739         vmexit->rip = rip;
1740         vmexit->inst_length = 0;
1741         vmexit->exitcode = VM_EXITCODE_REQIDLE;
1742         vmm_stat_incr(vm, vcpuid, VMEXIT_REQIDLE, 1);
1743 }
1744
1745 void
1746 vm_exit_astpending(struct vm *vm, int vcpuid, uint64_t rip)
1747 {
1748         struct vm_exit *vmexit;
1749
1750         vmexit = vm_exitinfo(vm, vcpuid);
1751         vmexit->rip = rip;
1752         vmexit->inst_length = 0;
1753         vmexit->exitcode = VM_EXITCODE_BOGUS;
1754         vmm_stat_incr(vm, vcpuid, VMEXIT_ASTPENDING, 1);
1755 }
1756
1757 int
1758 vm_run(struct vm *vm, struct vm_run *vmrun)
1759 {
1760         struct vm_eventinfo evinfo;
1761         int error, vcpuid;
1762         struct vcpu *vcpu;
1763         struct pcb *pcb;
1764         uint64_t tscval;
1765         struct vm_exit *vme;
1766         bool retu, intr_disabled;
1767         pmap_t pmap;
1768
1769         vcpuid = vmrun->cpuid;
1770
1771         if (vcpuid < 0 || vcpuid >= vm->maxcpus)
1772                 return (EINVAL);
1773
1774         if (!CPU_ISSET(vcpuid, &vm->active_cpus))
1775                 return (EINVAL);
1776
1777         if (CPU_ISSET(vcpuid, &vm->suspended_cpus))
1778                 return (EINVAL);
1779
1780         pmap = vmspace_pmap(vm->vmspace);
1781         vcpu = &vm->vcpu[vcpuid];
1782         vme = &vcpu->exitinfo;
1783         evinfo.rptr = &vm->rendezvous_func;
1784         evinfo.sptr = &vm->suspend;
1785         evinfo.iptr = &vcpu->reqidle;
1786 restart:
1787         critical_enter();
1788
1789         KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1790             ("vm_run: absurd pm_active"));
1791
1792         tscval = rdtsc();
1793
1794         pcb = PCPU_GET(curpcb);
1795         set_pcb_flags(pcb, PCB_FULL_IRET);
1796
1797         restore_guest_fpustate(vcpu);
1798
1799         vcpu_require_state(vm, vcpuid, VCPU_RUNNING);
1800         error = vmmops_run(vcpu->cookie, vcpu->nextrip, pmap, &evinfo);
1801         vcpu_require_state(vm, vcpuid, VCPU_FROZEN);
1802
1803         save_guest_fpustate(vcpu);
1804
1805         vmm_stat_incr(vm, vcpuid, VCPU_TOTAL_RUNTIME, rdtsc() - tscval);
1806
1807         critical_exit();
1808
1809         if (error == 0) {
1810                 retu = false;
1811                 vcpu->nextrip = vme->rip + vme->inst_length;
1812                 switch (vme->exitcode) {
1813                 case VM_EXITCODE_REQIDLE:
1814                         error = vm_handle_reqidle(vm, vcpuid, &retu);
1815                         break;
1816                 case VM_EXITCODE_SUSPENDED:
1817                         error = vm_handle_suspend(vm, vcpuid, &retu);
1818                         break;
1819                 case VM_EXITCODE_IOAPIC_EOI:
1820                         vioapic_process_eoi(vm, vcpuid,
1821                             vme->u.ioapic_eoi.vector);
1822                         break;
1823                 case VM_EXITCODE_RENDEZVOUS:
1824                         error = vm_handle_rendezvous(vm, vcpuid);
1825                         break;
1826                 case VM_EXITCODE_HLT:
1827                         intr_disabled = ((vme->u.hlt.rflags & PSL_I) == 0);
1828                         error = vm_handle_hlt(vm, vcpuid, intr_disabled, &retu);
1829                         break;
1830                 case VM_EXITCODE_PAGING:
1831                         error = vm_handle_paging(vm, vcpuid, &retu);
1832                         break;
1833                 case VM_EXITCODE_INST_EMUL:
1834                         error = vm_handle_inst_emul(vm, vcpuid, &retu);
1835                         break;
1836                 case VM_EXITCODE_INOUT:
1837                 case VM_EXITCODE_INOUT_STR:
1838                         error = vm_handle_inout(vm, vcpuid, vme, &retu);
1839                         break;
1840                 case VM_EXITCODE_MONITOR:
1841                 case VM_EXITCODE_MWAIT:
1842                 case VM_EXITCODE_VMINSN:
1843                         vm_inject_ud(vm, vcpuid);
1844                         break;
1845                 default:
1846                         retu = true;    /* handled in userland */
1847                         break;
1848                 }
1849         }
1850
1851         /*
1852          * VM_EXITCODE_INST_EMUL could access the apic which could transform the
1853          * exit code into VM_EXITCODE_IPI.
1854          */
1855         if (error == 0 && vme->exitcode == VM_EXITCODE_IPI) {
1856                 retu = false;
1857                 error = vm_handle_ipi(vm, vcpuid, vme, &retu);
1858         }
1859
1860         if (error == 0 && retu == false)
1861                 goto restart;
1862
1863         vmm_stat_incr(vm, vcpuid, VMEXIT_USERSPACE, 1);
1864         VCPU_CTR2(vm, vcpuid, "retu %d/%d", error, vme->exitcode);
1865
1866         /* copy the exit information */
1867         bcopy(vme, &vmrun->vm_exit, sizeof(struct vm_exit));
1868         return (error);
1869 }
1870
1871 int
1872 vm_restart_instruction(void *arg, int vcpuid)
1873 {
1874         struct vm *vm;
1875         struct vcpu *vcpu;
1876         enum vcpu_state state;
1877         uint64_t rip;
1878         int error __diagused;
1879
1880         vm = arg;
1881         if (vcpuid < 0 || vcpuid >= vm->maxcpus)
1882                 return (EINVAL);
1883
1884         vcpu = &vm->vcpu[vcpuid];
1885         state = vcpu_get_state(vm, vcpuid, NULL);
1886         if (state == VCPU_RUNNING) {
1887                 /*
1888                  * When a vcpu is "running" the next instruction is determined
1889                  * by adding 'rip' and 'inst_length' in the vcpu's 'exitinfo'.
1890                  * Thus setting 'inst_length' to zero will cause the current
1891                  * instruction to be restarted.
1892                  */
1893                 vcpu->exitinfo.inst_length = 0;
1894                 VCPU_CTR1(vm, vcpuid, "restarting instruction at %#lx by "
1895                     "setting inst_length to zero", vcpu->exitinfo.rip);
1896         } else if (state == VCPU_FROZEN) {
1897                 /*
1898                  * When a vcpu is "frozen" it is outside the critical section
1899                  * around vmmops_run() and 'nextrip' points to the next
1900                  * instruction. Thus instruction restart is achieved by setting
1901                  * 'nextrip' to the vcpu's %rip.
1902                  */
1903                 error = vm_get_register(vm, vcpuid, VM_REG_GUEST_RIP, &rip);
1904                 KASSERT(!error, ("%s: error %d getting rip", __func__, error));
1905                 VCPU_CTR2(vm, vcpuid, "restarting instruction by updating "
1906                     "nextrip from %#lx to %#lx", vcpu->nextrip, rip);
1907                 vcpu->nextrip = rip;
1908         } else {
1909                 panic("%s: invalid state %d", __func__, state);
1910         }
1911         return (0);
1912 }
1913
1914 int
1915 vm_exit_intinfo(struct vm *vm, int vcpuid, uint64_t info)
1916 {
1917         struct vcpu *vcpu;
1918         int type, vector;
1919
1920         if (vcpuid < 0 || vcpuid >= vm->maxcpus)
1921                 return (EINVAL);
1922
1923         vcpu = &vm->vcpu[vcpuid];
1924
1925         if (info & VM_INTINFO_VALID) {
1926                 type = info & VM_INTINFO_TYPE;
1927                 vector = info & 0xff;
1928                 if (type == VM_INTINFO_NMI && vector != IDT_NMI)
1929                         return (EINVAL);
1930                 if (type == VM_INTINFO_HWEXCEPTION && vector >= 32)
1931                         return (EINVAL);
1932                 if (info & VM_INTINFO_RSVD)
1933                         return (EINVAL);
1934         } else {
1935                 info = 0;
1936         }
1937         VCPU_CTR2(vm, vcpuid, "%s: info1(%#lx)", __func__, info);
1938         vcpu->exitintinfo = info;
1939         return (0);
1940 }
1941
1942 enum exc_class {
1943         EXC_BENIGN,
1944         EXC_CONTRIBUTORY,
1945         EXC_PAGEFAULT
1946 };
1947
1948 #define IDT_VE  20      /* Virtualization Exception (Intel specific) */
1949
1950 static enum exc_class
1951 exception_class(uint64_t info)
1952 {
1953         int type, vector;
1954
1955         KASSERT(info & VM_INTINFO_VALID, ("intinfo must be valid: %#lx", info));
1956         type = info & VM_INTINFO_TYPE;
1957         vector = info & 0xff;
1958
1959         /* Table 6-4, "Interrupt and Exception Classes", Intel SDM, Vol 3 */
1960         switch (type) {
1961         case VM_INTINFO_HWINTR:
1962         case VM_INTINFO_SWINTR:
1963         case VM_INTINFO_NMI:
1964                 return (EXC_BENIGN);
1965         default:
1966                 /*
1967                  * Hardware exception.
1968                  *
1969                  * SVM and VT-x use identical type values to represent NMI,
1970                  * hardware interrupt and software interrupt.
1971                  *
1972                  * SVM uses type '3' for all exceptions. VT-x uses type '3'
1973                  * for exceptions except #BP and #OF. #BP and #OF use a type
1974                  * value of '5' or '6'. Therefore we don't check for explicit
1975                  * values of 'type' to classify 'intinfo' into a hardware
1976                  * exception.
1977                  */
1978                 break;
1979         }
1980
1981         switch (vector) {
1982         case IDT_PF:
1983         case IDT_VE:
1984                 return (EXC_PAGEFAULT);
1985         case IDT_DE:
1986         case IDT_TS:
1987         case IDT_NP:
1988         case IDT_SS:
1989         case IDT_GP:
1990                 return (EXC_CONTRIBUTORY);
1991         default:
1992                 return (EXC_BENIGN);
1993         }
1994 }
1995
1996 static int
1997 nested_fault(struct vm *vm, int vcpuid, uint64_t info1, uint64_t info2,
1998     uint64_t *retinfo)
1999 {
2000         enum exc_class exc1, exc2;
2001         int type1, vector1;
2002
2003         KASSERT(info1 & VM_INTINFO_VALID, ("info1 %#lx is not valid", info1));
2004         KASSERT(info2 & VM_INTINFO_VALID, ("info2 %#lx is not valid", info2));
2005
2006         /*
2007          * If an exception occurs while attempting to call the double-fault
2008          * handler the processor enters shutdown mode (aka triple fault).
2009          */
2010         type1 = info1 & VM_INTINFO_TYPE;
2011         vector1 = info1 & 0xff;
2012         if (type1 == VM_INTINFO_HWEXCEPTION && vector1 == IDT_DF) {
2013                 VCPU_CTR2(vm, vcpuid, "triple fault: info1(%#lx), info2(%#lx)",
2014                     info1, info2);
2015                 vm_suspend(vm, VM_SUSPEND_TRIPLEFAULT);
2016                 *retinfo = 0;
2017                 return (0);
2018         }
2019
2020         /*
2021          * Table 6-5 "Conditions for Generating a Double Fault", Intel SDM, Vol3
2022          */
2023         exc1 = exception_class(info1);
2024         exc2 = exception_class(info2);
2025         if ((exc1 == EXC_CONTRIBUTORY && exc2 == EXC_CONTRIBUTORY) ||
2026             (exc1 == EXC_PAGEFAULT && exc2 != EXC_BENIGN)) {
2027                 /* Convert nested fault into a double fault. */
2028                 *retinfo = IDT_DF;
2029                 *retinfo |= VM_INTINFO_VALID | VM_INTINFO_HWEXCEPTION;
2030                 *retinfo |= VM_INTINFO_DEL_ERRCODE;
2031         } else {
2032                 /* Handle exceptions serially */
2033                 *retinfo = info2;
2034         }
2035         return (1);
2036 }
2037
2038 static uint64_t
2039 vcpu_exception_intinfo(struct vcpu *vcpu)
2040 {
2041         uint64_t info = 0;
2042
2043         if (vcpu->exception_pending) {
2044                 info = vcpu->exc_vector & 0xff;
2045                 info |= VM_INTINFO_VALID | VM_INTINFO_HWEXCEPTION;
2046                 if (vcpu->exc_errcode_valid) {
2047                         info |= VM_INTINFO_DEL_ERRCODE;
2048                         info |= (uint64_t)vcpu->exc_errcode << 32;
2049                 }
2050         }
2051         return (info);
2052 }
2053
2054 int
2055 vm_entry_intinfo(struct vm *vm, int vcpuid, uint64_t *retinfo)
2056 {
2057         struct vcpu *vcpu;
2058         uint64_t info1, info2;
2059         int valid;
2060
2061         KASSERT(vcpuid >= 0 &&
2062             vcpuid < vm->maxcpus, ("invalid vcpu %d", vcpuid));
2063
2064         vcpu = &vm->vcpu[vcpuid];
2065
2066         info1 = vcpu->exitintinfo;
2067         vcpu->exitintinfo = 0;
2068
2069         info2 = 0;
2070         if (vcpu->exception_pending) {
2071                 info2 = vcpu_exception_intinfo(vcpu);
2072                 vcpu->exception_pending = 0;
2073                 VCPU_CTR2(vm, vcpuid, "Exception %d delivered: %#lx",
2074                     vcpu->exc_vector, info2);
2075         }
2076
2077         if ((info1 & VM_INTINFO_VALID) && (info2 & VM_INTINFO_VALID)) {
2078                 valid = nested_fault(vm, vcpuid, info1, info2, retinfo);
2079         } else if (info1 & VM_INTINFO_VALID) {
2080                 *retinfo = info1;
2081                 valid = 1;
2082         } else if (info2 & VM_INTINFO_VALID) {
2083                 *retinfo = info2;
2084                 valid = 1;
2085         } else {
2086                 valid = 0;
2087         }
2088
2089         if (valid) {
2090                 VCPU_CTR4(vm, vcpuid, "%s: info1(%#lx), info2(%#lx), "
2091                     "retinfo(%#lx)", __func__, info1, info2, *retinfo);
2092         }
2093
2094         return (valid);
2095 }
2096
2097 int
2098 vm_get_intinfo(struct vm *vm, int vcpuid, uint64_t *info1, uint64_t *info2)
2099 {
2100         struct vcpu *vcpu;
2101
2102         if (vcpuid < 0 || vcpuid >= vm->maxcpus)
2103                 return (EINVAL);
2104
2105         vcpu = &vm->vcpu[vcpuid];
2106         *info1 = vcpu->exitintinfo;
2107         *info2 = vcpu_exception_intinfo(vcpu);
2108         return (0);
2109 }
2110
2111 int
2112 vm_inject_exception(struct vm *vm, int vcpuid, int vector, int errcode_valid,
2113     uint32_t errcode, int restart_instruction)
2114 {
2115         struct vcpu *vcpu;
2116         uint64_t regval;
2117         int error __diagused;
2118
2119         if (vcpuid < 0 || vcpuid >= vm->maxcpus)
2120                 return (EINVAL);
2121
2122         if (vector < 0 || vector >= 32)
2123                 return (EINVAL);
2124
2125         /*
2126          * A double fault exception should never be injected directly into
2127          * the guest. It is a derived exception that results from specific
2128          * combinations of nested faults.
2129          */
2130         if (vector == IDT_DF)
2131                 return (EINVAL);
2132
2133         vcpu = &vm->vcpu[vcpuid];
2134
2135         if (vcpu->exception_pending) {
2136                 VCPU_CTR2(vm, vcpuid, "Unable to inject exception %d due to "
2137                     "pending exception %d", vector, vcpu->exc_vector);
2138                 return (EBUSY);
2139         }
2140
2141         if (errcode_valid) {
2142                 /*
2143                  * Exceptions don't deliver an error code in real mode.
2144                  */
2145                 error = vm_get_register(vm, vcpuid, VM_REG_GUEST_CR0, &regval);
2146                 KASSERT(!error, ("%s: error %d getting CR0", __func__, error));
2147                 if (!(regval & CR0_PE))
2148                         errcode_valid = 0;
2149         }
2150
2151         /*
2152          * From section 26.6.1 "Interruptibility State" in Intel SDM:
2153          *
2154          * Event blocking by "STI" or "MOV SS" is cleared after guest executes
2155          * one instruction or incurs an exception.
2156          */
2157         error = vm_set_register(vm, vcpuid, VM_REG_GUEST_INTR_SHADOW, 0);
2158         KASSERT(error == 0, ("%s: error %d clearing interrupt shadow",
2159             __func__, error));
2160
2161         if (restart_instruction)
2162                 vm_restart_instruction(vm, vcpuid);
2163
2164         vcpu->exception_pending = 1;
2165         vcpu->exc_vector = vector;
2166         vcpu->exc_errcode = errcode;
2167         vcpu->exc_errcode_valid = errcode_valid;
2168         VCPU_CTR1(vm, vcpuid, "Exception %d pending", vector);
2169         return (0);
2170 }
2171
2172 void
2173 vm_inject_fault(void *vmarg, int vcpuid, int vector, int errcode_valid,
2174     int errcode)
2175 {
2176         struct vm *vm;
2177         int error __diagused, restart_instruction;
2178
2179         vm = vmarg;
2180         restart_instruction = 1;
2181
2182         error = vm_inject_exception(vm, vcpuid, vector, errcode_valid,
2183             errcode, restart_instruction);
2184         KASSERT(error == 0, ("vm_inject_exception error %d", error));
2185 }
2186
2187 void
2188 vm_inject_pf(void *vmarg, int vcpuid, int error_code, uint64_t cr2)
2189 {
2190         struct vm *vm;
2191         int error __diagused;
2192
2193         vm = vmarg;
2194         VCPU_CTR2(vm, vcpuid, "Injecting page fault: error_code %#x, cr2 %#lx",
2195             error_code, cr2);
2196
2197         error = vm_set_register(vm, vcpuid, VM_REG_GUEST_CR2, cr2);
2198         KASSERT(error == 0, ("vm_set_register(cr2) error %d", error));
2199
2200         vm_inject_fault(vm, vcpuid, IDT_PF, 1, error_code);
2201 }
2202
2203 static VMM_STAT(VCPU_NMI_COUNT, "number of NMIs delivered to vcpu");
2204
2205 int
2206 vm_inject_nmi(struct vm *vm, int vcpuid)
2207 {
2208         struct vcpu *vcpu;
2209
2210         if (vcpuid < 0 || vcpuid >= vm->maxcpus)
2211                 return (EINVAL);
2212
2213         vcpu = &vm->vcpu[vcpuid];
2214
2215         vcpu->nmi_pending = 1;
2216         vcpu_notify_event(vm, vcpuid, false);
2217         return (0);
2218 }
2219
2220 int
2221 vm_nmi_pending(struct vm *vm, int vcpuid)
2222 {
2223         struct vcpu *vcpu;
2224
2225         if (vcpuid < 0 || vcpuid >= vm->maxcpus)
2226                 panic("vm_nmi_pending: invalid vcpuid %d", vcpuid);
2227
2228         vcpu = &vm->vcpu[vcpuid];
2229
2230         return (vcpu->nmi_pending);
2231 }
2232
2233 void
2234 vm_nmi_clear(struct vm *vm, int vcpuid)
2235 {
2236         struct vcpu *vcpu;
2237
2238         if (vcpuid < 0 || vcpuid >= vm->maxcpus)
2239                 panic("vm_nmi_pending: invalid vcpuid %d", vcpuid);
2240
2241         vcpu = &vm->vcpu[vcpuid];
2242
2243         if (vcpu->nmi_pending == 0)
2244                 panic("vm_nmi_clear: inconsistent nmi_pending state");
2245
2246         vcpu->nmi_pending = 0;
2247         vmm_stat_incr(vm, vcpuid, VCPU_NMI_COUNT, 1);
2248 }
2249
2250 static VMM_STAT(VCPU_EXTINT_COUNT, "number of ExtINTs delivered to vcpu");
2251
2252 int
2253 vm_inject_extint(struct vm *vm, int vcpuid)
2254 {
2255         struct vcpu *vcpu;
2256
2257         if (vcpuid < 0 || vcpuid >= vm->maxcpus)
2258                 return (EINVAL);
2259
2260         vcpu = &vm->vcpu[vcpuid];
2261
2262         vcpu->extint_pending = 1;
2263         vcpu_notify_event(vm, vcpuid, false);
2264         return (0);
2265 }
2266
2267 int
2268 vm_extint_pending(struct vm *vm, int vcpuid)
2269 {
2270         struct vcpu *vcpu;
2271
2272         if (vcpuid < 0 || vcpuid >= vm->maxcpus)
2273                 panic("vm_extint_pending: invalid vcpuid %d", vcpuid);
2274
2275         vcpu = &vm->vcpu[vcpuid];
2276
2277         return (vcpu->extint_pending);
2278 }
2279
2280 void
2281 vm_extint_clear(struct vm *vm, int vcpuid)
2282 {
2283         struct vcpu *vcpu;
2284
2285         if (vcpuid < 0 || vcpuid >= vm->maxcpus)
2286                 panic("vm_extint_pending: invalid vcpuid %d", vcpuid);
2287
2288         vcpu = &vm->vcpu[vcpuid];
2289
2290         if (vcpu->extint_pending == 0)
2291                 panic("vm_extint_clear: inconsistent extint_pending state");
2292
2293         vcpu->extint_pending = 0;
2294         vmm_stat_incr(vm, vcpuid, VCPU_EXTINT_COUNT, 1);
2295 }
2296
2297 int
2298 vm_get_capability(struct vm *vm, int vcpu, int type, int *retval)
2299 {
2300         if (vcpu < 0 || vcpu >= vm->maxcpus)
2301                 return (EINVAL);
2302
2303         if (type < 0 || type >= VM_CAP_MAX)
2304                 return (EINVAL);
2305
2306         return (vmmops_getcap(vcpu_cookie(vm, vcpu), type, retval));
2307 }
2308
2309 int
2310 vm_set_capability(struct vm *vm, int vcpu, int type, int val)
2311 {
2312         if (vcpu < 0 || vcpu >= vm->maxcpus)
2313                 return (EINVAL);
2314
2315         if (type < 0 || type >= VM_CAP_MAX)
2316                 return (EINVAL);
2317
2318         return (vmmops_setcap(vcpu_cookie(vm, vcpu), type, val));
2319 }
2320
2321 struct vm *
2322 vcpu_vm(struct vcpu *vcpu)
2323 {
2324         return (vcpu->vm);
2325 }
2326
2327 int
2328 vcpu_vcpuid(struct vcpu *vcpu)
2329 {
2330         return (vcpu->vcpuid);
2331 }
2332
2333 struct vcpu *
2334 vm_vcpu(struct vm *vm, int vcpuid)
2335 {
2336         return (&vm->vcpu[vcpuid]);
2337 }
2338
2339 struct vlapic *
2340 vm_lapic(struct vm *vm, int cpu)
2341 {
2342         return (vm->vcpu[cpu].vlapic);
2343 }
2344
2345 struct vioapic *
2346 vm_ioapic(struct vm *vm)
2347 {
2348
2349         return (vm->vioapic);
2350 }
2351
2352 struct vhpet *
2353 vm_hpet(struct vm *vm)
2354 {
2355
2356         return (vm->vhpet);
2357 }
2358
2359 bool
2360 vmm_is_pptdev(int bus, int slot, int func)
2361 {
2362         int b, f, i, n, s;
2363         char *val, *cp, *cp2;
2364         bool found;
2365
2366         /*
2367          * XXX
2368          * The length of an environment variable is limited to 128 bytes which
2369          * puts an upper limit on the number of passthru devices that may be
2370          * specified using a single environment variable.
2371          *
2372          * Work around this by scanning multiple environment variable
2373          * names instead of a single one - yuck!
2374          */
2375         const char *names[] = { "pptdevs", "pptdevs2", "pptdevs3", NULL };
2376
2377         /* set pptdevs="1/2/3 4/5/6 7/8/9 10/11/12" */
2378         found = false;
2379         for (i = 0; names[i] != NULL && !found; i++) {
2380                 cp = val = kern_getenv(names[i]);
2381                 while (cp != NULL && *cp != '\0') {
2382                         if ((cp2 = strchr(cp, ' ')) != NULL)
2383                                 *cp2 = '\0';
2384
2385                         n = sscanf(cp, "%d/%d/%d", &b, &s, &f);
2386                         if (n == 3 && bus == b && slot == s && func == f) {
2387                                 found = true;
2388                                 break;
2389                         }
2390                 
2391                         if (cp2 != NULL)
2392                                 *cp2++ = ' ';
2393
2394                         cp = cp2;
2395                 }
2396                 freeenv(val);
2397         }
2398         return (found);
2399 }
2400
2401 void *
2402 vm_iommu_domain(struct vm *vm)
2403 {
2404
2405         return (vm->iommu);
2406 }
2407
2408 int
2409 vcpu_set_state(struct vm *vm, int vcpuid, enum vcpu_state newstate,
2410     bool from_idle)
2411 {
2412         int error;
2413         struct vcpu *vcpu;
2414
2415         if (vcpuid < 0 || vcpuid >= vm->maxcpus)
2416                 panic("vm_set_run_state: invalid vcpuid %d", vcpuid);
2417
2418         vcpu = &vm->vcpu[vcpuid];
2419
2420         vcpu_lock(vcpu);
2421         error = vcpu_set_state_locked(vm, vcpuid, newstate, from_idle);
2422         vcpu_unlock(vcpu);
2423
2424         return (error);
2425 }
2426
2427 enum vcpu_state
2428 vcpu_get_state(struct vm *vm, int vcpuid, int *hostcpu)
2429 {
2430         struct vcpu *vcpu;
2431         enum vcpu_state state;
2432
2433         if (vcpuid < 0 || vcpuid >= vm->maxcpus)
2434                 panic("vm_get_run_state: invalid vcpuid %d", vcpuid);
2435
2436         vcpu = &vm->vcpu[vcpuid];
2437
2438         vcpu_lock(vcpu);
2439         state = vcpu->state;
2440         if (hostcpu != NULL)
2441                 *hostcpu = vcpu->hostcpu;
2442         vcpu_unlock(vcpu);
2443
2444         return (state);
2445 }
2446
2447 int
2448 vm_activate_cpu(struct vm *vm, int vcpuid)
2449 {
2450
2451         if (vcpuid < 0 || vcpuid >= vm->maxcpus)
2452                 return (EINVAL);
2453
2454         if (CPU_ISSET(vcpuid, &vm->active_cpus))
2455                 return (EBUSY);
2456
2457         VCPU_CTR0(vm, vcpuid, "activated");
2458         CPU_SET_ATOMIC(vcpuid, &vm->active_cpus);
2459         return (0);
2460 }
2461
2462 int
2463 vm_suspend_cpu(struct vm *vm, int vcpuid)
2464 {
2465         int i;
2466
2467         if (vcpuid < -1 || vcpuid >= vm->maxcpus)
2468                 return (EINVAL);
2469
2470         if (vcpuid == -1) {
2471                 vm->debug_cpus = vm->active_cpus;
2472                 for (i = 0; i < vm->maxcpus; i++) {
2473                         if (CPU_ISSET(i, &vm->active_cpus))
2474                                 vcpu_notify_event(vm, i, false);
2475                 }
2476         } else {
2477                 if (!CPU_ISSET(vcpuid, &vm->active_cpus))
2478                         return (EINVAL);
2479
2480                 CPU_SET_ATOMIC(vcpuid, &vm->debug_cpus);
2481                 vcpu_notify_event(vm, vcpuid, false);
2482         }
2483         return (0);
2484 }
2485
2486 int
2487 vm_resume_cpu(struct vm *vm, int vcpuid)
2488 {
2489
2490         if (vcpuid < -1 || vcpuid >= vm->maxcpus)
2491                 return (EINVAL);
2492
2493         if (vcpuid == -1) {
2494                 CPU_ZERO(&vm->debug_cpus);
2495         } else {
2496                 if (!CPU_ISSET(vcpuid, &vm->debug_cpus))
2497                         return (EINVAL);
2498
2499                 CPU_CLR_ATOMIC(vcpuid, &vm->debug_cpus);
2500         }
2501         return (0);
2502 }
2503
2504 int
2505 vcpu_debugged(struct vm *vm, int vcpuid)
2506 {
2507
2508         return (CPU_ISSET(vcpuid, &vm->debug_cpus));
2509 }
2510
2511 cpuset_t
2512 vm_active_cpus(struct vm *vm)
2513 {
2514
2515         return (vm->active_cpus);
2516 }
2517
2518 cpuset_t
2519 vm_debug_cpus(struct vm *vm)
2520 {
2521
2522         return (vm->debug_cpus);
2523 }
2524
2525 cpuset_t
2526 vm_suspended_cpus(struct vm *vm)
2527 {
2528
2529         return (vm->suspended_cpus);
2530 }
2531
2532 void *
2533 vcpu_stats(struct vm *vm, int vcpuid)
2534 {
2535
2536         return (vm->vcpu[vcpuid].stats);
2537 }
2538
2539 int
2540 vm_get_x2apic_state(struct vm *vm, int vcpuid, enum x2apic_state *state)
2541 {
2542         if (vcpuid < 0 || vcpuid >= vm->maxcpus)
2543                 return (EINVAL);
2544
2545         *state = vm->vcpu[vcpuid].x2apic_state;
2546
2547         return (0);
2548 }
2549
2550 int
2551 vm_set_x2apic_state(struct vm *vm, int vcpuid, enum x2apic_state state)
2552 {
2553         if (vcpuid < 0 || vcpuid >= vm->maxcpus)
2554                 return (EINVAL);
2555
2556         if (state >= X2APIC_STATE_LAST)
2557                 return (EINVAL);
2558
2559         vm->vcpu[vcpuid].x2apic_state = state;
2560
2561         vlapic_set_x2apic_state(vm, vcpuid, state);
2562
2563         return (0);
2564 }
2565
2566 /*
2567  * This function is called to ensure that a vcpu "sees" a pending event
2568  * as soon as possible:
2569  * - If the vcpu thread is sleeping then it is woken up.
2570  * - If the vcpu is running on a different host_cpu then an IPI will be directed
2571  *   to the host_cpu to cause the vcpu to trap into the hypervisor.
2572  */
2573 static void
2574 vcpu_notify_event_locked(struct vcpu *vcpu, bool lapic_intr)
2575 {
2576         int hostcpu;
2577
2578         hostcpu = vcpu->hostcpu;
2579         if (vcpu->state == VCPU_RUNNING) {
2580                 KASSERT(hostcpu != NOCPU, ("vcpu running on invalid hostcpu"));
2581                 if (hostcpu != curcpu) {
2582                         if (lapic_intr) {
2583                                 vlapic_post_intr(vcpu->vlapic, hostcpu,
2584                                     vmm_ipinum);
2585                         } else {
2586                                 ipi_cpu(hostcpu, vmm_ipinum);
2587                         }
2588                 } else {
2589                         /*
2590                          * If the 'vcpu' is running on 'curcpu' then it must
2591                          * be sending a notification to itself (e.g. SELF_IPI).
2592                          * The pending event will be picked up when the vcpu
2593                          * transitions back to guest context.
2594                          */
2595                 }
2596         } else {
2597                 KASSERT(hostcpu == NOCPU, ("vcpu state %d not consistent "
2598                     "with hostcpu %d", vcpu->state, hostcpu));
2599                 if (vcpu->state == VCPU_SLEEPING)
2600                         wakeup_one(vcpu);
2601         }
2602 }
2603
2604 void
2605 vcpu_notify_event(struct vm *vm, int vcpuid, bool lapic_intr)
2606 {
2607         struct vcpu *vcpu = &vm->vcpu[vcpuid];
2608
2609         vcpu_lock(vcpu);
2610         vcpu_notify_event_locked(vcpu, lapic_intr);
2611         vcpu_unlock(vcpu);
2612 }
2613
2614 struct vmspace *
2615 vm_get_vmspace(struct vm *vm)
2616 {
2617
2618         return (vm->vmspace);
2619 }
2620
2621 int
2622 vm_apicid2vcpuid(struct vm *vm, int apicid)
2623 {
2624         /*
2625          * XXX apic id is assumed to be numerically identical to vcpu id
2626          */
2627         return (apicid);
2628 }
2629
2630 int
2631 vm_smp_rendezvous(struct vm *vm, int vcpuid, cpuset_t dest,
2632     vm_rendezvous_func_t func, void *arg)
2633 {
2634         int error, i;
2635
2636         /*
2637          * Enforce that this function is called without any locks
2638          */
2639         WITNESS_WARN(WARN_PANIC, NULL, "vm_smp_rendezvous");
2640         KASSERT(vcpuid == -1 || (vcpuid >= 0 && vcpuid < vm->maxcpus),
2641             ("vm_smp_rendezvous: invalid vcpuid %d", vcpuid));
2642
2643 restart:
2644         mtx_lock(&vm->rendezvous_mtx);
2645         if (vm->rendezvous_func != NULL) {
2646                 /*
2647                  * If a rendezvous is already in progress then we need to
2648                  * call the rendezvous handler in case this 'vcpuid' is one
2649                  * of the targets of the rendezvous.
2650                  */
2651                 RENDEZVOUS_CTR0(vm, vcpuid, "Rendezvous already in progress");
2652                 mtx_unlock(&vm->rendezvous_mtx);
2653                 error = vm_handle_rendezvous(vm, vcpuid);
2654                 if (error != 0)
2655                         return (error);
2656                 goto restart;
2657         }
2658         KASSERT(vm->rendezvous_func == NULL, ("vm_smp_rendezvous: previous "
2659             "rendezvous is still in progress"));
2660
2661         RENDEZVOUS_CTR0(vm, vcpuid, "Initiating rendezvous");
2662         vm->rendezvous_req_cpus = dest;
2663         CPU_ZERO(&vm->rendezvous_done_cpus);
2664         vm->rendezvous_arg = arg;
2665         vm->rendezvous_func = func;
2666         mtx_unlock(&vm->rendezvous_mtx);
2667
2668         /*
2669          * Wake up any sleeping vcpus and trigger a VM-exit in any running
2670          * vcpus so they handle the rendezvous as soon as possible.
2671          */
2672         for (i = 0; i < vm->maxcpus; i++) {
2673                 if (CPU_ISSET(i, &dest))
2674                         vcpu_notify_event(vm, i, false);
2675         }
2676
2677         return (vm_handle_rendezvous(vm, vcpuid));
2678 }
2679
2680 struct vatpic *
2681 vm_atpic(struct vm *vm)
2682 {
2683         return (vm->vatpic);
2684 }
2685
2686 struct vatpit *
2687 vm_atpit(struct vm *vm)
2688 {
2689         return (vm->vatpit);
2690 }
2691
2692 struct vpmtmr *
2693 vm_pmtmr(struct vm *vm)
2694 {
2695
2696         return (vm->vpmtmr);
2697 }
2698
2699 struct vrtc *
2700 vm_rtc(struct vm *vm)
2701 {
2702
2703         return (vm->vrtc);
2704 }
2705
2706 enum vm_reg_name
2707 vm_segment_name(int seg)
2708 {
2709         static enum vm_reg_name seg_names[] = {
2710                 VM_REG_GUEST_ES,
2711                 VM_REG_GUEST_CS,
2712                 VM_REG_GUEST_SS,
2713                 VM_REG_GUEST_DS,
2714                 VM_REG_GUEST_FS,
2715                 VM_REG_GUEST_GS
2716         };
2717
2718         KASSERT(seg >= 0 && seg < nitems(seg_names),
2719             ("%s: invalid segment encoding %d", __func__, seg));
2720         return (seg_names[seg]);
2721 }
2722
2723 void
2724 vm_copy_teardown(struct vm *vm, int vcpuid, struct vm_copyinfo *copyinfo,
2725     int num_copyinfo)
2726 {
2727         int idx;
2728
2729         for (idx = 0; idx < num_copyinfo; idx++) {
2730                 if (copyinfo[idx].cookie != NULL)
2731                         vm_gpa_release(copyinfo[idx].cookie);
2732         }
2733         bzero(copyinfo, num_copyinfo * sizeof(struct vm_copyinfo));
2734 }
2735
2736 int
2737 vm_copy_setup(struct vm *vm, int vcpuid, struct vm_guest_paging *paging,
2738     uint64_t gla, size_t len, int prot, struct vm_copyinfo *copyinfo,
2739     int num_copyinfo, int *fault)
2740 {
2741         int error, idx, nused;
2742         size_t n, off, remaining;
2743         void *hva, *cookie;
2744         uint64_t gpa;
2745
2746         bzero(copyinfo, sizeof(struct vm_copyinfo) * num_copyinfo);
2747
2748         nused = 0;
2749         remaining = len;
2750         while (remaining > 0) {
2751                 KASSERT(nused < num_copyinfo, ("insufficient vm_copyinfo"));
2752                 error = vm_gla2gpa(vm, vcpuid, paging, gla, prot, &gpa, fault);
2753                 if (error || *fault)
2754                         return (error);
2755                 off = gpa & PAGE_MASK;
2756                 n = min(remaining, PAGE_SIZE - off);
2757                 copyinfo[nused].gpa = gpa;
2758                 copyinfo[nused].len = n;
2759                 remaining -= n;
2760                 gla += n;
2761                 nused++;
2762         }
2763
2764         for (idx = 0; idx < nused; idx++) {
2765                 hva = vm_gpa_hold(vm, vcpuid, copyinfo[idx].gpa,
2766                     copyinfo[idx].len, prot, &cookie);
2767                 if (hva == NULL)
2768                         break;
2769                 copyinfo[idx].hva = hva;
2770                 copyinfo[idx].cookie = cookie;
2771         }
2772
2773         if (idx != nused) {
2774                 vm_copy_teardown(vm, vcpuid, copyinfo, num_copyinfo);
2775                 return (EFAULT);
2776         } else {
2777                 *fault = 0;
2778                 return (0);
2779         }
2780 }
2781
2782 void
2783 vm_copyin(struct vm *vm, int vcpuid, struct vm_copyinfo *copyinfo, void *kaddr,
2784     size_t len)
2785 {
2786         char *dst;
2787         int idx;
2788
2789         dst = kaddr;
2790         idx = 0;
2791         while (len > 0) {
2792                 bcopy(copyinfo[idx].hva, dst, copyinfo[idx].len);
2793                 len -= copyinfo[idx].len;
2794                 dst += copyinfo[idx].len;
2795                 idx++;
2796         }
2797 }
2798
2799 void
2800 vm_copyout(struct vm *vm, int vcpuid, const void *kaddr,
2801     struct vm_copyinfo *copyinfo, size_t len)
2802 {
2803         const char *src;
2804         int idx;
2805
2806         src = kaddr;
2807         idx = 0;
2808         while (len > 0) {
2809                 bcopy(src, copyinfo[idx].hva, copyinfo[idx].len);
2810                 len -= copyinfo[idx].len;
2811                 src += copyinfo[idx].len;
2812                 idx++;
2813         }
2814 }
2815
2816 /*
2817  * Return the amount of in-use and wired memory for the VM. Since
2818  * these are global stats, only return the values with for vCPU 0
2819  */
2820 VMM_STAT_DECLARE(VMM_MEM_RESIDENT);
2821 VMM_STAT_DECLARE(VMM_MEM_WIRED);
2822
2823 static void
2824 vm_get_rescnt(struct vm *vm, int vcpu, struct vmm_stat_type *stat)
2825 {
2826
2827         if (vcpu == 0) {
2828                 vmm_stat_set(vm, vcpu, VMM_MEM_RESIDENT,
2829                     PAGE_SIZE * vmspace_resident_count(vm->vmspace));
2830         }       
2831 }
2832
2833 static void
2834 vm_get_wiredcnt(struct vm *vm, int vcpu, struct vmm_stat_type *stat)
2835 {
2836
2837         if (vcpu == 0) {
2838                 vmm_stat_set(vm, vcpu, VMM_MEM_WIRED,
2839                     PAGE_SIZE * pmap_wired_count(vmspace_pmap(vm->vmspace)));
2840         }       
2841 }
2842
2843 VMM_STAT_FUNC(VMM_MEM_RESIDENT, "Resident memory", vm_get_rescnt);
2844 VMM_STAT_FUNC(VMM_MEM_WIRED, "Wired memory", vm_get_wiredcnt);
2845
2846 #ifdef BHYVE_SNAPSHOT
2847 static int
2848 vm_snapshot_vcpus(struct vm *vm, struct vm_snapshot_meta *meta)
2849 {
2850         uint64_t tsc, now;
2851         int ret;
2852         struct vcpu *vcpu;
2853         uint16_t i, maxcpus;
2854
2855         now = rdtsc();
2856         maxcpus = vm_get_maxcpus(vm);
2857         for (i = 0; i < maxcpus; i++) {
2858                 vcpu = &vm->vcpu[i];
2859
2860                 SNAPSHOT_VAR_OR_LEAVE(vcpu->x2apic_state, meta, ret, done);
2861                 SNAPSHOT_VAR_OR_LEAVE(vcpu->exitintinfo, meta, ret, done);
2862                 SNAPSHOT_VAR_OR_LEAVE(vcpu->exc_vector, meta, ret, done);
2863                 SNAPSHOT_VAR_OR_LEAVE(vcpu->exc_errcode_valid, meta, ret, done);
2864                 SNAPSHOT_VAR_OR_LEAVE(vcpu->exc_errcode, meta, ret, done);
2865                 SNAPSHOT_VAR_OR_LEAVE(vcpu->guest_xcr0, meta, ret, done);
2866                 SNAPSHOT_VAR_OR_LEAVE(vcpu->exitinfo, meta, ret, done);
2867                 SNAPSHOT_VAR_OR_LEAVE(vcpu->nextrip, meta, ret, done);
2868
2869                 /*
2870                  * Save the absolute TSC value by adding now to tsc_offset.
2871                  *
2872                  * It will be turned turned back into an actual offset when the
2873                  * TSC restore function is called
2874                  */
2875                 tsc = now + vcpu->tsc_offset;
2876                 SNAPSHOT_VAR_OR_LEAVE(tsc, meta, ret, done);
2877         }
2878
2879 done:
2880         return (ret);
2881 }
2882
2883 static int
2884 vm_snapshot_vm(struct vm *vm, struct vm_snapshot_meta *meta)
2885 {
2886         int ret;
2887
2888         ret = vm_snapshot_vcpus(vm, meta);
2889         if (ret != 0)
2890                 goto done;
2891
2892 done:
2893         return (ret);
2894 }
2895
2896 static int
2897 vm_snapshot_vcpu(struct vm *vm, struct vm_snapshot_meta *meta)
2898 {
2899         int error;
2900         struct vcpu *vcpu;
2901         uint16_t i, maxcpus;
2902
2903         error = 0;
2904
2905         maxcpus = vm_get_maxcpus(vm);
2906         for (i = 0; i < maxcpus; i++) {
2907                 vcpu = &vm->vcpu[i];
2908
2909                 error = vmmops_vcpu_snapshot(vcpu->cookie, meta);
2910                 if (error != 0) {
2911                         printf("%s: failed to snapshot vmcs/vmcb data for "
2912                                "vCPU: %d; error: %d\n", __func__, i, error);
2913                         goto done;
2914                 }
2915         }
2916
2917 done:
2918         return (error);
2919 }
2920
2921 /*
2922  * Save kernel-side structures to user-space for snapshotting.
2923  */
2924 int
2925 vm_snapshot_req(struct vm *vm, struct vm_snapshot_meta *meta)
2926 {
2927         int ret = 0;
2928
2929         switch (meta->dev_req) {
2930         case STRUCT_VMX:
2931                 ret = vmmops_snapshot(vm->cookie, meta);
2932                 break;
2933         case STRUCT_VMCX:
2934                 ret = vm_snapshot_vcpu(vm, meta);
2935                 break;
2936         case STRUCT_VM:
2937                 ret = vm_snapshot_vm(vm, meta);
2938                 break;
2939         case STRUCT_VIOAPIC:
2940                 ret = vioapic_snapshot(vm_ioapic(vm), meta);
2941                 break;
2942         case STRUCT_VLAPIC:
2943                 ret = vlapic_snapshot(vm, meta);
2944                 break;
2945         case STRUCT_VHPET:
2946                 ret = vhpet_snapshot(vm_hpet(vm), meta);
2947                 break;
2948         case STRUCT_VATPIC:
2949                 ret = vatpic_snapshot(vm_atpic(vm), meta);
2950                 break;
2951         case STRUCT_VATPIT:
2952                 ret = vatpit_snapshot(vm_atpit(vm), meta);
2953                 break;
2954         case STRUCT_VPMTMR:
2955                 ret = vpmtmr_snapshot(vm_pmtmr(vm), meta);
2956                 break;
2957         case STRUCT_VRTC:
2958                 ret = vrtc_snapshot(vm_rtc(vm), meta);
2959                 break;
2960         default:
2961                 printf("%s: failed to find the requested type %#x\n",
2962                        __func__, meta->dev_req);
2963                 ret = (EINVAL);
2964         }
2965         return (ret);
2966 }
2967
2968 int
2969 vm_set_tsc_offset(struct vm *vm, int vcpuid, uint64_t offset)
2970 {
2971         struct vcpu *vcpu;
2972
2973         if (vcpuid < 0 || vcpuid >= vm_get_maxcpus(vm))
2974                 return (EINVAL);
2975
2976         vcpu = &vm->vcpu[vcpuid];
2977         vcpu->tsc_offset = offset;
2978
2979         return (0);
2980 }
2981
2982 int
2983 vm_restore_time(struct vm *vm)
2984 {
2985         int error;
2986         uint64_t now;
2987         struct vcpu *vcpu;
2988         uint16_t i, maxcpus;
2989
2990         now = rdtsc();
2991
2992         error = vhpet_restore_time(vm_hpet(vm));
2993         if (error)
2994                 return (error);
2995
2996         maxcpus = vm_get_maxcpus(vm);
2997         for (i = 0; i < maxcpus; i++) {
2998                 vcpu = &vm->vcpu[i];
2999
3000                 error = vmmops_restore_tsc(vcpu->cookie,
3001                     vcpu->tsc_offset - now);
3002                 if (error)
3003                         return (error);
3004         }
3005
3006         return (0);
3007 }
3008 #endif