]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/amd64/vmm/vmm.c
Update LLDB snapshot to upstream r225923 (git 2b588ecd)
[FreeBSD/FreeBSD.git] / sys / amd64 / vmm / vmm.c
1 /*-
2  * Copyright (c) 2011 NetApp, Inc.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD$
27  */
28
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/kernel.h>
35 #include <sys/module.h>
36 #include <sys/sysctl.h>
37 #include <sys/malloc.h>
38 #include <sys/pcpu.h>
39 #include <sys/lock.h>
40 #include <sys/mutex.h>
41 #include <sys/proc.h>
42 #include <sys/rwlock.h>
43 #include <sys/sched.h>
44 #include <sys/smp.h>
45 #include <sys/systm.h>
46
47 #include <vm/vm.h>
48 #include <vm/vm_object.h>
49 #include <vm/vm_page.h>
50 #include <vm/pmap.h>
51 #include <vm/vm_map.h>
52 #include <vm/vm_extern.h>
53 #include <vm/vm_param.h>
54
55 #include <machine/cpu.h>
56 #include <machine/vm.h>
57 #include <machine/pcb.h>
58 #include <machine/smp.h>
59 #include <x86/psl.h>
60 #include <x86/apicreg.h>
61 #include <machine/vmparam.h>
62
63 #include <machine/vmm.h>
64 #include <machine/vmm_dev.h>
65 #include <machine/vmm_instruction_emul.h>
66
67 #include "vmm_ioport.h"
68 #include "vmm_ktr.h"
69 #include "vmm_host.h"
70 #include "vmm_mem.h"
71 #include "vmm_util.h"
72 #include "vatpic.h"
73 #include "vatpit.h"
74 #include "vhpet.h"
75 #include "vioapic.h"
76 #include "vlapic.h"
77 #include "vpmtmr.h"
78 #include "vrtc.h"
79 #include "vmm_ipi.h"
80 #include "vmm_stat.h"
81 #include "vmm_lapic.h"
82
83 #include "io/ppt.h"
84 #include "io/iommu.h"
85
86 struct vlapic;
87
88 /*
89  * Initialization:
90  * (a) allocated when vcpu is created
91  * (i) initialized when vcpu is created and when it is reinitialized
92  * (o) initialized the first time the vcpu is created
93  * (x) initialized before use
94  */
95 struct vcpu {
96         struct mtx      mtx;            /* (o) protects 'state' and 'hostcpu' */
97         enum vcpu_state state;          /* (o) vcpu state */
98         int             hostcpu;        /* (o) vcpu's host cpu */
99         struct vlapic   *vlapic;        /* (i) APIC device model */
100         enum x2apic_state x2apic_state; /* (i) APIC mode */
101         uint64_t        exitintinfo;    /* (i) events pending at VM exit */
102         int             nmi_pending;    /* (i) NMI pending */
103         int             extint_pending; /* (i) INTR pending */
104         int     exception_pending;      /* (i) exception pending */
105         int     exc_vector;             /* (x) exception collateral */
106         int     exc_errcode_valid;
107         uint32_t exc_errcode;
108         struct savefpu  *guestfpu;      /* (a,i) guest fpu state */
109         uint64_t        guest_xcr0;     /* (i) guest %xcr0 register */
110         void            *stats;         /* (a,i) statistics */
111         struct vm_exit  exitinfo;       /* (x) exit reason and collateral */
112         uint64_t        nextrip;        /* (x) next instruction to execute */
113 };
114
115 #define vcpu_lock_initialized(v) mtx_initialized(&((v)->mtx))
116 #define vcpu_lock_init(v)       mtx_init(&((v)->mtx), "vcpu lock", 0, MTX_SPIN)
117 #define vcpu_lock(v)            mtx_lock_spin(&((v)->mtx))
118 #define vcpu_unlock(v)          mtx_unlock_spin(&((v)->mtx))
119 #define vcpu_assert_locked(v)   mtx_assert(&((v)->mtx), MA_OWNED)
120
121 struct mem_seg {
122         vm_paddr_t      gpa;
123         size_t          len;
124         boolean_t       wired;
125         vm_object_t     object;
126 };
127 #define VM_MAX_MEMORY_SEGMENTS  2
128
129 /*
130  * Initialization:
131  * (o) initialized the first time the VM is created
132  * (i) initialized when VM is created and when it is reinitialized
133  * (x) initialized before use
134  */
135 struct vm {
136         void            *cookie;                /* (i) cpu-specific data */
137         void            *iommu;                 /* (x) iommu-specific data */
138         struct vhpet    *vhpet;                 /* (i) virtual HPET */
139         struct vioapic  *vioapic;               /* (i) virtual ioapic */
140         struct vatpic   *vatpic;                /* (i) virtual atpic */
141         struct vatpit   *vatpit;                /* (i) virtual atpit */
142         struct vpmtmr   *vpmtmr;                /* (i) virtual ACPI PM timer */
143         struct vrtc     *vrtc;                  /* (o) virtual RTC */
144         volatile cpuset_t active_cpus;          /* (i) active vcpus */
145         int             suspend;                /* (i) stop VM execution */
146         volatile cpuset_t suspended_cpus;       /* (i) suspended vcpus */
147         volatile cpuset_t halted_cpus;          /* (x) cpus in a hard halt */
148         cpuset_t        rendezvous_req_cpus;    /* (x) rendezvous requested */
149         cpuset_t        rendezvous_done_cpus;   /* (x) rendezvous finished */
150         void            *rendezvous_arg;        /* (x) rendezvous func/arg */
151         vm_rendezvous_func_t rendezvous_func;
152         struct mtx      rendezvous_mtx;         /* (o) rendezvous lock */
153         int             num_mem_segs;           /* (o) guest memory segments */
154         struct mem_seg  mem_segs[VM_MAX_MEMORY_SEGMENTS];
155         struct vmspace  *vmspace;               /* (o) guest's address space */
156         char            name[VM_MAX_NAMELEN];   /* (o) virtual machine name */
157         struct vcpu     vcpu[VM_MAXCPU];        /* (i) guest vcpus */
158 };
159
160 static int vmm_initialized;
161
162 static struct vmm_ops *ops;
163 #define VMM_INIT(num)   (ops != NULL ? (*ops->init)(num) : 0)
164 #define VMM_CLEANUP()   (ops != NULL ? (*ops->cleanup)() : 0)
165 #define VMM_RESUME()    (ops != NULL ? (*ops->resume)() : 0)
166
167 #define VMINIT(vm, pmap) (ops != NULL ? (*ops->vminit)(vm, pmap): NULL)
168 #define VMRUN(vmi, vcpu, rip, pmap, rptr, sptr) \
169         (ops != NULL ? (*ops->vmrun)(vmi, vcpu, rip, pmap, rptr, sptr) : ENXIO)
170 #define VMCLEANUP(vmi)  (ops != NULL ? (*ops->vmcleanup)(vmi) : NULL)
171 #define VMSPACE_ALLOC(min, max) \
172         (ops != NULL ? (*ops->vmspace_alloc)(min, max) : NULL)
173 #define VMSPACE_FREE(vmspace) \
174         (ops != NULL ? (*ops->vmspace_free)(vmspace) : ENXIO)
175 #define VMGETREG(vmi, vcpu, num, retval)                \
176         (ops != NULL ? (*ops->vmgetreg)(vmi, vcpu, num, retval) : ENXIO)
177 #define VMSETREG(vmi, vcpu, num, val)           \
178         (ops != NULL ? (*ops->vmsetreg)(vmi, vcpu, num, val) : ENXIO)
179 #define VMGETDESC(vmi, vcpu, num, desc)         \
180         (ops != NULL ? (*ops->vmgetdesc)(vmi, vcpu, num, desc) : ENXIO)
181 #define VMSETDESC(vmi, vcpu, num, desc)         \
182         (ops != NULL ? (*ops->vmsetdesc)(vmi, vcpu, num, desc) : ENXIO)
183 #define VMGETCAP(vmi, vcpu, num, retval)        \
184         (ops != NULL ? (*ops->vmgetcap)(vmi, vcpu, num, retval) : ENXIO)
185 #define VMSETCAP(vmi, vcpu, num, val)           \
186         (ops != NULL ? (*ops->vmsetcap)(vmi, vcpu, num, val) : ENXIO)
187 #define VLAPIC_INIT(vmi, vcpu)                  \
188         (ops != NULL ? (*ops->vlapic_init)(vmi, vcpu) : NULL)
189 #define VLAPIC_CLEANUP(vmi, vlapic)             \
190         (ops != NULL ? (*ops->vlapic_cleanup)(vmi, vlapic) : NULL)
191
192 #define fpu_start_emulating()   load_cr0(rcr0() | CR0_TS)
193 #define fpu_stop_emulating()    clts()
194
195 static MALLOC_DEFINE(M_VM, "vm", "vm");
196
197 /* statistics */
198 static VMM_STAT(VCPU_TOTAL_RUNTIME, "vcpu total runtime");
199
200 SYSCTL_NODE(_hw, OID_AUTO, vmm, CTLFLAG_RW, NULL, NULL);
201
202 /*
203  * Halt the guest if all vcpus are executing a HLT instruction with
204  * interrupts disabled.
205  */
206 static int halt_detection_enabled = 1;
207 SYSCTL_INT(_hw_vmm, OID_AUTO, halt_detection, CTLFLAG_RDTUN,
208     &halt_detection_enabled, 0,
209     "Halt VM if all vcpus execute HLT with interrupts disabled");
210
211 static int vmm_ipinum;
212 SYSCTL_INT(_hw_vmm, OID_AUTO, ipinum, CTLFLAG_RD, &vmm_ipinum, 0,
213     "IPI vector used for vcpu notifications");
214
215 static int trace_guest_exceptions;
216 SYSCTL_INT(_hw_vmm, OID_AUTO, trace_guest_exceptions, CTLFLAG_RDTUN,
217     &trace_guest_exceptions, 0,
218     "Trap into hypervisor on all guest exceptions and reflect them back");
219
220 static void
221 vcpu_cleanup(struct vm *vm, int i, bool destroy)
222 {
223         struct vcpu *vcpu = &vm->vcpu[i];
224
225         VLAPIC_CLEANUP(vm->cookie, vcpu->vlapic);
226         if (destroy) {
227                 vmm_stat_free(vcpu->stats);     
228                 fpu_save_area_free(vcpu->guestfpu);
229         }
230 }
231
232 static void
233 vcpu_init(struct vm *vm, int vcpu_id, bool create)
234 {
235         struct vcpu *vcpu;
236
237         KASSERT(vcpu_id >= 0 && vcpu_id < VM_MAXCPU,
238             ("vcpu_init: invalid vcpu %d", vcpu_id));
239           
240         vcpu = &vm->vcpu[vcpu_id];
241
242         if (create) {
243                 KASSERT(!vcpu_lock_initialized(vcpu), ("vcpu %d already "
244                     "initialized", vcpu_id));
245                 vcpu_lock_init(vcpu);
246                 vcpu->state = VCPU_IDLE;
247                 vcpu->hostcpu = NOCPU;
248                 vcpu->guestfpu = fpu_save_area_alloc();
249                 vcpu->stats = vmm_stat_alloc();
250         }
251
252         vcpu->vlapic = VLAPIC_INIT(vm->cookie, vcpu_id);
253         vm_set_x2apic_state(vm, vcpu_id, X2APIC_DISABLED);
254         vcpu->exitintinfo = 0;
255         vcpu->nmi_pending = 0;
256         vcpu->extint_pending = 0;
257         vcpu->exception_pending = 0;
258         vcpu->guest_xcr0 = XFEATURE_ENABLED_X87;
259         fpu_save_area_reset(vcpu->guestfpu);
260         vmm_stat_init(vcpu->stats);
261 }
262
263 int
264 vcpu_trace_exceptions(struct vm *vm, int vcpuid)
265 {
266
267         return (trace_guest_exceptions);
268 }
269
270 struct vm_exit *
271 vm_exitinfo(struct vm *vm, int cpuid)
272 {
273         struct vcpu *vcpu;
274
275         if (cpuid < 0 || cpuid >= VM_MAXCPU)
276                 panic("vm_exitinfo: invalid cpuid %d", cpuid);
277
278         vcpu = &vm->vcpu[cpuid];
279
280         return (&vcpu->exitinfo);
281 }
282
283 static void
284 vmm_resume(void)
285 {
286         VMM_RESUME();
287 }
288
289 static int
290 vmm_init(void)
291 {
292         int error;
293
294         vmm_host_state_init();
295
296         vmm_ipinum = vmm_ipi_alloc();
297         if (vmm_ipinum == 0)
298                 vmm_ipinum = IPI_AST;
299
300         error = vmm_mem_init();
301         if (error)
302                 return (error);
303         
304         if (vmm_is_intel())
305                 ops = &vmm_ops_intel;
306         else if (vmm_is_amd())
307                 ops = &vmm_ops_amd;
308         else
309                 return (ENXIO);
310
311         vmm_resume_p = vmm_resume;
312
313         return (VMM_INIT(vmm_ipinum));
314 }
315
316 static int
317 vmm_handler(module_t mod, int what, void *arg)
318 {
319         int error;
320
321         switch (what) {
322         case MOD_LOAD:
323                 vmmdev_init();
324                 if (ppt_avail_devices() > 0)
325                         iommu_init();
326                 error = vmm_init();
327                 if (error == 0)
328                         vmm_initialized = 1;
329                 break;
330         case MOD_UNLOAD:
331                 error = vmmdev_cleanup();
332                 if (error == 0) {
333                         vmm_resume_p = NULL;
334                         iommu_cleanup();
335                         if (vmm_ipinum != IPI_AST)
336                                 vmm_ipi_free(vmm_ipinum);
337                         error = VMM_CLEANUP();
338                         /*
339                          * Something bad happened - prevent new
340                          * VMs from being created
341                          */
342                         if (error)
343                                 vmm_initialized = 0;
344                 }
345                 break;
346         default:
347                 error = 0;
348                 break;
349         }
350         return (error);
351 }
352
353 static moduledata_t vmm_kmod = {
354         "vmm",
355         vmm_handler,
356         NULL
357 };
358
359 /*
360  * vmm initialization has the following dependencies:
361  *
362  * - iommu initialization must happen after the pci passthru driver has had
363  *   a chance to attach to any passthru devices (after SI_SUB_CONFIGURE).
364  *
365  * - VT-x initialization requires smp_rendezvous() and therefore must happen
366  *   after SMP is fully functional (after SI_SUB_SMP).
367  */
368 DECLARE_MODULE(vmm, vmm_kmod, SI_SUB_SMP + 1, SI_ORDER_ANY);
369 MODULE_VERSION(vmm, 1);
370
371 static void
372 vm_init(struct vm *vm, bool create)
373 {
374         int i;
375
376         vm->cookie = VMINIT(vm, vmspace_pmap(vm->vmspace));
377         vm->iommu = NULL;
378         vm->vioapic = vioapic_init(vm);
379         vm->vhpet = vhpet_init(vm);
380         vm->vatpic = vatpic_init(vm);
381         vm->vatpit = vatpit_init(vm);
382         vm->vpmtmr = vpmtmr_init(vm);
383         if (create)
384                 vm->vrtc = vrtc_init(vm);
385
386         CPU_ZERO(&vm->active_cpus);
387
388         vm->suspend = 0;
389         CPU_ZERO(&vm->suspended_cpus);
390
391         for (i = 0; i < VM_MAXCPU; i++)
392                 vcpu_init(vm, i, create);
393 }
394
395 int
396 vm_create(const char *name, struct vm **retvm)
397 {
398         struct vm *vm;
399         struct vmspace *vmspace;
400
401         /*
402          * If vmm.ko could not be successfully initialized then don't attempt
403          * to create the virtual machine.
404          */
405         if (!vmm_initialized)
406                 return (ENXIO);
407
408         if (name == NULL || strlen(name) >= VM_MAX_NAMELEN)
409                 return (EINVAL);
410
411         vmspace = VMSPACE_ALLOC(0, VM_MAXUSER_ADDRESS);
412         if (vmspace == NULL)
413                 return (ENOMEM);
414
415         vm = malloc(sizeof(struct vm), M_VM, M_WAITOK | M_ZERO);
416         strcpy(vm->name, name);
417         vm->num_mem_segs = 0;
418         vm->vmspace = vmspace;
419         mtx_init(&vm->rendezvous_mtx, "vm rendezvous lock", 0, MTX_DEF);
420
421         vm_init(vm, true);
422
423         *retvm = vm;
424         return (0);
425 }
426
427 static void
428 vm_free_mem_seg(struct vm *vm, struct mem_seg *seg)
429 {
430
431         if (seg->object != NULL)
432                 vmm_mem_free(vm->vmspace, seg->gpa, seg->len);
433
434         bzero(seg, sizeof(*seg));
435 }
436
437 static void
438 vm_cleanup(struct vm *vm, bool destroy)
439 {
440         int i;
441
442         ppt_unassign_all(vm);
443
444         if (vm->iommu != NULL)
445                 iommu_destroy_domain(vm->iommu);
446
447         if (destroy)
448                 vrtc_cleanup(vm->vrtc);
449         else
450                 vrtc_reset(vm->vrtc);
451         vpmtmr_cleanup(vm->vpmtmr);
452         vatpit_cleanup(vm->vatpit);
453         vhpet_cleanup(vm->vhpet);
454         vatpic_cleanup(vm->vatpic);
455         vioapic_cleanup(vm->vioapic);
456
457         for (i = 0; i < VM_MAXCPU; i++)
458                 vcpu_cleanup(vm, i, destroy);
459
460         VMCLEANUP(vm->cookie);
461
462         if (destroy) {
463                 for (i = 0; i < vm->num_mem_segs; i++)
464                         vm_free_mem_seg(vm, &vm->mem_segs[i]);
465
466                 vm->num_mem_segs = 0;
467
468                 VMSPACE_FREE(vm->vmspace);
469                 vm->vmspace = NULL;
470         }
471 }
472
473 void
474 vm_destroy(struct vm *vm)
475 {
476         vm_cleanup(vm, true);
477         free(vm, M_VM);
478 }
479
480 int
481 vm_reinit(struct vm *vm)
482 {
483         int error;
484
485         /*
486          * A virtual machine can be reset only if all vcpus are suspended.
487          */
488         if (CPU_CMP(&vm->suspended_cpus, &vm->active_cpus) == 0) {
489                 vm_cleanup(vm, false);
490                 vm_init(vm, false);
491                 error = 0;
492         } else {
493                 error = EBUSY;
494         }
495
496         return (error);
497 }
498
499 const char *
500 vm_name(struct vm *vm)
501 {
502         return (vm->name);
503 }
504
505 int
506 vm_map_mmio(struct vm *vm, vm_paddr_t gpa, size_t len, vm_paddr_t hpa)
507 {
508         vm_object_t obj;
509
510         if ((obj = vmm_mmio_alloc(vm->vmspace, gpa, len, hpa)) == NULL)
511                 return (ENOMEM);
512         else
513                 return (0);
514 }
515
516 int
517 vm_unmap_mmio(struct vm *vm, vm_paddr_t gpa, size_t len)
518 {
519
520         vmm_mmio_free(vm->vmspace, gpa, len);
521         return (0);
522 }
523
524 boolean_t
525 vm_mem_allocated(struct vm *vm, vm_paddr_t gpa)
526 {
527         int i;
528         vm_paddr_t gpabase, gpalimit;
529
530         for (i = 0; i < vm->num_mem_segs; i++) {
531                 gpabase = vm->mem_segs[i].gpa;
532                 gpalimit = gpabase + vm->mem_segs[i].len;
533                 if (gpa >= gpabase && gpa < gpalimit)
534                         return (TRUE);          /* 'gpa' is regular memory */
535         }
536
537         if (ppt_is_mmio(vm, gpa))
538                 return (TRUE);                  /* 'gpa' is pci passthru mmio */
539
540         return (FALSE);
541 }
542
543 int
544 vm_malloc(struct vm *vm, vm_paddr_t gpa, size_t len)
545 {
546         int available, allocated;
547         struct mem_seg *seg;
548         vm_object_t object;
549         vm_paddr_t g;
550
551         if ((gpa & PAGE_MASK) || (len & PAGE_MASK) || len == 0)
552                 return (EINVAL);
553         
554         available = allocated = 0;
555         g = gpa;
556         while (g < gpa + len) {
557                 if (vm_mem_allocated(vm, g))
558                         allocated++;
559                 else
560                         available++;
561
562                 g += PAGE_SIZE;
563         }
564
565         /*
566          * If there are some allocated and some available pages in the address
567          * range then it is an error.
568          */
569         if (allocated && available)
570                 return (EINVAL);
571
572         /*
573          * If the entire address range being requested has already been
574          * allocated then there isn't anything more to do.
575          */
576         if (allocated && available == 0)
577                 return (0);
578
579         if (vm->num_mem_segs >= VM_MAX_MEMORY_SEGMENTS)
580                 return (E2BIG);
581
582         seg = &vm->mem_segs[vm->num_mem_segs];
583
584         if ((object = vmm_mem_alloc(vm->vmspace, gpa, len)) == NULL)
585                 return (ENOMEM);
586
587         seg->gpa = gpa;
588         seg->len = len;
589         seg->object = object;
590         seg->wired = FALSE;
591
592         vm->num_mem_segs++;
593
594         return (0);
595 }
596
597 static vm_paddr_t
598 vm_maxmem(struct vm *vm)
599 {
600         int i;
601         vm_paddr_t gpa, maxmem;
602
603         maxmem = 0;
604         for (i = 0; i < vm->num_mem_segs; i++) {
605                 gpa = vm->mem_segs[i].gpa + vm->mem_segs[i].len;
606                 if (gpa > maxmem)
607                         maxmem = gpa;
608         }
609         return (maxmem);
610 }
611
612 static void
613 vm_gpa_unwire(struct vm *vm)
614 {
615         int i, rv;
616         struct mem_seg *seg;
617
618         for (i = 0; i < vm->num_mem_segs; i++) {
619                 seg = &vm->mem_segs[i];
620                 if (!seg->wired)
621                         continue;
622
623                 rv = vm_map_unwire(&vm->vmspace->vm_map,
624                                    seg->gpa, seg->gpa + seg->len,
625                                    VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
626                 KASSERT(rv == KERN_SUCCESS, ("vm(%s) memory segment "
627                     "%#lx/%ld could not be unwired: %d",
628                     vm_name(vm), seg->gpa, seg->len, rv));
629
630                 seg->wired = FALSE;
631         }
632 }
633
634 static int
635 vm_gpa_wire(struct vm *vm)
636 {
637         int i, rv;
638         struct mem_seg *seg;
639
640         for (i = 0; i < vm->num_mem_segs; i++) {
641                 seg = &vm->mem_segs[i];
642                 if (seg->wired)
643                         continue;
644
645                 /* XXX rlimits? */
646                 rv = vm_map_wire(&vm->vmspace->vm_map,
647                                  seg->gpa, seg->gpa + seg->len,
648                                  VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
649                 if (rv != KERN_SUCCESS)
650                         break;
651
652                 seg->wired = TRUE;
653         }
654
655         if (i < vm->num_mem_segs) {
656                 /*
657                  * Undo the wiring before returning an error.
658                  */
659                 vm_gpa_unwire(vm);
660                 return (EAGAIN);
661         }
662
663         return (0);
664 }
665
666 static void
667 vm_iommu_modify(struct vm *vm, boolean_t map)
668 {
669         int i, sz;
670         vm_paddr_t gpa, hpa;
671         struct mem_seg *seg;
672         void *vp, *cookie, *host_domain;
673
674         sz = PAGE_SIZE;
675         host_domain = iommu_host_domain();
676
677         for (i = 0; i < vm->num_mem_segs; i++) {
678                 seg = &vm->mem_segs[i];
679                 KASSERT(seg->wired, ("vm(%s) memory segment %#lx/%ld not wired",
680                     vm_name(vm), seg->gpa, seg->len));
681
682                 gpa = seg->gpa;
683                 while (gpa < seg->gpa + seg->len) {
684                         vp = vm_gpa_hold(vm, gpa, PAGE_SIZE, VM_PROT_WRITE,
685                                          &cookie);
686                         KASSERT(vp != NULL, ("vm(%s) could not map gpa %#lx",
687                             vm_name(vm), gpa));
688
689                         vm_gpa_release(cookie);
690
691                         hpa = DMAP_TO_PHYS((uintptr_t)vp);
692                         if (map) {
693                                 iommu_create_mapping(vm->iommu, gpa, hpa, sz);
694                                 iommu_remove_mapping(host_domain, hpa, sz);
695                         } else {
696                                 iommu_remove_mapping(vm->iommu, gpa, sz);
697                                 iommu_create_mapping(host_domain, hpa, hpa, sz);
698                         }
699
700                         gpa += PAGE_SIZE;
701                 }
702         }
703
704         /*
705          * Invalidate the cached translations associated with the domain
706          * from which pages were removed.
707          */
708         if (map)
709                 iommu_invalidate_tlb(host_domain);
710         else
711                 iommu_invalidate_tlb(vm->iommu);
712 }
713
714 #define vm_iommu_unmap(vm)      vm_iommu_modify((vm), FALSE)
715 #define vm_iommu_map(vm)        vm_iommu_modify((vm), TRUE)
716
717 int
718 vm_unassign_pptdev(struct vm *vm, int bus, int slot, int func)
719 {
720         int error;
721
722         error = ppt_unassign_device(vm, bus, slot, func);
723         if (error)
724                 return (error);
725
726         if (ppt_assigned_devices(vm) == 0) {
727                 vm_iommu_unmap(vm);
728                 vm_gpa_unwire(vm);
729         }
730         return (0);
731 }
732
733 int
734 vm_assign_pptdev(struct vm *vm, int bus, int slot, int func)
735 {
736         int error;
737         vm_paddr_t maxaddr;
738
739         /*
740          * Virtual machines with pci passthru devices get special treatment:
741          * - the guest physical memory is wired
742          * - the iommu is programmed to do the 'gpa' to 'hpa' translation
743          *
744          * We need to do this before the first pci passthru device is attached.
745          */
746         if (ppt_assigned_devices(vm) == 0) {
747                 KASSERT(vm->iommu == NULL,
748                     ("vm_assign_pptdev: iommu must be NULL"));
749                 maxaddr = vm_maxmem(vm);
750                 vm->iommu = iommu_create_domain(maxaddr);
751
752                 error = vm_gpa_wire(vm);
753                 if (error)
754                         return (error);
755
756                 vm_iommu_map(vm);
757         }
758
759         error = ppt_assign_device(vm, bus, slot, func);
760         return (error);
761 }
762
763 void *
764 vm_gpa_hold(struct vm *vm, vm_paddr_t gpa, size_t len, int reqprot,
765             void **cookie)
766 {
767         int count, pageoff;
768         vm_page_t m;
769
770         pageoff = gpa & PAGE_MASK;
771         if (len > PAGE_SIZE - pageoff)
772                 panic("vm_gpa_hold: invalid gpa/len: 0x%016lx/%lu", gpa, len);
773
774         count = vm_fault_quick_hold_pages(&vm->vmspace->vm_map,
775             trunc_page(gpa), PAGE_SIZE, reqprot, &m, 1);
776
777         if (count == 1) {
778                 *cookie = m;
779                 return ((void *)(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)) + pageoff));
780         } else {
781                 *cookie = NULL;
782                 return (NULL);
783         }
784 }
785
786 void
787 vm_gpa_release(void *cookie)
788 {
789         vm_page_t m = cookie;
790
791         vm_page_lock(m);
792         vm_page_unhold(m);
793         vm_page_unlock(m);
794 }
795
796 int
797 vm_gpabase2memseg(struct vm *vm, vm_paddr_t gpabase,
798                   struct vm_memory_segment *seg)
799 {
800         int i;
801
802         for (i = 0; i < vm->num_mem_segs; i++) {
803                 if (gpabase == vm->mem_segs[i].gpa) {
804                         seg->gpa = vm->mem_segs[i].gpa;
805                         seg->len = vm->mem_segs[i].len;
806                         seg->wired = vm->mem_segs[i].wired;
807                         return (0);
808                 }
809         }
810         return (-1);
811 }
812
813 int
814 vm_get_memobj(struct vm *vm, vm_paddr_t gpa, size_t len,
815               vm_offset_t *offset, struct vm_object **object)
816 {
817         int i;
818         size_t seg_len;
819         vm_paddr_t seg_gpa;
820         vm_object_t seg_obj;
821
822         for (i = 0; i < vm->num_mem_segs; i++) {
823                 if ((seg_obj = vm->mem_segs[i].object) == NULL)
824                         continue;
825
826                 seg_gpa = vm->mem_segs[i].gpa;
827                 seg_len = vm->mem_segs[i].len;
828
829                 if (gpa >= seg_gpa && gpa < seg_gpa + seg_len) {
830                         *offset = gpa - seg_gpa;
831                         *object = seg_obj;
832                         vm_object_reference(seg_obj);
833                         return (0);
834                 }
835         }
836
837         return (EINVAL);
838 }
839
840 int
841 vm_get_register(struct vm *vm, int vcpu, int reg, uint64_t *retval)
842 {
843
844         if (vcpu < 0 || vcpu >= VM_MAXCPU)
845                 return (EINVAL);
846
847         if (reg >= VM_REG_LAST)
848                 return (EINVAL);
849
850         return (VMGETREG(vm->cookie, vcpu, reg, retval));
851 }
852
853 int
854 vm_set_register(struct vm *vm, int vcpuid, int reg, uint64_t val)
855 {
856         struct vcpu *vcpu;
857         int error;
858
859         if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
860                 return (EINVAL);
861
862         if (reg >= VM_REG_LAST)
863                 return (EINVAL);
864
865         error = VMSETREG(vm->cookie, vcpuid, reg, val);
866         if (error || reg != VM_REG_GUEST_RIP)
867                 return (error);
868
869         /* Set 'nextrip' to match the value of %rip */
870         VCPU_CTR1(vm, vcpuid, "Setting nextrip to %#lx", val);
871         vcpu = &vm->vcpu[vcpuid];
872         vcpu->nextrip = val;
873         return (0);
874 }
875
876 static boolean_t
877 is_descriptor_table(int reg)
878 {
879
880         switch (reg) {
881         case VM_REG_GUEST_IDTR:
882         case VM_REG_GUEST_GDTR:
883                 return (TRUE);
884         default:
885                 return (FALSE);
886         }
887 }
888
889 static boolean_t
890 is_segment_register(int reg)
891 {
892         
893         switch (reg) {
894         case VM_REG_GUEST_ES:
895         case VM_REG_GUEST_CS:
896         case VM_REG_GUEST_SS:
897         case VM_REG_GUEST_DS:
898         case VM_REG_GUEST_FS:
899         case VM_REG_GUEST_GS:
900         case VM_REG_GUEST_TR:
901         case VM_REG_GUEST_LDTR:
902                 return (TRUE);
903         default:
904                 return (FALSE);
905         }
906 }
907
908 int
909 vm_get_seg_desc(struct vm *vm, int vcpu, int reg,
910                 struct seg_desc *desc)
911 {
912
913         if (vcpu < 0 || vcpu >= VM_MAXCPU)
914                 return (EINVAL);
915
916         if (!is_segment_register(reg) && !is_descriptor_table(reg))
917                 return (EINVAL);
918
919         return (VMGETDESC(vm->cookie, vcpu, reg, desc));
920 }
921
922 int
923 vm_set_seg_desc(struct vm *vm, int vcpu, int reg,
924                 struct seg_desc *desc)
925 {
926         if (vcpu < 0 || vcpu >= VM_MAXCPU)
927                 return (EINVAL);
928
929         if (!is_segment_register(reg) && !is_descriptor_table(reg))
930                 return (EINVAL);
931
932         return (VMSETDESC(vm->cookie, vcpu, reg, desc));
933 }
934
935 static void
936 restore_guest_fpustate(struct vcpu *vcpu)
937 {
938
939         /* flush host state to the pcb */
940         fpuexit(curthread);
941
942         /* restore guest FPU state */
943         fpu_stop_emulating();
944         fpurestore(vcpu->guestfpu);
945
946         /* restore guest XCR0 if XSAVE is enabled in the host */
947         if (rcr4() & CR4_XSAVE)
948                 load_xcr(0, vcpu->guest_xcr0);
949
950         /*
951          * The FPU is now "dirty" with the guest's state so turn on emulation
952          * to trap any access to the FPU by the host.
953          */
954         fpu_start_emulating();
955 }
956
957 static void
958 save_guest_fpustate(struct vcpu *vcpu)
959 {
960
961         if ((rcr0() & CR0_TS) == 0)
962                 panic("fpu emulation not enabled in host!");
963
964         /* save guest XCR0 and restore host XCR0 */
965         if (rcr4() & CR4_XSAVE) {
966                 vcpu->guest_xcr0 = rxcr(0);
967                 load_xcr(0, vmm_get_host_xcr0());
968         }
969
970         /* save guest FPU state */
971         fpu_stop_emulating();
972         fpusave(vcpu->guestfpu);
973         fpu_start_emulating();
974 }
975
976 static VMM_STAT(VCPU_IDLE_TICKS, "number of ticks vcpu was idle");
977
978 static int
979 vcpu_set_state_locked(struct vcpu *vcpu, enum vcpu_state newstate,
980     bool from_idle)
981 {
982         int error;
983
984         vcpu_assert_locked(vcpu);
985
986         /*
987          * State transitions from the vmmdev_ioctl() must always begin from
988          * the VCPU_IDLE state. This guarantees that there is only a single
989          * ioctl() operating on a vcpu at any point.
990          */
991         if (from_idle) {
992                 while (vcpu->state != VCPU_IDLE)
993                         msleep_spin(&vcpu->state, &vcpu->mtx, "vmstat", hz);
994         } else {
995                 KASSERT(vcpu->state != VCPU_IDLE, ("invalid transition from "
996                     "vcpu idle state"));
997         }
998
999         if (vcpu->state == VCPU_RUNNING) {
1000                 KASSERT(vcpu->hostcpu == curcpu, ("curcpu %d and hostcpu %d "
1001                     "mismatch for running vcpu", curcpu, vcpu->hostcpu));
1002         } else {
1003                 KASSERT(vcpu->hostcpu == NOCPU, ("Invalid hostcpu %d for a "
1004                     "vcpu that is not running", vcpu->hostcpu));
1005         }
1006
1007         /*
1008          * The following state transitions are allowed:
1009          * IDLE -> FROZEN -> IDLE
1010          * FROZEN -> RUNNING -> FROZEN
1011          * FROZEN -> SLEEPING -> FROZEN
1012          */
1013         switch (vcpu->state) {
1014         case VCPU_IDLE:
1015         case VCPU_RUNNING:
1016         case VCPU_SLEEPING:
1017                 error = (newstate != VCPU_FROZEN);
1018                 break;
1019         case VCPU_FROZEN:
1020                 error = (newstate == VCPU_FROZEN);
1021                 break;
1022         default:
1023                 error = 1;
1024                 break;
1025         }
1026
1027         if (error)
1028                 return (EBUSY);
1029
1030         vcpu->state = newstate;
1031         if (newstate == VCPU_RUNNING)
1032                 vcpu->hostcpu = curcpu;
1033         else
1034                 vcpu->hostcpu = NOCPU;
1035
1036         if (newstate == VCPU_IDLE)
1037                 wakeup(&vcpu->state);
1038
1039         return (0);
1040 }
1041
1042 static void
1043 vcpu_require_state(struct vm *vm, int vcpuid, enum vcpu_state newstate)
1044 {
1045         int error;
1046
1047         if ((error = vcpu_set_state(vm, vcpuid, newstate, false)) != 0)
1048                 panic("Error %d setting state to %d\n", error, newstate);
1049 }
1050
1051 static void
1052 vcpu_require_state_locked(struct vcpu *vcpu, enum vcpu_state newstate)
1053 {
1054         int error;
1055
1056         if ((error = vcpu_set_state_locked(vcpu, newstate, false)) != 0)
1057                 panic("Error %d setting state to %d", error, newstate);
1058 }
1059
1060 static void
1061 vm_set_rendezvous_func(struct vm *vm, vm_rendezvous_func_t func)
1062 {
1063
1064         KASSERT(mtx_owned(&vm->rendezvous_mtx), ("rendezvous_mtx not locked"));
1065
1066         /*
1067          * Update 'rendezvous_func' and execute a write memory barrier to
1068          * ensure that it is visible across all host cpus. This is not needed
1069          * for correctness but it does ensure that all the vcpus will notice
1070          * that the rendezvous is requested immediately.
1071          */
1072         vm->rendezvous_func = func;
1073         wmb();
1074 }
1075
1076 #define RENDEZVOUS_CTR0(vm, vcpuid, fmt)                                \
1077         do {                                                            \
1078                 if (vcpuid >= 0)                                        \
1079                         VCPU_CTR0(vm, vcpuid, fmt);                     \
1080                 else                                                    \
1081                         VM_CTR0(vm, fmt);                               \
1082         } while (0)
1083
1084 static void
1085 vm_handle_rendezvous(struct vm *vm, int vcpuid)
1086 {
1087
1088         KASSERT(vcpuid == -1 || (vcpuid >= 0 && vcpuid < VM_MAXCPU),
1089             ("vm_handle_rendezvous: invalid vcpuid %d", vcpuid));
1090
1091         mtx_lock(&vm->rendezvous_mtx);
1092         while (vm->rendezvous_func != NULL) {
1093                 /* 'rendezvous_req_cpus' must be a subset of 'active_cpus' */
1094                 CPU_AND(&vm->rendezvous_req_cpus, &vm->active_cpus);
1095
1096                 if (vcpuid != -1 &&
1097                     CPU_ISSET(vcpuid, &vm->rendezvous_req_cpus) &&
1098                     !CPU_ISSET(vcpuid, &vm->rendezvous_done_cpus)) {
1099                         VCPU_CTR0(vm, vcpuid, "Calling rendezvous func");
1100                         (*vm->rendezvous_func)(vm, vcpuid, vm->rendezvous_arg);
1101                         CPU_SET(vcpuid, &vm->rendezvous_done_cpus);
1102                 }
1103                 if (CPU_CMP(&vm->rendezvous_req_cpus,
1104                     &vm->rendezvous_done_cpus) == 0) {
1105                         VCPU_CTR0(vm, vcpuid, "Rendezvous completed");
1106                         vm_set_rendezvous_func(vm, NULL);
1107                         wakeup(&vm->rendezvous_func);
1108                         break;
1109                 }
1110                 RENDEZVOUS_CTR0(vm, vcpuid, "Wait for rendezvous completion");
1111                 mtx_sleep(&vm->rendezvous_func, &vm->rendezvous_mtx, 0,
1112                     "vmrndv", 0);
1113         }
1114         mtx_unlock(&vm->rendezvous_mtx);
1115 }
1116
1117 /*
1118  * Emulate a guest 'hlt' by sleeping until the vcpu is ready to run.
1119  */
1120 static int
1121 vm_handle_hlt(struct vm *vm, int vcpuid, bool intr_disabled, bool *retu)
1122 {
1123         struct vcpu *vcpu;
1124         const char *wmesg;
1125         int t, vcpu_halted, vm_halted;
1126
1127         KASSERT(!CPU_ISSET(vcpuid, &vm->halted_cpus), ("vcpu already halted"));
1128
1129         vcpu = &vm->vcpu[vcpuid];
1130         vcpu_halted = 0;
1131         vm_halted = 0;
1132
1133         vcpu_lock(vcpu);
1134         while (1) {
1135                 /*
1136                  * Do a final check for pending NMI or interrupts before
1137                  * really putting this thread to sleep. Also check for
1138                  * software events that would cause this vcpu to wakeup.
1139                  *
1140                  * These interrupts/events could have happened after the
1141                  * vcpu returned from VMRUN() and before it acquired the
1142                  * vcpu lock above.
1143                  */
1144                 if (vm->rendezvous_func != NULL || vm->suspend)
1145                         break;
1146                 if (vm_nmi_pending(vm, vcpuid))
1147                         break;
1148                 if (!intr_disabled) {
1149                         if (vm_extint_pending(vm, vcpuid) ||
1150                             vlapic_pending_intr(vcpu->vlapic, NULL)) {
1151                                 break;
1152                         }
1153                 }
1154
1155                 /* Don't go to sleep if the vcpu thread needs to yield */
1156                 if (vcpu_should_yield(vm, vcpuid))
1157                         break;
1158
1159                 /*
1160                  * Some Linux guests implement "halt" by having all vcpus
1161                  * execute HLT with interrupts disabled. 'halted_cpus' keeps
1162                  * track of the vcpus that have entered this state. When all
1163                  * vcpus enter the halted state the virtual machine is halted.
1164                  */
1165                 if (intr_disabled) {
1166                         wmesg = "vmhalt";
1167                         VCPU_CTR0(vm, vcpuid, "Halted");
1168                         if (!vcpu_halted && halt_detection_enabled) {
1169                                 vcpu_halted = 1;
1170                                 CPU_SET_ATOMIC(vcpuid, &vm->halted_cpus);
1171                         }
1172                         if (CPU_CMP(&vm->halted_cpus, &vm->active_cpus) == 0) {
1173                                 vm_halted = 1;
1174                                 break;
1175                         }
1176                 } else {
1177                         wmesg = "vmidle";
1178                 }
1179
1180                 t = ticks;
1181                 vcpu_require_state_locked(vcpu, VCPU_SLEEPING);
1182                 /*
1183                  * XXX msleep_spin() cannot be interrupted by signals so
1184                  * wake up periodically to check pending signals.
1185                  */
1186                 msleep_spin(vcpu, &vcpu->mtx, wmesg, hz);
1187                 vcpu_require_state_locked(vcpu, VCPU_FROZEN);
1188                 vmm_stat_incr(vm, vcpuid, VCPU_IDLE_TICKS, ticks - t);
1189         }
1190
1191         if (vcpu_halted)
1192                 CPU_CLR_ATOMIC(vcpuid, &vm->halted_cpus);
1193
1194         vcpu_unlock(vcpu);
1195
1196         if (vm_halted)
1197                 vm_suspend(vm, VM_SUSPEND_HALT);
1198
1199         return (0);
1200 }
1201
1202 static int
1203 vm_handle_paging(struct vm *vm, int vcpuid, bool *retu)
1204 {
1205         int rv, ftype;
1206         struct vm_map *map;
1207         struct vcpu *vcpu;
1208         struct vm_exit *vme;
1209
1210         vcpu = &vm->vcpu[vcpuid];
1211         vme = &vcpu->exitinfo;
1212
1213         KASSERT(vme->inst_length == 0, ("%s: invalid inst_length %d",
1214             __func__, vme->inst_length));
1215
1216         ftype = vme->u.paging.fault_type;
1217         KASSERT(ftype == VM_PROT_READ ||
1218             ftype == VM_PROT_WRITE || ftype == VM_PROT_EXECUTE,
1219             ("vm_handle_paging: invalid fault_type %d", ftype));
1220
1221         if (ftype == VM_PROT_READ || ftype == VM_PROT_WRITE) {
1222                 rv = pmap_emulate_accessed_dirty(vmspace_pmap(vm->vmspace),
1223                     vme->u.paging.gpa, ftype);
1224                 if (rv == 0) {
1225                         VCPU_CTR2(vm, vcpuid, "%s bit emulation for gpa %#lx",
1226                             ftype == VM_PROT_READ ? "accessed" : "dirty",
1227                             vme->u.paging.gpa);
1228                         goto done;
1229                 }
1230         }
1231
1232         map = &vm->vmspace->vm_map;
1233         rv = vm_fault(map, vme->u.paging.gpa, ftype, VM_FAULT_NORMAL);
1234
1235         VCPU_CTR3(vm, vcpuid, "vm_handle_paging rv = %d, gpa = %#lx, "
1236             "ftype = %d", rv, vme->u.paging.gpa, ftype);
1237
1238         if (rv != KERN_SUCCESS)
1239                 return (EFAULT);
1240 done:
1241         return (0);
1242 }
1243
1244 static int
1245 vm_handle_inst_emul(struct vm *vm, int vcpuid, bool *retu)
1246 {
1247         struct vie *vie;
1248         struct vcpu *vcpu;
1249         struct vm_exit *vme;
1250         uint64_t gla, gpa;
1251         struct vm_guest_paging *paging;
1252         mem_region_read_t mread;
1253         mem_region_write_t mwrite;
1254         enum vm_cpu_mode cpu_mode;
1255         int cs_d, error, length;
1256
1257         vcpu = &vm->vcpu[vcpuid];
1258         vme = &vcpu->exitinfo;
1259
1260         gla = vme->u.inst_emul.gla;
1261         gpa = vme->u.inst_emul.gpa;
1262         cs_d = vme->u.inst_emul.cs_d;
1263         vie = &vme->u.inst_emul.vie;
1264         paging = &vme->u.inst_emul.paging;
1265         cpu_mode = paging->cpu_mode;
1266
1267         VCPU_CTR1(vm, vcpuid, "inst_emul fault accessing gpa %#lx", gpa);
1268
1269         /* Fetch, decode and emulate the faulting instruction */
1270         if (vie->num_valid == 0) {
1271                 /*
1272                  * If the instruction length is not known then assume a
1273                  * maximum size instruction.
1274                  */
1275                 length = vme->inst_length ? vme->inst_length : VIE_INST_SIZE;
1276                 error = vmm_fetch_instruction(vm, vcpuid, paging, vme->rip,
1277                     length, vie);
1278         } else {
1279                 /*
1280                  * The instruction bytes have already been copied into 'vie'
1281                  */
1282                 error = 0;
1283         }
1284         if (error == 1)
1285                 return (0);             /* Resume guest to handle page fault */
1286         else if (error == -1)
1287                 return (EFAULT);
1288         else if (error != 0)
1289                 panic("%s: vmm_fetch_instruction error %d", __func__, error);
1290
1291         if (vmm_decode_instruction(vm, vcpuid, gla, cpu_mode, cs_d, vie) != 0)
1292                 return (EFAULT);
1293
1294         /*
1295          * If the instruction length was not specified then update it now
1296          * along with 'nextrip'.
1297          */
1298         if (vme->inst_length == 0) {
1299                 vme->inst_length = vie->num_processed;
1300                 vcpu->nextrip += vie->num_processed;
1301         }
1302  
1303         /* return to userland unless this is an in-kernel emulated device */
1304         if (gpa >= DEFAULT_APIC_BASE && gpa < DEFAULT_APIC_BASE + PAGE_SIZE) {
1305                 mread = lapic_mmio_read;
1306                 mwrite = lapic_mmio_write;
1307         } else if (gpa >= VIOAPIC_BASE && gpa < VIOAPIC_BASE + VIOAPIC_SIZE) {
1308                 mread = vioapic_mmio_read;
1309                 mwrite = vioapic_mmio_write;
1310         } else if (gpa >= VHPET_BASE && gpa < VHPET_BASE + VHPET_SIZE) {
1311                 mread = vhpet_mmio_read;
1312                 mwrite = vhpet_mmio_write;
1313         } else {
1314                 *retu = true;
1315                 return (0);
1316         }
1317
1318         error = vmm_emulate_instruction(vm, vcpuid, gpa, vie, paging,
1319             mread, mwrite, retu);
1320
1321         return (error);
1322 }
1323
1324 static int
1325 vm_handle_suspend(struct vm *vm, int vcpuid, bool *retu)
1326 {
1327         int i, done;
1328         struct vcpu *vcpu;
1329
1330         done = 0;
1331         vcpu = &vm->vcpu[vcpuid];
1332
1333         CPU_SET_ATOMIC(vcpuid, &vm->suspended_cpus);
1334
1335         /*
1336          * Wait until all 'active_cpus' have suspended themselves.
1337          *
1338          * Since a VM may be suspended at any time including when one or
1339          * more vcpus are doing a rendezvous we need to call the rendezvous
1340          * handler while we are waiting to prevent a deadlock.
1341          */
1342         vcpu_lock(vcpu);
1343         while (1) {
1344                 if (CPU_CMP(&vm->suspended_cpus, &vm->active_cpus) == 0) {
1345                         VCPU_CTR0(vm, vcpuid, "All vcpus suspended");
1346                         break;
1347                 }
1348
1349                 if (vm->rendezvous_func == NULL) {
1350                         VCPU_CTR0(vm, vcpuid, "Sleeping during suspend");
1351                         vcpu_require_state_locked(vcpu, VCPU_SLEEPING);
1352                         msleep_spin(vcpu, &vcpu->mtx, "vmsusp", hz);
1353                         vcpu_require_state_locked(vcpu, VCPU_FROZEN);
1354                 } else {
1355                         VCPU_CTR0(vm, vcpuid, "Rendezvous during suspend");
1356                         vcpu_unlock(vcpu);
1357                         vm_handle_rendezvous(vm, vcpuid);
1358                         vcpu_lock(vcpu);
1359                 }
1360         }
1361         vcpu_unlock(vcpu);
1362
1363         /*
1364          * Wakeup the other sleeping vcpus and return to userspace.
1365          */
1366         for (i = 0; i < VM_MAXCPU; i++) {
1367                 if (CPU_ISSET(i, &vm->suspended_cpus)) {
1368                         vcpu_notify_event(vm, i, false);
1369                 }
1370         }
1371
1372         *retu = true;
1373         return (0);
1374 }
1375
1376 int
1377 vm_suspend(struct vm *vm, enum vm_suspend_how how)
1378 {
1379         int i;
1380
1381         if (how <= VM_SUSPEND_NONE || how >= VM_SUSPEND_LAST)
1382                 return (EINVAL);
1383
1384         if (atomic_cmpset_int(&vm->suspend, 0, how) == 0) {
1385                 VM_CTR2(vm, "virtual machine already suspended %d/%d",
1386                     vm->suspend, how);
1387                 return (EALREADY);
1388         }
1389
1390         VM_CTR1(vm, "virtual machine successfully suspended %d", how);
1391
1392         /*
1393          * Notify all active vcpus that they are now suspended.
1394          */
1395         for (i = 0; i < VM_MAXCPU; i++) {
1396                 if (CPU_ISSET(i, &vm->active_cpus))
1397                         vcpu_notify_event(vm, i, false);
1398         }
1399
1400         return (0);
1401 }
1402
1403 void
1404 vm_exit_suspended(struct vm *vm, int vcpuid, uint64_t rip)
1405 {
1406         struct vm_exit *vmexit;
1407
1408         KASSERT(vm->suspend > VM_SUSPEND_NONE && vm->suspend < VM_SUSPEND_LAST,
1409             ("vm_exit_suspended: invalid suspend type %d", vm->suspend));
1410
1411         vmexit = vm_exitinfo(vm, vcpuid);
1412         vmexit->rip = rip;
1413         vmexit->inst_length = 0;
1414         vmexit->exitcode = VM_EXITCODE_SUSPENDED;
1415         vmexit->u.suspended.how = vm->suspend;
1416 }
1417
1418 void
1419 vm_exit_rendezvous(struct vm *vm, int vcpuid, uint64_t rip)
1420 {
1421         struct vm_exit *vmexit;
1422
1423         KASSERT(vm->rendezvous_func != NULL, ("rendezvous not in progress"));
1424
1425         vmexit = vm_exitinfo(vm, vcpuid);
1426         vmexit->rip = rip;
1427         vmexit->inst_length = 0;
1428         vmexit->exitcode = VM_EXITCODE_RENDEZVOUS;
1429         vmm_stat_incr(vm, vcpuid, VMEXIT_RENDEZVOUS, 1);
1430 }
1431
1432 void
1433 vm_exit_astpending(struct vm *vm, int vcpuid, uint64_t rip)
1434 {
1435         struct vm_exit *vmexit;
1436
1437         vmexit = vm_exitinfo(vm, vcpuid);
1438         vmexit->rip = rip;
1439         vmexit->inst_length = 0;
1440         vmexit->exitcode = VM_EXITCODE_BOGUS;
1441         vmm_stat_incr(vm, vcpuid, VMEXIT_ASTPENDING, 1);
1442 }
1443
1444 int
1445 vm_run(struct vm *vm, struct vm_run *vmrun)
1446 {
1447         int error, vcpuid;
1448         struct vcpu *vcpu;
1449         struct pcb *pcb;
1450         uint64_t tscval;
1451         struct vm_exit *vme;
1452         bool retu, intr_disabled;
1453         pmap_t pmap;
1454         void *rptr, *sptr;
1455
1456         vcpuid = vmrun->cpuid;
1457
1458         if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1459                 return (EINVAL);
1460
1461         if (!CPU_ISSET(vcpuid, &vm->active_cpus))
1462                 return (EINVAL);
1463
1464         if (CPU_ISSET(vcpuid, &vm->suspended_cpus))
1465                 return (EINVAL);
1466
1467         rptr = &vm->rendezvous_func;
1468         sptr = &vm->suspend;
1469         pmap = vmspace_pmap(vm->vmspace);
1470         vcpu = &vm->vcpu[vcpuid];
1471         vme = &vcpu->exitinfo;
1472 restart:
1473         critical_enter();
1474
1475         KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1476             ("vm_run: absurd pm_active"));
1477
1478         tscval = rdtsc();
1479
1480         pcb = PCPU_GET(curpcb);
1481         set_pcb_flags(pcb, PCB_FULL_IRET);
1482
1483         restore_guest_fpustate(vcpu);
1484
1485         vcpu_require_state(vm, vcpuid, VCPU_RUNNING);
1486         error = VMRUN(vm->cookie, vcpuid, vcpu->nextrip, pmap, rptr, sptr);
1487         vcpu_require_state(vm, vcpuid, VCPU_FROZEN);
1488
1489         save_guest_fpustate(vcpu);
1490
1491         vmm_stat_incr(vm, vcpuid, VCPU_TOTAL_RUNTIME, rdtsc() - tscval);
1492
1493         critical_exit();
1494
1495         if (error == 0) {
1496                 retu = false;
1497                 vcpu->nextrip = vme->rip + vme->inst_length;
1498                 switch (vme->exitcode) {
1499                 case VM_EXITCODE_SUSPENDED:
1500                         error = vm_handle_suspend(vm, vcpuid, &retu);
1501                         break;
1502                 case VM_EXITCODE_IOAPIC_EOI:
1503                         vioapic_process_eoi(vm, vcpuid,
1504                             vme->u.ioapic_eoi.vector);
1505                         break;
1506                 case VM_EXITCODE_RENDEZVOUS:
1507                         vm_handle_rendezvous(vm, vcpuid);
1508                         error = 0;
1509                         break;
1510                 case VM_EXITCODE_HLT:
1511                         intr_disabled = ((vme->u.hlt.rflags & PSL_I) == 0);
1512                         error = vm_handle_hlt(vm, vcpuid, intr_disabled, &retu);
1513                         break;
1514                 case VM_EXITCODE_PAGING:
1515                         error = vm_handle_paging(vm, vcpuid, &retu);
1516                         break;
1517                 case VM_EXITCODE_INST_EMUL:
1518                         error = vm_handle_inst_emul(vm, vcpuid, &retu);
1519                         break;
1520                 case VM_EXITCODE_INOUT:
1521                 case VM_EXITCODE_INOUT_STR:
1522                         error = vm_handle_inout(vm, vcpuid, vme, &retu);
1523                         break;
1524                 case VM_EXITCODE_MONITOR:
1525                 case VM_EXITCODE_MWAIT:
1526                         vm_inject_ud(vm, vcpuid);
1527                         break;
1528                 default:
1529                         retu = true;    /* handled in userland */
1530                         break;
1531                 }
1532         }
1533
1534         if (error == 0 && retu == false)
1535                 goto restart;
1536
1537         /* copy the exit information */
1538         bcopy(vme, &vmrun->vm_exit, sizeof(struct vm_exit));
1539         return (error);
1540 }
1541
1542 int
1543 vm_restart_instruction(void *arg, int vcpuid)
1544 {
1545         struct vm *vm;
1546         struct vcpu *vcpu;
1547         enum vcpu_state state;
1548         uint64_t rip;
1549         int error;
1550
1551         vm = arg;
1552         if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1553                 return (EINVAL);
1554
1555         vcpu = &vm->vcpu[vcpuid];
1556         state = vcpu_get_state(vm, vcpuid, NULL);
1557         if (state == VCPU_RUNNING) {
1558                 /*
1559                  * When a vcpu is "running" the next instruction is determined
1560                  * by adding 'rip' and 'inst_length' in the vcpu's 'exitinfo'.
1561                  * Thus setting 'inst_length' to zero will cause the current
1562                  * instruction to be restarted.
1563                  */
1564                 vcpu->exitinfo.inst_length = 0;
1565                 VCPU_CTR1(vm, vcpuid, "restarting instruction at %#lx by "
1566                     "setting inst_length to zero", vcpu->exitinfo.rip);
1567         } else if (state == VCPU_FROZEN) {
1568                 /*
1569                  * When a vcpu is "frozen" it is outside the critical section
1570                  * around VMRUN() and 'nextrip' points to the next instruction.
1571                  * Thus instruction restart is achieved by setting 'nextrip'
1572                  * to the vcpu's %rip.
1573                  */
1574                 error = vm_get_register(vm, vcpuid, VM_REG_GUEST_RIP, &rip);
1575                 KASSERT(!error, ("%s: error %d getting rip", __func__, error));
1576                 VCPU_CTR2(vm, vcpuid, "restarting instruction by updating "
1577                     "nextrip from %#lx to %#lx", vcpu->nextrip, rip);
1578                 vcpu->nextrip = rip;
1579         } else {
1580                 panic("%s: invalid state %d", __func__, state);
1581         }
1582         return (0);
1583 }
1584
1585 int
1586 vm_exit_intinfo(struct vm *vm, int vcpuid, uint64_t info)
1587 {
1588         struct vcpu *vcpu;
1589         int type, vector;
1590
1591         if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1592                 return (EINVAL);
1593
1594         vcpu = &vm->vcpu[vcpuid];
1595
1596         if (info & VM_INTINFO_VALID) {
1597                 type = info & VM_INTINFO_TYPE;
1598                 vector = info & 0xff;
1599                 if (type == VM_INTINFO_NMI && vector != IDT_NMI)
1600                         return (EINVAL);
1601                 if (type == VM_INTINFO_HWEXCEPTION && vector >= 32)
1602                         return (EINVAL);
1603                 if (info & VM_INTINFO_RSVD)
1604                         return (EINVAL);
1605         } else {
1606                 info = 0;
1607         }
1608         VCPU_CTR2(vm, vcpuid, "%s: info1(%#lx)", __func__, info);
1609         vcpu->exitintinfo = info;
1610         return (0);
1611 }
1612
1613 enum exc_class {
1614         EXC_BENIGN,
1615         EXC_CONTRIBUTORY,
1616         EXC_PAGEFAULT
1617 };
1618
1619 #define IDT_VE  20      /* Virtualization Exception (Intel specific) */
1620
1621 static enum exc_class
1622 exception_class(uint64_t info)
1623 {
1624         int type, vector;
1625
1626         KASSERT(info & VM_INTINFO_VALID, ("intinfo must be valid: %#lx", info));
1627         type = info & VM_INTINFO_TYPE;
1628         vector = info & 0xff;
1629
1630         /* Table 6-4, "Interrupt and Exception Classes", Intel SDM, Vol 3 */
1631         switch (type) {
1632         case VM_INTINFO_HWINTR:
1633         case VM_INTINFO_SWINTR:
1634         case VM_INTINFO_NMI:
1635                 return (EXC_BENIGN);
1636         default:
1637                 /*
1638                  * Hardware exception.
1639                  *
1640                  * SVM and VT-x use identical type values to represent NMI,
1641                  * hardware interrupt and software interrupt.
1642                  *
1643                  * SVM uses type '3' for all exceptions. VT-x uses type '3'
1644                  * for exceptions except #BP and #OF. #BP and #OF use a type
1645                  * value of '5' or '6'. Therefore we don't check for explicit
1646                  * values of 'type' to classify 'intinfo' into a hardware
1647                  * exception.
1648                  */
1649                 break;
1650         }
1651
1652         switch (vector) {
1653         case IDT_PF:
1654         case IDT_VE:
1655                 return (EXC_PAGEFAULT);
1656         case IDT_DE:
1657         case IDT_TS:
1658         case IDT_NP:
1659         case IDT_SS:
1660         case IDT_GP:
1661                 return (EXC_CONTRIBUTORY);
1662         default:
1663                 return (EXC_BENIGN);
1664         }
1665 }
1666
1667 static int
1668 nested_fault(struct vm *vm, int vcpuid, uint64_t info1, uint64_t info2,
1669     uint64_t *retinfo)
1670 {
1671         enum exc_class exc1, exc2;
1672         int type1, vector1;
1673
1674         KASSERT(info1 & VM_INTINFO_VALID, ("info1 %#lx is not valid", info1));
1675         KASSERT(info2 & VM_INTINFO_VALID, ("info2 %#lx is not valid", info2));
1676
1677         /*
1678          * If an exception occurs while attempting to call the double-fault
1679          * handler the processor enters shutdown mode (aka triple fault).
1680          */
1681         type1 = info1 & VM_INTINFO_TYPE;
1682         vector1 = info1 & 0xff;
1683         if (type1 == VM_INTINFO_HWEXCEPTION && vector1 == IDT_DF) {
1684                 VCPU_CTR2(vm, vcpuid, "triple fault: info1(%#lx), info2(%#lx)",
1685                     info1, info2);
1686                 vm_suspend(vm, VM_SUSPEND_TRIPLEFAULT);
1687                 *retinfo = 0;
1688                 return (0);
1689         }
1690
1691         /*
1692          * Table 6-5 "Conditions for Generating a Double Fault", Intel SDM, Vol3
1693          */
1694         exc1 = exception_class(info1);
1695         exc2 = exception_class(info2);
1696         if ((exc1 == EXC_CONTRIBUTORY && exc2 == EXC_CONTRIBUTORY) ||
1697             (exc1 == EXC_PAGEFAULT && exc2 != EXC_BENIGN)) {
1698                 /* Convert nested fault into a double fault. */
1699                 *retinfo = IDT_DF;
1700                 *retinfo |= VM_INTINFO_VALID | VM_INTINFO_HWEXCEPTION;
1701                 *retinfo |= VM_INTINFO_DEL_ERRCODE;
1702         } else {
1703                 /* Handle exceptions serially */
1704                 *retinfo = info2;
1705         }
1706         return (1);
1707 }
1708
1709 static uint64_t
1710 vcpu_exception_intinfo(struct vcpu *vcpu)
1711 {
1712         uint64_t info = 0;
1713
1714         if (vcpu->exception_pending) {
1715                 info = vcpu->exc_vector & 0xff;
1716                 info |= VM_INTINFO_VALID | VM_INTINFO_HWEXCEPTION;
1717                 if (vcpu->exc_errcode_valid) {
1718                         info |= VM_INTINFO_DEL_ERRCODE;
1719                         info |= (uint64_t)vcpu->exc_errcode << 32;
1720                 }
1721         }
1722         return (info);
1723 }
1724
1725 int
1726 vm_entry_intinfo(struct vm *vm, int vcpuid, uint64_t *retinfo)
1727 {
1728         struct vcpu *vcpu;
1729         uint64_t info1, info2;
1730         int valid;
1731
1732         KASSERT(vcpuid >= 0 && vcpuid < VM_MAXCPU, ("invalid vcpu %d", vcpuid));
1733
1734         vcpu = &vm->vcpu[vcpuid];
1735
1736         info1 = vcpu->exitintinfo;
1737         vcpu->exitintinfo = 0;
1738
1739         info2 = 0;
1740         if (vcpu->exception_pending) {
1741                 info2 = vcpu_exception_intinfo(vcpu);
1742                 vcpu->exception_pending = 0;
1743                 VCPU_CTR2(vm, vcpuid, "Exception %d delivered: %#lx",
1744                     vcpu->exc_vector, info2);
1745         }
1746
1747         if ((info1 & VM_INTINFO_VALID) && (info2 & VM_INTINFO_VALID)) {
1748                 valid = nested_fault(vm, vcpuid, info1, info2, retinfo);
1749         } else if (info1 & VM_INTINFO_VALID) {
1750                 *retinfo = info1;
1751                 valid = 1;
1752         } else if (info2 & VM_INTINFO_VALID) {
1753                 *retinfo = info2;
1754                 valid = 1;
1755         } else {
1756                 valid = 0;
1757         }
1758
1759         if (valid) {
1760                 VCPU_CTR4(vm, vcpuid, "%s: info1(%#lx), info2(%#lx), "
1761                     "retinfo(%#lx)", __func__, info1, info2, *retinfo);
1762         }
1763
1764         return (valid);
1765 }
1766
1767 int
1768 vm_get_intinfo(struct vm *vm, int vcpuid, uint64_t *info1, uint64_t *info2)
1769 {
1770         struct vcpu *vcpu;
1771
1772         if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1773                 return (EINVAL);
1774
1775         vcpu = &vm->vcpu[vcpuid];
1776         *info1 = vcpu->exitintinfo;
1777         *info2 = vcpu_exception_intinfo(vcpu);
1778         return (0);
1779 }
1780
1781 int
1782 vm_inject_exception(struct vm *vm, int vcpuid, int vector, int errcode_valid,
1783     uint32_t errcode, int restart_instruction)
1784 {
1785         struct vcpu *vcpu;
1786         int error;
1787
1788         if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1789                 return (EINVAL);
1790
1791         if (vector < 0 || vector >= 32)
1792                 return (EINVAL);
1793
1794         /*
1795          * A double fault exception should never be injected directly into
1796          * the guest. It is a derived exception that results from specific
1797          * combinations of nested faults.
1798          */
1799         if (vector == IDT_DF)
1800                 return (EINVAL);
1801
1802         vcpu = &vm->vcpu[vcpuid];
1803
1804         if (vcpu->exception_pending) {
1805                 VCPU_CTR2(vm, vcpuid, "Unable to inject exception %d due to "
1806                     "pending exception %d", vector, vcpu->exc_vector);
1807                 return (EBUSY);
1808         }
1809
1810         /*
1811          * From section 26.6.1 "Interruptibility State" in Intel SDM:
1812          *
1813          * Event blocking by "STI" or "MOV SS" is cleared after guest executes
1814          * one instruction or incurs an exception.
1815          */
1816         error = vm_set_register(vm, vcpuid, VM_REG_GUEST_INTR_SHADOW, 0);
1817         KASSERT(error == 0, ("%s: error %d clearing interrupt shadow",
1818             __func__, error));
1819
1820         if (restart_instruction)
1821                 vm_restart_instruction(vm, vcpuid);
1822
1823         vcpu->exception_pending = 1;
1824         vcpu->exc_vector = vector;
1825         vcpu->exc_errcode = errcode;
1826         vcpu->exc_errcode_valid = errcode_valid;
1827         VCPU_CTR1(vm, vcpuid, "Exception %d pending", vector);
1828         return (0);
1829 }
1830
1831 void
1832 vm_inject_fault(void *vmarg, int vcpuid, int vector, int errcode_valid,
1833     int errcode)
1834 {
1835         struct vm *vm;
1836         int error, restart_instruction;
1837
1838         vm = vmarg;
1839         restart_instruction = 1;
1840
1841         error = vm_inject_exception(vm, vcpuid, vector, errcode_valid,
1842             errcode, restart_instruction);
1843         KASSERT(error == 0, ("vm_inject_exception error %d", error));
1844 }
1845
1846 void
1847 vm_inject_pf(void *vmarg, int vcpuid, int error_code, uint64_t cr2)
1848 {
1849         struct vm *vm;
1850         int error;
1851
1852         vm = vmarg;
1853         VCPU_CTR2(vm, vcpuid, "Injecting page fault: error_code %#x, cr2 %#lx",
1854             error_code, cr2);
1855
1856         error = vm_set_register(vm, vcpuid, VM_REG_GUEST_CR2, cr2);
1857         KASSERT(error == 0, ("vm_set_register(cr2) error %d", error));
1858
1859         vm_inject_fault(vm, vcpuid, IDT_PF, 1, error_code);
1860 }
1861
1862 static VMM_STAT(VCPU_NMI_COUNT, "number of NMIs delivered to vcpu");
1863
1864 int
1865 vm_inject_nmi(struct vm *vm, int vcpuid)
1866 {
1867         struct vcpu *vcpu;
1868
1869         if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1870                 return (EINVAL);
1871
1872         vcpu = &vm->vcpu[vcpuid];
1873
1874         vcpu->nmi_pending = 1;
1875         vcpu_notify_event(vm, vcpuid, false);
1876         return (0);
1877 }
1878
1879 int
1880 vm_nmi_pending(struct vm *vm, int vcpuid)
1881 {
1882         struct vcpu *vcpu;
1883
1884         if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1885                 panic("vm_nmi_pending: invalid vcpuid %d", vcpuid);
1886
1887         vcpu = &vm->vcpu[vcpuid];
1888
1889         return (vcpu->nmi_pending);
1890 }
1891
1892 void
1893 vm_nmi_clear(struct vm *vm, int vcpuid)
1894 {
1895         struct vcpu *vcpu;
1896
1897         if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1898                 panic("vm_nmi_pending: invalid vcpuid %d", vcpuid);
1899
1900         vcpu = &vm->vcpu[vcpuid];
1901
1902         if (vcpu->nmi_pending == 0)
1903                 panic("vm_nmi_clear: inconsistent nmi_pending state");
1904
1905         vcpu->nmi_pending = 0;
1906         vmm_stat_incr(vm, vcpuid, VCPU_NMI_COUNT, 1);
1907 }
1908
1909 static VMM_STAT(VCPU_EXTINT_COUNT, "number of ExtINTs delivered to vcpu");
1910
1911 int
1912 vm_inject_extint(struct vm *vm, int vcpuid)
1913 {
1914         struct vcpu *vcpu;
1915
1916         if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1917                 return (EINVAL);
1918
1919         vcpu = &vm->vcpu[vcpuid];
1920
1921         vcpu->extint_pending = 1;
1922         vcpu_notify_event(vm, vcpuid, false);
1923         return (0);
1924 }
1925
1926 int
1927 vm_extint_pending(struct vm *vm, int vcpuid)
1928 {
1929         struct vcpu *vcpu;
1930
1931         if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1932                 panic("vm_extint_pending: invalid vcpuid %d", vcpuid);
1933
1934         vcpu = &vm->vcpu[vcpuid];
1935
1936         return (vcpu->extint_pending);
1937 }
1938
1939 void
1940 vm_extint_clear(struct vm *vm, int vcpuid)
1941 {
1942         struct vcpu *vcpu;
1943
1944         if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1945                 panic("vm_extint_pending: invalid vcpuid %d", vcpuid);
1946
1947         vcpu = &vm->vcpu[vcpuid];
1948
1949         if (vcpu->extint_pending == 0)
1950                 panic("vm_extint_clear: inconsistent extint_pending state");
1951
1952         vcpu->extint_pending = 0;
1953         vmm_stat_incr(vm, vcpuid, VCPU_EXTINT_COUNT, 1);
1954 }
1955
1956 int
1957 vm_get_capability(struct vm *vm, int vcpu, int type, int *retval)
1958 {
1959         if (vcpu < 0 || vcpu >= VM_MAXCPU)
1960                 return (EINVAL);
1961
1962         if (type < 0 || type >= VM_CAP_MAX)
1963                 return (EINVAL);
1964
1965         return (VMGETCAP(vm->cookie, vcpu, type, retval));
1966 }
1967
1968 int
1969 vm_set_capability(struct vm *vm, int vcpu, int type, int val)
1970 {
1971         if (vcpu < 0 || vcpu >= VM_MAXCPU)
1972                 return (EINVAL);
1973
1974         if (type < 0 || type >= VM_CAP_MAX)
1975                 return (EINVAL);
1976
1977         return (VMSETCAP(vm->cookie, vcpu, type, val));
1978 }
1979
1980 struct vlapic *
1981 vm_lapic(struct vm *vm, int cpu)
1982 {
1983         return (vm->vcpu[cpu].vlapic);
1984 }
1985
1986 struct vioapic *
1987 vm_ioapic(struct vm *vm)
1988 {
1989
1990         return (vm->vioapic);
1991 }
1992
1993 struct vhpet *
1994 vm_hpet(struct vm *vm)
1995 {
1996
1997         return (vm->vhpet);
1998 }
1999
2000 boolean_t
2001 vmm_is_pptdev(int bus, int slot, int func)
2002 {
2003         int found, i, n;
2004         int b, s, f;
2005         char *val, *cp, *cp2;
2006
2007         /*
2008          * XXX
2009          * The length of an environment variable is limited to 128 bytes which
2010          * puts an upper limit on the number of passthru devices that may be
2011          * specified using a single environment variable.
2012          *
2013          * Work around this by scanning multiple environment variable
2014          * names instead of a single one - yuck!
2015          */
2016         const char *names[] = { "pptdevs", "pptdevs2", "pptdevs3", NULL };
2017
2018         /* set pptdevs="1/2/3 4/5/6 7/8/9 10/11/12" */
2019         found = 0;
2020         for (i = 0; names[i] != NULL && !found; i++) {
2021                 cp = val = kern_getenv(names[i]);
2022                 while (cp != NULL && *cp != '\0') {
2023                         if ((cp2 = strchr(cp, ' ')) != NULL)
2024                                 *cp2 = '\0';
2025
2026                         n = sscanf(cp, "%d/%d/%d", &b, &s, &f);
2027                         if (n == 3 && bus == b && slot == s && func == f) {
2028                                 found = 1;
2029                                 break;
2030                         }
2031                 
2032                         if (cp2 != NULL)
2033                                 *cp2++ = ' ';
2034
2035                         cp = cp2;
2036                 }
2037                 freeenv(val);
2038         }
2039         return (found);
2040 }
2041
2042 void *
2043 vm_iommu_domain(struct vm *vm)
2044 {
2045
2046         return (vm->iommu);
2047 }
2048
2049 int
2050 vcpu_set_state(struct vm *vm, int vcpuid, enum vcpu_state newstate,
2051     bool from_idle)
2052 {
2053         int error;
2054         struct vcpu *vcpu;
2055
2056         if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
2057                 panic("vm_set_run_state: invalid vcpuid %d", vcpuid);
2058
2059         vcpu = &vm->vcpu[vcpuid];
2060
2061         vcpu_lock(vcpu);
2062         error = vcpu_set_state_locked(vcpu, newstate, from_idle);
2063         vcpu_unlock(vcpu);
2064
2065         return (error);
2066 }
2067
2068 enum vcpu_state
2069 vcpu_get_state(struct vm *vm, int vcpuid, int *hostcpu)
2070 {
2071         struct vcpu *vcpu;
2072         enum vcpu_state state;
2073
2074         if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
2075                 panic("vm_get_run_state: invalid vcpuid %d", vcpuid);
2076
2077         vcpu = &vm->vcpu[vcpuid];
2078
2079         vcpu_lock(vcpu);
2080         state = vcpu->state;
2081         if (hostcpu != NULL)
2082                 *hostcpu = vcpu->hostcpu;
2083         vcpu_unlock(vcpu);
2084
2085         return (state);
2086 }
2087
2088 int
2089 vm_activate_cpu(struct vm *vm, int vcpuid)
2090 {
2091
2092         if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
2093                 return (EINVAL);
2094
2095         if (CPU_ISSET(vcpuid, &vm->active_cpus))
2096                 return (EBUSY);
2097
2098         VCPU_CTR0(vm, vcpuid, "activated");
2099         CPU_SET_ATOMIC(vcpuid, &vm->active_cpus);
2100         return (0);
2101 }
2102
2103 cpuset_t
2104 vm_active_cpus(struct vm *vm)
2105 {
2106
2107         return (vm->active_cpus);
2108 }
2109
2110 cpuset_t
2111 vm_suspended_cpus(struct vm *vm)
2112 {
2113
2114         return (vm->suspended_cpus);
2115 }
2116
2117 void *
2118 vcpu_stats(struct vm *vm, int vcpuid)
2119 {
2120
2121         return (vm->vcpu[vcpuid].stats);
2122 }
2123
2124 int
2125 vm_get_x2apic_state(struct vm *vm, int vcpuid, enum x2apic_state *state)
2126 {
2127         if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
2128                 return (EINVAL);
2129
2130         *state = vm->vcpu[vcpuid].x2apic_state;
2131
2132         return (0);
2133 }
2134
2135 int
2136 vm_set_x2apic_state(struct vm *vm, int vcpuid, enum x2apic_state state)
2137 {
2138         if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
2139                 return (EINVAL);
2140
2141         if (state >= X2APIC_STATE_LAST)
2142                 return (EINVAL);
2143
2144         vm->vcpu[vcpuid].x2apic_state = state;
2145
2146         vlapic_set_x2apic_state(vm, vcpuid, state);
2147
2148         return (0);
2149 }
2150
2151 /*
2152  * This function is called to ensure that a vcpu "sees" a pending event
2153  * as soon as possible:
2154  * - If the vcpu thread is sleeping then it is woken up.
2155  * - If the vcpu is running on a different host_cpu then an IPI will be directed
2156  *   to the host_cpu to cause the vcpu to trap into the hypervisor.
2157  */
2158 void
2159 vcpu_notify_event(struct vm *vm, int vcpuid, bool lapic_intr)
2160 {
2161         int hostcpu;
2162         struct vcpu *vcpu;
2163
2164         vcpu = &vm->vcpu[vcpuid];
2165
2166         vcpu_lock(vcpu);
2167         hostcpu = vcpu->hostcpu;
2168         if (vcpu->state == VCPU_RUNNING) {
2169                 KASSERT(hostcpu != NOCPU, ("vcpu running on invalid hostcpu"));
2170                 if (hostcpu != curcpu) {
2171                         if (lapic_intr) {
2172                                 vlapic_post_intr(vcpu->vlapic, hostcpu,
2173                                     vmm_ipinum);
2174                         } else {
2175                                 ipi_cpu(hostcpu, vmm_ipinum);
2176                         }
2177                 } else {
2178                         /*
2179                          * If the 'vcpu' is running on 'curcpu' then it must
2180                          * be sending a notification to itself (e.g. SELF_IPI).
2181                          * The pending event will be picked up when the vcpu
2182                          * transitions back to guest context.
2183                          */
2184                 }
2185         } else {
2186                 KASSERT(hostcpu == NOCPU, ("vcpu state %d not consistent "
2187                     "with hostcpu %d", vcpu->state, hostcpu));
2188                 if (vcpu->state == VCPU_SLEEPING)
2189                         wakeup_one(vcpu);
2190         }
2191         vcpu_unlock(vcpu);
2192 }
2193
2194 struct vmspace *
2195 vm_get_vmspace(struct vm *vm)
2196 {
2197
2198         return (vm->vmspace);
2199 }
2200
2201 int
2202 vm_apicid2vcpuid(struct vm *vm, int apicid)
2203 {
2204         /*
2205          * XXX apic id is assumed to be numerically identical to vcpu id
2206          */
2207         return (apicid);
2208 }
2209
2210 void
2211 vm_smp_rendezvous(struct vm *vm, int vcpuid, cpuset_t dest,
2212     vm_rendezvous_func_t func, void *arg)
2213 {
2214         int i;
2215
2216         /*
2217          * Enforce that this function is called without any locks
2218          */
2219         WITNESS_WARN(WARN_PANIC, NULL, "vm_smp_rendezvous");
2220         KASSERT(vcpuid == -1 || (vcpuid >= 0 && vcpuid < VM_MAXCPU),
2221             ("vm_smp_rendezvous: invalid vcpuid %d", vcpuid));
2222
2223 restart:
2224         mtx_lock(&vm->rendezvous_mtx);
2225         if (vm->rendezvous_func != NULL) {
2226                 /*
2227                  * If a rendezvous is already in progress then we need to
2228                  * call the rendezvous handler in case this 'vcpuid' is one
2229                  * of the targets of the rendezvous.
2230                  */
2231                 RENDEZVOUS_CTR0(vm, vcpuid, "Rendezvous already in progress");
2232                 mtx_unlock(&vm->rendezvous_mtx);
2233                 vm_handle_rendezvous(vm, vcpuid);
2234                 goto restart;
2235         }
2236         KASSERT(vm->rendezvous_func == NULL, ("vm_smp_rendezvous: previous "
2237             "rendezvous is still in progress"));
2238
2239         RENDEZVOUS_CTR0(vm, vcpuid, "Initiating rendezvous");
2240         vm->rendezvous_req_cpus = dest;
2241         CPU_ZERO(&vm->rendezvous_done_cpus);
2242         vm->rendezvous_arg = arg;
2243         vm_set_rendezvous_func(vm, func);
2244         mtx_unlock(&vm->rendezvous_mtx);
2245
2246         /*
2247          * Wake up any sleeping vcpus and trigger a VM-exit in any running
2248          * vcpus so they handle the rendezvous as soon as possible.
2249          */
2250         for (i = 0; i < VM_MAXCPU; i++) {
2251                 if (CPU_ISSET(i, &dest))
2252                         vcpu_notify_event(vm, i, false);
2253         }
2254
2255         vm_handle_rendezvous(vm, vcpuid);
2256 }
2257
2258 struct vatpic *
2259 vm_atpic(struct vm *vm)
2260 {
2261         return (vm->vatpic);
2262 }
2263
2264 struct vatpit *
2265 vm_atpit(struct vm *vm)
2266 {
2267         return (vm->vatpit);
2268 }
2269
2270 struct vpmtmr *
2271 vm_pmtmr(struct vm *vm)
2272 {
2273
2274         return (vm->vpmtmr);
2275 }
2276
2277 struct vrtc *
2278 vm_rtc(struct vm *vm)
2279 {
2280
2281         return (vm->vrtc);
2282 }
2283
2284 enum vm_reg_name
2285 vm_segment_name(int seg)
2286 {
2287         static enum vm_reg_name seg_names[] = {
2288                 VM_REG_GUEST_ES,
2289                 VM_REG_GUEST_CS,
2290                 VM_REG_GUEST_SS,
2291                 VM_REG_GUEST_DS,
2292                 VM_REG_GUEST_FS,
2293                 VM_REG_GUEST_GS
2294         };
2295
2296         KASSERT(seg >= 0 && seg < nitems(seg_names),
2297             ("%s: invalid segment encoding %d", __func__, seg));
2298         return (seg_names[seg]);
2299 }
2300
2301 void
2302 vm_copy_teardown(struct vm *vm, int vcpuid, struct vm_copyinfo *copyinfo,
2303     int num_copyinfo)
2304 {
2305         int idx;
2306
2307         for (idx = 0; idx < num_copyinfo; idx++) {
2308                 if (copyinfo[idx].cookie != NULL)
2309                         vm_gpa_release(copyinfo[idx].cookie);
2310         }
2311         bzero(copyinfo, num_copyinfo * sizeof(struct vm_copyinfo));
2312 }
2313
2314 int
2315 vm_copy_setup(struct vm *vm, int vcpuid, struct vm_guest_paging *paging,
2316     uint64_t gla, size_t len, int prot, struct vm_copyinfo *copyinfo,
2317     int num_copyinfo)
2318 {
2319         int error, idx, nused;
2320         size_t n, off, remaining;
2321         void *hva, *cookie;
2322         uint64_t gpa;
2323
2324         bzero(copyinfo, sizeof(struct vm_copyinfo) * num_copyinfo);
2325
2326         nused = 0;
2327         remaining = len;
2328         while (remaining > 0) {
2329                 KASSERT(nused < num_copyinfo, ("insufficient vm_copyinfo"));
2330                 error = vmm_gla2gpa(vm, vcpuid, paging, gla, prot, &gpa);
2331                 if (error)
2332                         return (error);
2333                 off = gpa & PAGE_MASK;
2334                 n = min(remaining, PAGE_SIZE - off);
2335                 copyinfo[nused].gpa = gpa;
2336                 copyinfo[nused].len = n;
2337                 remaining -= n;
2338                 gla += n;
2339                 nused++;
2340         }
2341
2342         for (idx = 0; idx < nused; idx++) {
2343                 hva = vm_gpa_hold(vm, copyinfo[idx].gpa, copyinfo[idx].len,
2344                     prot, &cookie);
2345                 if (hva == NULL)
2346                         break;
2347                 copyinfo[idx].hva = hva;
2348                 copyinfo[idx].cookie = cookie;
2349         }
2350
2351         if (idx != nused) {
2352                 vm_copy_teardown(vm, vcpuid, copyinfo, num_copyinfo);
2353                 return (-1);
2354         } else {
2355                 return (0);
2356         }
2357 }
2358
2359 void
2360 vm_copyin(struct vm *vm, int vcpuid, struct vm_copyinfo *copyinfo, void *kaddr,
2361     size_t len)
2362 {
2363         char *dst;
2364         int idx;
2365         
2366         dst = kaddr;
2367         idx = 0;
2368         while (len > 0) {
2369                 bcopy(copyinfo[idx].hva, dst, copyinfo[idx].len);
2370                 len -= copyinfo[idx].len;
2371                 dst += copyinfo[idx].len;
2372                 idx++;
2373         }
2374 }
2375
2376 void
2377 vm_copyout(struct vm *vm, int vcpuid, const void *kaddr,
2378     struct vm_copyinfo *copyinfo, size_t len)
2379 {
2380         const char *src;
2381         int idx;
2382
2383         src = kaddr;
2384         idx = 0;
2385         while (len > 0) {
2386                 bcopy(src, copyinfo[idx].hva, copyinfo[idx].len);
2387                 len -= copyinfo[idx].len;
2388                 src += copyinfo[idx].len;
2389                 idx++;
2390         }
2391 }
2392
2393 /*
2394  * Return the amount of in-use and wired memory for the VM. Since
2395  * these are global stats, only return the values with for vCPU 0
2396  */
2397 VMM_STAT_DECLARE(VMM_MEM_RESIDENT);
2398 VMM_STAT_DECLARE(VMM_MEM_WIRED);
2399
2400 static void
2401 vm_get_rescnt(struct vm *vm, int vcpu, struct vmm_stat_type *stat)
2402 {
2403
2404         if (vcpu == 0) {
2405                 vmm_stat_set(vm, vcpu, VMM_MEM_RESIDENT,
2406                     PAGE_SIZE * vmspace_resident_count(vm->vmspace));
2407         }       
2408 }
2409
2410 static void
2411 vm_get_wiredcnt(struct vm *vm, int vcpu, struct vmm_stat_type *stat)
2412 {
2413
2414         if (vcpu == 0) {
2415                 vmm_stat_set(vm, vcpu, VMM_MEM_WIRED,
2416                     PAGE_SIZE * pmap_wired_count(vmspace_pmap(vm->vmspace)));
2417         }       
2418 }
2419
2420 VMM_STAT_FUNC(VMM_MEM_RESIDENT, "Resident memory", vm_get_rescnt);
2421 VMM_STAT_FUNC(VMM_MEM_WIRED, "Wired memory", vm_get_wiredcnt);