~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/arch/x86/kvm/vmx.c

Version: ~ [ linux-5.1-rc1 ] ~ [ linux-5.0.3 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.30 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.107 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.164 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.176 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.136 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.63 ] ~ [ linux-3.15.10 ] ~ [ linux-3.14.79 ] ~ [ linux-3.13.11 ] ~ [ linux-3.12.74 ] ~ [ linux-3.11.10 ] ~ [ linux-3.10.108 ] ~ [ linux-3.9.11 ] ~ [ linux-3.8.13 ] ~ [ linux-3.7.10 ] ~ [ linux-3.6.11 ] ~ [ linux-3.5.7 ] ~ [ linux-3.4.113 ] ~ [ linux-3.3.8 ] ~ [ linux-3.2.102 ] ~ [ linux-3.1.10 ] ~ [ linux-3.0.101 ] ~ [ linux-2.6.39.4 ] ~ [ linux-2.6.38.8 ] ~ [ linux-2.6.37.6 ] ~ [ linux-2.6.36.4 ] ~ [ linux-2.6.35.14 ] ~ [ linux-2.6.34.15 ] ~ [ linux-2.6.33.20 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

  1 /*
  2  * Kernel-based Virtual Machine driver for Linux
  3  *
  4  * This module enables machines with Intel VT-x extensions to run virtual
  5  * machines without emulation or binary translation.
  6  *
  7  * Copyright (C) 2006 Qumranet, Inc.
  8  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
  9  *
 10  * Authors:
 11  *   Avi Kivity   <avi@qumranet.com>
 12  *   Yaniv Kamay  <yaniv@qumranet.com>
 13  *
 14  * This work is licensed under the terms of the GNU GPL, version 2.  See
 15  * the COPYING file in the top-level directory.
 16  *
 17  */
 18 
 19 #include "irq.h"
 20 #include "mmu.h"
 21 
 22 #include <linux/kvm_host.h>
 23 #include <linux/module.h>
 24 #include <linux/kernel.h>
 25 #include <linux/mm.h>
 26 #include <linux/highmem.h>
 27 #include <linux/sched.h>
 28 #include <linux/moduleparam.h>
 29 #include <linux/ftrace_event.h>
 30 #include <linux/slab.h>
 31 #include <linux/tboot.h>
 32 #include "kvm_cache_regs.h"
 33 #include "x86.h"
 34 
 35 #include <asm/io.h>
 36 #include <asm/desc.h>
 37 #include <asm/vmx.h>
 38 #include <asm/virtext.h>
 39 #include <asm/mce.h>
 40 #include <asm/i387.h>
 41 #include <asm/xcr.h>
 42 
 43 #include "trace.h"
 44 
 45 #define __ex(x) __kvm_handle_fault_on_reboot(x)
 46 
 47 MODULE_AUTHOR("Qumranet");
 48 MODULE_LICENSE("GPL");
 49 
 50 static int __read_mostly bypass_guest_pf = 1;
 51 module_param(bypass_guest_pf, bool, S_IRUGO);
 52 
 53 static int __read_mostly enable_vpid = 1;
 54 module_param_named(vpid, enable_vpid, bool, 0444);
 55 
 56 static int __read_mostly flexpriority_enabled = 1;
 57 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
 58 
 59 static int __read_mostly enable_ept = 1;
 60 module_param_named(ept, enable_ept, bool, S_IRUGO);
 61 
 62 static int __read_mostly enable_unrestricted_guest = 1;
 63 module_param_named(unrestricted_guest,
 64                         enable_unrestricted_guest, bool, S_IRUGO);
 65 
 66 static int __read_mostly emulate_invalid_guest_state = 0;
 67 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
 68 
 69 static int __read_mostly vmm_exclusive = 1;
 70 module_param(vmm_exclusive, bool, S_IRUGO);
 71 
 72 static int __read_mostly yield_on_hlt = 1;
 73 module_param(yield_on_hlt, bool, S_IRUGO);
 74 
 75 #define KVM_GUEST_CR0_MASK_UNRESTRICTED_GUEST                           \
 76         (X86_CR0_WP | X86_CR0_NE | X86_CR0_NW | X86_CR0_CD)
 77 #define KVM_GUEST_CR0_MASK                                              \
 78         (KVM_GUEST_CR0_MASK_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE)
 79 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST                         \
 80         (X86_CR0_WP | X86_CR0_NE)
 81 #define KVM_VM_CR0_ALWAYS_ON                                            \
 82         (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE)
 83 #define KVM_CR4_GUEST_OWNED_BITS                                      \
 84         (X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR      \
 85          | X86_CR4_OSXMMEXCPT)
 86 
 87 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
 88 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
 89 
 90 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
 91 
 92 /*
 93  * These 2 parameters are used to config the controls for Pause-Loop Exiting:
 94  * ple_gap:    upper bound on the amount of time between two successive
 95  *             executions of PAUSE in a loop. Also indicate if ple enabled.
 96  *             According to test, this time is usually smaller than 128 cycles.
 97  * ple_window: upper bound on the amount of time a guest is allowed to execute
 98  *             in a PAUSE loop. Tests indicate that most spinlocks are held for
 99  *             less than 2^12 cycles
100  * Time is measured based on a counter that runs at the same rate as the TSC,
101  * refer SDM volume 3b section 21.6.13 & 22.1.3.
102  */
103 #define KVM_VMX_DEFAULT_PLE_GAP    128
104 #define KVM_VMX_DEFAULT_PLE_WINDOW 4096
105 static int ple_gap = KVM_VMX_DEFAULT_PLE_GAP;
106 module_param(ple_gap, int, S_IRUGO);
107 
108 static int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
109 module_param(ple_window, int, S_IRUGO);
110 
111 #define NR_AUTOLOAD_MSRS 1
112 
113 struct vmcs {
114         u32 revision_id;
115         u32 abort;
116         char data[0];
117 };
118 
119 struct shared_msr_entry {
120         unsigned index;
121         u64 data;
122         u64 mask;
123 };
124 
125 struct vcpu_vmx {
126         struct kvm_vcpu       vcpu;
127         struct list_head      local_vcpus_link;
128         unsigned long         host_rsp;
129         int                   launched;
130         u8                    fail;
131         u8                    cpl;
132         bool                  nmi_known_unmasked;
133         u32                   exit_intr_info;
134         u32                   idt_vectoring_info;
135         ulong                 rflags;
136         struct shared_msr_entry *guest_msrs;
137         int                   nmsrs;
138         int                   save_nmsrs;
139 #ifdef CONFIG_X86_64
140         u64                   msr_host_kernel_gs_base;
141         u64                   msr_guest_kernel_gs_base;
142 #endif
143         struct vmcs          *vmcs;
144         struct msr_autoload {
145                 unsigned nr;
146                 struct vmx_msr_entry guest[NR_AUTOLOAD_MSRS];
147                 struct vmx_msr_entry host[NR_AUTOLOAD_MSRS];
148         } msr_autoload;
149         struct {
150                 int           loaded;
151                 u16           fs_sel, gs_sel, ldt_sel;
152                 int           gs_ldt_reload_needed;
153                 int           fs_reload_needed;
154         } host_state;
155         struct {
156                 int vm86_active;
157                 ulong save_rflags;
158                 struct kvm_save_segment {
159                         u16 selector;
160                         unsigned long base;
161                         u32 limit;
162                         u32 ar;
163                 } tr, es, ds, fs, gs;
164         } rmode;
165         struct {
166                 u32 bitmask; /* 4 bits per segment (1 bit per field) */
167                 struct kvm_save_segment seg[8];
168         } segment_cache;
169         int vpid;
170         bool emulation_required;
171 
172         /* Support for vnmi-less CPUs */
173         int soft_vnmi_blocked;
174         ktime_t entry_time;
175         s64 vnmi_blocked_time;
176         u32 exit_reason;
177 
178         bool rdtscp_enabled;
179 };
180 
181 enum segment_cache_field {
182         SEG_FIELD_SEL = 0,
183         SEG_FIELD_BASE = 1,
184         SEG_FIELD_LIMIT = 2,
185         SEG_FIELD_AR = 3,
186 
187         SEG_FIELD_NR = 4
188 };
189 
190 static inline struct vcpu_vmx *to_vmx(struct kvm_vcpu *vcpu)
191 {
192         return container_of(vcpu, struct vcpu_vmx, vcpu);
193 }
194 
195 static u64 construct_eptp(unsigned long root_hpa);
196 static void kvm_cpu_vmxon(u64 addr);
197 static void kvm_cpu_vmxoff(void);
198 static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3);
199 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr);
200 
201 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
202 static DEFINE_PER_CPU(struct vmcs *, current_vmcs);
203 static DEFINE_PER_CPU(struct list_head, vcpus_on_cpu);
204 static DEFINE_PER_CPU(struct desc_ptr, host_gdt);
205 
206 static unsigned long *vmx_io_bitmap_a;
207 static unsigned long *vmx_io_bitmap_b;
208 static unsigned long *vmx_msr_bitmap_legacy;
209 static unsigned long *vmx_msr_bitmap_longmode;
210 
211 static bool cpu_has_load_ia32_efer;
212 
213 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
214 static DEFINE_SPINLOCK(vmx_vpid_lock);
215 
216 static struct vmcs_config {
217         int size;
218         int order;
219         u32 revision_id;
220         u32 pin_based_exec_ctrl;
221         u32 cpu_based_exec_ctrl;
222         u32 cpu_based_2nd_exec_ctrl;
223         u32 vmexit_ctrl;
224         u32 vmentry_ctrl;
225 } vmcs_config;
226 
227 static struct vmx_capability {
228         u32 ept;
229         u32 vpid;
230 } vmx_capability;
231 
232 #define VMX_SEGMENT_FIELD(seg)                                  \
233         [VCPU_SREG_##seg] = {                                   \
234                 .selector = GUEST_##seg##_SELECTOR,             \
235                 .base = GUEST_##seg##_BASE,                     \
236                 .limit = GUEST_##seg##_LIMIT,                   \
237                 .ar_bytes = GUEST_##seg##_AR_BYTES,             \
238         }
239 
240 static struct kvm_vmx_segment_field {
241         unsigned selector;
242         unsigned base;
243         unsigned limit;
244         unsigned ar_bytes;
245 } kvm_vmx_segment_fields[] = {
246         VMX_SEGMENT_FIELD(CS),
247         VMX_SEGMENT_FIELD(DS),
248         VMX_SEGMENT_FIELD(ES),
249         VMX_SEGMENT_FIELD(FS),
250         VMX_SEGMENT_FIELD(GS),
251         VMX_SEGMENT_FIELD(SS),
252         VMX_SEGMENT_FIELD(TR),
253         VMX_SEGMENT_FIELD(LDTR),
254 };
255 
256 static u64 host_efer;
257 
258 static void ept_save_pdptrs(struct kvm_vcpu *vcpu);
259 
260 /*
261  * Keep MSR_STAR at the end, as setup_msrs() will try to optimize it
262  * away by decrementing the array size.
263  */
264 static const u32 vmx_msr_index[] = {
265 #ifdef CONFIG_X86_64
266         MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
267 #endif
268         MSR_EFER, MSR_TSC_AUX, MSR_STAR,
269 };
270 #define NR_VMX_MSR ARRAY_SIZE(vmx_msr_index)
271 
272 static inline bool is_page_fault(u32 intr_info)
273 {
274         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
275                              INTR_INFO_VALID_MASK)) ==
276                 (INTR_TYPE_HARD_EXCEPTION | PF_VECTOR | INTR_INFO_VALID_MASK);
277 }
278 
279 static inline bool is_no_device(u32 intr_info)
280 {
281         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
282                              INTR_INFO_VALID_MASK)) ==
283                 (INTR_TYPE_HARD_EXCEPTION | NM_VECTOR | INTR_INFO_VALID_MASK);
284 }
285 
286 static inline bool is_invalid_opcode(u32 intr_info)
287 {
288         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
289                              INTR_INFO_VALID_MASK)) ==
290                 (INTR_TYPE_HARD_EXCEPTION | UD_VECTOR | INTR_INFO_VALID_MASK);
291 }
292 
293 static inline bool is_external_interrupt(u32 intr_info)
294 {
295         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
296                 == (INTR_TYPE_EXT_INTR | INTR_INFO_VALID_MASK);
297 }
298 
299 static inline bool is_machine_check(u32 intr_info)
300 {
301         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
302                              INTR_INFO_VALID_MASK)) ==
303                 (INTR_TYPE_HARD_EXCEPTION | MC_VECTOR | INTR_INFO_VALID_MASK);
304 }
305 
306 static inline bool cpu_has_vmx_msr_bitmap(void)
307 {
308         return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_USE_MSR_BITMAPS;
309 }
310 
311 static inline bool cpu_has_vmx_tpr_shadow(void)
312 {
313         return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW;
314 }
315 
316 static inline bool vm_need_tpr_shadow(struct kvm *kvm)
317 {
318         return (cpu_has_vmx_tpr_shadow()) && (irqchip_in_kernel(kvm));
319 }
320 
321 static inline bool cpu_has_secondary_exec_ctrls(void)
322 {
323         return vmcs_config.cpu_based_exec_ctrl &
324                 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
325 }
326 
327 static inline bool cpu_has_vmx_virtualize_apic_accesses(void)
328 {
329         return vmcs_config.cpu_based_2nd_exec_ctrl &
330                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
331 }
332 
333 static inline bool cpu_has_vmx_flexpriority(void)
334 {
335         return cpu_has_vmx_tpr_shadow() &&
336                 cpu_has_vmx_virtualize_apic_accesses();
337 }
338 
339 static inline bool cpu_has_vmx_ept_execute_only(void)
340 {
341         return vmx_capability.ept & VMX_EPT_EXECUTE_ONLY_BIT;
342 }
343 
344 static inline bool cpu_has_vmx_eptp_uncacheable(void)
345 {
346         return vmx_capability.ept & VMX_EPTP_UC_BIT;
347 }
348 
349 static inline bool cpu_has_vmx_eptp_writeback(void)
350 {
351         return vmx_capability.ept & VMX_EPTP_WB_BIT;
352 }
353 
354 static inline bool cpu_has_vmx_ept_2m_page(void)
355 {
356         return vmx_capability.ept & VMX_EPT_2MB_PAGE_BIT;
357 }
358 
359 static inline bool cpu_has_vmx_ept_1g_page(void)
360 {
361         return vmx_capability.ept & VMX_EPT_1GB_PAGE_BIT;
362 }
363 
364 static inline bool cpu_has_vmx_ept_4levels(void)
365 {
366         return vmx_capability.ept & VMX_EPT_PAGE_WALK_4_BIT;
367 }
368 
369 static inline bool cpu_has_vmx_invept_individual_addr(void)
370 {
371         return vmx_capability.ept & VMX_EPT_EXTENT_INDIVIDUAL_BIT;
372 }
373 
374 static inline bool cpu_has_vmx_invept_context(void)
375 {
376         return vmx_capability.ept & VMX_EPT_EXTENT_CONTEXT_BIT;
377 }
378 
379 static inline bool cpu_has_vmx_invept_global(void)
380 {
381         return vmx_capability.ept & VMX_EPT_EXTENT_GLOBAL_BIT;
382 }
383 
384 static inline bool cpu_has_vmx_invvpid_single(void)
385 {
386         return vmx_capability.vpid & VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT;
387 }
388 
389 static inline bool cpu_has_vmx_invvpid_global(void)
390 {
391         return vmx_capability.vpid & VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT;
392 }
393 
394 static inline bool cpu_has_vmx_ept(void)
395 {
396         return vmcs_config.cpu_based_2nd_exec_ctrl &
397                 SECONDARY_EXEC_ENABLE_EPT;
398 }
399 
400 static inline bool cpu_has_vmx_unrestricted_guest(void)
401 {
402         return vmcs_config.cpu_based_2nd_exec_ctrl &
403                 SECONDARY_EXEC_UNRESTRICTED_GUEST;
404 }
405 
406 static inline bool cpu_has_vmx_ple(void)
407 {
408         return vmcs_config.cpu_based_2nd_exec_ctrl &
409                 SECONDARY_EXEC_PAUSE_LOOP_EXITING;
410 }
411 
412 static inline bool vm_need_virtualize_apic_accesses(struct kvm *kvm)
413 {
414         return flexpriority_enabled && irqchip_in_kernel(kvm);
415 }
416 
417 static inline bool cpu_has_vmx_vpid(void)
418 {
419         return vmcs_config.cpu_based_2nd_exec_ctrl &
420                 SECONDARY_EXEC_ENABLE_VPID;
421 }
422 
423 static inline bool cpu_has_vmx_rdtscp(void)
424 {
425         return vmcs_config.cpu_based_2nd_exec_ctrl &
426                 SECONDARY_EXEC_RDTSCP;
427 }
428 
429 static inline bool cpu_has_virtual_nmis(void)
430 {
431         return vmcs_config.pin_based_exec_ctrl & PIN_BASED_VIRTUAL_NMIS;
432 }
433 
434 static inline bool cpu_has_vmx_wbinvd_exit(void)
435 {
436         return vmcs_config.cpu_based_2nd_exec_ctrl &
437                 SECONDARY_EXEC_WBINVD_EXITING;
438 }
439 
440 static inline bool report_flexpriority(void)
441 {
442         return flexpriority_enabled;
443 }
444 
445 static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
446 {
447         int i;
448 
449         for (i = 0; i < vmx->nmsrs; ++i)
450                 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
451                         return i;
452         return -1;
453 }
454 
455 static inline void __invvpid(int ext, u16 vpid, gva_t gva)
456 {
457     struct {
458         u64 vpid : 16;
459         u64 rsvd : 48;
460         u64 gva;
461     } operand = { vpid, 0, gva };
462 
463     asm volatile (__ex(ASM_VMX_INVVPID)
464                   /* CF==1 or ZF==1 --> rc = -1 */
465                   "; ja 1f ; ud2 ; 1:"
466                   : : "a"(&operand), "c"(ext) : "cc", "memory");
467 }
468 
469 static inline void __invept(int ext, u64 eptp, gpa_t gpa)
470 {
471         struct {
472                 u64 eptp, gpa;
473         } operand = {eptp, gpa};
474 
475         asm volatile (__ex(ASM_VMX_INVEPT)
476                         /* CF==1 or ZF==1 --> rc = -1 */
477                         "; ja 1f ; ud2 ; 1:\n"
478                         : : "a" (&operand), "c" (ext) : "cc", "memory");
479 }
480 
481 static struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
482 {
483         int i;
484 
485         i = __find_msr_index(vmx, msr);
486         if (i >= 0)
487                 return &vmx->guest_msrs[i];
488         return NULL;
489 }
490 
491 static void vmcs_clear(struct vmcs *vmcs)
492 {
493         u64 phys_addr = __pa(vmcs);
494         u8 error;
495 
496         asm volatile (__ex(ASM_VMX_VMCLEAR_RAX) "; setna %0"
497                       : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
498                       : "cc", "memory");
499         if (error)
500                 printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n",
501                        vmcs, phys_addr);
502 }
503 
504 static void vmcs_load(struct vmcs *vmcs)
505 {
506         u64 phys_addr = __pa(vmcs);
507         u8 error;
508 
509         asm volatile (__ex(ASM_VMX_VMPTRLD_RAX) "; setna %0"
510                         : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
511                         : "cc", "memory");
512         if (error)
513                 printk(KERN_ERR "kvm: vmptrld %p/%llx fail\n",
514                        vmcs, phys_addr);
515 }
516 
517 static void __vcpu_clear(void *arg)
518 {
519         struct vcpu_vmx *vmx = arg;
520         int cpu = raw_smp_processor_id();
521 
522         if (vmx->vcpu.cpu == cpu)
523                 vmcs_clear(vmx->vmcs);
524         if (per_cpu(current_vmcs, cpu) == vmx->vmcs)
525                 per_cpu(current_vmcs, cpu) = NULL;
526         list_del(&vmx->local_vcpus_link);
527         vmx->vcpu.cpu = -1;
528         vmx->launched = 0;
529 }
530 
531 static void vcpu_clear(struct vcpu_vmx *vmx)
532 {
533         if (vmx->vcpu.cpu == -1)
534                 return;
535         smp_call_function_single(vmx->vcpu.cpu, __vcpu_clear, vmx, 1);
536 }
537 
538 static inline void vpid_sync_vcpu_single(struct vcpu_vmx *vmx)
539 {
540         if (vmx->vpid == 0)
541                 return;
542 
543         if (cpu_has_vmx_invvpid_single())
544                 __invvpid(VMX_VPID_EXTENT_SINGLE_CONTEXT, vmx->vpid, 0);
545 }
546 
547 static inline void vpid_sync_vcpu_global(void)
548 {
549         if (cpu_has_vmx_invvpid_global())
550                 __invvpid(VMX_VPID_EXTENT_ALL_CONTEXT, 0, 0);
551 }
552 
553 static inline void vpid_sync_context(struct vcpu_vmx *vmx)
554 {
555         if (cpu_has_vmx_invvpid_single())
556                 vpid_sync_vcpu_single(vmx);
557         else
558                 vpid_sync_vcpu_global();
559 }
560 
561 static inline void ept_sync_global(void)
562 {
563         if (cpu_has_vmx_invept_global())
564                 __invept(VMX_EPT_EXTENT_GLOBAL, 0, 0);
565 }
566 
567 static inline void ept_sync_context(u64 eptp)
568 {
569         if (enable_ept) {
570                 if (cpu_has_vmx_invept_context())
571                         __invept(VMX_EPT_EXTENT_CONTEXT, eptp, 0);
572                 else
573                         ept_sync_global();
574         }
575 }
576 
577 static inline void ept_sync_individual_addr(u64 eptp, gpa_t gpa)
578 {
579         if (enable_ept) {
580                 if (cpu_has_vmx_invept_individual_addr())
581                         __invept(VMX_EPT_EXTENT_INDIVIDUAL_ADDR,
582                                         eptp, gpa);
583                 else
584                         ept_sync_context(eptp);
585         }
586 }
587 
588 static unsigned long vmcs_readl(unsigned long field)
589 {
590         unsigned long value = 0;
591 
592         asm volatile (__ex(ASM_VMX_VMREAD_RDX_RAX)
593                       : "+a"(value) : "d"(field) : "cc");
594         return value;
595 }
596 
597 static u16 vmcs_read16(unsigned long field)
598 {
599         return vmcs_readl(field);
600 }
601 
602 static u32 vmcs_read32(unsigned long field)
603 {
604         return vmcs_readl(field);
605 }
606 
607 static u64 vmcs_read64(unsigned long field)
608 {
609 #ifdef CONFIG_X86_64
610         return vmcs_readl(field);
611 #else
612         return vmcs_readl(field) | ((u64)vmcs_readl(field+1) << 32);
613 #endif
614 }
615 
616 static noinline void vmwrite_error(unsigned long field, unsigned long value)
617 {
618         printk(KERN_ERR "vmwrite error: reg %lx value %lx (err %d)\n",
619                field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
620         dump_stack();
621 }
622 
623 static void vmcs_writel(unsigned long field, unsigned long value)
624 {
625         u8 error;
626 
627         asm volatile (__ex(ASM_VMX_VMWRITE_RAX_RDX) "; setna %0"
628                        : "=q"(error) : "a"(value), "d"(field) : "cc");
629         if (unlikely(error))
630                 vmwrite_error(field, value);
631 }
632 
633 static void vmcs_write16(unsigned long field, u16 value)
634 {
635         vmcs_writel(field, value);
636 }
637 
638 static void vmcs_write32(unsigned long field, u32 value)
639 {
640         vmcs_writel(field, value);
641 }
642 
643 static void vmcs_write64(unsigned long field, u64 value)
644 {
645         vmcs_writel(field, value);
646 #ifndef CONFIG_X86_64
647         asm volatile ("");
648         vmcs_writel(field+1, value >> 32);
649 #endif
650 }
651 
652 static void vmcs_clear_bits(unsigned long field, u32 mask)
653 {
654         vmcs_writel(field, vmcs_readl(field) & ~mask);
655 }
656 
657 static void vmcs_set_bits(unsigned long field, u32 mask)
658 {
659         vmcs_writel(field, vmcs_readl(field) | mask);
660 }
661 
662 static void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
663 {
664         vmx->segment_cache.bitmask = 0;
665 }
666 
667 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
668                                        unsigned field)
669 {
670         bool ret;
671         u32 mask = 1 << (seg * SEG_FIELD_NR + field);
672 
673         if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
674                 vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
675                 vmx->segment_cache.bitmask = 0;
676         }
677         ret = vmx->segment_cache.bitmask & mask;
678         vmx->segment_cache.bitmask |= mask;
679         return ret;
680 }
681 
682 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
683 {
684         u16 *p = &vmx->segment_cache.seg[seg].selector;
685 
686         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
687                 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
688         return *p;
689 }
690 
691 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
692 {
693         ulong *p = &vmx->segment_cache.seg[seg].base;
694 
695         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
696                 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
697         return *p;
698 }
699 
700 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
701 {
702         u32 *p = &vmx->segment_cache.seg[seg].limit;
703 
704         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
705                 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
706         return *p;
707 }
708 
709 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
710 {
711         u32 *p = &vmx->segment_cache.seg[seg].ar;
712 
713         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
714                 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
715         return *p;
716 }
717 
718 static void update_exception_bitmap(struct kvm_vcpu *vcpu)
719 {
720         u32 eb;
721 
722         eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
723              (1u << NM_VECTOR) | (1u << DB_VECTOR);
724         if ((vcpu->guest_debug &
725              (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
726             (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
727                 eb |= 1u << BP_VECTOR;
728         if (to_vmx(vcpu)->rmode.vm86_active)
729                 eb = ~0;
730         if (enable_ept)
731                 eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
732         if (vcpu->fpu_active)
733                 eb &= ~(1u << NM_VECTOR);
734         vmcs_write32(EXCEPTION_BITMAP, eb);
735 }
736 
737 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
738 {
739         unsigned i;
740         struct msr_autoload *m = &vmx->msr_autoload;
741 
742         if (msr == MSR_EFER && cpu_has_load_ia32_efer) {
743                 vmcs_clear_bits(VM_ENTRY_CONTROLS, VM_ENTRY_LOAD_IA32_EFER);
744                 vmcs_clear_bits(VM_EXIT_CONTROLS, VM_EXIT_LOAD_IA32_EFER);
745                 return;
746         }
747 
748         for (i = 0; i < m->nr; ++i)
749                 if (m->guest[i].index == msr)
750                         break;
751 
752         if (i == m->nr)
753                 return;
754         --m->nr;
755         m->guest[i] = m->guest[m->nr];
756         m->host[i] = m->host[m->nr];
757         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
758         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
759 }
760 
761 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
762                                   u64 guest_val, u64 host_val)
763 {
764         unsigned i;
765         struct msr_autoload *m = &vmx->msr_autoload;
766 
767         if (msr == MSR_EFER && cpu_has_load_ia32_efer) {
768                 vmcs_write64(GUEST_IA32_EFER, guest_val);
769                 vmcs_write64(HOST_IA32_EFER, host_val);
770                 vmcs_set_bits(VM_ENTRY_CONTROLS, VM_ENTRY_LOAD_IA32_EFER);
771                 vmcs_set_bits(VM_EXIT_CONTROLS, VM_EXIT_LOAD_IA32_EFER);
772                 return;
773         }
774 
775         for (i = 0; i < m->nr; ++i)
776                 if (m->guest[i].index == msr)
777                         break;
778 
779         if (i == m->nr) {
780                 ++m->nr;
781                 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
782                 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
783         }
784 
785         m->guest[i].index = msr;
786         m->guest[i].value = guest_val;
787         m->host[i].index = msr;
788         m->host[i].value = host_val;
789 }
790 
791 static void reload_tss(void)
792 {
793         /*
794          * VT restores TR but not its size.  Useless.
795          */
796         struct desc_ptr *gdt = &__get_cpu_var(host_gdt);
797         struct desc_struct *descs;
798 
799         descs = (void *)gdt->address;
800         descs[GDT_ENTRY_TSS].type = 9; /* available TSS */
801         load_TR_desc();
802 }
803 
804 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
805 {
806         u64 guest_efer;
807         u64 ignore_bits;
808 
809         guest_efer = vmx->vcpu.arch.efer;
810 
811         /*
812          * NX is emulated; LMA and LME handled by hardware; SCE meaninless
813          * outside long mode
814          */
815         ignore_bits = EFER_NX | EFER_SCE;
816 #ifdef CONFIG_X86_64
817         ignore_bits |= EFER_LMA | EFER_LME;
818         /* SCE is meaningful only in long mode on Intel */
819         if (guest_efer & EFER_LMA)
820                 ignore_bits &= ~(u64)EFER_SCE;
821 #endif
822         guest_efer &= ~ignore_bits;
823         guest_efer |= host_efer & ignore_bits;
824         vmx->guest_msrs[efer_offset].data = guest_efer;
825         vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
826 
827         clear_atomic_switch_msr(vmx, MSR_EFER);
828         /* On ept, can't emulate nx, and must switch nx atomically */
829         if (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX)) {
830                 guest_efer = vmx->vcpu.arch.efer;
831                 if (!(guest_efer & EFER_LMA))
832                         guest_efer &= ~EFER_LME;
833                 add_atomic_switch_msr(vmx, MSR_EFER, guest_efer, host_efer);
834                 return false;
835         }
836 
837         return true;
838 }
839 
840 static unsigned long segment_base(u16 selector)
841 {
842         struct desc_ptr *gdt = &__get_cpu_var(host_gdt);
843         struct desc_struct *d;
844         unsigned long table_base;
845         unsigned long v;
846 
847         if (!(selector & ~3))
848                 return 0;
849 
850         table_base = gdt->address;
851 
852         if (selector & 4) {           /* from ldt */
853                 u16 ldt_selector = kvm_read_ldt();
854 
855                 if (!(ldt_selector & ~3))
856                         return 0;
857 
858                 table_base = segment_base(ldt_selector);
859         }
860         d = (struct desc_struct *)(table_base + (selector & ~7));
861         v = get_desc_base(d);
862 #ifdef CONFIG_X86_64
863        if (d->s == 0 && (d->type == 2 || d->type == 9 || d->type == 11))
864                v |= ((unsigned long)((struct ldttss_desc64 *)d)->base3) << 32;
865 #endif
866         return v;
867 }
868 
869 static inline unsigned long kvm_read_tr_base(void)
870 {
871         u16 tr;
872         asm("str %0" : "=g"(tr));
873         return segment_base(tr);
874 }
875 
876 static void vmx_save_host_state(struct kvm_vcpu *vcpu)
877 {
878         struct vcpu_vmx *vmx = to_vmx(vcpu);
879         int i;
880 
881         if (vmx->host_state.loaded)
882                 return;
883 
884         vmx->host_state.loaded = 1;
885         /*
886          * Set host fs and gs selectors.  Unfortunately, 22.2.3 does not
887          * allow segment selectors with cpl > 0 or ti == 1.
888          */
889         vmx->host_state.ldt_sel = kvm_read_ldt();
890         vmx->host_state.gs_ldt_reload_needed = vmx->host_state.ldt_sel;
891         savesegment(fs, vmx->host_state.fs_sel);
892         if (!(vmx->host_state.fs_sel & 7)) {
893                 vmcs_write16(HOST_FS_SELECTOR, vmx->host_state.fs_sel);
894                 vmx->host_state.fs_reload_needed = 0;
895         } else {
896                 vmcs_write16(HOST_FS_SELECTOR, 0);
897                 vmx->host_state.fs_reload_needed = 1;
898         }
899         savesegment(gs, vmx->host_state.gs_sel);
900         if (!(vmx->host_state.gs_sel & 7))
901                 vmcs_write16(HOST_GS_SELECTOR, vmx->host_state.gs_sel);
902         else {
903                 vmcs_write16(HOST_GS_SELECTOR, 0);
904                 vmx->host_state.gs_ldt_reload_needed = 1;
905         }
906 
907 #ifdef CONFIG_X86_64
908         vmcs_writel(HOST_FS_BASE, read_msr(MSR_FS_BASE));
909         vmcs_writel(HOST_GS_BASE, read_msr(MSR_GS_BASE));
910 #else
911         vmcs_writel(HOST_FS_BASE, segment_base(vmx->host_state.fs_sel));
912         vmcs_writel(HOST_GS_BASE, segment_base(vmx->host_state.gs_sel));
913 #endif
914 
915 #ifdef CONFIG_X86_64
916         rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
917         if (is_long_mode(&vmx->vcpu))
918                 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
919 #endif
920         for (i = 0; i < vmx->save_nmsrs; ++i)
921                 kvm_set_shared_msr(vmx->guest_msrs[i].index,
922                                    vmx->guest_msrs[i].data,
923                                    vmx->guest_msrs[i].mask);
924 }
925 
926 static void __vmx_load_host_state(struct vcpu_vmx *vmx)
927 {
928         if (!vmx->host_state.loaded)
929                 return;
930 
931         ++vmx->vcpu.stat.host_state_reload;
932         vmx->host_state.loaded = 0;
933 #ifdef CONFIG_X86_64
934         if (is_long_mode(&vmx->vcpu))
935                 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
936 #endif
937         if (vmx->host_state.gs_ldt_reload_needed) {
938                 kvm_load_ldt(vmx->host_state.ldt_sel);
939 #ifdef CONFIG_X86_64
940                 load_gs_index(vmx->host_state.gs_sel);
941 #else
942                 loadsegment(gs, vmx->host_state.gs_sel);
943 #endif
944         }
945         if (vmx->host_state.fs_reload_needed)
946                 loadsegment(fs, vmx->host_state.fs_sel);
947         reload_tss();
948 #ifdef CONFIG_X86_64
949         wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
950 #endif
951         if (__thread_has_fpu(current))
952                 clts();
953         load_gdt(&__get_cpu_var(host_gdt));
954 }
955 
956 static void vmx_load_host_state(struct vcpu_vmx *vmx)
957 {
958         preempt_disable();
959         __vmx_load_host_state(vmx);
960         preempt_enable();
961 }
962 
963 /*
964  * Switches to specified vcpu, until a matching vcpu_put(), but assumes
965  * vcpu mutex is already taken.
966  */
967 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
968 {
969         struct vcpu_vmx *vmx = to_vmx(vcpu);
970         u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
971 
972         if (!vmm_exclusive)
973                 kvm_cpu_vmxon(phys_addr);
974         else if (vcpu->cpu != cpu)
975                 vcpu_clear(vmx);
976 
977         if (per_cpu(current_vmcs, cpu) != vmx->vmcs) {
978                 per_cpu(current_vmcs, cpu) = vmx->vmcs;
979                 vmcs_load(vmx->vmcs);
980         }
981 
982         if (vcpu->cpu != cpu) {
983                 struct desc_ptr *gdt = &__get_cpu_var(host_gdt);
984                 unsigned long sysenter_esp;
985 
986                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
987                 local_irq_disable();
988                 list_add(&vmx->local_vcpus_link,
989                          &per_cpu(vcpus_on_cpu, cpu));
990                 local_irq_enable();
991 
992                 /*
993                  * Linux uses per-cpu TSS and GDT, so set these when switching
994                  * processors.
995                  */
996                 vmcs_writel(HOST_TR_BASE, kvm_read_tr_base()); /* 22.2.4 */
997                 vmcs_writel(HOST_GDTR_BASE, gdt->address);   /* 22.2.4 */
998 
999                 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
1000                 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
1001         }
1002 }
1003 
1004 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1005 {
1006         __vmx_load_host_state(to_vmx(vcpu));
1007         if (!vmm_exclusive) {
1008                 __vcpu_clear(to_vmx(vcpu));
1009                 kvm_cpu_vmxoff();
1010         }
1011 }
1012 
1013 static void vmx_fpu_activate(struct kvm_vcpu *vcpu)
1014 {
1015         ulong cr0;
1016 
1017         if (vcpu->fpu_active)
1018                 return;
1019         vcpu->fpu_active = 1;
1020         cr0 = vmcs_readl(GUEST_CR0);
1021         cr0 &= ~(X86_CR0_TS | X86_CR0_MP);
1022         cr0 |= kvm_read_cr0_bits(vcpu, X86_CR0_TS | X86_CR0_MP);
1023         vmcs_writel(GUEST_CR0, cr0);
1024         update_exception_bitmap(vcpu);
1025         vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
1026         vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
1027 }
1028 
1029 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
1030 
1031 static void vmx_fpu_deactivate(struct kvm_vcpu *vcpu)
1032 {
1033         vmx_decache_cr0_guest_bits(vcpu);
1034         vmcs_set_bits(GUEST_CR0, X86_CR0_TS | X86_CR0_MP);
1035         update_exception_bitmap(vcpu);
1036         vcpu->arch.cr0_guest_owned_bits = 0;
1037         vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
1038         vmcs_writel(CR0_READ_SHADOW, vcpu->arch.cr0);
1039 }
1040 
1041 static unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
1042 {
1043         unsigned long rflags, save_rflags;
1044 
1045         if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
1046                 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
1047                 rflags = vmcs_readl(GUEST_RFLAGS);
1048                 if (to_vmx(vcpu)->rmode.vm86_active) {
1049                         rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1050                         save_rflags = to_vmx(vcpu)->rmode.save_rflags;
1051                         rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1052                 }
1053                 to_vmx(vcpu)->rflags = rflags;
1054         }
1055         return to_vmx(vcpu)->rflags;
1056 }
1057 
1058 static void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1059 {
1060         __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
1061         __clear_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail);
1062         to_vmx(vcpu)->rflags = rflags;
1063         if (to_vmx(vcpu)->rmode.vm86_active) {
1064                 to_vmx(vcpu)->rmode.save_rflags = rflags;
1065                 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1066         }
1067         vmcs_writel(GUEST_RFLAGS, rflags);
1068 }
1069 
1070 static u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1071 {
1072         u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1073         int ret = 0;
1074 
1075         if (interruptibility & GUEST_INTR_STATE_STI)
1076                 ret |= KVM_X86_SHADOW_INT_STI;
1077         if (interruptibility & GUEST_INTR_STATE_MOV_SS)
1078                 ret |= KVM_X86_SHADOW_INT_MOV_SS;
1079 
1080         return ret & mask;
1081 }
1082 
1083 static void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1084 {
1085         u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1086         u32 interruptibility = interruptibility_old;
1087 
1088         interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1089 
1090         if (mask & KVM_X86_SHADOW_INT_MOV_SS)
1091                 interruptibility |= GUEST_INTR_STATE_MOV_SS;
1092         else if (mask & KVM_X86_SHADOW_INT_STI)
1093                 interruptibility |= GUEST_INTR_STATE_STI;
1094 
1095         if ((interruptibility != interruptibility_old))
1096                 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1097 }
1098 
1099 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
1100 {
1101         unsigned long rip;
1102 
1103         rip = kvm_rip_read(vcpu);
1104         rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1105         kvm_rip_write(vcpu, rip);
1106 
1107         /* skipping an emulated instruction also counts */
1108         vmx_set_interrupt_shadow(vcpu, 0);
1109 }
1110 
1111 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
1112 {
1113         /* Ensure that we clear the HLT state in the VMCS.  We don't need to
1114          * explicitly skip the instruction because if the HLT state is set, then
1115          * the instruction is already executing and RIP has already been
1116          * advanced. */
1117         if (!yield_on_hlt &&
1118             vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
1119                 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
1120 }
1121 
1122 static void vmx_queue_exception(struct kvm_vcpu *vcpu, unsigned nr,
1123                                 bool has_error_code, u32 error_code,
1124                                 bool reinject)
1125 {
1126         struct vcpu_vmx *vmx = to_vmx(vcpu);
1127         u32 intr_info = nr | INTR_INFO_VALID_MASK;
1128 
1129         if (has_error_code) {
1130                 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
1131                 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
1132         }
1133 
1134         if (vmx->rmode.vm86_active) {
1135                 int inc_eip = 0;
1136                 if (kvm_exception_is_soft(nr))
1137                         inc_eip = vcpu->arch.event_exit_inst_len;
1138                 if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
1139                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
1140                 return;
1141         }
1142 
1143         if (kvm_exception_is_soft(nr)) {
1144                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
1145                              vmx->vcpu.arch.event_exit_inst_len);
1146                 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
1147         } else
1148                 intr_info |= INTR_TYPE_HARD_EXCEPTION;
1149 
1150         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
1151         vmx_clear_hlt(vcpu);
1152 }
1153 
1154 static bool vmx_rdtscp_supported(void)
1155 {
1156         return cpu_has_vmx_rdtscp();
1157 }
1158 
1159 /*
1160  * Swap MSR entry in host/guest MSR entry array.
1161  */
1162 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
1163 {
1164         struct shared_msr_entry tmp;
1165 
1166         tmp = vmx->guest_msrs[to];
1167         vmx->guest_msrs[to] = vmx->guest_msrs[from];
1168         vmx->guest_msrs[from] = tmp;
1169 }
1170 
1171 /*
1172  * Set up the vmcs to automatically save and restore system
1173  * msrs.  Don't touch the 64-bit msrs if the guest is in legacy
1174  * mode, as fiddling with msrs is very expensive.
1175  */
1176 static void setup_msrs(struct vcpu_vmx *vmx)
1177 {
1178         int save_nmsrs, index;
1179         unsigned long *msr_bitmap;
1180 
1181         vmx_load_host_state(vmx);
1182         save_nmsrs = 0;
1183 #ifdef CONFIG_X86_64
1184         if (is_long_mode(&vmx->vcpu)) {
1185                 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
1186                 if (index >= 0)
1187                         move_msr_up(vmx, index, save_nmsrs++);
1188                 index = __find_msr_index(vmx, MSR_LSTAR);
1189                 if (index >= 0)
1190                         move_msr_up(vmx, index, save_nmsrs++);
1191                 index = __find_msr_index(vmx, MSR_CSTAR);
1192                 if (index >= 0)
1193                         move_msr_up(vmx, index, save_nmsrs++);
1194                 index = __find_msr_index(vmx, MSR_TSC_AUX);
1195                 if (index >= 0 && vmx->rdtscp_enabled)
1196                         move_msr_up(vmx, index, save_nmsrs++);
1197                 /*
1198                  * MSR_STAR is only needed on long mode guests, and only
1199                  * if efer.sce is enabled.
1200                  */
1201                 index = __find_msr_index(vmx, MSR_STAR);
1202                 if ((index >= 0) && (vmx->vcpu.arch.efer & EFER_SCE))
1203                         move_msr_up(vmx, index, save_nmsrs++);
1204         }
1205 #endif
1206         index = __find_msr_index(vmx, MSR_EFER);
1207         if (index >= 0 && update_transition_efer(vmx, index))
1208                 move_msr_up(vmx, index, save_nmsrs++);
1209 
1210         vmx->save_nmsrs = save_nmsrs;
1211 
1212         if (cpu_has_vmx_msr_bitmap()) {
1213                 if (is_long_mode(&vmx->vcpu))
1214                         msr_bitmap = vmx_msr_bitmap_longmode;
1215                 else
1216                         msr_bitmap = vmx_msr_bitmap_legacy;
1217 
1218                 vmcs_write64(MSR_BITMAP, __pa(msr_bitmap));
1219         }
1220 }
1221 
1222 /*
1223  * reads and returns guest's timestamp counter "register"
1224  * guest_tsc = host_tsc + tsc_offset    -- 21.3
1225  */
1226 static u64 guest_read_tsc(void)
1227 {
1228         u64 host_tsc, tsc_offset;
1229 
1230         rdtscll(host_tsc);
1231         tsc_offset = vmcs_read64(TSC_OFFSET);
1232         return host_tsc + tsc_offset;
1233 }
1234 
1235 /*
1236  * Empty call-back. Needs to be implemented when VMX enables the SET_TSC_KHZ
1237  * ioctl. In this case the call-back should update internal vmx state to make
1238  * the changes effective.
1239  */
1240 static void vmx_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
1241 {
1242         /* Nothing to do here */
1243 }
1244 
1245 /*
1246  * writes 'offset' into guest's timestamp counter offset register
1247  */
1248 static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1249 {
1250         vmcs_write64(TSC_OFFSET, offset);
1251 }
1252 
1253 static void vmx_adjust_tsc_offset(struct kvm_vcpu *vcpu, s64 adjustment)
1254 {
1255         u64 offset = vmcs_read64(TSC_OFFSET);
1256         vmcs_write64(TSC_OFFSET, offset + adjustment);
1257 }
1258 
1259 static u64 vmx_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
1260 {
1261         return target_tsc - native_read_tsc();
1262 }
1263 
1264 /*
1265  * Reads an msr value (of 'msr_index') into 'pdata'.
1266  * Returns 0 on success, non-0 otherwise.
1267  * Assumes vcpu_load() was already called.
1268  */
1269 static int vmx_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
1270 {
1271         u64 data;
1272         struct shared_msr_entry *msr;
1273 
1274         if (!pdata) {
1275                 printk(KERN_ERR "BUG: get_msr called with NULL pdata\n");
1276                 return -EINVAL;
1277         }
1278 
1279         switch (msr_index) {
1280 #ifdef CONFIG_X86_64
1281         case MSR_FS_BASE:
1282                 data = vmcs_readl(GUEST_FS_BASE);
1283                 break;
1284         case MSR_GS_BASE:
1285                 data = vmcs_readl(GUEST_GS_BASE);
1286                 break;
1287         case MSR_KERNEL_GS_BASE:
1288                 vmx_load_host_state(to_vmx(vcpu));
1289                 data = to_vmx(vcpu)->msr_guest_kernel_gs_base;
1290                 break;
1291 #endif
1292         case MSR_EFER:
1293                 return kvm_get_msr_common(vcpu, msr_index, pdata);
1294         case MSR_IA32_TSC:
1295                 data = guest_read_tsc();
1296                 break;
1297         case MSR_IA32_SYSENTER_CS:
1298                 data = vmcs_read32(GUEST_SYSENTER_CS);
1299                 break;
1300         case MSR_IA32_SYSENTER_EIP:
1301                 data = vmcs_readl(GUEST_SYSENTER_EIP);
1302                 break;
1303         case MSR_IA32_SYSENTER_ESP:
1304                 data = vmcs_readl(GUEST_SYSENTER_ESP);
1305                 break;
1306         case MSR_TSC_AUX:
1307                 if (!to_vmx(vcpu)->rdtscp_enabled)
1308                         return 1;
1309                 /* Otherwise falls through */
1310         default:
1311                 vmx_load_host_state(to_vmx(vcpu));
1312                 msr = find_msr_entry(to_vmx(vcpu), msr_index);
1313                 if (msr) {
1314                         vmx_load_host_state(to_vmx(vcpu));
1315                         data = msr->data;
1316                         break;
1317                 }
1318                 return kvm_get_msr_common(vcpu, msr_index, pdata);
1319         }
1320 
1321         *pdata = data;
1322         return 0;
1323 }
1324 
1325 /*
1326  * Writes msr value into into the appropriate "register".
1327  * Returns 0 on success, non-0 otherwise.
1328  * Assumes vcpu_load() was already called.
1329  */
1330 static int vmx_set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
1331 {
1332         struct vcpu_vmx *vmx = to_vmx(vcpu);
1333         struct shared_msr_entry *msr;
1334         int ret = 0;
1335 
1336         switch (msr_index) {
1337         case MSR_EFER:
1338                 vmx_load_host_state(vmx);
1339                 ret = kvm_set_msr_common(vcpu, msr_index, data);
1340                 break;
1341 #ifdef CONFIG_X86_64
1342         case MSR_FS_BASE:
1343                 vmx_segment_cache_clear(vmx);
1344                 vmcs_writel(GUEST_FS_BASE, data);
1345                 break;
1346         case MSR_GS_BASE:
1347                 vmx_segment_cache_clear(vmx);
1348                 vmcs_writel(GUEST_GS_BASE, data);
1349                 break;
1350         case MSR_KERNEL_GS_BASE:
1351                 vmx_load_host_state(vmx);
1352                 vmx->msr_guest_kernel_gs_base = data;
1353                 break;
1354 #endif
1355         case MSR_IA32_SYSENTER_CS:
1356                 vmcs_write32(GUEST_SYSENTER_CS, data);
1357                 break;
1358         case MSR_IA32_SYSENTER_EIP:
1359                 vmcs_writel(GUEST_SYSENTER_EIP, data);
1360                 break;
1361         case MSR_IA32_SYSENTER_ESP:
1362                 vmcs_writel(GUEST_SYSENTER_ESP, data);
1363                 break;
1364         case MSR_IA32_TSC:
1365                 kvm_write_tsc(vcpu, data);
1366                 break;
1367         case MSR_IA32_CR_PAT:
1368                 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
1369                         vmcs_write64(GUEST_IA32_PAT, data);
1370                         vcpu->arch.pat = data;
1371                         break;
1372                 }
1373                 ret = kvm_set_msr_common(vcpu, msr_index, data);
1374                 break;
1375         case MSR_TSC_AUX:
1376                 if (!vmx->rdtscp_enabled)
1377                         return 1;
1378                 /* Check reserved bit, higher 32 bits should be zero */
1379                 if ((data >> 32) != 0)
1380                         return 1;
1381                 /* Otherwise falls through */
1382         default:
1383                 msr = find_msr_entry(vmx, msr_index);
1384                 if (msr) {
1385                         vmx_load_host_state(vmx);
1386                         msr->data = data;
1387                         break;
1388                 }
1389                 ret = kvm_set_msr_common(vcpu, msr_index, data);
1390         }
1391 
1392         return ret;
1393 }
1394 
1395 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
1396 {
1397         __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
1398         switch (reg) {
1399         case VCPU_REGS_RSP:
1400                 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
1401                 break;
1402         case VCPU_REGS_RIP:
1403                 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
1404                 break;
1405         case VCPU_EXREG_PDPTR:
1406                 if (enable_ept)
1407                         ept_save_pdptrs(vcpu);
1408                 break;
1409         default:
1410                 break;
1411         }
1412 }
1413 
1414 static void set_guest_debug(struct kvm_vcpu *vcpu, struct kvm_guest_debug *dbg)
1415 {
1416         if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
1417                 vmcs_writel(GUEST_DR7, dbg->arch.debugreg[7]);
1418         else
1419                 vmcs_writel(GUEST_DR7, vcpu->arch.dr7);
1420 
1421         update_exception_bitmap(vcpu);
1422 }
1423 
1424 static __init int cpu_has_kvm_support(void)
1425 {
1426         return cpu_has_vmx();
1427 }
1428 
1429 static __init int vmx_disabled_by_bios(void)
1430 {
1431         u64 msr;
1432 
1433         rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
1434         if (msr & FEATURE_CONTROL_LOCKED) {
1435                 /* launched w/ TXT and VMX disabled */
1436                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
1437                         && tboot_enabled())
1438                         return 1;
1439                 /* launched w/o TXT and VMX only enabled w/ TXT */
1440                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
1441                         && (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
1442                         && !tboot_enabled()) {
1443                         printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
1444                                 "activate TXT before enabling KVM\n");
1445                         return 1;
1446                 }
1447                 /* launched w/o TXT and VMX disabled */
1448                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
1449                         && !tboot_enabled())
1450                         return 1;
1451         }
1452 
1453         return 0;
1454 }
1455 
1456 static void kvm_cpu_vmxon(u64 addr)
1457 {
1458         asm volatile (ASM_VMX_VMXON_RAX
1459                         : : "a"(&addr), "m"(addr)
1460                         : "memory", "cc");
1461 }
1462 
1463 static int hardware_enable(void *garbage)
1464 {
1465         int cpu = raw_smp_processor_id();
1466         u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
1467         u64 old, test_bits;
1468 
1469         if (read_cr4() & X86_CR4_VMXE)
1470                 return -EBUSY;
1471 
1472         INIT_LIST_HEAD(&per_cpu(vcpus_on_cpu, cpu));
1473         rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
1474 
1475         test_bits = FEATURE_CONTROL_LOCKED;
1476         test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
1477         if (tboot_enabled())
1478                 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
1479 
1480         if ((old & test_bits) != test_bits) {
1481                 /* enable and lock */
1482                 wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
1483         }
1484         write_cr4(read_cr4() | X86_CR4_VMXE); /* FIXME: not cpu hotplug safe */
1485 
1486         if (vmm_exclusive) {
1487                 kvm_cpu_vmxon(phys_addr);
1488                 ept_sync_global();
1489         }
1490 
1491         store_gdt(&__get_cpu_var(host_gdt));
1492 
1493         return 0;
1494 }
1495 
1496 static void vmclear_local_vcpus(void)
1497 {
1498         int cpu = raw_smp_processor_id();
1499         struct vcpu_vmx *vmx, *n;
1500 
1501         list_for_each_entry_safe(vmx, n, &per_cpu(vcpus_on_cpu, cpu),
1502                                  local_vcpus_link)
1503                 __vcpu_clear(vmx);
1504 }
1505 
1506 
1507 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
1508  * tricks.
1509  */
1510 static void kvm_cpu_vmxoff(void)
1511 {
1512         asm volatile (__ex(ASM_VMX_VMXOFF) : : : "cc");
1513 }
1514 
1515 static void hardware_disable(void *garbage)
1516 {
1517         if (vmm_exclusive) {
1518                 vmclear_local_vcpus();
1519                 kvm_cpu_vmxoff();
1520         }
1521         write_cr4(read_cr4() & ~X86_CR4_VMXE);
1522 }
1523 
1524 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
1525                                       u32 msr, u32 *result)
1526 {
1527         u32 vmx_msr_low, vmx_msr_high;
1528         u32 ctl = ctl_min | ctl_opt;
1529 
1530         rdmsr(msr, vmx_msr_low, vmx_msr_high);
1531 
1532         ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
1533         ctl |= vmx_msr_low;  /* bit == 1 in low word  ==> must be one  */
1534 
1535         /* Ensure minimum (required) set of control bits are supported. */
1536         if (ctl_min & ~ctl)
1537                 return -EIO;
1538 
1539         *result = ctl;
1540         return 0;
1541 }
1542 
1543 static __init bool allow_1_setting(u32 msr, u32 ctl)
1544 {
1545         u32 vmx_msr_low, vmx_msr_high;
1546 
1547         rdmsr(msr, vmx_msr_low, vmx_msr_high);
1548         return vmx_msr_high & ctl;
1549 }
1550 
1551 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
1552 {
1553         u32 vmx_msr_low, vmx_msr_high;
1554         u32 min, opt, min2, opt2;
1555         u32 _pin_based_exec_control = 0;
1556         u32 _cpu_based_exec_control = 0;
1557         u32 _cpu_based_2nd_exec_control = 0;
1558         u32 _vmexit_control = 0;
1559         u32 _vmentry_control = 0;
1560 
1561         min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
1562         opt = PIN_BASED_VIRTUAL_NMIS;
1563         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
1564                                 &_pin_based_exec_control) < 0)
1565                 return -EIO;
1566 
1567         min =
1568 #ifdef CONFIG_X86_64
1569               CPU_BASED_CR8_LOAD_EXITING |
1570               CPU_BASED_CR8_STORE_EXITING |
1571 #endif
1572               CPU_BASED_CR3_LOAD_EXITING |
1573               CPU_BASED_CR3_STORE_EXITING |
1574               CPU_BASED_USE_IO_BITMAPS |
1575               CPU_BASED_MOV_DR_EXITING |
1576               CPU_BASED_USE_TSC_OFFSETING |
1577               CPU_BASED_MWAIT_EXITING |
1578               CPU_BASED_MONITOR_EXITING |
1579               CPU_BASED_INVLPG_EXITING;
1580 
1581         if (yield_on_hlt)
1582                 min |= CPU_BASED_HLT_EXITING;
1583 
1584         opt = CPU_BASED_TPR_SHADOW |
1585               CPU_BASED_USE_MSR_BITMAPS |
1586               CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
1587         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
1588                                 &_cpu_based_exec_control) < 0)
1589                 return -EIO;
1590 #ifdef CONFIG_X86_64
1591         if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
1592                 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
1593                                            ~CPU_BASED_CR8_STORE_EXITING;
1594 #endif
1595         if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
1596                 min2 = 0;
1597                 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
1598                         SECONDARY_EXEC_WBINVD_EXITING |
1599                         SECONDARY_EXEC_ENABLE_VPID |
1600                         SECONDARY_EXEC_ENABLE_EPT |
1601                         SECONDARY_EXEC_UNRESTRICTED_GUEST |
1602                         SECONDARY_EXEC_PAUSE_LOOP_EXITING |
1603                         SECONDARY_EXEC_RDTSCP;
1604                 if (adjust_vmx_controls(min2, opt2,
1605                                         MSR_IA32_VMX_PROCBASED_CTLS2,
1606                                         &_cpu_based_2nd_exec_control) < 0)
1607                         return -EIO;
1608         }
1609 #ifndef CONFIG_X86_64
1610         if (!(_cpu_based_2nd_exec_control &
1611                                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
1612                 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
1613 #endif
1614         if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
1615                 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
1616                    enabled */
1617                 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
1618                                              CPU_BASED_CR3_STORE_EXITING |
1619                                              CPU_BASED_INVLPG_EXITING);
1620                 rdmsr(MSR_IA32_VMX_EPT_VPID_CAP,
1621                       vmx_capability.ept, vmx_capability.vpid);
1622         }
1623 
1624         min = 0;
1625 #ifdef CONFIG_X86_64
1626         min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
1627 #endif
1628         opt = VM_EXIT_SAVE_IA32_PAT | VM_EXIT_LOAD_IA32_PAT;
1629         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
1630                                 &_vmexit_control) < 0)
1631                 return -EIO;
1632 
1633         min = 0;
1634         opt = VM_ENTRY_LOAD_IA32_PAT;
1635         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
1636                                 &_vmentry_control) < 0)
1637                 return -EIO;
1638 
1639         rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
1640 
1641         /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
1642         if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
1643                 return -EIO;
1644 
1645 #ifdef CONFIG_X86_64
1646         /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
1647         if (vmx_msr_high & (1u<<16))
1648                 return -EIO;
1649 #endif
1650 
1651         /* Require Write-Back (WB) memory type for VMCS accesses. */
1652         if (((vmx_msr_high >> 18) & 15) != 6)
1653                 return -EIO;
1654 
1655         vmcs_conf->size = vmx_msr_high & 0x1fff;
1656         vmcs_conf->order = get_order(vmcs_config.size);
1657         vmcs_conf->revision_id = vmx_msr_low;
1658 
1659         vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
1660         vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
1661         vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
1662         vmcs_conf->vmexit_ctrl         = _vmexit_control;
1663         vmcs_conf->vmentry_ctrl        = _vmentry_control;
1664 
1665         cpu_has_load_ia32_efer =
1666                 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
1667                                 VM_ENTRY_LOAD_IA32_EFER)
1668                 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
1669                                    VM_EXIT_LOAD_IA32_EFER);
1670 
1671         return 0;
1672 }
1673 
1674 static struct vmcs *alloc_vmcs_cpu(int cpu)
1675 {
1676         int node = cpu_to_node(cpu);
1677         struct page *pages;
1678         struct vmcs *vmcs;
1679 
1680         pages = alloc_pages_exact_node(node, GFP_KERNEL, vmcs_config.order);
1681         if (!pages)
1682                 return NULL;
1683         vmcs = page_address(pages);
1684         memset(vmcs, 0, vmcs_config.size);
1685         vmcs->revision_id = vmcs_config.revision_id; /* vmcs revision id */
1686         return vmcs;
1687 }
1688 
1689 static struct vmcs *alloc_vmcs(void)
1690 {
1691         return alloc_vmcs_cpu(raw_smp_processor_id());
1692 }
1693 
1694 static void free_vmcs(struct vmcs *vmcs)
1695 {
1696         free_pages((unsigned long)vmcs, vmcs_config.order);
1697 }
1698 
1699 static void free_kvm_area(void)
1700 {
1701         int cpu;
1702 
1703         for_each_possible_cpu(cpu) {
1704                 free_vmcs(per_cpu(vmxarea, cpu));
1705                 per_cpu(vmxarea, cpu) = NULL;
1706         }
1707 }
1708 
1709 static __init int alloc_kvm_area(void)
1710 {
1711         int cpu;
1712 
1713         for_each_possible_cpu(cpu) {
1714                 struct vmcs *vmcs;
1715 
1716                 vmcs = alloc_vmcs_cpu(cpu);
1717                 if (!vmcs) {
1718                         free_kvm_area();
1719                         return -ENOMEM;
1720                 }
1721 
1722                 per_cpu(vmxarea, cpu) = vmcs;
1723         }
1724         return 0;
1725 }
1726 
1727 static __init int hardware_setup(void)
1728 {
1729         if (setup_vmcs_config(&vmcs_config) < 0)
1730                 return -EIO;
1731 
1732         if (boot_cpu_has(X86_FEATURE_NX))
1733                 kvm_enable_efer_bits(EFER_NX);
1734 
1735         if (!cpu_has_vmx_vpid())
1736                 enable_vpid = 0;
1737 
1738         if (!cpu_has_vmx_ept() ||
1739             !cpu_has_vmx_ept_4levels()) {
1740                 enable_ept = 0;
1741                 enable_unrestricted_guest = 0;
1742         }
1743 
1744         if (!cpu_has_vmx_unrestricted_guest())
1745                 enable_unrestricted_guest = 0;
1746 
1747         if (!cpu_has_vmx_flexpriority())
1748                 flexpriority_enabled = 0;
1749 
1750         if (!cpu_has_vmx_tpr_shadow())
1751                 kvm_x86_ops->update_cr8_intercept = NULL;
1752 
1753         if (enable_ept && !cpu_has_vmx_ept_2m_page())
1754                 kvm_disable_largepages();
1755 
1756         if (!cpu_has_vmx_ple())
1757                 ple_gap = 0;
1758 
1759         return alloc_kvm_area();
1760 }
1761 
1762 static __exit void hardware_unsetup(void)
1763 {
1764         free_kvm_area();
1765 }
1766 
1767 static void fix_pmode_dataseg(int seg, struct kvm_save_segment *save)
1768 {
1769         struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
1770 
1771         if (vmcs_readl(sf->base) == save->base && (save->base & AR_S_MASK)) {
1772                 vmcs_write16(sf->selector, save->selector);
1773                 vmcs_writel(sf->base, save->base);
1774                 vmcs_write32(sf->limit, save->limit);
1775                 vmcs_write32(sf->ar_bytes, save->ar);
1776         } else {
1777                 u32 dpl = (vmcs_read16(sf->selector) & SELECTOR_RPL_MASK)
1778                         << AR_DPL_SHIFT;
1779                 vmcs_write32(sf->ar_bytes, 0x93 | dpl);
1780         }
1781 }
1782 
1783 static void enter_pmode(struct kvm_vcpu *vcpu)
1784 {
1785         unsigned long flags;
1786         struct vcpu_vmx *vmx = to_vmx(vcpu);
1787 
1788         vmx->emulation_required = 1;
1789         vmx->rmode.vm86_active = 0;
1790 
1791         vmx_segment_cache_clear(vmx);
1792 
1793         vmcs_write16(GUEST_TR_SELECTOR, vmx->rmode.tr.selector);
1794         vmcs_writel(GUEST_TR_BASE, vmx->rmode.tr.base);
1795         vmcs_write32(GUEST_TR_LIMIT, vmx->rmode.tr.limit);
1796         vmcs_write32(GUEST_TR_AR_BYTES, vmx->rmode.tr.ar);
1797 
1798         flags = vmcs_readl(GUEST_RFLAGS);
1799         flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1800         flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1801         vmcs_writel(GUEST_RFLAGS, flags);
1802 
1803         vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
1804                         (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
1805 
1806         update_exception_bitmap(vcpu);
1807 
1808         if (emulate_invalid_guest_state)
1809                 return;
1810 
1811         fix_pmode_dataseg(VCPU_SREG_ES, &vmx->rmode.es);
1812         fix_pmode_dataseg(VCPU_SREG_DS, &vmx->rmode.ds);
1813         fix_pmode_dataseg(VCPU_SREG_GS, &vmx->rmode.gs);
1814         fix_pmode_dataseg(VCPU_SREG_FS, &vmx->rmode.fs);
1815 
1816         vmx_segment_cache_clear(vmx);
1817 
1818         vmcs_write16(GUEST_SS_SELECTOR, 0);
1819         vmcs_write32(GUEST_SS_AR_BYTES, 0x93);
1820 
1821         vmcs_write16(GUEST_CS_SELECTOR,
1822                      vmcs_read16(GUEST_CS_SELECTOR) & ~SELECTOR_RPL_MASK);
1823         vmcs_write32(GUEST_CS_AR_BYTES, 0x9b);
1824 }
1825 
1826 static gva_t rmode_tss_base(struct kvm *kvm)
1827 {
1828         if (!kvm->arch.tss_addr) {
1829                 struct kvm_memslots *slots;
1830                 gfn_t base_gfn;
1831 
1832                 slots = kvm_memslots(kvm);
1833                 base_gfn = slots->memslots[0].base_gfn +
1834                                  kvm->memslots->memslots[0].npages - 3;
1835                 return base_gfn << PAGE_SHIFT;
1836         }
1837         return kvm->arch.tss_addr;
1838 }
1839 
1840 static void fix_rmode_seg(int seg, struct kvm_save_segment *save)
1841 {
1842         struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
1843 
1844         save->selector = vmcs_read16(sf->selector);
1845         save->base = vmcs_readl(sf->base);
1846         save->limit = vmcs_read32(sf->limit);
1847         save->ar = vmcs_read32(sf->ar_bytes);
1848         vmcs_write16(sf->selector, save->base >> 4);
1849         vmcs_write32(sf->base, save->base & 0xffff0);
1850         vmcs_write32(sf->limit, 0xffff);
1851         vmcs_write32(sf->ar_bytes, 0xf3);
1852         if (save->base & 0xf)
1853                 printk_once(KERN_WARNING "kvm: segment base is not paragraph"
1854                             " aligned when entering protected mode (seg=%d)",
1855                             seg);
1856 }
1857 
1858 static void enter_rmode(struct kvm_vcpu *vcpu)
1859 {
1860         unsigned long flags;
1861         struct vcpu_vmx *vmx = to_vmx(vcpu);
1862 
1863         if (enable_unrestricted_guest)
1864                 return;
1865 
1866         vmx->emulation_required = 1;
1867         vmx->rmode.vm86_active = 1;
1868 
1869         /*
1870          * Very old userspace does not call KVM_SET_TSS_ADDR before entering
1871          * vcpu. Call it here with phys address pointing 16M below 4G.
1872          */
1873         if (!vcpu->kvm->arch.tss_addr) {
1874                 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
1875                              "called before entering vcpu\n");
1876                 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
1877                 vmx_set_tss_addr(vcpu->kvm, 0xfeffd000);
1878                 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
1879         }
1880 
1881         vmx_segment_cache_clear(vmx);
1882 
1883         vmx->rmode.tr.selector = vmcs_read16(GUEST_TR_SELECTOR);
1884         vmx->rmode.tr.base = vmcs_readl(GUEST_TR_BASE);
1885         vmcs_writel(GUEST_TR_BASE, rmode_tss_base(vcpu->kvm));
1886 
1887         vmx->rmode.tr.limit = vmcs_read32(GUEST_TR_LIMIT);
1888         vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
1889 
1890         vmx->rmode.tr.ar = vmcs_read32(GUEST_TR_AR_BYTES);
1891         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
1892 
1893         flags = vmcs_readl(GUEST_RFLAGS);
1894         vmx->rmode.save_rflags = flags;
1895 
1896         flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1897 
1898         vmcs_writel(GUEST_RFLAGS, flags);
1899         vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
1900         update_exception_bitmap(vcpu);
1901 
1902         if (emulate_invalid_guest_state)
1903                 goto continue_rmode;
1904 
1905         vmcs_write16(GUEST_SS_SELECTOR, vmcs_readl(GUEST_SS_BASE) >> 4);
1906         vmcs_write32(GUEST_SS_LIMIT, 0xffff);
1907         vmcs_write32(GUEST_SS_AR_BYTES, 0xf3);
1908 
1909         vmcs_write32(GUEST_CS_AR_BYTES, 0xf3);
1910         vmcs_write32(GUEST_CS_LIMIT, 0xffff);
1911         if (vmcs_readl(GUEST_CS_BASE) == 0xffff0000)
1912                 vmcs_writel(GUEST_CS_BASE, 0xf0000);
1913         vmcs_write16(GUEST_CS_SELECTOR, vmcs_readl(GUEST_CS_BASE) >> 4);
1914 
1915         fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.es);
1916         fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.ds);
1917         fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.gs);
1918         fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.fs);
1919 
1920 continue_rmode:
1921         kvm_mmu_reset_context(vcpu);
1922 }
1923 
1924 static void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
1925 {
1926         struct vcpu_vmx *vmx = to_vmx(vcpu);
1927         struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
1928 
1929         if (!msr)
1930                 return;
1931 
1932         /*
1933          * Force kernel_gs_base reloading before EFER changes, as control
1934          * of this msr depends on is_long_mode().
1935          */
1936         vmx_load_host_state(to_vmx(vcpu));
1937         vcpu->arch.efer = efer;
1938         if (efer & EFER_LMA) {
1939                 vmcs_write32(VM_ENTRY_CONTROLS,
1940                              vmcs_read32(VM_ENTRY_CONTROLS) |
1941                              VM_ENTRY_IA32E_MODE);
1942                 msr->data = efer;
1943         } else {
1944                 vmcs_write32(VM_ENTRY_CONTROLS,
1945                              vmcs_read32(VM_ENTRY_CONTROLS) &
1946                              ~VM_ENTRY_IA32E_MODE);
1947 
1948                 msr->data = efer & ~EFER_LME;
1949         }
1950         setup_msrs(vmx);
1951 }
1952 
1953 #ifdef CONFIG_X86_64
1954 
1955 static void enter_lmode(struct kvm_vcpu *vcpu)
1956 {
1957         u32 guest_tr_ar;
1958 
1959         vmx_segment_cache_clear(to_vmx(vcpu));
1960 
1961         guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
1962         if ((guest_tr_ar & AR_TYPE_MASK) != AR_TYPE_BUSY_64_TSS) {
1963                 printk(KERN_DEBUG "%s: tss fixup for long mode. \n",
1964                        __func__);
1965                 vmcs_write32(GUEST_TR_AR_BYTES,
1966                              (guest_tr_ar & ~AR_TYPE_MASK)
1967                              | AR_TYPE_BUSY_64_TSS);
1968         }
1969         vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
1970 }
1971 
1972 static void exit_lmode(struct kvm_vcpu *vcpu)
1973 {
1974         vmcs_write32(VM_ENTRY_CONTROLS,
1975                      vmcs_read32(VM_ENTRY_CONTROLS)
1976                      & ~VM_ENTRY_IA32E_MODE);
1977         vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
1978 }
1979 
1980 #endif
1981 
1982 static void vmx_flush_tlb(struct kvm_vcpu *vcpu)
1983 {
1984         vpid_sync_context(to_vmx(vcpu));
1985         if (enable_ept) {
1986                 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
1987                         return;
1988                 ept_sync_context(construct_eptp(vcpu->arch.mmu.root_hpa));
1989         }
1990 }
1991 
1992 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
1993 {
1994         ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
1995 
1996         vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
1997         vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
1998 }
1999 
2000 static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
2001 {
2002         if (enable_ept && is_paging(vcpu))
2003                 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
2004         __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
2005 }
2006 
2007 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
2008 {
2009         ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
2010 
2011         vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
2012         vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
2013 }
2014 
2015 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
2016 {
2017         if (!test_bit(VCPU_EXREG_PDPTR,
2018                       (unsigned long *)&vcpu->arch.regs_dirty))
2019                 return;
2020 
2021         if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
2022                 vmcs_write64(GUEST_PDPTR0, vcpu->arch.mmu.pdptrs[0]);
2023                 vmcs_write64(GUEST_PDPTR1, vcpu->arch.mmu.pdptrs[1]);
2024                 vmcs_write64(GUEST_PDPTR2, vcpu->arch.mmu.pdptrs[2]);
2025                 vmcs_write64(GUEST_PDPTR3, vcpu->arch.mmu.pdptrs[3]);
2026         }
2027 }
2028 
2029 static void ept_save_pdptrs(struct kvm_vcpu *vcpu)
2030 {
2031         if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
2032                 vcpu->arch.mmu.pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
2033                 vcpu->arch.mmu.pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
2034                 vcpu->arch.mmu.pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
2035                 vcpu->arch.mmu.pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
2036         }
2037 
2038         __set_bit(VCPU_EXREG_PDPTR,
2039                   (unsigned long *)&vcpu->arch.regs_avail);
2040         __set_bit(VCPU_EXREG_PDPTR,
2041                   (unsigned long *)&vcpu->arch.regs_dirty);
2042 }
2043 
2044 static void vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
2045 
2046 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
2047                                         unsigned long cr0,
2048                                         struct kvm_vcpu *vcpu)
2049 {
2050         if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
2051                 vmx_decache_cr3(vcpu);
2052         if (!(cr0 & X86_CR0_PG)) {
2053                 /* From paging/starting to nonpaging */
2054                 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
2055                              vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
2056                              (CPU_BASED_CR3_LOAD_EXITING |
2057                               CPU_BASED_CR3_STORE_EXITING));
2058                 vcpu->arch.cr0 = cr0;
2059                 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
2060         } else if (!is_paging(vcpu)) {
2061                 /* From nonpaging to paging */
2062                 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
2063                              vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
2064                              ~(CPU_BASED_CR3_LOAD_EXITING |
2065                                CPU_BASED_CR3_STORE_EXITING));
2066                 vcpu->arch.cr0 = cr0;
2067                 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
2068         }
2069 
2070         if (!(cr0 & X86_CR0_WP))
2071                 *hw_cr0 &= ~X86_CR0_WP;
2072 }
2073 
2074 static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
2075 {
2076         struct vcpu_vmx *vmx = to_vmx(vcpu);
2077         unsigned long hw_cr0;
2078 
2079         if (enable_unrestricted_guest)
2080                 hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK_UNRESTRICTED_GUEST)
2081                         | KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
2082         else
2083                 hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK) | KVM_VM_CR0_ALWAYS_ON;
2084 
2085         if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
2086                 enter_pmode(vcpu);
2087 
2088         if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
2089                 enter_rmode(vcpu);
2090 
2091 #ifdef CONFIG_X86_64
2092         if (vcpu->arch.efer & EFER_LME) {
2093                 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
2094                         enter_lmode(vcpu);
2095                 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
2096                         exit_lmode(vcpu);
2097         }
2098 #endif
2099 
2100         if (enable_ept)
2101                 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
2102 
2103         if (!vcpu->fpu_active)
2104                 hw_cr0 |= X86_CR0_TS | X86_CR0_MP;
2105 
2106         vmcs_writel(CR0_READ_SHADOW, cr0);
2107         vmcs_writel(GUEST_CR0, hw_cr0);
2108         vcpu->arch.cr0 = cr0;
2109         __clear_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail);
2110 }
2111 
2112 static u64 construct_eptp(unsigned long root_hpa)
2113 {
2114         u64 eptp;
2115 
2116         /* TODO write the value reading from MSR */
2117         eptp = VMX_EPT_DEFAULT_MT |
2118                 VMX_EPT_DEFAULT_GAW << VMX_EPT_GAW_EPTP_SHIFT;
2119         eptp |= (root_hpa & PAGE_MASK);
2120 
2121         return eptp;
2122 }
2123 
2124 static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
2125 {
2126         unsigned long guest_cr3;
2127         u64 eptp;
2128 
2129         guest_cr3 = cr3;
2130         if (enable_ept) {
2131                 eptp = construct_eptp(cr3);
2132                 vmcs_write64(EPT_POINTER, eptp);
2133                 guest_cr3 = is_paging(vcpu) ? kvm_read_cr3(vcpu) :
2134                         vcpu->kvm->arch.ept_identity_map_addr;
2135                 ept_load_pdptrs(vcpu);
2136         }
2137 
2138         vmx_flush_tlb(vcpu);
2139         vmcs_writel(GUEST_CR3, guest_cr3);
2140 }
2141 
2142 static void vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
2143 {
2144         unsigned long hw_cr4 = cr4 | (to_vmx(vcpu)->rmode.vm86_active ?
2145                     KVM_RMODE_VM_CR4_ALWAYS_ON : KVM_PMODE_VM_CR4_ALWAYS_ON);
2146 
2147         vcpu->arch.cr4 = cr4;
2148         if (enable_ept) {
2149                 if (!is_paging(vcpu)) {
2150                         hw_cr4 &= ~X86_CR4_PAE;
2151                         hw_cr4 |= X86_CR4_PSE;
2152                 } else if (!(cr4 & X86_CR4_PAE)) {
2153                         hw_cr4 &= ~X86_CR4_PAE;
2154                 }
2155         }
2156 
2157         vmcs_writel(CR4_READ_SHADOW, cr4);
2158         vmcs_writel(GUEST_CR4, hw_cr4);
2159 }
2160 
2161 static void vmx_get_segment(struct kvm_vcpu *vcpu,
2162                             struct kvm_segment *var, int seg)
2163 {
2164         struct vcpu_vmx *vmx = to_vmx(vcpu);
2165         struct kvm_save_segment *save;
2166         u32 ar;
2167 
2168         if (vmx->rmode.vm86_active
2169             && (seg == VCPU_SREG_TR || seg == VCPU_SREG_ES
2170                 || seg == VCPU_SREG_DS || seg == VCPU_SREG_FS
2171                 || seg == VCPU_SREG_GS)
2172             && !emulate_invalid_guest_state) {
2173                 switch (seg) {
2174                 case VCPU_SREG_TR: save = &vmx->rmode.tr; break;
2175                 case VCPU_SREG_ES: save = &vmx->rmode.es; break;
2176                 case VCPU_SREG_DS: save = &vmx->rmode.ds; break;
2177                 case VCPU_SREG_FS: save = &vmx->rmode.fs; break;
2178                 case VCPU_SREG_GS: save = &vmx->rmode.gs; break;
2179                 default: BUG();
2180                 }
2181                 var->selector = save->selector;
2182                 var->base = save->base;
2183                 var->limit = save->limit;
2184                 ar = save->ar;
2185                 if (seg == VCPU_SREG_TR
2186                     || var->selector == vmx_read_guest_seg_selector(vmx, seg))
2187                         goto use_saved_rmode_seg;
2188         }
2189         var->base = vmx_read_guest_seg_base(vmx, seg);
2190         var->limit = vmx_read_guest_seg_limit(vmx, seg);
2191         var->selector = vmx_read_guest_seg_selector(vmx, seg);
2192         ar = vmx_read_guest_seg_ar(vmx, seg);
2193 use_saved_rmode_seg:
2194         if ((ar & AR_UNUSABLE_MASK) && !emulate_invalid_guest_state)
2195                 ar = 0;
2196         var->type = ar & 15;
2197         var->s = (ar >> 4) & 1;
2198         var->dpl = (ar >> 5) & 3;
2199         var->present = (ar >> 7) & 1;
2200         var->avl = (ar >> 12) & 1;
2201         var->l = (ar >> 13) & 1;
2202         var->db = (ar >> 14) & 1;
2203         var->g = (ar >> 15) & 1;
2204         var->unusable = (ar >> 16) & 1;
2205 }
2206 
2207 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
2208 {
2209         struct kvm_segment s;
2210 
2211         if (to_vmx(vcpu)->rmode.vm86_active) {
2212                 vmx_get_segment(vcpu, &s, seg);
2213                 return s.base;
2214         }
2215         return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
2216 }
2217 
2218 static int __vmx_get_cpl(struct kvm_vcpu *vcpu)
2219 {
2220         if (!is_protmode(vcpu))
2221                 return 0;
2222 
2223         if (!is_long_mode(vcpu)
2224             && (kvm_get_rflags(vcpu) & X86_EFLAGS_VM)) /* if virtual 8086 */
2225                 return 3;
2226 
2227         return vmx_read_guest_seg_selector(to_vmx(vcpu), VCPU_SREG_CS) & 3;
2228 }
2229 
2230 static int vmx_get_cpl(struct kvm_vcpu *vcpu)
2231 {
2232         if (!test_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail)) {
2233                 __set_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail);
2234                 to_vmx(vcpu)->cpl = __vmx_get_cpl(vcpu);
2235         }
2236         return to_vmx(vcpu)->cpl;
2237 }
2238 
2239 
2240 static u32 vmx_segment_access_rights(struct kvm_segment *var)
2241 {
2242         u32 ar;
2243 
2244         if (var->unusable)
2245                 ar = 1 << 16;
2246         else {
2247                 ar = var->type & 15;
2248                 ar |= (var->s & 1) << 4;
2249                 ar |= (var->dpl & 3) << 5;
2250                 ar |= (var->present & 1) << 7;
2251                 ar |= (var->avl & 1) << 12;
2252                 ar |= (var->l & 1) << 13;
2253                 ar |= (var->db & 1) << 14;
2254                 ar |= (var->g & 1) << 15;
2255         }
2256         if (ar == 0) /* a 0 value means unusable */
2257                 ar = AR_UNUSABLE_MASK;
2258 
2259         return ar;
2260 }
2261 
2262 static void vmx_set_segment(struct kvm_vcpu *vcpu,
2263                             struct kvm_segment *var, int seg)
2264 {
2265         struct vcpu_vmx *vmx = to_vmx(vcpu);
2266         struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
2267         u32 ar;
2268 
2269         vmx_segment_cache_clear(vmx);
2270 
2271         if (vmx->rmode.vm86_active && seg == VCPU_SREG_TR) {
2272                 vmcs_write16(sf->selector, var->selector);
2273                 vmx->rmode.tr.selector = var->selector;
2274                 vmx->rmode.tr.base = var->base;
2275                 vmx->rmode.tr.limit = var->limit;
2276                 vmx->rmode.tr.ar = vmx_segment_access_rights(var);
2277                 return;
2278         }
2279         vmcs_writel(sf->base, var->base);
2280         vmcs_write32(sf->limit, var->limit);
2281         vmcs_write16(sf->selector, var->selector);
2282         if (vmx->rmode.vm86_active && var->s) {
2283                 /*
2284                  * Hack real-mode segments into vm86 compatibility.
2285                  */
2286                 if (var->base == 0xffff0000 && var->selector == 0xf000)
2287                         vmcs_writel(sf->base, 0xf0000);
2288                 ar = 0xf3;
2289         } else
2290                 ar = vmx_segment_access_rights(var);
2291 
2292         /*
2293          *   Fix the "Accessed" bit in AR field of segment registers for older
2294          * qemu binaries.
2295          *   IA32 arch specifies that at the time of processor reset the
2296          * "Accessed" bit in the AR field of segment registers is 1. And qemu
2297          * is setting it to 0 in the usedland code. This causes invalid guest
2298          * state vmexit when "unrestricted guest" mode is turned on.
2299          *    Fix for this setup issue in cpu_reset is being pushed in the qemu
2300          * tree. Newer qemu binaries with that qemu fix would not need this
2301          * kvm hack.
2302          */
2303         if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
2304                 ar |= 0x1; /* Accessed */
2305 
2306         vmcs_write32(sf->ar_bytes, ar);
2307         __clear_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail);
2308 }
2309 
2310 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
2311 {
2312         u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
2313 
2314         *db = (ar >> 14) & 1;
2315         *l = (ar >> 13) & 1;
2316 }
2317 
2318 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2319 {
2320         dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
2321         dt->address = vmcs_readl(GUEST_IDTR_BASE);
2322 }
2323 
2324 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2325 {
2326         vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
2327         vmcs_writel(GUEST_IDTR_BASE, dt->address);
2328 }
2329 
2330 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2331 {
2332         dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
2333         dt->address = vmcs_readl(GUEST_GDTR_BASE);
2334 }
2335 
2336 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2337 {
2338         vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
2339         vmcs_writel(GUEST_GDTR_BASE, dt->address);
2340 }
2341 
2342 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
2343 {
2344         struct kvm_segment var;
2345         u32 ar;
2346 
2347         vmx_get_segment(vcpu, &var, seg);
2348         ar = vmx_segment_access_rights(&var);
2349 
2350         if (var.base != (var.selector << 4))
2351                 return false;
2352         if (var.limit != 0xffff)
2353                 return false;
2354         if (ar != 0xf3)
2355                 return false;
2356 
2357         return true;
2358 }
2359 
2360 static bool code_segment_valid(struct kvm_vcpu *vcpu)
2361 {
2362         struct kvm_segment cs;
2363         unsigned int cs_rpl;
2364 
2365         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
2366         cs_rpl = cs.selector & SELECTOR_RPL_MASK;
2367 
2368         if (cs.unusable)
2369                 return false;
2370         if (~cs.type & (AR_TYPE_CODE_MASK|AR_TYPE_ACCESSES_MASK))
2371                 return false;
2372         if (!cs.s)
2373                 return false;
2374         if (cs.type & AR_TYPE_WRITEABLE_MASK) {
2375                 if (cs.dpl > cs_rpl)
2376                         return false;
2377         } else {
2378                 if (cs.dpl != cs_rpl)
2379                         return false;
2380         }
2381         if (!cs.present)
2382                 return false;
2383 
2384         /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
2385         return true;
2386 }
2387 
2388 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
2389 {
2390         struct kvm_segment ss;
2391         unsigned int ss_rpl;
2392 
2393         vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
2394         ss_rpl = ss.selector & SELECTOR_RPL_MASK;
2395 
2396         if (ss.unusable)
2397                 return true;
2398         if (ss.type != 3 && ss.type != 7)
2399                 return false;
2400         if (!ss.s)
2401                 return false;
2402         if (ss.dpl != ss_rpl) /* DPL != RPL */
2403                 return false;
2404         if (!ss.present)
2405                 return false;
2406 
2407         return true;
2408 }
2409 
2410 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
2411 {
2412         struct kvm_segment var;
2413         unsigned int rpl;
2414 
2415         vmx_get_segment(vcpu, &var, seg);
2416         rpl = var.selector & SELECTOR_RPL_MASK;
2417 
2418         if (var.unusable)
2419                 return true;
2420         if (!var.s)
2421                 return false;
2422         if (!var.present)
2423                 return false;
2424         if (~var.type & (AR_TYPE_CODE_MASK|AR_TYPE_WRITEABLE_MASK)) {
2425                 if (var.dpl < rpl) /* DPL < RPL */
2426                         return false;
2427         }
2428 
2429         /* TODO: Add other members to kvm_segment_field to allow checking for other access
2430          * rights flags
2431          */
2432         return true;
2433 }
2434 
2435 static bool tr_valid(struct kvm_vcpu *vcpu)
2436 {
2437         struct kvm_segment tr;
2438 
2439         vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
2440 
2441         if (tr.unusable)
2442                 return false;
2443         if (tr.selector & SELECTOR_TI_MASK)     /* TI = 1 */
2444                 return false;
2445         if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
2446                 return false;
2447         if (!tr.present)
2448                 return false;
2449 
2450         return true;
2451 }
2452 
2453 static bool ldtr_valid(struct kvm_vcpu *vcpu)
2454 {
2455         struct kvm_segment ldtr;
2456 
2457         vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
2458 
2459         if (ldtr.unusable)
2460                 return true;
2461         if (ldtr.selector & SELECTOR_TI_MASK)   /* TI = 1 */
2462                 return false;
2463         if (ldtr.type != 2)
2464                 return false;
2465         if (!ldtr.present)
2466                 return false;
2467 
2468         return true;
2469 }
2470 
2471 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
2472 {
2473         struct kvm_segment cs, ss;
2474 
2475         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
2476         vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
2477 
2478         return ((cs.selector & SELECTOR_RPL_MASK) ==
2479                  (ss.selector & SELECTOR_RPL_MASK));
2480 }
2481 
2482 /*
2483  * Check if guest state is valid. Returns true if valid, false if
2484  * not.
2485  * We assume that registers are always usable
2486  */
2487 static bool guest_state_valid(struct kvm_vcpu *vcpu)
2488 {
2489         /* real mode guest state checks */
2490         if (!is_protmode(vcpu)) {
2491                 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
2492                         return false;
2493                 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
2494                         return false;
2495                 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
2496                         return false;
2497                 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
2498                         return false;
2499                 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
2500                         return false;
2501                 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
2502                         return false;
2503         } else {
2504         /* protected mode guest state checks */
2505                 if (!cs_ss_rpl_check(vcpu))
2506                         return false;
2507                 if (!code_segment_valid(vcpu))
2508                         return false;
2509                 if (!stack_segment_valid(vcpu))
2510                         return false;
2511                 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
2512                         return false;
2513                 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
2514                         return false;
2515                 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
2516                         return false;
2517                 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
2518                         return false;
2519                 if (!tr_valid(vcpu))
2520                         return false;
2521                 if (!ldtr_valid(vcpu))
2522                         return false;
2523         }
2524         /* TODO:
2525          * - Add checks on RIP
2526          * - Add checks on RFLAGS
2527          */
2528 
2529         return true;
2530 }
2531 
2532 static int init_rmode_tss(struct kvm *kvm)
2533 {
2534         gfn_t fn;
2535         u16 data = 0;
2536         int r, idx, ret = 0;
2537 
2538         idx = srcu_read_lock(&kvm->srcu);
2539         fn = rmode_tss_base(kvm) >> PAGE_SHIFT;
2540         r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
2541         if (r < 0)
2542                 goto out;
2543         data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
2544         r = kvm_write_guest_page(kvm, fn++, &data,
2545                         TSS_IOPB_BASE_OFFSET, sizeof(u16));
2546         if (r < 0)
2547                 goto out;
2548         r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
2549         if (r < 0)
2550                 goto out;
2551         r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
2552         if (r < 0)
2553                 goto out;
2554         data = ~0;
2555         r = kvm_write_guest_page(kvm, fn, &data,
2556                                  RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
2557                                  sizeof(u8));
2558         if (r < 0)
2559                 goto out;
2560 
2561         ret = 1;
2562 out:
2563         srcu_read_unlock(&kvm->srcu, idx);
2564         return ret;
2565 }
2566 
2567 static int init_rmode_identity_map(struct kvm *kvm)
2568 {
2569         int i, idx, r, ret;
2570         pfn_t identity_map_pfn;
2571         u32 tmp;
2572 
2573         if (!enable_ept)
2574                 return 1;
2575         if (unlikely(!kvm->arch.ept_identity_pagetable)) {
2576                 printk(KERN_ERR "EPT: identity-mapping pagetable "
2577                         "haven't been allocated!\n");
2578                 return 0;
2579         }
2580         if (likely(kvm->arch.ept_identity_pagetable_done))
2581                 return 1;
2582         ret = 0;
2583         identity_map_pfn = kvm->arch.ept_identity_map_addr >> PAGE_SHIFT;
2584         idx = srcu_read_lock(&kvm->srcu);
2585         r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
2586         if (r < 0)
2587                 goto out;
2588         /* Set up identity-mapping pagetable for EPT in real mode */
2589         for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
2590                 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
2591                         _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
2592                 r = kvm_write_guest_page(kvm, identity_map_pfn,
2593                                 &tmp, i * sizeof(tmp), sizeof(tmp));
2594                 if (r < 0)
2595                         goto out;
2596         }
2597         kvm->arch.ept_identity_pagetable_done = true;
2598         ret = 1;
2599 out:
2600         srcu_read_unlock(&kvm->srcu, idx);
2601         return ret;
2602 }
2603 
2604 static void seg_setup(int seg)
2605 {
2606         struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
2607         unsigned int ar;
2608 
2609         vmcs_write16(sf->selector, 0);
2610         vmcs_writel(sf->base, 0);
2611         vmcs_write32(sf->limit, 0xffff);
2612         if (enable_unrestricted_guest) {
2613                 ar = 0x93;
2614                 if (seg == VCPU_SREG_CS)
2615                         ar |= 0x08; /* code segment */
2616         } else
2617                 ar = 0xf3;
2618 
2619         vmcs_write32(sf->ar_bytes, ar);
2620 }
2621 
2622 static int alloc_apic_access_page(struct kvm *kvm)
2623 {
2624         struct kvm_userspace_memory_region kvm_userspace_mem;
2625         int r = 0;
2626 
2627         mutex_lock(&kvm->slots_lock);
2628         if (kvm->arch.apic_access_page)
2629                 goto out;
2630         kvm_userspace_mem.slot = APIC_ACCESS_PAGE_PRIVATE_MEMSLOT;
2631         kvm_userspace_mem.flags = 0;
2632         kvm_userspace_mem.guest_phys_addr = 0xfee00000ULL;
2633         kvm_userspace_mem.memory_size = PAGE_SIZE;
2634         r = __kvm_set_memory_region(kvm, &kvm_userspace_mem, 0);
2635         if (r)
2636                 goto out;
2637 
2638         kvm->arch.apic_access_page = gfn_to_page(kvm, 0xfee00);
2639 out:
2640         mutex_unlock(&kvm->slots_lock);
2641         return r;
2642 }
2643 
2644 static int alloc_identity_pagetable(struct kvm *kvm)
2645 {
2646         struct kvm_userspace_memory_region kvm_userspace_mem;
2647         int r = 0;
2648 
2649         mutex_lock(&kvm->slots_lock);
2650         if (kvm->arch.ept_identity_pagetable)
2651                 goto out;
2652         kvm_userspace_mem.slot = IDENTITY_PAGETABLE_PRIVATE_MEMSLOT;
2653         kvm_userspace_mem.flags = 0;
2654         kvm_userspace_mem.guest_phys_addr =
2655                 kvm->arch.ept_identity_map_addr;
2656         kvm_userspace_mem.memory_size = PAGE_SIZE;
2657         r = __kvm_set_memory_region(kvm, &kvm_userspace_mem, 0);
2658         if (r)
2659                 goto out;
2660 
2661         kvm->arch.ept_identity_pagetable = gfn_to_page(kvm,
2662                         kvm->arch.ept_identity_map_addr >> PAGE_SHIFT);
2663 out:
2664         mutex_unlock(&kvm->slots_lock);
2665         return r;
2666 }
2667 
2668 static void allocate_vpid(struct vcpu_vmx *vmx)
2669 {
2670         int vpid;
2671 
2672         vmx->vpid = 0;
2673         if (!enable_vpid)
2674                 return;
2675         spin_lock(&vmx_vpid_lock);
2676         vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
2677         if (vpid < VMX_NR_VPIDS) {
2678                 vmx->vpid = vpid;
2679                 __set_bit(vpid, vmx_vpid_bitmap);
2680         }
2681         spin_unlock(&vmx_vpid_lock);
2682 }
2683 
2684 static void free_vpid(struct vcpu_vmx *vmx)
2685 {
2686         if (!enable_vpid)
2687                 return;
2688         spin_lock(&vmx_vpid_lock);
2689         if (vmx->vpid != 0)
2690                 __clear_bit(vmx->vpid, vmx_vpid_bitmap);
2691         spin_unlock(&vmx_vpid_lock);
2692 }
2693 
2694 static void __vmx_disable_intercept_for_msr(unsigned long *msr_bitmap, u32 msr)
2695 {
2696         int f = sizeof(unsigned long);
2697 
2698         if (!cpu_has_vmx_msr_bitmap())
2699                 return;
2700 
2701         /*
2702          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
2703          * have the write-low and read-high bitmap offsets the wrong way round.
2704          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
2705          */
2706         if (msr <= 0x1fff) {
2707                 __clear_bit(msr, msr_bitmap + 0x000 / f); /* read-low */
2708                 __clear_bit(msr, msr_bitmap + 0x800 / f); /* write-low */
2709         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
2710                 msr &= 0x1fff;
2711                 __clear_bit(msr, msr_bitmap + 0x400 / f); /* read-high */
2712                 __clear_bit(msr, msr_bitmap + 0xc00 / f); /* write-high */
2713         }
2714 }
2715 
2716 static void vmx_disable_intercept_for_msr(u32 msr, bool longmode_only)
2717 {
2718         if (!longmode_only)
2719                 __vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy, msr);
2720         __vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode, msr);
2721 }
2722 
2723 /*
2724  * Sets up the vmcs for emulated real mode.
2725  */
2726 static int vmx_vcpu_setup(struct vcpu_vmx *vmx)
2727 {
2728         u32 host_sysenter_cs, msr_low, msr_high;
2729         u32 junk;
2730         u64 host_pat;
2731         unsigned long a;
2732         struct desc_ptr dt;
2733         int i;
2734         unsigned long kvm_vmx_return;
2735         u32 exec_control;
2736 
2737         /* I/O */
2738         vmcs_write64(IO_BITMAP_A, __pa(vmx_io_bitmap_a));
2739         vmcs_write64(IO_BITMAP_B, __pa(vmx_io_bitmap_b));
2740 
2741         if (cpu_has_vmx_msr_bitmap())
2742                 vmcs_write64(MSR_BITMAP, __pa(vmx_msr_bitmap_legacy));
2743 
2744         vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
2745 
2746         /* Control */
2747         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL,
2748                 vmcs_config.pin_based_exec_ctrl);
2749 
2750         exec_control = vmcs_config.cpu_based_exec_ctrl;
2751         if (!vm_need_tpr_shadow(vmx->vcpu.kvm)) {
2752                 exec_control &= ~CPU_BASED_TPR_SHADOW;
2753 #ifdef CONFIG_X86_64
2754                 exec_control |= CPU_BASED_CR8_STORE_EXITING |
2755                                 CPU_BASED_CR8_LOAD_EXITING;
2756 #endif
2757         }
2758         if (!enable_ept)
2759                 exec_control |= CPU_BASED_CR3_STORE_EXITING |
2760                                 CPU_BASED_CR3_LOAD_EXITING  |
2761                                 CPU_BASED_INVLPG_EXITING;
2762         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
2763 
2764         if (cpu_has_secondary_exec_ctrls()) {
2765                 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
2766                 if (!vm_need_virtualize_apic_accesses(vmx->vcpu.kvm))
2767                         exec_control &=
2768                                 ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
2769                 if (vmx->vpid == 0)
2770                         exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
2771                 if (!enable_ept) {
2772                         exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
2773                         enable_unrestricted_guest = 0;
2774                 }
2775                 if (!enable_unrestricted_guest)
2776                         exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
2777                 if (!ple_gap)
2778                         exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
2779                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
2780         }
2781 
2782         if (ple_gap) {
2783                 vmcs_write32(PLE_GAP, ple_gap);
2784                 vmcs_write32(PLE_WINDOW, ple_window);
2785         }
2786 
2787         vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, !!bypass_guest_pf);
2788         vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, !!bypass_guest_pf);
2789         vmcs_write32(CR3_TARGET_COUNT, 0);           /* 22.2.1 */
2790 
2791         vmcs_writel(HOST_CR0, read_cr0() | X86_CR0_TS);  /* 22.2.3 */
2792         vmcs_writel(HOST_CR4, read_cr4());  /* 22.2.3, 22.2.5 */
2793         vmcs_writel(HOST_CR3, read_cr3());  /* 22.2.3  FIXME: shadow tables */
2794 
2795         vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS);  /* 22.2.4 */
2796         vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
2797         vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
2798         vmcs_write16(HOST_FS_SELECTOR, 0);            /* 22.2.4 */
2799         vmcs_write16(HOST_GS_SELECTOR, 0);            /* 22.2.4 */
2800         vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
2801 #ifdef CONFIG_X86_64
2802         rdmsrl(MSR_FS_BASE, a);
2803         vmcs_writel(HOST_FS_BASE, a); /* 22.2.4 */
2804         rdmsrl(MSR_GS_BASE, a);
2805         vmcs_writel(HOST_GS_BASE, a); /* 22.2.4 */
2806 #else
2807         vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
2808         vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
2809 #endif
2810 
2811         vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8);  /* 22.2.4 */
2812 
2813         native_store_idt(&dt);
2814         vmcs_writel(HOST_IDTR_BASE, dt.address);   /* 22.2.4 */
2815 
2816         asm("mov $.Lkvm_vmx_return, %0" : "=r"(kvm_vmx_return));
2817         vmcs_writel(HOST_RIP, kvm_vmx_return); /* 22.2.5 */
2818         vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
2819         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
2820         vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host));
2821         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
2822         vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest));
2823 
2824         rdmsr(MSR_IA32_SYSENTER_CS, host_sysenter_cs, junk);
2825         vmcs_write32(HOST_IA32_SYSENTER_CS, host_sysenter_cs);
2826         rdmsrl(MSR_IA32_SYSENTER_ESP, a);
2827         vmcs_writel(HOST_IA32_SYSENTER_ESP, a);   /* 22.2.3 */
2828         rdmsrl(MSR_IA32_SYSENTER_EIP, a);
2829         vmcs_writel(HOST_IA32_SYSENTER_EIP, a);   /* 22.2.3 */
2830 
2831         if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
2832                 rdmsr(MSR_IA32_CR_PAT, msr_low, msr_high);
2833                 host_pat = msr_low | ((u64) msr_high << 32);
2834                 vmcs_write64(HOST_IA32_PAT, host_pat);
2835         }
2836         if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
2837                 rdmsr(MSR_IA32_CR_PAT, msr_low, msr_high);
2838                 host_pat = msr_low | ((u64) msr_high << 32);
2839                 /* Write the default value follow host pat */
2840                 vmcs_write64(GUEST_IA32_PAT, host_pat);
2841                 /* Keep arch.pat sync with GUEST_IA32_PAT */
2842                 vmx->vcpu.arch.pat = host_pat;
2843         }
2844 
2845         for (i = 0; i < NR_VMX_MSR; ++i) {
2846                 u32 index = vmx_msr_index[i];
2847                 u32 data_low, data_high;
2848                 int j = vmx->nmsrs;
2849 
2850                 if (rdmsr_safe(index, &data_low, &data_high) < 0)
2851                         continue;
2852                 if (wrmsr_safe(index, data_low, data_high) < 0)
2853                         continue;
2854                 vmx->guest_msrs[j].index = i;
2855                 vmx->guest_msrs[j].data = 0;
2856                 vmx->guest_msrs[j].mask = -1ull;
2857                 ++vmx->nmsrs;
2858         }
2859 
2860         vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);
2861 
2862         /* 22.2.1, 20.8.1 */
2863         vmcs_write32(VM_ENTRY_CONTROLS, vmcs_config.vmentry_ctrl);
2864 
2865         vmcs_writel(CR0_GUEST_HOST_MASK, ~0UL);
2866         vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
2867         if (enable_ept)
2868                 vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
2869         vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
2870 
2871         kvm_write_tsc(&vmx->vcpu, 0);
2872 
2873         return 0;
2874 }
2875 
2876 static int vmx_vcpu_reset(struct kvm_vcpu *vcpu)
2877 {
2878         struct vcpu_vmx *vmx = to_vmx(vcpu);
2879         u64 msr;
2880         int ret;
2881 
2882         vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP));
2883 
2884         vmx->rmode.vm86_active = 0;
2885 
2886         vmx->soft_vnmi_blocked = 0;
2887 
2888         vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
2889         kvm_set_cr8(&vmx->vcpu, 0);
2890         msr = 0xfee00000 | MSR_IA32_APICBASE_ENABLE;
2891         if (kvm_vcpu_is_bsp(&vmx->vcpu))
2892                 msr |= MSR_IA32_APICBASE_BSP;
2893         kvm_set_apic_base(&vmx->vcpu, msr);
2894 
2895         ret = fx_init(&vmx->vcpu);
2896         if (ret != 0)
2897                 goto out;
2898 
2899         vmx_segment_cache_clear(vmx);
2900 
2901         seg_setup(VCPU_SREG_CS);
2902         /*
2903          * GUEST_CS_BASE should really be 0xffff0000, but VT vm86 mode
2904          * insists on having GUEST_CS_BASE == GUEST_CS_SELECTOR << 4.  Sigh.
2905          */
2906         if (kvm_vcpu_is_bsp(&vmx->vcpu)) {
2907                 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
2908                 vmcs_writel(GUEST_CS_BASE, 0x000f0000);
2909         } else {
2910                 vmcs_write16(GUEST_CS_SELECTOR, vmx->vcpu.arch.sipi_vector << 8);
2911                 vmcs_writel(GUEST_CS_BASE, vmx->vcpu.arch.sipi_vector << 12);
2912         }
2913 
2914         seg_setup(VCPU_SREG_DS);
2915         seg_setup(VCPU_SREG_ES);
2916         seg_setup(VCPU_SREG_FS);
2917         seg_setup(VCPU_SREG_GS);
2918         seg_setup(VCPU_SREG_SS);
2919 
2920         vmcs_write16(GUEST_TR_SELECTOR, 0);
2921         vmcs_writel(GUEST_TR_BASE, 0);
2922         vmcs_write32(GUEST_TR_LIMIT, 0xffff);
2923         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
2924 
2925         vmcs_write16(GUEST_LDTR_SELECTOR, 0);
2926         vmcs_writel(GUEST_LDTR_BASE, 0);
2927         vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
2928         vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
2929 
2930         vmcs_write32(GUEST_SYSENTER_CS, 0);
2931         vmcs_writel(GUEST_SYSENTER_ESP, 0);
2932         vmcs_writel(GUEST_SYSENTER_EIP, 0);
2933 
2934         vmcs_writel(GUEST_RFLAGS, 0x02);
2935         if (kvm_vcpu_is_bsp(&vmx->vcpu))
2936                 kvm_rip_write(vcpu, 0xfff0);
2937         else
2938                 kvm_rip_write(vcpu, 0);
2939         kvm_register_write(vcpu, VCPU_REGS_RSP, 0);
2940 
2941         vmcs_writel(GUEST_DR7, 0x400);
2942 
2943         vmcs_writel(GUEST_GDTR_BASE, 0);
2944         vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
2945 
2946         vmcs_writel(GUEST_IDTR_BASE, 0);
2947         vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
2948 
2949         vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
2950         vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
2951         vmcs_write32(GUEST_PENDING_DBG_EXCEPTIONS, 0);
2952 
2953         /* Special registers */
2954         vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
2955 
2956         setup_msrs(vmx);
2957 
2958         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);  /* 22.2.1 */
2959 
2960         if (cpu_has_vmx_tpr_shadow()) {
2961                 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
2962                 if (vm_need_tpr_shadow(vmx->vcpu.kvm))
2963                         vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
2964                                      __pa(vmx->vcpu.arch.apic->regs));
2965                 vmcs_write32(TPR_THRESHOLD, 0);
2966         }
2967 
2968         if (vm_need_virtualize_apic_accesses(vmx->vcpu.kvm))
2969                 vmcs_write64(APIC_ACCESS_ADDR,
2970                              page_to_phys(vmx->vcpu.kvm->arch.apic_access_page));
2971 
2972         if (vmx->vpid != 0)
2973                 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
2974 
2975         vmx->vcpu.arch.cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
2976         vmx_set_cr0(&vmx->vcpu, kvm_read_cr0(vcpu)); /* enter rmode */
2977         vmx_set_cr4(&vmx->vcpu, 0);
2978         vmx_set_efer(&vmx->vcpu, 0);
2979         vmx_fpu_activate(&vmx->vcpu);
2980         update_exception_bitmap(&vmx->vcpu);
2981 
2982         vpid_sync_context(vmx);
2983 
2984         ret = 0;
2985 
2986         /* HACK: Don't enable emulation on guest boot/reset */
2987         vmx->emulation_required = 0;
2988 
2989 out:
2990         return ret;
2991 }
2992 
2993 static void enable_irq_window(struct kvm_vcpu *vcpu)
2994 {
2995         u32 cpu_based_vm_exec_control;
2996 
2997         cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
2998         cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_INTR_PENDING;
2999         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
3000 }
3001 
3002 static void enable_nmi_window(struct kvm_vcpu *vcpu)
3003 {
3004         u32 cpu_based_vm_exec_control;
3005 
3006         if (!cpu_has_virtual_nmis()) {
3007                 enable_irq_window(vcpu);
3008                 return;
3009         }
3010 
3011         if (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
3012                 enable_irq_window(vcpu);
3013                 return;
3014         }
3015         cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
3016         cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_NMI_PENDING;
3017         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
3018 }
3019 
3020 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
3021 {
3022         struct vcpu_vmx *vmx = to_vmx(vcpu);
3023         uint32_t intr;
3024         int irq = vcpu->arch.interrupt.nr;
3025 
3026         trace_kvm_inj_virq(irq);
3027 
3028         ++vcpu->stat.irq_injections;
3029         if (vmx->rmode.vm86_active) {
3030                 int inc_eip = 0;
3031                 if (vcpu->arch.interrupt.soft)
3032                         inc_eip = vcpu->arch.event_exit_inst_len;
3033                 if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE)
3034                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3035                 return;
3036         }
3037         intr = irq | INTR_INFO_VALID_MASK;
3038         if (vcpu->arch.interrupt.soft) {
3039                 intr |= INTR_TYPE_SOFT_INTR;
3040                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
3041                              vmx->vcpu.arch.event_exit_inst_len);
3042         } else
3043                 intr |= INTR_TYPE_EXT_INTR;
3044         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
3045         vmx_clear_hlt(vcpu);
3046 }
3047 
3048 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
3049 {
3050         struct vcpu_vmx *vmx = to_vmx(vcpu);
3051 
3052         if (!cpu_has_virtual_nmis()) {
3053                 /*
3054                  * Tracking the NMI-blocked state in software is built upon
3055                  * finding the next open IRQ window. This, in turn, depends on
3056                  * well-behaving guests: They have to keep IRQs disabled at
3057                  * least as long as the NMI handler runs. Otherwise we may
3058                  * cause NMI nesting, maybe breaking the guest. But as this is
3059                  * highly unlikely, we can live with the residual risk.
3060                  */
3061                 vmx->soft_vnmi_blocked = 1;
3062                 vmx->vnmi_blocked_time = 0;
3063         }
3064 
3065         ++vcpu->stat.nmi_injections;
3066         vmx->nmi_known_unmasked = false;
3067         if (vmx->rmode.vm86_active) {
3068                 if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE)
3069                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3070                 return;
3071         }
3072         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
3073                         INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
3074         vmx_clear_hlt(vcpu);
3075 }
3076 
3077 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
3078 {
3079         if (!cpu_has_virtual_nmis() && to_vmx(vcpu)->soft_vnmi_blocked)
3080                 return 0;
3081 
3082         return  !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
3083                   (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
3084                    | GUEST_INTR_STATE_NMI));
3085 }
3086 
3087 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
3088 {
3089         if (!cpu_has_virtual_nmis())
3090                 return to_vmx(vcpu)->soft_vnmi_blocked;
3091         if (to_vmx(vcpu)->nmi_known_unmasked)
3092                 return false;
3093         return vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
3094 }
3095 
3096 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
3097 {
3098         struct vcpu_vmx *vmx = to_vmx(vcpu);
3099 
3100         if (!cpu_has_virtual_nmis()) {
3101                 if (vmx->soft_vnmi_blocked != masked) {
3102                         vmx->soft_vnmi_blocked = masked;
3103                         vmx->vnmi_blocked_time = 0;
3104                 }
3105         } else {
3106                 vmx->nmi_known_unmasked = !masked;
3107                 if (masked)
3108                         vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
3109                                       GUEST_INTR_STATE_NMI);
3110                 else
3111                         vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
3112                                         GUEST_INTR_STATE_NMI);
3113         }
3114 }
3115 
3116 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
3117 {
3118         return (vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
3119                 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
3120                         (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
3121 }
3122 
3123 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
3124 {
3125         int ret;
3126         struct kvm_userspace_memory_region tss_mem = {
3127                 .slot = TSS_PRIVATE_MEMSLOT,
3128                 .guest_phys_addr = addr,
3129                 .memory_size = PAGE_SIZE * 3,
3130                 .flags = 0,
3131         };
3132 
3133         ret = kvm_set_memory_region(kvm, &tss_mem, 0);
3134         if (ret)
3135                 return ret;
3136         kvm->arch.tss_addr = addr;
3137         if (!init_rmode_tss(kvm))
3138                 return  -ENOMEM;
3139 
3140         return 0;
3141 }
3142 
3143 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
3144                                   int vec, u32 err_code)
3145 {
3146         /*
3147          * Instruction with address size override prefix opcode 0x67
3148          * Cause the #SS fault with 0 error code in VM86 mode.
3149          */
3150         if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0)
3151                 if (emulate_instruction(vcpu, 0) == EMULATE_DONE)
3152                         return 1;
3153         /*
3154          * Forward all other exceptions that are valid in real mode.
3155          * FIXME: Breaks guest debugging in real mode, needs to be fixed with
3156          *        the required debugging infrastructure rework.
3157          */
3158         switch (vec) {
3159         case DB_VECTOR:
3160                 if (vcpu->guest_debug &
3161                     (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
3162                         return 0;
3163                 kvm_queue_exception(vcpu, vec);
3164                 return 1;
3165         case BP_VECTOR:
3166                 /*
3167                  * Update instruction length as we may reinject the exception
3168                  * from user space while in guest debugging mode.
3169                  */
3170                 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
3171                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
3172                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
3173                         return 0;
3174                 /* fall through */
3175         case DE_VECTOR:
3176         case OF_VECTOR:
3177         case BR_VECTOR:
3178         case UD_VECTOR:
3179         case DF_VECTOR:
3180         case SS_VECTOR:
3181         case GP_VECTOR:
3182         case MF_VECTOR:
3183                 kvm_queue_exception(vcpu, vec);
3184                 return 1;
3185         }
3186         return 0;
3187 }
3188 
3189 /*
3190  * Trigger machine check on the host. We assume all the MSRs are already set up
3191  * by the CPU and that we still run on the same CPU as the MCE occurred on.
3192  * We pass a fake environment to the machine check handler because we want
3193  * the guest to be always treated like user space, no matter what context
3194  * it used internally.
3195  */
3196 static void kvm_machine_check(void)
3197 {
3198 #if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
3199         struct pt_regs regs = {
3200                 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
3201                 .flags = X86_EFLAGS_IF,
3202         };
3203 
3204         do_machine_check(&regs, 0);
3205 #endif
3206 }
3207 
3208 static int handle_machine_check(struct kvm_vcpu *vcpu)
3209 {
3210         /* already handled by vcpu_run */
3211         return 1;
3212 }
3213 
3214 static int handle_exception(struct kvm_vcpu *vcpu)
3215 {
3216         struct vcpu_vmx *vmx = to_vmx(vcpu);
3217         struct kvm_run *kvm_run = vcpu->run;
3218         u32 intr_info, ex_no, error_code;
3219         unsigned long cr2, rip, dr6;
3220         u32 vect_info;
3221         enum emulation_result er;
3222 
3223         vect_info = vmx->idt_vectoring_info;
3224         intr_info = vmx->exit_intr_info;
3225 
3226         if (is_machine_check(intr_info))
3227                 return handle_machine_check(vcpu);
3228 
3229         if ((vect_info & VECTORING_INFO_VALID_MASK) &&
3230             !is_page_fault(intr_info)) {
3231                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
3232                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
3233                 vcpu->run->internal.ndata = 2;
3234                 vcpu->run->internal.data[0] = vect_info;
3235                 vcpu->run->internal.data[1] = intr_info;
3236                 return 0;
3237         }
3238 
3239         if ((intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR)
3240                 return 1;  /* already handled by vmx_vcpu_run() */
3241 
3242         if (is_no_device(intr_info)) {
3243                 vmx_fpu_activate(vcpu);
3244                 return 1;
3245         }
3246 
3247         if (is_invalid_opcode(intr_info)) {
3248                 er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD);
3249                 if (er != EMULATE_DONE)
3250                         kvm_queue_exception(vcpu, UD_VECTOR);
3251                 return 1;
3252         }
3253 
3254         error_code = 0;
3255         if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
3256                 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
3257         if (is_page_fault(intr_info)) {
3258                 /* EPT won't cause page fault directly */
3259                 if (enable_ept)
3260                         BUG();
3261                 cr2 = vmcs_readl(EXIT_QUALIFICATION);
3262                 trace_kvm_page_fault(cr2, error_code);
3263 
3264                 if (kvm_event_needs_reinjection(vcpu))
3265                         kvm_mmu_unprotect_page_virt(vcpu, cr2);
3266                 return kvm_mmu_page_fault(vcpu, cr2, error_code, NULL, 0);
3267         }
3268 
3269         if (vmx->rmode.vm86_active &&
3270             handle_rmode_exception(vcpu, intr_info & INTR_INFO_VECTOR_MASK,
3271                                                                 error_code)) {
3272                 if (vcpu->arch.halt_request) {
3273                         vcpu->arch.halt_request = 0;
3274                         return kvm_emulate_halt(vcpu);
3275                 }
3276                 return 1;
3277         }
3278 
3279         ex_no = intr_info & INTR_INFO_VECTOR_MASK;
3280         switch (ex_no) {
3281         case DB_VECTOR:
3282                 dr6 = vmcs_readl(EXIT_QUALIFICATION);
3283                 if (!(vcpu->guest_debug &
3284                       (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
3285                         vcpu->arch.dr6 = dr6 | DR6_FIXED_1;
3286                         kvm_queue_exception(vcpu, DB_VECTOR);
3287                         return 1;
3288                 }
3289                 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
3290                 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
3291                 /* fall through */
3292         case BP_VECTOR:
3293                 /*
3294                  * Update instruction length as we may reinject #BP from
3295                  * user space while in guest debugging mode. Reading it for
3296                  * #DB as well causes no harm, it is not used in that case.
3297                  */
3298                 vmx->vcpu.arch.event_exit_inst_len =
3299                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
3300                 kvm_run->exit_reason = KVM_EXIT_DEBUG;
3301                 rip = kvm_rip_read(vcpu);
3302                 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
3303                 kvm_run->debug.arch.exception = ex_no;
3304                 break;
3305         default:
3306                 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
3307                 kvm_run->ex.exception = ex_no;
3308                 kvm_run->ex.error_code = error_code;
3309                 break;
3310         }
3311         return 0;
3312 }
3313 
3314 static int handle_external_interrupt(struct kvm_vcpu *vcpu)
3315 {
3316         ++vcpu->stat.irq_exits;
3317         return 1;
3318 }
3319 
3320 static int handle_triple_fault(struct kvm_vcpu *vcpu)
3321 {
3322         vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
3323         return 0;
3324 }
3325 
3326 static int handle_io(struct kvm_vcpu *vcpu)
3327 {
3328         unsigned long exit_qualification;
3329         int size, in, string;
3330         unsigned port;
3331 
3332         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
3333         string = (exit_qualification & 16) != 0;
3334         in = (exit_qualification & 8) != 0;
3335 
3336         ++vcpu->stat.io_exits;
3337 
3338         if (string || in)
3339                 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
3340 
3341         port = exit_qualification >> 16;
3342         size = (exit_qualification & 7) + 1;
3343         skip_emulated_instruction(vcpu);
3344 
3345         return kvm_fast_pio_out(vcpu, size, port);
3346 }
3347 
3348 static void
3349 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
3350 {
3351         /*
3352          * Patch in the VMCALL instruction:
3353          */
3354         hypercall[0] = 0x0f;
3355         hypercall[1] = 0x01;
3356         hypercall[2] = 0xc1;
3357 }
3358 
3359 static int handle_cr(struct kvm_vcpu *vcpu)
3360 {
3361         unsigned long exit_qualification, val;
3362         int cr;
3363         int reg;
3364         int err;
3365 
3366         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
3367         cr = exit_qualification & 15;
3368         reg = (exit_qualification >> 8) & 15;
3369         switch ((exit_qualification >> 4) & 3) {
3370         case 0: /* mov to cr */
3371                 val = kvm_register_read(vcpu, reg);
3372                 trace_kvm_cr_write(cr, val);
3373                 switch (cr) {
3374                 case 0:
3375                         err = kvm_set_cr0(vcpu, val);
3376                         kvm_complete_insn_gp(vcpu, err);
3377                         return 1;
3378                 case 3:
3379                         err = kvm_set_cr3(vcpu, val);
3380                         kvm_complete_insn_gp(vcpu, err);
3381                         return 1;
3382                 case 4:
3383                         err = kvm_set_cr4(vcpu, val);
3384                         kvm_complete_insn_gp(vcpu, err);
3385                         return 1;
3386                 case 8: {
3387                                 u8 cr8_prev = kvm_get_cr8(vcpu);
3388                                 u8 cr8 = kvm_register_read(vcpu, reg);
3389                                 err = kvm_set_cr8(vcpu, cr8);
3390                                 kvm_complete_insn_gp(vcpu, err);
3391                                 if (irqchip_in_kernel(vcpu->kvm))
3392                                         return 1;
3393                                 if (cr8_prev <= cr8)
3394                                         return 1;
3395                                 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
3396                                 return 0;
3397                         }
3398                 };
3399                 break;
3400         case 2: /* clts */
3401                 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
3402                 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
3403                 skip_emulated_instruction(vcpu);
3404                 vmx_fpu_activate(vcpu);
3405                 return 1;
3406         case 1: /*mov from cr*/
3407                 switch (cr) {
3408                 case 3:
3409                         val = kvm_read_cr3(vcpu);
3410                         kvm_register_write(vcpu, reg, val);
3411                         trace_kvm_cr_read(cr, val);
3412                         skip_emulated_instruction(vcpu);
3413                         return 1;
3414                 case 8:
3415                         val = kvm_get_cr8(vcpu);
3416                         kvm_register_write(vcpu, reg, val);
3417                         trace_kvm_cr_read(cr, val);
3418                         skip_emulated_instruction(vcpu);
3419                         return 1;
3420                 }
3421                 break;
3422         case 3: /* lmsw */
3423                 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
3424                 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
3425                 kvm_lmsw(vcpu, val);
3426 
3427                 skip_emulated_instruction(vcpu);
3428                 return 1;
3429         default:
3430                 break;
3431         }
3432         vcpu->run->exit_reason = 0;
3433         pr_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
3434                (int)(exit_qualification >> 4) & 3, cr);
3435         return 0;
3436 }
3437 
3438 static int handle_dr(struct kvm_vcpu *vcpu)
3439 {
3440         unsigned long exit_qualification;
3441         int dr, reg;
3442 
3443         /* Do not handle if the CPL > 0, will trigger GP on re-entry */
3444         if (!kvm_require_cpl(vcpu, 0))
3445                 return 1;
3446         dr = vmcs_readl(GUEST_DR7);
3447         if (dr & DR7_GD) {
3448                 /*
3449                  * As the vm-exit takes precedence over the debug trap, we
3450                  * need to emulate the latter, either for the host or the
3451                  * guest debugging itself.
3452                  */
3453                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
3454                         vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
3455                         vcpu->run->debug.arch.dr7 = dr;
3456                         vcpu->run->debug.arch.pc =
3457                                 vmcs_readl(GUEST_CS_BASE) +
3458                                 vmcs_readl(GUEST_RIP);
3459                         vcpu->run->debug.arch.exception = DB_VECTOR;
3460                         vcpu->run->exit_reason = KVM_EXIT_DEBUG;
3461                         return 0;
3462                 } else {
3463                         vcpu->arch.dr7 &= ~DR7_GD;
3464                         vcpu->arch.dr6 |= DR6_BD;
3465                         vmcs_writel(GUEST_DR7, vcpu->arch.dr7);
3466                         kvm_queue_exception(vcpu, DB_VECTOR);
3467                         return 1;
3468                 }
3469         }
3470 
3471         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
3472         dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
3473         reg = DEBUG_REG_ACCESS_REG(exit_qualification);
3474         if (exit_qualification & TYPE_MOV_FROM_DR) {
3475                 unsigned long val;
3476                 if (!kvm_get_dr(vcpu, dr, &val))
3477                         kvm_register_write(vcpu, reg, val);
3478         } else
3479                 kvm_set_dr(vcpu, dr, vcpu->arch.regs[reg]);
3480         skip_emulated_instruction(vcpu);
3481         return 1;
3482 }
3483 
3484 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
3485 {
3486         vmcs_writel(GUEST_DR7, val);
3487 }
3488 
3489 static int handle_cpuid(struct kvm_vcpu *vcpu)
3490 {
3491         kvm_emulate_cpuid(vcpu);
3492         return 1;
3493 }
3494 
3495 static int handle_rdmsr(struct kvm_vcpu *vcpu)
3496 {
3497         u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
3498         u64 data;
3499 
3500         if (vmx_get_msr(vcpu, ecx, &data)) {
3501                 trace_kvm_msr_read_ex(ecx);
3502                 kvm_inject_gp(vcpu, 0);
3503                 return 1;
3504         }
3505 
3506         trace_kvm_msr_read(ecx, data);
3507 
3508         /* FIXME: handling of bits 32:63 of rax, rdx */
3509         vcpu->arch.regs[VCPU_REGS_RAX] = data & -1u;
3510         vcpu->arch.regs[VCPU_REGS_RDX] = (data >> 32) & -1u;
3511         skip_emulated_instruction(vcpu);
3512         return 1;
3513 }
3514 
3515 static int handle_wrmsr(struct kvm_vcpu *vcpu)
3516 {
3517         u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
3518         u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
3519                 | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
3520 
3521         if (vmx_set_msr(vcpu, ecx, data) != 0) {
3522                 trace_kvm_msr_write_ex(ecx, data);
3523                 kvm_inject_gp(vcpu, 0);
3524                 return 1;
3525         }
3526 
3527         trace_kvm_msr_write(ecx, data);
3528         skip_emulated_instruction(vcpu);
3529         return 1;
3530 }
3531 
3532 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
3533 {
3534         kvm_make_request(KVM_REQ_EVENT, vcpu);
3535         return 1;
3536 }
3537 
3538 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
3539 {
3540         u32 cpu_based_vm_exec_control;
3541 
3542         /* clear pending irq */
3543         cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
3544         cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
3545         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
3546 
3547         kvm_make_request(KVM_REQ_EVENT, vcpu);
3548 
3549         ++vcpu->stat.irq_window_exits;
3550 
3551         /*
3552          * If the user space waits to inject interrupts, exit as soon as
3553          * possible
3554          */
3555         if (!irqchip_in_kernel(vcpu->kvm) &&
3556             vcpu->run->request_interrupt_window &&
3557             !kvm_cpu_has_interrupt(vcpu)) {
3558                 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
3559                 return 0;
3560         }
3561         return 1;
3562 }
3563 
3564 static int handle_halt(struct kvm_vcpu *vcpu)
3565 {
3566         skip_emulated_instruction(vcpu);
3567         return kvm_emulate_halt(vcpu);
3568 }
3569 
3570 static int handle_vmcall(struct kvm_vcpu *vcpu)
3571 {
3572         skip_emulated_instruction(vcpu);
3573         kvm_emulate_hypercall(vcpu);
3574         return 1;
3575 }
3576 
3577 static int handle_vmx_insn(struct kvm_vcpu *vcpu)
3578 {
3579         kvm_queue_exception(vcpu, UD_VECTOR);
3580         return 1;
3581 }
3582 
3583 static int handle_invd(struct kvm_vcpu *vcpu)
3584 {
3585         return emulate_instruction(vcpu, 0) == EMULATE_DONE;
3586 }
3587 
3588 static int handle_invlpg(struct kvm_vcpu *vcpu)
3589 {
3590         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
3591 
3592         kvm_mmu_invlpg(vcpu, exit_qualification);
3593         skip_emulated_instruction(vcpu);
3594         return 1;
3595 }
3596 
3597 static int handle_wbinvd(struct kvm_vcpu *vcpu)
3598 {
3599         skip_emulated_instruction(vcpu);
3600         kvm_emulate_wbinvd(vcpu);
3601         return 1;
3602 }
3603 
3604 static int handle_xsetbv(struct kvm_vcpu *vcpu)
3605 {
3606         u64 new_bv = kvm_read_edx_eax(vcpu);
3607         u32 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
3608 
3609         if (kvm_set_xcr(vcpu, index, new_bv) == 0)
3610                 skip_emulated_instruction(vcpu);
3611         return 1;
3612 }
3613 
3614 static int handle_apic_access(struct kvm_vcpu *vcpu)
3615 {
3616         return emulate_instruction(vcpu, 0) == EMULATE_DONE;
3617 }
3618 
3619 static int handle_task_switch(struct kvm_vcpu *vcpu)
3620 {
3621         struct vcpu_vmx *vmx = to_vmx(vcpu);
3622         unsigned long exit_qualification;
3623         bool has_error_code = false;
3624         u32 error_code = 0;
3625         u16 tss_selector;
3626         int reason, type, idt_v;
3627 
3628         idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
3629         type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
3630 
3631         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
3632 
3633         reason = (u32)exit_qualification >> 30;
3634         if (reason == TASK_SWITCH_GATE && idt_v) {
3635                 switch (type) {
3636                 case INTR_TYPE_NMI_INTR:
3637                         vcpu->arch.nmi_injected = false;
3638                         vmx_set_nmi_mask(vcpu, true);
3639                         break;
3640                 case INTR_TYPE_EXT_INTR:
3641                 case INTR_TYPE_SOFT_INTR:
3642                         kvm_clear_interrupt_queue(vcpu);
3643                         break;
3644                 case INTR_TYPE_HARD_EXCEPTION:
3645                         if (vmx->idt_vectoring_info &
3646                             VECTORING_INFO_DELIVER_CODE_MASK) {
3647                                 has_error_code = true;
3648                                 error_code =
3649                                         vmcs_read32(IDT_VECTORING_ERROR_CODE);
3650                         }
3651                         /* fall through */
3652                 case INTR_TYPE_SOFT_EXCEPTION:
3653                         kvm_clear_exception_queue(vcpu);
3654                         break;
3655                 default:
3656                         break;
3657                 }
3658         }
3659         tss_selector = exit_qualification;
3660 
3661         if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
3662                        type != INTR_TYPE_EXT_INTR &&
3663                        type != INTR_TYPE_NMI_INTR))
3664                 skip_emulated_instruction(vcpu);
3665 
3666         if (kvm_task_switch(vcpu, tss_selector, reason,
3667                                 has_error_code, error_code) == EMULATE_FAIL) {
3668                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
3669                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
3670                 vcpu->run->internal.ndata = 0;
3671                 return 0;
3672         }
3673 
3674         /* clear all local breakpoint enable flags */
3675         vmcs_writel(GUEST_DR7, vmcs_readl(GUEST_DR7) & ~55);
3676 
3677         /*
3678          * TODO: What about debug traps on tss switch?
3679          *       Are we supposed to inject them and update dr6?
3680          */
3681 
3682         return 1;
3683 }
3684 
3685 static int handle_ept_violation(struct kvm_vcpu *vcpu)
3686 {
3687         unsigned long exit_qualification;
3688         gpa_t gpa;
3689         int gla_validity;
3690 
3691         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
3692 
3693         if (exit_qualification & (1 << 6)) {
3694                 printk(KERN_ERR "EPT: GPA exceeds GAW!\n");
3695                 return -EINVAL;
3696         }
3697 
3698         gla_validity = (exit_qualification >> 7) & 0x3;
3699         if (gla_validity != 0x3 && gla_validity != 0x1 && gla_validity != 0) {
3700                 printk(KERN_ERR "EPT: Handling EPT violation failed!\n");
3701                 printk(KERN_ERR "EPT: GPA: 0x%lx, GVA: 0x%lx\n",
3702                         (long unsigned int)vmcs_read64(GUEST_PHYSICAL_ADDRESS),
3703                         vmcs_readl(GUEST_LINEAR_ADDRESS));
3704                 printk(KERN_ERR "EPT: Exit qualification is 0x%lx\n",
3705                         (long unsigned int)exit_qualification);
3706                 vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
3707                 vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_VIOLATION;
3708                 return 0;
3709         }
3710 
3711         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
3712         trace_kvm_page_fault(gpa, exit_qualification);
3713         return kvm_mmu_page_fault(vcpu, gpa, exit_qualification & 0x3, NULL, 0);
3714 }
3715 
3716 static u64 ept_rsvd_mask(u64 spte, int level)
3717 {
3718         int i;
3719         u64 mask = 0;
3720 
3721         for (i = 51; i > boot_cpu_data.x86_phys_bits; i--)
3722                 mask |= (1ULL << i);
3723 
3724         if (level > 2)
3725                 /* bits 7:3 reserved */
3726                 mask |= 0xf8;
3727         else if (level == 2) {
3728                 if (spte & (1ULL << 7))
3729                         /* 2MB ref, bits 20:12 reserved */
3730                         mask |= 0x1ff000;
3731                 else
3732                         /* bits 6:3 reserved */
3733                         mask |= 0x78;
3734         }
3735 
3736         return mask;
3737 }
3738 
3739 static void ept_misconfig_inspect_spte(struct kvm_vcpu *vcpu, u64 spte,
3740                                        int level)
3741 {
3742         printk(KERN_ERR "%s: spte 0x%llx level %d\n", __func__, spte, level);
3743 
3744         /* 010b (write-only) */
3745         WARN_ON((spte & 0x7) == 0x2);
3746 
3747         /* 110b (write/execute) */
3748         WARN_ON((spte & 0x7) == 0x6);
3749 
3750         /* 100b (execute-only) and value not supported by logical processor */
3751         if (!cpu_has_vmx_ept_execute_only())
3752                 WARN_ON((spte & 0x7) == 0x4);
3753 
3754         /* not 000b */
3755         if ((spte & 0x7)) {
3756                 u64 rsvd_bits = spte & ept_rsvd_mask(spte, level);
3757 
3758                 if (rsvd_bits != 0) {
3759                         printk(KERN_ERR "%s: rsvd_bits = 0x%llx\n",
3760                                          __func__, rsvd_bits);
3761                         WARN_ON(1);
3762                 }
3763 
3764                 if (level == 1 || (level == 2 && (spte & (1ULL << 7)))) {
3765                         u64 ept_mem_type = (spte & 0x38) >> 3;
3766 
3767                         if (ept_mem_type == 2 || ept_mem_type == 3 ||
3768                             ept_mem_type == 7) {
3769                                 printk(KERN_ERR "%s: ept_mem_type=0x%llx\n",
3770                                                 __func__, ept_mem_type);
3771                                 WARN_ON(1);
3772                         }
3773                 }
3774         }
3775 }
3776 
3777 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
3778 {
3779         u64 sptes[4];
3780         int nr_sptes, i;
3781         gpa_t gpa;
3782 
3783         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
3784 
3785         printk(KERN_ERR "EPT: Misconfiguration.\n");
3786         printk(KERN_ERR "EPT: GPA: 0x%llx\n", gpa);
3787 
3788         nr_sptes = kvm_mmu_get_spte_hierarchy(vcpu, gpa, sptes);
3789 
3790         for (i = PT64_ROOT_LEVEL; i > PT64_ROOT_LEVEL - nr_sptes; --i)
3791                 ept_misconfig_inspect_spte(vcpu, sptes[i-1], i);
3792 
3793         vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
3794         vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_MISCONFIG;
3795 
3796         return 0;
3797 }
3798 
3799 static int handle_nmi_window(struct kvm_vcpu *vcpu)
3800 {
3801         u32 cpu_based_vm_exec_control;
3802 
3803         /* clear pending NMI */
3804         cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
3805         cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
3806         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
3807         ++vcpu->stat.nmi_window_exits;
3808         kvm_make_request(KVM_REQ_EVENT, vcpu);
3809 
3810         return 1;
3811 }
3812 
3813 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
3814 {
3815         struct vcpu_vmx *vmx = to_vmx(vcpu);
3816         enum emulation_result err = EMULATE_DONE;
3817         int ret = 1;
3818         u32 cpu_exec_ctrl;
3819         bool intr_window_requested;
3820 
3821         cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
3822         intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
3823 
3824         while (!guest_state_valid(vcpu)) {
3825                 if (intr_window_requested
3826                     && (kvm_get_rflags(&vmx->vcpu) & X86_EFLAGS_IF))
3827                         return handle_interrupt_window(&vmx->vcpu);
3828 
3829                 err = emulate_instruction(vcpu, 0);
3830 
3831                 if (err == EMULATE_DO_MMIO) {
3832                         ret = 0;
3833                         goto out;
3834                 }
3835 
3836                 if (err != EMULATE_DONE)
3837                         return 0;
3838 
3839                 if (vcpu->arch.halt_request) {
3840                         vcpu->arch.halt_request = 0;
3841                         ret = kvm_emulate_halt(vcpu);
3842                         goto out;
3843                 }
3844 
3845                 if (signal_pending(current))
3846                         goto out;
3847                 if (need_resched())
3848                         schedule();
3849         }
3850 
3851         vmx->emulation_required = 0;
3852 out:
3853         return ret;
3854 }
3855 
3856 /*
3857  * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
3858  * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
3859  */
3860 static int handle_pause(struct kvm_vcpu *vcpu)
3861 {
3862         skip_emulated_instruction(vcpu);
3863         kvm_vcpu_on_spin(vcpu);
3864 
3865         return 1;
3866 }
3867 
3868 static int handle_invalid_op(struct kvm_vcpu *vcpu)
3869 {
3870         kvm_queue_exception(vcpu, UD_VECTOR);
3871         return 1;
3872 }
3873 
3874 /*
3875  * The exit handlers return 1 if the exit was handled fully and guest execution
3876  * may resume.  Otherwise they set the kvm_run parameter to indicate what needs
3877  * to be done to userspace and return 0.
3878  */
3879 static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
3880         [EXIT_REASON_EXCEPTION_NMI]           = handle_exception,
3881         [EXIT_REASON_EXTERNAL_INTERRUPT]      = handle_external_interrupt,
3882         [EXIT_REASON_TRIPLE_FAULT]            = handle_triple_fault,
3883         [EXIT_REASON_NMI_WINDOW]              = handle_nmi_window,
3884         [EXIT_REASON_IO_INSTRUCTION]          = handle_io,
3885         [EXIT_REASON_CR_ACCESS]               = handle_cr,
3886         [EXIT_REASON_DR_ACCESS]               = handle_dr,
3887         [EXIT_REASON_CPUID]                   = handle_cpuid,
3888         [EXIT_REASON_MSR_READ]                = handle_rdmsr,
3889         [EXIT_REASON_MSR_WRITE]               = handle_wrmsr,
3890         [EXIT_REASON_PENDING_INTERRUPT]       = handle_interrupt_window,
3891         [EXIT_REASON_HLT]                     = handle_halt,
3892         [EXIT_REASON_INVD]                    = handle_invd,
3893         [EXIT_REASON_INVLPG]                  = handle_invlpg,
3894         [EXIT_REASON_VMCALL]                  = handle_vmcall,
3895         [EXIT_REASON_VMCLEAR]                 = handle_vmx_insn,
3896         [EXIT_REASON_VMLAUNCH]                = handle_vmx_insn,
3897         [EXIT_REASON_VMPTRLD]                 = handle_vmx_insn,
3898         [EXIT_REASON_VMPTRST]                 = handle_vmx_insn,
3899         [EXIT_REASON_VMREAD]                  = handle_vmx_insn,
3900         [EXIT_REASON_VMRESUME]                = handle_vmx_insn,
3901         [EXIT_REASON_VMWRITE]                 = handle_vmx_insn,
3902         [EXIT_REASON_VMOFF]                   = handle_vmx_insn,
3903         [EXIT_REASON_VMON]                    = handle_vmx_insn,
3904         [EXIT_REASON_TPR_BELOW_THRESHOLD]     = handle_tpr_below_threshold,
3905         [EXIT_REASON_APIC_ACCESS]             = handle_apic_access,
3906         [EXIT_REASON_WBINVD]                  = handle_wbinvd,
3907         [EXIT_REASON_XSETBV]                  = handle_xsetbv,
3908         [EXIT_REASON_TASK_SWITCH]             = handle_task_switch,
3909         [EXIT_REASON_MCE_DURING_VMENTRY]      = handle_machine_check,
3910         [EXIT_REASON_EPT_VIOLATION]           = handle_ept_violation,
3911         [EXIT_REASON_EPT_MISCONFIG]           = handle_ept_misconfig,
3912         [EXIT_REASON_PAUSE_INSTRUCTION]       = handle_pause,
3913         [EXIT_REASON_MWAIT_INSTRUCTION]       = handle_invalid_op,
3914         [EXIT_REASON_MONITOR_INSTRUCTION]     = handle_invalid_op,
3915 };
3916 
3917 static const int kvm_vmx_max_exit_handlers =
3918         ARRAY_SIZE(kvm_vmx_exit_handlers);
3919 
3920 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
3921 {
3922         *info1 = vmcs_readl(EXIT_QUALIFICATION);
3923         *info2 = vmcs_read32(VM_EXIT_INTR_INFO);
3924 }
3925 
3926 /*
3927  * The guest has exited.  See if we can fix it or if we need userspace
3928  * assistance.
3929  */
3930 static int vmx_handle_exit(struct kvm_vcpu *vcpu)
3931 {
3932         struct vcpu_vmx *vmx = to_vmx(vcpu);
3933         u32 exit_reason = vmx->exit_reason;
3934         u32 vectoring_info = vmx->idt_vectoring_info;
3935 
3936         trace_kvm_exit(exit_reason, vcpu, KVM_ISA_VMX);
3937 
3938         /* If guest state is invalid, start emulating */
3939         if (vmx->emulation_required && emulate_invalid_guest_state)
3940                 return handle_invalid_guest_state(vcpu);
3941 
3942         if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
3943                 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
3944                 vcpu->run->fail_entry.hardware_entry_failure_reason
3945                         = exit_reason;
3946                 return 0;
3947         }
3948 
3949         if (unlikely(vmx->fail)) {
3950                 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
3951                 vcpu->run->fail_entry.hardware_entry_failure_reason
3952                         = vmcs_read32(VM_INSTRUCTION_ERROR);
3953                 return 0;
3954         }
3955 
3956         if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
3957                         (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
3958                         exit_reason != EXIT_REASON_EPT_VIOLATION &&
3959                         exit_reason != EXIT_REASON_TASK_SWITCH))
3960                 printk(KERN_WARNING "%s: unexpected, valid vectoring info "
3961                        "(0x%x) and exit reason is 0x%x\n",
3962                        __func__, vectoring_info, exit_reason);
3963 
3964         if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked)) {
3965                 if (vmx_interrupt_allowed(vcpu)) {
3966                         vmx->soft_vnmi_blocked = 0;
3967                 } else if (vmx->vnmi_blocked_time > 1000000000LL &&
3968                            vcpu->arch.nmi_pending) {
3969                         /*
3970                          * This CPU don't support us in finding the end of an
3971                          * NMI-blocked window if the guest runs with IRQs
3972                          * disabled. So we pull the trigger after 1 s of
3973                          * futile waiting, but inform the user about this.
3974                          */
3975                         printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
3976                                "state on VCPU %d after 1 s timeout\n",
3977                                __func__, vcpu->vcpu_id);
3978                         vmx->soft_vnmi_blocked = 0;
3979                 }
3980         }
3981 
3982         if (exit_reason < kvm_vmx_max_exit_handlers
3983             && kvm_vmx_exit_handlers[exit_reason])
3984                 return kvm_vmx_exit_handlers[exit_reason](vcpu);
3985         else {
3986                 vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
3987                 vcpu->run->hw.hardware_exit_reason = exit_reason;
3988         }
3989         return 0;
3990 }
3991 
3992 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
3993 {
3994         if (irr == -1 || tpr < irr) {
3995                 vmcs_write32(TPR_THRESHOLD, 0);
3996                 return;
3997         }
3998 
3999         vmcs_write32(TPR_THRESHOLD, irr);
4000 }
4001 
4002 static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
4003 {
4004         u32 exit_intr_info;
4005 
4006         if (!(vmx->exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
4007               || vmx->exit_reason == EXIT_REASON_EXCEPTION_NMI))
4008                 return;
4009 
4010         vmx->exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
4011         exit_intr_info = vmx->exit_intr_info;
4012 
4013         /* Handle machine checks before interrupts are enabled */
4014         if (is_machine_check(exit_intr_info))
4015                 kvm_machine_check();
4016 
4017         /* We need to handle NMIs before interrupts are enabled */
4018         if ((exit_intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR &&
4019             (exit_intr_info & INTR_INFO_VALID_MASK)) {
4020                 kvm_before_handle_nmi(&vmx->vcpu);
4021                 asm("int $2");
4022                 kvm_after_handle_nmi(&vmx->vcpu);
4023         }
4024 }
4025 
4026 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
4027 {
4028         u32 exit_intr_info;
4029         bool unblock_nmi;
4030         u8 vector;
4031         bool idtv_info_valid;
4032 
4033         idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
4034 
4035         if (cpu_has_virtual_nmis()) {
4036                 if (vmx->nmi_known_unmasked)
4037                         return;
4038                 /*
4039                  * Can't use vmx->exit_intr_info since we're not sure what
4040                  * the exit reason is.
4041                  */
4042                 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
4043                 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
4044                 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
4045                 /*
4046                  * SDM 3: 27.7.1.2 (September 2008)
4047                  * Re-set bit "block by NMI" before VM entry if vmexit caused by
4048                  * a guest IRET fault.
4049                  * SDM 3: 23.2.2 (September 2008)
4050                  * Bit 12 is undefined in any of the following cases:
4051                  *  If the VM exit sets the valid bit in the IDT-vectoring
4052                  *   information field.
4053                  *  If the VM exit is due to a double fault.
4054                  */
4055                 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
4056                     vector != DF_VECTOR && !idtv_info_valid)
4057                         vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
4058                                       GUEST_INTR_STATE_NMI);
4059                 else
4060                         vmx->nmi_known_unmasked =
4061                                 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
4062                                   & GUEST_INTR_STATE_NMI);
4063         } else if (unlikely(vmx->soft_vnmi_blocked))
4064                 vmx->vnmi_blocked_time +=
4065                         ktime_to_ns(ktime_sub(ktime_get(), vmx->entry_time));
4066 }
4067 
4068 static void __vmx_complete_interrupts(struct vcpu_vmx *vmx,
4069                                       u32 idt_vectoring_info,
4070                                       int instr_len_field,
4071                                       int error_code_field)
4072 {
4073         u8 vector;
4074         int type;
4075         bool idtv_info_valid;
4076 
4077         idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
4078 
4079         vmx->vcpu.arch.nmi_injected = false;
4080         kvm_clear_exception_queue(&vmx->vcpu);
4081         kvm_clear_interrupt_queue(&vmx->vcpu);
4082 
4083         if (!idtv_info_valid)
4084                 return;
4085 
4086         kvm_make_request(KVM_REQ_EVENT, &vmx->vcpu);
4087 
4088         vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
4089         type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
4090 
4091         switch (type) {
4092         case INTR_TYPE_NMI_INTR:
4093                 vmx->vcpu.arch.nmi_injected = true;
4094                 /*
4095                  * SDM 3: 27.7.1.2 (September 2008)
4096                  * Clear bit "block by NMI" before VM entry if a NMI
4097                  * delivery faulted.
4098                  */
4099                 vmx_set_nmi_mask(&vmx->vcpu, false);
4100                 break;
4101         case INTR_TYPE_SOFT_EXCEPTION:
4102                 vmx->vcpu.arch.event_exit_inst_len =
4103                         vmcs_read32(instr_len_field);
4104                 /* fall through */
4105         case INTR_TYPE_HARD_EXCEPTION:
4106                 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
4107                         u32 err = vmcs_read32(error_code_field);
4108                         kvm_queue_exception_e(&vmx->vcpu, vector, err);
4109                 } else
4110                         kvm_queue_exception(&vmx->vcpu, vector);
4111                 break;
4112         case INTR_TYPE_SOFT_INTR:
4113                 vmx->vcpu.arch.event_exit_inst_len =
4114                         vmcs_read32(instr_len_field);
4115                 /* fall through */
4116         case INTR_TYPE_EXT_INTR:
4117                 kvm_queue_interrupt(&vmx->vcpu, vector,
4118                         type == INTR_TYPE_SOFT_INTR);
4119                 break;
4120         default:
4121                 break;
4122         }
4123 }
4124 
4125 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
4126 {
4127         __vmx_complete_interrupts(vmx, vmx->idt_vectoring_info,
4128                                   VM_EXIT_INSTRUCTION_LEN,
4129                                   IDT_VECTORING_ERROR_CODE);
4130 }
4131 
4132 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
4133 {
4134         __vmx_complete_interrupts(to_vmx(vcpu),
4135                                   vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
4136                                   VM_ENTRY_INSTRUCTION_LEN,
4137                                   VM_ENTRY_EXCEPTION_ERROR_CODE);
4138 
4139         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
4140 }
4141 
4142 #ifdef CONFIG_X86_64
4143 #define R "r"
4144 #define Q "q"
4145 #else
4146 #define R "e"
4147 #define Q "l"
4148 #endif
4149 
4150 static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
4151 {
4152         struct vcpu_vmx *vmx = to_vmx(vcpu);
4153 
4154         /* Record the guest's net vcpu time for enforced NMI injections. */
4155         if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked))
4156                 vmx->entry_time = ktime_get();
4157 
4158         /* Don't enter VMX if guest state is invalid, let the exit handler
4159            start emulation until we arrive back to a valid state */
4160         if (vmx->emulation_required && emulate_invalid_guest_state)
4161                 return;
4162 
4163         if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
4164                 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
4165         if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
4166                 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
4167 
4168         /* When single-stepping over STI and MOV SS, we must clear the
4169          * corresponding interruptibility bits in the guest state. Otherwise
4170          * vmentry fails as it then expects bit 14 (BS) in pending debug
4171          * exceptions being set, but that's not correct for the guest debugging
4172          * case. */
4173         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
4174                 vmx_set_interrupt_shadow(vcpu, 0);
4175 
4176         asm(
4177                 /* Store host registers */
4178                 "push %%"R"dx; push %%"R"bp;"
4179                 "push %%"R"cx \n\t" /* placeholder for guest rcx */
4180                 "push %%"R"cx \n\t"
4181                 "cmp %%"R"sp, %c[host_rsp](%0) \n\t"
4182                 "je 1f \n\t"
4183                 "mov %%"R"sp, %c[host_rsp](%0) \n\t"
4184                 __ex(ASM_VMX_VMWRITE_RSP_RDX) "\n\t"
4185                 "1: \n\t"
4186                 /* Reload cr2 if changed */
4187                 "mov %c[cr2](%0), %%"R"ax \n\t"
4188                 "mov %%cr2, %%"R"dx \n\t"
4189                 "cmp %%"R"ax, %%"R"dx \n\t"
4190                 "je 2f \n\t"
4191                 "mov %%"R"ax, %%cr2 \n\t"
4192                 "2: \n\t"
4193                 /* Check if vmlaunch of vmresume is needed */
4194                 "cmpl $0, %c[launched](%0) \n\t"
4195                 /* Load guest registers.  Don't clobber flags. */
4196                 "mov %c[rax](%0), %%"R"ax \n\t"
4197                 "mov %c[rbx](%0), %%"R"bx \n\t"
4198                 "mov %c[rdx](%0), %%"R"dx \n\t"
4199                 "mov %c[rsi](%0), %%"R"si \n\t"
4200                 "mov %c[rdi](%0), %%"R"di \n\t"
4201                 "mov %c[rbp](%0), %%"R"bp \n\t"
4202 #ifdef CONFIG_X86_64
4203                 "mov %c[r8](%0),  %%r8  \n\t"
4204                 "mov %c[r9](%0),  %%r9  \n\t"
4205                 "mov %c[r10](%0), %%r10 \n\t"
4206                 "mov %c[r11](%0), %%r11 \n\t"
4207                 "mov %c[r12](%0), %%r12 \n\t"
4208                 "mov %c[r13](%0), %%r13 \n\t"
4209                 "mov %c[r14](%0), %%r14 \n\t"
4210                 "mov %c[r15](%0), %%r15 \n\t"
4211 #endif
4212                 "mov %c[rcx](%0), %%"R"cx \n\t" /* kills %0 (ecx) */
4213 
4214                 /* Enter guest mode */
4215                 "jne .Llaunched \n\t"
4216                 __ex(ASM_VMX_VMLAUNCH) "\n\t"
4217                 "jmp .Lkvm_vmx_return \n\t"
4218                 ".Llaunched: " __ex(ASM_VMX_VMRESUME) "\n\t"
4219                 ".Lkvm_vmx_return: "
4220                 /* Save guest registers, load host registers, keep flags */
4221                 "mov %0, %c[wordsize](%%"R"sp) \n\t"
4222                 "pop %0 \n\t"
4223                 "mov %%"R"ax, %c[rax](%0) \n\t"
4224                 "mov %%"R"bx, %c[rbx](%0) \n\t"
4225                 "pop"Q" %c[rcx](%0) \n\t"
4226                 "mov %%"R"dx, %c[rdx](%0) \n\t"
4227                 "mov %%"R"si, %c[rsi](%0) \n\t"
4228                 "mov %%"R"di, %c[rdi](%0) \n\t"
4229                 "mov %%"R"bp, %c[rbp](%0) \n\t"
4230 #ifdef CONFIG_X86_64
4231                 "mov %%r8,  %c[r8](%0) \n\t"
4232                 "mov %%r9,  %c[r9](%0) \n\t"
4233                 "mov %%r10, %c[r10](%0) \n\t"
4234                 "mov %%r11, %c[r11](%0) \n\t"
4235                 "mov %%r12, %c[r12](%0) \n\t"
4236                 "mov %%r13, %c[r13](%0) \n\t"
4237                 "mov %%r14, %c[r14](%0) \n\t"
4238                 "mov %%r15, %c[r15](%0) \n\t"
4239 #endif
4240                 "mov %%cr2, %%"R"ax   \n\t"
4241                 "mov %%"R"ax, %c[cr2](%0) \n\t"
4242 
4243                 "pop  %%"R"bp; pop  %%"R"dx \n\t"
4244                 "setbe %c[fail](%0) \n\t"
4245               : : "c"(vmx), "d"((unsigned long)HOST_RSP),
4246                 [launched]"i"(offsetof(struct vcpu_vmx, launched)),
4247                 [fail]"i"(offsetof(struct vcpu_vmx, fail)),
4248                 [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)),
4249                 [rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])),
4250                 [rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])),
4251                 [rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])),
4252                 [rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])),
4253                 [rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])),
4254                 [rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])),
4255                 [rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])),
4256 #ifdef CONFIG_X86_64
4257                 [r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])),
4258                 [r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])),
4259                 [r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])),
4260                 [r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])),
4261                 [r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])),
4262                 [r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])),
4263                 [r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])),
4264                 [r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])),
4265 #endif
4266                 [cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2)),
4267                 [wordsize]"i"(sizeof(ulong))
4268               : "cc", "memory"
4269                 , R"ax", R"bx", R"di", R"si"
4270 #ifdef CONFIG_X86_64
4271                 , "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
4272 #endif
4273               );
4274 
4275         vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
4276                                   | (1 << VCPU_EXREG_RFLAGS)
4277                                   | (1 << VCPU_EXREG_CPL)
4278                                   | (1 << VCPU_EXREG_PDPTR)
4279                                   | (1 << VCPU_EXREG_SEGMENTS)
4280                                   | (1 << VCPU_EXREG_CR3));
4281         vcpu->arch.regs_dirty = 0;
4282 
4283         vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
4284 
4285         asm("mov %0, %%ds; mov %0, %%es" : : "r"(__USER_DS));
4286         vmx->launched = 1;
4287 
4288         vmx->exit_reason = vmcs_read32(VM_EXIT_REASON);
4289 
4290         vmx_complete_atomic_exit(vmx);
4291         vmx_recover_nmi_blocking(vmx);
4292         vmx_complete_interrupts(vmx);
4293 }
4294 
4295 #undef R
4296 #undef Q
4297 
4298 static void vmx_free_vmcs(struct kvm_vcpu *vcpu)
4299 {
4300         struct vcpu_vmx *vmx = to_vmx(vcpu);
4301 
4302         if (vmx->vmcs) {
4303                 vcpu_clear(vmx);
4304                 free_vmcs(vmx->vmcs);
4305                 vmx->vmcs = NULL;
4306         }
4307 }
4308 
4309 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
4310 {
4311         struct vcpu_vmx *vmx = to_vmx(vcpu);
4312 
4313         free_vpid(vmx);
4314         vmx_free_vmcs(vcpu);
4315         kfree(vmx->guest_msrs);
4316         kvm_vcpu_uninit(vcpu);
4317         kmem_cache_free(kvm_vcpu_cache, vmx);
4318 }
4319 
4320 static inline void vmcs_init(struct vmcs *vmcs)
4321 {
4322         u64 phys_addr = __pa(per_cpu(vmxarea, raw_smp_processor_id()));
4323 
4324         if (!vmm_exclusive)
4325                 kvm_cpu_vmxon(phys_addr);
4326 
4327         vmcs_clear(vmcs);
4328 
4329         if (!vmm_exclusive)
4330                 kvm_cpu_vmxoff();
4331 }
4332 
4333 static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
4334 {
4335         int err;
4336         struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
4337         int cpu;
4338 
4339         if (!vmx)
4340                 return ERR_PTR(-ENOMEM);
4341 
4342         allocate_vpid(vmx);
4343 
4344         err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
4345         if (err)
4346                 goto free_vcpu;
4347 
4348         vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
4349         err = -ENOMEM;
4350         if (!vmx->guest_msrs) {
4351                 goto uninit_vcpu;
4352         }
4353 
4354         vmx->vmcs = alloc_vmcs();
4355         if (!vmx->vmcs)
4356                 goto free_msrs;
4357 
4358         vmcs_init(vmx->vmcs);
4359 
4360         cpu = get_cpu();
4361         vmx_vcpu_load(&vmx->vcpu, cpu);
4362         vmx->vcpu.cpu = cpu;
4363         err = vmx_vcpu_setup(vmx);
4364         vmx_vcpu_put(&vmx->vcpu);
4365         put_cpu();
4366         if (err)
4367                 goto free_vmcs;
4368         if (vm_need_virtualize_apic_accesses(kvm))
4369                 err = alloc_apic_access_page(kvm);
4370                 if (err)
4371                         goto free_vmcs;
4372 
4373         if (enable_ept) {
4374                 if (!kvm->arch.ept_identity_map_addr)
4375                         kvm->arch.ept_identity_map_addr =
4376                                 VMX_EPT_IDENTITY_PAGETABLE_ADDR;
4377                 err = -ENOMEM;
4378                 if (alloc_identity_pagetable(kvm) != 0)
4379                         goto free_vmcs;
4380                 if (!init_rmode_identity_map(kvm))
4381                         goto free_vmcs;
4382         }
4383 
4384         return &vmx->vcpu;
4385 
4386 free_vmcs:
4387         free_vmcs(vmx->vmcs);
4388 free_msrs:
4389         kfree(vmx->guest_msrs);
4390 uninit_vcpu:
4391         kvm_vcpu_uninit(&vmx->vcpu);
4392 free_vcpu:
4393         free_vpid(vmx);
4394         kmem_cache_free(kvm_vcpu_cache, vmx);
4395         return ERR_PTR(err);
4396 }
4397 
4398 static void __init vmx_check_processor_compat(void *rtn)
4399 {
4400         struct vmcs_config vmcs_conf;
4401 
4402         *(int *)rtn = 0;
4403         if (setup_vmcs_config(&vmcs_conf) < 0)
4404                 *(int *)rtn = -EIO;
4405         if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
4406                 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
4407                                 smp_processor_id());
4408                 *(int *)rtn = -EIO;
4409         }
4410 }
4411 
4412 static int get_ept_level(void)
4413 {
4414         return VMX_EPT_DEFAULT_GAW + 1;
4415 }
4416 
4417 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
4418 {
4419         u64 ret;
4420 
4421         /* For VT-d and EPT combination
4422          * 1. MMIO: always map as UC
4423          * 2. EPT with VT-d:
4424          *   a. VT-d without snooping control feature: can't guarantee the
4425          *      result, try to trust guest.
4426          *   b. VT-d with snooping control feature: snooping control feature of
4427          *      VT-d engine can guarantee the cache correctness. Just set it
4428          *      to WB to keep consistent with host. So the same as item 3.
4429          * 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
4430          *    consistent with host MTRR
4431          */
4432         if (is_mmio)
4433                 ret = MTRR_TYPE_UNCACHABLE << VMX_EPT_MT_EPTE_SHIFT;
4434         else if (vcpu->kvm->arch.iommu_domain &&
4435                 !(vcpu->kvm->arch.iommu_flags & KVM_IOMMU_CACHE_COHERENCY))
4436                 ret = kvm_get_guest_memory_type(vcpu, gfn) <<
4437                       VMX_EPT_MT_EPTE_SHIFT;
4438         else
4439                 ret = (MTRR_TYPE_WRBACK << VMX_EPT_MT_EPTE_SHIFT)
4440                         | VMX_EPT_IPAT_BIT;
4441 
4442         return ret;
4443 }
4444 
4445 #define _ER(x) { EXIT_REASON_##x, #x }
4446 
4447 static const struct trace_print_flags vmx_exit_reasons_str[] = {
4448         _ER(EXCEPTION_NMI),
4449         _ER(EXTERNAL_INTERRUPT),
4450         _ER(TRIPLE_FAULT),
4451         _ER(PENDING_INTERRUPT),
4452         _ER(NMI_WINDOW),
4453         _ER(TASK_SWITCH),
4454         _ER(CPUID),
4455         _ER(HLT),
4456         _ER(INVLPG),
4457         _ER(RDPMC),
4458         _ER(RDTSC),
4459         _ER(VMCALL),
4460         _ER(VMCLEAR),
4461         _ER(VMLAUNCH),
4462         _ER(VMPTRLD),
4463         _ER(VMPTRST),
4464         _ER(VMREAD),
4465         _ER(VMRESUME),
4466         _ER(VMWRITE),
4467         _ER(VMOFF),
4468         _ER(VMON),
4469         _ER(CR_ACCESS),
4470         _ER(DR_ACCESS),
4471         _ER(IO_INSTRUCTION),
4472         _ER(MSR_READ),
4473         _ER(MSR_WRITE),
4474         _ER(MWAIT_INSTRUCTION),
4475         _ER(MONITOR_INSTRUCTION),
4476         _ER(PAUSE_INSTRUCTION),
4477         _ER(MCE_DURING_VMENTRY),
4478         _ER(TPR_BELOW_THRESHOLD),
4479         _ER(APIC_ACCESS),
4480         _ER(EPT_VIOLATION),
4481         _ER(EPT_MISCONFIG),
4482         _ER(WBINVD),
4483         { -1, NULL }
4484 };
4485 
4486 #undef _ER
4487 
4488 static int vmx_get_lpage_level(void)
4489 {
4490         if (enable_ept && !cpu_has_vmx_ept_1g_page())
4491                 return PT_DIRECTORY_LEVEL;
4492         else
4493                 /* For shadow and EPT supported 1GB page */
4494                 return PT_PDPE_LEVEL;
4495 }
4496 
4497 static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
4498 {
4499         struct kvm_cpuid_entry2 *best;
4500         struct vcpu_vmx *vmx = to_vmx(vcpu);
4501         u32 exec_control;
4502 
4503         vmx->rdtscp_enabled = false;
4504         if (vmx_rdtscp_supported()) {
4505                 exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
4506                 if (exec_control & SECONDARY_EXEC_RDTSCP) {
4507                         best = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
4508                         if (best && (best->edx & bit(X86_FEATURE_RDTSCP)))
4509                                 vmx->rdtscp_enabled = true;
4510                         else {
4511                                 exec_control &= ~SECONDARY_EXEC_RDTSCP;
4512                                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
4513                                                 exec_control);
4514                         }
4515                 }
4516         }
4517 }
4518 
4519 static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
4520 {
4521 }
4522 
4523 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
4524                                struct x86_instruction_info *info,
4525                                enum x86_intercept_stage stage)
4526 {
4527         return X86EMUL_CONTINUE;
4528 }
4529 
4530 static struct kvm_x86_ops vmx_x86_ops = {
4531         .cpu_has_kvm_support = cpu_has_kvm_support,
4532         .disabled_by_bios = vmx_disabled_by_bios,
4533         .hardware_setup = hardware_setup,
4534         .hardware_unsetup = hardware_unsetup,
4535         .check_processor_compatibility = vmx_check_processor_compat,
4536         .hardware_enable = hardware_enable,
4537         .hardware_disable = hardware_disable,
4538         .cpu_has_accelerated_tpr = report_flexpriority,
4539 
4540         .vcpu_create = vmx_create_vcpu,
4541         .vcpu_free = vmx_free_vcpu,
4542         .vcpu_reset = vmx_vcpu_reset,
4543 
4544         .prepare_guest_switch = vmx_save_host_state,
4545         .vcpu_load = vmx_vcpu_load,
4546         .vcpu_put = vmx_vcpu_put,
4547 
4548         .set_guest_debug = set_guest_debug,
4549         .get_msr = vmx_get_msr,
4550         .set_msr = vmx_set_msr,
4551         .get_segment_base = vmx_get_segment_base,
4552         .get_segment = vmx_get_segment,
4553         .set_segment = vmx_set_segment,
4554         .get_cpl = vmx_get_cpl,
4555         .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
4556         .decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
4557         .decache_cr3 = vmx_decache_cr3,
4558         .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
4559         .set_cr0 = vmx_set_cr0,
4560         .set_cr3 = vmx_set_cr3,
4561         .set_cr4 = vmx_set_cr4,
4562         .set_efer = vmx_set_efer,
4563         .get_idt = vmx_get_idt,
4564         .set_idt = vmx_set_idt,
4565         .get_gdt = vmx_get_gdt,
4566         .set_gdt = vmx_set_gdt,
4567         .set_dr7 = vmx_set_dr7,
4568         .cache_reg = vmx_cache_reg,
4569         .get_rflags = vmx_get_rflags,
4570         .set_rflags = vmx_set_rflags,
4571         .fpu_activate = vmx_fpu_activate,
4572         .fpu_deactivate = vmx_fpu_deactivate,
4573 
4574         .tlb_flush = vmx_flush_tlb,
4575 
4576         .run = vmx_vcpu_run,
4577         .handle_exit = vmx_handle_exit,
4578         .skip_emulated_instruction = skip_emulated_instruction,
4579         .set_interrupt_shadow = vmx_set_interrupt_shadow,
4580         .get_interrupt_shadow = vmx_get_interrupt_shadow,
4581         .patch_hypercall = vmx_patch_hypercall,
4582         .set_irq = vmx_inject_irq,
4583         .set_nmi = vmx_inject_nmi,
4584         .queue_exception = vmx_queue_exception,
4585         .cancel_injection = vmx_cancel_injection,
4586         .interrupt_allowed = vmx_interrupt_allowed,
4587         .nmi_allowed = vmx_nmi_allowed,
4588         .get_nmi_mask = vmx_get_nmi_mask,
4589         .set_nmi_mask = vmx_set_nmi_mask,
4590         .enable_nmi_window = enable_nmi_window,
4591         .enable_irq_window = enable_irq_window,
4592         .update_cr8_intercept = update_cr8_intercept,
4593 
4594         .set_tss_addr = vmx_set_tss_addr,
4595         .get_tdp_level = get_ept_level,
4596         .get_mt_mask = vmx_get_mt_mask,
4597 
4598         .get_exit_info = vmx_get_exit_info,
4599         .exit_reasons_str = vmx_exit_reasons_str,
4600 
4601         .get_lpage_level = vmx_get_lpage_level,
4602 
4603         .cpuid_update = vmx_cpuid_update,
4604 
4605         .rdtscp_supported = vmx_rdtscp_supported,
4606 
4607         .set_supported_cpuid = vmx_set_supported_cpuid,
4608 
4609         .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
4610 
4611         .set_tsc_khz = vmx_set_tsc_khz,
4612         .write_tsc_offset = vmx_write_tsc_offset,
4613         .adjust_tsc_offset = vmx_adjust_tsc_offset,
4614         .compute_tsc_offset = vmx_compute_tsc_offset,
4615 
4616         .set_tdp_cr3 = vmx_set_cr3,
4617 
4618         .check_intercept = vmx_check_intercept,
4619 };
4620 
4621 static int __init vmx_init(void)
4622 {
4623         int r, i;
4624 
4625         rdmsrl_safe(MSR_EFER, &host_efer);
4626 
4627         for (i = 0; i < NR_VMX_MSR; ++i)
4628                 kvm_define_shared_msr(i, vmx_msr_index[i]);
4629 
4630         vmx_io_bitmap_a = (unsigned long *)__get_free_page(GFP_KERNEL);
4631         if (!vmx_io_bitmap_a)
4632                 return -ENOMEM;
4633 
4634         vmx_io_bitmap_b = (unsigned long *)__get_free_page(GFP_KERNEL);
4635         if (!vmx_io_bitmap_b) {
4636                 r = -ENOMEM;
4637                 goto out;
4638         }
4639 
4640         vmx_msr_bitmap_legacy = (unsigned long *)__get_free_page(GFP_KERNEL);
4641         if (!vmx_msr_bitmap_legacy) {
4642                 r = -ENOMEM;
4643                 goto out1;
4644         }
4645 
4646         vmx_msr_bitmap_longmode = (unsigned long *)__get_free_page(GFP_KERNEL);
4647         if (!vmx_msr_bitmap_longmode) {
4648                 r = -ENOMEM;
4649                 goto out2;
4650         }
4651 
4652         /*
4653          * Allow direct access to the PC debug port (it is often used for I/O
4654          * delays, but the vmexits simply slow things down).
4655          */
4656         memset(vmx_io_bitmap_a, 0xff, PAGE_SIZE);
4657         clear_bit(0x80, vmx_io_bitmap_a);
4658 
4659         memset(vmx_io_bitmap_b, 0xff, PAGE_SIZE);
4660 
4661         memset(vmx_msr_bitmap_legacy, 0xff, PAGE_SIZE);
4662         memset(vmx_msr_bitmap_longmode, 0xff, PAGE_SIZE);
4663 
4664         set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
4665 
4666         r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
4667                      __alignof__(struct vcpu_vmx), THIS_MODULE);
4668         if (r)
4669                 goto out3;
4670 
4671         vmx_disable_intercept_for_msr(MSR_FS_BASE, false);
4672         vmx_disable_intercept_for_msr(MSR_GS_BASE, false);
4673         vmx_disable_intercept_for_msr(MSR_KERNEL_GS_BASE, true);
4674         vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_CS, false);
4675         vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_ESP, false);
4676         vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_EIP, false);
4677 
4678         if (enable_ept) {
4679                 bypass_guest_pf = 0;
4680                 kvm_mmu_set_mask_ptes(0ull, 0ull, 0ull, 0ull,
4681                                 VMX_EPT_EXECUTABLE_MASK);
4682                 kvm_enable_tdp();
4683         } else
4684                 kvm_disable_tdp();
4685 
4686         if (bypass_guest_pf)
4687                 kvm_mmu_set_nonpresent_ptes(~0xffeull, 0ull);
4688 
4689         return 0;
4690 
4691 out3:
4692         free_page((unsigned long)vmx_msr_bitmap_longmode);
4693 out2:
4694         free_page((unsigned long)vmx_msr_bitmap_legacy);
4695 out1:
4696         free_page((unsigned long)vmx_io_bitmap_b);
4697 out:
4698         free_page((unsigned long)vmx_io_bitmap_a);
4699         return r;
4700 }
4701 
4702 static void __exit vmx_exit(void)
4703 {
4704         free_page((unsigned long)vmx_msr_bitmap_legacy);
4705         free_page((unsigned long)vmx_msr_bitmap_longmode);
4706         free_page((unsigned long)vmx_io_bitmap_b);
4707         free_page((unsigned long)vmx_io_bitmap_a);
4708 
4709         kvm_exit();
4710 }
4711 
4712 module_init(vmx_init)
4713 module_exit(vmx_exit)
4714 

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | Wiki (Japanese) | Wiki (English) | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

osdn.jp