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