KVM: nVMX: Fully emulate preemption timer
[firefly-linux-kernel-4.4.55.git] / arch / x86 / kvm / vmx.c
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 #include "cpuid.h"
22
23 #include <linux/kvm_host.h>
24 #include <linux/module.h>
25 #include <linux/kernel.h>
26 #include <linux/mm.h>
27 #include <linux/highmem.h>
28 #include <linux/sched.h>
29 #include <linux/moduleparam.h>
30 #include <linux/mod_devicetable.h>
31 #include <linux/ftrace_event.h>
32 #include <linux/slab.h>
33 #include <linux/tboot.h>
34 #include <linux/hrtimer.h>
35 #include "kvm_cache_regs.h"
36 #include "x86.h"
37
38 #include <asm/io.h>
39 #include <asm/desc.h>
40 #include <asm/vmx.h>
41 #include <asm/virtext.h>
42 #include <asm/mce.h>
43 #include <asm/i387.h>
44 #include <asm/xcr.h>
45 #include <asm/perf_event.h>
46 #include <asm/kexec.h>
47
48 #include "trace.h"
49
50 #define __ex(x) __kvm_handle_fault_on_reboot(x)
51 #define __ex_clear(x, reg) \
52         ____kvm_handle_fault_on_reboot(x, "xor " reg " , " reg)
53
54 MODULE_AUTHOR("Qumranet");
55 MODULE_LICENSE("GPL");
56
57 static const struct x86_cpu_id vmx_cpu_id[] = {
58         X86_FEATURE_MATCH(X86_FEATURE_VMX),
59         {}
60 };
61 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
62
63 static bool __read_mostly enable_vpid = 1;
64 module_param_named(vpid, enable_vpid, bool, 0444);
65
66 static bool __read_mostly flexpriority_enabled = 1;
67 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
68
69 static bool __read_mostly enable_ept = 1;
70 module_param_named(ept, enable_ept, bool, S_IRUGO);
71
72 static bool __read_mostly enable_unrestricted_guest = 1;
73 module_param_named(unrestricted_guest,
74                         enable_unrestricted_guest, bool, S_IRUGO);
75
76 static bool __read_mostly enable_ept_ad_bits = 1;
77 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
78
79 static bool __read_mostly emulate_invalid_guest_state = true;
80 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
81
82 static bool __read_mostly vmm_exclusive = 1;
83 module_param(vmm_exclusive, bool, S_IRUGO);
84
85 static bool __read_mostly fasteoi = 1;
86 module_param(fasteoi, bool, S_IRUGO);
87
88 static bool __read_mostly enable_apicv = 1;
89 module_param(enable_apicv, bool, S_IRUGO);
90
91 static bool __read_mostly enable_shadow_vmcs = 1;
92 module_param_named(enable_shadow_vmcs, enable_shadow_vmcs, bool, S_IRUGO);
93 /*
94  * If nested=1, nested virtualization is supported, i.e., guests may use
95  * VMX and be a hypervisor for its own guests. If nested=0, guests may not
96  * use VMX instructions.
97  */
98 static bool __read_mostly nested = 0;
99 module_param(nested, bool, S_IRUGO);
100
101 #define KVM_GUEST_CR0_MASK (X86_CR0_NW | X86_CR0_CD)
102 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST (X86_CR0_WP | X86_CR0_NE)
103 #define KVM_VM_CR0_ALWAYS_ON                                            \
104         (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE)
105 #define KVM_CR4_GUEST_OWNED_BITS                                      \
106         (X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR      \
107          | X86_CR4_OSXMMEXCPT)
108
109 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
110 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
111
112 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
113
114 #define VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE 5
115
116 /*
117  * These 2 parameters are used to config the controls for Pause-Loop Exiting:
118  * ple_gap:    upper bound on the amount of time between two successive
119  *             executions of PAUSE in a loop. Also indicate if ple enabled.
120  *             According to test, this time is usually smaller than 128 cycles.
121  * ple_window: upper bound on the amount of time a guest is allowed to execute
122  *             in a PAUSE loop. Tests indicate that most spinlocks are held for
123  *             less than 2^12 cycles
124  * Time is measured based on a counter that runs at the same rate as the TSC,
125  * refer SDM volume 3b section 21.6.13 & 22.1.3.
126  */
127 #define KVM_VMX_DEFAULT_PLE_GAP    128
128 #define KVM_VMX_DEFAULT_PLE_WINDOW 4096
129 static int ple_gap = KVM_VMX_DEFAULT_PLE_GAP;
130 module_param(ple_gap, int, S_IRUGO);
131
132 static int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
133 module_param(ple_window, int, S_IRUGO);
134
135 extern const ulong vmx_return;
136
137 #define NR_AUTOLOAD_MSRS 8
138 #define VMCS02_POOL_SIZE 1
139
140 struct vmcs {
141         u32 revision_id;
142         u32 abort;
143         char data[0];
144 };
145
146 /*
147  * Track a VMCS that may be loaded on a certain CPU. If it is (cpu!=-1), also
148  * remember whether it was VMLAUNCHed, and maintain a linked list of all VMCSs
149  * loaded on this CPU (so we can clear them if the CPU goes down).
150  */
151 struct loaded_vmcs {
152         struct vmcs *vmcs;
153         int cpu;
154         int launched;
155         struct list_head loaded_vmcss_on_cpu_link;
156 };
157
158 struct shared_msr_entry {
159         unsigned index;
160         u64 data;
161         u64 mask;
162 };
163
164 /*
165  * struct vmcs12 describes the state that our guest hypervisor (L1) keeps for a
166  * single nested guest (L2), hence the name vmcs12. Any VMX implementation has
167  * a VMCS structure, and vmcs12 is our emulated VMX's VMCS. This structure is
168  * stored in guest memory specified by VMPTRLD, but is opaque to the guest,
169  * which must access it using VMREAD/VMWRITE/VMCLEAR instructions.
170  * More than one of these structures may exist, if L1 runs multiple L2 guests.
171  * nested_vmx_run() will use the data here to build a vmcs02: a VMCS for the
172  * underlying hardware which will be used to run L2.
173  * This structure is packed to ensure that its layout is identical across
174  * machines (necessary for live migration).
175  * If there are changes in this struct, VMCS12_REVISION must be changed.
176  */
177 typedef u64 natural_width;
178 struct __packed vmcs12 {
179         /* According to the Intel spec, a VMCS region must start with the
180          * following two fields. Then follow implementation-specific data.
181          */
182         u32 revision_id;
183         u32 abort;
184
185         u32 launch_state; /* set to 0 by VMCLEAR, to 1 by VMLAUNCH */
186         u32 padding[7]; /* room for future expansion */
187
188         u64 io_bitmap_a;
189         u64 io_bitmap_b;
190         u64 msr_bitmap;
191         u64 vm_exit_msr_store_addr;
192         u64 vm_exit_msr_load_addr;
193         u64 vm_entry_msr_load_addr;
194         u64 tsc_offset;
195         u64 virtual_apic_page_addr;
196         u64 apic_access_addr;
197         u64 ept_pointer;
198         u64 guest_physical_address;
199         u64 vmcs_link_pointer;
200         u64 guest_ia32_debugctl;
201         u64 guest_ia32_pat;
202         u64 guest_ia32_efer;
203         u64 guest_ia32_perf_global_ctrl;
204         u64 guest_pdptr0;
205         u64 guest_pdptr1;
206         u64 guest_pdptr2;
207         u64 guest_pdptr3;
208         u64 host_ia32_pat;
209         u64 host_ia32_efer;
210         u64 host_ia32_perf_global_ctrl;
211         u64 padding64[8]; /* room for future expansion */
212         /*
213          * To allow migration of L1 (complete with its L2 guests) between
214          * machines of different natural widths (32 or 64 bit), we cannot have
215          * unsigned long fields with no explict size. We use u64 (aliased
216          * natural_width) instead. Luckily, x86 is little-endian.
217          */
218         natural_width cr0_guest_host_mask;
219         natural_width cr4_guest_host_mask;
220         natural_width cr0_read_shadow;
221         natural_width cr4_read_shadow;
222         natural_width cr3_target_value0;
223         natural_width cr3_target_value1;
224         natural_width cr3_target_value2;
225         natural_width cr3_target_value3;
226         natural_width exit_qualification;
227         natural_width guest_linear_address;
228         natural_width guest_cr0;
229         natural_width guest_cr3;
230         natural_width guest_cr4;
231         natural_width guest_es_base;
232         natural_width guest_cs_base;
233         natural_width guest_ss_base;
234         natural_width guest_ds_base;
235         natural_width guest_fs_base;
236         natural_width guest_gs_base;
237         natural_width guest_ldtr_base;
238         natural_width guest_tr_base;
239         natural_width guest_gdtr_base;
240         natural_width guest_idtr_base;
241         natural_width guest_dr7;
242         natural_width guest_rsp;
243         natural_width guest_rip;
244         natural_width guest_rflags;
245         natural_width guest_pending_dbg_exceptions;
246         natural_width guest_sysenter_esp;
247         natural_width guest_sysenter_eip;
248         natural_width host_cr0;
249         natural_width host_cr3;
250         natural_width host_cr4;
251         natural_width host_fs_base;
252         natural_width host_gs_base;
253         natural_width host_tr_base;
254         natural_width host_gdtr_base;
255         natural_width host_idtr_base;
256         natural_width host_ia32_sysenter_esp;
257         natural_width host_ia32_sysenter_eip;
258         natural_width host_rsp;
259         natural_width host_rip;
260         natural_width paddingl[8]; /* room for future expansion */
261         u32 pin_based_vm_exec_control;
262         u32 cpu_based_vm_exec_control;
263         u32 exception_bitmap;
264         u32 page_fault_error_code_mask;
265         u32 page_fault_error_code_match;
266         u32 cr3_target_count;
267         u32 vm_exit_controls;
268         u32 vm_exit_msr_store_count;
269         u32 vm_exit_msr_load_count;
270         u32 vm_entry_controls;
271         u32 vm_entry_msr_load_count;
272         u32 vm_entry_intr_info_field;
273         u32 vm_entry_exception_error_code;
274         u32 vm_entry_instruction_len;
275         u32 tpr_threshold;
276         u32 secondary_vm_exec_control;
277         u32 vm_instruction_error;
278         u32 vm_exit_reason;
279         u32 vm_exit_intr_info;
280         u32 vm_exit_intr_error_code;
281         u32 idt_vectoring_info_field;
282         u32 idt_vectoring_error_code;
283         u32 vm_exit_instruction_len;
284         u32 vmx_instruction_info;
285         u32 guest_es_limit;
286         u32 guest_cs_limit;
287         u32 guest_ss_limit;
288         u32 guest_ds_limit;
289         u32 guest_fs_limit;
290         u32 guest_gs_limit;
291         u32 guest_ldtr_limit;
292         u32 guest_tr_limit;
293         u32 guest_gdtr_limit;
294         u32 guest_idtr_limit;
295         u32 guest_es_ar_bytes;
296         u32 guest_cs_ar_bytes;
297         u32 guest_ss_ar_bytes;
298         u32 guest_ds_ar_bytes;
299         u32 guest_fs_ar_bytes;
300         u32 guest_gs_ar_bytes;
301         u32 guest_ldtr_ar_bytes;
302         u32 guest_tr_ar_bytes;
303         u32 guest_interruptibility_info;
304         u32 guest_activity_state;
305         u32 guest_sysenter_cs;
306         u32 host_ia32_sysenter_cs;
307         u32 vmx_preemption_timer_value;
308         u32 padding32[7]; /* room for future expansion */
309         u16 virtual_processor_id;
310         u16 guest_es_selector;
311         u16 guest_cs_selector;
312         u16 guest_ss_selector;
313         u16 guest_ds_selector;
314         u16 guest_fs_selector;
315         u16 guest_gs_selector;
316         u16 guest_ldtr_selector;
317         u16 guest_tr_selector;
318         u16 host_es_selector;
319         u16 host_cs_selector;
320         u16 host_ss_selector;
321         u16 host_ds_selector;
322         u16 host_fs_selector;
323         u16 host_gs_selector;
324         u16 host_tr_selector;
325 };
326
327 /*
328  * VMCS12_REVISION is an arbitrary id that should be changed if the content or
329  * layout of struct vmcs12 is changed. MSR_IA32_VMX_BASIC returns this id, and
330  * VMPTRLD verifies that the VMCS region that L1 is loading contains this id.
331  */
332 #define VMCS12_REVISION 0x11e57ed0
333
334 /*
335  * VMCS12_SIZE is the number of bytes L1 should allocate for the VMXON region
336  * and any VMCS region. Although only sizeof(struct vmcs12) are used by the
337  * current implementation, 4K are reserved to avoid future complications.
338  */
339 #define VMCS12_SIZE 0x1000
340
341 /* Used to remember the last vmcs02 used for some recently used vmcs12s */
342 struct vmcs02_list {
343         struct list_head list;
344         gpa_t vmptr;
345         struct loaded_vmcs vmcs02;
346 };
347
348 /*
349  * The nested_vmx structure is part of vcpu_vmx, and holds information we need
350  * for correct emulation of VMX (i.e., nested VMX) on this vcpu.
351  */
352 struct nested_vmx {
353         /* Has the level1 guest done vmxon? */
354         bool vmxon;
355
356         /* The guest-physical address of the current VMCS L1 keeps for L2 */
357         gpa_t current_vmptr;
358         /* The host-usable pointer to the above */
359         struct page *current_vmcs12_page;
360         struct vmcs12 *current_vmcs12;
361         struct vmcs *current_shadow_vmcs;
362         /*
363          * Indicates if the shadow vmcs must be updated with the
364          * data hold by vmcs12
365          */
366         bool sync_shadow_vmcs;
367
368         /* vmcs02_list cache of VMCSs recently used to run L2 guests */
369         struct list_head vmcs02_pool;
370         int vmcs02_num;
371         u64 vmcs01_tsc_offset;
372         /* L2 must run next, and mustn't decide to exit to L1. */
373         bool nested_run_pending;
374         /*
375          * Guest pages referred to in vmcs02 with host-physical pointers, so
376          * we must keep them pinned while L2 runs.
377          */
378         struct page *apic_access_page;
379         u64 msr_ia32_feature_control;
380
381         struct hrtimer preemption_timer;
382         bool preemption_timer_expired;
383 };
384
385 #define POSTED_INTR_ON  0
386 /* Posted-Interrupt Descriptor */
387 struct pi_desc {
388         u32 pir[8];     /* Posted interrupt requested */
389         u32 control;    /* bit 0 of control is outstanding notification bit */
390         u32 rsvd[7];
391 } __aligned(64);
392
393 static bool pi_test_and_set_on(struct pi_desc *pi_desc)
394 {
395         return test_and_set_bit(POSTED_INTR_ON,
396                         (unsigned long *)&pi_desc->control);
397 }
398
399 static bool pi_test_and_clear_on(struct pi_desc *pi_desc)
400 {
401         return test_and_clear_bit(POSTED_INTR_ON,
402                         (unsigned long *)&pi_desc->control);
403 }
404
405 static int pi_test_and_set_pir(int vector, struct pi_desc *pi_desc)
406 {
407         return test_and_set_bit(vector, (unsigned long *)pi_desc->pir);
408 }
409
410 struct vcpu_vmx {
411         struct kvm_vcpu       vcpu;
412         unsigned long         host_rsp;
413         u8                    fail;
414         u8                    cpl;
415         bool                  nmi_known_unmasked;
416         u32                   exit_intr_info;
417         u32                   idt_vectoring_info;
418         ulong                 rflags;
419         struct shared_msr_entry *guest_msrs;
420         int                   nmsrs;
421         int                   save_nmsrs;
422         unsigned long         host_idt_base;
423 #ifdef CONFIG_X86_64
424         u64                   msr_host_kernel_gs_base;
425         u64                   msr_guest_kernel_gs_base;
426 #endif
427         u32 vm_entry_controls_shadow;
428         u32 vm_exit_controls_shadow;
429         /*
430          * loaded_vmcs points to the VMCS currently used in this vcpu. For a
431          * non-nested (L1) guest, it always points to vmcs01. For a nested
432          * guest (L2), it points to a different VMCS.
433          */
434         struct loaded_vmcs    vmcs01;
435         struct loaded_vmcs   *loaded_vmcs;
436         bool                  __launched; /* temporary, used in vmx_vcpu_run */
437         struct msr_autoload {
438                 unsigned nr;
439                 struct vmx_msr_entry guest[NR_AUTOLOAD_MSRS];
440                 struct vmx_msr_entry host[NR_AUTOLOAD_MSRS];
441         } msr_autoload;
442         struct {
443                 int           loaded;
444                 u16           fs_sel, gs_sel, ldt_sel;
445 #ifdef CONFIG_X86_64
446                 u16           ds_sel, es_sel;
447 #endif
448                 int           gs_ldt_reload_needed;
449                 int           fs_reload_needed;
450                 u64           msr_host_bndcfgs;
451         } host_state;
452         struct {
453                 int vm86_active;
454                 ulong save_rflags;
455                 struct kvm_segment segs[8];
456         } rmode;
457         struct {
458                 u32 bitmask; /* 4 bits per segment (1 bit per field) */
459                 struct kvm_save_segment {
460                         u16 selector;
461                         unsigned long base;
462                         u32 limit;
463                         u32 ar;
464                 } seg[8];
465         } segment_cache;
466         int vpid;
467         bool emulation_required;
468
469         /* Support for vnmi-less CPUs */
470         int soft_vnmi_blocked;
471         ktime_t entry_time;
472         s64 vnmi_blocked_time;
473         u32 exit_reason;
474
475         bool rdtscp_enabled;
476
477         /* Posted interrupt descriptor */
478         struct pi_desc pi_desc;
479
480         /* Support for a guest hypervisor (nested VMX) */
481         struct nested_vmx nested;
482 };
483
484 enum segment_cache_field {
485         SEG_FIELD_SEL = 0,
486         SEG_FIELD_BASE = 1,
487         SEG_FIELD_LIMIT = 2,
488         SEG_FIELD_AR = 3,
489
490         SEG_FIELD_NR = 4
491 };
492
493 static inline struct vcpu_vmx *to_vmx(struct kvm_vcpu *vcpu)
494 {
495         return container_of(vcpu, struct vcpu_vmx, vcpu);
496 }
497
498 #define VMCS12_OFFSET(x) offsetof(struct vmcs12, x)
499 #define FIELD(number, name)     [number] = VMCS12_OFFSET(name)
500 #define FIELD64(number, name)   [number] = VMCS12_OFFSET(name), \
501                                 [number##_HIGH] = VMCS12_OFFSET(name)+4
502
503
504 static const unsigned long shadow_read_only_fields[] = {
505         /*
506          * We do NOT shadow fields that are modified when L0
507          * traps and emulates any vmx instruction (e.g. VMPTRLD,
508          * VMXON...) executed by L1.
509          * For example, VM_INSTRUCTION_ERROR is read
510          * by L1 if a vmx instruction fails (part of the error path).
511          * Note the code assumes this logic. If for some reason
512          * we start shadowing these fields then we need to
513          * force a shadow sync when L0 emulates vmx instructions
514          * (e.g. force a sync if VM_INSTRUCTION_ERROR is modified
515          * by nested_vmx_failValid)
516          */
517         VM_EXIT_REASON,
518         VM_EXIT_INTR_INFO,
519         VM_EXIT_INSTRUCTION_LEN,
520         IDT_VECTORING_INFO_FIELD,
521         IDT_VECTORING_ERROR_CODE,
522         VM_EXIT_INTR_ERROR_CODE,
523         EXIT_QUALIFICATION,
524         GUEST_LINEAR_ADDRESS,
525         GUEST_PHYSICAL_ADDRESS
526 };
527 static const int max_shadow_read_only_fields =
528         ARRAY_SIZE(shadow_read_only_fields);
529
530 static const unsigned long shadow_read_write_fields[] = {
531         GUEST_RIP,
532         GUEST_RSP,
533         GUEST_CR0,
534         GUEST_CR3,
535         GUEST_CR4,
536         GUEST_INTERRUPTIBILITY_INFO,
537         GUEST_RFLAGS,
538         GUEST_CS_SELECTOR,
539         GUEST_CS_AR_BYTES,
540         GUEST_CS_LIMIT,
541         GUEST_CS_BASE,
542         GUEST_ES_BASE,
543         CR0_GUEST_HOST_MASK,
544         CR0_READ_SHADOW,
545         CR4_READ_SHADOW,
546         TSC_OFFSET,
547         EXCEPTION_BITMAP,
548         CPU_BASED_VM_EXEC_CONTROL,
549         VM_ENTRY_EXCEPTION_ERROR_CODE,
550         VM_ENTRY_INTR_INFO_FIELD,
551         VM_ENTRY_INSTRUCTION_LEN,
552         VM_ENTRY_EXCEPTION_ERROR_CODE,
553         HOST_FS_BASE,
554         HOST_GS_BASE,
555         HOST_FS_SELECTOR,
556         HOST_GS_SELECTOR
557 };
558 static const int max_shadow_read_write_fields =
559         ARRAY_SIZE(shadow_read_write_fields);
560
561 static const unsigned short vmcs_field_to_offset_table[] = {
562         FIELD(VIRTUAL_PROCESSOR_ID, virtual_processor_id),
563         FIELD(GUEST_ES_SELECTOR, guest_es_selector),
564         FIELD(GUEST_CS_SELECTOR, guest_cs_selector),
565         FIELD(GUEST_SS_SELECTOR, guest_ss_selector),
566         FIELD(GUEST_DS_SELECTOR, guest_ds_selector),
567         FIELD(GUEST_FS_SELECTOR, guest_fs_selector),
568         FIELD(GUEST_GS_SELECTOR, guest_gs_selector),
569         FIELD(GUEST_LDTR_SELECTOR, guest_ldtr_selector),
570         FIELD(GUEST_TR_SELECTOR, guest_tr_selector),
571         FIELD(HOST_ES_SELECTOR, host_es_selector),
572         FIELD(HOST_CS_SELECTOR, host_cs_selector),
573         FIELD(HOST_SS_SELECTOR, host_ss_selector),
574         FIELD(HOST_DS_SELECTOR, host_ds_selector),
575         FIELD(HOST_FS_SELECTOR, host_fs_selector),
576         FIELD(HOST_GS_SELECTOR, host_gs_selector),
577         FIELD(HOST_TR_SELECTOR, host_tr_selector),
578         FIELD64(IO_BITMAP_A, io_bitmap_a),
579         FIELD64(IO_BITMAP_B, io_bitmap_b),
580         FIELD64(MSR_BITMAP, msr_bitmap),
581         FIELD64(VM_EXIT_MSR_STORE_ADDR, vm_exit_msr_store_addr),
582         FIELD64(VM_EXIT_MSR_LOAD_ADDR, vm_exit_msr_load_addr),
583         FIELD64(VM_ENTRY_MSR_LOAD_ADDR, vm_entry_msr_load_addr),
584         FIELD64(TSC_OFFSET, tsc_offset),
585         FIELD64(VIRTUAL_APIC_PAGE_ADDR, virtual_apic_page_addr),
586         FIELD64(APIC_ACCESS_ADDR, apic_access_addr),
587         FIELD64(EPT_POINTER, ept_pointer),
588         FIELD64(GUEST_PHYSICAL_ADDRESS, guest_physical_address),
589         FIELD64(VMCS_LINK_POINTER, vmcs_link_pointer),
590         FIELD64(GUEST_IA32_DEBUGCTL, guest_ia32_debugctl),
591         FIELD64(GUEST_IA32_PAT, guest_ia32_pat),
592         FIELD64(GUEST_IA32_EFER, guest_ia32_efer),
593         FIELD64(GUEST_IA32_PERF_GLOBAL_CTRL, guest_ia32_perf_global_ctrl),
594         FIELD64(GUEST_PDPTR0, guest_pdptr0),
595         FIELD64(GUEST_PDPTR1, guest_pdptr1),
596         FIELD64(GUEST_PDPTR2, guest_pdptr2),
597         FIELD64(GUEST_PDPTR3, guest_pdptr3),
598         FIELD64(HOST_IA32_PAT, host_ia32_pat),
599         FIELD64(HOST_IA32_EFER, host_ia32_efer),
600         FIELD64(HOST_IA32_PERF_GLOBAL_CTRL, host_ia32_perf_global_ctrl),
601         FIELD(PIN_BASED_VM_EXEC_CONTROL, pin_based_vm_exec_control),
602         FIELD(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control),
603         FIELD(EXCEPTION_BITMAP, exception_bitmap),
604         FIELD(PAGE_FAULT_ERROR_CODE_MASK, page_fault_error_code_mask),
605         FIELD(PAGE_FAULT_ERROR_CODE_MATCH, page_fault_error_code_match),
606         FIELD(CR3_TARGET_COUNT, cr3_target_count),
607         FIELD(VM_EXIT_CONTROLS, vm_exit_controls),
608         FIELD(VM_EXIT_MSR_STORE_COUNT, vm_exit_msr_store_count),
609         FIELD(VM_EXIT_MSR_LOAD_COUNT, vm_exit_msr_load_count),
610         FIELD(VM_ENTRY_CONTROLS, vm_entry_controls),
611         FIELD(VM_ENTRY_MSR_LOAD_COUNT, vm_entry_msr_load_count),
612         FIELD(VM_ENTRY_INTR_INFO_FIELD, vm_entry_intr_info_field),
613         FIELD(VM_ENTRY_EXCEPTION_ERROR_CODE, vm_entry_exception_error_code),
614         FIELD(VM_ENTRY_INSTRUCTION_LEN, vm_entry_instruction_len),
615         FIELD(TPR_THRESHOLD, tpr_threshold),
616         FIELD(SECONDARY_VM_EXEC_CONTROL, secondary_vm_exec_control),
617         FIELD(VM_INSTRUCTION_ERROR, vm_instruction_error),
618         FIELD(VM_EXIT_REASON, vm_exit_reason),
619         FIELD(VM_EXIT_INTR_INFO, vm_exit_intr_info),
620         FIELD(VM_EXIT_INTR_ERROR_CODE, vm_exit_intr_error_code),
621         FIELD(IDT_VECTORING_INFO_FIELD, idt_vectoring_info_field),
622         FIELD(IDT_VECTORING_ERROR_CODE, idt_vectoring_error_code),
623         FIELD(VM_EXIT_INSTRUCTION_LEN, vm_exit_instruction_len),
624         FIELD(VMX_INSTRUCTION_INFO, vmx_instruction_info),
625         FIELD(GUEST_ES_LIMIT, guest_es_limit),
626         FIELD(GUEST_CS_LIMIT, guest_cs_limit),
627         FIELD(GUEST_SS_LIMIT, guest_ss_limit),
628         FIELD(GUEST_DS_LIMIT, guest_ds_limit),
629         FIELD(GUEST_FS_LIMIT, guest_fs_limit),
630         FIELD(GUEST_GS_LIMIT, guest_gs_limit),
631         FIELD(GUEST_LDTR_LIMIT, guest_ldtr_limit),
632         FIELD(GUEST_TR_LIMIT, guest_tr_limit),
633         FIELD(GUEST_GDTR_LIMIT, guest_gdtr_limit),
634         FIELD(GUEST_IDTR_LIMIT, guest_idtr_limit),
635         FIELD(GUEST_ES_AR_BYTES, guest_es_ar_bytes),
636         FIELD(GUEST_CS_AR_BYTES, guest_cs_ar_bytes),
637         FIELD(GUEST_SS_AR_BYTES, guest_ss_ar_bytes),
638         FIELD(GUEST_DS_AR_BYTES, guest_ds_ar_bytes),
639         FIELD(GUEST_FS_AR_BYTES, guest_fs_ar_bytes),
640         FIELD(GUEST_GS_AR_BYTES, guest_gs_ar_bytes),
641         FIELD(GUEST_LDTR_AR_BYTES, guest_ldtr_ar_bytes),
642         FIELD(GUEST_TR_AR_BYTES, guest_tr_ar_bytes),
643         FIELD(GUEST_INTERRUPTIBILITY_INFO, guest_interruptibility_info),
644         FIELD(GUEST_ACTIVITY_STATE, guest_activity_state),
645         FIELD(GUEST_SYSENTER_CS, guest_sysenter_cs),
646         FIELD(HOST_IA32_SYSENTER_CS, host_ia32_sysenter_cs),
647         FIELD(VMX_PREEMPTION_TIMER_VALUE, vmx_preemption_timer_value),
648         FIELD(CR0_GUEST_HOST_MASK, cr0_guest_host_mask),
649         FIELD(CR4_GUEST_HOST_MASK, cr4_guest_host_mask),
650         FIELD(CR0_READ_SHADOW, cr0_read_shadow),
651         FIELD(CR4_READ_SHADOW, cr4_read_shadow),
652         FIELD(CR3_TARGET_VALUE0, cr3_target_value0),
653         FIELD(CR3_TARGET_VALUE1, cr3_target_value1),
654         FIELD(CR3_TARGET_VALUE2, cr3_target_value2),
655         FIELD(CR3_TARGET_VALUE3, cr3_target_value3),
656         FIELD(EXIT_QUALIFICATION, exit_qualification),
657         FIELD(GUEST_LINEAR_ADDRESS, guest_linear_address),
658         FIELD(GUEST_CR0, guest_cr0),
659         FIELD(GUEST_CR3, guest_cr3),
660         FIELD(GUEST_CR4, guest_cr4),
661         FIELD(GUEST_ES_BASE, guest_es_base),
662         FIELD(GUEST_CS_BASE, guest_cs_base),
663         FIELD(GUEST_SS_BASE, guest_ss_base),
664         FIELD(GUEST_DS_BASE, guest_ds_base),
665         FIELD(GUEST_FS_BASE, guest_fs_base),
666         FIELD(GUEST_GS_BASE, guest_gs_base),
667         FIELD(GUEST_LDTR_BASE, guest_ldtr_base),
668         FIELD(GUEST_TR_BASE, guest_tr_base),
669         FIELD(GUEST_GDTR_BASE, guest_gdtr_base),
670         FIELD(GUEST_IDTR_BASE, guest_idtr_base),
671         FIELD(GUEST_DR7, guest_dr7),
672         FIELD(GUEST_RSP, guest_rsp),
673         FIELD(GUEST_RIP, guest_rip),
674         FIELD(GUEST_RFLAGS, guest_rflags),
675         FIELD(GUEST_PENDING_DBG_EXCEPTIONS, guest_pending_dbg_exceptions),
676         FIELD(GUEST_SYSENTER_ESP, guest_sysenter_esp),
677         FIELD(GUEST_SYSENTER_EIP, guest_sysenter_eip),
678         FIELD(HOST_CR0, host_cr0),
679         FIELD(HOST_CR3, host_cr3),
680         FIELD(HOST_CR4, host_cr4),
681         FIELD(HOST_FS_BASE, host_fs_base),
682         FIELD(HOST_GS_BASE, host_gs_base),
683         FIELD(HOST_TR_BASE, host_tr_base),
684         FIELD(HOST_GDTR_BASE, host_gdtr_base),
685         FIELD(HOST_IDTR_BASE, host_idtr_base),
686         FIELD(HOST_IA32_SYSENTER_ESP, host_ia32_sysenter_esp),
687         FIELD(HOST_IA32_SYSENTER_EIP, host_ia32_sysenter_eip),
688         FIELD(HOST_RSP, host_rsp),
689         FIELD(HOST_RIP, host_rip),
690 };
691 static const int max_vmcs_field = ARRAY_SIZE(vmcs_field_to_offset_table);
692
693 static inline short vmcs_field_to_offset(unsigned long field)
694 {
695         if (field >= max_vmcs_field || vmcs_field_to_offset_table[field] == 0)
696                 return -1;
697         return vmcs_field_to_offset_table[field];
698 }
699
700 static inline struct vmcs12 *get_vmcs12(struct kvm_vcpu *vcpu)
701 {
702         return to_vmx(vcpu)->nested.current_vmcs12;
703 }
704
705 static struct page *nested_get_page(struct kvm_vcpu *vcpu, gpa_t addr)
706 {
707         struct page *page = gfn_to_page(vcpu->kvm, addr >> PAGE_SHIFT);
708         if (is_error_page(page))
709                 return NULL;
710
711         return page;
712 }
713
714 static void nested_release_page(struct page *page)
715 {
716         kvm_release_page_dirty(page);
717 }
718
719 static void nested_release_page_clean(struct page *page)
720 {
721         kvm_release_page_clean(page);
722 }
723
724 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu);
725 static u64 construct_eptp(unsigned long root_hpa);
726 static void kvm_cpu_vmxon(u64 addr);
727 static void kvm_cpu_vmxoff(void);
728 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr);
729 static void vmx_set_segment(struct kvm_vcpu *vcpu,
730                             struct kvm_segment *var, int seg);
731 static void vmx_get_segment(struct kvm_vcpu *vcpu,
732                             struct kvm_segment *var, int seg);
733 static bool guest_state_valid(struct kvm_vcpu *vcpu);
734 static u32 vmx_segment_access_rights(struct kvm_segment *var);
735 static void vmx_sync_pir_to_irr_dummy(struct kvm_vcpu *vcpu);
736 static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx);
737 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx);
738
739 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
740 static DEFINE_PER_CPU(struct vmcs *, current_vmcs);
741 /*
742  * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
743  * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
744  */
745 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
746 static DEFINE_PER_CPU(struct desc_ptr, host_gdt);
747
748 static unsigned long *vmx_io_bitmap_a;
749 static unsigned long *vmx_io_bitmap_b;
750 static unsigned long *vmx_msr_bitmap_legacy;
751 static unsigned long *vmx_msr_bitmap_longmode;
752 static unsigned long *vmx_msr_bitmap_legacy_x2apic;
753 static unsigned long *vmx_msr_bitmap_longmode_x2apic;
754 static unsigned long *vmx_vmread_bitmap;
755 static unsigned long *vmx_vmwrite_bitmap;
756
757 static bool cpu_has_load_ia32_efer;
758 static bool cpu_has_load_perf_global_ctrl;
759
760 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
761 static DEFINE_SPINLOCK(vmx_vpid_lock);
762
763 static struct vmcs_config {
764         int size;
765         int order;
766         u32 revision_id;
767         u32 pin_based_exec_ctrl;
768         u32 cpu_based_exec_ctrl;
769         u32 cpu_based_2nd_exec_ctrl;
770         u32 vmexit_ctrl;
771         u32 vmentry_ctrl;
772 } vmcs_config;
773
774 static struct vmx_capability {
775         u32 ept;
776         u32 vpid;
777 } vmx_capability;
778
779 #define VMX_SEGMENT_FIELD(seg)                                  \
780         [VCPU_SREG_##seg] = {                                   \
781                 .selector = GUEST_##seg##_SELECTOR,             \
782                 .base = GUEST_##seg##_BASE,                     \
783                 .limit = GUEST_##seg##_LIMIT,                   \
784                 .ar_bytes = GUEST_##seg##_AR_BYTES,             \
785         }
786
787 static const struct kvm_vmx_segment_field {
788         unsigned selector;
789         unsigned base;
790         unsigned limit;
791         unsigned ar_bytes;
792 } kvm_vmx_segment_fields[] = {
793         VMX_SEGMENT_FIELD(CS),
794         VMX_SEGMENT_FIELD(DS),
795         VMX_SEGMENT_FIELD(ES),
796         VMX_SEGMENT_FIELD(FS),
797         VMX_SEGMENT_FIELD(GS),
798         VMX_SEGMENT_FIELD(SS),
799         VMX_SEGMENT_FIELD(TR),
800         VMX_SEGMENT_FIELD(LDTR),
801 };
802
803 static u64 host_efer;
804
805 static void ept_save_pdptrs(struct kvm_vcpu *vcpu);
806
807 /*
808  * Keep MSR_STAR at the end, as setup_msrs() will try to optimize it
809  * away by decrementing the array size.
810  */
811 static const u32 vmx_msr_index[] = {
812 #ifdef CONFIG_X86_64
813         MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
814 #endif
815         MSR_EFER, MSR_TSC_AUX, MSR_STAR,
816 };
817 #define NR_VMX_MSR ARRAY_SIZE(vmx_msr_index)
818
819 static inline bool is_page_fault(u32 intr_info)
820 {
821         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
822                              INTR_INFO_VALID_MASK)) ==
823                 (INTR_TYPE_HARD_EXCEPTION | PF_VECTOR | INTR_INFO_VALID_MASK);
824 }
825
826 static inline bool is_no_device(u32 intr_info)
827 {
828         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
829                              INTR_INFO_VALID_MASK)) ==
830                 (INTR_TYPE_HARD_EXCEPTION | NM_VECTOR | INTR_INFO_VALID_MASK);
831 }
832
833 static inline bool is_invalid_opcode(u32 intr_info)
834 {
835         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
836                              INTR_INFO_VALID_MASK)) ==
837                 (INTR_TYPE_HARD_EXCEPTION | UD_VECTOR | INTR_INFO_VALID_MASK);
838 }
839
840 static inline bool is_external_interrupt(u32 intr_info)
841 {
842         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
843                 == (INTR_TYPE_EXT_INTR | INTR_INFO_VALID_MASK);
844 }
845
846 static inline bool is_machine_check(u32 intr_info)
847 {
848         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
849                              INTR_INFO_VALID_MASK)) ==
850                 (INTR_TYPE_HARD_EXCEPTION | MC_VECTOR | INTR_INFO_VALID_MASK);
851 }
852
853 static inline bool cpu_has_vmx_msr_bitmap(void)
854 {
855         return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_USE_MSR_BITMAPS;
856 }
857
858 static inline bool cpu_has_vmx_tpr_shadow(void)
859 {
860         return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW;
861 }
862
863 static inline bool vm_need_tpr_shadow(struct kvm *kvm)
864 {
865         return (cpu_has_vmx_tpr_shadow()) && (irqchip_in_kernel(kvm));
866 }
867
868 static inline bool cpu_has_secondary_exec_ctrls(void)
869 {
870         return vmcs_config.cpu_based_exec_ctrl &
871                 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
872 }
873
874 static inline bool cpu_has_vmx_virtualize_apic_accesses(void)
875 {
876         return vmcs_config.cpu_based_2nd_exec_ctrl &
877                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
878 }
879
880 static inline bool cpu_has_vmx_virtualize_x2apic_mode(void)
881 {
882         return vmcs_config.cpu_based_2nd_exec_ctrl &
883                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
884 }
885
886 static inline bool cpu_has_vmx_apic_register_virt(void)
887 {
888         return vmcs_config.cpu_based_2nd_exec_ctrl &
889                 SECONDARY_EXEC_APIC_REGISTER_VIRT;
890 }
891
892 static inline bool cpu_has_vmx_virtual_intr_delivery(void)
893 {
894         return vmcs_config.cpu_based_2nd_exec_ctrl &
895                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY;
896 }
897
898 static inline bool cpu_has_vmx_posted_intr(void)
899 {
900         return vmcs_config.pin_based_exec_ctrl & PIN_BASED_POSTED_INTR;
901 }
902
903 static inline bool cpu_has_vmx_apicv(void)
904 {
905         return cpu_has_vmx_apic_register_virt() &&
906                 cpu_has_vmx_virtual_intr_delivery() &&
907                 cpu_has_vmx_posted_intr();
908 }
909
910 static inline bool cpu_has_vmx_flexpriority(void)
911 {
912         return cpu_has_vmx_tpr_shadow() &&
913                 cpu_has_vmx_virtualize_apic_accesses();
914 }
915
916 static inline bool cpu_has_vmx_ept_execute_only(void)
917 {
918         return vmx_capability.ept & VMX_EPT_EXECUTE_ONLY_BIT;
919 }
920
921 static inline bool cpu_has_vmx_eptp_uncacheable(void)
922 {
923         return vmx_capability.ept & VMX_EPTP_UC_BIT;
924 }
925
926 static inline bool cpu_has_vmx_eptp_writeback(void)
927 {
928         return vmx_capability.ept & VMX_EPTP_WB_BIT;
929 }
930
931 static inline bool cpu_has_vmx_ept_2m_page(void)
932 {
933         return vmx_capability.ept & VMX_EPT_2MB_PAGE_BIT;
934 }
935
936 static inline bool cpu_has_vmx_ept_1g_page(void)
937 {
938         return vmx_capability.ept & VMX_EPT_1GB_PAGE_BIT;
939 }
940
941 static inline bool cpu_has_vmx_ept_4levels(void)
942 {
943         return vmx_capability.ept & VMX_EPT_PAGE_WALK_4_BIT;
944 }
945
946 static inline bool cpu_has_vmx_ept_ad_bits(void)
947 {
948         return vmx_capability.ept & VMX_EPT_AD_BIT;
949 }
950
951 static inline bool cpu_has_vmx_invept_context(void)
952 {
953         return vmx_capability.ept & VMX_EPT_EXTENT_CONTEXT_BIT;
954 }
955
956 static inline bool cpu_has_vmx_invept_global(void)
957 {
958         return vmx_capability.ept & VMX_EPT_EXTENT_GLOBAL_BIT;
959 }
960
961 static inline bool cpu_has_vmx_invvpid_single(void)
962 {
963         return vmx_capability.vpid & VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT;
964 }
965
966 static inline bool cpu_has_vmx_invvpid_global(void)
967 {
968         return vmx_capability.vpid & VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT;
969 }
970
971 static inline bool cpu_has_vmx_ept(void)
972 {
973         return vmcs_config.cpu_based_2nd_exec_ctrl &
974                 SECONDARY_EXEC_ENABLE_EPT;
975 }
976
977 static inline bool cpu_has_vmx_unrestricted_guest(void)
978 {
979         return vmcs_config.cpu_based_2nd_exec_ctrl &
980                 SECONDARY_EXEC_UNRESTRICTED_GUEST;
981 }
982
983 static inline bool cpu_has_vmx_ple(void)
984 {
985         return vmcs_config.cpu_based_2nd_exec_ctrl &
986                 SECONDARY_EXEC_PAUSE_LOOP_EXITING;
987 }
988
989 static inline bool vm_need_virtualize_apic_accesses(struct kvm *kvm)
990 {
991         return flexpriority_enabled && irqchip_in_kernel(kvm);
992 }
993
994 static inline bool cpu_has_vmx_vpid(void)
995 {
996         return vmcs_config.cpu_based_2nd_exec_ctrl &
997                 SECONDARY_EXEC_ENABLE_VPID;
998 }
999
1000 static inline bool cpu_has_vmx_rdtscp(void)
1001 {
1002         return vmcs_config.cpu_based_2nd_exec_ctrl &
1003                 SECONDARY_EXEC_RDTSCP;
1004 }
1005
1006 static inline bool cpu_has_vmx_invpcid(void)
1007 {
1008         return vmcs_config.cpu_based_2nd_exec_ctrl &
1009                 SECONDARY_EXEC_ENABLE_INVPCID;
1010 }
1011
1012 static inline bool cpu_has_virtual_nmis(void)
1013 {
1014         return vmcs_config.pin_based_exec_ctrl & PIN_BASED_VIRTUAL_NMIS;
1015 }
1016
1017 static inline bool cpu_has_vmx_wbinvd_exit(void)
1018 {
1019         return vmcs_config.cpu_based_2nd_exec_ctrl &
1020                 SECONDARY_EXEC_WBINVD_EXITING;
1021 }
1022
1023 static inline bool cpu_has_vmx_shadow_vmcs(void)
1024 {
1025         u64 vmx_msr;
1026         rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
1027         /* check if the cpu supports writing r/o exit information fields */
1028         if (!(vmx_msr & MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS))
1029                 return false;
1030
1031         return vmcs_config.cpu_based_2nd_exec_ctrl &
1032                 SECONDARY_EXEC_SHADOW_VMCS;
1033 }
1034
1035 static inline bool report_flexpriority(void)
1036 {
1037         return flexpriority_enabled;
1038 }
1039
1040 static inline bool nested_cpu_has(struct vmcs12 *vmcs12, u32 bit)
1041 {
1042         return vmcs12->cpu_based_vm_exec_control & bit;
1043 }
1044
1045 static inline bool nested_cpu_has2(struct vmcs12 *vmcs12, u32 bit)
1046 {
1047         return (vmcs12->cpu_based_vm_exec_control &
1048                         CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
1049                 (vmcs12->secondary_vm_exec_control & bit);
1050 }
1051
1052 static inline bool nested_cpu_has_virtual_nmis(struct vmcs12 *vmcs12)
1053 {
1054         return vmcs12->pin_based_vm_exec_control & PIN_BASED_VIRTUAL_NMIS;
1055 }
1056
1057 static inline bool nested_cpu_has_preemption_timer(struct vmcs12 *vmcs12)
1058 {
1059         return vmcs12->pin_based_vm_exec_control &
1060                 PIN_BASED_VMX_PREEMPTION_TIMER;
1061 }
1062
1063 static inline int nested_cpu_has_ept(struct vmcs12 *vmcs12)
1064 {
1065         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_EPT);
1066 }
1067
1068 static inline bool is_exception(u32 intr_info)
1069 {
1070         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1071                 == (INTR_TYPE_HARD_EXCEPTION | INTR_INFO_VALID_MASK);
1072 }
1073
1074 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
1075                               u32 exit_intr_info,
1076                               unsigned long exit_qualification);
1077 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
1078                         struct vmcs12 *vmcs12,
1079                         u32 reason, unsigned long qualification);
1080
1081 static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
1082 {
1083         int i;
1084
1085         for (i = 0; i < vmx->nmsrs; ++i)
1086                 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
1087                         return i;
1088         return -1;
1089 }
1090
1091 static inline void __invvpid(int ext, u16 vpid, gva_t gva)
1092 {
1093     struct {
1094         u64 vpid : 16;
1095         u64 rsvd : 48;
1096         u64 gva;
1097     } operand = { vpid, 0, gva };
1098
1099     asm volatile (__ex(ASM_VMX_INVVPID)
1100                   /* CF==1 or ZF==1 --> rc = -1 */
1101                   "; ja 1f ; ud2 ; 1:"
1102                   : : "a"(&operand), "c"(ext) : "cc", "memory");
1103 }
1104
1105 static inline void __invept(int ext, u64 eptp, gpa_t gpa)
1106 {
1107         struct {
1108                 u64 eptp, gpa;
1109         } operand = {eptp, gpa};
1110
1111         asm volatile (__ex(ASM_VMX_INVEPT)
1112                         /* CF==1 or ZF==1 --> rc = -1 */
1113                         "; ja 1f ; ud2 ; 1:\n"
1114                         : : "a" (&operand), "c" (ext) : "cc", "memory");
1115 }
1116
1117 static struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
1118 {
1119         int i;
1120
1121         i = __find_msr_index(vmx, msr);
1122         if (i >= 0)
1123                 return &vmx->guest_msrs[i];
1124         return NULL;
1125 }
1126
1127 static void vmcs_clear(struct vmcs *vmcs)
1128 {
1129         u64 phys_addr = __pa(vmcs);
1130         u8 error;
1131
1132         asm volatile (__ex(ASM_VMX_VMCLEAR_RAX) "; setna %0"
1133                       : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
1134                       : "cc", "memory");
1135         if (error)
1136                 printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n",
1137                        vmcs, phys_addr);
1138 }
1139
1140 static inline void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
1141 {
1142         vmcs_clear(loaded_vmcs->vmcs);
1143         loaded_vmcs->cpu = -1;
1144         loaded_vmcs->launched = 0;
1145 }
1146
1147 static void vmcs_load(struct vmcs *vmcs)
1148 {
1149         u64 phys_addr = __pa(vmcs);
1150         u8 error;
1151
1152         asm volatile (__ex(ASM_VMX_VMPTRLD_RAX) "; setna %0"
1153                         : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
1154                         : "cc", "memory");
1155         if (error)
1156                 printk(KERN_ERR "kvm: vmptrld %p/%llx failed\n",
1157                        vmcs, phys_addr);
1158 }
1159
1160 #ifdef CONFIG_KEXEC
1161 /*
1162  * This bitmap is used to indicate whether the vmclear
1163  * operation is enabled on all cpus. All disabled by
1164  * default.
1165  */
1166 static cpumask_t crash_vmclear_enabled_bitmap = CPU_MASK_NONE;
1167
1168 static inline void crash_enable_local_vmclear(int cpu)
1169 {
1170         cpumask_set_cpu(cpu, &crash_vmclear_enabled_bitmap);
1171 }
1172
1173 static inline void crash_disable_local_vmclear(int cpu)
1174 {
1175         cpumask_clear_cpu(cpu, &crash_vmclear_enabled_bitmap);
1176 }
1177
1178 static inline int crash_local_vmclear_enabled(int cpu)
1179 {
1180         return cpumask_test_cpu(cpu, &crash_vmclear_enabled_bitmap);
1181 }
1182
1183 static void crash_vmclear_local_loaded_vmcss(void)
1184 {
1185         int cpu = raw_smp_processor_id();
1186         struct loaded_vmcs *v;
1187
1188         if (!crash_local_vmclear_enabled(cpu))
1189                 return;
1190
1191         list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
1192                             loaded_vmcss_on_cpu_link)
1193                 vmcs_clear(v->vmcs);
1194 }
1195 #else
1196 static inline void crash_enable_local_vmclear(int cpu) { }
1197 static inline void crash_disable_local_vmclear(int cpu) { }
1198 #endif /* CONFIG_KEXEC */
1199
1200 static void __loaded_vmcs_clear(void *arg)
1201 {
1202         struct loaded_vmcs *loaded_vmcs = arg;
1203         int cpu = raw_smp_processor_id();
1204
1205         if (loaded_vmcs->cpu != cpu)
1206                 return; /* vcpu migration can race with cpu offline */
1207         if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
1208                 per_cpu(current_vmcs, cpu) = NULL;
1209         crash_disable_local_vmclear(cpu);
1210         list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
1211
1212         /*
1213          * we should ensure updating loaded_vmcs->loaded_vmcss_on_cpu_link
1214          * is before setting loaded_vmcs->vcpu to -1 which is done in
1215          * loaded_vmcs_init. Otherwise, other cpu can see vcpu = -1 fist
1216          * then adds the vmcs into percpu list before it is deleted.
1217          */
1218         smp_wmb();
1219
1220         loaded_vmcs_init(loaded_vmcs);
1221         crash_enable_local_vmclear(cpu);
1222 }
1223
1224 static void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
1225 {
1226         int cpu = loaded_vmcs->cpu;
1227
1228         if (cpu != -1)
1229                 smp_call_function_single(cpu,
1230                          __loaded_vmcs_clear, loaded_vmcs, 1);
1231 }
1232
1233 static inline void vpid_sync_vcpu_single(struct vcpu_vmx *vmx)
1234 {
1235         if (vmx->vpid == 0)
1236                 return;
1237
1238         if (cpu_has_vmx_invvpid_single())
1239                 __invvpid(VMX_VPID_EXTENT_SINGLE_CONTEXT, vmx->vpid, 0);
1240 }
1241
1242 static inline void vpid_sync_vcpu_global(void)
1243 {
1244         if (cpu_has_vmx_invvpid_global())
1245                 __invvpid(VMX_VPID_EXTENT_ALL_CONTEXT, 0, 0);
1246 }
1247
1248 static inline void vpid_sync_context(struct vcpu_vmx *vmx)
1249 {
1250         if (cpu_has_vmx_invvpid_single())
1251                 vpid_sync_vcpu_single(vmx);
1252         else
1253                 vpid_sync_vcpu_global();
1254 }
1255
1256 static inline void ept_sync_global(void)
1257 {
1258         if (cpu_has_vmx_invept_global())
1259                 __invept(VMX_EPT_EXTENT_GLOBAL, 0, 0);
1260 }
1261
1262 static inline void ept_sync_context(u64 eptp)
1263 {
1264         if (enable_ept) {
1265                 if (cpu_has_vmx_invept_context())
1266                         __invept(VMX_EPT_EXTENT_CONTEXT, eptp, 0);
1267                 else
1268                         ept_sync_global();
1269         }
1270 }
1271
1272 static __always_inline unsigned long vmcs_readl(unsigned long field)
1273 {
1274         unsigned long value;
1275
1276         asm volatile (__ex_clear(ASM_VMX_VMREAD_RDX_RAX, "%0")
1277                       : "=a"(value) : "d"(field) : "cc");
1278         return value;
1279 }
1280
1281 static __always_inline u16 vmcs_read16(unsigned long field)
1282 {
1283         return vmcs_readl(field);
1284 }
1285
1286 static __always_inline u32 vmcs_read32(unsigned long field)
1287 {
1288         return vmcs_readl(field);
1289 }
1290
1291 static __always_inline u64 vmcs_read64(unsigned long field)
1292 {
1293 #ifdef CONFIG_X86_64
1294         return vmcs_readl(field);
1295 #else
1296         return vmcs_readl(field) | ((u64)vmcs_readl(field+1) << 32);
1297 #endif
1298 }
1299
1300 static noinline void vmwrite_error(unsigned long field, unsigned long value)
1301 {
1302         printk(KERN_ERR "vmwrite error: reg %lx value %lx (err %d)\n",
1303                field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
1304         dump_stack();
1305 }
1306
1307 static void vmcs_writel(unsigned long field, unsigned long value)
1308 {
1309         u8 error;
1310
1311         asm volatile (__ex(ASM_VMX_VMWRITE_RAX_RDX) "; setna %0"
1312                        : "=q"(error) : "a"(value), "d"(field) : "cc");
1313         if (unlikely(error))
1314                 vmwrite_error(field, value);
1315 }
1316
1317 static void vmcs_write16(unsigned long field, u16 value)
1318 {
1319         vmcs_writel(field, value);
1320 }
1321
1322 static void vmcs_write32(unsigned long field, u32 value)
1323 {
1324         vmcs_writel(field, value);
1325 }
1326
1327 static void vmcs_write64(unsigned long field, u64 value)
1328 {
1329         vmcs_writel(field, value);
1330 #ifndef CONFIG_X86_64
1331         asm volatile ("");
1332         vmcs_writel(field+1, value >> 32);
1333 #endif
1334 }
1335
1336 static void vmcs_clear_bits(unsigned long field, u32 mask)
1337 {
1338         vmcs_writel(field, vmcs_readl(field) & ~mask);
1339 }
1340
1341 static void vmcs_set_bits(unsigned long field, u32 mask)
1342 {
1343         vmcs_writel(field, vmcs_readl(field) | mask);
1344 }
1345
1346 static inline void vm_entry_controls_init(struct vcpu_vmx *vmx, u32 val)
1347 {
1348         vmcs_write32(VM_ENTRY_CONTROLS, val);
1349         vmx->vm_entry_controls_shadow = val;
1350 }
1351
1352 static inline void vm_entry_controls_set(struct vcpu_vmx *vmx, u32 val)
1353 {
1354         if (vmx->vm_entry_controls_shadow != val)
1355                 vm_entry_controls_init(vmx, val);
1356 }
1357
1358 static inline u32 vm_entry_controls_get(struct vcpu_vmx *vmx)
1359 {
1360         return vmx->vm_entry_controls_shadow;
1361 }
1362
1363
1364 static inline void vm_entry_controls_setbit(struct vcpu_vmx *vmx, u32 val)
1365 {
1366         vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) | val);
1367 }
1368
1369 static inline void vm_entry_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
1370 {
1371         vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) & ~val);
1372 }
1373
1374 static inline void vm_exit_controls_init(struct vcpu_vmx *vmx, u32 val)
1375 {
1376         vmcs_write32(VM_EXIT_CONTROLS, val);
1377         vmx->vm_exit_controls_shadow = val;
1378 }
1379
1380 static inline void vm_exit_controls_set(struct vcpu_vmx *vmx, u32 val)
1381 {
1382         if (vmx->vm_exit_controls_shadow != val)
1383                 vm_exit_controls_init(vmx, val);
1384 }
1385
1386 static inline u32 vm_exit_controls_get(struct vcpu_vmx *vmx)
1387 {
1388         return vmx->vm_exit_controls_shadow;
1389 }
1390
1391
1392 static inline void vm_exit_controls_setbit(struct vcpu_vmx *vmx, u32 val)
1393 {
1394         vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) | val);
1395 }
1396
1397 static inline void vm_exit_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
1398 {
1399         vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) & ~val);
1400 }
1401
1402 static void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
1403 {
1404         vmx->segment_cache.bitmask = 0;
1405 }
1406
1407 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
1408                                        unsigned field)
1409 {
1410         bool ret;
1411         u32 mask = 1 << (seg * SEG_FIELD_NR + field);
1412
1413         if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
1414                 vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
1415                 vmx->segment_cache.bitmask = 0;
1416         }
1417         ret = vmx->segment_cache.bitmask & mask;
1418         vmx->segment_cache.bitmask |= mask;
1419         return ret;
1420 }
1421
1422 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
1423 {
1424         u16 *p = &vmx->segment_cache.seg[seg].selector;
1425
1426         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
1427                 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
1428         return *p;
1429 }
1430
1431 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
1432 {
1433         ulong *p = &vmx->segment_cache.seg[seg].base;
1434
1435         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
1436                 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
1437         return *p;
1438 }
1439
1440 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
1441 {
1442         u32 *p = &vmx->segment_cache.seg[seg].limit;
1443
1444         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
1445                 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
1446         return *p;
1447 }
1448
1449 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
1450 {
1451         u32 *p = &vmx->segment_cache.seg[seg].ar;
1452
1453         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
1454                 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
1455         return *p;
1456 }
1457
1458 static void update_exception_bitmap(struct kvm_vcpu *vcpu)
1459 {
1460         u32 eb;
1461
1462         eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
1463              (1u << NM_VECTOR) | (1u << DB_VECTOR);
1464         if ((vcpu->guest_debug &
1465              (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
1466             (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
1467                 eb |= 1u << BP_VECTOR;
1468         if (to_vmx(vcpu)->rmode.vm86_active)
1469                 eb = ~0;
1470         if (enable_ept)
1471                 eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
1472         if (vcpu->fpu_active)
1473                 eb &= ~(1u << NM_VECTOR);
1474
1475         /* When we are running a nested L2 guest and L1 specified for it a
1476          * certain exception bitmap, we must trap the same exceptions and pass
1477          * them to L1. When running L2, we will only handle the exceptions
1478          * specified above if L1 did not want them.
1479          */
1480         if (is_guest_mode(vcpu))
1481                 eb |= get_vmcs12(vcpu)->exception_bitmap;
1482
1483         vmcs_write32(EXCEPTION_BITMAP, eb);
1484 }
1485
1486 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
1487                 unsigned long entry, unsigned long exit)
1488 {
1489         vm_entry_controls_clearbit(vmx, entry);
1490         vm_exit_controls_clearbit(vmx, exit);
1491 }
1492
1493 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
1494 {
1495         unsigned i;
1496         struct msr_autoload *m = &vmx->msr_autoload;
1497
1498         switch (msr) {
1499         case MSR_EFER:
1500                 if (cpu_has_load_ia32_efer) {
1501                         clear_atomic_switch_msr_special(vmx,
1502                                         VM_ENTRY_LOAD_IA32_EFER,
1503                                         VM_EXIT_LOAD_IA32_EFER);
1504                         return;
1505                 }
1506                 break;
1507         case MSR_CORE_PERF_GLOBAL_CTRL:
1508                 if (cpu_has_load_perf_global_ctrl) {
1509                         clear_atomic_switch_msr_special(vmx,
1510                                         VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
1511                                         VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
1512                         return;
1513                 }
1514                 break;
1515         }
1516
1517         for (i = 0; i < m->nr; ++i)
1518                 if (m->guest[i].index == msr)
1519                         break;
1520
1521         if (i == m->nr)
1522                 return;
1523         --m->nr;
1524         m->guest[i] = m->guest[m->nr];
1525         m->host[i] = m->host[m->nr];
1526         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
1527         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
1528 }
1529
1530 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
1531                 unsigned long entry, unsigned long exit,
1532                 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
1533                 u64 guest_val, u64 host_val)
1534 {
1535         vmcs_write64(guest_val_vmcs, guest_val);
1536         vmcs_write64(host_val_vmcs, host_val);
1537         vm_entry_controls_setbit(vmx, entry);
1538         vm_exit_controls_setbit(vmx, exit);
1539 }
1540
1541 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
1542                                   u64 guest_val, u64 host_val)
1543 {
1544         unsigned i;
1545         struct msr_autoload *m = &vmx->msr_autoload;
1546
1547         switch (msr) {
1548         case MSR_EFER:
1549                 if (cpu_has_load_ia32_efer) {
1550                         add_atomic_switch_msr_special(vmx,
1551                                         VM_ENTRY_LOAD_IA32_EFER,
1552                                         VM_EXIT_LOAD_IA32_EFER,
1553                                         GUEST_IA32_EFER,
1554                                         HOST_IA32_EFER,
1555                                         guest_val, host_val);
1556                         return;
1557                 }
1558                 break;
1559         case MSR_CORE_PERF_GLOBAL_CTRL:
1560                 if (cpu_has_load_perf_global_ctrl) {
1561                         add_atomic_switch_msr_special(vmx,
1562                                         VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
1563                                         VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
1564                                         GUEST_IA32_PERF_GLOBAL_CTRL,
1565                                         HOST_IA32_PERF_GLOBAL_CTRL,
1566                                         guest_val, host_val);
1567                         return;
1568                 }
1569                 break;
1570         }
1571
1572         for (i = 0; i < m->nr; ++i)
1573                 if (m->guest[i].index == msr)
1574                         break;
1575
1576         if (i == NR_AUTOLOAD_MSRS) {
1577                 printk_once(KERN_WARNING "Not enough msr switch entries. "
1578                                 "Can't add msr %x\n", msr);
1579                 return;
1580         } else if (i == m->nr) {
1581                 ++m->nr;
1582                 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
1583                 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
1584         }
1585
1586         m->guest[i].index = msr;
1587         m->guest[i].value = guest_val;
1588         m->host[i].index = msr;
1589         m->host[i].value = host_val;
1590 }
1591
1592 static void reload_tss(void)
1593 {
1594         /*
1595          * VT restores TR but not its size.  Useless.
1596          */
1597         struct desc_ptr *gdt = &__get_cpu_var(host_gdt);
1598         struct desc_struct *descs;
1599
1600         descs = (void *)gdt->address;
1601         descs[GDT_ENTRY_TSS].type = 9; /* available TSS */
1602         load_TR_desc();
1603 }
1604
1605 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
1606 {
1607         u64 guest_efer;
1608         u64 ignore_bits;
1609
1610         guest_efer = vmx->vcpu.arch.efer;
1611
1612         /*
1613          * NX is emulated; LMA and LME handled by hardware; SCE meaningless
1614          * outside long mode
1615          */
1616         ignore_bits = EFER_NX | EFER_SCE;
1617 #ifdef CONFIG_X86_64
1618         ignore_bits |= EFER_LMA | EFER_LME;
1619         /* SCE is meaningful only in long mode on Intel */
1620         if (guest_efer & EFER_LMA)
1621                 ignore_bits &= ~(u64)EFER_SCE;
1622 #endif
1623         guest_efer &= ~ignore_bits;
1624         guest_efer |= host_efer & ignore_bits;
1625         vmx->guest_msrs[efer_offset].data = guest_efer;
1626         vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
1627
1628         clear_atomic_switch_msr(vmx, MSR_EFER);
1629         /* On ept, can't emulate nx, and must switch nx atomically */
1630         if (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX)) {
1631                 guest_efer = vmx->vcpu.arch.efer;
1632                 if (!(guest_efer & EFER_LMA))
1633                         guest_efer &= ~EFER_LME;
1634                 add_atomic_switch_msr(vmx, MSR_EFER, guest_efer, host_efer);
1635                 return false;
1636         }
1637
1638         return true;
1639 }
1640
1641 static unsigned long segment_base(u16 selector)
1642 {
1643         struct desc_ptr *gdt = &__get_cpu_var(host_gdt);
1644         struct desc_struct *d;
1645         unsigned long table_base;
1646         unsigned long v;
1647
1648         if (!(selector & ~3))
1649                 return 0;
1650
1651         table_base = gdt->address;
1652
1653         if (selector & 4) {           /* from ldt */
1654                 u16 ldt_selector = kvm_read_ldt();
1655
1656                 if (!(ldt_selector & ~3))
1657                         return 0;
1658
1659                 table_base = segment_base(ldt_selector);
1660         }
1661         d = (struct desc_struct *)(table_base + (selector & ~7));
1662         v = get_desc_base(d);
1663 #ifdef CONFIG_X86_64
1664        if (d->s == 0 && (d->type == 2 || d->type == 9 || d->type == 11))
1665                v |= ((unsigned long)((struct ldttss_desc64 *)d)->base3) << 32;
1666 #endif
1667         return v;
1668 }
1669
1670 static inline unsigned long kvm_read_tr_base(void)
1671 {
1672         u16 tr;
1673         asm("str %0" : "=g"(tr));
1674         return segment_base(tr);
1675 }
1676
1677 static void vmx_save_host_state(struct kvm_vcpu *vcpu)
1678 {
1679         struct vcpu_vmx *vmx = to_vmx(vcpu);
1680         int i;
1681
1682         if (vmx->host_state.loaded)
1683                 return;
1684
1685         vmx->host_state.loaded = 1;
1686         /*
1687          * Set host fs and gs selectors.  Unfortunately, 22.2.3 does not
1688          * allow segment selectors with cpl > 0 or ti == 1.
1689          */
1690         vmx->host_state.ldt_sel = kvm_read_ldt();
1691         vmx->host_state.gs_ldt_reload_needed = vmx->host_state.ldt_sel;
1692         savesegment(fs, vmx->host_state.fs_sel);
1693         if (!(vmx->host_state.fs_sel & 7)) {
1694                 vmcs_write16(HOST_FS_SELECTOR, vmx->host_state.fs_sel);
1695                 vmx->host_state.fs_reload_needed = 0;
1696         } else {
1697                 vmcs_write16(HOST_FS_SELECTOR, 0);
1698                 vmx->host_state.fs_reload_needed = 1;
1699         }
1700         savesegment(gs, vmx->host_state.gs_sel);
1701         if (!(vmx->host_state.gs_sel & 7))
1702                 vmcs_write16(HOST_GS_SELECTOR, vmx->host_state.gs_sel);
1703         else {
1704                 vmcs_write16(HOST_GS_SELECTOR, 0);
1705                 vmx->host_state.gs_ldt_reload_needed = 1;
1706         }
1707
1708 #ifdef CONFIG_X86_64
1709         savesegment(ds, vmx->host_state.ds_sel);
1710         savesegment(es, vmx->host_state.es_sel);
1711 #endif
1712
1713 #ifdef CONFIG_X86_64
1714         vmcs_writel(HOST_FS_BASE, read_msr(MSR_FS_BASE));
1715         vmcs_writel(HOST_GS_BASE, read_msr(MSR_GS_BASE));
1716 #else
1717         vmcs_writel(HOST_FS_BASE, segment_base(vmx->host_state.fs_sel));
1718         vmcs_writel(HOST_GS_BASE, segment_base(vmx->host_state.gs_sel));
1719 #endif
1720
1721 #ifdef CONFIG_X86_64
1722         rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1723         if (is_long_mode(&vmx->vcpu))
1724                 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1725 #endif
1726         if (boot_cpu_has(X86_FEATURE_MPX))
1727                 rdmsrl(MSR_IA32_BNDCFGS, vmx->host_state.msr_host_bndcfgs);
1728         for (i = 0; i < vmx->save_nmsrs; ++i)
1729                 kvm_set_shared_msr(vmx->guest_msrs[i].index,
1730                                    vmx->guest_msrs[i].data,
1731                                    vmx->guest_msrs[i].mask);
1732 }
1733
1734 static void __vmx_load_host_state(struct vcpu_vmx *vmx)
1735 {
1736         if (!vmx->host_state.loaded)
1737                 return;
1738
1739         ++vmx->vcpu.stat.host_state_reload;
1740         vmx->host_state.loaded = 0;
1741 #ifdef CONFIG_X86_64
1742         if (is_long_mode(&vmx->vcpu))
1743                 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1744 #endif
1745         if (vmx->host_state.gs_ldt_reload_needed) {
1746                 kvm_load_ldt(vmx->host_state.ldt_sel);
1747 #ifdef CONFIG_X86_64
1748                 load_gs_index(vmx->host_state.gs_sel);
1749 #else
1750                 loadsegment(gs, vmx->host_state.gs_sel);
1751 #endif
1752         }
1753         if (vmx->host_state.fs_reload_needed)
1754                 loadsegment(fs, vmx->host_state.fs_sel);
1755 #ifdef CONFIG_X86_64
1756         if (unlikely(vmx->host_state.ds_sel | vmx->host_state.es_sel)) {
1757                 loadsegment(ds, vmx->host_state.ds_sel);
1758                 loadsegment(es, vmx->host_state.es_sel);
1759         }
1760 #endif
1761         reload_tss();
1762 #ifdef CONFIG_X86_64
1763         wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1764 #endif
1765         if (vmx->host_state.msr_host_bndcfgs)
1766                 wrmsrl(MSR_IA32_BNDCFGS, vmx->host_state.msr_host_bndcfgs);
1767         /*
1768          * If the FPU is not active (through the host task or
1769          * the guest vcpu), then restore the cr0.TS bit.
1770          */
1771         if (!user_has_fpu() && !vmx->vcpu.guest_fpu_loaded)
1772                 stts();
1773         load_gdt(&__get_cpu_var(host_gdt));
1774 }
1775
1776 static void vmx_load_host_state(struct vcpu_vmx *vmx)
1777 {
1778         preempt_disable();
1779         __vmx_load_host_state(vmx);
1780         preempt_enable();
1781 }
1782
1783 /*
1784  * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1785  * vcpu mutex is already taken.
1786  */
1787 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1788 {
1789         struct vcpu_vmx *vmx = to_vmx(vcpu);
1790         u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
1791
1792         if (!vmm_exclusive)
1793                 kvm_cpu_vmxon(phys_addr);
1794         else if (vmx->loaded_vmcs->cpu != cpu)
1795                 loaded_vmcs_clear(vmx->loaded_vmcs);
1796
1797         if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
1798                 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1799                 vmcs_load(vmx->loaded_vmcs->vmcs);
1800         }
1801
1802         if (vmx->loaded_vmcs->cpu != cpu) {
1803                 struct desc_ptr *gdt = &__get_cpu_var(host_gdt);
1804                 unsigned long sysenter_esp;
1805
1806                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1807                 local_irq_disable();
1808                 crash_disable_local_vmclear(cpu);
1809
1810                 /*
1811                  * Read loaded_vmcs->cpu should be before fetching
1812                  * loaded_vmcs->loaded_vmcss_on_cpu_link.
1813                  * See the comments in __loaded_vmcs_clear().
1814                  */
1815                 smp_rmb();
1816
1817                 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1818                          &per_cpu(loaded_vmcss_on_cpu, cpu));
1819                 crash_enable_local_vmclear(cpu);
1820                 local_irq_enable();
1821
1822                 /*
1823                  * Linux uses per-cpu TSS and GDT, so set these when switching
1824                  * processors.
1825                  */
1826                 vmcs_writel(HOST_TR_BASE, kvm_read_tr_base()); /* 22.2.4 */
1827                 vmcs_writel(HOST_GDTR_BASE, gdt->address);   /* 22.2.4 */
1828
1829                 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
1830                 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
1831                 vmx->loaded_vmcs->cpu = cpu;
1832         }
1833 }
1834
1835 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1836 {
1837         __vmx_load_host_state(to_vmx(vcpu));
1838         if (!vmm_exclusive) {
1839                 __loaded_vmcs_clear(to_vmx(vcpu)->loaded_vmcs);
1840                 vcpu->cpu = -1;
1841                 kvm_cpu_vmxoff();
1842         }
1843 }
1844
1845 static void vmx_fpu_activate(struct kvm_vcpu *vcpu)
1846 {
1847         ulong cr0;
1848
1849         if (vcpu->fpu_active)
1850                 return;
1851         vcpu->fpu_active = 1;
1852         cr0 = vmcs_readl(GUEST_CR0);
1853         cr0 &= ~(X86_CR0_TS | X86_CR0_MP);
1854         cr0 |= kvm_read_cr0_bits(vcpu, X86_CR0_TS | X86_CR0_MP);
1855         vmcs_writel(GUEST_CR0, cr0);
1856         update_exception_bitmap(vcpu);
1857         vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
1858         if (is_guest_mode(vcpu))
1859                 vcpu->arch.cr0_guest_owned_bits &=
1860                         ~get_vmcs12(vcpu)->cr0_guest_host_mask;
1861         vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
1862 }
1863
1864 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
1865
1866 /*
1867  * Return the cr0 value that a nested guest would read. This is a combination
1868  * of the real cr0 used to run the guest (guest_cr0), and the bits shadowed by
1869  * its hypervisor (cr0_read_shadow).
1870  */
1871 static inline unsigned long nested_read_cr0(struct vmcs12 *fields)
1872 {
1873         return (fields->guest_cr0 & ~fields->cr0_guest_host_mask) |
1874                 (fields->cr0_read_shadow & fields->cr0_guest_host_mask);
1875 }
1876 static inline unsigned long nested_read_cr4(struct vmcs12 *fields)
1877 {
1878         return (fields->guest_cr4 & ~fields->cr4_guest_host_mask) |
1879                 (fields->cr4_read_shadow & fields->cr4_guest_host_mask);
1880 }
1881
1882 static void vmx_fpu_deactivate(struct kvm_vcpu *vcpu)
1883 {
1884         /* Note that there is no vcpu->fpu_active = 0 here. The caller must
1885          * set this *before* calling this function.
1886          */
1887         vmx_decache_cr0_guest_bits(vcpu);
1888         vmcs_set_bits(GUEST_CR0, X86_CR0_TS | X86_CR0_MP);
1889         update_exception_bitmap(vcpu);
1890         vcpu->arch.cr0_guest_owned_bits = 0;
1891         vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
1892         if (is_guest_mode(vcpu)) {
1893                 /*
1894                  * L1's specified read shadow might not contain the TS bit,
1895                  * so now that we turned on shadowing of this bit, we need to
1896                  * set this bit of the shadow. Like in nested_vmx_run we need
1897                  * nested_read_cr0(vmcs12), but vmcs12->guest_cr0 is not yet
1898                  * up-to-date here because we just decached cr0.TS (and we'll
1899                  * only update vmcs12->guest_cr0 on nested exit).
1900                  */
1901                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1902                 vmcs12->guest_cr0 = (vmcs12->guest_cr0 & ~X86_CR0_TS) |
1903                         (vcpu->arch.cr0 & X86_CR0_TS);
1904                 vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
1905         } else
1906                 vmcs_writel(CR0_READ_SHADOW, vcpu->arch.cr0);
1907 }
1908
1909 static unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
1910 {
1911         unsigned long rflags, save_rflags;
1912
1913         if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
1914                 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
1915                 rflags = vmcs_readl(GUEST_RFLAGS);
1916                 if (to_vmx(vcpu)->rmode.vm86_active) {
1917                         rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1918                         save_rflags = to_vmx(vcpu)->rmode.save_rflags;
1919                         rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1920                 }
1921                 to_vmx(vcpu)->rflags = rflags;
1922         }
1923         return to_vmx(vcpu)->rflags;
1924 }
1925
1926 static void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1927 {
1928         __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
1929         to_vmx(vcpu)->rflags = rflags;
1930         if (to_vmx(vcpu)->rmode.vm86_active) {
1931                 to_vmx(vcpu)->rmode.save_rflags = rflags;
1932                 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1933         }
1934         vmcs_writel(GUEST_RFLAGS, rflags);
1935 }
1936
1937 static u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1938 {
1939         u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1940         int ret = 0;
1941
1942         if (interruptibility & GUEST_INTR_STATE_STI)
1943                 ret |= KVM_X86_SHADOW_INT_STI;
1944         if (interruptibility & GUEST_INTR_STATE_MOV_SS)
1945                 ret |= KVM_X86_SHADOW_INT_MOV_SS;
1946
1947         return ret & mask;
1948 }
1949
1950 static void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1951 {
1952         u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1953         u32 interruptibility = interruptibility_old;
1954
1955         interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1956
1957         if (mask & KVM_X86_SHADOW_INT_MOV_SS)
1958                 interruptibility |= GUEST_INTR_STATE_MOV_SS;
1959         else if (mask & KVM_X86_SHADOW_INT_STI)
1960                 interruptibility |= GUEST_INTR_STATE_STI;
1961
1962         if ((interruptibility != interruptibility_old))
1963                 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1964 }
1965
1966 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
1967 {
1968         unsigned long rip;
1969
1970         rip = kvm_rip_read(vcpu);
1971         rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1972         kvm_rip_write(vcpu, rip);
1973
1974         /* skipping an emulated instruction also counts */
1975         vmx_set_interrupt_shadow(vcpu, 0);
1976 }
1977
1978 /*
1979  * KVM wants to inject page-faults which it got to the guest. This function
1980  * checks whether in a nested guest, we need to inject them to L1 or L2.
1981  */
1982 static int nested_vmx_check_exception(struct kvm_vcpu *vcpu, unsigned nr)
1983 {
1984         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1985
1986         if (!(vmcs12->exception_bitmap & (1u << nr)))
1987                 return 0;
1988
1989         nested_vmx_vmexit(vcpu, to_vmx(vcpu)->exit_reason,
1990                           vmcs_read32(VM_EXIT_INTR_INFO),
1991                           vmcs_readl(EXIT_QUALIFICATION));
1992         return 1;
1993 }
1994
1995 static void vmx_queue_exception(struct kvm_vcpu *vcpu, unsigned nr,
1996                                 bool has_error_code, u32 error_code,
1997                                 bool reinject)
1998 {
1999         struct vcpu_vmx *vmx = to_vmx(vcpu);
2000         u32 intr_info = nr | INTR_INFO_VALID_MASK;
2001
2002         if (!reinject && is_guest_mode(vcpu) &&
2003             nested_vmx_check_exception(vcpu, nr))
2004                 return;
2005
2006         if (has_error_code) {
2007                 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
2008                 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
2009         }
2010
2011         if (vmx->rmode.vm86_active) {
2012                 int inc_eip = 0;
2013                 if (kvm_exception_is_soft(nr))
2014                         inc_eip = vcpu->arch.event_exit_inst_len;
2015                 if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
2016                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2017                 return;
2018         }
2019
2020         if (kvm_exception_is_soft(nr)) {
2021                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
2022                              vmx->vcpu.arch.event_exit_inst_len);
2023                 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
2024         } else
2025                 intr_info |= INTR_TYPE_HARD_EXCEPTION;
2026
2027         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
2028 }
2029
2030 static bool vmx_rdtscp_supported(void)
2031 {
2032         return cpu_has_vmx_rdtscp();
2033 }
2034
2035 static bool vmx_invpcid_supported(void)
2036 {
2037         return cpu_has_vmx_invpcid() && enable_ept;
2038 }
2039
2040 /*
2041  * Swap MSR entry in host/guest MSR entry array.
2042  */
2043 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
2044 {
2045         struct shared_msr_entry tmp;
2046
2047         tmp = vmx->guest_msrs[to];
2048         vmx->guest_msrs[to] = vmx->guest_msrs[from];
2049         vmx->guest_msrs[from] = tmp;
2050 }
2051
2052 static void vmx_set_msr_bitmap(struct kvm_vcpu *vcpu)
2053 {
2054         unsigned long *msr_bitmap;
2055
2056         if (irqchip_in_kernel(vcpu->kvm) && apic_x2apic_mode(vcpu->arch.apic)) {
2057                 if (is_long_mode(vcpu))
2058                         msr_bitmap = vmx_msr_bitmap_longmode_x2apic;
2059                 else
2060                         msr_bitmap = vmx_msr_bitmap_legacy_x2apic;
2061         } else {
2062                 if (is_long_mode(vcpu))
2063                         msr_bitmap = vmx_msr_bitmap_longmode;
2064                 else
2065                         msr_bitmap = vmx_msr_bitmap_legacy;
2066         }
2067
2068         vmcs_write64(MSR_BITMAP, __pa(msr_bitmap));
2069 }
2070
2071 /*
2072  * Set up the vmcs to automatically save and restore system
2073  * msrs.  Don't touch the 64-bit msrs if the guest is in legacy
2074  * mode, as fiddling with msrs is very expensive.
2075  */
2076 static void setup_msrs(struct vcpu_vmx *vmx)
2077 {
2078         int save_nmsrs, index;
2079
2080         save_nmsrs = 0;
2081 #ifdef CONFIG_X86_64
2082         if (is_long_mode(&vmx->vcpu)) {
2083                 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
2084                 if (index >= 0)
2085                         move_msr_up(vmx, index, save_nmsrs++);
2086                 index = __find_msr_index(vmx, MSR_LSTAR);
2087                 if (index >= 0)
2088                         move_msr_up(vmx, index, save_nmsrs++);
2089                 index = __find_msr_index(vmx, MSR_CSTAR);
2090                 if (index >= 0)
2091                         move_msr_up(vmx, index, save_nmsrs++);
2092                 index = __find_msr_index(vmx, MSR_TSC_AUX);
2093                 if (index >= 0 && vmx->rdtscp_enabled)
2094                         move_msr_up(vmx, index, save_nmsrs++);
2095                 /*
2096                  * MSR_STAR is only needed on long mode guests, and only
2097                  * if efer.sce is enabled.
2098                  */
2099                 index = __find_msr_index(vmx, MSR_STAR);
2100                 if ((index >= 0) && (vmx->vcpu.arch.efer & EFER_SCE))
2101                         move_msr_up(vmx, index, save_nmsrs++);
2102         }
2103 #endif
2104         index = __find_msr_index(vmx, MSR_EFER);
2105         if (index >= 0 && update_transition_efer(vmx, index))
2106                 move_msr_up(vmx, index, save_nmsrs++);
2107
2108         vmx->save_nmsrs = save_nmsrs;
2109
2110         if (cpu_has_vmx_msr_bitmap())
2111                 vmx_set_msr_bitmap(&vmx->vcpu);
2112 }
2113
2114 /*
2115  * reads and returns guest's timestamp counter "register"
2116  * guest_tsc = host_tsc + tsc_offset    -- 21.3
2117  */
2118 static u64 guest_read_tsc(void)
2119 {
2120         u64 host_tsc, tsc_offset;
2121
2122         rdtscll(host_tsc);
2123         tsc_offset = vmcs_read64(TSC_OFFSET);
2124         return host_tsc + tsc_offset;
2125 }
2126
2127 /*
2128  * Like guest_read_tsc, but always returns L1's notion of the timestamp
2129  * counter, even if a nested guest (L2) is currently running.
2130  */
2131 u64 vmx_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
2132 {
2133         u64 tsc_offset;
2134
2135         tsc_offset = is_guest_mode(vcpu) ?
2136                 to_vmx(vcpu)->nested.vmcs01_tsc_offset :
2137                 vmcs_read64(TSC_OFFSET);
2138         return host_tsc + tsc_offset;
2139 }
2140
2141 /*
2142  * Engage any workarounds for mis-matched TSC rates.  Currently limited to
2143  * software catchup for faster rates on slower CPUs.
2144  */
2145 static void vmx_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
2146 {
2147         if (!scale)
2148                 return;
2149
2150         if (user_tsc_khz > tsc_khz) {
2151                 vcpu->arch.tsc_catchup = 1;
2152                 vcpu->arch.tsc_always_catchup = 1;
2153         } else
2154                 WARN(1, "user requested TSC rate below hardware speed\n");
2155 }
2156
2157 static u64 vmx_read_tsc_offset(struct kvm_vcpu *vcpu)
2158 {
2159         return vmcs_read64(TSC_OFFSET);
2160 }
2161
2162 /*
2163  * writes 'offset' into guest's timestamp counter offset register
2164  */
2165 static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
2166 {
2167         if (is_guest_mode(vcpu)) {
2168                 /*
2169                  * We're here if L1 chose not to trap WRMSR to TSC. According
2170                  * to the spec, this should set L1's TSC; The offset that L1
2171                  * set for L2 remains unchanged, and still needs to be added
2172                  * to the newly set TSC to get L2's TSC.
2173                  */
2174                 struct vmcs12 *vmcs12;
2175                 to_vmx(vcpu)->nested.vmcs01_tsc_offset = offset;
2176                 /* recalculate vmcs02.TSC_OFFSET: */
2177                 vmcs12 = get_vmcs12(vcpu);
2178                 vmcs_write64(TSC_OFFSET, offset +
2179                         (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETING) ?
2180                          vmcs12->tsc_offset : 0));
2181         } else {
2182                 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
2183                                            vmcs_read64(TSC_OFFSET), offset);
2184                 vmcs_write64(TSC_OFFSET, offset);
2185         }
2186 }
2187
2188 static void vmx_adjust_tsc_offset(struct kvm_vcpu *vcpu, s64 adjustment, bool host)
2189 {
2190         u64 offset = vmcs_read64(TSC_OFFSET);
2191
2192         vmcs_write64(TSC_OFFSET, offset + adjustment);
2193         if (is_guest_mode(vcpu)) {
2194                 /* Even when running L2, the adjustment needs to apply to L1 */
2195                 to_vmx(vcpu)->nested.vmcs01_tsc_offset += adjustment;
2196         } else
2197                 trace_kvm_write_tsc_offset(vcpu->vcpu_id, offset,
2198                                            offset + adjustment);
2199 }
2200
2201 static u64 vmx_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
2202 {
2203         return target_tsc - native_read_tsc();
2204 }
2205
2206 static bool guest_cpuid_has_vmx(struct kvm_vcpu *vcpu)
2207 {
2208         struct kvm_cpuid_entry2 *best = kvm_find_cpuid_entry(vcpu, 1, 0);
2209         return best && (best->ecx & (1 << (X86_FEATURE_VMX & 31)));
2210 }
2211
2212 /*
2213  * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
2214  * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
2215  * all guests if the "nested" module option is off, and can also be disabled
2216  * for a single guest by disabling its VMX cpuid bit.
2217  */
2218 static inline bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
2219 {
2220         return nested && guest_cpuid_has_vmx(vcpu);
2221 }
2222
2223 /*
2224  * nested_vmx_setup_ctls_msrs() sets up variables containing the values to be
2225  * returned for the various VMX controls MSRs when nested VMX is enabled.
2226  * The same values should also be used to verify that vmcs12 control fields are
2227  * valid during nested entry from L1 to L2.
2228  * Each of these control msrs has a low and high 32-bit half: A low bit is on
2229  * if the corresponding bit in the (32-bit) control field *must* be on, and a
2230  * bit in the high half is on if the corresponding bit in the control field
2231  * may be on. See also vmx_control_verify().
2232  * TODO: allow these variables to be modified (downgraded) by module options
2233  * or other means.
2234  */
2235 static u32 nested_vmx_procbased_ctls_low, nested_vmx_procbased_ctls_high;
2236 static u32 nested_vmx_secondary_ctls_low, nested_vmx_secondary_ctls_high;
2237 static u32 nested_vmx_pinbased_ctls_low, nested_vmx_pinbased_ctls_high;
2238 static u32 nested_vmx_exit_ctls_low, nested_vmx_exit_ctls_high;
2239 static u32 nested_vmx_entry_ctls_low, nested_vmx_entry_ctls_high;
2240 static u32 nested_vmx_misc_low, nested_vmx_misc_high;
2241 static u32 nested_vmx_ept_caps;
2242 static __init void nested_vmx_setup_ctls_msrs(void)
2243 {
2244         /*
2245          * Note that as a general rule, the high half of the MSRs (bits in
2246          * the control fields which may be 1) should be initialized by the
2247          * intersection of the underlying hardware's MSR (i.e., features which
2248          * can be supported) and the list of features we want to expose -
2249          * because they are known to be properly supported in our code.
2250          * Also, usually, the low half of the MSRs (bits which must be 1) can
2251          * be set to 0, meaning that L1 may turn off any of these bits. The
2252          * reason is that if one of these bits is necessary, it will appear
2253          * in vmcs01 and prepare_vmcs02, when it bitwise-or's the control
2254          * fields of vmcs01 and vmcs02, will turn these bits off - and
2255          * nested_vmx_exit_handled() will not pass related exits to L1.
2256          * These rules have exceptions below.
2257          */
2258
2259         /* pin-based controls */
2260         rdmsr(MSR_IA32_VMX_PINBASED_CTLS,
2261               nested_vmx_pinbased_ctls_low, nested_vmx_pinbased_ctls_high);
2262         /*
2263          * According to the Intel spec, if bit 55 of VMX_BASIC is off (as it is
2264          * in our case), bits 1, 2 and 4 (i.e., 0x16) must be 1 in this MSR.
2265          */
2266         nested_vmx_pinbased_ctls_low |= PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
2267         nested_vmx_pinbased_ctls_high &= PIN_BASED_EXT_INTR_MASK |
2268                 PIN_BASED_NMI_EXITING | PIN_BASED_VIRTUAL_NMIS;
2269         nested_vmx_pinbased_ctls_high |= PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
2270                 PIN_BASED_VMX_PREEMPTION_TIMER;
2271
2272         /*
2273          * Exit controls
2274          * If bit 55 of VMX_BASIC is off, bits 0-8 and 10, 11, 13, 14, 16 and
2275          * 17 must be 1.
2276          */
2277         rdmsr(MSR_IA32_VMX_EXIT_CTLS,
2278                 nested_vmx_exit_ctls_low, nested_vmx_exit_ctls_high);
2279         nested_vmx_exit_ctls_low = VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
2280         /* Note that guest use of VM_EXIT_ACK_INTR_ON_EXIT is not supported. */
2281         nested_vmx_exit_ctls_high &=
2282 #ifdef CONFIG_X86_64
2283                 VM_EXIT_HOST_ADDR_SPACE_SIZE |
2284 #endif
2285                 VM_EXIT_LOAD_IA32_PAT | VM_EXIT_SAVE_IA32_PAT;
2286         nested_vmx_exit_ctls_high |= VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR |
2287                 VM_EXIT_LOAD_IA32_EFER | VM_EXIT_SAVE_IA32_EFER |
2288                 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER;
2289
2290         /* entry controls */
2291         rdmsr(MSR_IA32_VMX_ENTRY_CTLS,
2292                 nested_vmx_entry_ctls_low, nested_vmx_entry_ctls_high);
2293         /* If bit 55 of VMX_BASIC is off, bits 0-8 and 12 must be 1. */
2294         nested_vmx_entry_ctls_low = VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
2295         nested_vmx_entry_ctls_high &=
2296 #ifdef CONFIG_X86_64
2297                 VM_ENTRY_IA32E_MODE |
2298 #endif
2299                 VM_ENTRY_LOAD_IA32_PAT;
2300         nested_vmx_entry_ctls_high |= (VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR |
2301                                        VM_ENTRY_LOAD_IA32_EFER);
2302
2303         /* cpu-based controls */
2304         rdmsr(MSR_IA32_VMX_PROCBASED_CTLS,
2305                 nested_vmx_procbased_ctls_low, nested_vmx_procbased_ctls_high);
2306         nested_vmx_procbased_ctls_low = 0;
2307         nested_vmx_procbased_ctls_high &=
2308                 CPU_BASED_VIRTUAL_INTR_PENDING |
2309                 CPU_BASED_VIRTUAL_NMI_PENDING | CPU_BASED_USE_TSC_OFFSETING |
2310                 CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING |
2311                 CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING |
2312                 CPU_BASED_CR3_STORE_EXITING |
2313 #ifdef CONFIG_X86_64
2314                 CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING |
2315 #endif
2316                 CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING |
2317                 CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_EXITING |
2318                 CPU_BASED_RDPMC_EXITING | CPU_BASED_RDTSC_EXITING |
2319                 CPU_BASED_PAUSE_EXITING |
2320                 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2321         /*
2322          * We can allow some features even when not supported by the
2323          * hardware. For example, L1 can specify an MSR bitmap - and we
2324          * can use it to avoid exits to L1 - even when L0 runs L2
2325          * without MSR bitmaps.
2326          */
2327         nested_vmx_procbased_ctls_high |= CPU_BASED_USE_MSR_BITMAPS;
2328
2329         /* secondary cpu-based controls */
2330         rdmsr(MSR_IA32_VMX_PROCBASED_CTLS2,
2331                 nested_vmx_secondary_ctls_low, nested_vmx_secondary_ctls_high);
2332         nested_vmx_secondary_ctls_low = 0;
2333         nested_vmx_secondary_ctls_high &=
2334                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2335                 SECONDARY_EXEC_UNRESTRICTED_GUEST |
2336                 SECONDARY_EXEC_WBINVD_EXITING;
2337
2338         if (enable_ept) {
2339                 /* nested EPT: emulate EPT also to L1 */
2340                 nested_vmx_secondary_ctls_high |= SECONDARY_EXEC_ENABLE_EPT;
2341                 nested_vmx_ept_caps = VMX_EPT_PAGE_WALK_4_BIT |
2342                          VMX_EPTP_WB_BIT | VMX_EPT_2MB_PAGE_BIT |
2343                          VMX_EPT_INVEPT_BIT;
2344                 nested_vmx_ept_caps &= vmx_capability.ept;
2345                 /*
2346                  * Since invept is completely emulated we support both global
2347                  * and context invalidation independent of what host cpu
2348                  * supports
2349                  */
2350                 nested_vmx_ept_caps |= VMX_EPT_EXTENT_GLOBAL_BIT |
2351                         VMX_EPT_EXTENT_CONTEXT_BIT;
2352         } else
2353                 nested_vmx_ept_caps = 0;
2354
2355         /* miscellaneous data */
2356         rdmsr(MSR_IA32_VMX_MISC, nested_vmx_misc_low, nested_vmx_misc_high);
2357         nested_vmx_misc_low &= VMX_MISC_SAVE_EFER_LMA;
2358         nested_vmx_misc_low |= VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE |
2359                 VMX_MISC_ACTIVITY_HLT;
2360         nested_vmx_misc_high = 0;
2361 }
2362
2363 static inline bool vmx_control_verify(u32 control, u32 low, u32 high)
2364 {
2365         /*
2366          * Bits 0 in high must be 0, and bits 1 in low must be 1.
2367          */
2368         return ((control & high) | low) == control;
2369 }
2370
2371 static inline u64 vmx_control_msr(u32 low, u32 high)
2372 {
2373         return low | ((u64)high << 32);
2374 }
2375
2376 /* Returns 0 on success, non-0 otherwise. */
2377 static int vmx_get_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
2378 {
2379         switch (msr_index) {
2380         case MSR_IA32_VMX_BASIC:
2381                 /*
2382                  * This MSR reports some information about VMX support. We
2383                  * should return information about the VMX we emulate for the
2384                  * guest, and the VMCS structure we give it - not about the
2385                  * VMX support of the underlying hardware.
2386                  */
2387                 *pdata = VMCS12_REVISION |
2388                            ((u64)VMCS12_SIZE << VMX_BASIC_VMCS_SIZE_SHIFT) |
2389                            (VMX_BASIC_MEM_TYPE_WB << VMX_BASIC_MEM_TYPE_SHIFT);
2390                 break;
2391         case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
2392         case MSR_IA32_VMX_PINBASED_CTLS:
2393                 *pdata = vmx_control_msr(nested_vmx_pinbased_ctls_low,
2394                                         nested_vmx_pinbased_ctls_high);
2395                 break;
2396         case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
2397         case MSR_IA32_VMX_PROCBASED_CTLS:
2398                 *pdata = vmx_control_msr(nested_vmx_procbased_ctls_low,
2399                                         nested_vmx_procbased_ctls_high);
2400                 break;
2401         case MSR_IA32_VMX_TRUE_EXIT_CTLS:
2402         case MSR_IA32_VMX_EXIT_CTLS:
2403                 *pdata = vmx_control_msr(nested_vmx_exit_ctls_low,
2404                                         nested_vmx_exit_ctls_high);
2405                 break;
2406         case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
2407         case MSR_IA32_VMX_ENTRY_CTLS:
2408                 *pdata = vmx_control_msr(nested_vmx_entry_ctls_low,
2409                                         nested_vmx_entry_ctls_high);
2410                 break;
2411         case MSR_IA32_VMX_MISC:
2412                 *pdata = vmx_control_msr(nested_vmx_misc_low,
2413                                          nested_vmx_misc_high);
2414                 break;
2415         /*
2416          * These MSRs specify bits which the guest must keep fixed (on or off)
2417          * while L1 is in VMXON mode (in L1's root mode, or running an L2).
2418          * We picked the standard core2 setting.
2419          */
2420 #define VMXON_CR0_ALWAYSON      (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE)
2421 #define VMXON_CR4_ALWAYSON      X86_CR4_VMXE
2422         case MSR_IA32_VMX_CR0_FIXED0:
2423                 *pdata = VMXON_CR0_ALWAYSON;
2424                 break;
2425         case MSR_IA32_VMX_CR0_FIXED1:
2426                 *pdata = -1ULL;
2427                 break;
2428         case MSR_IA32_VMX_CR4_FIXED0:
2429                 *pdata = VMXON_CR4_ALWAYSON;
2430                 break;
2431         case MSR_IA32_VMX_CR4_FIXED1:
2432                 *pdata = -1ULL;
2433                 break;
2434         case MSR_IA32_VMX_VMCS_ENUM:
2435                 *pdata = 0x1f;
2436                 break;
2437         case MSR_IA32_VMX_PROCBASED_CTLS2:
2438                 *pdata = vmx_control_msr(nested_vmx_secondary_ctls_low,
2439                                         nested_vmx_secondary_ctls_high);
2440                 break;
2441         case MSR_IA32_VMX_EPT_VPID_CAP:
2442                 /* Currently, no nested vpid support */
2443                 *pdata = nested_vmx_ept_caps;
2444                 break;
2445         default:
2446                 return 1;
2447         }
2448
2449         return 0;
2450 }
2451
2452 /*
2453  * Reads an msr value (of 'msr_index') into 'pdata'.
2454  * Returns 0 on success, non-0 otherwise.
2455  * Assumes vcpu_load() was already called.
2456  */
2457 static int vmx_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
2458 {
2459         u64 data;
2460         struct shared_msr_entry *msr;
2461
2462         if (!pdata) {
2463                 printk(KERN_ERR "BUG: get_msr called with NULL pdata\n");
2464                 return -EINVAL;
2465         }
2466
2467         switch (msr_index) {
2468 #ifdef CONFIG_X86_64
2469         case MSR_FS_BASE:
2470                 data = vmcs_readl(GUEST_FS_BASE);
2471                 break;
2472         case MSR_GS_BASE:
2473                 data = vmcs_readl(GUEST_GS_BASE);
2474                 break;
2475         case MSR_KERNEL_GS_BASE:
2476                 vmx_load_host_state(to_vmx(vcpu));
2477                 data = to_vmx(vcpu)->msr_guest_kernel_gs_base;
2478                 break;
2479 #endif
2480         case MSR_EFER:
2481                 return kvm_get_msr_common(vcpu, msr_index, pdata);
2482         case MSR_IA32_TSC:
2483                 data = guest_read_tsc();
2484                 break;
2485         case MSR_IA32_SYSENTER_CS:
2486                 data = vmcs_read32(GUEST_SYSENTER_CS);
2487                 break;
2488         case MSR_IA32_SYSENTER_EIP:
2489                 data = vmcs_readl(GUEST_SYSENTER_EIP);
2490                 break;
2491         case MSR_IA32_SYSENTER_ESP:
2492                 data = vmcs_readl(GUEST_SYSENTER_ESP);
2493                 break;
2494         case MSR_IA32_BNDCFGS:
2495                 data = vmcs_read64(GUEST_BNDCFGS);
2496                 break;
2497         case MSR_IA32_FEATURE_CONTROL:
2498                 if (!nested_vmx_allowed(vcpu))
2499                         return 1;
2500                 data = to_vmx(vcpu)->nested.msr_ia32_feature_control;
2501                 break;
2502         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
2503                 if (!nested_vmx_allowed(vcpu))
2504                         return 1;
2505                 return vmx_get_vmx_msr(vcpu, msr_index, pdata);
2506         case MSR_TSC_AUX:
2507                 if (!to_vmx(vcpu)->rdtscp_enabled)
2508                         return 1;
2509                 /* Otherwise falls through */
2510         default:
2511                 msr = find_msr_entry(to_vmx(vcpu), msr_index);
2512                 if (msr) {
2513                         data = msr->data;
2514                         break;
2515                 }
2516                 return kvm_get_msr_common(vcpu, msr_index, pdata);
2517         }
2518
2519         *pdata = data;
2520         return 0;
2521 }
2522
2523 static void vmx_leave_nested(struct kvm_vcpu *vcpu);
2524
2525 /*
2526  * Writes msr value into into the appropriate "register".
2527  * Returns 0 on success, non-0 otherwise.
2528  * Assumes vcpu_load() was already called.
2529  */
2530 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2531 {
2532         struct vcpu_vmx *vmx = to_vmx(vcpu);
2533         struct shared_msr_entry *msr;
2534         int ret = 0;
2535         u32 msr_index = msr_info->index;
2536         u64 data = msr_info->data;
2537
2538         switch (msr_index) {
2539         case MSR_EFER:
2540                 ret = kvm_set_msr_common(vcpu, msr_info);
2541                 break;
2542 #ifdef CONFIG_X86_64
2543         case MSR_FS_BASE:
2544                 vmx_segment_cache_clear(vmx);
2545                 vmcs_writel(GUEST_FS_BASE, data);
2546                 break;
2547         case MSR_GS_BASE:
2548                 vmx_segment_cache_clear(vmx);
2549                 vmcs_writel(GUEST_GS_BASE, data);
2550                 break;
2551         case MSR_KERNEL_GS_BASE:
2552                 vmx_load_host_state(vmx);
2553                 vmx->msr_guest_kernel_gs_base = data;
2554                 break;
2555 #endif
2556         case MSR_IA32_SYSENTER_CS:
2557                 vmcs_write32(GUEST_SYSENTER_CS, data);
2558                 break;
2559         case MSR_IA32_SYSENTER_EIP:
2560                 vmcs_writel(GUEST_SYSENTER_EIP, data);
2561                 break;
2562         case MSR_IA32_SYSENTER_ESP:
2563                 vmcs_writel(GUEST_SYSENTER_ESP, data);
2564                 break;
2565         case MSR_IA32_BNDCFGS:
2566                 vmcs_write64(GUEST_BNDCFGS, data);
2567                 break;
2568         case MSR_IA32_TSC:
2569                 kvm_write_tsc(vcpu, msr_info);
2570                 break;
2571         case MSR_IA32_CR_PAT:
2572                 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
2573                         vmcs_write64(GUEST_IA32_PAT, data);
2574                         vcpu->arch.pat = data;
2575                         break;
2576                 }
2577                 ret = kvm_set_msr_common(vcpu, msr_info);
2578                 break;
2579         case MSR_IA32_TSC_ADJUST:
2580                 ret = kvm_set_msr_common(vcpu, msr_info);
2581                 break;
2582         case MSR_IA32_FEATURE_CONTROL:
2583                 if (!nested_vmx_allowed(vcpu) ||
2584                     (to_vmx(vcpu)->nested.msr_ia32_feature_control &
2585                      FEATURE_CONTROL_LOCKED && !msr_info->host_initiated))
2586                         return 1;
2587                 vmx->nested.msr_ia32_feature_control = data;
2588                 if (msr_info->host_initiated && data == 0)
2589                         vmx_leave_nested(vcpu);
2590                 break;
2591         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
2592                 return 1; /* they are read-only */
2593         case MSR_TSC_AUX:
2594                 if (!vmx->rdtscp_enabled)
2595                         return 1;
2596                 /* Check reserved bit, higher 32 bits should be zero */
2597                 if ((data >> 32) != 0)
2598                         return 1;
2599                 /* Otherwise falls through */
2600         default:
2601                 msr = find_msr_entry(vmx, msr_index);
2602                 if (msr) {
2603                         msr->data = data;
2604                         if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
2605                                 preempt_disable();
2606                                 kvm_set_shared_msr(msr->index, msr->data,
2607                                                    msr->mask);
2608                                 preempt_enable();
2609                         }
2610                         break;
2611                 }
2612                 ret = kvm_set_msr_common(vcpu, msr_info);
2613         }
2614
2615         return ret;
2616 }
2617
2618 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2619 {
2620         __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
2621         switch (reg) {
2622         case VCPU_REGS_RSP:
2623                 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
2624                 break;
2625         case VCPU_REGS_RIP:
2626                 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
2627                 break;
2628         case VCPU_EXREG_PDPTR:
2629                 if (enable_ept)
2630                         ept_save_pdptrs(vcpu);
2631                 break;
2632         default:
2633                 break;
2634         }
2635 }
2636
2637 static __init int cpu_has_kvm_support(void)
2638 {
2639         return cpu_has_vmx();
2640 }
2641
2642 static __init int vmx_disabled_by_bios(void)
2643 {
2644         u64 msr;
2645
2646         rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
2647         if (msr & FEATURE_CONTROL_LOCKED) {
2648                 /* launched w/ TXT and VMX disabled */
2649                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
2650                         && tboot_enabled())
2651                         return 1;
2652                 /* launched w/o TXT and VMX only enabled w/ TXT */
2653                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
2654                         && (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
2655                         && !tboot_enabled()) {
2656                         printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
2657                                 "activate TXT before enabling KVM\n");
2658                         return 1;
2659                 }
2660                 /* launched w/o TXT and VMX disabled */
2661                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
2662                         && !tboot_enabled())
2663                         return 1;
2664         }
2665
2666         return 0;
2667 }
2668
2669 static void kvm_cpu_vmxon(u64 addr)
2670 {
2671         asm volatile (ASM_VMX_VMXON_RAX
2672                         : : "a"(&addr), "m"(addr)
2673                         : "memory", "cc");
2674 }
2675
2676 static int hardware_enable(void *garbage)
2677 {
2678         int cpu = raw_smp_processor_id();
2679         u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2680         u64 old, test_bits;
2681
2682         if (read_cr4() & X86_CR4_VMXE)
2683                 return -EBUSY;
2684
2685         INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
2686
2687         /*
2688          * Now we can enable the vmclear operation in kdump
2689          * since the loaded_vmcss_on_cpu list on this cpu
2690          * has been initialized.
2691          *
2692          * Though the cpu is not in VMX operation now, there
2693          * is no problem to enable the vmclear operation
2694          * for the loaded_vmcss_on_cpu list is empty!
2695          */
2696         crash_enable_local_vmclear(cpu);
2697
2698         rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
2699
2700         test_bits = FEATURE_CONTROL_LOCKED;
2701         test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
2702         if (tboot_enabled())
2703                 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
2704
2705         if ((old & test_bits) != test_bits) {
2706                 /* enable and lock */
2707                 wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
2708         }
2709         write_cr4(read_cr4() | X86_CR4_VMXE); /* FIXME: not cpu hotplug safe */
2710
2711         if (vmm_exclusive) {
2712                 kvm_cpu_vmxon(phys_addr);
2713                 ept_sync_global();
2714         }
2715
2716         native_store_gdt(&__get_cpu_var(host_gdt));
2717
2718         return 0;
2719 }
2720
2721 static void vmclear_local_loaded_vmcss(void)
2722 {
2723         int cpu = raw_smp_processor_id();
2724         struct loaded_vmcs *v, *n;
2725
2726         list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
2727                                  loaded_vmcss_on_cpu_link)
2728                 __loaded_vmcs_clear(v);
2729 }
2730
2731
2732 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
2733  * tricks.
2734  */
2735 static void kvm_cpu_vmxoff(void)
2736 {
2737         asm volatile (__ex(ASM_VMX_VMXOFF) : : : "cc");
2738 }
2739
2740 static void hardware_disable(void *garbage)
2741 {
2742         if (vmm_exclusive) {
2743                 vmclear_local_loaded_vmcss();
2744                 kvm_cpu_vmxoff();
2745         }
2746         write_cr4(read_cr4() & ~X86_CR4_VMXE);
2747 }
2748
2749 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
2750                                       u32 msr, u32 *result)
2751 {
2752         u32 vmx_msr_low, vmx_msr_high;
2753         u32 ctl = ctl_min | ctl_opt;
2754
2755         rdmsr(msr, vmx_msr_low, vmx_msr_high);
2756
2757         ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
2758         ctl |= vmx_msr_low;  /* bit == 1 in low word  ==> must be one  */
2759
2760         /* Ensure minimum (required) set of control bits are supported. */
2761         if (ctl_min & ~ctl)
2762                 return -EIO;
2763
2764         *result = ctl;
2765         return 0;
2766 }
2767
2768 static __init bool allow_1_setting(u32 msr, u32 ctl)
2769 {
2770         u32 vmx_msr_low, vmx_msr_high;
2771
2772         rdmsr(msr, vmx_msr_low, vmx_msr_high);
2773         return vmx_msr_high & ctl;
2774 }
2775
2776 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
2777 {
2778         u32 vmx_msr_low, vmx_msr_high;
2779         u32 min, opt, min2, opt2;
2780         u32 _pin_based_exec_control = 0;
2781         u32 _cpu_based_exec_control = 0;
2782         u32 _cpu_based_2nd_exec_control = 0;
2783         u32 _vmexit_control = 0;
2784         u32 _vmentry_control = 0;
2785
2786         min = CPU_BASED_HLT_EXITING |
2787 #ifdef CONFIG_X86_64
2788               CPU_BASED_CR8_LOAD_EXITING |
2789               CPU_BASED_CR8_STORE_EXITING |
2790 #endif
2791               CPU_BASED_CR3_LOAD_EXITING |
2792               CPU_BASED_CR3_STORE_EXITING |
2793               CPU_BASED_USE_IO_BITMAPS |
2794               CPU_BASED_MOV_DR_EXITING |
2795               CPU_BASED_USE_TSC_OFFSETING |
2796               CPU_BASED_MWAIT_EXITING |
2797               CPU_BASED_MONITOR_EXITING |
2798               CPU_BASED_INVLPG_EXITING |
2799               CPU_BASED_RDPMC_EXITING;
2800
2801         opt = CPU_BASED_TPR_SHADOW |
2802               CPU_BASED_USE_MSR_BITMAPS |
2803               CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2804         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
2805                                 &_cpu_based_exec_control) < 0)
2806                 return -EIO;
2807 #ifdef CONFIG_X86_64
2808         if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2809                 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
2810                                            ~CPU_BASED_CR8_STORE_EXITING;
2811 #endif
2812         if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
2813                 min2 = 0;
2814                 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2815                         SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2816                         SECONDARY_EXEC_WBINVD_EXITING |
2817                         SECONDARY_EXEC_ENABLE_VPID |
2818                         SECONDARY_EXEC_ENABLE_EPT |
2819                         SECONDARY_EXEC_UNRESTRICTED_GUEST |
2820                         SECONDARY_EXEC_PAUSE_LOOP_EXITING |
2821                         SECONDARY_EXEC_RDTSCP |
2822                         SECONDARY_EXEC_ENABLE_INVPCID |
2823                         SECONDARY_EXEC_APIC_REGISTER_VIRT |
2824                         SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2825                         SECONDARY_EXEC_SHADOW_VMCS;
2826                 if (adjust_vmx_controls(min2, opt2,
2827                                         MSR_IA32_VMX_PROCBASED_CTLS2,
2828                                         &_cpu_based_2nd_exec_control) < 0)
2829                         return -EIO;
2830         }
2831 #ifndef CONFIG_X86_64
2832         if (!(_cpu_based_2nd_exec_control &
2833                                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
2834                 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
2835 #endif
2836
2837         if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2838                 _cpu_based_2nd_exec_control &= ~(
2839                                 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2840                                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2841                                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2842
2843         if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
2844                 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
2845                    enabled */
2846                 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
2847                                              CPU_BASED_CR3_STORE_EXITING |
2848                                              CPU_BASED_INVLPG_EXITING);
2849                 rdmsr(MSR_IA32_VMX_EPT_VPID_CAP,
2850                       vmx_capability.ept, vmx_capability.vpid);
2851         }
2852
2853         min = 0;
2854 #ifdef CONFIG_X86_64
2855         min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
2856 #endif
2857         opt = VM_EXIT_SAVE_IA32_PAT | VM_EXIT_LOAD_IA32_PAT |
2858                 VM_EXIT_ACK_INTR_ON_EXIT | VM_EXIT_CLEAR_BNDCFGS;
2859         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
2860                                 &_vmexit_control) < 0)
2861                 return -EIO;
2862
2863         min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
2864         opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR;
2865         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
2866                                 &_pin_based_exec_control) < 0)
2867                 return -EIO;
2868
2869         if (!(_cpu_based_2nd_exec_control &
2870                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) ||
2871                 !(_vmexit_control & VM_EXIT_ACK_INTR_ON_EXIT))
2872                 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
2873
2874         min = 0;
2875         opt = VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_BNDCFGS;
2876         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
2877                                 &_vmentry_control) < 0)
2878                 return -EIO;
2879
2880         rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
2881
2882         /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
2883         if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
2884                 return -EIO;
2885
2886 #ifdef CONFIG_X86_64
2887         /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
2888         if (vmx_msr_high & (1u<<16))
2889                 return -EIO;
2890 #endif
2891
2892         /* Require Write-Back (WB) memory type for VMCS accesses. */
2893         if (((vmx_msr_high >> 18) & 15) != 6)
2894                 return -EIO;
2895
2896         vmcs_conf->size = vmx_msr_high & 0x1fff;
2897         vmcs_conf->order = get_order(vmcs_config.size);
2898         vmcs_conf->revision_id = vmx_msr_low;
2899
2900         vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
2901         vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
2902         vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
2903         vmcs_conf->vmexit_ctrl         = _vmexit_control;
2904         vmcs_conf->vmentry_ctrl        = _vmentry_control;
2905
2906         cpu_has_load_ia32_efer =
2907                 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
2908                                 VM_ENTRY_LOAD_IA32_EFER)
2909                 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
2910                                    VM_EXIT_LOAD_IA32_EFER);
2911
2912         cpu_has_load_perf_global_ctrl =
2913                 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
2914                                 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
2915                 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
2916                                    VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
2917
2918         /*
2919          * Some cpus support VM_ENTRY_(LOAD|SAVE)_IA32_PERF_GLOBAL_CTRL
2920          * but due to arrata below it can't be used. Workaround is to use
2921          * msr load mechanism to switch IA32_PERF_GLOBAL_CTRL.
2922          *
2923          * VM Exit May Incorrectly Clear IA32_PERF_GLOBAL_CTRL [34:32]
2924          *
2925          * AAK155             (model 26)
2926          * AAP115             (model 30)
2927          * AAT100             (model 37)
2928          * BC86,AAY89,BD102   (model 44)
2929          * BA97               (model 46)
2930          *
2931          */
2932         if (cpu_has_load_perf_global_ctrl && boot_cpu_data.x86 == 0x6) {
2933                 switch (boot_cpu_data.x86_model) {
2934                 case 26:
2935                 case 30:
2936                 case 37:
2937                 case 44:
2938                 case 46:
2939                         cpu_has_load_perf_global_ctrl = false;
2940                         printk_once(KERN_WARNING"kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
2941                                         "does not work properly. Using workaround\n");
2942                         break;
2943                 default:
2944                         break;
2945                 }
2946         }
2947
2948         return 0;
2949 }
2950
2951 static struct vmcs *alloc_vmcs_cpu(int cpu)
2952 {
2953         int node = cpu_to_node(cpu);
2954         struct page *pages;
2955         struct vmcs *vmcs;
2956
2957         pages = alloc_pages_exact_node(node, GFP_KERNEL, vmcs_config.order);
2958         if (!pages)
2959                 return NULL;
2960         vmcs = page_address(pages);
2961         memset(vmcs, 0, vmcs_config.size);
2962         vmcs->revision_id = vmcs_config.revision_id; /* vmcs revision id */
2963         return vmcs;
2964 }
2965
2966 static struct vmcs *alloc_vmcs(void)
2967 {
2968         return alloc_vmcs_cpu(raw_smp_processor_id());
2969 }
2970
2971 static void free_vmcs(struct vmcs *vmcs)
2972 {
2973         free_pages((unsigned long)vmcs, vmcs_config.order);
2974 }
2975
2976 /*
2977  * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
2978  */
2979 static void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2980 {
2981         if (!loaded_vmcs->vmcs)
2982                 return;
2983         loaded_vmcs_clear(loaded_vmcs);
2984         free_vmcs(loaded_vmcs->vmcs);
2985         loaded_vmcs->vmcs = NULL;
2986 }
2987
2988 static void free_kvm_area(void)
2989 {
2990         int cpu;
2991
2992         for_each_possible_cpu(cpu) {
2993                 free_vmcs(per_cpu(vmxarea, cpu));
2994                 per_cpu(vmxarea, cpu) = NULL;
2995         }
2996 }
2997
2998 static __init int alloc_kvm_area(void)
2999 {
3000         int cpu;
3001
3002         for_each_possible_cpu(cpu) {
3003                 struct vmcs *vmcs;
3004
3005                 vmcs = alloc_vmcs_cpu(cpu);
3006                 if (!vmcs) {
3007                         free_kvm_area();
3008                         return -ENOMEM;
3009                 }
3010
3011                 per_cpu(vmxarea, cpu) = vmcs;
3012         }
3013         return 0;
3014 }
3015
3016 static __init int hardware_setup(void)
3017 {
3018         if (setup_vmcs_config(&vmcs_config) < 0)
3019                 return -EIO;
3020
3021         if (boot_cpu_has(X86_FEATURE_NX))
3022                 kvm_enable_efer_bits(EFER_NX);
3023
3024         if (!cpu_has_vmx_vpid())
3025                 enable_vpid = 0;
3026         if (!cpu_has_vmx_shadow_vmcs())
3027                 enable_shadow_vmcs = 0;
3028
3029         if (!cpu_has_vmx_ept() ||
3030             !cpu_has_vmx_ept_4levels()) {
3031                 enable_ept = 0;
3032                 enable_unrestricted_guest = 0;
3033                 enable_ept_ad_bits = 0;
3034         }
3035
3036         if (!cpu_has_vmx_ept_ad_bits())
3037                 enable_ept_ad_bits = 0;
3038
3039         if (!cpu_has_vmx_unrestricted_guest())
3040                 enable_unrestricted_guest = 0;
3041
3042         if (!cpu_has_vmx_flexpriority())
3043                 flexpriority_enabled = 0;
3044
3045         if (!cpu_has_vmx_tpr_shadow())
3046                 kvm_x86_ops->update_cr8_intercept = NULL;
3047
3048         if (enable_ept && !cpu_has_vmx_ept_2m_page())
3049                 kvm_disable_largepages();
3050
3051         if (!cpu_has_vmx_ple())
3052                 ple_gap = 0;
3053
3054         if (!cpu_has_vmx_apicv())
3055                 enable_apicv = 0;
3056
3057         if (enable_apicv)
3058                 kvm_x86_ops->update_cr8_intercept = NULL;
3059         else {
3060                 kvm_x86_ops->hwapic_irr_update = NULL;
3061                 kvm_x86_ops->deliver_posted_interrupt = NULL;
3062                 kvm_x86_ops->sync_pir_to_irr = vmx_sync_pir_to_irr_dummy;
3063         }
3064
3065         if (nested)
3066                 nested_vmx_setup_ctls_msrs();
3067
3068         return alloc_kvm_area();
3069 }
3070
3071 static __exit void hardware_unsetup(void)
3072 {
3073         free_kvm_area();
3074 }
3075
3076 static bool emulation_required(struct kvm_vcpu *vcpu)
3077 {
3078         return emulate_invalid_guest_state && !guest_state_valid(vcpu);
3079 }
3080
3081 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
3082                 struct kvm_segment *save)
3083 {
3084         if (!emulate_invalid_guest_state) {
3085                 /*
3086                  * CS and SS RPL should be equal during guest entry according
3087                  * to VMX spec, but in reality it is not always so. Since vcpu
3088                  * is in the middle of the transition from real mode to
3089                  * protected mode it is safe to assume that RPL 0 is a good
3090                  * default value.
3091                  */
3092                 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
3093                         save->selector &= ~SELECTOR_RPL_MASK;
3094                 save->dpl = save->selector & SELECTOR_RPL_MASK;
3095                 save->s = 1;
3096         }
3097         vmx_set_segment(vcpu, save, seg);
3098 }
3099
3100 static void enter_pmode(struct kvm_vcpu *vcpu)
3101 {
3102         unsigned long flags;
3103         struct vcpu_vmx *vmx = to_vmx(vcpu);
3104
3105         /*
3106          * Update real mode segment cache. It may be not up-to-date if sement
3107          * register was written while vcpu was in a guest mode.
3108          */
3109         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
3110         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
3111         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
3112         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
3113         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
3114         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
3115
3116         vmx->rmode.vm86_active = 0;
3117
3118         vmx_segment_cache_clear(vmx);
3119
3120         vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
3121
3122         flags = vmcs_readl(GUEST_RFLAGS);
3123         flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
3124         flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
3125         vmcs_writel(GUEST_RFLAGS, flags);
3126
3127         vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
3128                         (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
3129
3130         update_exception_bitmap(vcpu);
3131
3132         fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
3133         fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
3134         fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
3135         fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
3136         fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
3137         fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
3138
3139         /* CPL is always 0 when CPU enters protected mode */
3140         __set_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail);
3141         vmx->cpl = 0;
3142 }
3143
3144 static void fix_rmode_seg(int seg, struct kvm_segment *save)
3145 {
3146         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3147         struct kvm_segment var = *save;
3148
3149         var.dpl = 0x3;
3150         if (seg == VCPU_SREG_CS)
3151                 var.type = 0x3;
3152
3153         if (!emulate_invalid_guest_state) {
3154                 var.selector = var.base >> 4;
3155                 var.base = var.base & 0xffff0;
3156                 var.limit = 0xffff;
3157                 var.g = 0;
3158                 var.db = 0;
3159                 var.present = 1;
3160                 var.s = 1;
3161                 var.l = 0;
3162                 var.unusable = 0;
3163                 var.type = 0x3;
3164                 var.avl = 0;
3165                 if (save->base & 0xf)
3166                         printk_once(KERN_WARNING "kvm: segment base is not "
3167                                         "paragraph aligned when entering "
3168                                         "protected mode (seg=%d)", seg);
3169         }
3170
3171         vmcs_write16(sf->selector, var.selector);
3172         vmcs_write32(sf->base, var.base);
3173         vmcs_write32(sf->limit, var.limit);
3174         vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
3175 }
3176
3177 static void enter_rmode(struct kvm_vcpu *vcpu)
3178 {
3179         unsigned long flags;
3180         struct vcpu_vmx *vmx = to_vmx(vcpu);
3181
3182         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
3183         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
3184         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
3185         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
3186         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
3187         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
3188         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
3189
3190         vmx->rmode.vm86_active = 1;
3191
3192         /*
3193          * Very old userspace does not call KVM_SET_TSS_ADDR before entering
3194          * vcpu. Warn the user that an update is overdue.
3195          */
3196         if (!vcpu->kvm->arch.tss_addr)
3197                 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
3198                              "called before entering vcpu\n");
3199
3200         vmx_segment_cache_clear(vmx);
3201
3202         vmcs_writel(GUEST_TR_BASE, vcpu->kvm->arch.tss_addr);
3203         vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
3204         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
3205
3206         flags = vmcs_readl(GUEST_RFLAGS);
3207         vmx->rmode.save_rflags = flags;
3208
3209         flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
3210
3211         vmcs_writel(GUEST_RFLAGS, flags);
3212         vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
3213         update_exception_bitmap(vcpu);
3214
3215         fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
3216         fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
3217         fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
3218         fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
3219         fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
3220         fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
3221
3222         kvm_mmu_reset_context(vcpu);
3223 }
3224
3225 static void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
3226 {
3227         struct vcpu_vmx *vmx = to_vmx(vcpu);
3228         struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
3229
3230         if (!msr)
3231                 return;
3232
3233         /*
3234          * Force kernel_gs_base reloading before EFER changes, as control
3235          * of this msr depends on is_long_mode().
3236          */
3237         vmx_load_host_state(to_vmx(vcpu));
3238         vcpu->arch.efer = efer;
3239         if (efer & EFER_LMA) {
3240                 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
3241                 msr->data = efer;
3242         } else {
3243                 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
3244
3245                 msr->data = efer & ~EFER_LME;
3246         }
3247         setup_msrs(vmx);
3248 }
3249
3250 #ifdef CONFIG_X86_64
3251
3252 static void enter_lmode(struct kvm_vcpu *vcpu)
3253 {
3254         u32 guest_tr_ar;
3255
3256         vmx_segment_cache_clear(to_vmx(vcpu));
3257
3258         guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
3259         if ((guest_tr_ar & AR_TYPE_MASK) != AR_TYPE_BUSY_64_TSS) {
3260                 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
3261                                      __func__);
3262                 vmcs_write32(GUEST_TR_AR_BYTES,
3263                              (guest_tr_ar & ~AR_TYPE_MASK)
3264                              | AR_TYPE_BUSY_64_TSS);
3265         }
3266         vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
3267 }
3268
3269 static void exit_lmode(struct kvm_vcpu *vcpu)
3270 {
3271         vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
3272         vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
3273 }
3274
3275 #endif
3276
3277 static void vmx_flush_tlb(struct kvm_vcpu *vcpu)
3278 {
3279         vpid_sync_context(to_vmx(vcpu));
3280         if (enable_ept) {
3281                 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3282                         return;
3283                 ept_sync_context(construct_eptp(vcpu->arch.mmu.root_hpa));
3284         }
3285 }
3286
3287 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
3288 {
3289         ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
3290
3291         vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
3292         vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
3293 }
3294
3295 static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
3296 {
3297         if (enable_ept && is_paging(vcpu))
3298                 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
3299         __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
3300 }
3301
3302 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
3303 {
3304         ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
3305
3306         vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
3307         vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
3308 }
3309
3310 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
3311 {
3312         struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
3313
3314         if (!test_bit(VCPU_EXREG_PDPTR,
3315                       (unsigned long *)&vcpu->arch.regs_dirty))
3316                 return;
3317
3318         if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
3319                 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
3320                 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
3321                 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
3322                 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
3323         }
3324 }
3325
3326 static void ept_save_pdptrs(struct kvm_vcpu *vcpu)
3327 {
3328         struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
3329
3330         if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
3331                 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
3332                 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
3333                 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
3334                 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
3335         }
3336
3337         __set_bit(VCPU_EXREG_PDPTR,
3338                   (unsigned long *)&vcpu->arch.regs_avail);
3339         __set_bit(VCPU_EXREG_PDPTR,
3340                   (unsigned long *)&vcpu->arch.regs_dirty);
3341 }
3342
3343 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
3344
3345 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
3346                                         unsigned long cr0,
3347                                         struct kvm_vcpu *vcpu)
3348 {
3349         if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
3350                 vmx_decache_cr3(vcpu);
3351         if (!(cr0 & X86_CR0_PG)) {
3352                 /* From paging/starting to nonpaging */
3353                 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
3354                              vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
3355                              (CPU_BASED_CR3_LOAD_EXITING |
3356                               CPU_BASED_CR3_STORE_EXITING));
3357                 vcpu->arch.cr0 = cr0;
3358                 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3359         } else if (!is_paging(vcpu)) {
3360                 /* From nonpaging to paging */
3361                 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
3362                              vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
3363                              ~(CPU_BASED_CR3_LOAD_EXITING |
3364                                CPU_BASED_CR3_STORE_EXITING));
3365                 vcpu->arch.cr0 = cr0;
3366                 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3367         }
3368
3369         if (!(cr0 & X86_CR0_WP))
3370                 *hw_cr0 &= ~X86_CR0_WP;
3371 }
3372
3373 static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
3374 {
3375         struct vcpu_vmx *vmx = to_vmx(vcpu);
3376         unsigned long hw_cr0;
3377
3378         hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK);
3379         if (enable_unrestricted_guest)
3380                 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
3381         else {
3382                 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
3383
3384                 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
3385                         enter_pmode(vcpu);
3386
3387                 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
3388                         enter_rmode(vcpu);
3389         }
3390
3391 #ifdef CONFIG_X86_64
3392         if (vcpu->arch.efer & EFER_LME) {
3393                 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
3394                         enter_lmode(vcpu);
3395                 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
3396                         exit_lmode(vcpu);
3397         }
3398 #endif
3399
3400         if (enable_ept)
3401                 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
3402
3403         if (!vcpu->fpu_active)
3404                 hw_cr0 |= X86_CR0_TS | X86_CR0_MP;
3405
3406         vmcs_writel(CR0_READ_SHADOW, cr0);
3407         vmcs_writel(GUEST_CR0, hw_cr0);
3408         vcpu->arch.cr0 = cr0;
3409
3410         /* depends on vcpu->arch.cr0 to be set to a new value */
3411         vmx->emulation_required = emulation_required(vcpu);
3412 }
3413
3414 static u64 construct_eptp(unsigned long root_hpa)
3415 {
3416         u64 eptp;
3417
3418         /* TODO write the value reading from MSR */
3419         eptp = VMX_EPT_DEFAULT_MT |
3420                 VMX_EPT_DEFAULT_GAW << VMX_EPT_GAW_EPTP_SHIFT;
3421         if (enable_ept_ad_bits)
3422                 eptp |= VMX_EPT_AD_ENABLE_BIT;
3423         eptp |= (root_hpa & PAGE_MASK);
3424
3425         return eptp;
3426 }
3427
3428 static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
3429 {
3430         unsigned long guest_cr3;
3431         u64 eptp;
3432
3433         guest_cr3 = cr3;
3434         if (enable_ept) {
3435                 eptp = construct_eptp(cr3);
3436                 vmcs_write64(EPT_POINTER, eptp);
3437                 if (is_paging(vcpu) || is_guest_mode(vcpu))
3438                         guest_cr3 = kvm_read_cr3(vcpu);
3439                 else
3440                         guest_cr3 = vcpu->kvm->arch.ept_identity_map_addr;
3441                 ept_load_pdptrs(vcpu);
3442         }
3443
3444         vmx_flush_tlb(vcpu);
3445         vmcs_writel(GUEST_CR3, guest_cr3);
3446 }
3447
3448 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3449 {
3450         unsigned long hw_cr4 = cr4 | (to_vmx(vcpu)->rmode.vm86_active ?
3451                     KVM_RMODE_VM_CR4_ALWAYS_ON : KVM_PMODE_VM_CR4_ALWAYS_ON);
3452
3453         if (cr4 & X86_CR4_VMXE) {
3454                 /*
3455                  * To use VMXON (and later other VMX instructions), a guest
3456                  * must first be able to turn on cr4.VMXE (see handle_vmon()).
3457                  * So basically the check on whether to allow nested VMX
3458                  * is here.
3459                  */
3460                 if (!nested_vmx_allowed(vcpu))
3461                         return 1;
3462         }
3463         if (to_vmx(vcpu)->nested.vmxon &&
3464             ((cr4 & VMXON_CR4_ALWAYSON) != VMXON_CR4_ALWAYSON))
3465                 return 1;
3466
3467         vcpu->arch.cr4 = cr4;
3468         if (enable_ept) {
3469                 if (!is_paging(vcpu)) {
3470                         hw_cr4 &= ~X86_CR4_PAE;
3471                         hw_cr4 |= X86_CR4_PSE;
3472                         /*
3473                          * SMEP is disabled if CPU is in non-paging mode in
3474                          * hardware. However KVM always uses paging mode to
3475                          * emulate guest non-paging mode with TDP.
3476                          * To emulate this behavior, SMEP needs to be manually
3477                          * disabled when guest switches to non-paging mode.
3478                          */
3479                         hw_cr4 &= ~X86_CR4_SMEP;
3480                 } else if (!(cr4 & X86_CR4_PAE)) {
3481                         hw_cr4 &= ~X86_CR4_PAE;
3482                 }
3483         }
3484
3485         vmcs_writel(CR4_READ_SHADOW, cr4);
3486         vmcs_writel(GUEST_CR4, hw_cr4);
3487         return 0;
3488 }
3489
3490 static void vmx_get_segment(struct kvm_vcpu *vcpu,
3491                             struct kvm_segment *var, int seg)
3492 {
3493         struct vcpu_vmx *vmx = to_vmx(vcpu);
3494         u32 ar;
3495
3496         if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3497                 *var = vmx->rmode.segs[seg];
3498                 if (seg == VCPU_SREG_TR
3499                     || var->selector == vmx_read_guest_seg_selector(vmx, seg))
3500                         return;
3501                 var->base = vmx_read_guest_seg_base(vmx, seg);
3502                 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3503                 return;
3504         }
3505         var->base = vmx_read_guest_seg_base(vmx, seg);
3506         var->limit = vmx_read_guest_seg_limit(vmx, seg);
3507         var->selector = vmx_read_guest_seg_selector(vmx, seg);
3508         ar = vmx_read_guest_seg_ar(vmx, seg);
3509         var->unusable = (ar >> 16) & 1;
3510         var->type = ar & 15;
3511         var->s = (ar >> 4) & 1;
3512         var->dpl = (ar >> 5) & 3;
3513         /*
3514          * Some userspaces do not preserve unusable property. Since usable
3515          * segment has to be present according to VMX spec we can use present
3516          * property to amend userspace bug by making unusable segment always
3517          * nonpresent. vmx_segment_access_rights() already marks nonpresent
3518          * segment as unusable.
3519          */
3520         var->present = !var->unusable;
3521         var->avl = (ar >> 12) & 1;
3522         var->l = (ar >> 13) & 1;
3523         var->db = (ar >> 14) & 1;
3524         var->g = (ar >> 15) & 1;
3525 }
3526
3527 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
3528 {
3529         struct kvm_segment s;
3530
3531         if (to_vmx(vcpu)->rmode.vm86_active) {
3532                 vmx_get_segment(vcpu, &s, seg);
3533                 return s.base;
3534         }
3535         return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
3536 }
3537
3538 static int vmx_get_cpl(struct kvm_vcpu *vcpu)
3539 {
3540         struct vcpu_vmx *vmx = to_vmx(vcpu);
3541
3542         if (!is_protmode(vcpu))
3543                 return 0;
3544
3545         if (!is_long_mode(vcpu)
3546             && (kvm_get_rflags(vcpu) & X86_EFLAGS_VM)) /* if virtual 8086 */
3547                 return 3;
3548
3549         if (!test_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail)) {
3550                 __set_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail);
3551                 vmx->cpl = vmx_read_guest_seg_selector(vmx, VCPU_SREG_CS) & 3;
3552         }
3553
3554         return vmx->cpl;
3555 }
3556
3557
3558 static u32 vmx_segment_access_rights(struct kvm_segment *var)
3559 {
3560         u32 ar;
3561
3562         if (var->unusable || !var->present)
3563                 ar = 1 << 16;
3564         else {
3565                 ar = var->type & 15;
3566                 ar |= (var->s & 1) << 4;
3567                 ar |= (var->dpl & 3) << 5;
3568                 ar |= (var->present & 1) << 7;
3569                 ar |= (var->avl & 1) << 12;
3570                 ar |= (var->l & 1) << 13;
3571                 ar |= (var->db & 1) << 14;
3572                 ar |= (var->g & 1) << 15;
3573         }
3574
3575         return ar;
3576 }
3577
3578 static void vmx_set_segment(struct kvm_vcpu *vcpu,
3579                             struct kvm_segment *var, int seg)
3580 {
3581         struct vcpu_vmx *vmx = to_vmx(vcpu);
3582         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3583
3584         vmx_segment_cache_clear(vmx);
3585         if (seg == VCPU_SREG_CS)
3586                 __clear_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail);
3587
3588         if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3589                 vmx->rmode.segs[seg] = *var;
3590                 if (seg == VCPU_SREG_TR)
3591                         vmcs_write16(sf->selector, var->selector);
3592                 else if (var->s)
3593                         fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
3594                 goto out;
3595         }
3596
3597         vmcs_writel(sf->base, var->base);
3598         vmcs_write32(sf->limit, var->limit);
3599         vmcs_write16(sf->selector, var->selector);
3600
3601         /*
3602          *   Fix the "Accessed" bit in AR field of segment registers for older
3603          * qemu binaries.
3604          *   IA32 arch specifies that at the time of processor reset the
3605          * "Accessed" bit in the AR field of segment registers is 1. And qemu
3606          * is setting it to 0 in the userland code. This causes invalid guest
3607          * state vmexit when "unrestricted guest" mode is turned on.
3608          *    Fix for this setup issue in cpu_reset is being pushed in the qemu
3609          * tree. Newer qemu binaries with that qemu fix would not need this
3610          * kvm hack.
3611          */
3612         if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
3613                 var->type |= 0x1; /* Accessed */
3614
3615         vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
3616
3617 out:
3618         vmx->emulation_required |= emulation_required(vcpu);
3619 }
3620
3621 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3622 {
3623         u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
3624
3625         *db = (ar >> 14) & 1;
3626         *l = (ar >> 13) & 1;
3627 }
3628
3629 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3630 {
3631         dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
3632         dt->address = vmcs_readl(GUEST_IDTR_BASE);
3633 }
3634
3635 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3636 {
3637         vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
3638         vmcs_writel(GUEST_IDTR_BASE, dt->address);
3639 }
3640
3641 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3642 {
3643         dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
3644         dt->address = vmcs_readl(GUEST_GDTR_BASE);
3645 }
3646
3647 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3648 {
3649         vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
3650         vmcs_writel(GUEST_GDTR_BASE, dt->address);
3651 }
3652
3653 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
3654 {
3655         struct kvm_segment var;
3656         u32 ar;
3657
3658         vmx_get_segment(vcpu, &var, seg);
3659         var.dpl = 0x3;
3660         if (seg == VCPU_SREG_CS)
3661                 var.type = 0x3;
3662         ar = vmx_segment_access_rights(&var);
3663
3664         if (var.base != (var.selector << 4))
3665                 return false;
3666         if (var.limit != 0xffff)
3667                 return false;
3668         if (ar != 0xf3)
3669                 return false;
3670
3671         return true;
3672 }
3673
3674 static bool code_segment_valid(struct kvm_vcpu *vcpu)
3675 {
3676         struct kvm_segment cs;
3677         unsigned int cs_rpl;
3678
3679         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3680         cs_rpl = cs.selector & SELECTOR_RPL_MASK;
3681
3682         if (cs.unusable)
3683                 return false;
3684         if (~cs.type & (AR_TYPE_CODE_MASK|AR_TYPE_ACCESSES_MASK))
3685                 return false;
3686         if (!cs.s)
3687                 return false;
3688         if (cs.type & AR_TYPE_WRITEABLE_MASK) {
3689                 if (cs.dpl > cs_rpl)
3690                         return false;
3691         } else {
3692                 if (cs.dpl != cs_rpl)
3693                         return false;
3694         }
3695         if (!cs.present)
3696                 return false;
3697
3698         /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
3699         return true;
3700 }
3701
3702 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
3703 {
3704         struct kvm_segment ss;
3705         unsigned int ss_rpl;
3706
3707         vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3708         ss_rpl = ss.selector & SELECTOR_RPL_MASK;
3709
3710         if (ss.unusable)
3711                 return true;
3712         if (ss.type != 3 && ss.type != 7)
3713                 return false;
3714         if (!ss.s)
3715                 return false;
3716         if (ss.dpl != ss_rpl) /* DPL != RPL */
3717                 return false;
3718         if (!ss.present)
3719                 return false;
3720
3721         return true;
3722 }
3723
3724 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
3725 {
3726         struct kvm_segment var;
3727         unsigned int rpl;
3728
3729         vmx_get_segment(vcpu, &var, seg);
3730         rpl = var.selector & SELECTOR_RPL_MASK;
3731
3732         if (var.unusable)
3733                 return true;
3734         if (!var.s)
3735                 return false;
3736         if (!var.present)
3737                 return false;
3738         if (~var.type & (AR_TYPE_CODE_MASK|AR_TYPE_WRITEABLE_MASK)) {
3739                 if (var.dpl < rpl) /* DPL < RPL */
3740                         return false;
3741         }
3742
3743         /* TODO: Add other members to kvm_segment_field to allow checking for other access
3744          * rights flags
3745          */
3746         return true;
3747 }
3748
3749 static bool tr_valid(struct kvm_vcpu *vcpu)
3750 {
3751         struct kvm_segment tr;
3752
3753         vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
3754
3755         if (tr.unusable)
3756                 return false;
3757         if (tr.selector & SELECTOR_TI_MASK)     /* TI = 1 */
3758                 return false;
3759         if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
3760                 return false;
3761         if (!tr.present)
3762                 return false;
3763
3764         return true;
3765 }
3766
3767 static bool ldtr_valid(struct kvm_vcpu *vcpu)
3768 {
3769         struct kvm_segment ldtr;
3770
3771         vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
3772
3773         if (ldtr.unusable)
3774                 return true;
3775         if (ldtr.selector & SELECTOR_TI_MASK)   /* TI = 1 */
3776                 return false;
3777         if (ldtr.type != 2)
3778                 return false;
3779         if (!ldtr.present)
3780                 return false;
3781
3782         return true;
3783 }
3784
3785 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
3786 {
3787         struct kvm_segment cs, ss;
3788
3789         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3790         vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3791
3792         return ((cs.selector & SELECTOR_RPL_MASK) ==
3793                  (ss.selector & SELECTOR_RPL_MASK));
3794 }
3795
3796 /*
3797  * Check if guest state is valid. Returns true if valid, false if
3798  * not.
3799  * We assume that registers are always usable
3800  */
3801 static bool guest_state_valid(struct kvm_vcpu *vcpu)
3802 {
3803         if (enable_unrestricted_guest)
3804                 return true;
3805
3806         /* real mode guest state checks */
3807         if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
3808                 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
3809                         return false;
3810                 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
3811                         return false;
3812                 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
3813                         return false;
3814                 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
3815                         return false;
3816                 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
3817                         return false;
3818                 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
3819                         return false;
3820         } else {
3821         /* protected mode guest state checks */
3822                 if (!cs_ss_rpl_check(vcpu))
3823                         return false;
3824                 if (!code_segment_valid(vcpu))
3825                         return false;
3826                 if (!stack_segment_valid(vcpu))
3827                         return false;
3828                 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
3829                         return false;
3830                 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
3831                         return false;
3832                 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
3833                         return false;
3834                 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
3835                         return false;
3836                 if (!tr_valid(vcpu))
3837                         return false;
3838                 if (!ldtr_valid(vcpu))
3839                         return false;
3840         }
3841         /* TODO:
3842          * - Add checks on RIP
3843          * - Add checks on RFLAGS
3844          */
3845
3846         return true;
3847 }
3848
3849 static int init_rmode_tss(struct kvm *kvm)
3850 {
3851         gfn_t fn;
3852         u16 data = 0;
3853         int r, idx, ret = 0;
3854
3855         idx = srcu_read_lock(&kvm->srcu);
3856         fn = kvm->arch.tss_addr >> PAGE_SHIFT;
3857         r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3858         if (r < 0)
3859                 goto out;
3860         data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
3861         r = kvm_write_guest_page(kvm, fn++, &data,
3862                         TSS_IOPB_BASE_OFFSET, sizeof(u16));
3863         if (r < 0)
3864                 goto out;
3865         r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
3866         if (r < 0)
3867                 goto out;
3868         r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3869         if (r < 0)
3870                 goto out;
3871         data = ~0;
3872         r = kvm_write_guest_page(kvm, fn, &data,
3873                                  RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
3874                                  sizeof(u8));
3875         if (r < 0)
3876                 goto out;
3877
3878         ret = 1;
3879 out:
3880         srcu_read_unlock(&kvm->srcu, idx);
3881         return ret;
3882 }
3883
3884 static int init_rmode_identity_map(struct kvm *kvm)
3885 {
3886         int i, idx, r, ret;
3887         pfn_t identity_map_pfn;
3888         u32 tmp;
3889
3890         if (!enable_ept)
3891                 return 1;
3892         if (unlikely(!kvm->arch.ept_identity_pagetable)) {
3893                 printk(KERN_ERR "EPT: identity-mapping pagetable "
3894                         "haven't been allocated!\n");
3895                 return 0;
3896         }
3897         if (likely(kvm->arch.ept_identity_pagetable_done))
3898                 return 1;
3899         ret = 0;
3900         identity_map_pfn = kvm->arch.ept_identity_map_addr >> PAGE_SHIFT;
3901         idx = srcu_read_lock(&kvm->srcu);
3902         r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
3903         if (r < 0)
3904                 goto out;
3905         /* Set up identity-mapping pagetable for EPT in real mode */
3906         for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
3907                 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
3908                         _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
3909                 r = kvm_write_guest_page(kvm, identity_map_pfn,
3910                                 &tmp, i * sizeof(tmp), sizeof(tmp));
3911                 if (r < 0)
3912                         goto out;
3913         }
3914         kvm->arch.ept_identity_pagetable_done = true;
3915         ret = 1;
3916 out:
3917         srcu_read_unlock(&kvm->srcu, idx);
3918         return ret;
3919 }
3920
3921 static void seg_setup(int seg)
3922 {
3923         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3924         unsigned int ar;
3925
3926         vmcs_write16(sf->selector, 0);
3927         vmcs_writel(sf->base, 0);
3928         vmcs_write32(sf->limit, 0xffff);
3929         ar = 0x93;
3930         if (seg == VCPU_SREG_CS)
3931                 ar |= 0x08; /* code segment */
3932
3933         vmcs_write32(sf->ar_bytes, ar);
3934 }
3935
3936 static int alloc_apic_access_page(struct kvm *kvm)
3937 {
3938         struct page *page;
3939         struct kvm_userspace_memory_region kvm_userspace_mem;
3940         int r = 0;
3941
3942         mutex_lock(&kvm->slots_lock);
3943         if (kvm->arch.apic_access_page)
3944                 goto out;
3945         kvm_userspace_mem.slot = APIC_ACCESS_PAGE_PRIVATE_MEMSLOT;
3946         kvm_userspace_mem.flags = 0;
3947         kvm_userspace_mem.guest_phys_addr = 0xfee00000ULL;
3948         kvm_userspace_mem.memory_size = PAGE_SIZE;
3949         r = __kvm_set_memory_region(kvm, &kvm_userspace_mem);
3950         if (r)
3951                 goto out;
3952
3953         page = gfn_to_page(kvm, 0xfee00);
3954         if (is_error_page(page)) {
3955                 r = -EFAULT;
3956                 goto out;
3957         }
3958
3959         kvm->arch.apic_access_page = page;
3960 out:
3961         mutex_unlock(&kvm->slots_lock);
3962         return r;
3963 }
3964
3965 static int alloc_identity_pagetable(struct kvm *kvm)
3966 {
3967         struct page *page;
3968         struct kvm_userspace_memory_region kvm_userspace_mem;
3969         int r = 0;
3970
3971         mutex_lock(&kvm->slots_lock);
3972         if (kvm->arch.ept_identity_pagetable)
3973                 goto out;
3974         kvm_userspace_mem.slot = IDENTITY_PAGETABLE_PRIVATE_MEMSLOT;
3975         kvm_userspace_mem.flags = 0;
3976         kvm_userspace_mem.guest_phys_addr =
3977                 kvm->arch.ept_identity_map_addr;
3978         kvm_userspace_mem.memory_size = PAGE_SIZE;
3979         r = __kvm_set_memory_region(kvm, &kvm_userspace_mem);
3980         if (r)
3981                 goto out;
3982
3983         page = gfn_to_page(kvm, kvm->arch.ept_identity_map_addr >> PAGE_SHIFT);
3984         if (is_error_page(page)) {
3985                 r = -EFAULT;
3986                 goto out;
3987         }
3988
3989         kvm->arch.ept_identity_pagetable = page;
3990 out:
3991         mutex_unlock(&kvm->slots_lock);
3992         return r;
3993 }
3994
3995 static void allocate_vpid(struct vcpu_vmx *vmx)
3996 {
3997         int vpid;
3998
3999         vmx->vpid = 0;
4000         if (!enable_vpid)
4001                 return;
4002         spin_lock(&vmx_vpid_lock);
4003         vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
4004         if (vpid < VMX_NR_VPIDS) {
4005                 vmx->vpid = vpid;
4006                 __set_bit(vpid, vmx_vpid_bitmap);
4007         }
4008         spin_unlock(&vmx_vpid_lock);
4009 }
4010
4011 static void free_vpid(struct vcpu_vmx *vmx)
4012 {
4013         if (!enable_vpid)
4014                 return;
4015         spin_lock(&vmx_vpid_lock);
4016         if (vmx->vpid != 0)
4017                 __clear_bit(vmx->vpid, vmx_vpid_bitmap);
4018         spin_unlock(&vmx_vpid_lock);
4019 }
4020
4021 #define MSR_TYPE_R      1
4022 #define MSR_TYPE_W      2
4023 static void __vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
4024                                                 u32 msr, int type)
4025 {
4026         int f = sizeof(unsigned long);
4027
4028         if (!cpu_has_vmx_msr_bitmap())
4029                 return;
4030
4031         /*
4032          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
4033          * have the write-low and read-high bitmap offsets the wrong way round.
4034          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
4035          */
4036         if (msr <= 0x1fff) {
4037                 if (type & MSR_TYPE_R)
4038                         /* read-low */
4039                         __clear_bit(msr, msr_bitmap + 0x000 / f);
4040
4041                 if (type & MSR_TYPE_W)
4042                         /* write-low */
4043                         __clear_bit(msr, msr_bitmap + 0x800 / f);
4044
4045         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
4046                 msr &= 0x1fff;
4047                 if (type & MSR_TYPE_R)
4048                         /* read-high */
4049                         __clear_bit(msr, msr_bitmap + 0x400 / f);
4050
4051                 if (type & MSR_TYPE_W)
4052                         /* write-high */
4053                         __clear_bit(msr, msr_bitmap + 0xc00 / f);
4054
4055         }
4056 }
4057
4058 static void __vmx_enable_intercept_for_msr(unsigned long *msr_bitmap,
4059                                                 u32 msr, int type)
4060 {
4061         int f = sizeof(unsigned long);
4062
4063         if (!cpu_has_vmx_msr_bitmap())
4064                 return;
4065
4066         /*
4067          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
4068          * have the write-low and read-high bitmap offsets the wrong way round.
4069          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
4070          */
4071         if (msr <= 0x1fff) {
4072                 if (type & MSR_TYPE_R)
4073                         /* read-low */
4074                         __set_bit(msr, msr_bitmap + 0x000 / f);
4075
4076                 if (type & MSR_TYPE_W)
4077                         /* write-low */
4078                         __set_bit(msr, msr_bitmap + 0x800 / f);
4079
4080         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
4081                 msr &= 0x1fff;
4082                 if (type & MSR_TYPE_R)
4083                         /* read-high */
4084                         __set_bit(msr, msr_bitmap + 0x400 / f);
4085
4086                 if (type & MSR_TYPE_W)
4087                         /* write-high */
4088                         __set_bit(msr, msr_bitmap + 0xc00 / f);
4089
4090         }
4091 }
4092
4093 static void vmx_disable_intercept_for_msr(u32 msr, bool longmode_only)
4094 {
4095         if (!longmode_only)
4096                 __vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy,
4097                                                 msr, MSR_TYPE_R | MSR_TYPE_W);
4098         __vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode,
4099                                                 msr, MSR_TYPE_R | MSR_TYPE_W);
4100 }
4101
4102 static void vmx_enable_intercept_msr_read_x2apic(u32 msr)
4103 {
4104         __vmx_enable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic,
4105                         msr, MSR_TYPE_R);
4106         __vmx_enable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic,
4107                         msr, MSR_TYPE_R);
4108 }
4109
4110 static void vmx_disable_intercept_msr_read_x2apic(u32 msr)
4111 {
4112         __vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic,
4113                         msr, MSR_TYPE_R);
4114         __vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic,
4115                         msr, MSR_TYPE_R);
4116 }
4117
4118 static void vmx_disable_intercept_msr_write_x2apic(u32 msr)
4119 {
4120         __vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic,
4121                         msr, MSR_TYPE_W);
4122         __vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic,
4123                         msr, MSR_TYPE_W);
4124 }
4125
4126 static int vmx_vm_has_apicv(struct kvm *kvm)
4127 {
4128         return enable_apicv && irqchip_in_kernel(kvm);
4129 }
4130
4131 /*
4132  * Send interrupt to vcpu via posted interrupt way.
4133  * 1. If target vcpu is running(non-root mode), send posted interrupt
4134  * notification to vcpu and hardware will sync PIR to vIRR atomically.
4135  * 2. If target vcpu isn't running(root mode), kick it to pick up the
4136  * interrupt from PIR in next vmentry.
4137  */
4138 static void vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
4139 {
4140         struct vcpu_vmx *vmx = to_vmx(vcpu);
4141         int r;
4142
4143         if (pi_test_and_set_pir(vector, &vmx->pi_desc))
4144                 return;
4145
4146         r = pi_test_and_set_on(&vmx->pi_desc);
4147         kvm_make_request(KVM_REQ_EVENT, vcpu);
4148 #ifdef CONFIG_SMP
4149         if (!r && (vcpu->mode == IN_GUEST_MODE))
4150                 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu),
4151                                 POSTED_INTR_VECTOR);
4152         else
4153 #endif
4154                 kvm_vcpu_kick(vcpu);
4155 }
4156
4157 static void vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
4158 {
4159         struct vcpu_vmx *vmx = to_vmx(vcpu);
4160
4161         if (!pi_test_and_clear_on(&vmx->pi_desc))
4162                 return;
4163
4164         kvm_apic_update_irr(vcpu, vmx->pi_desc.pir);
4165 }
4166
4167 static void vmx_sync_pir_to_irr_dummy(struct kvm_vcpu *vcpu)
4168 {
4169         return;
4170 }
4171
4172 /*
4173  * Set up the vmcs's constant host-state fields, i.e., host-state fields that
4174  * will not change in the lifetime of the guest.
4175  * Note that host-state that does change is set elsewhere. E.g., host-state
4176  * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
4177  */
4178 static void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
4179 {
4180         u32 low32, high32;
4181         unsigned long tmpl;
4182         struct desc_ptr dt;
4183
4184         vmcs_writel(HOST_CR0, read_cr0() & ~X86_CR0_TS);  /* 22.2.3 */
4185         vmcs_writel(HOST_CR4, read_cr4());  /* 22.2.3, 22.2.5 */
4186         vmcs_writel(HOST_CR3, read_cr3());  /* 22.2.3  FIXME: shadow tables */
4187
4188         vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS);  /* 22.2.4 */
4189 #ifdef CONFIG_X86_64
4190         /*
4191          * Load null selectors, so we can avoid reloading them in
4192          * __vmx_load_host_state(), in case userspace uses the null selectors
4193          * too (the expected case).
4194          */
4195         vmcs_write16(HOST_DS_SELECTOR, 0);
4196         vmcs_write16(HOST_ES_SELECTOR, 0);
4197 #else
4198         vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
4199         vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
4200 #endif
4201         vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
4202         vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8);  /* 22.2.4 */
4203
4204         native_store_idt(&dt);
4205         vmcs_writel(HOST_IDTR_BASE, dt.address);   /* 22.2.4 */
4206         vmx->host_idt_base = dt.address;
4207
4208         vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */
4209
4210         rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
4211         vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
4212         rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
4213         vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl);   /* 22.2.3 */
4214
4215         if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
4216                 rdmsr(MSR_IA32_CR_PAT, low32, high32);
4217                 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
4218         }
4219 }
4220
4221 static void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
4222 {
4223         vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
4224         if (enable_ept)
4225                 vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
4226         if (is_guest_mode(&vmx->vcpu))
4227                 vmx->vcpu.arch.cr4_guest_owned_bits &=
4228                         ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
4229         vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
4230 }
4231
4232 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
4233 {
4234         u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
4235
4236         if (!vmx_vm_has_apicv(vmx->vcpu.kvm))
4237                 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
4238         return pin_based_exec_ctrl;
4239 }
4240
4241 static u32 vmx_exec_control(struct vcpu_vmx *vmx)
4242 {
4243         u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
4244         if (!vm_need_tpr_shadow(vmx->vcpu.kvm)) {
4245                 exec_control &= ~CPU_BASED_TPR_SHADOW;
4246 #ifdef CONFIG_X86_64
4247                 exec_control |= CPU_BASED_CR8_STORE_EXITING |
4248                                 CPU_BASED_CR8_LOAD_EXITING;
4249 #endif
4250         }
4251         if (!enable_ept)
4252                 exec_control |= CPU_BASED_CR3_STORE_EXITING |
4253                                 CPU_BASED_CR3_LOAD_EXITING  |
4254                                 CPU_BASED_INVLPG_EXITING;
4255         return exec_control;
4256 }
4257
4258 static u32 vmx_secondary_exec_control(struct vcpu_vmx *vmx)
4259 {
4260         u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
4261         if (!vm_need_virtualize_apic_accesses(vmx->vcpu.kvm))
4262                 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
4263         if (vmx->vpid == 0)
4264                 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
4265         if (!enable_ept) {
4266                 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
4267                 enable_unrestricted_guest = 0;
4268                 /* Enable INVPCID for non-ept guests may cause performance regression. */
4269                 exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
4270         }
4271         if (!enable_unrestricted_guest)
4272                 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
4273         if (!ple_gap)
4274                 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
4275         if (!vmx_vm_has_apicv(vmx->vcpu.kvm))
4276                 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
4277                                   SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4278         exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
4279         /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
4280            (handle_vmptrld).
4281            We can NOT enable shadow_vmcs here because we don't have yet
4282            a current VMCS12
4283         */
4284         exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
4285         return exec_control;
4286 }
4287
4288 static void ept_set_mmio_spte_mask(void)
4289 {
4290         /*
4291          * EPT Misconfigurations can be generated if the value of bits 2:0
4292          * of an EPT paging-structure entry is 110b (write/execute).
4293          * Also, magic bits (0x3ull << 62) is set to quickly identify mmio
4294          * spte.
4295          */
4296         kvm_mmu_set_mmio_spte_mask((0x3ull << 62) | 0x6ull);
4297 }
4298
4299 /*
4300  * Sets up the vmcs for emulated real mode.
4301  */
4302 static int vmx_vcpu_setup(struct vcpu_vmx *vmx)
4303 {
4304 #ifdef CONFIG_X86_64
4305         unsigned long a;
4306 #endif
4307         int i;
4308
4309         /* I/O */
4310         vmcs_write64(IO_BITMAP_A, __pa(vmx_io_bitmap_a));
4311         vmcs_write64(IO_BITMAP_B, __pa(vmx_io_bitmap_b));
4312
4313         if (enable_shadow_vmcs) {
4314                 vmcs_write64(VMREAD_BITMAP, __pa(vmx_vmread_bitmap));
4315                 vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmwrite_bitmap));
4316         }
4317         if (cpu_has_vmx_msr_bitmap())
4318                 vmcs_write64(MSR_BITMAP, __pa(vmx_msr_bitmap_legacy));
4319
4320         vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
4321
4322         /* Control */
4323         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
4324
4325         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
4326
4327         if (cpu_has_secondary_exec_ctrls()) {
4328                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
4329                                 vmx_secondary_exec_control(vmx));
4330         }
4331
4332         if (vmx_vm_has_apicv(vmx->vcpu.kvm)) {
4333                 vmcs_write64(EOI_EXIT_BITMAP0, 0);
4334                 vmcs_write64(EOI_EXIT_BITMAP1, 0);
4335                 vmcs_write64(EOI_EXIT_BITMAP2, 0);
4336                 vmcs_write64(EOI_EXIT_BITMAP3, 0);
4337
4338                 vmcs_write16(GUEST_INTR_STATUS, 0);
4339
4340                 vmcs_write64(POSTED_INTR_NV, POSTED_INTR_VECTOR);
4341                 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
4342         }
4343
4344         if (ple_gap) {
4345                 vmcs_write32(PLE_GAP, ple_gap);
4346                 vmcs_write32(PLE_WINDOW, ple_window);
4347         }
4348
4349         vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
4350         vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
4351         vmcs_write32(CR3_TARGET_COUNT, 0);           /* 22.2.1 */
4352
4353         vmcs_write16(HOST_FS_SELECTOR, 0);            /* 22.2.4 */
4354         vmcs_write16(HOST_GS_SELECTOR, 0);            /* 22.2.4 */
4355         vmx_set_constant_host_state(vmx);
4356 #ifdef CONFIG_X86_64
4357         rdmsrl(MSR_FS_BASE, a);
4358         vmcs_writel(HOST_FS_BASE, a); /* 22.2.4 */
4359         rdmsrl(MSR_GS_BASE, a);
4360         vmcs_writel(HOST_GS_BASE, a); /* 22.2.4 */
4361 #else
4362         vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
4363         vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
4364 #endif
4365
4366         vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
4367         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
4368         vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host));
4369         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
4370         vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest));
4371
4372         if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
4373                 u32 msr_low, msr_high;
4374                 u64 host_pat;
4375                 rdmsr(MSR_IA32_CR_PAT, msr_low, msr_high);
4376                 host_pat = msr_low | ((u64) msr_high << 32);
4377                 /* Write the default value follow host pat */
4378                 vmcs_write64(GUEST_IA32_PAT, host_pat);
4379                 /* Keep arch.pat sync with GUEST_IA32_PAT */
4380                 vmx->vcpu.arch.pat = host_pat;
4381         }
4382
4383         for (i = 0; i < NR_VMX_MSR; ++i) {
4384                 u32 index = vmx_msr_index[i];
4385                 u32 data_low, data_high;
4386                 int j = vmx->nmsrs;
4387
4388                 if (rdmsr_safe(index, &data_low, &data_high) < 0)
4389                         continue;
4390                 if (wrmsr_safe(index, data_low, data_high) < 0)
4391                         continue;
4392                 vmx->guest_msrs[j].index = i;
4393                 vmx->guest_msrs[j].data = 0;
4394                 vmx->guest_msrs[j].mask = -1ull;
4395                 ++vmx->nmsrs;
4396         }
4397
4398
4399         vm_exit_controls_init(vmx, vmcs_config.vmexit_ctrl);
4400
4401         /* 22.2.1, 20.8.1 */
4402         vm_entry_controls_init(vmx, vmcs_config.vmentry_ctrl);
4403
4404         vmcs_writel(CR0_GUEST_HOST_MASK, ~0UL);
4405         set_cr4_guest_host_mask(vmx);
4406
4407         return 0;
4408 }
4409
4410 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu)
4411 {
4412         struct vcpu_vmx *vmx = to_vmx(vcpu);
4413         struct msr_data apic_base_msr;
4414
4415         vmx->rmode.vm86_active = 0;
4416
4417         vmx->soft_vnmi_blocked = 0;
4418
4419         vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
4420         kvm_set_cr8(&vmx->vcpu, 0);
4421         apic_base_msr.data = 0xfee00000 | MSR_IA32_APICBASE_ENABLE;
4422         if (kvm_vcpu_is_bsp(&vmx->vcpu))
4423                 apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
4424         apic_base_msr.host_initiated = true;
4425         kvm_set_apic_base(&vmx->vcpu, &apic_base_msr);
4426
4427         vmx_segment_cache_clear(vmx);
4428
4429         seg_setup(VCPU_SREG_CS);
4430         vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
4431         vmcs_write32(GUEST_CS_BASE, 0xffff0000);
4432
4433         seg_setup(VCPU_SREG_DS);
4434         seg_setup(VCPU_SREG_ES);
4435         seg_setup(VCPU_SREG_FS);
4436         seg_setup(VCPU_SREG_GS);
4437         seg_setup(VCPU_SREG_SS);
4438
4439         vmcs_write16(GUEST_TR_SELECTOR, 0);
4440         vmcs_writel(GUEST_TR_BASE, 0);
4441         vmcs_write32(GUEST_TR_LIMIT, 0xffff);
4442         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4443
4444         vmcs_write16(GUEST_LDTR_SELECTOR, 0);
4445         vmcs_writel(GUEST_LDTR_BASE, 0);
4446         vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
4447         vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
4448
4449         vmcs_write32(GUEST_SYSENTER_CS, 0);
4450         vmcs_writel(GUEST_SYSENTER_ESP, 0);
4451         vmcs_writel(GUEST_SYSENTER_EIP, 0);
4452
4453         vmcs_writel(GUEST_RFLAGS, 0x02);
4454         kvm_rip_write(vcpu, 0xfff0);
4455
4456         vmcs_writel(GUEST_GDTR_BASE, 0);
4457         vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
4458
4459         vmcs_writel(GUEST_IDTR_BASE, 0);
4460         vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
4461
4462         vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
4463         vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
4464         vmcs_write32(GUEST_PENDING_DBG_EXCEPTIONS, 0);
4465
4466         /* Special registers */
4467         vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
4468
4469         setup_msrs(vmx);
4470
4471         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);  /* 22.2.1 */
4472
4473         if (cpu_has_vmx_tpr_shadow()) {
4474                 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
4475                 if (vm_need_tpr_shadow(vmx->vcpu.kvm))
4476                         vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
4477                                      __pa(vmx->vcpu.arch.apic->regs));
4478                 vmcs_write32(TPR_THRESHOLD, 0);
4479         }
4480
4481         if (vm_need_virtualize_apic_accesses(vmx->vcpu.kvm))
4482                 vmcs_write64(APIC_ACCESS_ADDR,
4483                              page_to_phys(vmx->vcpu.kvm->arch.apic_access_page));
4484
4485         if (vmx_vm_has_apicv(vcpu->kvm))
4486                 memset(&vmx->pi_desc, 0, sizeof(struct pi_desc));
4487
4488         if (vmx->vpid != 0)
4489                 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
4490
4491         vmx->vcpu.arch.cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
4492         vmx_set_cr0(&vmx->vcpu, kvm_read_cr0(vcpu)); /* enter rmode */
4493         vmx_set_cr4(&vmx->vcpu, 0);
4494         vmx_set_efer(&vmx->vcpu, 0);
4495         vmx_fpu_activate(&vmx->vcpu);
4496         update_exception_bitmap(&vmx->vcpu);
4497
4498         vpid_sync_context(vmx);
4499 }
4500
4501 /*
4502  * In nested virtualization, check if L1 asked to exit on external interrupts.
4503  * For most existing hypervisors, this will always return true.
4504  */
4505 static bool nested_exit_on_intr(struct kvm_vcpu *vcpu)
4506 {
4507         return get_vmcs12(vcpu)->pin_based_vm_exec_control &
4508                 PIN_BASED_EXT_INTR_MASK;
4509 }
4510
4511 static bool nested_exit_on_nmi(struct kvm_vcpu *vcpu)
4512 {
4513         return get_vmcs12(vcpu)->pin_based_vm_exec_control &
4514                 PIN_BASED_NMI_EXITING;
4515 }
4516
4517 static int enable_irq_window(struct kvm_vcpu *vcpu)
4518 {
4519         u32 cpu_based_vm_exec_control;
4520
4521         if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
4522                 /*
4523                  * We get here if vmx_interrupt_allowed() said we can't
4524                  * inject to L1 now because L2 must run. The caller will have
4525                  * to make L2 exit right after entry, so we can inject to L1
4526                  * more promptly.
4527                  */
4528                 return -EBUSY;
4529
4530         cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
4531         cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_INTR_PENDING;
4532         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
4533         return 0;
4534 }
4535
4536 static int enable_nmi_window(struct kvm_vcpu *vcpu)
4537 {
4538         u32 cpu_based_vm_exec_control;
4539
4540         if (!cpu_has_virtual_nmis())
4541                 return enable_irq_window(vcpu);
4542
4543         if (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI)
4544                 return enable_irq_window(vcpu);
4545
4546         cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
4547         cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_NMI_PENDING;
4548         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
4549         return 0;
4550 }
4551
4552 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
4553 {
4554         struct vcpu_vmx *vmx = to_vmx(vcpu);
4555         uint32_t intr;
4556         int irq = vcpu->arch.interrupt.nr;
4557
4558         trace_kvm_inj_virq(irq);
4559
4560         ++vcpu->stat.irq_injections;
4561         if (vmx->rmode.vm86_active) {
4562                 int inc_eip = 0;
4563                 if (vcpu->arch.interrupt.soft)
4564                         inc_eip = vcpu->arch.event_exit_inst_len;
4565                 if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE)
4566                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
4567                 return;
4568         }
4569         intr = irq | INTR_INFO_VALID_MASK;
4570         if (vcpu->arch.interrupt.soft) {
4571                 intr |= INTR_TYPE_SOFT_INTR;
4572                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
4573                              vmx->vcpu.arch.event_exit_inst_len);
4574         } else
4575                 intr |= INTR_TYPE_EXT_INTR;
4576         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
4577 }
4578
4579 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
4580 {
4581         struct vcpu_vmx *vmx = to_vmx(vcpu);
4582
4583         if (is_guest_mode(vcpu))
4584                 return;
4585
4586         if (!cpu_has_virtual_nmis()) {
4587                 /*
4588                  * Tracking the NMI-blocked state in software is built upon
4589                  * finding the next open IRQ window. This, in turn, depends on
4590                  * well-behaving guests: They have to keep IRQs disabled at
4591                  * least as long as the NMI handler runs. Otherwise we may
4592                  * cause NMI nesting, maybe breaking the guest. But as this is
4593                  * highly unlikely, we can live with the residual risk.
4594                  */
4595                 vmx->soft_vnmi_blocked = 1;
4596                 vmx->vnmi_blocked_time = 0;
4597         }
4598
4599         ++vcpu->stat.nmi_injections;
4600         vmx->nmi_known_unmasked = false;
4601         if (vmx->rmode.vm86_active) {
4602                 if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE)
4603                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
4604                 return;
4605         }
4606         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
4607                         INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
4608 }
4609
4610 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
4611 {
4612         if (!cpu_has_virtual_nmis())
4613                 return to_vmx(vcpu)->soft_vnmi_blocked;
4614         if (to_vmx(vcpu)->nmi_known_unmasked)
4615                 return false;
4616         return vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
4617 }
4618
4619 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
4620 {
4621         struct vcpu_vmx *vmx = to_vmx(vcpu);
4622
4623         if (!cpu_has_virtual_nmis()) {
4624                 if (vmx->soft_vnmi_blocked != masked) {
4625                         vmx->soft_vnmi_blocked = masked;
4626                         vmx->vnmi_blocked_time = 0;
4627                 }
4628         } else {
4629                 vmx->nmi_known_unmasked = !masked;
4630                 if (masked)
4631                         vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
4632                                       GUEST_INTR_STATE_NMI);
4633                 else
4634                         vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
4635                                         GUEST_INTR_STATE_NMI);
4636         }
4637 }
4638
4639 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
4640 {
4641         if (to_vmx(vcpu)->nested.nested_run_pending)
4642                 return 0;
4643
4644         if (!cpu_has_virtual_nmis() && to_vmx(vcpu)->soft_vnmi_blocked)
4645                 return 0;
4646
4647         return  !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4648                   (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
4649                    | GUEST_INTR_STATE_NMI));
4650 }
4651
4652 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
4653 {
4654         return (!to_vmx(vcpu)->nested.nested_run_pending &&
4655                 vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
4656                 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4657                         (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
4658 }
4659
4660 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
4661 {
4662         int ret;
4663         struct kvm_userspace_memory_region tss_mem = {
4664                 .slot = TSS_PRIVATE_MEMSLOT,
4665                 .guest_phys_addr = addr,
4666                 .memory_size = PAGE_SIZE * 3,
4667                 .flags = 0,
4668         };
4669
4670         ret = kvm_set_memory_region(kvm, &tss_mem);
4671         if (ret)
4672                 return ret;
4673         kvm->arch.tss_addr = addr;
4674         if (!init_rmode_tss(kvm))
4675                 return  -ENOMEM;
4676
4677         return 0;
4678 }
4679
4680 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
4681 {
4682         switch (vec) {
4683         case BP_VECTOR:
4684                 /*
4685                  * Update instruction length as we may reinject the exception
4686                  * from user space while in guest debugging mode.
4687                  */
4688                 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
4689                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4690                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
4691                         return false;
4692                 /* fall through */
4693         case DB_VECTOR:
4694                 if (vcpu->guest_debug &
4695                         (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
4696                         return false;
4697                 /* fall through */
4698         case DE_VECTOR:
4699         case OF_VECTOR:
4700         case BR_VECTOR:
4701         case UD_VECTOR:
4702         case DF_VECTOR:
4703         case SS_VECTOR:
4704         case GP_VECTOR:
4705         case MF_VECTOR:
4706                 return true;
4707         break;
4708         }
4709         return false;
4710 }
4711
4712 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
4713                                   int vec, u32 err_code)
4714 {
4715         /*
4716          * Instruction with address size override prefix opcode 0x67
4717          * Cause the #SS fault with 0 error code in VM86 mode.
4718          */
4719         if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
4720                 if (emulate_instruction(vcpu, 0) == EMULATE_DONE) {
4721                         if (vcpu->arch.halt_request) {
4722                                 vcpu->arch.halt_request = 0;
4723                                 return kvm_emulate_halt(vcpu);
4724                         }
4725                         return 1;
4726                 }
4727                 return 0;
4728         }
4729
4730         /*
4731          * Forward all other exceptions that are valid in real mode.
4732          * FIXME: Breaks guest debugging in real mode, needs to be fixed with
4733          *        the required debugging infrastructure rework.
4734          */
4735         kvm_queue_exception(vcpu, vec);
4736         return 1;
4737 }
4738
4739 /*
4740  * Trigger machine check on the host. We assume all the MSRs are already set up
4741  * by the CPU and that we still run on the same CPU as the MCE occurred on.
4742  * We pass a fake environment to the machine check handler because we want
4743  * the guest to be always treated like user space, no matter what context
4744  * it used internally.
4745  */
4746 static void kvm_machine_check(void)
4747 {
4748 #if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
4749         struct pt_regs regs = {
4750                 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
4751                 .flags = X86_EFLAGS_IF,
4752         };
4753
4754         do_machine_check(&regs, 0);
4755 #endif
4756 }
4757
4758 static int handle_machine_check(struct kvm_vcpu *vcpu)
4759 {
4760         /* already handled by vcpu_run */
4761         return 1;
4762 }
4763
4764 static int handle_exception(struct kvm_vcpu *vcpu)
4765 {
4766         struct vcpu_vmx *vmx = to_vmx(vcpu);
4767         struct kvm_run *kvm_run = vcpu->run;
4768         u32 intr_info, ex_no, error_code;
4769         unsigned long cr2, rip, dr6;
4770         u32 vect_info;
4771         enum emulation_result er;
4772
4773         vect_info = vmx->idt_vectoring_info;
4774         intr_info = vmx->exit_intr_info;
4775
4776         if (is_machine_check(intr_info))
4777                 return handle_machine_check(vcpu);
4778
4779         if ((intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR)
4780                 return 1;  /* already handled by vmx_vcpu_run() */
4781
4782         if (is_no_device(intr_info)) {
4783                 vmx_fpu_activate(vcpu);
4784                 return 1;
4785         }
4786
4787         if (is_invalid_opcode(intr_info)) {
4788                 er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD);
4789                 if (er != EMULATE_DONE)
4790                         kvm_queue_exception(vcpu, UD_VECTOR);
4791                 return 1;
4792         }
4793
4794         error_code = 0;
4795         if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
4796                 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
4797
4798         /*
4799          * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
4800          * MMIO, it is better to report an internal error.
4801          * See the comments in vmx_handle_exit.
4802          */
4803         if ((vect_info & VECTORING_INFO_VALID_MASK) &&
4804             !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
4805                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4806                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
4807                 vcpu->run->internal.ndata = 2;
4808                 vcpu->run->internal.data[0] = vect_info;
4809                 vcpu->run->internal.data[1] = intr_info;
4810                 return 0;
4811         }
4812
4813         if (is_page_fault(intr_info)) {
4814                 /* EPT won't cause page fault directly */
4815                 BUG_ON(enable_ept);
4816                 cr2 = vmcs_readl(EXIT_QUALIFICATION);
4817                 trace_kvm_page_fault(cr2, error_code);
4818
4819                 if (kvm_event_needs_reinjection(vcpu))
4820                         kvm_mmu_unprotect_page_virt(vcpu, cr2);
4821                 return kvm_mmu_page_fault(vcpu, cr2, error_code, NULL, 0);
4822         }
4823
4824         ex_no = intr_info & INTR_INFO_VECTOR_MASK;
4825
4826         if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
4827                 return handle_rmode_exception(vcpu, ex_no, error_code);
4828
4829         switch (ex_no) {
4830         case DB_VECTOR:
4831                 dr6 = vmcs_readl(EXIT_QUALIFICATION);
4832                 if (!(vcpu->guest_debug &
4833                       (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
4834                         vcpu->arch.dr6 &= ~15;
4835                         vcpu->arch.dr6 |= dr6;
4836                         kvm_queue_exception(vcpu, DB_VECTOR);
4837                         return 1;
4838                 }
4839                 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
4840                 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
4841                 /* fall through */
4842         case BP_VECTOR:
4843                 /*
4844                  * Update instruction length as we may reinject #BP from
4845                  * user space while in guest debugging mode. Reading it for
4846                  * #DB as well causes no harm, it is not used in that case.
4847                  */
4848                 vmx->vcpu.arch.event_exit_inst_len =
4849                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4850                 kvm_run->exit_reason = KVM_EXIT_DEBUG;
4851                 rip = kvm_rip_read(vcpu);
4852                 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
4853                 kvm_run->debug.arch.exception = ex_no;
4854                 break;
4855         default:
4856                 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
4857                 kvm_run->ex.exception = ex_no;
4858                 kvm_run->ex.error_code = error_code;
4859                 break;
4860         }
4861         return 0;
4862 }
4863
4864 static int handle_external_interrupt(struct kvm_vcpu *vcpu)
4865 {
4866         ++vcpu->stat.irq_exits;
4867         return 1;
4868 }
4869
4870 static int handle_triple_fault(struct kvm_vcpu *vcpu)
4871 {
4872         vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
4873         return 0;
4874 }
4875
4876 static int handle_io(struct kvm_vcpu *vcpu)
4877 {
4878         unsigned long exit_qualification;
4879         int size, in, string;
4880         unsigned port;
4881
4882         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4883         string = (exit_qualification & 16) != 0;
4884         in = (exit_qualification & 8) != 0;
4885
4886         ++vcpu->stat.io_exits;
4887
4888         if (string || in)
4889                 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
4890
4891         port = exit_qualification >> 16;
4892         size = (exit_qualification & 7) + 1;
4893         skip_emulated_instruction(vcpu);
4894
4895         return kvm_fast_pio_out(vcpu, size, port);
4896 }
4897
4898 static void
4899 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
4900 {
4901         /*
4902          * Patch in the VMCALL instruction:
4903          */
4904         hypercall[0] = 0x0f;
4905         hypercall[1] = 0x01;
4906         hypercall[2] = 0xc1;
4907 }
4908
4909 static bool nested_cr0_valid(struct vmcs12 *vmcs12, unsigned long val)
4910 {
4911         unsigned long always_on = VMXON_CR0_ALWAYSON;
4912
4913         if (nested_vmx_secondary_ctls_high &
4914                 SECONDARY_EXEC_UNRESTRICTED_GUEST &&
4915             nested_cpu_has2(vmcs12, SECONDARY_EXEC_UNRESTRICTED_GUEST))
4916                 always_on &= ~(X86_CR0_PE | X86_CR0_PG);
4917         return (val & always_on) == always_on;
4918 }
4919
4920 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
4921 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
4922 {
4923         if (is_guest_mode(vcpu)) {
4924                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4925                 unsigned long orig_val = val;
4926
4927                 /*
4928                  * We get here when L2 changed cr0 in a way that did not change
4929                  * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
4930                  * but did change L0 shadowed bits. So we first calculate the
4931                  * effective cr0 value that L1 would like to write into the
4932                  * hardware. It consists of the L2-owned bits from the new
4933                  * value combined with the L1-owned bits from L1's guest_cr0.
4934                  */
4935                 val = (val & ~vmcs12->cr0_guest_host_mask) |
4936                         (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
4937
4938                 if (!nested_cr0_valid(vmcs12, val))
4939                         return 1;
4940
4941                 if (kvm_set_cr0(vcpu, val))
4942                         return 1;
4943                 vmcs_writel(CR0_READ_SHADOW, orig_val);
4944                 return 0;
4945         } else {
4946                 if (to_vmx(vcpu)->nested.vmxon &&
4947                     ((val & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON))
4948                         return 1;
4949                 return kvm_set_cr0(vcpu, val);
4950         }
4951 }
4952
4953 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
4954 {
4955         if (is_guest_mode(vcpu)) {
4956                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4957                 unsigned long orig_val = val;
4958
4959                 /* analogously to handle_set_cr0 */
4960                 val = (val & ~vmcs12->cr4_guest_host_mask) |
4961                         (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
4962                 if (kvm_set_cr4(vcpu, val))
4963                         return 1;
4964                 vmcs_writel(CR4_READ_SHADOW, orig_val);
4965                 return 0;
4966         } else
4967                 return kvm_set_cr4(vcpu, val);
4968 }
4969
4970 /* called to set cr0 as approriate for clts instruction exit. */
4971 static void handle_clts(struct kvm_vcpu *vcpu)
4972 {
4973         if (is_guest_mode(vcpu)) {
4974                 /*
4975                  * We get here when L2 did CLTS, and L1 didn't shadow CR0.TS
4976                  * but we did (!fpu_active). We need to keep GUEST_CR0.TS on,
4977                  * just pretend it's off (also in arch.cr0 for fpu_activate).
4978                  */
4979                 vmcs_writel(CR0_READ_SHADOW,
4980                         vmcs_readl(CR0_READ_SHADOW) & ~X86_CR0_TS);
4981                 vcpu->arch.cr0 &= ~X86_CR0_TS;
4982         } else
4983                 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
4984 }
4985
4986 static int handle_cr(struct kvm_vcpu *vcpu)
4987 {
4988         unsigned long exit_qualification, val;
4989         int cr;
4990         int reg;
4991         int err;
4992
4993         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4994         cr = exit_qualification & 15;
4995         reg = (exit_qualification >> 8) & 15;
4996         switch ((exit_qualification >> 4) & 3) {
4997         case 0: /* mov to cr */
4998                 val = kvm_register_read(vcpu, reg);
4999                 trace_kvm_cr_write(cr, val);
5000                 switch (cr) {
5001                 case 0:
5002                         err = handle_set_cr0(vcpu, val);
5003                         kvm_complete_insn_gp(vcpu, err);
5004                         return 1;
5005                 case 3:
5006                         err = kvm_set_cr3(vcpu, val);
5007                         kvm_complete_insn_gp(vcpu, err);
5008                         return 1;
5009                 case 4:
5010                         err = handle_set_cr4(vcpu, val);
5011                         kvm_complete_insn_gp(vcpu, err);
5012                         return 1;
5013                 case 8: {
5014                                 u8 cr8_prev = kvm_get_cr8(vcpu);
5015                                 u8 cr8 = kvm_register_read(vcpu, reg);
5016                                 err = kvm_set_cr8(vcpu, cr8);
5017                                 kvm_complete_insn_gp(vcpu, err);
5018                                 if (irqchip_in_kernel(vcpu->kvm))
5019                                         return 1;
5020                                 if (cr8_prev <= cr8)
5021                                         return 1;
5022                                 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
5023                                 return 0;
5024                         }
5025                 }
5026                 break;
5027         case 2: /* clts */
5028                 handle_clts(vcpu);
5029                 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
5030                 skip_emulated_instruction(vcpu);
5031                 vmx_fpu_activate(vcpu);
5032                 return 1;
5033         case 1: /*mov from cr*/
5034                 switch (cr) {
5035                 case 3:
5036                         val = kvm_read_cr3(vcpu);
5037                         kvm_register_write(vcpu, reg, val);
5038                         trace_kvm_cr_read(cr, val);
5039                         skip_emulated_instruction(vcpu);
5040                         return 1;
5041                 case 8:
5042                         val = kvm_get_cr8(vcpu);
5043                         kvm_register_write(vcpu, reg, val);
5044                         trace_kvm_cr_read(cr, val);
5045                         skip_emulated_instruction(vcpu);
5046                         return 1;
5047                 }
5048                 break;
5049         case 3: /* lmsw */
5050                 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
5051                 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
5052                 kvm_lmsw(vcpu, val);
5053
5054                 skip_emulated_instruction(vcpu);
5055                 return 1;
5056         default:
5057                 break;
5058         }
5059         vcpu->run->exit_reason = 0;
5060         vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
5061                (int)(exit_qualification >> 4) & 3, cr);
5062         return 0;
5063 }
5064
5065 static int handle_dr(struct kvm_vcpu *vcpu)
5066 {
5067         unsigned long exit_qualification;
5068         int dr, reg;
5069
5070         /* Do not handle if the CPL > 0, will trigger GP on re-entry */
5071         if (!kvm_require_cpl(vcpu, 0))
5072                 return 1;
5073         dr = vmcs_readl(GUEST_DR7);
5074         if (dr & DR7_GD) {
5075                 /*
5076                  * As the vm-exit takes precedence over the debug trap, we
5077                  * need to emulate the latter, either for the host or the
5078                  * guest debugging itself.
5079                  */
5080                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
5081                         vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
5082                         vcpu->run->debug.arch.dr7 = dr;
5083                         vcpu->run->debug.arch.pc =
5084                                 vmcs_readl(GUEST_CS_BASE) +
5085                                 vmcs_readl(GUEST_RIP);
5086                         vcpu->run->debug.arch.exception = DB_VECTOR;
5087                         vcpu->run->exit_reason = KVM_EXIT_DEBUG;
5088                         return 0;
5089                 } else {
5090                         vcpu->arch.dr7 &= ~DR7_GD;
5091                         vcpu->arch.dr6 |= DR6_BD;
5092                         vmcs_writel(GUEST_DR7, vcpu->arch.dr7);
5093                         kvm_queue_exception(vcpu, DB_VECTOR);
5094                         return 1;
5095                 }
5096         }
5097
5098         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5099         dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
5100         reg = DEBUG_REG_ACCESS_REG(exit_qualification);
5101         if (exit_qualification & TYPE_MOV_FROM_DR) {
5102                 unsigned long val;
5103
5104                 if (kvm_get_dr(vcpu, dr, &val))
5105                         return 1;
5106                 kvm_register_write(vcpu, reg, val);
5107         } else
5108                 if (kvm_set_dr(vcpu, dr, vcpu->arch.regs[reg]))
5109                         return 1;
5110
5111         skip_emulated_instruction(vcpu);
5112         return 1;
5113 }
5114
5115 static u64 vmx_get_dr6(struct kvm_vcpu *vcpu)
5116 {
5117         return vcpu->arch.dr6;
5118 }
5119
5120 static void vmx_set_dr6(struct kvm_vcpu *vcpu, unsigned long val)
5121 {
5122 }
5123
5124 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
5125 {
5126         vmcs_writel(GUEST_DR7, val);
5127 }
5128
5129 static int handle_cpuid(struct kvm_vcpu *vcpu)
5130 {
5131         kvm_emulate_cpuid(vcpu);
5132         return 1;
5133 }
5134
5135 static int handle_rdmsr(struct kvm_vcpu *vcpu)
5136 {
5137         u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
5138         u64 data;
5139
5140         if (vmx_get_msr(vcpu, ecx, &data)) {
5141                 trace_kvm_msr_read_ex(ecx);
5142                 kvm_inject_gp(vcpu, 0);
5143                 return 1;
5144         }
5145
5146         trace_kvm_msr_read(ecx, data);
5147
5148         /* FIXME: handling of bits 32:63 of rax, rdx */
5149         vcpu->arch.regs[VCPU_REGS_RAX] = data & -1u;
5150         vcpu->arch.regs[VCPU_REGS_RDX] = (data >> 32) & -1u;
5151         skip_emulated_instruction(vcpu);
5152         return 1;
5153 }
5154
5155 static int handle_wrmsr(struct kvm_vcpu *vcpu)
5156 {
5157         struct msr_data msr;
5158         u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
5159         u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
5160                 | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
5161
5162         msr.data = data;
5163         msr.index = ecx;
5164         msr.host_initiated = false;
5165         if (vmx_set_msr(vcpu, &msr) != 0) {
5166                 trace_kvm_msr_write_ex(ecx, data);
5167                 kvm_inject_gp(vcpu, 0);
5168                 return 1;
5169         }
5170
5171         trace_kvm_msr_write(ecx, data);
5172         skip_emulated_instruction(vcpu);
5173         return 1;
5174 }
5175
5176 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
5177 {
5178         kvm_make_request(KVM_REQ_EVENT, vcpu);
5179         return 1;
5180 }
5181
5182 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
5183 {
5184         u32 cpu_based_vm_exec_control;
5185
5186         /* clear pending irq */
5187         cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5188         cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
5189         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
5190
5191         kvm_make_request(KVM_REQ_EVENT, vcpu);
5192
5193         ++vcpu->stat.irq_window_exits;
5194
5195         /*
5196          * If the user space waits to inject interrupts, exit as soon as
5197          * possible
5198          */
5199         if (!irqchip_in_kernel(vcpu->kvm) &&
5200             vcpu->run->request_interrupt_window &&
5201             !kvm_cpu_has_interrupt(vcpu)) {
5202                 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
5203                 return 0;
5204         }
5205         return 1;
5206 }
5207
5208 static int handle_halt(struct kvm_vcpu *vcpu)
5209 {
5210         skip_emulated_instruction(vcpu);
5211         return kvm_emulate_halt(vcpu);
5212 }
5213
5214 static int handle_vmcall(struct kvm_vcpu *vcpu)
5215 {
5216         skip_emulated_instruction(vcpu);
5217         kvm_emulate_hypercall(vcpu);
5218         return 1;
5219 }
5220
5221 static int handle_invd(struct kvm_vcpu *vcpu)
5222 {
5223         return emulate_instruction(vcpu, 0) == EMULATE_DONE;
5224 }
5225
5226 static int handle_invlpg(struct kvm_vcpu *vcpu)
5227 {
5228         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5229
5230         kvm_mmu_invlpg(vcpu, exit_qualification);
5231         skip_emulated_instruction(vcpu);
5232         return 1;
5233 }
5234
5235 static int handle_rdpmc(struct kvm_vcpu *vcpu)
5236 {
5237         int err;
5238
5239         err = kvm_rdpmc(vcpu);
5240         kvm_complete_insn_gp(vcpu, err);
5241
5242         return 1;
5243 }
5244
5245 static int handle_wbinvd(struct kvm_vcpu *vcpu)
5246 {
5247         skip_emulated_instruction(vcpu);
5248         kvm_emulate_wbinvd(vcpu);
5249         return 1;
5250 }
5251
5252 static int handle_xsetbv(struct kvm_vcpu *vcpu)
5253 {
5254         u64 new_bv = kvm_read_edx_eax(vcpu);
5255         u32 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
5256
5257         if (kvm_set_xcr(vcpu, index, new_bv) == 0)
5258                 skip_emulated_instruction(vcpu);
5259         return 1;
5260 }
5261
5262 static int handle_apic_access(struct kvm_vcpu *vcpu)
5263 {
5264         if (likely(fasteoi)) {
5265                 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5266                 int access_type, offset;
5267
5268                 access_type = exit_qualification & APIC_ACCESS_TYPE;
5269                 offset = exit_qualification & APIC_ACCESS_OFFSET;
5270                 /*
5271                  * Sane guest uses MOV to write EOI, with written value
5272                  * not cared. So make a short-circuit here by avoiding
5273                  * heavy instruction emulation.
5274                  */
5275                 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
5276                     (offset == APIC_EOI)) {
5277                         kvm_lapic_set_eoi(vcpu);
5278                         skip_emulated_instruction(vcpu);
5279                         return 1;
5280                 }
5281         }
5282         return emulate_instruction(vcpu, 0) == EMULATE_DONE;
5283 }
5284
5285 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
5286 {
5287         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5288         int vector = exit_qualification & 0xff;
5289
5290         /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
5291         kvm_apic_set_eoi_accelerated(vcpu, vector);
5292         return 1;
5293 }
5294
5295 static int handle_apic_write(struct kvm_vcpu *vcpu)
5296 {
5297         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5298         u32 offset = exit_qualification & 0xfff;
5299
5300         /* APIC-write VM exit is trap-like and thus no need to adjust IP */
5301         kvm_apic_write_nodecode(vcpu, offset);
5302         return 1;
5303 }
5304
5305 static int handle_task_switch(struct kvm_vcpu *vcpu)
5306 {
5307         struct vcpu_vmx *vmx = to_vmx(vcpu);
5308         unsigned long exit_qualification;
5309         bool has_error_code = false;
5310         u32 error_code = 0;
5311         u16 tss_selector;
5312         int reason, type, idt_v, idt_index;
5313
5314         idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
5315         idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
5316         type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
5317
5318         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5319
5320         reason = (u32)exit_qualification >> 30;
5321         if (reason == TASK_SWITCH_GATE && idt_v) {
5322                 switch (type) {
5323                 case INTR_TYPE_NMI_INTR:
5324                         vcpu->arch.nmi_injected = false;
5325                         vmx_set_nmi_mask(vcpu, true);
5326                         break;
5327                 case INTR_TYPE_EXT_INTR:
5328                 case INTR_TYPE_SOFT_INTR:
5329                         kvm_clear_interrupt_queue(vcpu);
5330                         break;
5331                 case INTR_TYPE_HARD_EXCEPTION:
5332                         if (vmx->idt_vectoring_info &
5333                             VECTORING_INFO_DELIVER_CODE_MASK) {
5334                                 has_error_code = true;
5335                                 error_code =
5336                                         vmcs_read32(IDT_VECTORING_ERROR_CODE);
5337                         }
5338                         /* fall through */
5339                 case INTR_TYPE_SOFT_EXCEPTION:
5340                         kvm_clear_exception_queue(vcpu);
5341                         break;
5342                 default:
5343                         break;
5344                 }
5345         }
5346         tss_selector = exit_qualification;
5347
5348         if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
5349                        type != INTR_TYPE_EXT_INTR &&
5350                        type != INTR_TYPE_NMI_INTR))
5351                 skip_emulated_instruction(vcpu);
5352
5353         if (kvm_task_switch(vcpu, tss_selector,
5354                             type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason,
5355                             has_error_code, error_code) == EMULATE_FAIL) {
5356                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5357                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5358                 vcpu->run->internal.ndata = 0;
5359                 return 0;
5360         }
5361
5362         /* clear all local breakpoint enable flags */
5363         vmcs_writel(GUEST_DR7, vmcs_readl(GUEST_DR7) & ~55);
5364
5365         /*
5366          * TODO: What about debug traps on tss switch?
5367          *       Are we supposed to inject them and update dr6?
5368          */
5369
5370         return 1;
5371 }
5372
5373 static int handle_ept_violation(struct kvm_vcpu *vcpu)
5374 {
5375         unsigned long exit_qualification;
5376         gpa_t gpa;
5377         u32 error_code;
5378         int gla_validity;
5379
5380         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5381
5382         gla_validity = (exit_qualification >> 7) & 0x3;
5383         if (gla_validity != 0x3 && gla_validity != 0x1 && gla_validity != 0) {
5384                 printk(KERN_ERR "EPT: Handling EPT violation failed!\n");
5385                 printk(KERN_ERR "EPT: GPA: 0x%lx, GVA: 0x%lx\n",
5386                         (long unsigned int)vmcs_read64(GUEST_PHYSICAL_ADDRESS),
5387                         vmcs_readl(GUEST_LINEAR_ADDRESS));
5388                 printk(KERN_ERR "EPT: Exit qualification is 0x%lx\n",
5389                         (long unsigned int)exit_qualification);
5390                 vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
5391                 vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_VIOLATION;
5392                 return 0;
5393         }
5394
5395         /*
5396          * EPT violation happened while executing iret from NMI,
5397          * "blocked by NMI" bit has to be set before next VM entry.
5398          * There are errata that may cause this bit to not be set:
5399          * AAK134, BY25.
5400          */
5401         if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5402                         cpu_has_virtual_nmis() &&
5403                         (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5404                 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
5405
5406         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5407         trace_kvm_page_fault(gpa, exit_qualification);
5408
5409         /* It is a write fault? */
5410         error_code = exit_qualification & (1U << 1);
5411         /* It is a fetch fault? */
5412         error_code |= (exit_qualification & (1U << 2)) << 2;
5413         /* ept page table is present? */
5414         error_code |= (exit_qualification >> 3) & 0x1;
5415
5416         vcpu->arch.exit_qualification = exit_qualification;
5417
5418         return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
5419 }
5420
5421 static u64 ept_rsvd_mask(u64 spte, int level)
5422 {
5423         int i;
5424         u64 mask = 0;
5425
5426         for (i = 51; i > boot_cpu_data.x86_phys_bits; i--)
5427                 mask |= (1ULL << i);
5428
5429         if (level > 2)
5430                 /* bits 7:3 reserved */
5431                 mask |= 0xf8;
5432         else if (level == 2) {
5433                 if (spte & (1ULL << 7))
5434                         /* 2MB ref, bits 20:12 reserved */
5435                         mask |= 0x1ff000;
5436                 else
5437                         /* bits 6:3 reserved */
5438                         mask |= 0x78;
5439         }
5440
5441         return mask;
5442 }
5443
5444 static void ept_misconfig_inspect_spte(struct kvm_vcpu *vcpu, u64 spte,
5445                                        int level)
5446 {
5447         printk(KERN_ERR "%s: spte 0x%llx level %d\n", __func__, spte, level);
5448
5449         /* 010b (write-only) */
5450         WARN_ON((spte & 0x7) == 0x2);
5451
5452         /* 110b (write/execute) */
5453         WARN_ON((spte & 0x7) == 0x6);
5454
5455         /* 100b (execute-only) and value not supported by logical processor */
5456         if (!cpu_has_vmx_ept_execute_only())
5457                 WARN_ON((spte & 0x7) == 0x4);
5458
5459         /* not 000b */
5460         if ((spte & 0x7)) {
5461                 u64 rsvd_bits = spte & ept_rsvd_mask(spte, level);
5462
5463                 if (rsvd_bits != 0) {
5464                         printk(KERN_ERR "%s: rsvd_bits = 0x%llx\n",
5465                                          __func__, rsvd_bits);
5466                         WARN_ON(1);
5467                 }
5468
5469                 if (level == 1 || (level == 2 && (spte & (1ULL << 7)))) {
5470                         u64 ept_mem_type = (spte & 0x38) >> 3;
5471
5472                         if (ept_mem_type == 2 || ept_mem_type == 3 ||
5473                             ept_mem_type == 7) {
5474                                 printk(KERN_ERR "%s: ept_mem_type=0x%llx\n",
5475                                                 __func__, ept_mem_type);
5476                                 WARN_ON(1);
5477                         }
5478                 }
5479         }
5480 }
5481
5482 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
5483 {
5484         u64 sptes[4];
5485         int nr_sptes, i, ret;
5486         gpa_t gpa;
5487
5488         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5489
5490         ret = handle_mmio_page_fault_common(vcpu, gpa, true);
5491         if (likely(ret == RET_MMIO_PF_EMULATE))
5492                 return x86_emulate_instruction(vcpu, gpa, 0, NULL, 0) ==
5493                                               EMULATE_DONE;
5494
5495         if (unlikely(ret == RET_MMIO_PF_INVALID))
5496                 return kvm_mmu_page_fault(vcpu, gpa, 0, NULL, 0);
5497
5498         if (unlikely(ret == RET_MMIO_PF_RETRY))
5499                 return 1;
5500
5501         /* It is the real ept misconfig */
5502         printk(KERN_ERR "EPT: Misconfiguration.\n");
5503         printk(KERN_ERR "EPT: GPA: 0x%llx\n", gpa);
5504
5505         nr_sptes = kvm_mmu_get_spte_hierarchy(vcpu, gpa, sptes);
5506
5507         for (i = PT64_ROOT_LEVEL; i > PT64_ROOT_LEVEL - nr_sptes; --i)
5508                 ept_misconfig_inspect_spte(vcpu, sptes[i-1], i);
5509
5510         vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
5511         vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_MISCONFIG;
5512
5513         return 0;
5514 }
5515
5516 static int handle_nmi_window(struct kvm_vcpu *vcpu)
5517 {
5518         u32 cpu_based_vm_exec_control;
5519
5520         /* clear pending NMI */
5521         cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5522         cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
5523         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
5524         ++vcpu->stat.nmi_window_exits;
5525         kvm_make_request(KVM_REQ_EVENT, vcpu);
5526
5527         return 1;
5528 }
5529
5530 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
5531 {
5532         struct vcpu_vmx *vmx = to_vmx(vcpu);
5533         enum emulation_result err = EMULATE_DONE;
5534         int ret = 1;
5535         u32 cpu_exec_ctrl;
5536         bool intr_window_requested;
5537         unsigned count = 130;
5538
5539         cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5540         intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
5541
5542         while (!guest_state_valid(vcpu) && count-- != 0) {
5543                 if (intr_window_requested && vmx_interrupt_allowed(vcpu))
5544                         return handle_interrupt_window(&vmx->vcpu);
5545
5546                 if (test_bit(KVM_REQ_EVENT, &vcpu->requests))
5547                         return 1;
5548
5549                 err = emulate_instruction(vcpu, EMULTYPE_NO_REEXECUTE);
5550
5551                 if (err == EMULATE_USER_EXIT) {
5552                         ++vcpu->stat.mmio_exits;
5553                         ret = 0;
5554                         goto out;
5555                 }
5556
5557                 if (err != EMULATE_DONE) {
5558                         vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5559                         vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5560                         vcpu->run->internal.ndata = 0;
5561                         return 0;
5562                 }
5563
5564                 if (vcpu->arch.halt_request) {
5565                         vcpu->arch.halt_request = 0;
5566                         ret = kvm_emulate_halt(vcpu);
5567                         goto out;
5568                 }
5569
5570                 if (signal_pending(current))
5571                         goto out;
5572                 if (need_resched())
5573                         schedule();
5574         }
5575
5576         vmx->emulation_required = emulation_required(vcpu);
5577 out:
5578         return ret;
5579 }
5580
5581 /*
5582  * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
5583  * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
5584  */
5585 static int handle_pause(struct kvm_vcpu *vcpu)
5586 {
5587         skip_emulated_instruction(vcpu);
5588         kvm_vcpu_on_spin(vcpu);
5589
5590         return 1;
5591 }
5592
5593 static int handle_invalid_op(struct kvm_vcpu *vcpu)
5594 {
5595         kvm_queue_exception(vcpu, UD_VECTOR);
5596         return 1;
5597 }
5598
5599 /*
5600  * To run an L2 guest, we need a vmcs02 based on the L1-specified vmcs12.
5601  * We could reuse a single VMCS for all the L2 guests, but we also want the
5602  * option to allocate a separate vmcs02 for each separate loaded vmcs12 - this
5603  * allows keeping them loaded on the processor, and in the future will allow
5604  * optimizations where prepare_vmcs02 doesn't need to set all the fields on
5605  * every entry if they never change.
5606  * So we keep, in vmx->nested.vmcs02_pool, a cache of size VMCS02_POOL_SIZE
5607  * (>=0) with a vmcs02 for each recently loaded vmcs12s, most recent first.
5608  *
5609  * The following functions allocate and free a vmcs02 in this pool.
5610  */
5611
5612 /* Get a VMCS from the pool to use as vmcs02 for the current vmcs12. */
5613 static struct loaded_vmcs *nested_get_current_vmcs02(struct vcpu_vmx *vmx)
5614 {
5615         struct vmcs02_list *item;
5616         list_for_each_entry(item, &vmx->nested.vmcs02_pool, list)
5617                 if (item->vmptr == vmx->nested.current_vmptr) {
5618                         list_move(&item->list, &vmx->nested.vmcs02_pool);
5619                         return &item->vmcs02;
5620                 }
5621
5622         if (vmx->nested.vmcs02_num >= max(VMCS02_POOL_SIZE, 1)) {
5623                 /* Recycle the least recently used VMCS. */
5624                 item = list_entry(vmx->nested.vmcs02_pool.prev,
5625                         struct vmcs02_list, list);
5626                 item->vmptr = vmx->nested.current_vmptr;
5627                 list_move(&item->list, &vmx->nested.vmcs02_pool);
5628                 return &item->vmcs02;
5629         }
5630
5631         /* Create a new VMCS */
5632         item = kmalloc(sizeof(struct vmcs02_list), GFP_KERNEL);
5633         if (!item)
5634                 return NULL;
5635         item->vmcs02.vmcs = alloc_vmcs();
5636         if (!item->vmcs02.vmcs) {
5637                 kfree(item);
5638                 return NULL;
5639         }
5640         loaded_vmcs_init(&item->vmcs02);
5641         item->vmptr = vmx->nested.current_vmptr;
5642         list_add(&(item->list), &(vmx->nested.vmcs02_pool));
5643         vmx->nested.vmcs02_num++;
5644         return &item->vmcs02;
5645 }
5646
5647 /* Free and remove from pool a vmcs02 saved for a vmcs12 (if there is one) */
5648 static void nested_free_vmcs02(struct vcpu_vmx *vmx, gpa_t vmptr)
5649 {
5650         struct vmcs02_list *item;
5651         list_for_each_entry(item, &vmx->nested.vmcs02_pool, list)
5652                 if (item->vmptr == vmptr) {
5653                         free_loaded_vmcs(&item->vmcs02);
5654                         list_del(&item->list);
5655                         kfree(item);
5656                         vmx->nested.vmcs02_num--;
5657                         return;
5658                 }
5659 }
5660
5661 /*
5662  * Free all VMCSs saved for this vcpu, except the one pointed by
5663  * vmx->loaded_vmcs. These include the VMCSs in vmcs02_pool (except the one
5664  * currently used, if running L2), and vmcs01 when running L2.
5665  */
5666 static void nested_free_all_saved_vmcss(struct vcpu_vmx *vmx)
5667 {
5668         struct vmcs02_list *item, *n;
5669         list_for_each_entry_safe(item, n, &vmx->nested.vmcs02_pool, list) {
5670                 if (vmx->loaded_vmcs != &item->vmcs02)
5671                         free_loaded_vmcs(&item->vmcs02);
5672                 list_del(&item->list);
5673                 kfree(item);
5674         }
5675         vmx->nested.vmcs02_num = 0;
5676
5677         if (vmx->loaded_vmcs != &vmx->vmcs01)
5678                 free_loaded_vmcs(&vmx->vmcs01);
5679 }
5680
5681 /*
5682  * The following 3 functions, nested_vmx_succeed()/failValid()/failInvalid(),
5683  * set the success or error code of an emulated VMX instruction, as specified
5684  * by Vol 2B, VMX Instruction Reference, "Conventions".
5685  */
5686 static void nested_vmx_succeed(struct kvm_vcpu *vcpu)
5687 {
5688         vmx_set_rflags(vcpu, vmx_get_rflags(vcpu)
5689                         & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
5690                             X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF));
5691 }
5692
5693 static void nested_vmx_failInvalid(struct kvm_vcpu *vcpu)
5694 {
5695         vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
5696                         & ~(X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
5697                             X86_EFLAGS_SF | X86_EFLAGS_OF))
5698                         | X86_EFLAGS_CF);
5699 }
5700
5701 static void nested_vmx_failValid(struct kvm_vcpu *vcpu,
5702                                         u32 vm_instruction_error)
5703 {
5704         if (to_vmx(vcpu)->nested.current_vmptr == -1ull) {
5705                 /*
5706                  * failValid writes the error number to the current VMCS, which
5707                  * can't be done there isn't a current VMCS.
5708                  */
5709                 nested_vmx_failInvalid(vcpu);
5710                 return;
5711         }
5712         vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
5713                         & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
5714                             X86_EFLAGS_SF | X86_EFLAGS_OF))
5715                         | X86_EFLAGS_ZF);
5716         get_vmcs12(vcpu)->vm_instruction_error = vm_instruction_error;
5717         /*
5718          * We don't need to force a shadow sync because
5719          * VM_INSTRUCTION_ERROR is not shadowed
5720          */
5721 }
5722
5723 static enum hrtimer_restart vmx_preemption_timer_fn(struct hrtimer *timer)
5724 {
5725         struct vcpu_vmx *vmx =
5726                 container_of(timer, struct vcpu_vmx, nested.preemption_timer);
5727
5728         vmx->nested.preemption_timer_expired = true;
5729         kvm_make_request(KVM_REQ_EVENT, &vmx->vcpu);
5730         kvm_vcpu_kick(&vmx->vcpu);
5731
5732         return HRTIMER_NORESTART;
5733 }
5734
5735 /*
5736  * Emulate the VMXON instruction.
5737  * Currently, we just remember that VMX is active, and do not save or even
5738  * inspect the argument to VMXON (the so-called "VMXON pointer") because we
5739  * do not currently need to store anything in that guest-allocated memory
5740  * region. Consequently, VMCLEAR and VMPTRLD also do not verify that the their
5741  * argument is different from the VMXON pointer (which the spec says they do).
5742  */
5743 static int handle_vmon(struct kvm_vcpu *vcpu)
5744 {
5745         struct kvm_segment cs;
5746         struct vcpu_vmx *vmx = to_vmx(vcpu);
5747         struct vmcs *shadow_vmcs;
5748         const u64 VMXON_NEEDED_FEATURES = FEATURE_CONTROL_LOCKED
5749                 | FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
5750
5751         /* The Intel VMX Instruction Reference lists a bunch of bits that
5752          * are prerequisite to running VMXON, most notably cr4.VMXE must be
5753          * set to 1 (see vmx_set_cr4() for when we allow the guest to set this).
5754          * Otherwise, we should fail with #UD. We test these now:
5755          */
5756         if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE) ||
5757             !kvm_read_cr0_bits(vcpu, X86_CR0_PE) ||
5758             (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
5759                 kvm_queue_exception(vcpu, UD_VECTOR);
5760                 return 1;
5761         }
5762
5763         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
5764         if (is_long_mode(vcpu) && !cs.l) {
5765                 kvm_queue_exception(vcpu, UD_VECTOR);
5766                 return 1;
5767         }
5768
5769         if (vmx_get_cpl(vcpu)) {
5770                 kvm_inject_gp(vcpu, 0);
5771                 return 1;
5772         }
5773         if (vmx->nested.vmxon) {
5774                 nested_vmx_failValid(vcpu, VMXERR_VMXON_IN_VMX_ROOT_OPERATION);
5775                 skip_emulated_instruction(vcpu);
5776                 return 1;
5777         }
5778
5779         if ((vmx->nested.msr_ia32_feature_control & VMXON_NEEDED_FEATURES)
5780                         != VMXON_NEEDED_FEATURES) {
5781                 kvm_inject_gp(vcpu, 0);
5782                 return 1;
5783         }
5784
5785         if (enable_shadow_vmcs) {
5786                 shadow_vmcs = alloc_vmcs();
5787                 if (!shadow_vmcs)
5788                         return -ENOMEM;
5789                 /* mark vmcs as shadow */
5790                 shadow_vmcs->revision_id |= (1u << 31);
5791                 /* init shadow vmcs */
5792                 vmcs_clear(shadow_vmcs);
5793                 vmx->nested.current_shadow_vmcs = shadow_vmcs;
5794         }
5795
5796         INIT_LIST_HEAD(&(vmx->nested.vmcs02_pool));
5797         vmx->nested.vmcs02_num = 0;
5798
5799         hrtimer_init(&vmx->nested.preemption_timer, CLOCK_MONOTONIC,
5800                      HRTIMER_MODE_REL);
5801         vmx->nested.preemption_timer.function = vmx_preemption_timer_fn;
5802
5803         vmx->nested.vmxon = true;
5804
5805         skip_emulated_instruction(vcpu);
5806         nested_vmx_succeed(vcpu);
5807         return 1;
5808 }
5809
5810 /*
5811  * Intel's VMX Instruction Reference specifies a common set of prerequisites
5812  * for running VMX instructions (except VMXON, whose prerequisites are
5813  * slightly different). It also specifies what exception to inject otherwise.
5814  */
5815 static int nested_vmx_check_permission(struct kvm_vcpu *vcpu)
5816 {
5817         struct kvm_segment cs;
5818         struct vcpu_vmx *vmx = to_vmx(vcpu);
5819
5820         if (!vmx->nested.vmxon) {
5821                 kvm_queue_exception(vcpu, UD_VECTOR);
5822                 return 0;
5823         }
5824
5825         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
5826         if ((vmx_get_rflags(vcpu) & X86_EFLAGS_VM) ||
5827             (is_long_mode(vcpu) && !cs.l)) {
5828                 kvm_queue_exception(vcpu, UD_VECTOR);
5829                 return 0;
5830         }
5831
5832         if (vmx_get_cpl(vcpu)) {
5833                 kvm_inject_gp(vcpu, 0);
5834                 return 0;
5835         }
5836
5837         return 1;
5838 }
5839
5840 static inline void nested_release_vmcs12(struct vcpu_vmx *vmx)
5841 {
5842         u32 exec_control;
5843         if (enable_shadow_vmcs) {
5844                 if (vmx->nested.current_vmcs12 != NULL) {
5845                         /* copy to memory all shadowed fields in case
5846                            they were modified */
5847                         copy_shadow_to_vmcs12(vmx);
5848                         vmx->nested.sync_shadow_vmcs = false;
5849                         exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
5850                         exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
5851                         vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
5852                         vmcs_write64(VMCS_LINK_POINTER, -1ull);
5853                 }
5854         }
5855         kunmap(vmx->nested.current_vmcs12_page);
5856         nested_release_page(vmx->nested.current_vmcs12_page);
5857 }
5858
5859 /*
5860  * Free whatever needs to be freed from vmx->nested when L1 goes down, or
5861  * just stops using VMX.
5862  */
5863 static void free_nested(struct vcpu_vmx *vmx)
5864 {
5865         if (!vmx->nested.vmxon)
5866                 return;
5867         vmx->nested.vmxon = false;
5868         if (vmx->nested.current_vmptr != -1ull) {
5869                 nested_release_vmcs12(vmx);
5870                 vmx->nested.current_vmptr = -1ull;
5871                 vmx->nested.current_vmcs12 = NULL;
5872         }
5873         if (enable_shadow_vmcs)
5874                 free_vmcs(vmx->nested.current_shadow_vmcs);
5875         /* Unpin physical memory we referred to in current vmcs02 */
5876         if (vmx->nested.apic_access_page) {
5877                 nested_release_page(vmx->nested.apic_access_page);
5878                 vmx->nested.apic_access_page = 0;
5879         }
5880
5881         nested_free_all_saved_vmcss(vmx);
5882 }
5883
5884 /* Emulate the VMXOFF instruction */
5885 static int handle_vmoff(struct kvm_vcpu *vcpu)
5886 {
5887         if (!nested_vmx_check_permission(vcpu))
5888                 return 1;
5889         free_nested(to_vmx(vcpu));
5890         skip_emulated_instruction(vcpu);
5891         nested_vmx_succeed(vcpu);
5892         return 1;
5893 }
5894
5895 /*
5896  * Decode the memory-address operand of a vmx instruction, as recorded on an
5897  * exit caused by such an instruction (run by a guest hypervisor).
5898  * On success, returns 0. When the operand is invalid, returns 1 and throws
5899  * #UD or #GP.
5900  */
5901 static int get_vmx_mem_address(struct kvm_vcpu *vcpu,
5902                                  unsigned long exit_qualification,
5903                                  u32 vmx_instruction_info, gva_t *ret)
5904 {
5905         /*
5906          * According to Vol. 3B, "Information for VM Exits Due to Instruction
5907          * Execution", on an exit, vmx_instruction_info holds most of the
5908          * addressing components of the operand. Only the displacement part
5909          * is put in exit_qualification (see 3B, "Basic VM-Exit Information").
5910          * For how an actual address is calculated from all these components,
5911          * refer to Vol. 1, "Operand Addressing".
5912          */
5913         int  scaling = vmx_instruction_info & 3;
5914         int  addr_size = (vmx_instruction_info >> 7) & 7;
5915         bool is_reg = vmx_instruction_info & (1u << 10);
5916         int  seg_reg = (vmx_instruction_info >> 15) & 7;
5917         int  index_reg = (vmx_instruction_info >> 18) & 0xf;
5918         bool index_is_valid = !(vmx_instruction_info & (1u << 22));
5919         int  base_reg       = (vmx_instruction_info >> 23) & 0xf;
5920         bool base_is_valid  = !(vmx_instruction_info & (1u << 27));
5921
5922         if (is_reg) {
5923                 kvm_queue_exception(vcpu, UD_VECTOR);
5924                 return 1;
5925         }
5926
5927         /* Addr = segment_base + offset */
5928         /* offset = base + [index * scale] + displacement */
5929         *ret = vmx_get_segment_base(vcpu, seg_reg);
5930         if (base_is_valid)
5931                 *ret += kvm_register_read(vcpu, base_reg);
5932         if (index_is_valid)
5933                 *ret += kvm_register_read(vcpu, index_reg)<<scaling;
5934         *ret += exit_qualification; /* holds the displacement */
5935
5936         if (addr_size == 1) /* 32 bit */
5937                 *ret &= 0xffffffff;
5938
5939         /*
5940          * TODO: throw #GP (and return 1) in various cases that the VM*
5941          * instructions require it - e.g., offset beyond segment limit,
5942          * unusable or unreadable/unwritable segment, non-canonical 64-bit
5943          * address, and so on. Currently these are not checked.
5944          */
5945         return 0;
5946 }
5947
5948 /* Emulate the VMCLEAR instruction */
5949 static int handle_vmclear(struct kvm_vcpu *vcpu)
5950 {
5951         struct vcpu_vmx *vmx = to_vmx(vcpu);
5952         gva_t gva;
5953         gpa_t vmptr;
5954         struct vmcs12 *vmcs12;
5955         struct page *page;
5956         struct x86_exception e;
5957
5958         if (!nested_vmx_check_permission(vcpu))
5959                 return 1;
5960
5961         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
5962                         vmcs_read32(VMX_INSTRUCTION_INFO), &gva))
5963                 return 1;
5964
5965         if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &vmptr,
5966                                 sizeof(vmptr), &e)) {
5967                 kvm_inject_page_fault(vcpu, &e);
5968                 return 1;
5969         }
5970
5971         if (!IS_ALIGNED(vmptr, PAGE_SIZE)) {
5972                 nested_vmx_failValid(vcpu, VMXERR_VMCLEAR_INVALID_ADDRESS);
5973                 skip_emulated_instruction(vcpu);
5974                 return 1;
5975         }
5976
5977         if (vmptr == vmx->nested.current_vmptr) {
5978                 nested_release_vmcs12(vmx);
5979                 vmx->nested.current_vmptr = -1ull;
5980                 vmx->nested.current_vmcs12 = NULL;
5981         }
5982
5983         page = nested_get_page(vcpu, vmptr);
5984         if (page == NULL) {
5985                 /*
5986                  * For accurate processor emulation, VMCLEAR beyond available
5987                  * physical memory should do nothing at all. However, it is
5988                  * possible that a nested vmx bug, not a guest hypervisor bug,
5989                  * resulted in this case, so let's shut down before doing any
5990                  * more damage:
5991                  */
5992                 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5993                 return 1;
5994         }
5995         vmcs12 = kmap(page);
5996         vmcs12->launch_state = 0;
5997         kunmap(page);
5998         nested_release_page(page);
5999
6000         nested_free_vmcs02(vmx, vmptr);
6001
6002         skip_emulated_instruction(vcpu);
6003         nested_vmx_succeed(vcpu);
6004         return 1;
6005 }
6006
6007 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch);
6008
6009 /* Emulate the VMLAUNCH instruction */
6010 static int handle_vmlaunch(struct kvm_vcpu *vcpu)
6011 {
6012         return nested_vmx_run(vcpu, true);
6013 }
6014
6015 /* Emulate the VMRESUME instruction */
6016 static int handle_vmresume(struct kvm_vcpu *vcpu)
6017 {
6018
6019         return nested_vmx_run(vcpu, false);
6020 }
6021
6022 enum vmcs_field_type {
6023         VMCS_FIELD_TYPE_U16 = 0,
6024         VMCS_FIELD_TYPE_U64 = 1,
6025         VMCS_FIELD_TYPE_U32 = 2,
6026         VMCS_FIELD_TYPE_NATURAL_WIDTH = 3
6027 };
6028
6029 static inline int vmcs_field_type(unsigned long field)
6030 {
6031         if (0x1 & field)        /* the *_HIGH fields are all 32 bit */
6032                 return VMCS_FIELD_TYPE_U32;
6033         return (field >> 13) & 0x3 ;
6034 }
6035
6036 static inline int vmcs_field_readonly(unsigned long field)
6037 {
6038         return (((field >> 10) & 0x3) == 1);
6039 }
6040
6041 /*
6042  * Read a vmcs12 field. Since these can have varying lengths and we return
6043  * one type, we chose the biggest type (u64) and zero-extend the return value
6044  * to that size. Note that the caller, handle_vmread, might need to use only
6045  * some of the bits we return here (e.g., on 32-bit guests, only 32 bits of
6046  * 64-bit fields are to be returned).
6047  */
6048 static inline bool vmcs12_read_any(struct kvm_vcpu *vcpu,
6049                                         unsigned long field, u64 *ret)
6050 {
6051         short offset = vmcs_field_to_offset(field);
6052         char *p;
6053
6054         if (offset < 0)
6055                 return 0;
6056
6057         p = ((char *)(get_vmcs12(vcpu))) + offset;
6058
6059         switch (vmcs_field_type(field)) {
6060         case VMCS_FIELD_TYPE_NATURAL_WIDTH:
6061                 *ret = *((natural_width *)p);
6062                 return 1;
6063         case VMCS_FIELD_TYPE_U16:
6064                 *ret = *((u16 *)p);
6065                 return 1;
6066         case VMCS_FIELD_TYPE_U32:
6067                 *ret = *((u32 *)p);
6068                 return 1;
6069         case VMCS_FIELD_TYPE_U64:
6070                 *ret = *((u64 *)p);
6071                 return 1;
6072         default:
6073                 return 0; /* can never happen. */
6074         }
6075 }
6076
6077
6078 static inline bool vmcs12_write_any(struct kvm_vcpu *vcpu,
6079                                     unsigned long field, u64 field_value){
6080         short offset = vmcs_field_to_offset(field);
6081         char *p = ((char *) get_vmcs12(vcpu)) + offset;
6082         if (offset < 0)
6083                 return false;
6084
6085         switch (vmcs_field_type(field)) {
6086         case VMCS_FIELD_TYPE_U16:
6087                 *(u16 *)p = field_value;
6088                 return true;
6089         case VMCS_FIELD_TYPE_U32:
6090                 *(u32 *)p = field_value;
6091                 return true;
6092         case VMCS_FIELD_TYPE_U64:
6093                 *(u64 *)p = field_value;
6094                 return true;
6095         case VMCS_FIELD_TYPE_NATURAL_WIDTH:
6096                 *(natural_width *)p = field_value;
6097                 return true;
6098         default:
6099                 return false; /* can never happen. */
6100         }
6101
6102 }
6103
6104 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx)
6105 {
6106         int i;
6107         unsigned long field;
6108         u64 field_value;
6109         struct vmcs *shadow_vmcs = vmx->nested.current_shadow_vmcs;
6110         const unsigned long *fields = shadow_read_write_fields;
6111         const int num_fields = max_shadow_read_write_fields;
6112
6113         vmcs_load(shadow_vmcs);
6114
6115         for (i = 0; i < num_fields; i++) {
6116                 field = fields[i];
6117                 switch (vmcs_field_type(field)) {
6118                 case VMCS_FIELD_TYPE_U16:
6119                         field_value = vmcs_read16(field);
6120                         break;
6121                 case VMCS_FIELD_TYPE_U32:
6122                         field_value = vmcs_read32(field);
6123                         break;
6124                 case VMCS_FIELD_TYPE_U64:
6125                         field_value = vmcs_read64(field);
6126                         break;
6127                 case VMCS_FIELD_TYPE_NATURAL_WIDTH:
6128                         field_value = vmcs_readl(field);
6129                         break;
6130                 }
6131                 vmcs12_write_any(&vmx->vcpu, field, field_value);
6132         }
6133
6134         vmcs_clear(shadow_vmcs);
6135         vmcs_load(vmx->loaded_vmcs->vmcs);
6136 }
6137
6138 static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx)
6139 {
6140         const unsigned long *fields[] = {
6141                 shadow_read_write_fields,
6142                 shadow_read_only_fields
6143         };
6144         const int max_fields[] = {
6145                 max_shadow_read_write_fields,
6146                 max_shadow_read_only_fields
6147         };
6148         int i, q;
6149         unsigned long field;
6150         u64 field_value = 0;
6151         struct vmcs *shadow_vmcs = vmx->nested.current_shadow_vmcs;
6152
6153         vmcs_load(shadow_vmcs);
6154
6155         for (q = 0; q < ARRAY_SIZE(fields); q++) {
6156                 for (i = 0; i < max_fields[q]; i++) {
6157                         field = fields[q][i];
6158                         vmcs12_read_any(&vmx->vcpu, field, &field_value);
6159
6160                         switch (vmcs_field_type(field)) {
6161                         case VMCS_FIELD_TYPE_U16:
6162                                 vmcs_write16(field, (u16)field_value);
6163                                 break;
6164                         case VMCS_FIELD_TYPE_U32:
6165                                 vmcs_write32(field, (u32)field_value);
6166                                 break;
6167                         case VMCS_FIELD_TYPE_U64:
6168                                 vmcs_write64(field, (u64)field_value);
6169                                 break;
6170                         case VMCS_FIELD_TYPE_NATURAL_WIDTH:
6171                                 vmcs_writel(field, (long)field_value);
6172                                 break;
6173                         }
6174                 }
6175         }
6176
6177         vmcs_clear(shadow_vmcs);
6178         vmcs_load(vmx->loaded_vmcs->vmcs);
6179 }
6180
6181 /*
6182  * VMX instructions which assume a current vmcs12 (i.e., that VMPTRLD was
6183  * used before) all generate the same failure when it is missing.
6184  */
6185 static int nested_vmx_check_vmcs12(struct kvm_vcpu *vcpu)
6186 {
6187         struct vcpu_vmx *vmx = to_vmx(vcpu);
6188         if (vmx->nested.current_vmptr == -1ull) {
6189                 nested_vmx_failInvalid(vcpu);
6190                 skip_emulated_instruction(vcpu);
6191                 return 0;
6192         }
6193         return 1;
6194 }
6195
6196 static int handle_vmread(struct kvm_vcpu *vcpu)
6197 {
6198         unsigned long field;
6199         u64 field_value;
6200         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6201         u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
6202         gva_t gva = 0;
6203
6204         if (!nested_vmx_check_permission(vcpu) ||
6205             !nested_vmx_check_vmcs12(vcpu))
6206                 return 1;
6207
6208         /* Decode instruction info and find the field to read */
6209         field = kvm_register_read(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
6210         /* Read the field, zero-extended to a u64 field_value */
6211         if (!vmcs12_read_any(vcpu, field, &field_value)) {
6212                 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
6213                 skip_emulated_instruction(vcpu);
6214                 return 1;
6215         }
6216         /*
6217          * Now copy part of this value to register or memory, as requested.
6218          * Note that the number of bits actually copied is 32 or 64 depending
6219          * on the guest's mode (32 or 64 bit), not on the given field's length.
6220          */
6221         if (vmx_instruction_info & (1u << 10)) {
6222                 kvm_register_write(vcpu, (((vmx_instruction_info) >> 3) & 0xf),
6223                         field_value);
6224         } else {
6225                 if (get_vmx_mem_address(vcpu, exit_qualification,
6226                                 vmx_instruction_info, &gva))
6227                         return 1;
6228                 /* _system ok, as nested_vmx_check_permission verified cpl=0 */
6229                 kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, gva,
6230                              &field_value, (is_long_mode(vcpu) ? 8 : 4), NULL);
6231         }
6232
6233         nested_vmx_succeed(vcpu);
6234         skip_emulated_instruction(vcpu);
6235         return 1;
6236 }
6237
6238
6239 static int handle_vmwrite(struct kvm_vcpu *vcpu)
6240 {
6241         unsigned long field;
6242         gva_t gva;
6243         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6244         u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
6245         /* The value to write might be 32 or 64 bits, depending on L1's long
6246          * mode, and eventually we need to write that into a field of several
6247          * possible lengths. The code below first zero-extends the value to 64
6248          * bit (field_value), and then copies only the approriate number of
6249          * bits into the vmcs12 field.
6250          */
6251         u64 field_value = 0;
6252         struct x86_exception e;
6253
6254         if (!nested_vmx_check_permission(vcpu) ||
6255             !nested_vmx_check_vmcs12(vcpu))
6256                 return 1;
6257
6258         if (vmx_instruction_info & (1u << 10))
6259                 field_value = kvm_register_read(vcpu,
6260                         (((vmx_instruction_info) >> 3) & 0xf));
6261         else {
6262                 if (get_vmx_mem_address(vcpu, exit_qualification,
6263                                 vmx_instruction_info, &gva))
6264                         return 1;
6265                 if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva,
6266                            &field_value, (is_long_mode(vcpu) ? 8 : 4), &e)) {
6267                         kvm_inject_page_fault(vcpu, &e);
6268                         return 1;
6269                 }
6270         }
6271
6272
6273         field = kvm_register_read(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
6274         if (vmcs_field_readonly(field)) {
6275                 nested_vmx_failValid(vcpu,
6276                         VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT);
6277                 skip_emulated_instruction(vcpu);
6278                 return 1;
6279         }
6280
6281         if (!vmcs12_write_any(vcpu, field, field_value)) {
6282                 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
6283                 skip_emulated_instruction(vcpu);
6284                 return 1;
6285         }
6286
6287         nested_vmx_succeed(vcpu);
6288         skip_emulated_instruction(vcpu);
6289         return 1;
6290 }
6291
6292 /* Emulate the VMPTRLD instruction */
6293 static int handle_vmptrld(struct kvm_vcpu *vcpu)
6294 {
6295         struct vcpu_vmx *vmx = to_vmx(vcpu);
6296         gva_t gva;
6297         gpa_t vmptr;
6298         struct x86_exception e;
6299         u32 exec_control;
6300
6301         if (!nested_vmx_check_permission(vcpu))
6302                 return 1;
6303
6304         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
6305                         vmcs_read32(VMX_INSTRUCTION_INFO), &gva))
6306                 return 1;
6307
6308         if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &vmptr,
6309                                 sizeof(vmptr), &e)) {
6310                 kvm_inject_page_fault(vcpu, &e);
6311                 return 1;
6312         }
6313
6314         if (!IS_ALIGNED(vmptr, PAGE_SIZE)) {
6315                 nested_vmx_failValid(vcpu, VMXERR_VMPTRLD_INVALID_ADDRESS);
6316                 skip_emulated_instruction(vcpu);
6317                 return 1;
6318         }
6319
6320         if (vmx->nested.current_vmptr != vmptr) {
6321                 struct vmcs12 *new_vmcs12;
6322                 struct page *page;
6323                 page = nested_get_page(vcpu, vmptr);
6324                 if (page == NULL) {
6325                         nested_vmx_failInvalid(vcpu);
6326                         skip_emulated_instruction(vcpu);
6327                         return 1;
6328                 }
6329                 new_vmcs12 = kmap(page);
6330                 if (new_vmcs12->revision_id != VMCS12_REVISION) {
6331                         kunmap(page);
6332                         nested_release_page_clean(page);
6333                         nested_vmx_failValid(vcpu,
6334                                 VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
6335                         skip_emulated_instruction(vcpu);
6336                         return 1;
6337                 }
6338                 if (vmx->nested.current_vmptr != -1ull)
6339                         nested_release_vmcs12(vmx);
6340
6341                 vmx->nested.current_vmptr = vmptr;
6342                 vmx->nested.current_vmcs12 = new_vmcs12;
6343                 vmx->nested.current_vmcs12_page = page;
6344                 if (enable_shadow_vmcs) {
6345                         exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
6346                         exec_control |= SECONDARY_EXEC_SHADOW_VMCS;
6347                         vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
6348                         vmcs_write64(VMCS_LINK_POINTER,
6349                                      __pa(vmx->nested.current_shadow_vmcs));
6350                         vmx->nested.sync_shadow_vmcs = true;
6351                 }
6352         }
6353
6354         nested_vmx_succeed(vcpu);
6355         skip_emulated_instruction(vcpu);
6356         return 1;
6357 }
6358
6359 /* Emulate the VMPTRST instruction */
6360 static int handle_vmptrst(struct kvm_vcpu *vcpu)
6361 {
6362         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6363         u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
6364         gva_t vmcs_gva;
6365         struct x86_exception e;
6366
6367         if (!nested_vmx_check_permission(vcpu))
6368                 return 1;
6369
6370         if (get_vmx_mem_address(vcpu, exit_qualification,
6371                         vmx_instruction_info, &vmcs_gva))
6372                 return 1;
6373         /* ok to use *_system, as nested_vmx_check_permission verified cpl=0 */
6374         if (kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, vmcs_gva,
6375                                  (void *)&to_vmx(vcpu)->nested.current_vmptr,
6376                                  sizeof(u64), &e)) {
6377                 kvm_inject_page_fault(vcpu, &e);
6378                 return 1;
6379         }
6380         nested_vmx_succeed(vcpu);
6381         skip_emulated_instruction(vcpu);
6382         return 1;
6383 }
6384
6385 /* Emulate the INVEPT instruction */
6386 static int handle_invept(struct kvm_vcpu *vcpu)
6387 {
6388         u32 vmx_instruction_info, types;
6389         unsigned long type;
6390         gva_t gva;
6391         struct x86_exception e;
6392         struct {
6393                 u64 eptp, gpa;
6394         } operand;
6395         u64 eptp_mask = ((1ull << 51) - 1) & PAGE_MASK;
6396
6397         if (!(nested_vmx_secondary_ctls_high & SECONDARY_EXEC_ENABLE_EPT) ||
6398             !(nested_vmx_ept_caps & VMX_EPT_INVEPT_BIT)) {
6399                 kvm_queue_exception(vcpu, UD_VECTOR);
6400                 return 1;
6401         }
6402
6403         if (!nested_vmx_check_permission(vcpu))
6404                 return 1;
6405
6406         if (!kvm_read_cr0_bits(vcpu, X86_CR0_PE)) {
6407                 kvm_queue_exception(vcpu, UD_VECTOR);
6408                 return 1;
6409         }
6410
6411         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
6412         type = kvm_register_read(vcpu, (vmx_instruction_info >> 28) & 0xf);
6413
6414         types = (nested_vmx_ept_caps >> VMX_EPT_EXTENT_SHIFT) & 6;
6415
6416         if (!(types & (1UL << type))) {
6417                 nested_vmx_failValid(vcpu,
6418                                 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
6419                 return 1;
6420         }
6421
6422         /* According to the Intel VMX instruction reference, the memory
6423          * operand is read even if it isn't needed (e.g., for type==global)
6424          */
6425         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
6426                         vmx_instruction_info, &gva))
6427                 return 1;
6428         if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &operand,
6429                                 sizeof(operand), &e)) {
6430                 kvm_inject_page_fault(vcpu, &e);
6431                 return 1;
6432         }
6433
6434         switch (type) {
6435         case VMX_EPT_EXTENT_CONTEXT:
6436                 if ((operand.eptp & eptp_mask) !=
6437                                 (nested_ept_get_cr3(vcpu) & eptp_mask))
6438                         break;
6439         case VMX_EPT_EXTENT_GLOBAL:
6440                 kvm_mmu_sync_roots(vcpu);
6441                 kvm_mmu_flush_tlb(vcpu);
6442                 nested_vmx_succeed(vcpu);
6443                 break;
6444         default:
6445                 BUG_ON(1);
6446                 break;
6447         }
6448
6449         skip_emulated_instruction(vcpu);
6450         return 1;
6451 }
6452
6453 /*
6454  * The exit handlers return 1 if the exit was handled fully and guest execution
6455  * may resume.  Otherwise they set the kvm_run parameter to indicate what needs
6456  * to be done to userspace and return 0.
6457  */
6458 static int (*const kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
6459         [EXIT_REASON_EXCEPTION_NMI]           = handle_exception,
6460         [EXIT_REASON_EXTERNAL_INTERRUPT]      = handle_external_interrupt,
6461         [EXIT_REASON_TRIPLE_FAULT]            = handle_triple_fault,
6462         [EXIT_REASON_NMI_WINDOW]              = handle_nmi_window,
6463         [EXIT_REASON_IO_INSTRUCTION]          = handle_io,
6464         [EXIT_REASON_CR_ACCESS]               = handle_cr,
6465         [EXIT_REASON_DR_ACCESS]               = handle_dr,
6466         [EXIT_REASON_CPUID]                   = handle_cpuid,
6467         [EXIT_REASON_MSR_READ]                = handle_rdmsr,
6468         [EXIT_REASON_MSR_WRITE]               = handle_wrmsr,
6469         [EXIT_REASON_PENDING_INTERRUPT]       = handle_interrupt_window,
6470         [EXIT_REASON_HLT]                     = handle_halt,
6471         [EXIT_REASON_INVD]                    = handle_invd,
6472         [EXIT_REASON_INVLPG]                  = handle_invlpg,
6473         [EXIT_REASON_RDPMC]                   = handle_rdpmc,
6474         [EXIT_REASON_VMCALL]                  = handle_vmcall,
6475         [EXIT_REASON_VMCLEAR]                 = handle_vmclear,
6476         [EXIT_REASON_VMLAUNCH]                = handle_vmlaunch,
6477         [EXIT_REASON_VMPTRLD]                 = handle_vmptrld,
6478         [EXIT_REASON_VMPTRST]                 = handle_vmptrst,
6479         [EXIT_REASON_VMREAD]                  = handle_vmread,
6480         [EXIT_REASON_VMRESUME]                = handle_vmresume,
6481         [EXIT_REASON_VMWRITE]                 = handle_vmwrite,
6482         [EXIT_REASON_VMOFF]                   = handle_vmoff,
6483         [EXIT_REASON_VMON]                    = handle_vmon,
6484         [EXIT_REASON_TPR_BELOW_THRESHOLD]     = handle_tpr_below_threshold,
6485         [EXIT_REASON_APIC_ACCESS]             = handle_apic_access,
6486         [EXIT_REASON_APIC_WRITE]              = handle_apic_write,
6487         [EXIT_REASON_EOI_INDUCED]             = handle_apic_eoi_induced,
6488         [EXIT_REASON_WBINVD]                  = handle_wbinvd,
6489         [EXIT_REASON_XSETBV]                  = handle_xsetbv,
6490         [EXIT_REASON_TASK_SWITCH]             = handle_task_switch,
6491         [EXIT_REASON_MCE_DURING_VMENTRY]      = handle_machine_check,
6492         [EXIT_REASON_EPT_VIOLATION]           = handle_ept_violation,
6493         [EXIT_REASON_EPT_MISCONFIG]           = handle_ept_misconfig,
6494         [EXIT_REASON_PAUSE_INSTRUCTION]       = handle_pause,
6495         [EXIT_REASON_MWAIT_INSTRUCTION]       = handle_invalid_op,
6496         [EXIT_REASON_MONITOR_INSTRUCTION]     = handle_invalid_op,
6497         [EXIT_REASON_INVEPT]                  = handle_invept,
6498 };
6499
6500 static const int kvm_vmx_max_exit_handlers =
6501         ARRAY_SIZE(kvm_vmx_exit_handlers);
6502
6503 static bool nested_vmx_exit_handled_io(struct kvm_vcpu *vcpu,
6504                                        struct vmcs12 *vmcs12)
6505 {
6506         unsigned long exit_qualification;
6507         gpa_t bitmap, last_bitmap;
6508         unsigned int port;
6509         int size;
6510         u8 b;
6511
6512         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
6513                 return nested_cpu_has(vmcs12, CPU_BASED_UNCOND_IO_EXITING);
6514
6515         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6516
6517         port = exit_qualification >> 16;
6518         size = (exit_qualification & 7) + 1;
6519
6520         last_bitmap = (gpa_t)-1;
6521         b = -1;
6522
6523         while (size > 0) {
6524                 if (port < 0x8000)
6525                         bitmap = vmcs12->io_bitmap_a;
6526                 else if (port < 0x10000)
6527                         bitmap = vmcs12->io_bitmap_b;
6528                 else
6529                         return 1;
6530                 bitmap += (port & 0x7fff) / 8;
6531
6532                 if (last_bitmap != bitmap)
6533                         if (kvm_read_guest(vcpu->kvm, bitmap, &b, 1))
6534                                 return 1;
6535                 if (b & (1 << (port & 7)))
6536                         return 1;
6537
6538                 port++;
6539                 size--;
6540                 last_bitmap = bitmap;
6541         }
6542
6543         return 0;
6544 }
6545
6546 /*
6547  * Return 1 if we should exit from L2 to L1 to handle an MSR access access,
6548  * rather than handle it ourselves in L0. I.e., check whether L1 expressed
6549  * disinterest in the current event (read or write a specific MSR) by using an
6550  * MSR bitmap. This may be the case even when L0 doesn't use MSR bitmaps.
6551  */
6552 static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu,
6553         struct vmcs12 *vmcs12, u32 exit_reason)
6554 {
6555         u32 msr_index = vcpu->arch.regs[VCPU_REGS_RCX];
6556         gpa_t bitmap;
6557
6558         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
6559                 return 1;
6560
6561         /*
6562          * The MSR_BITMAP page is divided into four 1024-byte bitmaps,
6563          * for the four combinations of read/write and low/high MSR numbers.
6564          * First we need to figure out which of the four to use:
6565          */
6566         bitmap = vmcs12->msr_bitmap;
6567         if (exit_reason == EXIT_REASON_MSR_WRITE)
6568                 bitmap += 2048;
6569         if (msr_index >= 0xc0000000) {
6570                 msr_index -= 0xc0000000;
6571                 bitmap += 1024;
6572         }
6573
6574         /* Then read the msr_index'th bit from this bitmap: */
6575         if (msr_index < 1024*8) {
6576                 unsigned char b;
6577                 if (kvm_read_guest(vcpu->kvm, bitmap + msr_index/8, &b, 1))
6578                         return 1;
6579                 return 1 & (b >> (msr_index & 7));
6580         } else
6581                 return 1; /* let L1 handle the wrong parameter */
6582 }
6583
6584 /*
6585  * Return 1 if we should exit from L2 to L1 to handle a CR access exit,
6586  * rather than handle it ourselves in L0. I.e., check if L1 wanted to
6587  * intercept (via guest_host_mask etc.) the current event.
6588  */
6589 static bool nested_vmx_exit_handled_cr(struct kvm_vcpu *vcpu,
6590         struct vmcs12 *vmcs12)
6591 {
6592         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6593         int cr = exit_qualification & 15;
6594         int reg = (exit_qualification >> 8) & 15;
6595         unsigned long val = kvm_register_read(vcpu, reg);
6596
6597         switch ((exit_qualification >> 4) & 3) {
6598         case 0: /* mov to cr */
6599                 switch (cr) {
6600                 case 0:
6601                         if (vmcs12->cr0_guest_host_mask &
6602                             (val ^ vmcs12->cr0_read_shadow))
6603                                 return 1;
6604                         break;
6605                 case 3:
6606                         if ((vmcs12->cr3_target_count >= 1 &&
6607                                         vmcs12->cr3_target_value0 == val) ||
6608                                 (vmcs12->cr3_target_count >= 2 &&
6609                                         vmcs12->cr3_target_value1 == val) ||
6610                                 (vmcs12->cr3_target_count >= 3 &&
6611                                         vmcs12->cr3_target_value2 == val) ||
6612                                 (vmcs12->cr3_target_count >= 4 &&
6613                                         vmcs12->cr3_target_value3 == val))
6614                                 return 0;
6615                         if (nested_cpu_has(vmcs12, CPU_BASED_CR3_LOAD_EXITING))
6616                                 return 1;
6617                         break;
6618                 case 4:
6619                         if (vmcs12->cr4_guest_host_mask &
6620                             (vmcs12->cr4_read_shadow ^ val))
6621                                 return 1;
6622                         break;
6623                 case 8:
6624                         if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING))
6625                                 return 1;
6626                         break;
6627                 }
6628                 break;
6629         case 2: /* clts */
6630                 if ((vmcs12->cr0_guest_host_mask & X86_CR0_TS) &&
6631                     (vmcs12->cr0_read_shadow & X86_CR0_TS))
6632                         return 1;
6633                 break;
6634         case 1: /* mov from cr */
6635                 switch (cr) {
6636                 case 3:
6637                         if (vmcs12->cpu_based_vm_exec_control &
6638                             CPU_BASED_CR3_STORE_EXITING)
6639                                 return 1;
6640                         break;
6641                 case 8:
6642                         if (vmcs12->cpu_based_vm_exec_control &
6643                             CPU_BASED_CR8_STORE_EXITING)
6644                                 return 1;
6645                         break;
6646                 }
6647                 break;
6648         case 3: /* lmsw */
6649                 /*
6650                  * lmsw can change bits 1..3 of cr0, and only set bit 0 of
6651                  * cr0. Other attempted changes are ignored, with no exit.
6652                  */
6653                 if (vmcs12->cr0_guest_host_mask & 0xe &
6654                     (val ^ vmcs12->cr0_read_shadow))
6655                         return 1;
6656                 if ((vmcs12->cr0_guest_host_mask & 0x1) &&
6657                     !(vmcs12->cr0_read_shadow & 0x1) &&
6658                     (val & 0x1))
6659                         return 1;
6660                 break;
6661         }
6662         return 0;
6663 }
6664
6665 /*
6666  * Return 1 if we should exit from L2 to L1 to handle an exit, or 0 if we
6667  * should handle it ourselves in L0 (and then continue L2). Only call this
6668  * when in is_guest_mode (L2).
6669  */
6670 static bool nested_vmx_exit_handled(struct kvm_vcpu *vcpu)
6671 {
6672         u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
6673         struct vcpu_vmx *vmx = to_vmx(vcpu);
6674         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6675         u32 exit_reason = vmx->exit_reason;
6676
6677         trace_kvm_nested_vmexit(kvm_rip_read(vcpu), exit_reason,
6678                                 vmcs_readl(EXIT_QUALIFICATION),
6679                                 vmx->idt_vectoring_info,
6680                                 intr_info,
6681                                 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
6682                                 KVM_ISA_VMX);
6683
6684         if (vmx->nested.nested_run_pending)
6685                 return 0;
6686
6687         if (unlikely(vmx->fail)) {
6688                 pr_info_ratelimited("%s failed vm entry %x\n", __func__,
6689                                     vmcs_read32(VM_INSTRUCTION_ERROR));
6690                 return 1;
6691         }
6692
6693         switch (exit_reason) {
6694         case EXIT_REASON_EXCEPTION_NMI:
6695                 if (!is_exception(intr_info))
6696                         return 0;
6697                 else if (is_page_fault(intr_info))
6698                         return enable_ept;
6699                 else if (is_no_device(intr_info) &&
6700                          !(vmcs12->guest_cr0 & X86_CR0_TS))
6701                         return 0;
6702                 return vmcs12->exception_bitmap &
6703                                 (1u << (intr_info & INTR_INFO_VECTOR_MASK));
6704         case EXIT_REASON_EXTERNAL_INTERRUPT:
6705                 return 0;
6706         case EXIT_REASON_TRIPLE_FAULT:
6707                 return 1;
6708         case EXIT_REASON_PENDING_INTERRUPT:
6709                 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_INTR_PENDING);
6710         case EXIT_REASON_NMI_WINDOW:
6711                 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING);
6712         case EXIT_REASON_TASK_SWITCH:
6713                 return 1;
6714         case EXIT_REASON_CPUID:
6715                 return 1;
6716         case EXIT_REASON_HLT:
6717                 return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
6718         case EXIT_REASON_INVD:
6719                 return 1;
6720         case EXIT_REASON_INVLPG:
6721                 return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
6722         case EXIT_REASON_RDPMC:
6723                 return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
6724         case EXIT_REASON_RDTSC:
6725                 return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
6726         case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
6727         case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
6728         case EXIT_REASON_VMPTRST: case EXIT_REASON_VMREAD:
6729         case EXIT_REASON_VMRESUME: case EXIT_REASON_VMWRITE:
6730         case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
6731         case EXIT_REASON_INVEPT:
6732                 /*
6733                  * VMX instructions trap unconditionally. This allows L1 to
6734                  * emulate them for its L2 guest, i.e., allows 3-level nesting!
6735                  */
6736                 return 1;
6737         case EXIT_REASON_CR_ACCESS:
6738                 return nested_vmx_exit_handled_cr(vcpu, vmcs12);
6739         case EXIT_REASON_DR_ACCESS:
6740                 return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
6741         case EXIT_REASON_IO_INSTRUCTION:
6742                 return nested_vmx_exit_handled_io(vcpu, vmcs12);
6743         case EXIT_REASON_MSR_READ:
6744         case EXIT_REASON_MSR_WRITE:
6745                 return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
6746         case EXIT_REASON_INVALID_STATE:
6747                 return 1;
6748         case EXIT_REASON_MWAIT_INSTRUCTION:
6749                 return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
6750         case EXIT_REASON_MONITOR_INSTRUCTION:
6751                 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
6752         case EXIT_REASON_PAUSE_INSTRUCTION:
6753                 return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
6754                         nested_cpu_has2(vmcs12,
6755                                 SECONDARY_EXEC_PAUSE_LOOP_EXITING);
6756         case EXIT_REASON_MCE_DURING_VMENTRY:
6757                 return 0;
6758         case EXIT_REASON_TPR_BELOW_THRESHOLD:
6759                 return 1;
6760         case EXIT_REASON_APIC_ACCESS:
6761                 return nested_cpu_has2(vmcs12,
6762                         SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
6763         case EXIT_REASON_EPT_VIOLATION:
6764                 /*
6765                  * L0 always deals with the EPT violation. If nested EPT is
6766                  * used, and the nested mmu code discovers that the address is
6767                  * missing in the guest EPT table (EPT12), the EPT violation
6768                  * will be injected with nested_ept_inject_page_fault()
6769                  */
6770                 return 0;
6771         case EXIT_REASON_EPT_MISCONFIG:
6772                 /*
6773                  * L2 never uses directly L1's EPT, but rather L0's own EPT
6774                  * table (shadow on EPT) or a merged EPT table that L0 built
6775                  * (EPT on EPT). So any problems with the structure of the
6776                  * table is L0's fault.
6777                  */
6778                 return 0;
6779         case EXIT_REASON_WBINVD:
6780                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
6781         case EXIT_REASON_XSETBV:
6782                 return 1;
6783         default:
6784                 return 1;
6785         }
6786 }
6787
6788 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
6789 {
6790         *info1 = vmcs_readl(EXIT_QUALIFICATION);
6791         *info2 = vmcs_read32(VM_EXIT_INTR_INFO);
6792 }
6793
6794 /*
6795  * The guest has exited.  See if we can fix it or if we need userspace
6796  * assistance.
6797  */
6798 static int vmx_handle_exit(struct kvm_vcpu *vcpu)
6799 {
6800         struct vcpu_vmx *vmx = to_vmx(vcpu);
6801         u32 exit_reason = vmx->exit_reason;
6802         u32 vectoring_info = vmx->idt_vectoring_info;
6803
6804         /* If guest state is invalid, start emulating */
6805         if (vmx->emulation_required)
6806                 return handle_invalid_guest_state(vcpu);
6807
6808         if (is_guest_mode(vcpu) && nested_vmx_exit_handled(vcpu)) {
6809                 nested_vmx_vmexit(vcpu, exit_reason,
6810                                   vmcs_read32(VM_EXIT_INTR_INFO),
6811                                   vmcs_readl(EXIT_QUALIFICATION));
6812                 return 1;
6813         }
6814
6815         if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
6816                 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6817                 vcpu->run->fail_entry.hardware_entry_failure_reason
6818                         = exit_reason;
6819                 return 0;
6820         }
6821
6822         if (unlikely(vmx->fail)) {
6823                 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6824                 vcpu->run->fail_entry.hardware_entry_failure_reason
6825                         = vmcs_read32(VM_INSTRUCTION_ERROR);
6826                 return 0;
6827         }
6828
6829         /*
6830          * Note:
6831          * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
6832          * delivery event since it indicates guest is accessing MMIO.
6833          * The vm-exit can be triggered again after return to guest that
6834          * will cause infinite loop.
6835          */
6836         if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
6837                         (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
6838                         exit_reason != EXIT_REASON_EPT_VIOLATION &&
6839                         exit_reason != EXIT_REASON_TASK_SWITCH)) {
6840                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6841                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
6842                 vcpu->run->internal.ndata = 2;
6843                 vcpu->run->internal.data[0] = vectoring_info;
6844                 vcpu->run->internal.data[1] = exit_reason;
6845                 return 0;
6846         }
6847
6848         if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked &&
6849             !(is_guest_mode(vcpu) && nested_cpu_has_virtual_nmis(
6850                                         get_vmcs12(vcpu))))) {
6851                 if (vmx_interrupt_allowed(vcpu)) {
6852                         vmx->soft_vnmi_blocked = 0;
6853                 } else if (vmx->vnmi_blocked_time > 1000000000LL &&
6854                            vcpu->arch.nmi_pending) {
6855                         /*
6856                          * This CPU don't support us in finding the end of an
6857                          * NMI-blocked window if the guest runs with IRQs
6858                          * disabled. So we pull the trigger after 1 s of
6859                          * futile waiting, but inform the user about this.
6860                          */
6861                         printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
6862                                "state on VCPU %d after 1 s timeout\n",
6863                                __func__, vcpu->vcpu_id);
6864                         vmx->soft_vnmi_blocked = 0;
6865                 }
6866         }
6867
6868         if (exit_reason < kvm_vmx_max_exit_handlers
6869             && kvm_vmx_exit_handlers[exit_reason])
6870                 return kvm_vmx_exit_handlers[exit_reason](vcpu);
6871         else {
6872                 vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
6873                 vcpu->run->hw.hardware_exit_reason = exit_reason;
6874         }
6875         return 0;
6876 }
6877
6878 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
6879 {
6880         if (irr == -1 || tpr < irr) {
6881                 vmcs_write32(TPR_THRESHOLD, 0);
6882                 return;
6883         }
6884
6885         vmcs_write32(TPR_THRESHOLD, irr);
6886 }
6887
6888 static void vmx_set_virtual_x2apic_mode(struct kvm_vcpu *vcpu, bool set)
6889 {
6890         u32 sec_exec_control;
6891
6892         /*
6893          * There is not point to enable virtualize x2apic without enable
6894          * apicv
6895          */
6896         if (!cpu_has_vmx_virtualize_x2apic_mode() ||
6897                                 !vmx_vm_has_apicv(vcpu->kvm))
6898                 return;
6899
6900         if (!vm_need_tpr_shadow(vcpu->kvm))
6901                 return;
6902
6903         sec_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
6904
6905         if (set) {
6906                 sec_exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6907                 sec_exec_control |= SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6908         } else {
6909                 sec_exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6910                 sec_exec_control |= SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6911         }
6912         vmcs_write32(SECONDARY_VM_EXEC_CONTROL, sec_exec_control);
6913
6914         vmx_set_msr_bitmap(vcpu);
6915 }
6916
6917 static void vmx_hwapic_isr_update(struct kvm *kvm, int isr)
6918 {
6919         u16 status;
6920         u8 old;
6921
6922         if (!vmx_vm_has_apicv(kvm))
6923                 return;
6924
6925         if (isr == -1)
6926                 isr = 0;
6927
6928         status = vmcs_read16(GUEST_INTR_STATUS);
6929         old = status >> 8;
6930         if (isr != old) {
6931                 status &= 0xff;
6932                 status |= isr << 8;
6933                 vmcs_write16(GUEST_INTR_STATUS, status);
6934         }
6935 }
6936
6937 static void vmx_set_rvi(int vector)
6938 {
6939         u16 status;
6940         u8 old;
6941
6942         status = vmcs_read16(GUEST_INTR_STATUS);
6943         old = (u8)status & 0xff;
6944         if ((u8)vector != old) {
6945                 status &= ~0xff;
6946                 status |= (u8)vector;
6947                 vmcs_write16(GUEST_INTR_STATUS, status);
6948         }
6949 }
6950
6951 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
6952 {
6953         if (max_irr == -1)
6954                 return;
6955
6956         vmx_set_rvi(max_irr);
6957 }
6958
6959 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
6960 {
6961         if (!vmx_vm_has_apicv(vcpu->kvm))
6962                 return;
6963
6964         vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
6965         vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
6966         vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
6967         vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
6968 }
6969
6970 static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
6971 {
6972         u32 exit_intr_info;
6973
6974         if (!(vmx->exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
6975               || vmx->exit_reason == EXIT_REASON_EXCEPTION_NMI))
6976                 return;
6977
6978         vmx->exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
6979         exit_intr_info = vmx->exit_intr_info;
6980
6981         /* Handle machine checks before interrupts are enabled */
6982         if (is_machine_check(exit_intr_info))
6983                 kvm_machine_check();
6984
6985         /* We need to handle NMIs before interrupts are enabled */
6986         if ((exit_intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR &&
6987             (exit_intr_info & INTR_INFO_VALID_MASK)) {
6988                 kvm_before_handle_nmi(&vmx->vcpu);
6989                 asm("int $2");
6990                 kvm_after_handle_nmi(&vmx->vcpu);
6991         }
6992 }
6993
6994 static void vmx_handle_external_intr(struct kvm_vcpu *vcpu)
6995 {
6996         u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
6997
6998         /*
6999          * If external interrupt exists, IF bit is set in rflags/eflags on the
7000          * interrupt stack frame, and interrupt will be enabled on a return
7001          * from interrupt handler.
7002          */
7003         if ((exit_intr_info & (INTR_INFO_VALID_MASK | INTR_INFO_INTR_TYPE_MASK))
7004                         == (INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR)) {
7005                 unsigned int vector;
7006                 unsigned long entry;
7007                 gate_desc *desc;
7008                 struct vcpu_vmx *vmx = to_vmx(vcpu);
7009 #ifdef CONFIG_X86_64
7010                 unsigned long tmp;
7011 #endif
7012
7013                 vector =  exit_intr_info & INTR_INFO_VECTOR_MASK;
7014                 desc = (gate_desc *)vmx->host_idt_base + vector;
7015                 entry = gate_offset(*desc);
7016                 asm volatile(
7017 #ifdef CONFIG_X86_64
7018                         "mov %%" _ASM_SP ", %[sp]\n\t"
7019                         "and $0xfffffffffffffff0, %%" _ASM_SP "\n\t"
7020                         "push $%c[ss]\n\t"
7021                         "push %[sp]\n\t"
7022 #endif
7023                         "pushf\n\t"
7024                         "orl $0x200, (%%" _ASM_SP ")\n\t"
7025                         __ASM_SIZE(push) " $%c[cs]\n\t"
7026                         "call *%[entry]\n\t"
7027                         :
7028 #ifdef CONFIG_X86_64
7029                         [sp]"=&r"(tmp)
7030 #endif
7031                         :
7032                         [entry]"r"(entry),
7033                         [ss]"i"(__KERNEL_DS),
7034                         [cs]"i"(__KERNEL_CS)
7035                         );
7036         } else
7037                 local_irq_enable();
7038 }
7039
7040 static bool vmx_mpx_supported(void)
7041 {
7042         return (vmcs_config.vmexit_ctrl & VM_EXIT_CLEAR_BNDCFGS) &&
7043                 (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_BNDCFGS);
7044 }
7045
7046 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
7047 {
7048         u32 exit_intr_info;
7049         bool unblock_nmi;
7050         u8 vector;
7051         bool idtv_info_valid;
7052
7053         idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
7054
7055         if (cpu_has_virtual_nmis()) {
7056                 if (vmx->nmi_known_unmasked)
7057                         return;
7058                 /*
7059                  * Can't use vmx->exit_intr_info since we're not sure what
7060                  * the exit reason is.
7061                  */
7062                 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
7063                 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
7064                 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
7065                 /*
7066                  * SDM 3: 27.7.1.2 (September 2008)
7067                  * Re-set bit "block by NMI" before VM entry if vmexit caused by
7068                  * a guest IRET fault.
7069                  * SDM 3: 23.2.2 (September 2008)
7070                  * Bit 12 is undefined in any of the following cases:
7071                  *  If the VM exit sets the valid bit in the IDT-vectoring
7072                  *   information field.
7073                  *  If the VM exit is due to a double fault.
7074                  */
7075                 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
7076                     vector != DF_VECTOR && !idtv_info_valid)
7077                         vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
7078                                       GUEST_INTR_STATE_NMI);
7079                 else
7080                         vmx->nmi_known_unmasked =
7081                                 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
7082                                   & GUEST_INTR_STATE_NMI);
7083         } else if (unlikely(vmx->soft_vnmi_blocked))
7084                 vmx->vnmi_blocked_time +=
7085                         ktime_to_ns(ktime_sub(ktime_get(), vmx->entry_time));
7086 }
7087
7088 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
7089                                       u32 idt_vectoring_info,
7090                                       int instr_len_field,
7091                                       int error_code_field)
7092 {
7093         u8 vector;
7094         int type;
7095         bool idtv_info_valid;
7096
7097         idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
7098
7099         vcpu->arch.nmi_injected = false;
7100         kvm_clear_exception_queue(vcpu);
7101         kvm_clear_interrupt_queue(vcpu);
7102
7103         if (!idtv_info_valid)
7104                 return;
7105
7106         kvm_make_request(KVM_REQ_EVENT, vcpu);
7107
7108         vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
7109         type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
7110
7111         switch (type) {
7112         case INTR_TYPE_NMI_INTR:
7113                 vcpu->arch.nmi_injected = true;
7114                 /*
7115                  * SDM 3: 27.7.1.2 (September 2008)
7116                  * Clear bit "block by NMI" before VM entry if a NMI
7117                  * delivery faulted.
7118                  */
7119                 vmx_set_nmi_mask(vcpu, false);
7120                 break;
7121         case INTR_TYPE_SOFT_EXCEPTION:
7122                 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
7123                 /* fall through */
7124         case INTR_TYPE_HARD_EXCEPTION:
7125                 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
7126                         u32 err = vmcs_read32(error_code_field);
7127                         kvm_requeue_exception_e(vcpu, vector, err);
7128                 } else
7129                         kvm_requeue_exception(vcpu, vector);
7130                 break;
7131         case INTR_TYPE_SOFT_INTR:
7132                 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
7133                 /* fall through */
7134         case INTR_TYPE_EXT_INTR:
7135                 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
7136                 break;
7137         default:
7138                 break;
7139         }
7140 }
7141
7142 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
7143 {
7144         __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
7145                                   VM_EXIT_INSTRUCTION_LEN,
7146                                   IDT_VECTORING_ERROR_CODE);
7147 }
7148
7149 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
7150 {
7151         __vmx_complete_interrupts(vcpu,
7152                                   vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
7153                                   VM_ENTRY_INSTRUCTION_LEN,
7154                                   VM_ENTRY_EXCEPTION_ERROR_CODE);
7155
7156         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
7157 }
7158
7159 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
7160 {
7161         int i, nr_msrs;
7162         struct perf_guest_switch_msr *msrs;
7163
7164         msrs = perf_guest_get_msrs(&nr_msrs);
7165
7166         if (!msrs)
7167                 return;
7168
7169         for (i = 0; i < nr_msrs; i++)
7170                 if (msrs[i].host == msrs[i].guest)
7171                         clear_atomic_switch_msr(vmx, msrs[i].msr);
7172                 else
7173                         add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
7174                                         msrs[i].host);
7175 }
7176
7177 static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
7178 {
7179         struct vcpu_vmx *vmx = to_vmx(vcpu);
7180         unsigned long debugctlmsr;
7181
7182         /* Record the guest's net vcpu time for enforced NMI injections. */
7183         if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked))
7184                 vmx->entry_time = ktime_get();
7185
7186         /* Don't enter VMX if guest state is invalid, let the exit handler
7187            start emulation until we arrive back to a valid state */
7188         if (vmx->emulation_required)
7189                 return;
7190
7191         if (vmx->nested.sync_shadow_vmcs) {
7192                 copy_vmcs12_to_shadow(vmx);
7193                 vmx->nested.sync_shadow_vmcs = false;
7194         }
7195
7196         if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
7197                 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
7198         if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
7199                 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
7200
7201         /* When single-stepping over STI and MOV SS, we must clear the
7202          * corresponding interruptibility bits in the guest state. Otherwise
7203          * vmentry fails as it then expects bit 14 (BS) in pending debug
7204          * exceptions being set, but that's not correct for the guest debugging
7205          * case. */
7206         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
7207                 vmx_set_interrupt_shadow(vcpu, 0);
7208
7209         atomic_switch_perf_msrs(vmx);
7210         debugctlmsr = get_debugctlmsr();
7211
7212         vmx->__launched = vmx->loaded_vmcs->launched;
7213         asm(
7214                 /* Store host registers */
7215                 "push %%" _ASM_DX "; push %%" _ASM_BP ";"
7216                 "push %%" _ASM_CX " \n\t" /* placeholder for guest rcx */
7217                 "push %%" _ASM_CX " \n\t"
7218                 "cmp %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
7219                 "je 1f \n\t"
7220                 "mov %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
7221                 __ex(ASM_VMX_VMWRITE_RSP_RDX) "\n\t"
7222                 "1: \n\t"
7223                 /* Reload cr2 if changed */
7224                 "mov %c[cr2](%0), %%" _ASM_AX " \n\t"
7225                 "mov %%cr2, %%" _ASM_DX " \n\t"
7226                 "cmp %%" _ASM_AX ", %%" _ASM_DX " \n\t"
7227                 "je 2f \n\t"
7228                 "mov %%" _ASM_AX", %%cr2 \n\t"
7229                 "2: \n\t"
7230                 /* Check if vmlaunch of vmresume is needed */
7231                 "cmpl $0, %c[launched](%0) \n\t"
7232                 /* Load guest registers.  Don't clobber flags. */
7233                 "mov %c[rax](%0), %%" _ASM_AX " \n\t"
7234                 "mov %c[rbx](%0), %%" _ASM_BX " \n\t"
7235                 "mov %c[rdx](%0), %%" _ASM_DX " \n\t"
7236                 "mov %c[rsi](%0), %%" _ASM_SI " \n\t"
7237                 "mov %c[rdi](%0), %%" _ASM_DI " \n\t"
7238                 "mov %c[rbp](%0), %%" _ASM_BP " \n\t"
7239 #ifdef CONFIG_X86_64
7240                 "mov %c[r8](%0),  %%r8  \n\t"
7241                 "mov %c[r9](%0),  %%r9  \n\t"
7242                 "mov %c[r10](%0), %%r10 \n\t"
7243                 "mov %c[r11](%0), %%r11 \n\t"
7244                 "mov %c[r12](%0), %%r12 \n\t"
7245                 "mov %c[r13](%0), %%r13 \n\t"
7246                 "mov %c[r14](%0), %%r14 \n\t"
7247                 "mov %c[r15](%0), %%r15 \n\t"
7248 #endif
7249                 "mov %c[rcx](%0), %%" _ASM_CX " \n\t" /* kills %0 (ecx) */
7250
7251                 /* Enter guest mode */
7252                 "jne 1f \n\t"
7253                 __ex(ASM_VMX_VMLAUNCH) "\n\t"
7254                 "jmp 2f \n\t"
7255                 "1: " __ex(ASM_VMX_VMRESUME) "\n\t"
7256                 "2: "
7257                 /* Save guest registers, load host registers, keep flags */
7258                 "mov %0, %c[wordsize](%%" _ASM_SP ") \n\t"
7259                 "pop %0 \n\t"
7260                 "mov %%" _ASM_AX ", %c[rax](%0) \n\t"
7261                 "mov %%" _ASM_BX ", %c[rbx](%0) \n\t"
7262                 __ASM_SIZE(pop) " %c[rcx](%0) \n\t"
7263                 "mov %%" _ASM_DX ", %c[rdx](%0) \n\t"
7264                 "mov %%" _ASM_SI ", %c[rsi](%0) \n\t"
7265                 "mov %%" _ASM_DI ", %c[rdi](%0) \n\t"
7266                 "mov %%" _ASM_BP ", %c[rbp](%0) \n\t"
7267 #ifdef CONFIG_X86_64
7268                 "mov %%r8,  %c[r8](%0) \n\t"
7269                 "mov %%r9,  %c[r9](%0) \n\t"
7270                 "mov %%r10, %c[r10](%0) \n\t"
7271                 "mov %%r11, %c[r11](%0) \n\t"
7272                 "mov %%r12, %c[r12](%0) \n\t"
7273                 "mov %%r13, %c[r13](%0) \n\t"
7274                 "mov %%r14, %c[r14](%0) \n\t"
7275                 "mov %%r15, %c[r15](%0) \n\t"
7276 #endif
7277                 "mov %%cr2, %%" _ASM_AX "   \n\t"
7278                 "mov %%" _ASM_AX ", %c[cr2](%0) \n\t"
7279
7280                 "pop  %%" _ASM_BP "; pop  %%" _ASM_DX " \n\t"
7281                 "setbe %c[fail](%0) \n\t"
7282                 ".pushsection .rodata \n\t"
7283                 ".global vmx_return \n\t"
7284                 "vmx_return: " _ASM_PTR " 2b \n\t"
7285                 ".popsection"
7286               : : "c"(vmx), "d"((unsigned long)HOST_RSP),
7287                 [launched]"i"(offsetof(struct vcpu_vmx, __launched)),
7288                 [fail]"i"(offsetof(struct vcpu_vmx, fail)),
7289                 [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)),
7290                 [rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])),
7291                 [rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])),
7292                 [rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])),
7293                 [rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])),
7294                 [rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])),
7295                 [rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])),
7296                 [rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])),
7297 #ifdef CONFIG_X86_64
7298                 [r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])),
7299                 [r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])),
7300                 [r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])),
7301                 [r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])),
7302                 [r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])),
7303                 [r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])),
7304                 [r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])),
7305                 [r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])),
7306 #endif
7307                 [cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2)),
7308                 [wordsize]"i"(sizeof(ulong))
7309               : "cc", "memory"
7310 #ifdef CONFIG_X86_64
7311                 , "rax", "rbx", "rdi", "rsi"
7312                 , "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
7313 #else
7314                 , "eax", "ebx", "edi", "esi"
7315 #endif
7316               );
7317
7318         /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
7319         if (debugctlmsr)
7320                 update_debugctlmsr(debugctlmsr);
7321
7322 #ifndef CONFIG_X86_64
7323         /*
7324          * The sysexit path does not restore ds/es, so we must set them to
7325          * a reasonable value ourselves.
7326          *
7327          * We can't defer this to vmx_load_host_state() since that function
7328          * may be executed in interrupt context, which saves and restore segments
7329          * around it, nullifying its effect.
7330          */
7331         loadsegment(ds, __USER_DS);
7332         loadsegment(es, __USER_DS);
7333 #endif
7334
7335         vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
7336                                   | (1 << VCPU_EXREG_RFLAGS)
7337                                   | (1 << VCPU_EXREG_CPL)
7338                                   | (1 << VCPU_EXREG_PDPTR)
7339                                   | (1 << VCPU_EXREG_SEGMENTS)
7340                                   | (1 << VCPU_EXREG_CR3));
7341         vcpu->arch.regs_dirty = 0;
7342
7343         vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
7344
7345         vmx->loaded_vmcs->launched = 1;
7346
7347         vmx->exit_reason = vmcs_read32(VM_EXIT_REASON);
7348         trace_kvm_exit(vmx->exit_reason, vcpu, KVM_ISA_VMX);
7349
7350         /*
7351          * the KVM_REQ_EVENT optimization bit is only on for one entry, and if
7352          * we did not inject a still-pending event to L1 now because of
7353          * nested_run_pending, we need to re-enable this bit.
7354          */
7355         if (vmx->nested.nested_run_pending)
7356                 kvm_make_request(KVM_REQ_EVENT, vcpu);
7357
7358         vmx->nested.nested_run_pending = 0;
7359
7360         vmx_complete_atomic_exit(vmx);
7361         vmx_recover_nmi_blocking(vmx);
7362         vmx_complete_interrupts(vmx);
7363 }
7364
7365 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
7366 {
7367         struct vcpu_vmx *vmx = to_vmx(vcpu);
7368
7369         free_vpid(vmx);
7370         free_loaded_vmcs(vmx->loaded_vmcs);
7371         free_nested(vmx);
7372         kfree(vmx->guest_msrs);
7373         kvm_vcpu_uninit(vcpu);
7374         kmem_cache_free(kvm_vcpu_cache, vmx);
7375 }
7376
7377 static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
7378 {
7379         int err;
7380         struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
7381         int cpu;
7382
7383         if (!vmx)
7384                 return ERR_PTR(-ENOMEM);
7385
7386         allocate_vpid(vmx);
7387
7388         err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
7389         if (err)
7390                 goto free_vcpu;
7391
7392         vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
7393         err = -ENOMEM;
7394         if (!vmx->guest_msrs) {
7395                 goto uninit_vcpu;
7396         }
7397
7398         vmx->loaded_vmcs = &vmx->vmcs01;
7399         vmx->loaded_vmcs->vmcs = alloc_vmcs();
7400         if (!vmx->loaded_vmcs->vmcs)
7401                 goto free_msrs;
7402         if (!vmm_exclusive)
7403                 kvm_cpu_vmxon(__pa(per_cpu(vmxarea, raw_smp_processor_id())));
7404         loaded_vmcs_init(vmx->loaded_vmcs);
7405         if (!vmm_exclusive)
7406                 kvm_cpu_vmxoff();
7407
7408         cpu = get_cpu();
7409         vmx_vcpu_load(&vmx->vcpu, cpu);
7410         vmx->vcpu.cpu = cpu;
7411         err = vmx_vcpu_setup(vmx);
7412         vmx_vcpu_put(&vmx->vcpu);
7413         put_cpu();
7414         if (err)
7415                 goto free_vmcs;
7416         if (vm_need_virtualize_apic_accesses(kvm)) {
7417                 err = alloc_apic_access_page(kvm);
7418                 if (err)
7419                         goto free_vmcs;
7420         }
7421
7422         if (enable_ept) {
7423                 if (!kvm->arch.ept_identity_map_addr)
7424                         kvm->arch.ept_identity_map_addr =
7425                                 VMX_EPT_IDENTITY_PAGETABLE_ADDR;
7426                 err = -ENOMEM;
7427                 if (alloc_identity_pagetable(kvm) != 0)
7428                         goto free_vmcs;
7429                 if (!init_rmode_identity_map(kvm))
7430                         goto free_vmcs;
7431         }
7432
7433         vmx->nested.current_vmptr = -1ull;
7434         vmx->nested.current_vmcs12 = NULL;
7435
7436         return &vmx->vcpu;
7437
7438 free_vmcs:
7439         free_loaded_vmcs(vmx->loaded_vmcs);
7440 free_msrs:
7441         kfree(vmx->guest_msrs);
7442 uninit_vcpu:
7443         kvm_vcpu_uninit(&vmx->vcpu);
7444 free_vcpu:
7445         free_vpid(vmx);
7446         kmem_cache_free(kvm_vcpu_cache, vmx);
7447         return ERR_PTR(err);
7448 }
7449
7450 static void __init vmx_check_processor_compat(void *rtn)
7451 {
7452         struct vmcs_config vmcs_conf;
7453
7454         *(int *)rtn = 0;
7455         if (setup_vmcs_config(&vmcs_conf) < 0)
7456                 *(int *)rtn = -EIO;
7457         if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
7458                 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
7459                                 smp_processor_id());
7460                 *(int *)rtn = -EIO;
7461         }
7462 }
7463
7464 static int get_ept_level(void)
7465 {
7466         return VMX_EPT_DEFAULT_GAW + 1;
7467 }
7468
7469 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
7470 {
7471         u64 ret;
7472
7473         /* For VT-d and EPT combination
7474          * 1. MMIO: always map as UC
7475          * 2. EPT with VT-d:
7476          *   a. VT-d without snooping control feature: can't guarantee the
7477          *      result, try to trust guest.
7478          *   b. VT-d with snooping control feature: snooping control feature of
7479          *      VT-d engine can guarantee the cache correctness. Just set it
7480          *      to WB to keep consistent with host. So the same as item 3.
7481          * 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
7482          *    consistent with host MTRR
7483          */
7484         if (is_mmio)
7485                 ret = MTRR_TYPE_UNCACHABLE << VMX_EPT_MT_EPTE_SHIFT;
7486         else if (kvm_arch_has_noncoherent_dma(vcpu->kvm))
7487                 ret = kvm_get_guest_memory_type(vcpu, gfn) <<
7488                       VMX_EPT_MT_EPTE_SHIFT;
7489         else
7490                 ret = (MTRR_TYPE_WRBACK << VMX_EPT_MT_EPTE_SHIFT)
7491                         | VMX_EPT_IPAT_BIT;
7492
7493         return ret;
7494 }
7495
7496 static int vmx_get_lpage_level(void)
7497 {
7498         if (enable_ept && !cpu_has_vmx_ept_1g_page())
7499                 return PT_DIRECTORY_LEVEL;
7500         else
7501                 /* For shadow and EPT supported 1GB page */
7502                 return PT_PDPE_LEVEL;
7503 }
7504
7505 static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
7506 {
7507         struct kvm_cpuid_entry2 *best;
7508         struct vcpu_vmx *vmx = to_vmx(vcpu);
7509         u32 exec_control;
7510
7511         vmx->rdtscp_enabled = false;
7512         if (vmx_rdtscp_supported()) {
7513                 exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
7514                 if (exec_control & SECONDARY_EXEC_RDTSCP) {
7515                         best = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
7516                         if (best && (best->edx & bit(X86_FEATURE_RDTSCP)))
7517                                 vmx->rdtscp_enabled = true;
7518                         else {
7519                                 exec_control &= ~SECONDARY_EXEC_RDTSCP;
7520                                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
7521                                                 exec_control);
7522                         }
7523                 }
7524         }
7525
7526         /* Exposing INVPCID only when PCID is exposed */
7527         best = kvm_find_cpuid_entry(vcpu, 0x7, 0);
7528         if (vmx_invpcid_supported() &&
7529             best && (best->ebx & bit(X86_FEATURE_INVPCID)) &&
7530             guest_cpuid_has_pcid(vcpu)) {
7531                 exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
7532                 exec_control |= SECONDARY_EXEC_ENABLE_INVPCID;
7533                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
7534                              exec_control);
7535         } else {
7536                 if (cpu_has_secondary_exec_ctrls()) {
7537                         exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
7538                         exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
7539                         vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
7540                                      exec_control);
7541                 }
7542                 if (best)
7543                         best->ebx &= ~bit(X86_FEATURE_INVPCID);
7544         }
7545 }
7546
7547 static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
7548 {
7549         if (func == 1 && nested)
7550                 entry->ecx |= bit(X86_FEATURE_VMX);
7551 }
7552
7553 static void nested_ept_inject_page_fault(struct kvm_vcpu *vcpu,
7554                 struct x86_exception *fault)
7555 {
7556         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7557         u32 exit_reason;
7558
7559         if (fault->error_code & PFERR_RSVD_MASK)
7560                 exit_reason = EXIT_REASON_EPT_MISCONFIG;
7561         else
7562                 exit_reason = EXIT_REASON_EPT_VIOLATION;
7563         nested_vmx_vmexit(vcpu, exit_reason, 0, vcpu->arch.exit_qualification);
7564         vmcs12->guest_physical_address = fault->address;
7565 }
7566
7567 /* Callbacks for nested_ept_init_mmu_context: */
7568
7569 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu)
7570 {
7571         /* return the page table to be shadowed - in our case, EPT12 */
7572         return get_vmcs12(vcpu)->ept_pointer;
7573 }
7574
7575 static void nested_ept_init_mmu_context(struct kvm_vcpu *vcpu)
7576 {
7577         kvm_init_shadow_ept_mmu(vcpu, &vcpu->arch.mmu,
7578                         nested_vmx_ept_caps & VMX_EPT_EXECUTE_ONLY_BIT);
7579
7580         vcpu->arch.mmu.set_cr3           = vmx_set_cr3;
7581         vcpu->arch.mmu.get_cr3           = nested_ept_get_cr3;
7582         vcpu->arch.mmu.inject_page_fault = nested_ept_inject_page_fault;
7583
7584         vcpu->arch.walk_mmu              = &vcpu->arch.nested_mmu;
7585 }
7586
7587 static void nested_ept_uninit_mmu_context(struct kvm_vcpu *vcpu)
7588 {
7589         vcpu->arch.walk_mmu = &vcpu->arch.mmu;
7590 }
7591
7592 static void vmx_inject_page_fault_nested(struct kvm_vcpu *vcpu,
7593                 struct x86_exception *fault)
7594 {
7595         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7596
7597         WARN_ON(!is_guest_mode(vcpu));
7598
7599         /* TODO: also check PFEC_MATCH/MASK, not just EB.PF. */
7600         if (vmcs12->exception_bitmap & (1u << PF_VECTOR))
7601                 nested_vmx_vmexit(vcpu, to_vmx(vcpu)->exit_reason,
7602                                   vmcs_read32(VM_EXIT_INTR_INFO),
7603                                   vmcs_readl(EXIT_QUALIFICATION));
7604         else
7605                 kvm_inject_page_fault(vcpu, fault);
7606 }
7607
7608 static void vmx_start_preemption_timer(struct kvm_vcpu *vcpu)
7609 {
7610         u64 preemption_timeout = get_vmcs12(vcpu)->vmx_preemption_timer_value;
7611         struct vcpu_vmx *vmx = to_vmx(vcpu);
7612
7613         if (vcpu->arch.virtual_tsc_khz == 0)
7614                 return;
7615
7616         /* Make sure short timeouts reliably trigger an immediate vmexit.
7617          * hrtimer_start does not guarantee this. */
7618         if (preemption_timeout <= 1) {
7619                 vmx_preemption_timer_fn(&vmx->nested.preemption_timer);
7620                 return;
7621         }
7622
7623         preemption_timeout <<= VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
7624         preemption_timeout *= 1000000;
7625         do_div(preemption_timeout, vcpu->arch.virtual_tsc_khz);
7626         hrtimer_start(&vmx->nested.preemption_timer,
7627                       ns_to_ktime(preemption_timeout), HRTIMER_MODE_REL);
7628 }
7629
7630 /*
7631  * prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
7632  * L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
7633  * with L0's requirements for its guest (a.k.a. vmsc01), so we can run the L2
7634  * guest in a way that will both be appropriate to L1's requests, and our
7635  * needs. In addition to modifying the active vmcs (which is vmcs02), this
7636  * function also has additional necessary side-effects, like setting various
7637  * vcpu->arch fields.
7638  */
7639 static void prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
7640 {
7641         struct vcpu_vmx *vmx = to_vmx(vcpu);
7642         u32 exec_control;
7643
7644         vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
7645         vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
7646         vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
7647         vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
7648         vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
7649         vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
7650         vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
7651         vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
7652         vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
7653         vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
7654         vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
7655         vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
7656         vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
7657         vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
7658         vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
7659         vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
7660         vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
7661         vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
7662         vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
7663         vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
7664         vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
7665         vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
7666         vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
7667         vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
7668         vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
7669         vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
7670         vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
7671         vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
7672         vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
7673         vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
7674         vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
7675         vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
7676         vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
7677         vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
7678         vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
7679         vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
7680
7681         vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
7682         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
7683                 vmcs12->vm_entry_intr_info_field);
7684         vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
7685                 vmcs12->vm_entry_exception_error_code);
7686         vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
7687                 vmcs12->vm_entry_instruction_len);
7688         vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
7689                 vmcs12->guest_interruptibility_info);
7690         vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
7691         kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
7692         vmx_set_rflags(vcpu, vmcs12->guest_rflags);
7693         vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
7694                 vmcs12->guest_pending_dbg_exceptions);
7695         vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
7696         vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
7697
7698         vmcs_write64(VMCS_LINK_POINTER, -1ull);
7699
7700         exec_control = vmcs12->pin_based_vm_exec_control;
7701         exec_control |= vmcs_config.pin_based_exec_ctrl;
7702         exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
7703         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, exec_control);
7704
7705         vmx->nested.preemption_timer_expired = false;
7706         if (nested_cpu_has_preemption_timer(vmcs12))
7707                 vmx_start_preemption_timer(vcpu);
7708
7709         /*
7710          * Whether page-faults are trapped is determined by a combination of
7711          * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.
7712          * If enable_ept, L0 doesn't care about page faults and we should
7713          * set all of these to L1's desires. However, if !enable_ept, L0 does
7714          * care about (at least some) page faults, and because it is not easy
7715          * (if at all possible?) to merge L0 and L1's desires, we simply ask
7716          * to exit on each and every L2 page fault. This is done by setting
7717          * MASK=MATCH=0 and (see below) EB.PF=1.
7718          * Note that below we don't need special code to set EB.PF beyond the
7719          * "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
7720          * vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
7721          * !enable_ept, EB.PF is 1, so the "or" will always be 1.
7722          *
7723          * A problem with this approach (when !enable_ept) is that L1 may be
7724          * injected with more page faults than it asked for. This could have
7725          * caused problems, but in practice existing hypervisors don't care.
7726          * To fix this, we will need to emulate the PFEC checking (on the L1
7727          * page tables), using walk_addr(), when injecting PFs to L1.
7728          */
7729         vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK,
7730                 enable_ept ? vmcs12->page_fault_error_code_mask : 0);
7731         vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
7732                 enable_ept ? vmcs12->page_fault_error_code_match : 0);
7733
7734         if (cpu_has_secondary_exec_ctrls()) {
7735                 exec_control = vmx_secondary_exec_control(vmx);
7736                 if (!vmx->rdtscp_enabled)
7737                         exec_control &= ~SECONDARY_EXEC_RDTSCP;
7738                 /* Take the following fields only from vmcs12 */
7739                 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
7740                 if (nested_cpu_has(vmcs12,
7741                                 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS))
7742                         exec_control |= vmcs12->secondary_vm_exec_control;
7743
7744                 if (exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) {
7745                         /*
7746                          * Translate L1 physical address to host physical
7747                          * address for vmcs02. Keep the page pinned, so this
7748                          * physical address remains valid. We keep a reference
7749                          * to it so we can release it later.
7750                          */
7751                         if (vmx->nested.apic_access_page) /* shouldn't happen */
7752                                 nested_release_page(vmx->nested.apic_access_page);
7753                         vmx->nested.apic_access_page =
7754                                 nested_get_page(vcpu, vmcs12->apic_access_addr);
7755                         /*
7756                          * If translation failed, no matter: This feature asks
7757                          * to exit when accessing the given address, and if it
7758                          * can never be accessed, this feature won't do
7759                          * anything anyway.
7760                          */
7761                         if (!vmx->nested.apic_access_page)
7762                                 exec_control &=
7763                                   ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
7764                         else
7765                                 vmcs_write64(APIC_ACCESS_ADDR,
7766                                   page_to_phys(vmx->nested.apic_access_page));
7767                 } else if (vm_need_virtualize_apic_accesses(vmx->vcpu.kvm)) {
7768                         exec_control |=
7769                                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
7770                         vmcs_write64(APIC_ACCESS_ADDR,
7771                                 page_to_phys(vcpu->kvm->arch.apic_access_page));
7772                 }
7773
7774                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
7775         }
7776
7777
7778         /*
7779          * Set host-state according to L0's settings (vmcs12 is irrelevant here)
7780          * Some constant fields are set here by vmx_set_constant_host_state().
7781          * Other fields are different per CPU, and will be set later when
7782          * vmx_vcpu_load() is called, and when vmx_save_host_state() is called.
7783          */
7784         vmx_set_constant_host_state(vmx);
7785
7786         /*
7787          * HOST_RSP is normally set correctly in vmx_vcpu_run() just before
7788          * entry, but only if the current (host) sp changed from the value
7789          * we wrote last (vmx->host_rsp). This cache is no longer relevant
7790          * if we switch vmcs, and rather than hold a separate cache per vmcs,
7791          * here we just force the write to happen on entry.
7792          */
7793         vmx->host_rsp = 0;
7794
7795         exec_control = vmx_exec_control(vmx); /* L0's desires */
7796         exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
7797         exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
7798         exec_control &= ~CPU_BASED_TPR_SHADOW;
7799         exec_control |= vmcs12->cpu_based_vm_exec_control;
7800         /*
7801          * Merging of IO and MSR bitmaps not currently supported.
7802          * Rather, exit every time.
7803          */
7804         exec_control &= ~CPU_BASED_USE_MSR_BITMAPS;
7805         exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
7806         exec_control |= CPU_BASED_UNCOND_IO_EXITING;
7807
7808         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
7809
7810         /* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
7811          * bitwise-or of what L1 wants to trap for L2, and what we want to
7812          * trap. Note that CR0.TS also needs updating - we do this later.
7813          */
7814         update_exception_bitmap(vcpu);
7815         vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
7816         vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
7817
7818         /* L2->L1 exit controls are emulated - the hardware exit is to L0 so
7819          * we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER
7820          * bits are further modified by vmx_set_efer() below.
7821          */
7822         vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);
7823
7824         /* vmcs12's VM_ENTRY_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE are
7825          * emulated by vmx_set_efer(), below.
7826          */
7827         vm_entry_controls_init(vmx, 
7828                 (vmcs12->vm_entry_controls & ~VM_ENTRY_LOAD_IA32_EFER &
7829                         ~VM_ENTRY_IA32E_MODE) |
7830                 (vmcs_config.vmentry_ctrl & ~VM_ENTRY_IA32E_MODE));
7831
7832         if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT) {
7833                 vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
7834                 vcpu->arch.pat = vmcs12->guest_ia32_pat;
7835         } else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
7836                 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
7837
7838
7839         set_cr4_guest_host_mask(vmx);
7840
7841         if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
7842                 vmcs_write64(TSC_OFFSET,
7843                         vmx->nested.vmcs01_tsc_offset + vmcs12->tsc_offset);
7844         else
7845                 vmcs_write64(TSC_OFFSET, vmx->nested.vmcs01_tsc_offset);
7846
7847         if (enable_vpid) {
7848                 /*
7849                  * Trivially support vpid by letting L2s share their parent
7850                  * L1's vpid. TODO: move to a more elaborate solution, giving
7851                  * each L2 its own vpid and exposing the vpid feature to L1.
7852                  */
7853                 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
7854                 vmx_flush_tlb(vcpu);
7855         }
7856
7857         if (nested_cpu_has_ept(vmcs12)) {
7858                 kvm_mmu_unload(vcpu);
7859                 nested_ept_init_mmu_context(vcpu);
7860         }
7861
7862         if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)
7863                 vcpu->arch.efer = vmcs12->guest_ia32_efer;
7864         else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
7865                 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
7866         else
7867                 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
7868         /* Note: modifies VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
7869         vmx_set_efer(vcpu, vcpu->arch.efer);
7870
7871         /*
7872          * This sets GUEST_CR0 to vmcs12->guest_cr0, with possibly a modified
7873          * TS bit (for lazy fpu) and bits which we consider mandatory enabled.
7874          * The CR0_READ_SHADOW is what L2 should have expected to read given
7875          * the specifications by L1; It's not enough to take
7876          * vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we
7877          * have more bits than L1 expected.
7878          */
7879         vmx_set_cr0(vcpu, vmcs12->guest_cr0);
7880         vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
7881
7882         vmx_set_cr4(vcpu, vmcs12->guest_cr4);
7883         vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
7884
7885         /* shadow page tables on either EPT or shadow page tables */
7886         kvm_set_cr3(vcpu, vmcs12->guest_cr3);
7887         kvm_mmu_reset_context(vcpu);
7888
7889         if (!enable_ept)
7890                 vcpu->arch.walk_mmu->inject_page_fault = vmx_inject_page_fault_nested;
7891
7892         /*
7893          * L1 may access the L2's PDPTR, so save them to construct vmcs12
7894          */
7895         if (enable_ept) {
7896                 vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
7897                 vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
7898                 vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
7899                 vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
7900         }
7901
7902         kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->guest_rsp);
7903         kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->guest_rip);
7904 }
7905
7906 /*
7907  * nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1
7908  * for running an L2 nested guest.
7909  */
7910 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
7911 {
7912         struct vmcs12 *vmcs12;
7913         struct vcpu_vmx *vmx = to_vmx(vcpu);
7914         int cpu;
7915         struct loaded_vmcs *vmcs02;
7916         bool ia32e;
7917
7918         if (!nested_vmx_check_permission(vcpu) ||
7919             !nested_vmx_check_vmcs12(vcpu))
7920                 return 1;
7921
7922         skip_emulated_instruction(vcpu);
7923         vmcs12 = get_vmcs12(vcpu);
7924
7925         if (enable_shadow_vmcs)
7926                 copy_shadow_to_vmcs12(vmx);
7927
7928         /*
7929          * The nested entry process starts with enforcing various prerequisites
7930          * on vmcs12 as required by the Intel SDM, and act appropriately when
7931          * they fail: As the SDM explains, some conditions should cause the
7932          * instruction to fail, while others will cause the instruction to seem
7933          * to succeed, but return an EXIT_REASON_INVALID_STATE.
7934          * To speed up the normal (success) code path, we should avoid checking
7935          * for misconfigurations which will anyway be caught by the processor
7936          * when using the merged vmcs02.
7937          */
7938         if (vmcs12->launch_state == launch) {
7939                 nested_vmx_failValid(vcpu,
7940                         launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
7941                                : VMXERR_VMRESUME_NONLAUNCHED_VMCS);
7942                 return 1;
7943         }
7944
7945         if (vmcs12->guest_activity_state != GUEST_ACTIVITY_ACTIVE &&
7946             vmcs12->guest_activity_state != GUEST_ACTIVITY_HLT) {
7947                 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
7948                 return 1;
7949         }
7950
7951         if ((vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_MSR_BITMAPS) &&
7952                         !IS_ALIGNED(vmcs12->msr_bitmap, PAGE_SIZE)) {
7953                 /*TODO: Also verify bits beyond physical address width are 0*/
7954                 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
7955                 return 1;
7956         }
7957
7958         if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) &&
7959                         !IS_ALIGNED(vmcs12->apic_access_addr, PAGE_SIZE)) {
7960                 /*TODO: Also verify bits beyond physical address width are 0*/
7961                 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
7962                 return 1;
7963         }
7964
7965         if (vmcs12->vm_entry_msr_load_count > 0 ||
7966             vmcs12->vm_exit_msr_load_count > 0 ||
7967             vmcs12->vm_exit_msr_store_count > 0) {
7968                 pr_warn_ratelimited("%s: VMCS MSR_{LOAD,STORE} unsupported\n",
7969                                     __func__);
7970                 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
7971                 return 1;
7972         }
7973
7974         if (!vmx_control_verify(vmcs12->cpu_based_vm_exec_control,
7975               nested_vmx_procbased_ctls_low, nested_vmx_procbased_ctls_high) ||
7976             !vmx_control_verify(vmcs12->secondary_vm_exec_control,
7977               nested_vmx_secondary_ctls_low, nested_vmx_secondary_ctls_high) ||
7978             !vmx_control_verify(vmcs12->pin_based_vm_exec_control,
7979               nested_vmx_pinbased_ctls_low, nested_vmx_pinbased_ctls_high) ||
7980             !vmx_control_verify(vmcs12->vm_exit_controls,
7981               nested_vmx_exit_ctls_low, nested_vmx_exit_ctls_high) ||
7982             !vmx_control_verify(vmcs12->vm_entry_controls,
7983               nested_vmx_entry_ctls_low, nested_vmx_entry_ctls_high))
7984         {
7985                 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
7986                 return 1;
7987         }
7988
7989         if (((vmcs12->host_cr0 & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON) ||
7990             ((vmcs12->host_cr4 & VMXON_CR4_ALWAYSON) != VMXON_CR4_ALWAYSON)) {
7991                 nested_vmx_failValid(vcpu,
7992                         VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
7993                 return 1;
7994         }
7995
7996         if (!nested_cr0_valid(vmcs12, vmcs12->guest_cr0) ||
7997             ((vmcs12->guest_cr4 & VMXON_CR4_ALWAYSON) != VMXON_CR4_ALWAYSON)) {
7998                 nested_vmx_entry_failure(vcpu, vmcs12,
7999                         EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT);
8000                 return 1;
8001         }
8002         if (vmcs12->vmcs_link_pointer != -1ull) {
8003                 nested_vmx_entry_failure(vcpu, vmcs12,
8004                         EXIT_REASON_INVALID_STATE, ENTRY_FAIL_VMCS_LINK_PTR);
8005                 return 1;
8006         }
8007
8008         /*
8009          * If the load IA32_EFER VM-entry control is 1, the following checks
8010          * are performed on the field for the IA32_EFER MSR:
8011          * - Bits reserved in the IA32_EFER MSR must be 0.
8012          * - Bit 10 (corresponding to IA32_EFER.LMA) must equal the value of
8013          *   the IA-32e mode guest VM-exit control. It must also be identical
8014          *   to bit 8 (LME) if bit 31 in the CR0 field (corresponding to
8015          *   CR0.PG) is 1.
8016          */
8017         if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER) {
8018                 ia32e = (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) != 0;
8019                 if (!kvm_valid_efer(vcpu, vmcs12->guest_ia32_efer) ||
8020                     ia32e != !!(vmcs12->guest_ia32_efer & EFER_LMA) ||
8021                     ((vmcs12->guest_cr0 & X86_CR0_PG) &&
8022                      ia32e != !!(vmcs12->guest_ia32_efer & EFER_LME))) {
8023                         nested_vmx_entry_failure(vcpu, vmcs12,
8024                                 EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT);
8025                         return 1;
8026                 }
8027         }
8028
8029         /*
8030          * If the load IA32_EFER VM-exit control is 1, bits reserved in the
8031          * IA32_EFER MSR must be 0 in the field for that register. In addition,
8032          * the values of the LMA and LME bits in the field must each be that of
8033          * the host address-space size VM-exit control.
8034          */
8035         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) {
8036                 ia32e = (vmcs12->vm_exit_controls &
8037                          VM_EXIT_HOST_ADDR_SPACE_SIZE) != 0;
8038                 if (!kvm_valid_efer(vcpu, vmcs12->host_ia32_efer) ||
8039                     ia32e != !!(vmcs12->host_ia32_efer & EFER_LMA) ||
8040                     ia32e != !!(vmcs12->host_ia32_efer & EFER_LME)) {
8041                         nested_vmx_entry_failure(vcpu, vmcs12,
8042                                 EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT);
8043                         return 1;
8044                 }
8045         }
8046
8047         /*
8048          * We're finally done with prerequisite checking, and can start with
8049          * the nested entry.
8050          */
8051
8052         vmcs02 = nested_get_current_vmcs02(vmx);
8053         if (!vmcs02)
8054                 return -ENOMEM;
8055
8056         enter_guest_mode(vcpu);
8057
8058         vmx->nested.vmcs01_tsc_offset = vmcs_read64(TSC_OFFSET);
8059
8060         cpu = get_cpu();
8061         vmx->loaded_vmcs = vmcs02;
8062         vmx_vcpu_put(vcpu);
8063         vmx_vcpu_load(vcpu, cpu);
8064         vcpu->cpu = cpu;
8065         put_cpu();
8066
8067         vmx_segment_cache_clear(vmx);
8068
8069         vmcs12->launch_state = 1;
8070
8071         prepare_vmcs02(vcpu, vmcs12);
8072
8073         if (vmcs12->guest_activity_state == GUEST_ACTIVITY_HLT)
8074                 return kvm_emulate_halt(vcpu);
8075
8076         vmx->nested.nested_run_pending = 1;
8077
8078         /*
8079          * Note no nested_vmx_succeed or nested_vmx_fail here. At this point
8080          * we are no longer running L1, and VMLAUNCH/VMRESUME has not yet
8081          * returned as far as L1 is concerned. It will only return (and set
8082          * the success flag) when L2 exits (see nested_vmx_vmexit()).
8083          */
8084         return 1;
8085 }
8086
8087 /*
8088  * On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
8089  * because L2 may have changed some cr0 bits directly (CRO_GUEST_HOST_MASK).
8090  * This function returns the new value we should put in vmcs12.guest_cr0.
8091  * It's not enough to just return the vmcs02 GUEST_CR0. Rather,
8092  *  1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
8093  *     available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0
8094  *     didn't trap the bit, because if L1 did, so would L0).
8095  *  2. Bits that L1 asked to trap (and therefore L0 also did) could not have
8096  *     been modified by L2, and L1 knows it. So just leave the old value of
8097  *     the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0
8098  *     isn't relevant, because if L0 traps this bit it can set it to anything.
8099  *  3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have
8100  *     changed these bits, and therefore they need to be updated, but L0
8101  *     didn't necessarily allow them to be changed in GUEST_CR0 - and rather
8102  *     put them in vmcs02 CR0_READ_SHADOW. So take these bits from there.
8103  */
8104 static inline unsigned long
8105 vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
8106 {
8107         return
8108         /*1*/   (vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) |
8109         /*2*/   (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) |
8110         /*3*/   (vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask |
8111                         vcpu->arch.cr0_guest_owned_bits));
8112 }
8113
8114 static inline unsigned long
8115 vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
8116 {
8117         return
8118         /*1*/   (vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) |
8119         /*2*/   (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) |
8120         /*3*/   (vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask |
8121                         vcpu->arch.cr4_guest_owned_bits));
8122 }
8123
8124 static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
8125                                        struct vmcs12 *vmcs12)
8126 {
8127         u32 idt_vectoring;
8128         unsigned int nr;
8129
8130         if (vcpu->arch.exception.pending && vcpu->arch.exception.reinject) {
8131                 nr = vcpu->arch.exception.nr;
8132                 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
8133
8134                 if (kvm_exception_is_soft(nr)) {
8135                         vmcs12->vm_exit_instruction_len =
8136                                 vcpu->arch.event_exit_inst_len;
8137                         idt_vectoring |= INTR_TYPE_SOFT_EXCEPTION;
8138                 } else
8139                         idt_vectoring |= INTR_TYPE_HARD_EXCEPTION;
8140
8141                 if (vcpu->arch.exception.has_error_code) {
8142                         idt_vectoring |= VECTORING_INFO_DELIVER_CODE_MASK;
8143                         vmcs12->idt_vectoring_error_code =
8144                                 vcpu->arch.exception.error_code;
8145                 }
8146
8147                 vmcs12->idt_vectoring_info_field = idt_vectoring;
8148         } else if (vcpu->arch.nmi_injected) {
8149                 vmcs12->idt_vectoring_info_field =
8150                         INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR;
8151         } else if (vcpu->arch.interrupt.pending) {
8152                 nr = vcpu->arch.interrupt.nr;
8153                 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
8154
8155                 if (vcpu->arch.interrupt.soft) {
8156                         idt_vectoring |= INTR_TYPE_SOFT_INTR;
8157                         vmcs12->vm_entry_instruction_len =
8158                                 vcpu->arch.event_exit_inst_len;
8159                 } else
8160                         idt_vectoring |= INTR_TYPE_EXT_INTR;
8161
8162                 vmcs12->idt_vectoring_info_field = idt_vectoring;
8163         }
8164 }
8165
8166 static int vmx_check_nested_events(struct kvm_vcpu *vcpu, bool external_intr)
8167 {
8168         struct vcpu_vmx *vmx = to_vmx(vcpu);
8169
8170         if (nested_cpu_has_preemption_timer(get_vmcs12(vcpu)) &&
8171             vmx->nested.preemption_timer_expired) {
8172                 if (vmx->nested.nested_run_pending)
8173                         return -EBUSY;
8174                 nested_vmx_vmexit(vcpu, EXIT_REASON_PREEMPTION_TIMER, 0, 0);
8175                 return 0;
8176         }
8177
8178         if (vcpu->arch.nmi_pending && nested_exit_on_nmi(vcpu)) {
8179                 if (vmx->nested.nested_run_pending)
8180                         return -EBUSY;
8181                 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
8182                                   NMI_VECTOR | INTR_TYPE_NMI_INTR |
8183                                   INTR_INFO_VALID_MASK, 0);
8184                 /*
8185                  * The NMI-triggered VM exit counts as injection:
8186                  * clear this one and block further NMIs.
8187                  */
8188                 vcpu->arch.nmi_pending = 0;
8189                 vmx_set_nmi_mask(vcpu, true);
8190                 return 0;
8191         }
8192
8193         if ((kvm_cpu_has_interrupt(vcpu) || external_intr) &&
8194             nested_exit_on_intr(vcpu)) {
8195                 if (vmx->nested.nested_run_pending)
8196                         return -EBUSY;
8197                 nested_vmx_vmexit(vcpu, EXIT_REASON_EXTERNAL_INTERRUPT, 0, 0);
8198         }
8199
8200         return 0;
8201 }
8202
8203 static u32 vmx_get_preemption_timer_value(struct kvm_vcpu *vcpu)
8204 {
8205         ktime_t remaining =
8206                 hrtimer_get_remaining(&to_vmx(vcpu)->nested.preemption_timer);
8207         u64 value;
8208
8209         if (ktime_to_ns(remaining) <= 0)
8210                 return 0;
8211
8212         value = ktime_to_ns(remaining) * vcpu->arch.virtual_tsc_khz;
8213         do_div(value, 1000000);
8214         return value >> VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
8215 }
8216
8217 /*
8218  * prepare_vmcs12 is part of what we need to do when the nested L2 guest exits
8219  * and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12),
8220  * and this function updates it to reflect the changes to the guest state while
8221  * L2 was running (and perhaps made some exits which were handled directly by L0
8222  * without going back to L1), and to reflect the exit reason.
8223  * Note that we do not have to copy here all VMCS fields, just those that
8224  * could have changed by the L2 guest or the exit - i.e., the guest-state and
8225  * exit-information fields only. Other fields are modified by L1 with VMWRITE,
8226  * which already writes to vmcs12 directly.
8227  */
8228 static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
8229                            u32 exit_reason, u32 exit_intr_info,
8230                            unsigned long exit_qualification)
8231 {
8232         /* update guest state fields: */
8233         vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12);
8234         vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12);
8235
8236         kvm_get_dr(vcpu, 7, (unsigned long *)&vmcs12->guest_dr7);
8237         vmcs12->guest_rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
8238         vmcs12->guest_rip = kvm_register_read(vcpu, VCPU_REGS_RIP);
8239         vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS);
8240
8241         vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR);
8242         vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR);
8243         vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR);
8244         vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR);
8245         vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR);
8246         vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR);
8247         vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR);
8248         vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR);
8249         vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT);
8250         vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT);
8251         vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT);
8252         vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT);
8253         vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT);
8254         vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT);
8255         vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT);
8256         vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT);
8257         vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT);
8258         vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT);
8259         vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES);
8260         vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES);
8261         vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES);
8262         vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES);
8263         vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES);
8264         vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES);
8265         vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES);
8266         vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES);
8267         vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE);
8268         vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE);
8269         vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE);
8270         vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE);
8271         vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE);
8272         vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE);
8273         vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE);
8274         vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE);
8275         vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE);
8276         vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE);
8277
8278         vmcs12->guest_interruptibility_info =
8279                 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
8280         vmcs12->guest_pending_dbg_exceptions =
8281                 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);
8282         if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
8283                 vmcs12->guest_activity_state = GUEST_ACTIVITY_HLT;
8284         else
8285                 vmcs12->guest_activity_state = GUEST_ACTIVITY_ACTIVE;
8286
8287         if (nested_cpu_has_preemption_timer(vmcs12)) {
8288                 if (vmcs12->vm_exit_controls &
8289                     VM_EXIT_SAVE_VMX_PREEMPTION_TIMER)
8290                         vmcs12->vmx_preemption_timer_value =
8291                                 vmx_get_preemption_timer_value(vcpu);
8292                 hrtimer_cancel(&to_vmx(vcpu)->nested.preemption_timer);
8293         }
8294
8295         /*
8296          * In some cases (usually, nested EPT), L2 is allowed to change its
8297          * own CR3 without exiting. If it has changed it, we must keep it.
8298          * Of course, if L0 is using shadow page tables, GUEST_CR3 was defined
8299          * by L0, not L1 or L2, so we mustn't unconditionally copy it to vmcs12.
8300          *
8301          * Additionally, restore L2's PDPTR to vmcs12.
8302          */
8303         if (enable_ept) {
8304                 vmcs12->guest_cr3 = vmcs_read64(GUEST_CR3);
8305                 vmcs12->guest_pdptr0 = vmcs_read64(GUEST_PDPTR0);
8306                 vmcs12->guest_pdptr1 = vmcs_read64(GUEST_PDPTR1);
8307                 vmcs12->guest_pdptr2 = vmcs_read64(GUEST_PDPTR2);
8308                 vmcs12->guest_pdptr3 = vmcs_read64(GUEST_PDPTR3);
8309         }
8310
8311         vmcs12->vm_entry_controls =
8312                 (vmcs12->vm_entry_controls & ~VM_ENTRY_IA32E_MODE) |
8313                 (vm_entry_controls_get(to_vmx(vcpu)) & VM_ENTRY_IA32E_MODE);
8314
8315         /* TODO: These cannot have changed unless we have MSR bitmaps and
8316          * the relevant bit asks not to trap the change */
8317         vmcs12->guest_ia32_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
8318         if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
8319                 vmcs12->guest_ia32_pat = vmcs_read64(GUEST_IA32_PAT);
8320         if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_EFER)
8321                 vmcs12->guest_ia32_efer = vcpu->arch.efer;
8322         vmcs12->guest_sysenter_cs = vmcs_read32(GUEST_SYSENTER_CS);
8323         vmcs12->guest_sysenter_esp = vmcs_readl(GUEST_SYSENTER_ESP);
8324         vmcs12->guest_sysenter_eip = vmcs_readl(GUEST_SYSENTER_EIP);
8325
8326         /* update exit information fields: */
8327
8328         vmcs12->vm_exit_reason = exit_reason;
8329         vmcs12->exit_qualification = exit_qualification;
8330
8331         vmcs12->vm_exit_intr_info = exit_intr_info;
8332         if ((vmcs12->vm_exit_intr_info &
8333              (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) ==
8334             (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK))
8335                 vmcs12->vm_exit_intr_error_code =
8336                         vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
8337         vmcs12->idt_vectoring_info_field = 0;
8338         vmcs12->vm_exit_instruction_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
8339         vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
8340
8341         if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY)) {
8342                 /* vm_entry_intr_info_field is cleared on exit. Emulate this
8343                  * instead of reading the real value. */
8344                 vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK;
8345
8346                 /*
8347                  * Transfer the event that L0 or L1 may wanted to inject into
8348                  * L2 to IDT_VECTORING_INFO_FIELD.
8349                  */
8350                 vmcs12_save_pending_event(vcpu, vmcs12);
8351         }
8352
8353         /*
8354          * Drop what we picked up for L2 via vmx_complete_interrupts. It is
8355          * preserved above and would only end up incorrectly in L1.
8356          */
8357         vcpu->arch.nmi_injected = false;
8358         kvm_clear_exception_queue(vcpu);
8359         kvm_clear_interrupt_queue(vcpu);
8360 }
8361
8362 /*
8363  * A part of what we need to when the nested L2 guest exits and we want to
8364  * run its L1 parent, is to reset L1's guest state to the host state specified
8365  * in vmcs12.
8366  * This function is to be called not only on normal nested exit, but also on
8367  * a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry
8368  * Failures During or After Loading Guest State").
8369  * This function should be called when the active VMCS is L1's (vmcs01).
8370  */
8371 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
8372                                    struct vmcs12 *vmcs12)
8373 {
8374         struct kvm_segment seg;
8375
8376         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
8377                 vcpu->arch.efer = vmcs12->host_ia32_efer;
8378         else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
8379                 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
8380         else
8381                 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
8382         vmx_set_efer(vcpu, vcpu->arch.efer);
8383
8384         kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp);
8385         kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip);
8386         vmx_set_rflags(vcpu, X86_EFLAGS_FIXED);
8387         /*
8388          * Note that calling vmx_set_cr0 is important, even if cr0 hasn't
8389          * actually changed, because it depends on the current state of
8390          * fpu_active (which may have changed).
8391          * Note that vmx_set_cr0 refers to efer set above.
8392          */
8393         vmx_set_cr0(vcpu, vmcs12->host_cr0);
8394         /*
8395          * If we did fpu_activate()/fpu_deactivate() during L2's run, we need
8396          * to apply the same changes to L1's vmcs. We just set cr0 correctly,
8397          * but we also need to update cr0_guest_host_mask and exception_bitmap.
8398          */
8399         update_exception_bitmap(vcpu);
8400         vcpu->arch.cr0_guest_owned_bits = (vcpu->fpu_active ? X86_CR0_TS : 0);
8401         vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
8402
8403         /*
8404          * Note that CR4_GUEST_HOST_MASK is already set in the original vmcs01
8405          * (KVM doesn't change it)- no reason to call set_cr4_guest_host_mask();
8406          */
8407         vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
8408         kvm_set_cr4(vcpu, vmcs12->host_cr4);
8409
8410         nested_ept_uninit_mmu_context(vcpu);
8411
8412         kvm_set_cr3(vcpu, vmcs12->host_cr3);
8413         kvm_mmu_reset_context(vcpu);
8414
8415         if (!enable_ept)
8416                 vcpu->arch.walk_mmu->inject_page_fault = kvm_inject_page_fault;
8417
8418         if (enable_vpid) {
8419                 /*
8420                  * Trivially support vpid by letting L2s share their parent
8421                  * L1's vpid. TODO: move to a more elaborate solution, giving
8422                  * each L2 its own vpid and exposing the vpid feature to L1.
8423                  */
8424                 vmx_flush_tlb(vcpu);
8425         }
8426
8427
8428         vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
8429         vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp);
8430         vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip);
8431         vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base);
8432         vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base);
8433
8434         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) {
8435                 vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat);
8436                 vcpu->arch.pat = vmcs12->host_ia32_pat;
8437         }
8438         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
8439                 vmcs_write64(GUEST_IA32_PERF_GLOBAL_CTRL,
8440                         vmcs12->host_ia32_perf_global_ctrl);
8441
8442         /* Set L1 segment info according to Intel SDM
8443             27.5.2 Loading Host Segment and Descriptor-Table Registers */
8444         seg = (struct kvm_segment) {
8445                 .base = 0,
8446                 .limit = 0xFFFFFFFF,
8447                 .selector = vmcs12->host_cs_selector,
8448                 .type = 11,
8449                 .present = 1,
8450                 .s = 1,
8451                 .g = 1
8452         };
8453         if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
8454                 seg.l = 1;
8455         else
8456                 seg.db = 1;
8457         vmx_set_segment(vcpu, &seg, VCPU_SREG_CS);
8458         seg = (struct kvm_segment) {
8459                 .base = 0,
8460                 .limit = 0xFFFFFFFF,
8461                 .type = 3,
8462                 .present = 1,
8463                 .s = 1,
8464                 .db = 1,
8465                 .g = 1
8466         };
8467         seg.selector = vmcs12->host_ds_selector;
8468         vmx_set_segment(vcpu, &seg, VCPU_SREG_DS);
8469         seg.selector = vmcs12->host_es_selector;
8470         vmx_set_segment(vcpu, &seg, VCPU_SREG_ES);
8471         seg.selector = vmcs12->host_ss_selector;
8472         vmx_set_segment(vcpu, &seg, VCPU_SREG_SS);
8473         seg.selector = vmcs12->host_fs_selector;
8474         seg.base = vmcs12->host_fs_base;
8475         vmx_set_segment(vcpu, &seg, VCPU_SREG_FS);
8476         seg.selector = vmcs12->host_gs_selector;
8477         seg.base = vmcs12->host_gs_base;
8478         vmx_set_segment(vcpu, &seg, VCPU_SREG_GS);
8479         seg = (struct kvm_segment) {
8480                 .base = vmcs12->host_tr_base,
8481                 .limit = 0x67,
8482                 .selector = vmcs12->host_tr_selector,
8483                 .type = 11,
8484                 .present = 1
8485         };
8486         vmx_set_segment(vcpu, &seg, VCPU_SREG_TR);
8487
8488         kvm_set_dr(vcpu, 7, 0x400);
8489         vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
8490 }
8491
8492 /*
8493  * Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
8494  * and modify vmcs12 to make it see what it would expect to see there if
8495  * L2 was its real guest. Must only be called when in L2 (is_guest_mode())
8496  */
8497 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
8498                               u32 exit_intr_info,
8499                               unsigned long exit_qualification)
8500 {
8501         struct vcpu_vmx *vmx = to_vmx(vcpu);
8502         int cpu;
8503         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
8504
8505         /* trying to cancel vmlaunch/vmresume is a bug */
8506         WARN_ON_ONCE(vmx->nested.nested_run_pending);
8507
8508         leave_guest_mode(vcpu);
8509         prepare_vmcs12(vcpu, vmcs12, exit_reason, exit_intr_info,
8510                        exit_qualification);
8511
8512         trace_kvm_nested_vmexit_inject(vmcs12->vm_exit_reason,
8513                                        vmcs12->exit_qualification,
8514                                        vmcs12->idt_vectoring_info_field,
8515                                        vmcs12->vm_exit_intr_info,
8516                                        vmcs12->vm_exit_intr_error_code,
8517                                        KVM_ISA_VMX);
8518
8519         cpu = get_cpu();
8520         vmx->loaded_vmcs = &vmx->vmcs01;
8521         vmx_vcpu_put(vcpu);
8522         vmx_vcpu_load(vcpu, cpu);
8523         vcpu->cpu = cpu;
8524         put_cpu();
8525
8526         vm_entry_controls_init(vmx, vmcs_read32(VM_ENTRY_CONTROLS));
8527         vm_exit_controls_init(vmx, vmcs_read32(VM_EXIT_CONTROLS));
8528         vmx_segment_cache_clear(vmx);
8529
8530         /* if no vmcs02 cache requested, remove the one we used */
8531         if (VMCS02_POOL_SIZE == 0)
8532                 nested_free_vmcs02(vmx, vmx->nested.current_vmptr);
8533
8534         load_vmcs12_host_state(vcpu, vmcs12);
8535
8536         /* Update TSC_OFFSET if TSC was changed while L2 ran */
8537         vmcs_write64(TSC_OFFSET, vmx->nested.vmcs01_tsc_offset);
8538
8539         /* This is needed for same reason as it was needed in prepare_vmcs02 */
8540         vmx->host_rsp = 0;
8541
8542         /* Unpin physical memory we referred to in vmcs02 */
8543         if (vmx->nested.apic_access_page) {
8544                 nested_release_page(vmx->nested.apic_access_page);
8545                 vmx->nested.apic_access_page = 0;
8546         }
8547
8548         /*
8549          * Exiting from L2 to L1, we're now back to L1 which thinks it just
8550          * finished a VMLAUNCH or VMRESUME instruction, so we need to set the
8551          * success or failure flag accordingly.
8552          */
8553         if (unlikely(vmx->fail)) {
8554                 vmx->fail = 0;
8555                 nested_vmx_failValid(vcpu, vmcs_read32(VM_INSTRUCTION_ERROR));
8556         } else
8557                 nested_vmx_succeed(vcpu);
8558         if (enable_shadow_vmcs)
8559                 vmx->nested.sync_shadow_vmcs = true;
8560
8561         /* in case we halted in L2 */
8562         vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
8563 }
8564
8565 /*
8566  * Forcibly leave nested mode in order to be able to reset the VCPU later on.
8567  */
8568 static void vmx_leave_nested(struct kvm_vcpu *vcpu)
8569 {
8570         if (is_guest_mode(vcpu))
8571                 nested_vmx_vmexit(vcpu, -1, 0, 0);
8572         free_nested(to_vmx(vcpu));
8573 }
8574
8575 /*
8576  * L1's failure to enter L2 is a subset of a normal exit, as explained in
8577  * 23.7 "VM-entry failures during or after loading guest state" (this also
8578  * lists the acceptable exit-reason and exit-qualification parameters).
8579  * It should only be called before L2 actually succeeded to run, and when
8580  * vmcs01 is current (it doesn't leave_guest_mode() or switch vmcss).
8581  */
8582 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
8583                         struct vmcs12 *vmcs12,
8584                         u32 reason, unsigned long qualification)
8585 {
8586         load_vmcs12_host_state(vcpu, vmcs12);
8587         vmcs12->vm_exit_reason = reason | VMX_EXIT_REASONS_FAILED_VMENTRY;
8588         vmcs12->exit_qualification = qualification;
8589         nested_vmx_succeed(vcpu);
8590         if (enable_shadow_vmcs)
8591                 to_vmx(vcpu)->nested.sync_shadow_vmcs = true;
8592 }
8593
8594 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
8595                                struct x86_instruction_info *info,
8596                                enum x86_intercept_stage stage)
8597 {
8598         return X86EMUL_CONTINUE;
8599 }
8600
8601 static struct kvm_x86_ops vmx_x86_ops = {
8602         .cpu_has_kvm_support = cpu_has_kvm_support,
8603         .disabled_by_bios = vmx_disabled_by_bios,
8604         .hardware_setup = hardware_setup,
8605         .hardware_unsetup = hardware_unsetup,
8606         .check_processor_compatibility = vmx_check_processor_compat,
8607         .hardware_enable = hardware_enable,
8608         .hardware_disable = hardware_disable,
8609         .cpu_has_accelerated_tpr = report_flexpriority,
8610
8611         .vcpu_create = vmx_create_vcpu,
8612         .vcpu_free = vmx_free_vcpu,
8613         .vcpu_reset = vmx_vcpu_reset,
8614
8615         .prepare_guest_switch = vmx_save_host_state,
8616         .vcpu_load = vmx_vcpu_load,
8617         .vcpu_put = vmx_vcpu_put,
8618
8619         .update_db_bp_intercept = update_exception_bitmap,
8620         .get_msr = vmx_get_msr,
8621         .set_msr = vmx_set_msr,
8622         .get_segment_base = vmx_get_segment_base,
8623         .get_segment = vmx_get_segment,
8624         .set_segment = vmx_set_segment,
8625         .get_cpl = vmx_get_cpl,
8626         .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
8627         .decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
8628         .decache_cr3 = vmx_decache_cr3,
8629         .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
8630         .set_cr0 = vmx_set_cr0,
8631         .set_cr3 = vmx_set_cr3,
8632         .set_cr4 = vmx_set_cr4,
8633         .set_efer = vmx_set_efer,
8634         .get_idt = vmx_get_idt,
8635         .set_idt = vmx_set_idt,
8636         .get_gdt = vmx_get_gdt,
8637         .set_gdt = vmx_set_gdt,
8638         .get_dr6 = vmx_get_dr6,
8639         .set_dr6 = vmx_set_dr6,
8640         .set_dr7 = vmx_set_dr7,
8641         .cache_reg = vmx_cache_reg,
8642         .get_rflags = vmx_get_rflags,
8643         .set_rflags = vmx_set_rflags,
8644         .fpu_activate = vmx_fpu_activate,
8645         .fpu_deactivate = vmx_fpu_deactivate,
8646
8647         .tlb_flush = vmx_flush_tlb,
8648
8649         .run = vmx_vcpu_run,
8650         .handle_exit = vmx_handle_exit,
8651         .skip_emulated_instruction = skip_emulated_instruction,
8652         .set_interrupt_shadow = vmx_set_interrupt_shadow,
8653         .get_interrupt_shadow = vmx_get_interrupt_shadow,
8654         .patch_hypercall = vmx_patch_hypercall,
8655         .set_irq = vmx_inject_irq,
8656         .set_nmi = vmx_inject_nmi,
8657         .queue_exception = vmx_queue_exception,
8658         .cancel_injection = vmx_cancel_injection,
8659         .interrupt_allowed = vmx_interrupt_allowed,
8660         .nmi_allowed = vmx_nmi_allowed,
8661         .get_nmi_mask = vmx_get_nmi_mask,
8662         .set_nmi_mask = vmx_set_nmi_mask,
8663         .enable_nmi_window = enable_nmi_window,
8664         .enable_irq_window = enable_irq_window,
8665         .update_cr8_intercept = update_cr8_intercept,
8666         .set_virtual_x2apic_mode = vmx_set_virtual_x2apic_mode,
8667         .vm_has_apicv = vmx_vm_has_apicv,
8668         .load_eoi_exitmap = vmx_load_eoi_exitmap,
8669         .hwapic_irr_update = vmx_hwapic_irr_update,
8670         .hwapic_isr_update = vmx_hwapic_isr_update,
8671         .sync_pir_to_irr = vmx_sync_pir_to_irr,
8672         .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
8673
8674         .set_tss_addr = vmx_set_tss_addr,
8675         .get_tdp_level = get_ept_level,
8676         .get_mt_mask = vmx_get_mt_mask,
8677
8678         .get_exit_info = vmx_get_exit_info,
8679
8680         .get_lpage_level = vmx_get_lpage_level,
8681
8682         .cpuid_update = vmx_cpuid_update,
8683
8684         .rdtscp_supported = vmx_rdtscp_supported,
8685         .invpcid_supported = vmx_invpcid_supported,
8686
8687         .set_supported_cpuid = vmx_set_supported_cpuid,
8688
8689         .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
8690
8691         .set_tsc_khz = vmx_set_tsc_khz,
8692         .read_tsc_offset = vmx_read_tsc_offset,
8693         .write_tsc_offset = vmx_write_tsc_offset,
8694         .adjust_tsc_offset = vmx_adjust_tsc_offset,
8695         .compute_tsc_offset = vmx_compute_tsc_offset,
8696         .read_l1_tsc = vmx_read_l1_tsc,
8697
8698         .set_tdp_cr3 = vmx_set_cr3,
8699
8700         .check_intercept = vmx_check_intercept,
8701         .handle_external_intr = vmx_handle_external_intr,
8702         .mpx_supported = vmx_mpx_supported,
8703
8704         .check_nested_events = vmx_check_nested_events,
8705 };
8706
8707 static int __init vmx_init(void)
8708 {
8709         int r, i, msr;
8710
8711         rdmsrl_safe(MSR_EFER, &host_efer);
8712
8713         for (i = 0; i < NR_VMX_MSR; ++i)
8714                 kvm_define_shared_msr(i, vmx_msr_index[i]);
8715
8716         vmx_io_bitmap_a = (unsigned long *)__get_free_page(GFP_KERNEL);
8717         if (!vmx_io_bitmap_a)
8718                 return -ENOMEM;
8719
8720         r = -ENOMEM;
8721
8722         vmx_io_bitmap_b = (unsigned long *)__get_free_page(GFP_KERNEL);
8723         if (!vmx_io_bitmap_b)
8724                 goto out;
8725
8726         vmx_msr_bitmap_legacy = (unsigned long *)__get_free_page(GFP_KERNEL);
8727         if (!vmx_msr_bitmap_legacy)
8728                 goto out1;
8729
8730         vmx_msr_bitmap_legacy_x2apic =
8731                                 (unsigned long *)__get_free_page(GFP_KERNEL);
8732         if (!vmx_msr_bitmap_legacy_x2apic)
8733                 goto out2;
8734
8735         vmx_msr_bitmap_longmode = (unsigned long *)__get_free_page(GFP_KERNEL);
8736         if (!vmx_msr_bitmap_longmode)
8737                 goto out3;
8738
8739         vmx_msr_bitmap_longmode_x2apic =
8740                                 (unsigned long *)__get_free_page(GFP_KERNEL);
8741         if (!vmx_msr_bitmap_longmode_x2apic)
8742                 goto out4;
8743         vmx_vmread_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);
8744         if (!vmx_vmread_bitmap)
8745                 goto out5;
8746
8747         vmx_vmwrite_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);
8748         if (!vmx_vmwrite_bitmap)
8749                 goto out6;
8750
8751         memset(vmx_vmread_bitmap, 0xff, PAGE_SIZE);
8752         memset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE);
8753         /* shadowed read/write fields */
8754         for (i = 0; i < max_shadow_read_write_fields; i++) {
8755                 clear_bit(shadow_read_write_fields[i], vmx_vmwrite_bitmap);
8756                 clear_bit(shadow_read_write_fields[i], vmx_vmread_bitmap);
8757         }
8758         /* shadowed read only fields */
8759         for (i = 0; i < max_shadow_read_only_fields; i++)
8760                 clear_bit(shadow_read_only_fields[i], vmx_vmread_bitmap);
8761
8762         /*
8763          * Allow direct access to the PC debug port (it is often used for I/O
8764          * delays, but the vmexits simply slow things down).
8765          */
8766         memset(vmx_io_bitmap_a, 0xff, PAGE_SIZE);
8767         clear_bit(0x80, vmx_io_bitmap_a);
8768
8769         memset(vmx_io_bitmap_b, 0xff, PAGE_SIZE);
8770
8771         memset(vmx_msr_bitmap_legacy, 0xff, PAGE_SIZE);
8772         memset(vmx_msr_bitmap_longmode, 0xff, PAGE_SIZE);
8773
8774         set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
8775
8776         r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
8777                      __alignof__(struct vcpu_vmx), THIS_MODULE);
8778         if (r)
8779                 goto out7;
8780
8781 #ifdef CONFIG_KEXEC
8782         rcu_assign_pointer(crash_vmclear_loaded_vmcss,
8783                            crash_vmclear_local_loaded_vmcss);
8784 #endif
8785
8786         vmx_disable_intercept_for_msr(MSR_FS_BASE, false);
8787         vmx_disable_intercept_for_msr(MSR_GS_BASE, false);
8788         vmx_disable_intercept_for_msr(MSR_KERNEL_GS_BASE, true);
8789         vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_CS, false);
8790         vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_ESP, false);
8791         vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_EIP, false);
8792         vmx_disable_intercept_for_msr(MSR_IA32_BNDCFGS, true);
8793
8794         memcpy(vmx_msr_bitmap_legacy_x2apic,
8795                         vmx_msr_bitmap_legacy, PAGE_SIZE);
8796         memcpy(vmx_msr_bitmap_longmode_x2apic,
8797                         vmx_msr_bitmap_longmode, PAGE_SIZE);
8798
8799         if (enable_apicv) {
8800                 for (msr = 0x800; msr <= 0x8ff; msr++)
8801                         vmx_disable_intercept_msr_read_x2apic(msr);
8802
8803                 /* According SDM, in x2apic mode, the whole id reg is used.
8804                  * But in KVM, it only use the highest eight bits. Need to
8805                  * intercept it */
8806                 vmx_enable_intercept_msr_read_x2apic(0x802);
8807                 /* TMCCT */
8808                 vmx_enable_intercept_msr_read_x2apic(0x839);
8809                 /* TPR */
8810                 vmx_disable_intercept_msr_write_x2apic(0x808);
8811                 /* EOI */
8812                 vmx_disable_intercept_msr_write_x2apic(0x80b);
8813                 /* SELF-IPI */
8814                 vmx_disable_intercept_msr_write_x2apic(0x83f);
8815         }
8816
8817         if (enable_ept) {
8818                 kvm_mmu_set_mask_ptes(0ull,
8819                         (enable_ept_ad_bits) ? VMX_EPT_ACCESS_BIT : 0ull,
8820                         (enable_ept_ad_bits) ? VMX_EPT_DIRTY_BIT : 0ull,
8821                         0ull, VMX_EPT_EXECUTABLE_MASK);
8822                 ept_set_mmio_spte_mask();
8823                 kvm_enable_tdp();
8824         } else
8825                 kvm_disable_tdp();
8826
8827         return 0;
8828
8829 out7:
8830         free_page((unsigned long)vmx_vmwrite_bitmap);
8831 out6:
8832         free_page((unsigned long)vmx_vmread_bitmap);
8833 out5:
8834         free_page((unsigned long)vmx_msr_bitmap_longmode_x2apic);
8835 out4:
8836         free_page((unsigned long)vmx_msr_bitmap_longmode);
8837 out3:
8838         free_page((unsigned long)vmx_msr_bitmap_legacy_x2apic);
8839 out2:
8840         free_page((unsigned long)vmx_msr_bitmap_legacy);
8841 out1:
8842         free_page((unsigned long)vmx_io_bitmap_b);
8843 out:
8844         free_page((unsigned long)vmx_io_bitmap_a);
8845         return r;
8846 }
8847
8848 static void __exit vmx_exit(void)
8849 {
8850         free_page((unsigned long)vmx_msr_bitmap_legacy_x2apic);
8851         free_page((unsigned long)vmx_msr_bitmap_longmode_x2apic);
8852         free_page((unsigned long)vmx_msr_bitmap_legacy);
8853         free_page((unsigned long)vmx_msr_bitmap_longmode);
8854         free_page((unsigned long)vmx_io_bitmap_b);
8855         free_page((unsigned long)vmx_io_bitmap_a);
8856         free_page((unsigned long)vmx_vmwrite_bitmap);
8857         free_page((unsigned long)vmx_vmread_bitmap);
8858
8859 #ifdef CONFIG_KEXEC
8860         rcu_assign_pointer(crash_vmclear_loaded_vmcss, NULL);
8861         synchronize_rcu();
8862 #endif
8863
8864         kvm_exit();
8865 }
8866
8867 module_init(vmx_init)
8868 module_exit(vmx_exit)