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