KVM: vVMX: signal failure for nested VMEntry if emulation_required
[linux-2.6-microblaze.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 #include "lapic.h"
23
24 #include <linux/kvm_host.h>
25 #include <linux/module.h>
26 #include <linux/kernel.h>
27 #include <linux/mm.h>
28 #include <linux/highmem.h>
29 #include <linux/sched.h>
30 #include <linux/moduleparam.h>
31 #include <linux/mod_devicetable.h>
32 #include <linux/trace_events.h>
33 #include <linux/slab.h>
34 #include <linux/tboot.h>
35 #include <linux/hrtimer.h>
36 #include <linux/frame.h>
37 #include <linux/nospec.h>
38 #include "kvm_cache_regs.h"
39 #include "x86.h"
40
41 #include <asm/cpu.h>
42 #include <asm/io.h>
43 #include <asm/desc.h>
44 #include <asm/vmx.h>
45 #include <asm/virtext.h>
46 #include <asm/mce.h>
47 #include <asm/fpu/internal.h>
48 #include <asm/perf_event.h>
49 #include <asm/debugreg.h>
50 #include <asm/kexec.h>
51 #include <asm/apic.h>
52 #include <asm/irq_remapping.h>
53 #include <asm/mmu_context.h>
54 #include <asm/microcode.h>
55 #include <asm/nospec-branch.h>
56
57 #include "trace.h"
58 #include "pmu.h"
59
60 #define __ex(x) __kvm_handle_fault_on_reboot(x)
61 #define __ex_clear(x, reg) \
62         ____kvm_handle_fault_on_reboot(x, "xor " reg " , " reg)
63
64 MODULE_AUTHOR("Qumranet");
65 MODULE_LICENSE("GPL");
66
67 static const struct x86_cpu_id vmx_cpu_id[] = {
68         X86_FEATURE_MATCH(X86_FEATURE_VMX),
69         {}
70 };
71 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
72
73 static bool __read_mostly enable_vpid = 1;
74 module_param_named(vpid, enable_vpid, bool, 0444);
75
76 static bool __read_mostly enable_vnmi = 1;
77 module_param_named(vnmi, enable_vnmi, bool, S_IRUGO);
78
79 static bool __read_mostly flexpriority_enabled = 1;
80 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
81
82 static bool __read_mostly enable_ept = 1;
83 module_param_named(ept, enable_ept, bool, S_IRUGO);
84
85 static bool __read_mostly enable_unrestricted_guest = 1;
86 module_param_named(unrestricted_guest,
87                         enable_unrestricted_guest, bool, S_IRUGO);
88
89 static bool __read_mostly enable_ept_ad_bits = 1;
90 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
91
92 static bool __read_mostly emulate_invalid_guest_state = true;
93 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
94
95 static bool __read_mostly fasteoi = 1;
96 module_param(fasteoi, bool, S_IRUGO);
97
98 static bool __read_mostly enable_apicv = 1;
99 module_param(enable_apicv, bool, S_IRUGO);
100
101 static bool __read_mostly enable_shadow_vmcs = 1;
102 module_param_named(enable_shadow_vmcs, enable_shadow_vmcs, bool, S_IRUGO);
103 /*
104  * If nested=1, nested virtualization is supported, i.e., guests may use
105  * VMX and be a hypervisor for its own guests. If nested=0, guests may not
106  * use VMX instructions.
107  */
108 static bool __read_mostly nested = 0;
109 module_param(nested, bool, S_IRUGO);
110
111 static u64 __read_mostly host_xss;
112
113 static bool __read_mostly enable_pml = 1;
114 module_param_named(pml, enable_pml, bool, S_IRUGO);
115
116 #define MSR_TYPE_R      1
117 #define MSR_TYPE_W      2
118 #define MSR_TYPE_RW     3
119
120 #define MSR_BITMAP_MODE_X2APIC          1
121 #define MSR_BITMAP_MODE_X2APIC_APICV    2
122 #define MSR_BITMAP_MODE_LM              4
123
124 #define KVM_VMX_TSC_MULTIPLIER_MAX     0xffffffffffffffffULL
125
126 /* Guest_tsc -> host_tsc conversion requires 64-bit division.  */
127 static int __read_mostly cpu_preemption_timer_multi;
128 static bool __read_mostly enable_preemption_timer = 1;
129 #ifdef CONFIG_X86_64
130 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
131 #endif
132
133 #define KVM_GUEST_CR0_MASK (X86_CR0_NW | X86_CR0_CD)
134 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE
135 #define KVM_VM_CR0_ALWAYS_ON                            \
136         (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST |      \
137          X86_CR0_WP | X86_CR0_PG | X86_CR0_PE)
138 #define KVM_CR4_GUEST_OWNED_BITS                                      \
139         (X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR      \
140          | X86_CR4_OSXMMEXCPT | X86_CR4_LA57 | X86_CR4_TSD)
141
142 #define KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR4_VMXE
143 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
144 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
145
146 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
147
148 #define VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE 5
149
150 /*
151  * Hyper-V requires all of these, so mark them as supported even though
152  * they are just treated the same as all-context.
153  */
154 #define VMX_VPID_EXTENT_SUPPORTED_MASK          \
155         (VMX_VPID_EXTENT_INDIVIDUAL_ADDR_BIT |  \
156         VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT |    \
157         VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT |    \
158         VMX_VPID_EXTENT_SINGLE_NON_GLOBAL_BIT)
159
160 /*
161  * These 2 parameters are used to config the controls for Pause-Loop Exiting:
162  * ple_gap:    upper bound on the amount of time between two successive
163  *             executions of PAUSE in a loop. Also indicate if ple enabled.
164  *             According to test, this time is usually smaller than 128 cycles.
165  * ple_window: upper bound on the amount of time a guest is allowed to execute
166  *             in a PAUSE loop. Tests indicate that most spinlocks are held for
167  *             less than 2^12 cycles
168  * Time is measured based on a counter that runs at the same rate as the TSC,
169  * refer SDM volume 3b section 21.6.13 & 22.1.3.
170  */
171 #define KVM_VMX_DEFAULT_PLE_GAP           128
172 #define KVM_VMX_DEFAULT_PLE_WINDOW        4096
173 #define KVM_VMX_DEFAULT_PLE_WINDOW_GROW   2
174 #define KVM_VMX_DEFAULT_PLE_WINDOW_SHRINK 0
175 #define KVM_VMX_DEFAULT_PLE_WINDOW_MAX    \
176                 INT_MAX / KVM_VMX_DEFAULT_PLE_WINDOW_GROW
177
178 static int ple_gap = KVM_VMX_DEFAULT_PLE_GAP;
179 module_param(ple_gap, int, S_IRUGO);
180
181 static int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
182 module_param(ple_window, int, S_IRUGO);
183
184 /* Default doubles per-vcpu window every exit. */
185 static int ple_window_grow = KVM_VMX_DEFAULT_PLE_WINDOW_GROW;
186 module_param(ple_window_grow, int, S_IRUGO);
187
188 /* Default resets per-vcpu window every exit to ple_window. */
189 static int ple_window_shrink = KVM_VMX_DEFAULT_PLE_WINDOW_SHRINK;
190 module_param(ple_window_shrink, int, S_IRUGO);
191
192 /* Default is to compute the maximum so we can never overflow. */
193 static int ple_window_actual_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
194 static int ple_window_max        = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
195 module_param(ple_window_max, int, S_IRUGO);
196
197 extern const ulong vmx_return;
198
199 #define NR_AUTOLOAD_MSRS 8
200
201 struct vmcs {
202         u32 revision_id;
203         u32 abort;
204         char data[0];
205 };
206
207 /*
208  * Track a VMCS that may be loaded on a certain CPU. If it is (cpu!=-1), also
209  * remember whether it was VMLAUNCHed, and maintain a linked list of all VMCSs
210  * loaded on this CPU (so we can clear them if the CPU goes down).
211  */
212 struct loaded_vmcs {
213         struct vmcs *vmcs;
214         struct vmcs *shadow_vmcs;
215         int cpu;
216         bool launched;
217         bool nmi_known_unmasked;
218         unsigned long vmcs_host_cr3;    /* May not match real cr3 */
219         unsigned long vmcs_host_cr4;    /* May not match real cr4 */
220         /* Support for vnmi-less CPUs */
221         int soft_vnmi_blocked;
222         ktime_t entry_time;
223         s64 vnmi_blocked_time;
224         unsigned long *msr_bitmap;
225         struct list_head loaded_vmcss_on_cpu_link;
226 };
227
228 struct shared_msr_entry {
229         unsigned index;
230         u64 data;
231         u64 mask;
232 };
233
234 /*
235  * struct vmcs12 describes the state that our guest hypervisor (L1) keeps for a
236  * single nested guest (L2), hence the name vmcs12. Any VMX implementation has
237  * a VMCS structure, and vmcs12 is our emulated VMX's VMCS. This structure is
238  * stored in guest memory specified by VMPTRLD, but is opaque to the guest,
239  * which must access it using VMREAD/VMWRITE/VMCLEAR instructions.
240  * More than one of these structures may exist, if L1 runs multiple L2 guests.
241  * nested_vmx_run() will use the data here to build the vmcs02: a VMCS for the
242  * underlying hardware which will be used to run L2.
243  * This structure is packed to ensure that its layout is identical across
244  * machines (necessary for live migration).
245  * If there are changes in this struct, VMCS12_REVISION must be changed.
246  */
247 typedef u64 natural_width;
248 struct __packed vmcs12 {
249         /* According to the Intel spec, a VMCS region must start with the
250          * following two fields. Then follow implementation-specific data.
251          */
252         u32 revision_id;
253         u32 abort;
254
255         u32 launch_state; /* set to 0 by VMCLEAR, to 1 by VMLAUNCH */
256         u32 padding[7]; /* room for future expansion */
257
258         u64 io_bitmap_a;
259         u64 io_bitmap_b;
260         u64 msr_bitmap;
261         u64 vm_exit_msr_store_addr;
262         u64 vm_exit_msr_load_addr;
263         u64 vm_entry_msr_load_addr;
264         u64 tsc_offset;
265         u64 virtual_apic_page_addr;
266         u64 apic_access_addr;
267         u64 posted_intr_desc_addr;
268         u64 vm_function_control;
269         u64 ept_pointer;
270         u64 eoi_exit_bitmap0;
271         u64 eoi_exit_bitmap1;
272         u64 eoi_exit_bitmap2;
273         u64 eoi_exit_bitmap3;
274         u64 eptp_list_address;
275         u64 xss_exit_bitmap;
276         u64 guest_physical_address;
277         u64 vmcs_link_pointer;
278         u64 pml_address;
279         u64 guest_ia32_debugctl;
280         u64 guest_ia32_pat;
281         u64 guest_ia32_efer;
282         u64 guest_ia32_perf_global_ctrl;
283         u64 guest_pdptr0;
284         u64 guest_pdptr1;
285         u64 guest_pdptr2;
286         u64 guest_pdptr3;
287         u64 guest_bndcfgs;
288         u64 host_ia32_pat;
289         u64 host_ia32_efer;
290         u64 host_ia32_perf_global_ctrl;
291         u64 padding64[8]; /* room for future expansion */
292         /*
293          * To allow migration of L1 (complete with its L2 guests) between
294          * machines of different natural widths (32 or 64 bit), we cannot have
295          * unsigned long fields with no explict size. We use u64 (aliased
296          * natural_width) instead. Luckily, x86 is little-endian.
297          */
298         natural_width cr0_guest_host_mask;
299         natural_width cr4_guest_host_mask;
300         natural_width cr0_read_shadow;
301         natural_width cr4_read_shadow;
302         natural_width cr3_target_value0;
303         natural_width cr3_target_value1;
304         natural_width cr3_target_value2;
305         natural_width cr3_target_value3;
306         natural_width exit_qualification;
307         natural_width guest_linear_address;
308         natural_width guest_cr0;
309         natural_width guest_cr3;
310         natural_width guest_cr4;
311         natural_width guest_es_base;
312         natural_width guest_cs_base;
313         natural_width guest_ss_base;
314         natural_width guest_ds_base;
315         natural_width guest_fs_base;
316         natural_width guest_gs_base;
317         natural_width guest_ldtr_base;
318         natural_width guest_tr_base;
319         natural_width guest_gdtr_base;
320         natural_width guest_idtr_base;
321         natural_width guest_dr7;
322         natural_width guest_rsp;
323         natural_width guest_rip;
324         natural_width guest_rflags;
325         natural_width guest_pending_dbg_exceptions;
326         natural_width guest_sysenter_esp;
327         natural_width guest_sysenter_eip;
328         natural_width host_cr0;
329         natural_width host_cr3;
330         natural_width host_cr4;
331         natural_width host_fs_base;
332         natural_width host_gs_base;
333         natural_width host_tr_base;
334         natural_width host_gdtr_base;
335         natural_width host_idtr_base;
336         natural_width host_ia32_sysenter_esp;
337         natural_width host_ia32_sysenter_eip;
338         natural_width host_rsp;
339         natural_width host_rip;
340         natural_width paddingl[8]; /* room for future expansion */
341         u32 pin_based_vm_exec_control;
342         u32 cpu_based_vm_exec_control;
343         u32 exception_bitmap;
344         u32 page_fault_error_code_mask;
345         u32 page_fault_error_code_match;
346         u32 cr3_target_count;
347         u32 vm_exit_controls;
348         u32 vm_exit_msr_store_count;
349         u32 vm_exit_msr_load_count;
350         u32 vm_entry_controls;
351         u32 vm_entry_msr_load_count;
352         u32 vm_entry_intr_info_field;
353         u32 vm_entry_exception_error_code;
354         u32 vm_entry_instruction_len;
355         u32 tpr_threshold;
356         u32 secondary_vm_exec_control;
357         u32 vm_instruction_error;
358         u32 vm_exit_reason;
359         u32 vm_exit_intr_info;
360         u32 vm_exit_intr_error_code;
361         u32 idt_vectoring_info_field;
362         u32 idt_vectoring_error_code;
363         u32 vm_exit_instruction_len;
364         u32 vmx_instruction_info;
365         u32 guest_es_limit;
366         u32 guest_cs_limit;
367         u32 guest_ss_limit;
368         u32 guest_ds_limit;
369         u32 guest_fs_limit;
370         u32 guest_gs_limit;
371         u32 guest_ldtr_limit;
372         u32 guest_tr_limit;
373         u32 guest_gdtr_limit;
374         u32 guest_idtr_limit;
375         u32 guest_es_ar_bytes;
376         u32 guest_cs_ar_bytes;
377         u32 guest_ss_ar_bytes;
378         u32 guest_ds_ar_bytes;
379         u32 guest_fs_ar_bytes;
380         u32 guest_gs_ar_bytes;
381         u32 guest_ldtr_ar_bytes;
382         u32 guest_tr_ar_bytes;
383         u32 guest_interruptibility_info;
384         u32 guest_activity_state;
385         u32 guest_sysenter_cs;
386         u32 host_ia32_sysenter_cs;
387         u32 vmx_preemption_timer_value;
388         u32 padding32[7]; /* room for future expansion */
389         u16 virtual_processor_id;
390         u16 posted_intr_nv;
391         u16 guest_es_selector;
392         u16 guest_cs_selector;
393         u16 guest_ss_selector;
394         u16 guest_ds_selector;
395         u16 guest_fs_selector;
396         u16 guest_gs_selector;
397         u16 guest_ldtr_selector;
398         u16 guest_tr_selector;
399         u16 guest_intr_status;
400         u16 guest_pml_index;
401         u16 host_es_selector;
402         u16 host_cs_selector;
403         u16 host_ss_selector;
404         u16 host_ds_selector;
405         u16 host_fs_selector;
406         u16 host_gs_selector;
407         u16 host_tr_selector;
408 };
409
410 /*
411  * VMCS12_REVISION is an arbitrary id that should be changed if the content or
412  * layout of struct vmcs12 is changed. MSR_IA32_VMX_BASIC returns this id, and
413  * VMPTRLD verifies that the VMCS region that L1 is loading contains this id.
414  */
415 #define VMCS12_REVISION 0x11e57ed0
416
417 /*
418  * VMCS12_SIZE is the number of bytes L1 should allocate for the VMXON region
419  * and any VMCS region. Although only sizeof(struct vmcs12) are used by the
420  * current implementation, 4K are reserved to avoid future complications.
421  */
422 #define VMCS12_SIZE 0x1000
423
424 /*
425  * VMCS12_MAX_FIELD_INDEX is the highest index value used in any
426  * supported VMCS12 field encoding.
427  */
428 #define VMCS12_MAX_FIELD_INDEX 0x17
429
430 struct nested_vmx_msrs {
431         /*
432          * We only store the "true" versions of the VMX capability MSRs. We
433          * generate the "non-true" versions by setting the must-be-1 bits
434          * according to the SDM.
435          */
436         u32 procbased_ctls_low;
437         u32 procbased_ctls_high;
438         u32 secondary_ctls_low;
439         u32 secondary_ctls_high;
440         u32 pinbased_ctls_low;
441         u32 pinbased_ctls_high;
442         u32 exit_ctls_low;
443         u32 exit_ctls_high;
444         u32 entry_ctls_low;
445         u32 entry_ctls_high;
446         u32 misc_low;
447         u32 misc_high;
448         u32 ept_caps;
449         u32 vpid_caps;
450         u64 basic;
451         u64 cr0_fixed0;
452         u64 cr0_fixed1;
453         u64 cr4_fixed0;
454         u64 cr4_fixed1;
455         u64 vmcs_enum;
456         u64 vmfunc_controls;
457 };
458
459 /*
460  * The nested_vmx structure is part of vcpu_vmx, and holds information we need
461  * for correct emulation of VMX (i.e., nested VMX) on this vcpu.
462  */
463 struct nested_vmx {
464         /* Has the level1 guest done vmxon? */
465         bool vmxon;
466         gpa_t vmxon_ptr;
467         bool pml_full;
468
469         /* The guest-physical address of the current VMCS L1 keeps for L2 */
470         gpa_t current_vmptr;
471         /*
472          * Cache of the guest's VMCS, existing outside of guest memory.
473          * Loaded from guest memory during VMPTRLD. Flushed to guest
474          * memory during VMCLEAR and VMPTRLD.
475          */
476         struct vmcs12 *cached_vmcs12;
477         /*
478          * Indicates if the shadow vmcs must be updated with the
479          * data hold by vmcs12
480          */
481         bool sync_shadow_vmcs;
482         bool dirty_vmcs12;
483
484         bool change_vmcs01_virtual_x2apic_mode;
485         /* L2 must run next, and mustn't decide to exit to L1. */
486         bool nested_run_pending;
487
488         struct loaded_vmcs vmcs02;
489
490         /*
491          * Guest pages referred to in the vmcs02 with host-physical
492          * pointers, so we must keep them pinned while L2 runs.
493          */
494         struct page *apic_access_page;
495         struct page *virtual_apic_page;
496         struct page *pi_desc_page;
497         struct pi_desc *pi_desc;
498         bool pi_pending;
499         u16 posted_intr_nv;
500
501         struct hrtimer preemption_timer;
502         bool preemption_timer_expired;
503
504         /* to migrate it to L2 if VM_ENTRY_LOAD_DEBUG_CONTROLS is off */
505         u64 vmcs01_debugctl;
506
507         u16 vpid02;
508         u16 last_vpid;
509
510         struct nested_vmx_msrs msrs;
511
512         /* SMM related state */
513         struct {
514                 /* in VMX operation on SMM entry? */
515                 bool vmxon;
516                 /* in guest mode on SMM entry? */
517                 bool guest_mode;
518         } smm;
519 };
520
521 #define POSTED_INTR_ON  0
522 #define POSTED_INTR_SN  1
523
524 /* Posted-Interrupt Descriptor */
525 struct pi_desc {
526         u32 pir[8];     /* Posted interrupt requested */
527         union {
528                 struct {
529                                 /* bit 256 - Outstanding Notification */
530                         u16     on      : 1,
531                                 /* bit 257 - Suppress Notification */
532                                 sn      : 1,
533                                 /* bit 271:258 - Reserved */
534                                 rsvd_1  : 14;
535                                 /* bit 279:272 - Notification Vector */
536                         u8      nv;
537                                 /* bit 287:280 - Reserved */
538                         u8      rsvd_2;
539                                 /* bit 319:288 - Notification Destination */
540                         u32     ndst;
541                 };
542                 u64 control;
543         };
544         u32 rsvd[6];
545 } __aligned(64);
546
547 static bool pi_test_and_set_on(struct pi_desc *pi_desc)
548 {
549         return test_and_set_bit(POSTED_INTR_ON,
550                         (unsigned long *)&pi_desc->control);
551 }
552
553 static bool pi_test_and_clear_on(struct pi_desc *pi_desc)
554 {
555         return test_and_clear_bit(POSTED_INTR_ON,
556                         (unsigned long *)&pi_desc->control);
557 }
558
559 static int pi_test_and_set_pir(int vector, struct pi_desc *pi_desc)
560 {
561         return test_and_set_bit(vector, (unsigned long *)pi_desc->pir);
562 }
563
564 static inline void pi_clear_sn(struct pi_desc *pi_desc)
565 {
566         return clear_bit(POSTED_INTR_SN,
567                         (unsigned long *)&pi_desc->control);
568 }
569
570 static inline void pi_set_sn(struct pi_desc *pi_desc)
571 {
572         return set_bit(POSTED_INTR_SN,
573                         (unsigned long *)&pi_desc->control);
574 }
575
576 static inline void pi_clear_on(struct pi_desc *pi_desc)
577 {
578         clear_bit(POSTED_INTR_ON,
579                   (unsigned long *)&pi_desc->control);
580 }
581
582 static inline int pi_test_on(struct pi_desc *pi_desc)
583 {
584         return test_bit(POSTED_INTR_ON,
585                         (unsigned long *)&pi_desc->control);
586 }
587
588 static inline int pi_test_sn(struct pi_desc *pi_desc)
589 {
590         return test_bit(POSTED_INTR_SN,
591                         (unsigned long *)&pi_desc->control);
592 }
593
594 struct vcpu_vmx {
595         struct kvm_vcpu       vcpu;
596         unsigned long         host_rsp;
597         u8                    fail;
598         u8                    msr_bitmap_mode;
599         u32                   exit_intr_info;
600         u32                   idt_vectoring_info;
601         ulong                 rflags;
602         struct shared_msr_entry *guest_msrs;
603         int                   nmsrs;
604         int                   save_nmsrs;
605         unsigned long         host_idt_base;
606 #ifdef CONFIG_X86_64
607         u64                   msr_host_kernel_gs_base;
608         u64                   msr_guest_kernel_gs_base;
609 #endif
610
611         u64                   arch_capabilities;
612         u64                   spec_ctrl;
613
614         u32 vm_entry_controls_shadow;
615         u32 vm_exit_controls_shadow;
616         u32 secondary_exec_control;
617
618         /*
619          * loaded_vmcs points to the VMCS currently used in this vcpu. For a
620          * non-nested (L1) guest, it always points to vmcs01. For a nested
621          * guest (L2), it points to a different VMCS.
622          */
623         struct loaded_vmcs    vmcs01;
624         struct loaded_vmcs   *loaded_vmcs;
625         bool                  __launched; /* temporary, used in vmx_vcpu_run */
626         struct msr_autoload {
627                 unsigned nr;
628                 struct vmx_msr_entry guest[NR_AUTOLOAD_MSRS];
629                 struct vmx_msr_entry host[NR_AUTOLOAD_MSRS];
630         } msr_autoload;
631         struct {
632                 int           loaded;
633                 u16           fs_sel, gs_sel, ldt_sel;
634 #ifdef CONFIG_X86_64
635                 u16           ds_sel, es_sel;
636 #endif
637                 int           gs_ldt_reload_needed;
638                 int           fs_reload_needed;
639                 u64           msr_host_bndcfgs;
640         } host_state;
641         struct {
642                 int vm86_active;
643                 ulong save_rflags;
644                 struct kvm_segment segs[8];
645         } rmode;
646         struct {
647                 u32 bitmask; /* 4 bits per segment (1 bit per field) */
648                 struct kvm_save_segment {
649                         u16 selector;
650                         unsigned long base;
651                         u32 limit;
652                         u32 ar;
653                 } seg[8];
654         } segment_cache;
655         int vpid;
656         bool emulation_required;
657
658         u32 exit_reason;
659
660         /* Posted interrupt descriptor */
661         struct pi_desc pi_desc;
662
663         /* Support for a guest hypervisor (nested VMX) */
664         struct nested_vmx nested;
665
666         /* Dynamic PLE window. */
667         int ple_window;
668         bool ple_window_dirty;
669
670         /* Support for PML */
671 #define PML_ENTITY_NUM          512
672         struct page *pml_pg;
673
674         /* apic deadline value in host tsc */
675         u64 hv_deadline_tsc;
676
677         u64 current_tsc_ratio;
678
679         u32 host_pkru;
680
681         unsigned long host_debugctlmsr;
682
683         /*
684          * Only bits masked by msr_ia32_feature_control_valid_bits can be set in
685          * msr_ia32_feature_control. FEATURE_CONTROL_LOCKED is always included
686          * in msr_ia32_feature_control_valid_bits.
687          */
688         u64 msr_ia32_feature_control;
689         u64 msr_ia32_feature_control_valid_bits;
690 };
691
692 enum segment_cache_field {
693         SEG_FIELD_SEL = 0,
694         SEG_FIELD_BASE = 1,
695         SEG_FIELD_LIMIT = 2,
696         SEG_FIELD_AR = 3,
697
698         SEG_FIELD_NR = 4
699 };
700
701 static inline struct vcpu_vmx *to_vmx(struct kvm_vcpu *vcpu)
702 {
703         return container_of(vcpu, struct vcpu_vmx, vcpu);
704 }
705
706 static struct pi_desc *vcpu_to_pi_desc(struct kvm_vcpu *vcpu)
707 {
708         return &(to_vmx(vcpu)->pi_desc);
709 }
710
711 #define ROL16(val, n) ((u16)(((u16)(val) << (n)) | ((u16)(val) >> (16 - (n)))))
712 #define VMCS12_OFFSET(x) offsetof(struct vmcs12, x)
713 #define FIELD(number, name)     [ROL16(number, 6)] = VMCS12_OFFSET(name)
714 #define FIELD64(number, name)                                           \
715         FIELD(number, name),                                            \
716         [ROL16(number##_HIGH, 6)] = VMCS12_OFFSET(name) + sizeof(u32)
717
718
719 static u16 shadow_read_only_fields[] = {
720 #define SHADOW_FIELD_RO(x) x,
721 #include "vmx_shadow_fields.h"
722 };
723 static int max_shadow_read_only_fields =
724         ARRAY_SIZE(shadow_read_only_fields);
725
726 static u16 shadow_read_write_fields[] = {
727 #define SHADOW_FIELD_RW(x) x,
728 #include "vmx_shadow_fields.h"
729 };
730 static int max_shadow_read_write_fields =
731         ARRAY_SIZE(shadow_read_write_fields);
732
733 static const unsigned short vmcs_field_to_offset_table[] = {
734         FIELD(VIRTUAL_PROCESSOR_ID, virtual_processor_id),
735         FIELD(POSTED_INTR_NV, posted_intr_nv),
736         FIELD(GUEST_ES_SELECTOR, guest_es_selector),
737         FIELD(GUEST_CS_SELECTOR, guest_cs_selector),
738         FIELD(GUEST_SS_SELECTOR, guest_ss_selector),
739         FIELD(GUEST_DS_SELECTOR, guest_ds_selector),
740         FIELD(GUEST_FS_SELECTOR, guest_fs_selector),
741         FIELD(GUEST_GS_SELECTOR, guest_gs_selector),
742         FIELD(GUEST_LDTR_SELECTOR, guest_ldtr_selector),
743         FIELD(GUEST_TR_SELECTOR, guest_tr_selector),
744         FIELD(GUEST_INTR_STATUS, guest_intr_status),
745         FIELD(GUEST_PML_INDEX, guest_pml_index),
746         FIELD(HOST_ES_SELECTOR, host_es_selector),
747         FIELD(HOST_CS_SELECTOR, host_cs_selector),
748         FIELD(HOST_SS_SELECTOR, host_ss_selector),
749         FIELD(HOST_DS_SELECTOR, host_ds_selector),
750         FIELD(HOST_FS_SELECTOR, host_fs_selector),
751         FIELD(HOST_GS_SELECTOR, host_gs_selector),
752         FIELD(HOST_TR_SELECTOR, host_tr_selector),
753         FIELD64(IO_BITMAP_A, io_bitmap_a),
754         FIELD64(IO_BITMAP_B, io_bitmap_b),
755         FIELD64(MSR_BITMAP, msr_bitmap),
756         FIELD64(VM_EXIT_MSR_STORE_ADDR, vm_exit_msr_store_addr),
757         FIELD64(VM_EXIT_MSR_LOAD_ADDR, vm_exit_msr_load_addr),
758         FIELD64(VM_ENTRY_MSR_LOAD_ADDR, vm_entry_msr_load_addr),
759         FIELD64(TSC_OFFSET, tsc_offset),
760         FIELD64(VIRTUAL_APIC_PAGE_ADDR, virtual_apic_page_addr),
761         FIELD64(APIC_ACCESS_ADDR, apic_access_addr),
762         FIELD64(POSTED_INTR_DESC_ADDR, posted_intr_desc_addr),
763         FIELD64(VM_FUNCTION_CONTROL, vm_function_control),
764         FIELD64(EPT_POINTER, ept_pointer),
765         FIELD64(EOI_EXIT_BITMAP0, eoi_exit_bitmap0),
766         FIELD64(EOI_EXIT_BITMAP1, eoi_exit_bitmap1),
767         FIELD64(EOI_EXIT_BITMAP2, eoi_exit_bitmap2),
768         FIELD64(EOI_EXIT_BITMAP3, eoi_exit_bitmap3),
769         FIELD64(EPTP_LIST_ADDRESS, eptp_list_address),
770         FIELD64(XSS_EXIT_BITMAP, xss_exit_bitmap),
771         FIELD64(GUEST_PHYSICAL_ADDRESS, guest_physical_address),
772         FIELD64(VMCS_LINK_POINTER, vmcs_link_pointer),
773         FIELD64(PML_ADDRESS, pml_address),
774         FIELD64(GUEST_IA32_DEBUGCTL, guest_ia32_debugctl),
775         FIELD64(GUEST_IA32_PAT, guest_ia32_pat),
776         FIELD64(GUEST_IA32_EFER, guest_ia32_efer),
777         FIELD64(GUEST_IA32_PERF_GLOBAL_CTRL, guest_ia32_perf_global_ctrl),
778         FIELD64(GUEST_PDPTR0, guest_pdptr0),
779         FIELD64(GUEST_PDPTR1, guest_pdptr1),
780         FIELD64(GUEST_PDPTR2, guest_pdptr2),
781         FIELD64(GUEST_PDPTR3, guest_pdptr3),
782         FIELD64(GUEST_BNDCFGS, guest_bndcfgs),
783         FIELD64(HOST_IA32_PAT, host_ia32_pat),
784         FIELD64(HOST_IA32_EFER, host_ia32_efer),
785         FIELD64(HOST_IA32_PERF_GLOBAL_CTRL, host_ia32_perf_global_ctrl),
786         FIELD(PIN_BASED_VM_EXEC_CONTROL, pin_based_vm_exec_control),
787         FIELD(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control),
788         FIELD(EXCEPTION_BITMAP, exception_bitmap),
789         FIELD(PAGE_FAULT_ERROR_CODE_MASK, page_fault_error_code_mask),
790         FIELD(PAGE_FAULT_ERROR_CODE_MATCH, page_fault_error_code_match),
791         FIELD(CR3_TARGET_COUNT, cr3_target_count),
792         FIELD(VM_EXIT_CONTROLS, vm_exit_controls),
793         FIELD(VM_EXIT_MSR_STORE_COUNT, vm_exit_msr_store_count),
794         FIELD(VM_EXIT_MSR_LOAD_COUNT, vm_exit_msr_load_count),
795         FIELD(VM_ENTRY_CONTROLS, vm_entry_controls),
796         FIELD(VM_ENTRY_MSR_LOAD_COUNT, vm_entry_msr_load_count),
797         FIELD(VM_ENTRY_INTR_INFO_FIELD, vm_entry_intr_info_field),
798         FIELD(VM_ENTRY_EXCEPTION_ERROR_CODE, vm_entry_exception_error_code),
799         FIELD(VM_ENTRY_INSTRUCTION_LEN, vm_entry_instruction_len),
800         FIELD(TPR_THRESHOLD, tpr_threshold),
801         FIELD(SECONDARY_VM_EXEC_CONTROL, secondary_vm_exec_control),
802         FIELD(VM_INSTRUCTION_ERROR, vm_instruction_error),
803         FIELD(VM_EXIT_REASON, vm_exit_reason),
804         FIELD(VM_EXIT_INTR_INFO, vm_exit_intr_info),
805         FIELD(VM_EXIT_INTR_ERROR_CODE, vm_exit_intr_error_code),
806         FIELD(IDT_VECTORING_INFO_FIELD, idt_vectoring_info_field),
807         FIELD(IDT_VECTORING_ERROR_CODE, idt_vectoring_error_code),
808         FIELD(VM_EXIT_INSTRUCTION_LEN, vm_exit_instruction_len),
809         FIELD(VMX_INSTRUCTION_INFO, vmx_instruction_info),
810         FIELD(GUEST_ES_LIMIT, guest_es_limit),
811         FIELD(GUEST_CS_LIMIT, guest_cs_limit),
812         FIELD(GUEST_SS_LIMIT, guest_ss_limit),
813         FIELD(GUEST_DS_LIMIT, guest_ds_limit),
814         FIELD(GUEST_FS_LIMIT, guest_fs_limit),
815         FIELD(GUEST_GS_LIMIT, guest_gs_limit),
816         FIELD(GUEST_LDTR_LIMIT, guest_ldtr_limit),
817         FIELD(GUEST_TR_LIMIT, guest_tr_limit),
818         FIELD(GUEST_GDTR_LIMIT, guest_gdtr_limit),
819         FIELD(GUEST_IDTR_LIMIT, guest_idtr_limit),
820         FIELD(GUEST_ES_AR_BYTES, guest_es_ar_bytes),
821         FIELD(GUEST_CS_AR_BYTES, guest_cs_ar_bytes),
822         FIELD(GUEST_SS_AR_BYTES, guest_ss_ar_bytes),
823         FIELD(GUEST_DS_AR_BYTES, guest_ds_ar_bytes),
824         FIELD(GUEST_FS_AR_BYTES, guest_fs_ar_bytes),
825         FIELD(GUEST_GS_AR_BYTES, guest_gs_ar_bytes),
826         FIELD(GUEST_LDTR_AR_BYTES, guest_ldtr_ar_bytes),
827         FIELD(GUEST_TR_AR_BYTES, guest_tr_ar_bytes),
828         FIELD(GUEST_INTERRUPTIBILITY_INFO, guest_interruptibility_info),
829         FIELD(GUEST_ACTIVITY_STATE, guest_activity_state),
830         FIELD(GUEST_SYSENTER_CS, guest_sysenter_cs),
831         FIELD(HOST_IA32_SYSENTER_CS, host_ia32_sysenter_cs),
832         FIELD(VMX_PREEMPTION_TIMER_VALUE, vmx_preemption_timer_value),
833         FIELD(CR0_GUEST_HOST_MASK, cr0_guest_host_mask),
834         FIELD(CR4_GUEST_HOST_MASK, cr4_guest_host_mask),
835         FIELD(CR0_READ_SHADOW, cr0_read_shadow),
836         FIELD(CR4_READ_SHADOW, cr4_read_shadow),
837         FIELD(CR3_TARGET_VALUE0, cr3_target_value0),
838         FIELD(CR3_TARGET_VALUE1, cr3_target_value1),
839         FIELD(CR3_TARGET_VALUE2, cr3_target_value2),
840         FIELD(CR3_TARGET_VALUE3, cr3_target_value3),
841         FIELD(EXIT_QUALIFICATION, exit_qualification),
842         FIELD(GUEST_LINEAR_ADDRESS, guest_linear_address),
843         FIELD(GUEST_CR0, guest_cr0),
844         FIELD(GUEST_CR3, guest_cr3),
845         FIELD(GUEST_CR4, guest_cr4),
846         FIELD(GUEST_ES_BASE, guest_es_base),
847         FIELD(GUEST_CS_BASE, guest_cs_base),
848         FIELD(GUEST_SS_BASE, guest_ss_base),
849         FIELD(GUEST_DS_BASE, guest_ds_base),
850         FIELD(GUEST_FS_BASE, guest_fs_base),
851         FIELD(GUEST_GS_BASE, guest_gs_base),
852         FIELD(GUEST_LDTR_BASE, guest_ldtr_base),
853         FIELD(GUEST_TR_BASE, guest_tr_base),
854         FIELD(GUEST_GDTR_BASE, guest_gdtr_base),
855         FIELD(GUEST_IDTR_BASE, guest_idtr_base),
856         FIELD(GUEST_DR7, guest_dr7),
857         FIELD(GUEST_RSP, guest_rsp),
858         FIELD(GUEST_RIP, guest_rip),
859         FIELD(GUEST_RFLAGS, guest_rflags),
860         FIELD(GUEST_PENDING_DBG_EXCEPTIONS, guest_pending_dbg_exceptions),
861         FIELD(GUEST_SYSENTER_ESP, guest_sysenter_esp),
862         FIELD(GUEST_SYSENTER_EIP, guest_sysenter_eip),
863         FIELD(HOST_CR0, host_cr0),
864         FIELD(HOST_CR3, host_cr3),
865         FIELD(HOST_CR4, host_cr4),
866         FIELD(HOST_FS_BASE, host_fs_base),
867         FIELD(HOST_GS_BASE, host_gs_base),
868         FIELD(HOST_TR_BASE, host_tr_base),
869         FIELD(HOST_GDTR_BASE, host_gdtr_base),
870         FIELD(HOST_IDTR_BASE, host_idtr_base),
871         FIELD(HOST_IA32_SYSENTER_ESP, host_ia32_sysenter_esp),
872         FIELD(HOST_IA32_SYSENTER_EIP, host_ia32_sysenter_eip),
873         FIELD(HOST_RSP, host_rsp),
874         FIELD(HOST_RIP, host_rip),
875 };
876
877 static inline short vmcs_field_to_offset(unsigned long field)
878 {
879         const size_t size = ARRAY_SIZE(vmcs_field_to_offset_table);
880         unsigned short offset;
881         unsigned index;
882
883         if (field >> 15)
884                 return -ENOENT;
885
886         index = ROL16(field, 6);
887         if (index >= size)
888                 return -ENOENT;
889
890         index = array_index_nospec(index, size);
891         offset = vmcs_field_to_offset_table[index];
892         if (offset == 0)
893                 return -ENOENT;
894         return offset;
895 }
896
897 static inline struct vmcs12 *get_vmcs12(struct kvm_vcpu *vcpu)
898 {
899         return to_vmx(vcpu)->nested.cached_vmcs12;
900 }
901
902 static bool nested_ept_ad_enabled(struct kvm_vcpu *vcpu);
903 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu);
904 static u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa);
905 static bool vmx_xsaves_supported(void);
906 static void vmx_set_segment(struct kvm_vcpu *vcpu,
907                             struct kvm_segment *var, int seg);
908 static void vmx_get_segment(struct kvm_vcpu *vcpu,
909                             struct kvm_segment *var, int seg);
910 static bool guest_state_valid(struct kvm_vcpu *vcpu);
911 static u32 vmx_segment_access_rights(struct kvm_segment *var);
912 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx);
913 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu);
914 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked);
915 static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
916                                             u16 error_code);
917 static void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu);
918 static void __always_inline vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
919                                                           u32 msr, int type);
920
921 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
922 static DEFINE_PER_CPU(struct vmcs *, current_vmcs);
923 /*
924  * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
925  * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
926  */
927 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
928
929 /*
930  * We maintian a per-CPU linked-list of vCPU, so in wakeup_handler() we
931  * can find which vCPU should be waken up.
932  */
933 static DEFINE_PER_CPU(struct list_head, blocked_vcpu_on_cpu);
934 static DEFINE_PER_CPU(spinlock_t, blocked_vcpu_on_cpu_lock);
935
936 enum {
937         VMX_VMREAD_BITMAP,
938         VMX_VMWRITE_BITMAP,
939         VMX_BITMAP_NR
940 };
941
942 static unsigned long *vmx_bitmap[VMX_BITMAP_NR];
943
944 #define vmx_vmread_bitmap                    (vmx_bitmap[VMX_VMREAD_BITMAP])
945 #define vmx_vmwrite_bitmap                   (vmx_bitmap[VMX_VMWRITE_BITMAP])
946
947 static bool cpu_has_load_ia32_efer;
948 static bool cpu_has_load_perf_global_ctrl;
949
950 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
951 static DEFINE_SPINLOCK(vmx_vpid_lock);
952
953 static struct vmcs_config {
954         int size;
955         int order;
956         u32 basic_cap;
957         u32 revision_id;
958         u32 pin_based_exec_ctrl;
959         u32 cpu_based_exec_ctrl;
960         u32 cpu_based_2nd_exec_ctrl;
961         u32 vmexit_ctrl;
962         u32 vmentry_ctrl;
963         struct nested_vmx_msrs nested;
964 } vmcs_config;
965
966 static struct vmx_capability {
967         u32 ept;
968         u32 vpid;
969 } vmx_capability;
970
971 #define VMX_SEGMENT_FIELD(seg)                                  \
972         [VCPU_SREG_##seg] = {                                   \
973                 .selector = GUEST_##seg##_SELECTOR,             \
974                 .base = GUEST_##seg##_BASE,                     \
975                 .limit = GUEST_##seg##_LIMIT,                   \
976                 .ar_bytes = GUEST_##seg##_AR_BYTES,             \
977         }
978
979 static const struct kvm_vmx_segment_field {
980         unsigned selector;
981         unsigned base;
982         unsigned limit;
983         unsigned ar_bytes;
984 } kvm_vmx_segment_fields[] = {
985         VMX_SEGMENT_FIELD(CS),
986         VMX_SEGMENT_FIELD(DS),
987         VMX_SEGMENT_FIELD(ES),
988         VMX_SEGMENT_FIELD(FS),
989         VMX_SEGMENT_FIELD(GS),
990         VMX_SEGMENT_FIELD(SS),
991         VMX_SEGMENT_FIELD(TR),
992         VMX_SEGMENT_FIELD(LDTR),
993 };
994
995 static u64 host_efer;
996
997 static void ept_save_pdptrs(struct kvm_vcpu *vcpu);
998
999 /*
1000  * Keep MSR_STAR at the end, as setup_msrs() will try to optimize it
1001  * away by decrementing the array size.
1002  */
1003 static const u32 vmx_msr_index[] = {
1004 #ifdef CONFIG_X86_64
1005         MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
1006 #endif
1007         MSR_EFER, MSR_TSC_AUX, MSR_STAR,
1008 };
1009
1010 static inline bool is_exception_n(u32 intr_info, u8 vector)
1011 {
1012         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1013                              INTR_INFO_VALID_MASK)) ==
1014                 (INTR_TYPE_HARD_EXCEPTION | vector | INTR_INFO_VALID_MASK);
1015 }
1016
1017 static inline bool is_debug(u32 intr_info)
1018 {
1019         return is_exception_n(intr_info, DB_VECTOR);
1020 }
1021
1022 static inline bool is_breakpoint(u32 intr_info)
1023 {
1024         return is_exception_n(intr_info, BP_VECTOR);
1025 }
1026
1027 static inline bool is_page_fault(u32 intr_info)
1028 {
1029         return is_exception_n(intr_info, PF_VECTOR);
1030 }
1031
1032 static inline bool is_no_device(u32 intr_info)
1033 {
1034         return is_exception_n(intr_info, NM_VECTOR);
1035 }
1036
1037 static inline bool is_invalid_opcode(u32 intr_info)
1038 {
1039         return is_exception_n(intr_info, UD_VECTOR);
1040 }
1041
1042 static inline bool is_external_interrupt(u32 intr_info)
1043 {
1044         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1045                 == (INTR_TYPE_EXT_INTR | INTR_INFO_VALID_MASK);
1046 }
1047
1048 static inline bool is_machine_check(u32 intr_info)
1049 {
1050         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1051                              INTR_INFO_VALID_MASK)) ==
1052                 (INTR_TYPE_HARD_EXCEPTION | MC_VECTOR | INTR_INFO_VALID_MASK);
1053 }
1054
1055 static inline bool cpu_has_vmx_msr_bitmap(void)
1056 {
1057         return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_USE_MSR_BITMAPS;
1058 }
1059
1060 static inline bool cpu_has_vmx_tpr_shadow(void)
1061 {
1062         return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW;
1063 }
1064
1065 static inline bool cpu_need_tpr_shadow(struct kvm_vcpu *vcpu)
1066 {
1067         return cpu_has_vmx_tpr_shadow() && lapic_in_kernel(vcpu);
1068 }
1069
1070 static inline bool cpu_has_secondary_exec_ctrls(void)
1071 {
1072         return vmcs_config.cpu_based_exec_ctrl &
1073                 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
1074 }
1075
1076 static inline bool cpu_has_vmx_virtualize_apic_accesses(void)
1077 {
1078         return vmcs_config.cpu_based_2nd_exec_ctrl &
1079                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
1080 }
1081
1082 static inline bool cpu_has_vmx_virtualize_x2apic_mode(void)
1083 {
1084         return vmcs_config.cpu_based_2nd_exec_ctrl &
1085                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
1086 }
1087
1088 static inline bool cpu_has_vmx_apic_register_virt(void)
1089 {
1090         return vmcs_config.cpu_based_2nd_exec_ctrl &
1091                 SECONDARY_EXEC_APIC_REGISTER_VIRT;
1092 }
1093
1094 static inline bool cpu_has_vmx_virtual_intr_delivery(void)
1095 {
1096         return vmcs_config.cpu_based_2nd_exec_ctrl &
1097                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY;
1098 }
1099
1100 /*
1101  * Comment's format: document - errata name - stepping - processor name.
1102  * Refer from
1103  * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
1104  */
1105 static u32 vmx_preemption_cpu_tfms[] = {
1106 /* 323344.pdf - BA86   - D0 - Xeon 7500 Series */
1107 0x000206E6,
1108 /* 323056.pdf - AAX65  - C2 - Xeon L3406 */
1109 /* 322814.pdf - AAT59  - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
1110 /* 322911.pdf - AAU65  - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
1111 0x00020652,
1112 /* 322911.pdf - AAU65  - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
1113 0x00020655,
1114 /* 322373.pdf - AAO95  - B1 - Xeon 3400 Series */
1115 /* 322166.pdf - AAN92  - B1 - i7-800 and i5-700 Desktop */
1116 /*
1117  * 320767.pdf - AAP86  - B1 -
1118  * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
1119  */
1120 0x000106E5,
1121 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
1122 0x000106A0,
1123 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
1124 0x000106A1,
1125 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
1126 0x000106A4,
1127  /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
1128  /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
1129  /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
1130 0x000106A5,
1131 };
1132
1133 static inline bool cpu_has_broken_vmx_preemption_timer(void)
1134 {
1135         u32 eax = cpuid_eax(0x00000001), i;
1136
1137         /* Clear the reserved bits */
1138         eax &= ~(0x3U << 14 | 0xfU << 28);
1139         for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
1140                 if (eax == vmx_preemption_cpu_tfms[i])
1141                         return true;
1142
1143         return false;
1144 }
1145
1146 static inline bool cpu_has_vmx_preemption_timer(void)
1147 {
1148         return vmcs_config.pin_based_exec_ctrl &
1149                 PIN_BASED_VMX_PREEMPTION_TIMER;
1150 }
1151
1152 static inline bool cpu_has_vmx_posted_intr(void)
1153 {
1154         return IS_ENABLED(CONFIG_X86_LOCAL_APIC) &&
1155                 vmcs_config.pin_based_exec_ctrl & PIN_BASED_POSTED_INTR;
1156 }
1157
1158 static inline bool cpu_has_vmx_apicv(void)
1159 {
1160         return cpu_has_vmx_apic_register_virt() &&
1161                 cpu_has_vmx_virtual_intr_delivery() &&
1162                 cpu_has_vmx_posted_intr();
1163 }
1164
1165 static inline bool cpu_has_vmx_flexpriority(void)
1166 {
1167         return cpu_has_vmx_tpr_shadow() &&
1168                 cpu_has_vmx_virtualize_apic_accesses();
1169 }
1170
1171 static inline bool cpu_has_vmx_ept_execute_only(void)
1172 {
1173         return vmx_capability.ept & VMX_EPT_EXECUTE_ONLY_BIT;
1174 }
1175
1176 static inline bool cpu_has_vmx_ept_2m_page(void)
1177 {
1178         return vmx_capability.ept & VMX_EPT_2MB_PAGE_BIT;
1179 }
1180
1181 static inline bool cpu_has_vmx_ept_1g_page(void)
1182 {
1183         return vmx_capability.ept & VMX_EPT_1GB_PAGE_BIT;
1184 }
1185
1186 static inline bool cpu_has_vmx_ept_4levels(void)
1187 {
1188         return vmx_capability.ept & VMX_EPT_PAGE_WALK_4_BIT;
1189 }
1190
1191 static inline bool cpu_has_vmx_ept_mt_wb(void)
1192 {
1193         return vmx_capability.ept & VMX_EPTP_WB_BIT;
1194 }
1195
1196 static inline bool cpu_has_vmx_ept_5levels(void)
1197 {
1198         return vmx_capability.ept & VMX_EPT_PAGE_WALK_5_BIT;
1199 }
1200
1201 static inline bool cpu_has_vmx_ept_ad_bits(void)
1202 {
1203         return vmx_capability.ept & VMX_EPT_AD_BIT;
1204 }
1205
1206 static inline bool cpu_has_vmx_invept_context(void)
1207 {
1208         return vmx_capability.ept & VMX_EPT_EXTENT_CONTEXT_BIT;
1209 }
1210
1211 static inline bool cpu_has_vmx_invept_global(void)
1212 {
1213         return vmx_capability.ept & VMX_EPT_EXTENT_GLOBAL_BIT;
1214 }
1215
1216 static inline bool cpu_has_vmx_invvpid_single(void)
1217 {
1218         return vmx_capability.vpid & VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT;
1219 }
1220
1221 static inline bool cpu_has_vmx_invvpid_global(void)
1222 {
1223         return vmx_capability.vpid & VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT;
1224 }
1225
1226 static inline bool cpu_has_vmx_invvpid(void)
1227 {
1228         return vmx_capability.vpid & VMX_VPID_INVVPID_BIT;
1229 }
1230
1231 static inline bool cpu_has_vmx_ept(void)
1232 {
1233         return vmcs_config.cpu_based_2nd_exec_ctrl &
1234                 SECONDARY_EXEC_ENABLE_EPT;
1235 }
1236
1237 static inline bool cpu_has_vmx_unrestricted_guest(void)
1238 {
1239         return vmcs_config.cpu_based_2nd_exec_ctrl &
1240                 SECONDARY_EXEC_UNRESTRICTED_GUEST;
1241 }
1242
1243 static inline bool cpu_has_vmx_ple(void)
1244 {
1245         return vmcs_config.cpu_based_2nd_exec_ctrl &
1246                 SECONDARY_EXEC_PAUSE_LOOP_EXITING;
1247 }
1248
1249 static inline bool cpu_has_vmx_basic_inout(void)
1250 {
1251         return  (((u64)vmcs_config.basic_cap << 32) & VMX_BASIC_INOUT);
1252 }
1253
1254 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
1255 {
1256         return flexpriority_enabled && lapic_in_kernel(vcpu);
1257 }
1258
1259 static inline bool cpu_has_vmx_vpid(void)
1260 {
1261         return vmcs_config.cpu_based_2nd_exec_ctrl &
1262                 SECONDARY_EXEC_ENABLE_VPID;
1263 }
1264
1265 static inline bool cpu_has_vmx_rdtscp(void)
1266 {
1267         return vmcs_config.cpu_based_2nd_exec_ctrl &
1268                 SECONDARY_EXEC_RDTSCP;
1269 }
1270
1271 static inline bool cpu_has_vmx_invpcid(void)
1272 {
1273         return vmcs_config.cpu_based_2nd_exec_ctrl &
1274                 SECONDARY_EXEC_ENABLE_INVPCID;
1275 }
1276
1277 static inline bool cpu_has_virtual_nmis(void)
1278 {
1279         return vmcs_config.pin_based_exec_ctrl & PIN_BASED_VIRTUAL_NMIS;
1280 }
1281
1282 static inline bool cpu_has_vmx_wbinvd_exit(void)
1283 {
1284         return vmcs_config.cpu_based_2nd_exec_ctrl &
1285                 SECONDARY_EXEC_WBINVD_EXITING;
1286 }
1287
1288 static inline bool cpu_has_vmx_shadow_vmcs(void)
1289 {
1290         u64 vmx_msr;
1291         rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
1292         /* check if the cpu supports writing r/o exit information fields */
1293         if (!(vmx_msr & MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS))
1294                 return false;
1295
1296         return vmcs_config.cpu_based_2nd_exec_ctrl &
1297                 SECONDARY_EXEC_SHADOW_VMCS;
1298 }
1299
1300 static inline bool cpu_has_vmx_pml(void)
1301 {
1302         return vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_ENABLE_PML;
1303 }
1304
1305 static inline bool cpu_has_vmx_tsc_scaling(void)
1306 {
1307         return vmcs_config.cpu_based_2nd_exec_ctrl &
1308                 SECONDARY_EXEC_TSC_SCALING;
1309 }
1310
1311 static inline bool cpu_has_vmx_vmfunc(void)
1312 {
1313         return vmcs_config.cpu_based_2nd_exec_ctrl &
1314                 SECONDARY_EXEC_ENABLE_VMFUNC;
1315 }
1316
1317 static inline bool report_flexpriority(void)
1318 {
1319         return flexpriority_enabled;
1320 }
1321
1322 static inline unsigned nested_cpu_vmx_misc_cr3_count(struct kvm_vcpu *vcpu)
1323 {
1324         return vmx_misc_cr3_count(to_vmx(vcpu)->nested.msrs.misc_low);
1325 }
1326
1327 static inline bool nested_cpu_has(struct vmcs12 *vmcs12, u32 bit)
1328 {
1329         return vmcs12->cpu_based_vm_exec_control & bit;
1330 }
1331
1332 static inline bool nested_cpu_has2(struct vmcs12 *vmcs12, u32 bit)
1333 {
1334         return (vmcs12->cpu_based_vm_exec_control &
1335                         CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
1336                 (vmcs12->secondary_vm_exec_control & bit);
1337 }
1338
1339 static inline bool nested_cpu_has_preemption_timer(struct vmcs12 *vmcs12)
1340 {
1341         return vmcs12->pin_based_vm_exec_control &
1342                 PIN_BASED_VMX_PREEMPTION_TIMER;
1343 }
1344
1345 static inline bool nested_cpu_has_nmi_exiting(struct vmcs12 *vmcs12)
1346 {
1347         return vmcs12->pin_based_vm_exec_control & PIN_BASED_NMI_EXITING;
1348 }
1349
1350 static inline bool nested_cpu_has_virtual_nmis(struct vmcs12 *vmcs12)
1351 {
1352         return vmcs12->pin_based_vm_exec_control & PIN_BASED_VIRTUAL_NMIS;
1353 }
1354
1355 static inline int nested_cpu_has_ept(struct vmcs12 *vmcs12)
1356 {
1357         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_EPT);
1358 }
1359
1360 static inline bool nested_cpu_has_xsaves(struct vmcs12 *vmcs12)
1361 {
1362         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
1363 }
1364
1365 static inline bool nested_cpu_has_pml(struct vmcs12 *vmcs12)
1366 {
1367         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_PML);
1368 }
1369
1370 static inline bool nested_cpu_has_virt_x2apic_mode(struct vmcs12 *vmcs12)
1371 {
1372         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
1373 }
1374
1375 static inline bool nested_cpu_has_vpid(struct vmcs12 *vmcs12)
1376 {
1377         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VPID);
1378 }
1379
1380 static inline bool nested_cpu_has_apic_reg_virt(struct vmcs12 *vmcs12)
1381 {
1382         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_APIC_REGISTER_VIRT);
1383 }
1384
1385 static inline bool nested_cpu_has_vid(struct vmcs12 *vmcs12)
1386 {
1387         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
1388 }
1389
1390 static inline bool nested_cpu_has_posted_intr(struct vmcs12 *vmcs12)
1391 {
1392         return vmcs12->pin_based_vm_exec_control & PIN_BASED_POSTED_INTR;
1393 }
1394
1395 static inline bool nested_cpu_has_vmfunc(struct vmcs12 *vmcs12)
1396 {
1397         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VMFUNC);
1398 }
1399
1400 static inline bool nested_cpu_has_eptp_switching(struct vmcs12 *vmcs12)
1401 {
1402         return nested_cpu_has_vmfunc(vmcs12) &&
1403                 (vmcs12->vm_function_control &
1404                  VMX_VMFUNC_EPTP_SWITCHING);
1405 }
1406
1407 static inline bool is_nmi(u32 intr_info)
1408 {
1409         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1410                 == (INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK);
1411 }
1412
1413 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
1414                               u32 exit_intr_info,
1415                               unsigned long exit_qualification);
1416 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
1417                         struct vmcs12 *vmcs12,
1418                         u32 reason, unsigned long qualification);
1419
1420 static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
1421 {
1422         int i;
1423
1424         for (i = 0; i < vmx->nmsrs; ++i)
1425                 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
1426                         return i;
1427         return -1;
1428 }
1429
1430 static inline void __invvpid(int ext, u16 vpid, gva_t gva)
1431 {
1432     struct {
1433         u64 vpid : 16;
1434         u64 rsvd : 48;
1435         u64 gva;
1436     } operand = { vpid, 0, gva };
1437
1438     asm volatile (__ex(ASM_VMX_INVVPID)
1439                   /* CF==1 or ZF==1 --> rc = -1 */
1440                   "; ja 1f ; ud2 ; 1:"
1441                   : : "a"(&operand), "c"(ext) : "cc", "memory");
1442 }
1443
1444 static inline void __invept(int ext, u64 eptp, gpa_t gpa)
1445 {
1446         struct {
1447                 u64 eptp, gpa;
1448         } operand = {eptp, gpa};
1449
1450         asm volatile (__ex(ASM_VMX_INVEPT)
1451                         /* CF==1 or ZF==1 --> rc = -1 */
1452                         "; ja 1f ; ud2 ; 1:\n"
1453                         : : "a" (&operand), "c" (ext) : "cc", "memory");
1454 }
1455
1456 static struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
1457 {
1458         int i;
1459
1460         i = __find_msr_index(vmx, msr);
1461         if (i >= 0)
1462                 return &vmx->guest_msrs[i];
1463         return NULL;
1464 }
1465
1466 static void vmcs_clear(struct vmcs *vmcs)
1467 {
1468         u64 phys_addr = __pa(vmcs);
1469         u8 error;
1470
1471         asm volatile (__ex(ASM_VMX_VMCLEAR_RAX) "; setna %0"
1472                       : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
1473                       : "cc", "memory");
1474         if (error)
1475                 printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n",
1476                        vmcs, phys_addr);
1477 }
1478
1479 static inline void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
1480 {
1481         vmcs_clear(loaded_vmcs->vmcs);
1482         if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
1483                 vmcs_clear(loaded_vmcs->shadow_vmcs);
1484         loaded_vmcs->cpu = -1;
1485         loaded_vmcs->launched = 0;
1486 }
1487
1488 static void vmcs_load(struct vmcs *vmcs)
1489 {
1490         u64 phys_addr = __pa(vmcs);
1491         u8 error;
1492
1493         asm volatile (__ex(ASM_VMX_VMPTRLD_RAX) "; setna %0"
1494                         : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
1495                         : "cc", "memory");
1496         if (error)
1497                 printk(KERN_ERR "kvm: vmptrld %p/%llx failed\n",
1498                        vmcs, phys_addr);
1499 }
1500
1501 #ifdef CONFIG_KEXEC_CORE
1502 /*
1503  * This bitmap is used to indicate whether the vmclear
1504  * operation is enabled on all cpus. All disabled by
1505  * default.
1506  */
1507 static cpumask_t crash_vmclear_enabled_bitmap = CPU_MASK_NONE;
1508
1509 static inline void crash_enable_local_vmclear(int cpu)
1510 {
1511         cpumask_set_cpu(cpu, &crash_vmclear_enabled_bitmap);
1512 }
1513
1514 static inline void crash_disable_local_vmclear(int cpu)
1515 {
1516         cpumask_clear_cpu(cpu, &crash_vmclear_enabled_bitmap);
1517 }
1518
1519 static inline int crash_local_vmclear_enabled(int cpu)
1520 {
1521         return cpumask_test_cpu(cpu, &crash_vmclear_enabled_bitmap);
1522 }
1523
1524 static void crash_vmclear_local_loaded_vmcss(void)
1525 {
1526         int cpu = raw_smp_processor_id();
1527         struct loaded_vmcs *v;
1528
1529         if (!crash_local_vmclear_enabled(cpu))
1530                 return;
1531
1532         list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
1533                             loaded_vmcss_on_cpu_link)
1534                 vmcs_clear(v->vmcs);
1535 }
1536 #else
1537 static inline void crash_enable_local_vmclear(int cpu) { }
1538 static inline void crash_disable_local_vmclear(int cpu) { }
1539 #endif /* CONFIG_KEXEC_CORE */
1540
1541 static void __loaded_vmcs_clear(void *arg)
1542 {
1543         struct loaded_vmcs *loaded_vmcs = arg;
1544         int cpu = raw_smp_processor_id();
1545
1546         if (loaded_vmcs->cpu != cpu)
1547                 return; /* vcpu migration can race with cpu offline */
1548         if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
1549                 per_cpu(current_vmcs, cpu) = NULL;
1550         crash_disable_local_vmclear(cpu);
1551         list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
1552
1553         /*
1554          * we should ensure updating loaded_vmcs->loaded_vmcss_on_cpu_link
1555          * is before setting loaded_vmcs->vcpu to -1 which is done in
1556          * loaded_vmcs_init. Otherwise, other cpu can see vcpu = -1 fist
1557          * then adds the vmcs into percpu list before it is deleted.
1558          */
1559         smp_wmb();
1560
1561         loaded_vmcs_init(loaded_vmcs);
1562         crash_enable_local_vmclear(cpu);
1563 }
1564
1565 static void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
1566 {
1567         int cpu = loaded_vmcs->cpu;
1568
1569         if (cpu != -1)
1570                 smp_call_function_single(cpu,
1571                          __loaded_vmcs_clear, loaded_vmcs, 1);
1572 }
1573
1574 static inline void vpid_sync_vcpu_single(int vpid)
1575 {
1576         if (vpid == 0)
1577                 return;
1578
1579         if (cpu_has_vmx_invvpid_single())
1580                 __invvpid(VMX_VPID_EXTENT_SINGLE_CONTEXT, vpid, 0);
1581 }
1582
1583 static inline void vpid_sync_vcpu_global(void)
1584 {
1585         if (cpu_has_vmx_invvpid_global())
1586                 __invvpid(VMX_VPID_EXTENT_ALL_CONTEXT, 0, 0);
1587 }
1588
1589 static inline void vpid_sync_context(int vpid)
1590 {
1591         if (cpu_has_vmx_invvpid_single())
1592                 vpid_sync_vcpu_single(vpid);
1593         else
1594                 vpid_sync_vcpu_global();
1595 }
1596
1597 static inline void ept_sync_global(void)
1598 {
1599         __invept(VMX_EPT_EXTENT_GLOBAL, 0, 0);
1600 }
1601
1602 static inline void ept_sync_context(u64 eptp)
1603 {
1604         if (cpu_has_vmx_invept_context())
1605                 __invept(VMX_EPT_EXTENT_CONTEXT, eptp, 0);
1606         else
1607                 ept_sync_global();
1608 }
1609
1610 static __always_inline void vmcs_check16(unsigned long field)
1611 {
1612         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
1613                          "16-bit accessor invalid for 64-bit field");
1614         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
1615                          "16-bit accessor invalid for 64-bit high field");
1616         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
1617                          "16-bit accessor invalid for 32-bit high field");
1618         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
1619                          "16-bit accessor invalid for natural width field");
1620 }
1621
1622 static __always_inline void vmcs_check32(unsigned long field)
1623 {
1624         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
1625                          "32-bit accessor invalid for 16-bit field");
1626         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
1627                          "32-bit accessor invalid for natural width field");
1628 }
1629
1630 static __always_inline void vmcs_check64(unsigned long field)
1631 {
1632         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
1633                          "64-bit accessor invalid for 16-bit field");
1634         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
1635                          "64-bit accessor invalid for 64-bit high field");
1636         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
1637                          "64-bit accessor invalid for 32-bit field");
1638         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
1639                          "64-bit accessor invalid for natural width field");
1640 }
1641
1642 static __always_inline void vmcs_checkl(unsigned long field)
1643 {
1644         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
1645                          "Natural width accessor invalid for 16-bit field");
1646         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
1647                          "Natural width accessor invalid for 64-bit field");
1648         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
1649                          "Natural width accessor invalid for 64-bit high field");
1650         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
1651                          "Natural width accessor invalid for 32-bit field");
1652 }
1653
1654 static __always_inline unsigned long __vmcs_readl(unsigned long field)
1655 {
1656         unsigned long value;
1657
1658         asm volatile (__ex_clear(ASM_VMX_VMREAD_RDX_RAX, "%0")
1659                       : "=a"(value) : "d"(field) : "cc");
1660         return value;
1661 }
1662
1663 static __always_inline u16 vmcs_read16(unsigned long field)
1664 {
1665         vmcs_check16(field);
1666         return __vmcs_readl(field);
1667 }
1668
1669 static __always_inline u32 vmcs_read32(unsigned long field)
1670 {
1671         vmcs_check32(field);
1672         return __vmcs_readl(field);
1673 }
1674
1675 static __always_inline u64 vmcs_read64(unsigned long field)
1676 {
1677         vmcs_check64(field);
1678 #ifdef CONFIG_X86_64
1679         return __vmcs_readl(field);
1680 #else
1681         return __vmcs_readl(field) | ((u64)__vmcs_readl(field+1) << 32);
1682 #endif
1683 }
1684
1685 static __always_inline unsigned long vmcs_readl(unsigned long field)
1686 {
1687         vmcs_checkl(field);
1688         return __vmcs_readl(field);
1689 }
1690
1691 static noinline void vmwrite_error(unsigned long field, unsigned long value)
1692 {
1693         printk(KERN_ERR "vmwrite error: reg %lx value %lx (err %d)\n",
1694                field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
1695         dump_stack();
1696 }
1697
1698 static __always_inline void __vmcs_writel(unsigned long field, unsigned long value)
1699 {
1700         u8 error;
1701
1702         asm volatile (__ex(ASM_VMX_VMWRITE_RAX_RDX) "; setna %0"
1703                        : "=q"(error) : "a"(value), "d"(field) : "cc");
1704         if (unlikely(error))
1705                 vmwrite_error(field, value);
1706 }
1707
1708 static __always_inline void vmcs_write16(unsigned long field, u16 value)
1709 {
1710         vmcs_check16(field);
1711         __vmcs_writel(field, value);
1712 }
1713
1714 static __always_inline void vmcs_write32(unsigned long field, u32 value)
1715 {
1716         vmcs_check32(field);
1717         __vmcs_writel(field, value);
1718 }
1719
1720 static __always_inline void vmcs_write64(unsigned long field, u64 value)
1721 {
1722         vmcs_check64(field);
1723         __vmcs_writel(field, value);
1724 #ifndef CONFIG_X86_64
1725         asm volatile ("");
1726         __vmcs_writel(field+1, value >> 32);
1727 #endif
1728 }
1729
1730 static __always_inline void vmcs_writel(unsigned long field, unsigned long value)
1731 {
1732         vmcs_checkl(field);
1733         __vmcs_writel(field, value);
1734 }
1735
1736 static __always_inline void vmcs_clear_bits(unsigned long field, u32 mask)
1737 {
1738         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
1739                          "vmcs_clear_bits does not support 64-bit fields");
1740         __vmcs_writel(field, __vmcs_readl(field) & ~mask);
1741 }
1742
1743 static __always_inline void vmcs_set_bits(unsigned long field, u32 mask)
1744 {
1745         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
1746                          "vmcs_set_bits does not support 64-bit fields");
1747         __vmcs_writel(field, __vmcs_readl(field) | mask);
1748 }
1749
1750 static inline void vm_entry_controls_reset_shadow(struct vcpu_vmx *vmx)
1751 {
1752         vmx->vm_entry_controls_shadow = vmcs_read32(VM_ENTRY_CONTROLS);
1753 }
1754
1755 static inline void vm_entry_controls_init(struct vcpu_vmx *vmx, u32 val)
1756 {
1757         vmcs_write32(VM_ENTRY_CONTROLS, val);
1758         vmx->vm_entry_controls_shadow = val;
1759 }
1760
1761 static inline void vm_entry_controls_set(struct vcpu_vmx *vmx, u32 val)
1762 {
1763         if (vmx->vm_entry_controls_shadow != val)
1764                 vm_entry_controls_init(vmx, val);
1765 }
1766
1767 static inline u32 vm_entry_controls_get(struct vcpu_vmx *vmx)
1768 {
1769         return vmx->vm_entry_controls_shadow;
1770 }
1771
1772
1773 static inline void vm_entry_controls_setbit(struct vcpu_vmx *vmx, u32 val)
1774 {
1775         vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) | val);
1776 }
1777
1778 static inline void vm_entry_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
1779 {
1780         vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) & ~val);
1781 }
1782
1783 static inline void vm_exit_controls_reset_shadow(struct vcpu_vmx *vmx)
1784 {
1785         vmx->vm_exit_controls_shadow = vmcs_read32(VM_EXIT_CONTROLS);
1786 }
1787
1788 static inline void vm_exit_controls_init(struct vcpu_vmx *vmx, u32 val)
1789 {
1790         vmcs_write32(VM_EXIT_CONTROLS, val);
1791         vmx->vm_exit_controls_shadow = val;
1792 }
1793
1794 static inline void vm_exit_controls_set(struct vcpu_vmx *vmx, u32 val)
1795 {
1796         if (vmx->vm_exit_controls_shadow != val)
1797                 vm_exit_controls_init(vmx, val);
1798 }
1799
1800 static inline u32 vm_exit_controls_get(struct vcpu_vmx *vmx)
1801 {
1802         return vmx->vm_exit_controls_shadow;
1803 }
1804
1805
1806 static inline void vm_exit_controls_setbit(struct vcpu_vmx *vmx, u32 val)
1807 {
1808         vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) | val);
1809 }
1810
1811 static inline void vm_exit_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
1812 {
1813         vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) & ~val);
1814 }
1815
1816 static void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
1817 {
1818         vmx->segment_cache.bitmask = 0;
1819 }
1820
1821 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
1822                                        unsigned field)
1823 {
1824         bool ret;
1825         u32 mask = 1 << (seg * SEG_FIELD_NR + field);
1826
1827         if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
1828                 vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
1829                 vmx->segment_cache.bitmask = 0;
1830         }
1831         ret = vmx->segment_cache.bitmask & mask;
1832         vmx->segment_cache.bitmask |= mask;
1833         return ret;
1834 }
1835
1836 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
1837 {
1838         u16 *p = &vmx->segment_cache.seg[seg].selector;
1839
1840         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
1841                 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
1842         return *p;
1843 }
1844
1845 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
1846 {
1847         ulong *p = &vmx->segment_cache.seg[seg].base;
1848
1849         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
1850                 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
1851         return *p;
1852 }
1853
1854 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
1855 {
1856         u32 *p = &vmx->segment_cache.seg[seg].limit;
1857
1858         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
1859                 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
1860         return *p;
1861 }
1862
1863 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
1864 {
1865         u32 *p = &vmx->segment_cache.seg[seg].ar;
1866
1867         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
1868                 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
1869         return *p;
1870 }
1871
1872 static void update_exception_bitmap(struct kvm_vcpu *vcpu)
1873 {
1874         u32 eb;
1875
1876         eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
1877              (1u << DB_VECTOR) | (1u << AC_VECTOR);
1878         if ((vcpu->guest_debug &
1879              (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
1880             (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
1881                 eb |= 1u << BP_VECTOR;
1882         if (to_vmx(vcpu)->rmode.vm86_active)
1883                 eb = ~0;
1884         if (enable_ept)
1885                 eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
1886
1887         /* When we are running a nested L2 guest and L1 specified for it a
1888          * certain exception bitmap, we must trap the same exceptions and pass
1889          * them to L1. When running L2, we will only handle the exceptions
1890          * specified above if L1 did not want them.
1891          */
1892         if (is_guest_mode(vcpu))
1893                 eb |= get_vmcs12(vcpu)->exception_bitmap;
1894
1895         vmcs_write32(EXCEPTION_BITMAP, eb);
1896 }
1897
1898 /*
1899  * Check if MSR is intercepted for currently loaded MSR bitmap.
1900  */
1901 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
1902 {
1903         unsigned long *msr_bitmap;
1904         int f = sizeof(unsigned long);
1905
1906         if (!cpu_has_vmx_msr_bitmap())
1907                 return true;
1908
1909         msr_bitmap = to_vmx(vcpu)->loaded_vmcs->msr_bitmap;
1910
1911         if (msr <= 0x1fff) {
1912                 return !!test_bit(msr, msr_bitmap + 0x800 / f);
1913         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
1914                 msr &= 0x1fff;
1915                 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
1916         }
1917
1918         return true;
1919 }
1920
1921 /*
1922  * Check if MSR is intercepted for L01 MSR bitmap.
1923  */
1924 static bool msr_write_intercepted_l01(struct kvm_vcpu *vcpu, u32 msr)
1925 {
1926         unsigned long *msr_bitmap;
1927         int f = sizeof(unsigned long);
1928
1929         if (!cpu_has_vmx_msr_bitmap())
1930                 return true;
1931
1932         msr_bitmap = to_vmx(vcpu)->vmcs01.msr_bitmap;
1933
1934         if (msr <= 0x1fff) {
1935                 return !!test_bit(msr, msr_bitmap + 0x800 / f);
1936         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
1937                 msr &= 0x1fff;
1938                 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
1939         }
1940
1941         return true;
1942 }
1943
1944 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
1945                 unsigned long entry, unsigned long exit)
1946 {
1947         vm_entry_controls_clearbit(vmx, entry);
1948         vm_exit_controls_clearbit(vmx, exit);
1949 }
1950
1951 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
1952 {
1953         unsigned i;
1954         struct msr_autoload *m = &vmx->msr_autoload;
1955
1956         switch (msr) {
1957         case MSR_EFER:
1958                 if (cpu_has_load_ia32_efer) {
1959                         clear_atomic_switch_msr_special(vmx,
1960                                         VM_ENTRY_LOAD_IA32_EFER,
1961                                         VM_EXIT_LOAD_IA32_EFER);
1962                         return;
1963                 }
1964                 break;
1965         case MSR_CORE_PERF_GLOBAL_CTRL:
1966                 if (cpu_has_load_perf_global_ctrl) {
1967                         clear_atomic_switch_msr_special(vmx,
1968                                         VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
1969                                         VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
1970                         return;
1971                 }
1972                 break;
1973         }
1974
1975         for (i = 0; i < m->nr; ++i)
1976                 if (m->guest[i].index == msr)
1977                         break;
1978
1979         if (i == m->nr)
1980                 return;
1981         --m->nr;
1982         m->guest[i] = m->guest[m->nr];
1983         m->host[i] = m->host[m->nr];
1984         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
1985         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
1986 }
1987
1988 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
1989                 unsigned long entry, unsigned long exit,
1990                 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
1991                 u64 guest_val, u64 host_val)
1992 {
1993         vmcs_write64(guest_val_vmcs, guest_val);
1994         vmcs_write64(host_val_vmcs, host_val);
1995         vm_entry_controls_setbit(vmx, entry);
1996         vm_exit_controls_setbit(vmx, exit);
1997 }
1998
1999 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
2000                                   u64 guest_val, u64 host_val)
2001 {
2002         unsigned i;
2003         struct msr_autoload *m = &vmx->msr_autoload;
2004
2005         switch (msr) {
2006         case MSR_EFER:
2007                 if (cpu_has_load_ia32_efer) {
2008                         add_atomic_switch_msr_special(vmx,
2009                                         VM_ENTRY_LOAD_IA32_EFER,
2010                                         VM_EXIT_LOAD_IA32_EFER,
2011                                         GUEST_IA32_EFER,
2012                                         HOST_IA32_EFER,
2013                                         guest_val, host_val);
2014                         return;
2015                 }
2016                 break;
2017         case MSR_CORE_PERF_GLOBAL_CTRL:
2018                 if (cpu_has_load_perf_global_ctrl) {
2019                         add_atomic_switch_msr_special(vmx,
2020                                         VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
2021                                         VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
2022                                         GUEST_IA32_PERF_GLOBAL_CTRL,
2023                                         HOST_IA32_PERF_GLOBAL_CTRL,
2024                                         guest_val, host_val);
2025                         return;
2026                 }
2027                 break;
2028         case MSR_IA32_PEBS_ENABLE:
2029                 /* PEBS needs a quiescent period after being disabled (to write
2030                  * a record).  Disabling PEBS through VMX MSR swapping doesn't
2031                  * provide that period, so a CPU could write host's record into
2032                  * guest's memory.
2033                  */
2034                 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
2035         }
2036
2037         for (i = 0; i < m->nr; ++i)
2038                 if (m->guest[i].index == msr)
2039                         break;
2040
2041         if (i == NR_AUTOLOAD_MSRS) {
2042                 printk_once(KERN_WARNING "Not enough msr switch entries. "
2043                                 "Can't add msr %x\n", msr);
2044                 return;
2045         } else if (i == m->nr) {
2046                 ++m->nr;
2047                 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
2048                 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
2049         }
2050
2051         m->guest[i].index = msr;
2052         m->guest[i].value = guest_val;
2053         m->host[i].index = msr;
2054         m->host[i].value = host_val;
2055 }
2056
2057 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
2058 {
2059         u64 guest_efer = vmx->vcpu.arch.efer;
2060         u64 ignore_bits = 0;
2061
2062         if (!enable_ept) {
2063                 /*
2064                  * NX is needed to handle CR0.WP=1, CR4.SMEP=1.  Testing
2065                  * host CPUID is more efficient than testing guest CPUID
2066                  * or CR4.  Host SMEP is anyway a requirement for guest SMEP.
2067                  */
2068                 if (boot_cpu_has(X86_FEATURE_SMEP))
2069                         guest_efer |= EFER_NX;
2070                 else if (!(guest_efer & EFER_NX))
2071                         ignore_bits |= EFER_NX;
2072         }
2073
2074         /*
2075          * LMA and LME handled by hardware; SCE meaningless outside long mode.
2076          */
2077         ignore_bits |= EFER_SCE;
2078 #ifdef CONFIG_X86_64
2079         ignore_bits |= EFER_LMA | EFER_LME;
2080         /* SCE is meaningful only in long mode on Intel */
2081         if (guest_efer & EFER_LMA)
2082                 ignore_bits &= ~(u64)EFER_SCE;
2083 #endif
2084
2085         clear_atomic_switch_msr(vmx, MSR_EFER);
2086
2087         /*
2088          * On EPT, we can't emulate NX, so we must switch EFER atomically.
2089          * On CPUs that support "load IA32_EFER", always switch EFER
2090          * atomically, since it's faster than switching it manually.
2091          */
2092         if (cpu_has_load_ia32_efer ||
2093             (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
2094                 if (!(guest_efer & EFER_LMA))
2095                         guest_efer &= ~EFER_LME;
2096                 if (guest_efer != host_efer)
2097                         add_atomic_switch_msr(vmx, MSR_EFER,
2098                                               guest_efer, host_efer);
2099                 return false;
2100         } else {
2101                 guest_efer &= ~ignore_bits;
2102                 guest_efer |= host_efer & ignore_bits;
2103
2104                 vmx->guest_msrs[efer_offset].data = guest_efer;
2105                 vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
2106
2107                 return true;
2108         }
2109 }
2110
2111 #ifdef CONFIG_X86_32
2112 /*
2113  * On 32-bit kernels, VM exits still load the FS and GS bases from the
2114  * VMCS rather than the segment table.  KVM uses this helper to figure
2115  * out the current bases to poke them into the VMCS before entry.
2116  */
2117 static unsigned long segment_base(u16 selector)
2118 {
2119         struct desc_struct *table;
2120         unsigned long v;
2121
2122         if (!(selector & ~SEGMENT_RPL_MASK))
2123                 return 0;
2124
2125         table = get_current_gdt_ro();
2126
2127         if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
2128                 u16 ldt_selector = kvm_read_ldt();
2129
2130                 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
2131                         return 0;
2132
2133                 table = (struct desc_struct *)segment_base(ldt_selector);
2134         }
2135         v = get_desc_base(&table[selector >> 3]);
2136         return v;
2137 }
2138 #endif
2139
2140 static void vmx_save_host_state(struct kvm_vcpu *vcpu)
2141 {
2142         struct vcpu_vmx *vmx = to_vmx(vcpu);
2143         int i;
2144
2145         if (vmx->host_state.loaded)
2146                 return;
2147
2148         vmx->host_state.loaded = 1;
2149         /*
2150          * Set host fs and gs selectors.  Unfortunately, 22.2.3 does not
2151          * allow segment selectors with cpl > 0 or ti == 1.
2152          */
2153         vmx->host_state.ldt_sel = kvm_read_ldt();
2154         vmx->host_state.gs_ldt_reload_needed = vmx->host_state.ldt_sel;
2155         savesegment(fs, vmx->host_state.fs_sel);
2156         if (!(vmx->host_state.fs_sel & 7)) {
2157                 vmcs_write16(HOST_FS_SELECTOR, vmx->host_state.fs_sel);
2158                 vmx->host_state.fs_reload_needed = 0;
2159         } else {
2160                 vmcs_write16(HOST_FS_SELECTOR, 0);
2161                 vmx->host_state.fs_reload_needed = 1;
2162         }
2163         savesegment(gs, vmx->host_state.gs_sel);
2164         if (!(vmx->host_state.gs_sel & 7))
2165                 vmcs_write16(HOST_GS_SELECTOR, vmx->host_state.gs_sel);
2166         else {
2167                 vmcs_write16(HOST_GS_SELECTOR, 0);
2168                 vmx->host_state.gs_ldt_reload_needed = 1;
2169         }
2170
2171 #ifdef CONFIG_X86_64
2172         savesegment(ds, vmx->host_state.ds_sel);
2173         savesegment(es, vmx->host_state.es_sel);
2174 #endif
2175
2176 #ifdef CONFIG_X86_64
2177         vmcs_writel(HOST_FS_BASE, read_msr(MSR_FS_BASE));
2178         vmcs_writel(HOST_GS_BASE, read_msr(MSR_GS_BASE));
2179 #else
2180         vmcs_writel(HOST_FS_BASE, segment_base(vmx->host_state.fs_sel));
2181         vmcs_writel(HOST_GS_BASE, segment_base(vmx->host_state.gs_sel));
2182 #endif
2183
2184 #ifdef CONFIG_X86_64
2185         rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
2186         if (is_long_mode(&vmx->vcpu))
2187                 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2188 #endif
2189         if (boot_cpu_has(X86_FEATURE_MPX))
2190                 rdmsrl(MSR_IA32_BNDCFGS, vmx->host_state.msr_host_bndcfgs);
2191         for (i = 0; i < vmx->save_nmsrs; ++i)
2192                 kvm_set_shared_msr(vmx->guest_msrs[i].index,
2193                                    vmx->guest_msrs[i].data,
2194                                    vmx->guest_msrs[i].mask);
2195 }
2196
2197 static void __vmx_load_host_state(struct vcpu_vmx *vmx)
2198 {
2199         if (!vmx->host_state.loaded)
2200                 return;
2201
2202         ++vmx->vcpu.stat.host_state_reload;
2203         vmx->host_state.loaded = 0;
2204 #ifdef CONFIG_X86_64
2205         if (is_long_mode(&vmx->vcpu))
2206                 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2207 #endif
2208         if (vmx->host_state.gs_ldt_reload_needed) {
2209                 kvm_load_ldt(vmx->host_state.ldt_sel);
2210 #ifdef CONFIG_X86_64
2211                 load_gs_index(vmx->host_state.gs_sel);
2212 #else
2213                 loadsegment(gs, vmx->host_state.gs_sel);
2214 #endif
2215         }
2216         if (vmx->host_state.fs_reload_needed)
2217                 loadsegment(fs, vmx->host_state.fs_sel);
2218 #ifdef CONFIG_X86_64
2219         if (unlikely(vmx->host_state.ds_sel | vmx->host_state.es_sel)) {
2220                 loadsegment(ds, vmx->host_state.ds_sel);
2221                 loadsegment(es, vmx->host_state.es_sel);
2222         }
2223 #endif
2224         invalidate_tss_limit();
2225 #ifdef CONFIG_X86_64
2226         wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
2227 #endif
2228         if (vmx->host_state.msr_host_bndcfgs)
2229                 wrmsrl(MSR_IA32_BNDCFGS, vmx->host_state.msr_host_bndcfgs);
2230         load_fixmap_gdt(raw_smp_processor_id());
2231 }
2232
2233 static void vmx_load_host_state(struct vcpu_vmx *vmx)
2234 {
2235         preempt_disable();
2236         __vmx_load_host_state(vmx);
2237         preempt_enable();
2238 }
2239
2240 static void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
2241 {
2242         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
2243         struct pi_desc old, new;
2244         unsigned int dest;
2245
2246         /*
2247          * In case of hot-plug or hot-unplug, we may have to undo
2248          * vmx_vcpu_pi_put even if there is no assigned device.  And we
2249          * always keep PI.NDST up to date for simplicity: it makes the
2250          * code easier, and CPU migration is not a fast path.
2251          */
2252         if (!pi_test_sn(pi_desc) && vcpu->cpu == cpu)
2253                 return;
2254
2255         /*
2256          * First handle the simple case where no cmpxchg is necessary; just
2257          * allow posting non-urgent interrupts.
2258          *
2259          * If the 'nv' field is POSTED_INTR_WAKEUP_VECTOR, do not change
2260          * PI.NDST: pi_post_block will do it for us and the wakeup_handler
2261          * expects the VCPU to be on the blocked_vcpu_list that matches
2262          * PI.NDST.
2263          */
2264         if (pi_desc->nv == POSTED_INTR_WAKEUP_VECTOR ||
2265             vcpu->cpu == cpu) {
2266                 pi_clear_sn(pi_desc);
2267                 return;
2268         }
2269
2270         /* The full case.  */
2271         do {
2272                 old.control = new.control = pi_desc->control;
2273
2274                 dest = cpu_physical_id(cpu);
2275
2276                 if (x2apic_enabled())
2277                         new.ndst = dest;
2278                 else
2279                         new.ndst = (dest << 8) & 0xFF00;
2280
2281                 new.sn = 0;
2282         } while (cmpxchg64(&pi_desc->control, old.control,
2283                            new.control) != old.control);
2284 }
2285
2286 static void decache_tsc_multiplier(struct vcpu_vmx *vmx)
2287 {
2288         vmx->current_tsc_ratio = vmx->vcpu.arch.tsc_scaling_ratio;
2289         vmcs_write64(TSC_MULTIPLIER, vmx->current_tsc_ratio);
2290 }
2291
2292 /*
2293  * Switches to specified vcpu, until a matching vcpu_put(), but assumes
2294  * vcpu mutex is already taken.
2295  */
2296 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2297 {
2298         struct vcpu_vmx *vmx = to_vmx(vcpu);
2299         bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
2300
2301         if (!already_loaded) {
2302                 loaded_vmcs_clear(vmx->loaded_vmcs);
2303                 local_irq_disable();
2304                 crash_disable_local_vmclear(cpu);
2305
2306                 /*
2307                  * Read loaded_vmcs->cpu should be before fetching
2308                  * loaded_vmcs->loaded_vmcss_on_cpu_link.
2309                  * See the comments in __loaded_vmcs_clear().
2310                  */
2311                 smp_rmb();
2312
2313                 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
2314                          &per_cpu(loaded_vmcss_on_cpu, cpu));
2315                 crash_enable_local_vmclear(cpu);
2316                 local_irq_enable();
2317         }
2318
2319         if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
2320                 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
2321                 vmcs_load(vmx->loaded_vmcs->vmcs);
2322                 indirect_branch_prediction_barrier();
2323         }
2324
2325         if (!already_loaded) {
2326                 void *gdt = get_current_gdt_ro();
2327                 unsigned long sysenter_esp;
2328
2329                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2330
2331                 /*
2332                  * Linux uses per-cpu TSS and GDT, so set these when switching
2333                  * processors.  See 22.2.4.
2334                  */
2335                 vmcs_writel(HOST_TR_BASE,
2336                             (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
2337                 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt);   /* 22.2.4 */
2338
2339                 /*
2340                  * VM exits change the host TR limit to 0x67 after a VM
2341                  * exit.  This is okay, since 0x67 covers everything except
2342                  * the IO bitmap and have have code to handle the IO bitmap
2343                  * being lost after a VM exit.
2344                  */
2345                 BUILD_BUG_ON(IO_BITMAP_OFFSET - 1 != 0x67);
2346
2347                 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
2348                 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
2349
2350                 vmx->loaded_vmcs->cpu = cpu;
2351         }
2352
2353         /* Setup TSC multiplier */
2354         if (kvm_has_tsc_control &&
2355             vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
2356                 decache_tsc_multiplier(vmx);
2357
2358         vmx_vcpu_pi_load(vcpu, cpu);
2359         vmx->host_pkru = read_pkru();
2360         vmx->host_debugctlmsr = get_debugctlmsr();
2361 }
2362
2363 static void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
2364 {
2365         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
2366
2367         if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
2368                 !irq_remapping_cap(IRQ_POSTING_CAP)  ||
2369                 !kvm_vcpu_apicv_active(vcpu))
2370                 return;
2371
2372         /* Set SN when the vCPU is preempted */
2373         if (vcpu->preempted)
2374                 pi_set_sn(pi_desc);
2375 }
2376
2377 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
2378 {
2379         vmx_vcpu_pi_put(vcpu);
2380
2381         __vmx_load_host_state(to_vmx(vcpu));
2382 }
2383
2384 static bool emulation_required(struct kvm_vcpu *vcpu)
2385 {
2386         return emulate_invalid_guest_state && !guest_state_valid(vcpu);
2387 }
2388
2389 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
2390
2391 /*
2392  * Return the cr0 value that a nested guest would read. This is a combination
2393  * of the real cr0 used to run the guest (guest_cr0), and the bits shadowed by
2394  * its hypervisor (cr0_read_shadow).
2395  */
2396 static inline unsigned long nested_read_cr0(struct vmcs12 *fields)
2397 {
2398         return (fields->guest_cr0 & ~fields->cr0_guest_host_mask) |
2399                 (fields->cr0_read_shadow & fields->cr0_guest_host_mask);
2400 }
2401 static inline unsigned long nested_read_cr4(struct vmcs12 *fields)
2402 {
2403         return (fields->guest_cr4 & ~fields->cr4_guest_host_mask) |
2404                 (fields->cr4_read_shadow & fields->cr4_guest_host_mask);
2405 }
2406
2407 static unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
2408 {
2409         unsigned long rflags, save_rflags;
2410
2411         if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
2412                 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
2413                 rflags = vmcs_readl(GUEST_RFLAGS);
2414                 if (to_vmx(vcpu)->rmode.vm86_active) {
2415                         rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2416                         save_rflags = to_vmx(vcpu)->rmode.save_rflags;
2417                         rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2418                 }
2419                 to_vmx(vcpu)->rflags = rflags;
2420         }
2421         return to_vmx(vcpu)->rflags;
2422 }
2423
2424 static void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
2425 {
2426         unsigned long old_rflags = vmx_get_rflags(vcpu);
2427
2428         __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
2429         to_vmx(vcpu)->rflags = rflags;
2430         if (to_vmx(vcpu)->rmode.vm86_active) {
2431                 to_vmx(vcpu)->rmode.save_rflags = rflags;
2432                 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2433         }
2434         vmcs_writel(GUEST_RFLAGS, rflags);
2435
2436         if ((old_rflags ^ to_vmx(vcpu)->rflags) & X86_EFLAGS_VM)
2437                 to_vmx(vcpu)->emulation_required = emulation_required(vcpu);
2438 }
2439
2440 static u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
2441 {
2442         u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
2443         int ret = 0;
2444
2445         if (interruptibility & GUEST_INTR_STATE_STI)
2446                 ret |= KVM_X86_SHADOW_INT_STI;
2447         if (interruptibility & GUEST_INTR_STATE_MOV_SS)
2448                 ret |= KVM_X86_SHADOW_INT_MOV_SS;
2449
2450         return ret;
2451 }
2452
2453 static void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
2454 {
2455         u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
2456         u32 interruptibility = interruptibility_old;
2457
2458         interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
2459
2460         if (mask & KVM_X86_SHADOW_INT_MOV_SS)
2461                 interruptibility |= GUEST_INTR_STATE_MOV_SS;
2462         else if (mask & KVM_X86_SHADOW_INT_STI)
2463                 interruptibility |= GUEST_INTR_STATE_STI;
2464
2465         if ((interruptibility != interruptibility_old))
2466                 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
2467 }
2468
2469 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
2470 {
2471         unsigned long rip;
2472
2473         rip = kvm_rip_read(vcpu);
2474         rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
2475         kvm_rip_write(vcpu, rip);
2476
2477         /* skipping an emulated instruction also counts */
2478         vmx_set_interrupt_shadow(vcpu, 0);
2479 }
2480
2481 static void nested_vmx_inject_exception_vmexit(struct kvm_vcpu *vcpu,
2482                                                unsigned long exit_qual)
2483 {
2484         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
2485         unsigned int nr = vcpu->arch.exception.nr;
2486         u32 intr_info = nr | INTR_INFO_VALID_MASK;
2487
2488         if (vcpu->arch.exception.has_error_code) {
2489                 vmcs12->vm_exit_intr_error_code = vcpu->arch.exception.error_code;
2490                 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
2491         }
2492
2493         if (kvm_exception_is_soft(nr))
2494                 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
2495         else
2496                 intr_info |= INTR_TYPE_HARD_EXCEPTION;
2497
2498         if (!(vmcs12->idt_vectoring_info_field & VECTORING_INFO_VALID_MASK) &&
2499             vmx_get_nmi_mask(vcpu))
2500                 intr_info |= INTR_INFO_UNBLOCK_NMI;
2501
2502         nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI, intr_info, exit_qual);
2503 }
2504
2505 /*
2506  * KVM wants to inject page-faults which it got to the guest. This function
2507  * checks whether in a nested guest, we need to inject them to L1 or L2.
2508  */
2509 static int nested_vmx_check_exception(struct kvm_vcpu *vcpu, unsigned long *exit_qual)
2510 {
2511         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
2512         unsigned int nr = vcpu->arch.exception.nr;
2513
2514         if (nr == PF_VECTOR) {
2515                 if (vcpu->arch.exception.nested_apf) {
2516                         *exit_qual = vcpu->arch.apf.nested_apf_token;
2517                         return 1;
2518                 }
2519                 /*
2520                  * FIXME: we must not write CR2 when L1 intercepts an L2 #PF exception.
2521                  * The fix is to add the ancillary datum (CR2 or DR6) to structs
2522                  * kvm_queued_exception and kvm_vcpu_events, so that CR2 and DR6
2523                  * can be written only when inject_pending_event runs.  This should be
2524                  * conditional on a new capability---if the capability is disabled,
2525                  * kvm_multiple_exception would write the ancillary information to
2526                  * CR2 or DR6, for backwards ABI-compatibility.
2527                  */
2528                 if (nested_vmx_is_page_fault_vmexit(vmcs12,
2529                                                     vcpu->arch.exception.error_code)) {
2530                         *exit_qual = vcpu->arch.cr2;
2531                         return 1;
2532                 }
2533         } else {
2534                 if (vmcs12->exception_bitmap & (1u << nr)) {
2535                         if (nr == DB_VECTOR)
2536                                 *exit_qual = vcpu->arch.dr6;
2537                         else
2538                                 *exit_qual = 0;
2539                         return 1;
2540                 }
2541         }
2542
2543         return 0;
2544 }
2545
2546 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
2547 {
2548         struct vcpu_vmx *vmx = to_vmx(vcpu);
2549         unsigned nr = vcpu->arch.exception.nr;
2550         bool has_error_code = vcpu->arch.exception.has_error_code;
2551         u32 error_code = vcpu->arch.exception.error_code;
2552         u32 intr_info = nr | INTR_INFO_VALID_MASK;
2553
2554         if (has_error_code) {
2555                 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
2556                 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
2557         }
2558
2559         if (vmx->rmode.vm86_active) {
2560                 int inc_eip = 0;
2561                 if (kvm_exception_is_soft(nr))
2562                         inc_eip = vcpu->arch.event_exit_inst_len;
2563                 if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
2564                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2565                 return;
2566         }
2567
2568         if (kvm_exception_is_soft(nr)) {
2569                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
2570                              vmx->vcpu.arch.event_exit_inst_len);
2571                 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
2572         } else
2573                 intr_info |= INTR_TYPE_HARD_EXCEPTION;
2574
2575         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
2576 }
2577
2578 static bool vmx_rdtscp_supported(void)
2579 {
2580         return cpu_has_vmx_rdtscp();
2581 }
2582
2583 static bool vmx_invpcid_supported(void)
2584 {
2585         return cpu_has_vmx_invpcid() && enable_ept;
2586 }
2587
2588 /*
2589  * Swap MSR entry in host/guest MSR entry array.
2590  */
2591 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
2592 {
2593         struct shared_msr_entry tmp;
2594
2595         tmp = vmx->guest_msrs[to];
2596         vmx->guest_msrs[to] = vmx->guest_msrs[from];
2597         vmx->guest_msrs[from] = tmp;
2598 }
2599
2600 /*
2601  * Set up the vmcs to automatically save and restore system
2602  * msrs.  Don't touch the 64-bit msrs if the guest is in legacy
2603  * mode, as fiddling with msrs is very expensive.
2604  */
2605 static void setup_msrs(struct vcpu_vmx *vmx)
2606 {
2607         int save_nmsrs, index;
2608
2609         save_nmsrs = 0;
2610 #ifdef CONFIG_X86_64
2611         if (is_long_mode(&vmx->vcpu)) {
2612                 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
2613                 if (index >= 0)
2614                         move_msr_up(vmx, index, save_nmsrs++);
2615                 index = __find_msr_index(vmx, MSR_LSTAR);
2616                 if (index >= 0)
2617                         move_msr_up(vmx, index, save_nmsrs++);
2618                 index = __find_msr_index(vmx, MSR_CSTAR);
2619                 if (index >= 0)
2620                         move_msr_up(vmx, index, save_nmsrs++);
2621                 index = __find_msr_index(vmx, MSR_TSC_AUX);
2622                 if (index >= 0 && guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP))
2623                         move_msr_up(vmx, index, save_nmsrs++);
2624                 /*
2625                  * MSR_STAR is only needed on long mode guests, and only
2626                  * if efer.sce is enabled.
2627                  */
2628                 index = __find_msr_index(vmx, MSR_STAR);
2629                 if ((index >= 0) && (vmx->vcpu.arch.efer & EFER_SCE))
2630                         move_msr_up(vmx, index, save_nmsrs++);
2631         }
2632 #endif
2633         index = __find_msr_index(vmx, MSR_EFER);
2634         if (index >= 0 && update_transition_efer(vmx, index))
2635                 move_msr_up(vmx, index, save_nmsrs++);
2636
2637         vmx->save_nmsrs = save_nmsrs;
2638
2639         if (cpu_has_vmx_msr_bitmap())
2640                 vmx_update_msr_bitmap(&vmx->vcpu);
2641 }
2642
2643 /*
2644  * reads and returns guest's timestamp counter "register"
2645  * guest_tsc = (host_tsc * tsc multiplier) >> 48 + tsc_offset
2646  * -- Intel TSC Scaling for Virtualization White Paper, sec 1.3
2647  */
2648 static u64 guest_read_tsc(struct kvm_vcpu *vcpu)
2649 {
2650         u64 host_tsc, tsc_offset;
2651
2652         host_tsc = rdtsc();
2653         tsc_offset = vmcs_read64(TSC_OFFSET);
2654         return kvm_scale_tsc(vcpu, host_tsc) + tsc_offset;
2655 }
2656
2657 /*
2658  * writes 'offset' into guest's timestamp counter offset register
2659  */
2660 static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
2661 {
2662         if (is_guest_mode(vcpu)) {
2663                 /*
2664                  * We're here if L1 chose not to trap WRMSR to TSC. According
2665                  * to the spec, this should set L1's TSC; The offset that L1
2666                  * set for L2 remains unchanged, and still needs to be added
2667                  * to the newly set TSC to get L2's TSC.
2668                  */
2669                 struct vmcs12 *vmcs12;
2670                 /* recalculate vmcs02.TSC_OFFSET: */
2671                 vmcs12 = get_vmcs12(vcpu);
2672                 vmcs_write64(TSC_OFFSET, offset +
2673                         (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETING) ?
2674                          vmcs12->tsc_offset : 0));
2675         } else {
2676                 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
2677                                            vmcs_read64(TSC_OFFSET), offset);
2678                 vmcs_write64(TSC_OFFSET, offset);
2679         }
2680 }
2681
2682 /*
2683  * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
2684  * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
2685  * all guests if the "nested" module option is off, and can also be disabled
2686  * for a single guest by disabling its VMX cpuid bit.
2687  */
2688 static inline bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
2689 {
2690         return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
2691 }
2692
2693 /*
2694  * nested_vmx_setup_ctls_msrs() sets up variables containing the values to be
2695  * returned for the various VMX controls MSRs when nested VMX is enabled.
2696  * The same values should also be used to verify that vmcs12 control fields are
2697  * valid during nested entry from L1 to L2.
2698  * Each of these control msrs has a low and high 32-bit half: A low bit is on
2699  * if the corresponding bit in the (32-bit) control field *must* be on, and a
2700  * bit in the high half is on if the corresponding bit in the control field
2701  * may be on. See also vmx_control_verify().
2702  */
2703 static void nested_vmx_setup_ctls_msrs(struct nested_vmx_msrs *msrs, bool apicv)
2704 {
2705         if (!nested) {
2706                 memset(msrs, 0, sizeof(*msrs));
2707                 return;
2708         }
2709
2710         /*
2711          * Note that as a general rule, the high half of the MSRs (bits in
2712          * the control fields which may be 1) should be initialized by the
2713          * intersection of the underlying hardware's MSR (i.e., features which
2714          * can be supported) and the list of features we want to expose -
2715          * because they are known to be properly supported in our code.
2716          * Also, usually, the low half of the MSRs (bits which must be 1) can
2717          * be set to 0, meaning that L1 may turn off any of these bits. The
2718          * reason is that if one of these bits is necessary, it will appear
2719          * in vmcs01 and prepare_vmcs02, when it bitwise-or's the control
2720          * fields of vmcs01 and vmcs02, will turn these bits off - and
2721          * nested_vmx_exit_reflected() will not pass related exits to L1.
2722          * These rules have exceptions below.
2723          */
2724
2725         /* pin-based controls */
2726         rdmsr(MSR_IA32_VMX_PINBASED_CTLS,
2727                 msrs->pinbased_ctls_low,
2728                 msrs->pinbased_ctls_high);
2729         msrs->pinbased_ctls_low |=
2730                 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
2731         msrs->pinbased_ctls_high &=
2732                 PIN_BASED_EXT_INTR_MASK |
2733                 PIN_BASED_NMI_EXITING |
2734                 PIN_BASED_VIRTUAL_NMIS |
2735                 (apicv ? PIN_BASED_POSTED_INTR : 0);
2736         msrs->pinbased_ctls_high |=
2737                 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
2738                 PIN_BASED_VMX_PREEMPTION_TIMER;
2739
2740         /* exit controls */
2741         rdmsr(MSR_IA32_VMX_EXIT_CTLS,
2742                 msrs->exit_ctls_low,
2743                 msrs->exit_ctls_high);
2744         msrs->exit_ctls_low =
2745                 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
2746
2747         msrs->exit_ctls_high &=
2748 #ifdef CONFIG_X86_64
2749                 VM_EXIT_HOST_ADDR_SPACE_SIZE |
2750 #endif
2751                 VM_EXIT_LOAD_IA32_PAT | VM_EXIT_SAVE_IA32_PAT;
2752         msrs->exit_ctls_high |=
2753                 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR |
2754                 VM_EXIT_LOAD_IA32_EFER | VM_EXIT_SAVE_IA32_EFER |
2755                 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER | VM_EXIT_ACK_INTR_ON_EXIT;
2756
2757         if (kvm_mpx_supported())
2758                 msrs->exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
2759
2760         /* We support free control of debug control saving. */
2761         msrs->exit_ctls_low &= ~VM_EXIT_SAVE_DEBUG_CONTROLS;
2762
2763         /* entry controls */
2764         rdmsr(MSR_IA32_VMX_ENTRY_CTLS,
2765                 msrs->entry_ctls_low,
2766                 msrs->entry_ctls_high);
2767         msrs->entry_ctls_low =
2768                 VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
2769         msrs->entry_ctls_high &=
2770 #ifdef CONFIG_X86_64
2771                 VM_ENTRY_IA32E_MODE |
2772 #endif
2773                 VM_ENTRY_LOAD_IA32_PAT;
2774         msrs->entry_ctls_high |=
2775                 (VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR | VM_ENTRY_LOAD_IA32_EFER);
2776         if (kvm_mpx_supported())
2777                 msrs->entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
2778
2779         /* We support free control of debug control loading. */
2780         msrs->entry_ctls_low &= ~VM_ENTRY_LOAD_DEBUG_CONTROLS;
2781
2782         /* cpu-based controls */
2783         rdmsr(MSR_IA32_VMX_PROCBASED_CTLS,
2784                 msrs->procbased_ctls_low,
2785                 msrs->procbased_ctls_high);
2786         msrs->procbased_ctls_low =
2787                 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
2788         msrs->procbased_ctls_high &=
2789                 CPU_BASED_VIRTUAL_INTR_PENDING |
2790                 CPU_BASED_VIRTUAL_NMI_PENDING | CPU_BASED_USE_TSC_OFFSETING |
2791                 CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING |
2792                 CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING |
2793                 CPU_BASED_CR3_STORE_EXITING |
2794 #ifdef CONFIG_X86_64
2795                 CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING |
2796 #endif
2797                 CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING |
2798                 CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_TRAP_FLAG |
2799                 CPU_BASED_MONITOR_EXITING | CPU_BASED_RDPMC_EXITING |
2800                 CPU_BASED_RDTSC_EXITING | CPU_BASED_PAUSE_EXITING |
2801                 CPU_BASED_TPR_SHADOW | CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2802         /*
2803          * We can allow some features even when not supported by the
2804          * hardware. For example, L1 can specify an MSR bitmap - and we
2805          * can use it to avoid exits to L1 - even when L0 runs L2
2806          * without MSR bitmaps.
2807          */
2808         msrs->procbased_ctls_high |=
2809                 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
2810                 CPU_BASED_USE_MSR_BITMAPS;
2811
2812         /* We support free control of CR3 access interception. */
2813         msrs->procbased_ctls_low &=
2814                 ~(CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_CR3_STORE_EXITING);
2815
2816         /*
2817          * secondary cpu-based controls.  Do not include those that
2818          * depend on CPUID bits, they are added later by vmx_cpuid_update.
2819          */
2820         rdmsr(MSR_IA32_VMX_PROCBASED_CTLS2,
2821                 msrs->secondary_ctls_low,
2822                 msrs->secondary_ctls_high);
2823         msrs->secondary_ctls_low = 0;
2824         msrs->secondary_ctls_high &=
2825                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2826                 SECONDARY_EXEC_DESC |
2827                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2828                 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2829                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2830                 SECONDARY_EXEC_WBINVD_EXITING;
2831
2832         if (enable_ept) {
2833                 /* nested EPT: emulate EPT also to L1 */
2834                 msrs->secondary_ctls_high |=
2835                         SECONDARY_EXEC_ENABLE_EPT;
2836                 msrs->ept_caps = VMX_EPT_PAGE_WALK_4_BIT |
2837                          VMX_EPTP_WB_BIT | VMX_EPT_INVEPT_BIT;
2838                 if (cpu_has_vmx_ept_execute_only())
2839                         msrs->ept_caps |=
2840                                 VMX_EPT_EXECUTE_ONLY_BIT;
2841                 msrs->ept_caps &= vmx_capability.ept;
2842                 msrs->ept_caps |= VMX_EPT_EXTENT_GLOBAL_BIT |
2843                         VMX_EPT_EXTENT_CONTEXT_BIT | VMX_EPT_2MB_PAGE_BIT |
2844                         VMX_EPT_1GB_PAGE_BIT;
2845                 if (enable_ept_ad_bits) {
2846                         msrs->secondary_ctls_high |=
2847                                 SECONDARY_EXEC_ENABLE_PML;
2848                         msrs->ept_caps |= VMX_EPT_AD_BIT;
2849                 }
2850         }
2851
2852         if (cpu_has_vmx_vmfunc()) {
2853                 msrs->secondary_ctls_high |=
2854                         SECONDARY_EXEC_ENABLE_VMFUNC;
2855                 /*
2856                  * Advertise EPTP switching unconditionally
2857                  * since we emulate it
2858                  */
2859                 if (enable_ept)
2860                         msrs->vmfunc_controls =
2861                                 VMX_VMFUNC_EPTP_SWITCHING;
2862         }
2863
2864         /*
2865          * Old versions of KVM use the single-context version without
2866          * checking for support, so declare that it is supported even
2867          * though it is treated as global context.  The alternative is
2868          * not failing the single-context invvpid, and it is worse.
2869          */
2870         if (enable_vpid) {
2871                 msrs->secondary_ctls_high |=
2872                         SECONDARY_EXEC_ENABLE_VPID;
2873                 msrs->vpid_caps = VMX_VPID_INVVPID_BIT |
2874                         VMX_VPID_EXTENT_SUPPORTED_MASK;
2875         }
2876
2877         if (enable_unrestricted_guest)
2878                 msrs->secondary_ctls_high |=
2879                         SECONDARY_EXEC_UNRESTRICTED_GUEST;
2880
2881         /* miscellaneous data */
2882         rdmsr(MSR_IA32_VMX_MISC,
2883                 msrs->misc_low,
2884                 msrs->misc_high);
2885         msrs->misc_low &= VMX_MISC_SAVE_EFER_LMA;
2886         msrs->misc_low |=
2887                 VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE |
2888                 VMX_MISC_ACTIVITY_HLT;
2889         msrs->misc_high = 0;
2890
2891         /*
2892          * This MSR reports some information about VMX support. We
2893          * should return information about the VMX we emulate for the
2894          * guest, and the VMCS structure we give it - not about the
2895          * VMX support of the underlying hardware.
2896          */
2897         msrs->basic =
2898                 VMCS12_REVISION |
2899                 VMX_BASIC_TRUE_CTLS |
2900                 ((u64)VMCS12_SIZE << VMX_BASIC_VMCS_SIZE_SHIFT) |
2901                 (VMX_BASIC_MEM_TYPE_WB << VMX_BASIC_MEM_TYPE_SHIFT);
2902
2903         if (cpu_has_vmx_basic_inout())
2904                 msrs->basic |= VMX_BASIC_INOUT;
2905
2906         /*
2907          * These MSRs specify bits which the guest must keep fixed on
2908          * while L1 is in VMXON mode (in L1's root mode, or running an L2).
2909          * We picked the standard core2 setting.
2910          */
2911 #define VMXON_CR0_ALWAYSON     (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE)
2912 #define VMXON_CR4_ALWAYSON     X86_CR4_VMXE
2913         msrs->cr0_fixed0 = VMXON_CR0_ALWAYSON;
2914         msrs->cr4_fixed0 = VMXON_CR4_ALWAYSON;
2915
2916         /* These MSRs specify bits which the guest must keep fixed off. */
2917         rdmsrl(MSR_IA32_VMX_CR0_FIXED1, msrs->cr0_fixed1);
2918         rdmsrl(MSR_IA32_VMX_CR4_FIXED1, msrs->cr4_fixed1);
2919
2920         /* highest index: VMX_PREEMPTION_TIMER_VALUE */
2921         msrs->vmcs_enum = VMCS12_MAX_FIELD_INDEX << 1;
2922 }
2923
2924 /*
2925  * if fixed0[i] == 1: val[i] must be 1
2926  * if fixed1[i] == 0: val[i] must be 0
2927  */
2928 static inline bool fixed_bits_valid(u64 val, u64 fixed0, u64 fixed1)
2929 {
2930         return ((val & fixed1) | fixed0) == val;
2931 }
2932
2933 static inline bool vmx_control_verify(u32 control, u32 low, u32 high)
2934 {
2935         return fixed_bits_valid(control, low, high);
2936 }
2937
2938 static inline u64 vmx_control_msr(u32 low, u32 high)
2939 {
2940         return low | ((u64)high << 32);
2941 }
2942
2943 static bool is_bitwise_subset(u64 superset, u64 subset, u64 mask)
2944 {
2945         superset &= mask;
2946         subset &= mask;
2947
2948         return (superset | subset) == superset;
2949 }
2950
2951 static int vmx_restore_vmx_basic(struct vcpu_vmx *vmx, u64 data)
2952 {
2953         const u64 feature_and_reserved =
2954                 /* feature (except bit 48; see below) */
2955                 BIT_ULL(49) | BIT_ULL(54) | BIT_ULL(55) |
2956                 /* reserved */
2957                 BIT_ULL(31) | GENMASK_ULL(47, 45) | GENMASK_ULL(63, 56);
2958         u64 vmx_basic = vmx->nested.msrs.basic;
2959
2960         if (!is_bitwise_subset(vmx_basic, data, feature_and_reserved))
2961                 return -EINVAL;
2962
2963         /*
2964          * KVM does not emulate a version of VMX that constrains physical
2965          * addresses of VMX structures (e.g. VMCS) to 32-bits.
2966          */
2967         if (data & BIT_ULL(48))
2968                 return -EINVAL;
2969
2970         if (vmx_basic_vmcs_revision_id(vmx_basic) !=
2971             vmx_basic_vmcs_revision_id(data))
2972                 return -EINVAL;
2973
2974         if (vmx_basic_vmcs_size(vmx_basic) > vmx_basic_vmcs_size(data))
2975                 return -EINVAL;
2976
2977         vmx->nested.msrs.basic = data;
2978         return 0;
2979 }
2980
2981 static int
2982 vmx_restore_control_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
2983 {
2984         u64 supported;
2985         u32 *lowp, *highp;
2986
2987         switch (msr_index) {
2988         case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
2989                 lowp = &vmx->nested.msrs.pinbased_ctls_low;
2990                 highp = &vmx->nested.msrs.pinbased_ctls_high;
2991                 break;
2992         case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
2993                 lowp = &vmx->nested.msrs.procbased_ctls_low;
2994                 highp = &vmx->nested.msrs.procbased_ctls_high;
2995                 break;
2996         case MSR_IA32_VMX_TRUE_EXIT_CTLS:
2997                 lowp = &vmx->nested.msrs.exit_ctls_low;
2998                 highp = &vmx->nested.msrs.exit_ctls_high;
2999                 break;
3000         case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3001                 lowp = &vmx->nested.msrs.entry_ctls_low;
3002                 highp = &vmx->nested.msrs.entry_ctls_high;
3003                 break;
3004         case MSR_IA32_VMX_PROCBASED_CTLS2:
3005                 lowp = &vmx->nested.msrs.secondary_ctls_low;
3006                 highp = &vmx->nested.msrs.secondary_ctls_high;
3007                 break;
3008         default:
3009                 BUG();
3010         }
3011
3012         supported = vmx_control_msr(*lowp, *highp);
3013
3014         /* Check must-be-1 bits are still 1. */
3015         if (!is_bitwise_subset(data, supported, GENMASK_ULL(31, 0)))
3016                 return -EINVAL;
3017
3018         /* Check must-be-0 bits are still 0. */
3019         if (!is_bitwise_subset(supported, data, GENMASK_ULL(63, 32)))
3020                 return -EINVAL;
3021
3022         *lowp = data;
3023         *highp = data >> 32;
3024         return 0;
3025 }
3026
3027 static int vmx_restore_vmx_misc(struct vcpu_vmx *vmx, u64 data)
3028 {
3029         const u64 feature_and_reserved_bits =
3030                 /* feature */
3031                 BIT_ULL(5) | GENMASK_ULL(8, 6) | BIT_ULL(14) | BIT_ULL(15) |
3032                 BIT_ULL(28) | BIT_ULL(29) | BIT_ULL(30) |
3033                 /* reserved */
3034                 GENMASK_ULL(13, 9) | BIT_ULL(31);
3035         u64 vmx_misc;
3036
3037         vmx_misc = vmx_control_msr(vmx->nested.msrs.misc_low,
3038                                    vmx->nested.msrs.misc_high);
3039
3040         if (!is_bitwise_subset(vmx_misc, data, feature_and_reserved_bits))
3041                 return -EINVAL;
3042
3043         if ((vmx->nested.msrs.pinbased_ctls_high &
3044              PIN_BASED_VMX_PREEMPTION_TIMER) &&
3045             vmx_misc_preemption_timer_rate(data) !=
3046             vmx_misc_preemption_timer_rate(vmx_misc))
3047                 return -EINVAL;
3048
3049         if (vmx_misc_cr3_count(data) > vmx_misc_cr3_count(vmx_misc))
3050                 return -EINVAL;
3051
3052         if (vmx_misc_max_msr(data) > vmx_misc_max_msr(vmx_misc))
3053                 return -EINVAL;
3054
3055         if (vmx_misc_mseg_revid(data) != vmx_misc_mseg_revid(vmx_misc))
3056                 return -EINVAL;
3057
3058         vmx->nested.msrs.misc_low = data;
3059         vmx->nested.msrs.misc_high = data >> 32;
3060         return 0;
3061 }
3062
3063 static int vmx_restore_vmx_ept_vpid_cap(struct vcpu_vmx *vmx, u64 data)
3064 {
3065         u64 vmx_ept_vpid_cap;
3066
3067         vmx_ept_vpid_cap = vmx_control_msr(vmx->nested.msrs.ept_caps,
3068                                            vmx->nested.msrs.vpid_caps);
3069
3070         /* Every bit is either reserved or a feature bit. */
3071         if (!is_bitwise_subset(vmx_ept_vpid_cap, data, -1ULL))
3072                 return -EINVAL;
3073
3074         vmx->nested.msrs.ept_caps = data;
3075         vmx->nested.msrs.vpid_caps = data >> 32;
3076         return 0;
3077 }
3078
3079 static int vmx_restore_fixed0_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
3080 {
3081         u64 *msr;
3082
3083         switch (msr_index) {
3084         case MSR_IA32_VMX_CR0_FIXED0:
3085                 msr = &vmx->nested.msrs.cr0_fixed0;
3086                 break;
3087         case MSR_IA32_VMX_CR4_FIXED0:
3088                 msr = &vmx->nested.msrs.cr4_fixed0;
3089                 break;
3090         default:
3091                 BUG();
3092         }
3093
3094         /*
3095          * 1 bits (which indicates bits which "must-be-1" during VMX operation)
3096          * must be 1 in the restored value.
3097          */
3098         if (!is_bitwise_subset(data, *msr, -1ULL))
3099                 return -EINVAL;
3100
3101         *msr = data;
3102         return 0;
3103 }
3104
3105 /*
3106  * Called when userspace is restoring VMX MSRs.
3107  *
3108  * Returns 0 on success, non-0 otherwise.
3109  */
3110 static int vmx_set_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
3111 {
3112         struct vcpu_vmx *vmx = to_vmx(vcpu);
3113
3114         switch (msr_index) {
3115         case MSR_IA32_VMX_BASIC:
3116                 return vmx_restore_vmx_basic(vmx, data);
3117         case MSR_IA32_VMX_PINBASED_CTLS:
3118         case MSR_IA32_VMX_PROCBASED_CTLS:
3119         case MSR_IA32_VMX_EXIT_CTLS:
3120         case MSR_IA32_VMX_ENTRY_CTLS:
3121                 /*
3122                  * The "non-true" VMX capability MSRs are generated from the
3123                  * "true" MSRs, so we do not support restoring them directly.
3124                  *
3125                  * If userspace wants to emulate VMX_BASIC[55]=0, userspace
3126                  * should restore the "true" MSRs with the must-be-1 bits
3127                  * set according to the SDM Vol 3. A.2 "RESERVED CONTROLS AND
3128                  * DEFAULT SETTINGS".
3129                  */
3130                 return -EINVAL;
3131         case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3132         case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3133         case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3134         case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3135         case MSR_IA32_VMX_PROCBASED_CTLS2:
3136                 return vmx_restore_control_msr(vmx, msr_index, data);
3137         case MSR_IA32_VMX_MISC:
3138                 return vmx_restore_vmx_misc(vmx, data);
3139         case MSR_IA32_VMX_CR0_FIXED0:
3140         case MSR_IA32_VMX_CR4_FIXED0:
3141                 return vmx_restore_fixed0_msr(vmx, msr_index, data);
3142         case MSR_IA32_VMX_CR0_FIXED1:
3143         case MSR_IA32_VMX_CR4_FIXED1:
3144                 /*
3145                  * These MSRs are generated based on the vCPU's CPUID, so we
3146                  * do not support restoring them directly.
3147                  */
3148                 return -EINVAL;
3149         case MSR_IA32_VMX_EPT_VPID_CAP:
3150                 return vmx_restore_vmx_ept_vpid_cap(vmx, data);
3151         case MSR_IA32_VMX_VMCS_ENUM:
3152                 vmx->nested.msrs.vmcs_enum = data;
3153                 return 0;
3154         default:
3155                 /*
3156                  * The rest of the VMX capability MSRs do not support restore.
3157                  */
3158                 return -EINVAL;
3159         }
3160 }
3161
3162 /* Returns 0 on success, non-0 otherwise. */
3163 static int vmx_get_vmx_msr(struct nested_vmx_msrs *msrs, u32 msr_index, u64 *pdata)
3164 {
3165         switch (msr_index) {
3166         case MSR_IA32_VMX_BASIC:
3167                 *pdata = msrs->basic;
3168                 break;
3169         case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3170         case MSR_IA32_VMX_PINBASED_CTLS:
3171                 *pdata = vmx_control_msr(
3172                         msrs->pinbased_ctls_low,
3173                         msrs->pinbased_ctls_high);
3174                 if (msr_index == MSR_IA32_VMX_PINBASED_CTLS)
3175                         *pdata |= PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3176                 break;
3177         case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3178         case MSR_IA32_VMX_PROCBASED_CTLS:
3179                 *pdata = vmx_control_msr(
3180                         msrs->procbased_ctls_low,
3181                         msrs->procbased_ctls_high);
3182                 if (msr_index == MSR_IA32_VMX_PROCBASED_CTLS)
3183                         *pdata |= CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3184                 break;
3185         case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3186         case MSR_IA32_VMX_EXIT_CTLS:
3187                 *pdata = vmx_control_msr(
3188                         msrs->exit_ctls_low,
3189                         msrs->exit_ctls_high);
3190                 if (msr_index == MSR_IA32_VMX_EXIT_CTLS)
3191                         *pdata |= VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
3192                 break;
3193         case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3194         case MSR_IA32_VMX_ENTRY_CTLS:
3195                 *pdata = vmx_control_msr(
3196                         msrs->entry_ctls_low,
3197                         msrs->entry_ctls_high);
3198                 if (msr_index == MSR_IA32_VMX_ENTRY_CTLS)
3199                         *pdata |= VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
3200                 break;
3201         case MSR_IA32_VMX_MISC:
3202                 *pdata = vmx_control_msr(
3203                         msrs->misc_low,
3204                         msrs->misc_high);
3205                 break;
3206         case MSR_IA32_VMX_CR0_FIXED0:
3207                 *pdata = msrs->cr0_fixed0;
3208                 break;
3209         case MSR_IA32_VMX_CR0_FIXED1:
3210                 *pdata = msrs->cr0_fixed1;
3211                 break;
3212         case MSR_IA32_VMX_CR4_FIXED0:
3213                 *pdata = msrs->cr4_fixed0;
3214                 break;
3215         case MSR_IA32_VMX_CR4_FIXED1:
3216                 *pdata = msrs->cr4_fixed1;
3217                 break;
3218         case MSR_IA32_VMX_VMCS_ENUM:
3219                 *pdata = msrs->vmcs_enum;
3220                 break;
3221         case MSR_IA32_VMX_PROCBASED_CTLS2:
3222                 *pdata = vmx_control_msr(
3223                         msrs->secondary_ctls_low,
3224                         msrs->secondary_ctls_high);
3225                 break;
3226         case MSR_IA32_VMX_EPT_VPID_CAP:
3227                 *pdata = msrs->ept_caps |
3228                         ((u64)msrs->vpid_caps << 32);
3229                 break;
3230         case MSR_IA32_VMX_VMFUNC:
3231                 *pdata = msrs->vmfunc_controls;
3232                 break;
3233         default:
3234                 return 1;
3235         }
3236
3237         return 0;
3238 }
3239
3240 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
3241                                                  uint64_t val)
3242 {
3243         uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
3244
3245         return !(val & ~valid_bits);
3246 }
3247
3248 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
3249 {
3250         switch (msr->index) {
3251         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
3252                 if (!nested)
3253                         return 1;
3254                 return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
3255         default:
3256                 return 1;
3257         }
3258
3259         return 0;
3260 }
3261
3262 /*
3263  * Reads an msr value (of 'msr_index') into 'pdata'.
3264  * Returns 0 on success, non-0 otherwise.
3265  * Assumes vcpu_load() was already called.
3266  */
3267 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3268 {
3269         struct vcpu_vmx *vmx = to_vmx(vcpu);
3270         struct shared_msr_entry *msr;
3271
3272         switch (msr_info->index) {
3273 #ifdef CONFIG_X86_64
3274         case MSR_FS_BASE:
3275                 msr_info->data = vmcs_readl(GUEST_FS_BASE);
3276                 break;
3277         case MSR_GS_BASE:
3278                 msr_info->data = vmcs_readl(GUEST_GS_BASE);
3279                 break;
3280         case MSR_KERNEL_GS_BASE:
3281                 vmx_load_host_state(vmx);
3282                 msr_info->data = vmx->msr_guest_kernel_gs_base;
3283                 break;
3284 #endif
3285         case MSR_EFER:
3286                 return kvm_get_msr_common(vcpu, msr_info);
3287         case MSR_IA32_TSC:
3288                 msr_info->data = guest_read_tsc(vcpu);
3289                 break;
3290         case MSR_IA32_SPEC_CTRL:
3291                 if (!msr_info->host_initiated &&
3292                     !guest_cpuid_has(vcpu, X86_FEATURE_IBRS) &&
3293                     !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
3294                         return 1;
3295
3296                 msr_info->data = to_vmx(vcpu)->spec_ctrl;
3297                 break;
3298         case MSR_IA32_ARCH_CAPABILITIES:
3299                 if (!msr_info->host_initiated &&
3300                     !guest_cpuid_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
3301                         return 1;
3302                 msr_info->data = to_vmx(vcpu)->arch_capabilities;
3303                 break;
3304         case MSR_IA32_SYSENTER_CS:
3305                 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
3306                 break;
3307         case MSR_IA32_SYSENTER_EIP:
3308                 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
3309                 break;
3310         case MSR_IA32_SYSENTER_ESP:
3311                 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
3312                 break;
3313         case MSR_IA32_BNDCFGS:
3314                 if (!kvm_mpx_supported() ||
3315                     (!msr_info->host_initiated &&
3316                      !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
3317                         return 1;
3318                 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
3319                 break;
3320         case MSR_IA32_MCG_EXT_CTL:
3321                 if (!msr_info->host_initiated &&
3322                     !(vmx->msr_ia32_feature_control &
3323                       FEATURE_CONTROL_LMCE))
3324                         return 1;
3325                 msr_info->data = vcpu->arch.mcg_ext_ctl;
3326                 break;
3327         case MSR_IA32_FEATURE_CONTROL:
3328                 msr_info->data = vmx->msr_ia32_feature_control;
3329                 break;
3330         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
3331                 if (!nested_vmx_allowed(vcpu))
3332                         return 1;
3333                 return vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
3334                                        &msr_info->data);
3335         case MSR_IA32_XSS:
3336                 if (!vmx_xsaves_supported())
3337                         return 1;
3338                 msr_info->data = vcpu->arch.ia32_xss;
3339                 break;
3340         case MSR_TSC_AUX:
3341                 if (!msr_info->host_initiated &&
3342                     !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
3343                         return 1;
3344                 /* Otherwise falls through */
3345         default:
3346                 msr = find_msr_entry(vmx, msr_info->index);
3347                 if (msr) {
3348                         msr_info->data = msr->data;
3349                         break;
3350                 }
3351                 return kvm_get_msr_common(vcpu, msr_info);
3352         }
3353
3354         return 0;
3355 }
3356
3357 static void vmx_leave_nested(struct kvm_vcpu *vcpu);
3358
3359 /*
3360  * Writes msr value into into the appropriate "register".
3361  * Returns 0 on success, non-0 otherwise.
3362  * Assumes vcpu_load() was already called.
3363  */
3364 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3365 {
3366         struct vcpu_vmx *vmx = to_vmx(vcpu);
3367         struct shared_msr_entry *msr;
3368         int ret = 0;
3369         u32 msr_index = msr_info->index;
3370         u64 data = msr_info->data;
3371
3372         switch (msr_index) {
3373         case MSR_EFER:
3374                 ret = kvm_set_msr_common(vcpu, msr_info);
3375                 break;
3376 #ifdef CONFIG_X86_64
3377         case MSR_FS_BASE:
3378                 vmx_segment_cache_clear(vmx);
3379                 vmcs_writel(GUEST_FS_BASE, data);
3380                 break;
3381         case MSR_GS_BASE:
3382                 vmx_segment_cache_clear(vmx);
3383                 vmcs_writel(GUEST_GS_BASE, data);
3384                 break;
3385         case MSR_KERNEL_GS_BASE:
3386                 vmx_load_host_state(vmx);
3387                 vmx->msr_guest_kernel_gs_base = data;
3388                 break;
3389 #endif
3390         case MSR_IA32_SYSENTER_CS:
3391                 vmcs_write32(GUEST_SYSENTER_CS, data);
3392                 break;
3393         case MSR_IA32_SYSENTER_EIP:
3394                 vmcs_writel(GUEST_SYSENTER_EIP, data);
3395                 break;
3396         case MSR_IA32_SYSENTER_ESP:
3397                 vmcs_writel(GUEST_SYSENTER_ESP, data);
3398                 break;
3399         case MSR_IA32_BNDCFGS:
3400                 if (!kvm_mpx_supported() ||
3401                     (!msr_info->host_initiated &&
3402                      !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
3403                         return 1;
3404                 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
3405                     (data & MSR_IA32_BNDCFGS_RSVD))
3406                         return 1;
3407                 vmcs_write64(GUEST_BNDCFGS, data);
3408                 break;
3409         case MSR_IA32_TSC:
3410                 kvm_write_tsc(vcpu, msr_info);
3411                 break;
3412         case MSR_IA32_SPEC_CTRL:
3413                 if (!msr_info->host_initiated &&
3414                     !guest_cpuid_has(vcpu, X86_FEATURE_IBRS) &&
3415                     !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
3416                         return 1;
3417
3418                 /* The STIBP bit doesn't fault even if it's not advertised */
3419                 if (data & ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP))
3420                         return 1;
3421
3422                 vmx->spec_ctrl = data;
3423
3424                 if (!data)
3425                         break;
3426
3427                 /*
3428                  * For non-nested:
3429                  * When it's written (to non-zero) for the first time, pass
3430                  * it through.
3431                  *
3432                  * For nested:
3433                  * The handling of the MSR bitmap for L2 guests is done in
3434                  * nested_vmx_merge_msr_bitmap. We should not touch the
3435                  * vmcs02.msr_bitmap here since it gets completely overwritten
3436                  * in the merging. We update the vmcs01 here for L1 as well
3437                  * since it will end up touching the MSR anyway now.
3438                  */
3439                 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap,
3440                                               MSR_IA32_SPEC_CTRL,
3441                                               MSR_TYPE_RW);
3442                 break;
3443         case MSR_IA32_PRED_CMD:
3444                 if (!msr_info->host_initiated &&
3445                     !guest_cpuid_has(vcpu, X86_FEATURE_IBPB) &&
3446                     !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
3447                         return 1;
3448
3449                 if (data & ~PRED_CMD_IBPB)
3450                         return 1;
3451
3452                 if (!data)
3453                         break;
3454
3455                 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
3456
3457                 /*
3458                  * For non-nested:
3459                  * When it's written (to non-zero) for the first time, pass
3460                  * it through.
3461                  *
3462                  * For nested:
3463                  * The handling of the MSR bitmap for L2 guests is done in
3464                  * nested_vmx_merge_msr_bitmap. We should not touch the
3465                  * vmcs02.msr_bitmap here since it gets completely overwritten
3466                  * in the merging.
3467                  */
3468                 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap, MSR_IA32_PRED_CMD,
3469                                               MSR_TYPE_W);
3470                 break;
3471         case MSR_IA32_ARCH_CAPABILITIES:
3472                 if (!msr_info->host_initiated)
3473                         return 1;
3474                 vmx->arch_capabilities = data;
3475                 break;
3476         case MSR_IA32_CR_PAT:
3477                 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
3478                         if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
3479                                 return 1;
3480                         vmcs_write64(GUEST_IA32_PAT, data);
3481                         vcpu->arch.pat = data;
3482                         break;
3483                 }
3484                 ret = kvm_set_msr_common(vcpu, msr_info);
3485                 break;
3486         case MSR_IA32_TSC_ADJUST:
3487                 ret = kvm_set_msr_common(vcpu, msr_info);
3488                 break;
3489         case MSR_IA32_MCG_EXT_CTL:
3490                 if ((!msr_info->host_initiated &&
3491                      !(to_vmx(vcpu)->msr_ia32_feature_control &
3492                        FEATURE_CONTROL_LMCE)) ||
3493                     (data & ~MCG_EXT_CTL_LMCE_EN))
3494                         return 1;
3495                 vcpu->arch.mcg_ext_ctl = data;
3496                 break;
3497         case MSR_IA32_FEATURE_CONTROL:
3498                 if (!vmx_feature_control_msr_valid(vcpu, data) ||
3499                     (to_vmx(vcpu)->msr_ia32_feature_control &
3500                      FEATURE_CONTROL_LOCKED && !msr_info->host_initiated))
3501                         return 1;
3502                 vmx->msr_ia32_feature_control = data;
3503                 if (msr_info->host_initiated && data == 0)
3504                         vmx_leave_nested(vcpu);
3505                 break;
3506         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
3507                 if (!msr_info->host_initiated)
3508                         return 1; /* they are read-only */
3509                 if (!nested_vmx_allowed(vcpu))
3510                         return 1;
3511                 return vmx_set_vmx_msr(vcpu, msr_index, data);
3512         case MSR_IA32_XSS:
3513                 if (!vmx_xsaves_supported())
3514                         return 1;
3515                 /*
3516                  * The only supported bit as of Skylake is bit 8, but
3517                  * it is not supported on KVM.
3518                  */
3519                 if (data != 0)
3520                         return 1;
3521                 vcpu->arch.ia32_xss = data;
3522                 if (vcpu->arch.ia32_xss != host_xss)
3523                         add_atomic_switch_msr(vmx, MSR_IA32_XSS,
3524                                 vcpu->arch.ia32_xss, host_xss);
3525                 else
3526                         clear_atomic_switch_msr(vmx, MSR_IA32_XSS);
3527                 break;
3528         case MSR_TSC_AUX:
3529                 if (!msr_info->host_initiated &&
3530                     !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
3531                         return 1;
3532                 /* Check reserved bit, higher 32 bits should be zero */
3533                 if ((data >> 32) != 0)
3534                         return 1;
3535                 /* Otherwise falls through */
3536         default:
3537                 msr = find_msr_entry(vmx, msr_index);
3538                 if (msr) {
3539                         u64 old_msr_data = msr->data;
3540                         msr->data = data;
3541                         if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
3542                                 preempt_disable();
3543                                 ret = kvm_set_shared_msr(msr->index, msr->data,
3544                                                          msr->mask);
3545                                 preempt_enable();
3546                                 if (ret)
3547                                         msr->data = old_msr_data;
3548                         }
3549                         break;
3550                 }
3551                 ret = kvm_set_msr_common(vcpu, msr_info);
3552         }
3553
3554         return ret;
3555 }
3556
3557 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
3558 {
3559         __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
3560         switch (reg) {
3561         case VCPU_REGS_RSP:
3562                 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
3563                 break;
3564         case VCPU_REGS_RIP:
3565                 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
3566                 break;
3567         case VCPU_EXREG_PDPTR:
3568                 if (enable_ept)
3569                         ept_save_pdptrs(vcpu);
3570                 break;
3571         default:
3572                 break;
3573         }
3574 }
3575
3576 static __init int cpu_has_kvm_support(void)
3577 {
3578         return cpu_has_vmx();
3579 }
3580
3581 static __init int vmx_disabled_by_bios(void)
3582 {
3583         u64 msr;
3584
3585         rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
3586         if (msr & FEATURE_CONTROL_LOCKED) {
3587                 /* launched w/ TXT and VMX disabled */
3588                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
3589                         && tboot_enabled())
3590                         return 1;
3591                 /* launched w/o TXT and VMX only enabled w/ TXT */
3592                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
3593                         && (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
3594                         && !tboot_enabled()) {
3595                         printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
3596                                 "activate TXT before enabling KVM\n");
3597                         return 1;
3598                 }
3599                 /* launched w/o TXT and VMX disabled */
3600                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
3601                         && !tboot_enabled())
3602                         return 1;
3603         }
3604
3605         return 0;
3606 }
3607
3608 static void kvm_cpu_vmxon(u64 addr)
3609 {
3610         cr4_set_bits(X86_CR4_VMXE);
3611         intel_pt_handle_vmx(1);
3612
3613         asm volatile (ASM_VMX_VMXON_RAX
3614                         : : "a"(&addr), "m"(addr)
3615                         : "memory", "cc");
3616 }
3617
3618 static int hardware_enable(void)
3619 {
3620         int cpu = raw_smp_processor_id();
3621         u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
3622         u64 old, test_bits;
3623
3624         if (cr4_read_shadow() & X86_CR4_VMXE)
3625                 return -EBUSY;
3626
3627         INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
3628         INIT_LIST_HEAD(&per_cpu(blocked_vcpu_on_cpu, cpu));
3629         spin_lock_init(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
3630
3631         /*
3632          * Now we can enable the vmclear operation in kdump
3633          * since the loaded_vmcss_on_cpu list on this cpu
3634          * has been initialized.
3635          *
3636          * Though the cpu is not in VMX operation now, there
3637          * is no problem to enable the vmclear operation
3638          * for the loaded_vmcss_on_cpu list is empty!
3639          */
3640         crash_enable_local_vmclear(cpu);
3641
3642         rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
3643
3644         test_bits = FEATURE_CONTROL_LOCKED;
3645         test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
3646         if (tboot_enabled())
3647                 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
3648
3649         if ((old & test_bits) != test_bits) {
3650                 /* enable and lock */
3651                 wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
3652         }
3653         kvm_cpu_vmxon(phys_addr);
3654         if (enable_ept)
3655                 ept_sync_global();
3656
3657         return 0;
3658 }
3659
3660 static void vmclear_local_loaded_vmcss(void)
3661 {
3662         int cpu = raw_smp_processor_id();
3663         struct loaded_vmcs *v, *n;
3664
3665         list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
3666                                  loaded_vmcss_on_cpu_link)
3667                 __loaded_vmcs_clear(v);
3668 }
3669
3670
3671 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
3672  * tricks.
3673  */
3674 static void kvm_cpu_vmxoff(void)
3675 {
3676         asm volatile (__ex(ASM_VMX_VMXOFF) : : : "cc");
3677
3678         intel_pt_handle_vmx(0);
3679         cr4_clear_bits(X86_CR4_VMXE);
3680 }
3681
3682 static void hardware_disable(void)
3683 {
3684         vmclear_local_loaded_vmcss();
3685         kvm_cpu_vmxoff();
3686 }
3687
3688 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
3689                                       u32 msr, u32 *result)
3690 {
3691         u32 vmx_msr_low, vmx_msr_high;
3692         u32 ctl = ctl_min | ctl_opt;
3693
3694         rdmsr(msr, vmx_msr_low, vmx_msr_high);
3695
3696         ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
3697         ctl |= vmx_msr_low;  /* bit == 1 in low word  ==> must be one  */
3698
3699         /* Ensure minimum (required) set of control bits are supported. */
3700         if (ctl_min & ~ctl)
3701                 return -EIO;
3702
3703         *result = ctl;
3704         return 0;
3705 }
3706
3707 static __init bool allow_1_setting(u32 msr, u32 ctl)
3708 {
3709         u32 vmx_msr_low, vmx_msr_high;
3710
3711         rdmsr(msr, vmx_msr_low, vmx_msr_high);
3712         return vmx_msr_high & ctl;
3713 }
3714
3715 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
3716 {
3717         u32 vmx_msr_low, vmx_msr_high;
3718         u32 min, opt, min2, opt2;
3719         u32 _pin_based_exec_control = 0;
3720         u32 _cpu_based_exec_control = 0;
3721         u32 _cpu_based_2nd_exec_control = 0;
3722         u32 _vmexit_control = 0;
3723         u32 _vmentry_control = 0;
3724
3725         memset(vmcs_conf, 0, sizeof(*vmcs_conf));
3726         min = CPU_BASED_HLT_EXITING |
3727 #ifdef CONFIG_X86_64
3728               CPU_BASED_CR8_LOAD_EXITING |
3729               CPU_BASED_CR8_STORE_EXITING |
3730 #endif
3731               CPU_BASED_CR3_LOAD_EXITING |
3732               CPU_BASED_CR3_STORE_EXITING |
3733               CPU_BASED_UNCOND_IO_EXITING |
3734               CPU_BASED_MOV_DR_EXITING |
3735               CPU_BASED_USE_TSC_OFFSETING |
3736               CPU_BASED_INVLPG_EXITING |
3737               CPU_BASED_RDPMC_EXITING;
3738
3739         if (!kvm_mwait_in_guest())
3740                 min |= CPU_BASED_MWAIT_EXITING |
3741                         CPU_BASED_MONITOR_EXITING;
3742
3743         opt = CPU_BASED_TPR_SHADOW |
3744               CPU_BASED_USE_MSR_BITMAPS |
3745               CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
3746         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
3747                                 &_cpu_based_exec_control) < 0)
3748                 return -EIO;
3749 #ifdef CONFIG_X86_64
3750         if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
3751                 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
3752                                            ~CPU_BASED_CR8_STORE_EXITING;
3753 #endif
3754         if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
3755                 min2 = 0;
3756                 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
3757                         SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
3758                         SECONDARY_EXEC_WBINVD_EXITING |
3759                         SECONDARY_EXEC_ENABLE_VPID |
3760                         SECONDARY_EXEC_ENABLE_EPT |
3761                         SECONDARY_EXEC_UNRESTRICTED_GUEST |
3762                         SECONDARY_EXEC_PAUSE_LOOP_EXITING |
3763                         SECONDARY_EXEC_DESC |
3764                         SECONDARY_EXEC_RDTSCP |
3765                         SECONDARY_EXEC_ENABLE_INVPCID |
3766                         SECONDARY_EXEC_APIC_REGISTER_VIRT |
3767                         SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
3768                         SECONDARY_EXEC_SHADOW_VMCS |
3769                         SECONDARY_EXEC_XSAVES |
3770                         SECONDARY_EXEC_RDSEED_EXITING |
3771                         SECONDARY_EXEC_RDRAND_EXITING |
3772                         SECONDARY_EXEC_ENABLE_PML |
3773                         SECONDARY_EXEC_TSC_SCALING |
3774                         SECONDARY_EXEC_ENABLE_VMFUNC;
3775                 if (adjust_vmx_controls(min2, opt2,
3776                                         MSR_IA32_VMX_PROCBASED_CTLS2,
3777                                         &_cpu_based_2nd_exec_control) < 0)
3778                         return -EIO;
3779         }
3780 #ifndef CONFIG_X86_64
3781         if (!(_cpu_based_2nd_exec_control &
3782                                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
3783                 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
3784 #endif
3785
3786         if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
3787                 _cpu_based_2nd_exec_control &= ~(
3788                                 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3789                                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
3790                                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
3791
3792         rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
3793                 &vmx_capability.ept, &vmx_capability.vpid);
3794
3795         if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
3796                 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
3797                    enabled */
3798                 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
3799                                              CPU_BASED_CR3_STORE_EXITING |
3800                                              CPU_BASED_INVLPG_EXITING);
3801         } else if (vmx_capability.ept) {
3802                 vmx_capability.ept = 0;
3803                 pr_warn_once("EPT CAP should not exist if not support "
3804                                 "1-setting enable EPT VM-execution control\n");
3805         }
3806         if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
3807                 vmx_capability.vpid) {
3808                 vmx_capability.vpid = 0;
3809                 pr_warn_once("VPID CAP should not exist if not support "
3810                                 "1-setting enable VPID VM-execution control\n");
3811         }
3812
3813         min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
3814 #ifdef CONFIG_X86_64
3815         min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
3816 #endif
3817         opt = VM_EXIT_SAVE_IA32_PAT | VM_EXIT_LOAD_IA32_PAT |
3818                 VM_EXIT_CLEAR_BNDCFGS;
3819         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
3820                                 &_vmexit_control) < 0)
3821                 return -EIO;
3822
3823         min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
3824         opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
3825                  PIN_BASED_VMX_PREEMPTION_TIMER;
3826         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
3827                                 &_pin_based_exec_control) < 0)
3828                 return -EIO;
3829
3830         if (cpu_has_broken_vmx_preemption_timer())
3831                 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
3832         if (!(_cpu_based_2nd_exec_control &
3833                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
3834                 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
3835
3836         min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
3837         opt = VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_BNDCFGS;
3838         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
3839                                 &_vmentry_control) < 0)
3840                 return -EIO;
3841
3842         rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
3843
3844         /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
3845         if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
3846                 return -EIO;
3847
3848 #ifdef CONFIG_X86_64
3849         /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
3850         if (vmx_msr_high & (1u<<16))
3851                 return -EIO;
3852 #endif
3853
3854         /* Require Write-Back (WB) memory type for VMCS accesses. */
3855         if (((vmx_msr_high >> 18) & 15) != 6)
3856                 return -EIO;
3857
3858         vmcs_conf->size = vmx_msr_high & 0x1fff;
3859         vmcs_conf->order = get_order(vmcs_conf->size);
3860         vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
3861         vmcs_conf->revision_id = vmx_msr_low;
3862
3863         vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
3864         vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
3865         vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
3866         vmcs_conf->vmexit_ctrl         = _vmexit_control;
3867         vmcs_conf->vmentry_ctrl        = _vmentry_control;
3868
3869         cpu_has_load_ia32_efer =
3870                 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
3871                                 VM_ENTRY_LOAD_IA32_EFER)
3872                 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
3873                                    VM_EXIT_LOAD_IA32_EFER);
3874
3875         cpu_has_load_perf_global_ctrl =
3876                 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
3877                                 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
3878                 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
3879                                    VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
3880
3881         /*
3882          * Some cpus support VM_ENTRY_(LOAD|SAVE)_IA32_PERF_GLOBAL_CTRL
3883          * but due to errata below it can't be used. Workaround is to use
3884          * msr load mechanism to switch IA32_PERF_GLOBAL_CTRL.
3885          *
3886          * VM Exit May Incorrectly Clear IA32_PERF_GLOBAL_CTRL [34:32]
3887          *
3888          * AAK155             (model 26)
3889          * AAP115             (model 30)
3890          * AAT100             (model 37)
3891          * BC86,AAY89,BD102   (model 44)
3892          * BA97               (model 46)
3893          *
3894          */
3895         if (cpu_has_load_perf_global_ctrl && boot_cpu_data.x86 == 0x6) {
3896                 switch (boot_cpu_data.x86_model) {
3897                 case 26:
3898                 case 30:
3899                 case 37:
3900                 case 44:
3901                 case 46:
3902                         cpu_has_load_perf_global_ctrl = false;
3903                         printk_once(KERN_WARNING"kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
3904                                         "does not work properly. Using workaround\n");
3905                         break;
3906                 default:
3907                         break;
3908                 }
3909         }
3910
3911         if (boot_cpu_has(X86_FEATURE_XSAVES))
3912                 rdmsrl(MSR_IA32_XSS, host_xss);
3913
3914         return 0;
3915 }
3916
3917 static struct vmcs *alloc_vmcs_cpu(int cpu)
3918 {
3919         int node = cpu_to_node(cpu);
3920         struct page *pages;
3921         struct vmcs *vmcs;
3922
3923         pages = __alloc_pages_node(node, GFP_KERNEL, vmcs_config.order);
3924         if (!pages)
3925                 return NULL;
3926         vmcs = page_address(pages);
3927         memset(vmcs, 0, vmcs_config.size);
3928         vmcs->revision_id = vmcs_config.revision_id; /* vmcs revision id */
3929         return vmcs;
3930 }
3931
3932 static void free_vmcs(struct vmcs *vmcs)
3933 {
3934         free_pages((unsigned long)vmcs, vmcs_config.order);
3935 }
3936
3937 /*
3938  * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
3939  */
3940 static void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
3941 {
3942         if (!loaded_vmcs->vmcs)
3943                 return;
3944         loaded_vmcs_clear(loaded_vmcs);
3945         free_vmcs(loaded_vmcs->vmcs);
3946         loaded_vmcs->vmcs = NULL;
3947         if (loaded_vmcs->msr_bitmap)
3948                 free_page((unsigned long)loaded_vmcs->msr_bitmap);
3949         WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
3950 }
3951
3952 static struct vmcs *alloc_vmcs(void)
3953 {
3954         return alloc_vmcs_cpu(raw_smp_processor_id());
3955 }
3956
3957 static int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
3958 {
3959         loaded_vmcs->vmcs = alloc_vmcs();
3960         if (!loaded_vmcs->vmcs)
3961                 return -ENOMEM;
3962
3963         loaded_vmcs->shadow_vmcs = NULL;
3964         loaded_vmcs_init(loaded_vmcs);
3965
3966         if (cpu_has_vmx_msr_bitmap()) {
3967                 loaded_vmcs->msr_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);
3968                 if (!loaded_vmcs->msr_bitmap)
3969                         goto out_vmcs;
3970                 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
3971         }
3972         return 0;
3973
3974 out_vmcs:
3975         free_loaded_vmcs(loaded_vmcs);
3976         return -ENOMEM;
3977 }
3978
3979 static void free_kvm_area(void)
3980 {
3981         int cpu;
3982
3983         for_each_possible_cpu(cpu) {
3984                 free_vmcs(per_cpu(vmxarea, cpu));
3985                 per_cpu(vmxarea, cpu) = NULL;
3986         }
3987 }
3988
3989 enum vmcs_field_width {
3990         VMCS_FIELD_WIDTH_U16 = 0,
3991         VMCS_FIELD_WIDTH_U64 = 1,
3992         VMCS_FIELD_WIDTH_U32 = 2,
3993         VMCS_FIELD_WIDTH_NATURAL_WIDTH = 3
3994 };
3995
3996 static inline int vmcs_field_width(unsigned long field)
3997 {
3998         if (0x1 & field)        /* the *_HIGH fields are all 32 bit */
3999                 return VMCS_FIELD_WIDTH_U32;
4000         return (field >> 13) & 0x3 ;
4001 }
4002
4003 static inline int vmcs_field_readonly(unsigned long field)
4004 {
4005         return (((field >> 10) & 0x3) == 1);
4006 }
4007
4008 static void init_vmcs_shadow_fields(void)
4009 {
4010         int i, j;
4011
4012         for (i = j = 0; i < max_shadow_read_only_fields; i++) {
4013                 u16 field = shadow_read_only_fields[i];
4014                 if (vmcs_field_width(field) == VMCS_FIELD_WIDTH_U64 &&
4015                     (i + 1 == max_shadow_read_only_fields ||
4016                      shadow_read_only_fields[i + 1] != field + 1))
4017                         pr_err("Missing field from shadow_read_only_field %x\n",
4018                                field + 1);
4019
4020                 clear_bit(field, vmx_vmread_bitmap);
4021 #ifdef CONFIG_X86_64
4022                 if (field & 1)
4023                         continue;
4024 #endif
4025                 if (j < i)
4026                         shadow_read_only_fields[j] = field;
4027                 j++;
4028         }
4029         max_shadow_read_only_fields = j;
4030
4031         for (i = j = 0; i < max_shadow_read_write_fields; i++) {
4032                 u16 field = shadow_read_write_fields[i];
4033                 if (vmcs_field_width(field) == VMCS_FIELD_WIDTH_U64 &&
4034                     (i + 1 == max_shadow_read_write_fields ||
4035                      shadow_read_write_fields[i + 1] != field + 1))
4036                         pr_err("Missing field from shadow_read_write_field %x\n",
4037                                field + 1);
4038
4039                 /*
4040                  * PML and the preemption timer can be emulated, but the
4041                  * processor cannot vmwrite to fields that don't exist
4042                  * on bare metal.
4043                  */
4044                 switch (field) {
4045                 case GUEST_PML_INDEX:
4046                         if (!cpu_has_vmx_pml())
4047                                 continue;
4048                         break;
4049                 case VMX_PREEMPTION_TIMER_VALUE:
4050                         if (!cpu_has_vmx_preemption_timer())
4051                                 continue;
4052                         break;
4053                 case GUEST_INTR_STATUS:
4054                         if (!cpu_has_vmx_apicv())
4055                                 continue;
4056                         break;
4057                 default:
4058                         break;
4059                 }
4060
4061                 clear_bit(field, vmx_vmwrite_bitmap);
4062                 clear_bit(field, vmx_vmread_bitmap);
4063 #ifdef CONFIG_X86_64
4064                 if (field & 1)
4065                         continue;
4066 #endif
4067                 if (j < i)
4068                         shadow_read_write_fields[j] = field;
4069                 j++;
4070         }
4071         max_shadow_read_write_fields = j;
4072 }
4073
4074 static __init int alloc_kvm_area(void)
4075 {
4076         int cpu;
4077
4078         for_each_possible_cpu(cpu) {
4079                 struct vmcs *vmcs;
4080
4081                 vmcs = alloc_vmcs_cpu(cpu);
4082                 if (!vmcs) {
4083                         free_kvm_area();
4084                         return -ENOMEM;
4085                 }
4086
4087                 per_cpu(vmxarea, cpu) = vmcs;
4088         }
4089         return 0;
4090 }
4091
4092 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
4093                 struct kvm_segment *save)
4094 {
4095         if (!emulate_invalid_guest_state) {
4096                 /*
4097                  * CS and SS RPL should be equal during guest entry according
4098                  * to VMX spec, but in reality it is not always so. Since vcpu
4099                  * is in the middle of the transition from real mode to
4100                  * protected mode it is safe to assume that RPL 0 is a good
4101                  * default value.
4102                  */
4103                 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
4104                         save->selector &= ~SEGMENT_RPL_MASK;
4105                 save->dpl = save->selector & SEGMENT_RPL_MASK;
4106                 save->s = 1;
4107         }
4108         vmx_set_segment(vcpu, save, seg);
4109 }
4110
4111 static void enter_pmode(struct kvm_vcpu *vcpu)
4112 {
4113         unsigned long flags;
4114         struct vcpu_vmx *vmx = to_vmx(vcpu);
4115
4116         /*
4117          * Update real mode segment cache. It may be not up-to-date if sement
4118          * register was written while vcpu was in a guest mode.
4119          */
4120         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
4121         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
4122         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
4123         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
4124         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
4125         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
4126
4127         vmx->rmode.vm86_active = 0;
4128
4129         vmx_segment_cache_clear(vmx);
4130
4131         vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
4132
4133         flags = vmcs_readl(GUEST_RFLAGS);
4134         flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
4135         flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
4136         vmcs_writel(GUEST_RFLAGS, flags);
4137
4138         vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
4139                         (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
4140
4141         update_exception_bitmap(vcpu);
4142
4143         fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
4144         fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
4145         fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
4146         fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
4147         fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
4148         fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
4149 }
4150
4151 static void fix_rmode_seg(int seg, struct kvm_segment *save)
4152 {
4153         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
4154         struct kvm_segment var = *save;
4155
4156         var.dpl = 0x3;
4157         if (seg == VCPU_SREG_CS)
4158                 var.type = 0x3;
4159
4160         if (!emulate_invalid_guest_state) {
4161                 var.selector = var.base >> 4;
4162                 var.base = var.base & 0xffff0;
4163                 var.limit = 0xffff;
4164                 var.g = 0;
4165                 var.db = 0;
4166                 var.present = 1;
4167                 var.s = 1;
4168                 var.l = 0;
4169                 var.unusable = 0;
4170                 var.type = 0x3;
4171                 var.avl = 0;
4172                 if (save->base & 0xf)
4173                         printk_once(KERN_WARNING "kvm: segment base is not "
4174                                         "paragraph aligned when entering "
4175                                         "protected mode (seg=%d)", seg);
4176         }
4177
4178         vmcs_write16(sf->selector, var.selector);
4179         vmcs_writel(sf->base, var.base);
4180         vmcs_write32(sf->limit, var.limit);
4181         vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
4182 }
4183
4184 static void enter_rmode(struct kvm_vcpu *vcpu)
4185 {
4186         unsigned long flags;
4187         struct vcpu_vmx *vmx = to_vmx(vcpu);
4188
4189         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
4190         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
4191         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
4192         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
4193         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
4194         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
4195         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
4196
4197         vmx->rmode.vm86_active = 1;
4198
4199         /*
4200          * Very old userspace does not call KVM_SET_TSS_ADDR before entering
4201          * vcpu. Warn the user that an update is overdue.
4202          */
4203         if (!vcpu->kvm->arch.tss_addr)
4204                 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
4205                              "called before entering vcpu\n");
4206
4207         vmx_segment_cache_clear(vmx);
4208
4209         vmcs_writel(GUEST_TR_BASE, vcpu->kvm->arch.tss_addr);
4210         vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
4211         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4212
4213         flags = vmcs_readl(GUEST_RFLAGS);
4214         vmx->rmode.save_rflags = flags;
4215
4216         flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
4217
4218         vmcs_writel(GUEST_RFLAGS, flags);
4219         vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
4220         update_exception_bitmap(vcpu);
4221
4222         fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
4223         fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
4224         fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
4225         fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
4226         fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
4227         fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
4228
4229         kvm_mmu_reset_context(vcpu);
4230 }
4231
4232 static void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
4233 {
4234         struct vcpu_vmx *vmx = to_vmx(vcpu);
4235         struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
4236
4237         if (!msr)
4238                 return;
4239
4240         /*
4241          * Force kernel_gs_base reloading before EFER changes, as control
4242          * of this msr depends on is_long_mode().
4243          */
4244         vmx_load_host_state(to_vmx(vcpu));
4245         vcpu->arch.efer = efer;
4246         if (efer & EFER_LMA) {
4247                 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
4248                 msr->data = efer;
4249         } else {
4250                 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
4251
4252                 msr->data = efer & ~EFER_LME;
4253         }
4254         setup_msrs(vmx);
4255 }
4256
4257 #ifdef CONFIG_X86_64
4258
4259 static void enter_lmode(struct kvm_vcpu *vcpu)
4260 {
4261         u32 guest_tr_ar;
4262
4263         vmx_segment_cache_clear(to_vmx(vcpu));
4264
4265         guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
4266         if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
4267                 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
4268                                      __func__);
4269                 vmcs_write32(GUEST_TR_AR_BYTES,
4270                              (guest_tr_ar & ~VMX_AR_TYPE_MASK)
4271                              | VMX_AR_TYPE_BUSY_64_TSS);
4272         }
4273         vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
4274 }
4275
4276 static void exit_lmode(struct kvm_vcpu *vcpu)
4277 {
4278         vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
4279         vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
4280 }
4281
4282 #endif
4283
4284 static inline void __vmx_flush_tlb(struct kvm_vcpu *vcpu, int vpid,
4285                                 bool invalidate_gpa)
4286 {
4287         if (enable_ept && (invalidate_gpa || !enable_vpid)) {
4288                 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
4289                         return;
4290                 ept_sync_context(construct_eptp(vcpu, vcpu->arch.mmu.root_hpa));
4291         } else {
4292                 vpid_sync_context(vpid);
4293         }
4294 }
4295
4296 static void vmx_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa)
4297 {
4298         __vmx_flush_tlb(vcpu, to_vmx(vcpu)->vpid, invalidate_gpa);
4299 }
4300
4301 static void vmx_flush_tlb_ept_only(struct kvm_vcpu *vcpu)
4302 {
4303         if (enable_ept)
4304                 vmx_flush_tlb(vcpu, true);
4305 }
4306
4307 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
4308 {
4309         ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
4310
4311         vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
4312         vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
4313 }
4314
4315 static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
4316 {
4317         if (enable_unrestricted_guest || (enable_ept && is_paging(vcpu)))
4318                 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
4319         __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
4320 }
4321
4322 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
4323 {
4324         ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
4325
4326         vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
4327         vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
4328 }
4329
4330 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
4331 {
4332         struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
4333
4334         if (!test_bit(VCPU_EXREG_PDPTR,
4335                       (unsigned long *)&vcpu->arch.regs_dirty))
4336                 return;
4337
4338         if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
4339                 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
4340                 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
4341                 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
4342                 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
4343         }
4344 }
4345
4346 static void ept_save_pdptrs(struct kvm_vcpu *vcpu)
4347 {
4348         struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
4349
4350         if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
4351                 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
4352                 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
4353                 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
4354                 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
4355         }
4356
4357         __set_bit(VCPU_EXREG_PDPTR,
4358                   (unsigned long *)&vcpu->arch.regs_avail);
4359         __set_bit(VCPU_EXREG_PDPTR,
4360                   (unsigned long *)&vcpu->arch.regs_dirty);
4361 }
4362
4363 static bool nested_guest_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
4364 {
4365         u64 fixed0 = to_vmx(vcpu)->nested.msrs.cr0_fixed0;
4366         u64 fixed1 = to_vmx(vcpu)->nested.msrs.cr0_fixed1;
4367         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4368
4369         if (to_vmx(vcpu)->nested.msrs.secondary_ctls_high &
4370                 SECONDARY_EXEC_UNRESTRICTED_GUEST &&
4371             nested_cpu_has2(vmcs12, SECONDARY_EXEC_UNRESTRICTED_GUEST))
4372                 fixed0 &= ~(X86_CR0_PE | X86_CR0_PG);
4373
4374         return fixed_bits_valid(val, fixed0, fixed1);
4375 }
4376
4377 static bool nested_host_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
4378 {
4379         u64 fixed0 = to_vmx(vcpu)->nested.msrs.cr0_fixed0;
4380         u64 fixed1 = to_vmx(vcpu)->nested.msrs.cr0_fixed1;
4381
4382         return fixed_bits_valid(val, fixed0, fixed1);
4383 }
4384
4385 static bool nested_cr4_valid(struct kvm_vcpu *vcpu, unsigned long val)
4386 {
4387         u64 fixed0 = to_vmx(vcpu)->nested.msrs.cr4_fixed0;
4388         u64 fixed1 = to_vmx(vcpu)->nested.msrs.cr4_fixed1;
4389
4390         return fixed_bits_valid(val, fixed0, fixed1);
4391 }
4392
4393 /* No difference in the restrictions on guest and host CR4 in VMX operation. */
4394 #define nested_guest_cr4_valid  nested_cr4_valid
4395 #define nested_host_cr4_valid   nested_cr4_valid
4396
4397 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
4398
4399 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
4400                                         unsigned long cr0,
4401                                         struct kvm_vcpu *vcpu)
4402 {
4403         if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
4404                 vmx_decache_cr3(vcpu);
4405         if (!(cr0 & X86_CR0_PG)) {
4406                 /* From paging/starting to nonpaging */
4407                 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
4408                              vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
4409                              (CPU_BASED_CR3_LOAD_EXITING |
4410                               CPU_BASED_CR3_STORE_EXITING));
4411                 vcpu->arch.cr0 = cr0;
4412                 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
4413         } else if (!is_paging(vcpu)) {
4414                 /* From nonpaging to paging */
4415                 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
4416                              vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
4417                              ~(CPU_BASED_CR3_LOAD_EXITING |
4418                                CPU_BASED_CR3_STORE_EXITING));
4419                 vcpu->arch.cr0 = cr0;
4420                 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
4421         }
4422
4423         if (!(cr0 & X86_CR0_WP))
4424                 *hw_cr0 &= ~X86_CR0_WP;
4425 }
4426
4427 static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
4428 {
4429         struct vcpu_vmx *vmx = to_vmx(vcpu);
4430         unsigned long hw_cr0;
4431
4432         hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK);
4433         if (enable_unrestricted_guest)
4434                 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
4435         else {
4436                 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
4437
4438                 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
4439                         enter_pmode(vcpu);
4440
4441                 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
4442                         enter_rmode(vcpu);
4443         }
4444
4445 #ifdef CONFIG_X86_64
4446         if (vcpu->arch.efer & EFER_LME) {
4447                 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
4448                         enter_lmode(vcpu);
4449                 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
4450                         exit_lmode(vcpu);
4451         }
4452 #endif
4453
4454         if (enable_ept && !enable_unrestricted_guest)
4455                 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
4456
4457         vmcs_writel(CR0_READ_SHADOW, cr0);
4458         vmcs_writel(GUEST_CR0, hw_cr0);
4459         vcpu->arch.cr0 = cr0;
4460
4461         /* depends on vcpu->arch.cr0 to be set to a new value */
4462         vmx->emulation_required = emulation_required(vcpu);
4463 }
4464
4465 static int get_ept_level(struct kvm_vcpu *vcpu)
4466 {
4467         if (cpu_has_vmx_ept_5levels() && (cpuid_maxphyaddr(vcpu) > 48))
4468                 return 5;
4469         return 4;
4470 }
4471
4472 static u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa)
4473 {
4474         u64 eptp = VMX_EPTP_MT_WB;
4475
4476         eptp |= (get_ept_level(vcpu) == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
4477
4478         if (enable_ept_ad_bits &&
4479             (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
4480                 eptp |= VMX_EPTP_AD_ENABLE_BIT;
4481         eptp |= (root_hpa & PAGE_MASK);
4482
4483         return eptp;
4484 }
4485
4486 static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
4487 {
4488         unsigned long guest_cr3;
4489         u64 eptp;
4490
4491         guest_cr3 = cr3;
4492         if (enable_ept) {
4493                 eptp = construct_eptp(vcpu, cr3);
4494                 vmcs_write64(EPT_POINTER, eptp);
4495                 if (enable_unrestricted_guest || is_paging(vcpu) ||
4496                     is_guest_mode(vcpu))
4497                         guest_cr3 = kvm_read_cr3(vcpu);
4498                 else
4499                         guest_cr3 = vcpu->kvm->arch.ept_identity_map_addr;
4500                 ept_load_pdptrs(vcpu);
4501         }
4502
4503         vmx_flush_tlb(vcpu, true);
4504         vmcs_writel(GUEST_CR3, guest_cr3);
4505 }
4506
4507 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
4508 {
4509         /*
4510          * Pass through host's Machine Check Enable value to hw_cr4, which
4511          * is in force while we are in guest mode.  Do not let guests control
4512          * this bit, even if host CR4.MCE == 0.
4513          */
4514         unsigned long hw_cr4;
4515
4516         hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
4517         if (enable_unrestricted_guest)
4518                 hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
4519         else if (to_vmx(vcpu)->rmode.vm86_active)
4520                 hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
4521         else
4522                 hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
4523
4524         if ((cr4 & X86_CR4_UMIP) && !boot_cpu_has(X86_FEATURE_UMIP)) {
4525                 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
4526                               SECONDARY_EXEC_DESC);
4527                 hw_cr4 &= ~X86_CR4_UMIP;
4528         } else if (!is_guest_mode(vcpu) ||
4529                    !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC))
4530                 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
4531                                 SECONDARY_EXEC_DESC);
4532
4533         if (cr4 & X86_CR4_VMXE) {
4534                 /*
4535                  * To use VMXON (and later other VMX instructions), a guest
4536                  * must first be able to turn on cr4.VMXE (see handle_vmon()).
4537                  * So basically the check on whether to allow nested VMX
4538                  * is here.
4539                  */
4540                 if (!nested_vmx_allowed(vcpu))
4541                         return 1;
4542         }
4543
4544         if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
4545                 return 1;
4546
4547         vcpu->arch.cr4 = cr4;
4548
4549         if (!enable_unrestricted_guest) {
4550                 if (enable_ept) {
4551                         if (!is_paging(vcpu)) {
4552                                 hw_cr4 &= ~X86_CR4_PAE;
4553                                 hw_cr4 |= X86_CR4_PSE;
4554                         } else if (!(cr4 & X86_CR4_PAE)) {
4555                                 hw_cr4 &= ~X86_CR4_PAE;
4556                         }
4557                 }
4558
4559                 /*
4560                  * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
4561                  * hardware.  To emulate this behavior, SMEP/SMAP/PKU needs
4562                  * to be manually disabled when guest switches to non-paging
4563                  * mode.
4564                  *
4565                  * If !enable_unrestricted_guest, the CPU is always running
4566                  * with CR0.PG=1 and CR4 needs to be modified.
4567                  * If enable_unrestricted_guest, the CPU automatically
4568                  * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
4569                  */
4570                 if (!is_paging(vcpu))
4571                         hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
4572         }
4573
4574         vmcs_writel(CR4_READ_SHADOW, cr4);
4575         vmcs_writel(GUEST_CR4, hw_cr4);
4576         return 0;
4577 }
4578
4579 static void vmx_get_segment(struct kvm_vcpu *vcpu,
4580                             struct kvm_segment *var, int seg)
4581 {
4582         struct vcpu_vmx *vmx = to_vmx(vcpu);
4583         u32 ar;
4584
4585         if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
4586                 *var = vmx->rmode.segs[seg];
4587                 if (seg == VCPU_SREG_TR
4588                     || var->selector == vmx_read_guest_seg_selector(vmx, seg))
4589                         return;
4590                 var->base = vmx_read_guest_seg_base(vmx, seg);
4591                 var->selector = vmx_read_guest_seg_selector(vmx, seg);
4592                 return;
4593         }
4594         var->base = vmx_read_guest_seg_base(vmx, seg);
4595         var->limit = vmx_read_guest_seg_limit(vmx, seg);
4596         var->selector = vmx_read_guest_seg_selector(vmx, seg);
4597         ar = vmx_read_guest_seg_ar(vmx, seg);
4598         var->unusable = (ar >> 16) & 1;
4599         var->type = ar & 15;
4600         var->s = (ar >> 4) & 1;
4601         var->dpl = (ar >> 5) & 3;
4602         /*
4603          * Some userspaces do not preserve unusable property. Since usable
4604          * segment has to be present according to VMX spec we can use present
4605          * property to amend userspace bug by making unusable segment always
4606          * nonpresent. vmx_segment_access_rights() already marks nonpresent
4607          * segment as unusable.
4608          */
4609         var->present = !var->unusable;
4610         var->avl = (ar >> 12) & 1;
4611         var->l = (ar >> 13) & 1;
4612         var->db = (ar >> 14) & 1;
4613         var->g = (ar >> 15) & 1;
4614 }
4615
4616 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
4617 {
4618         struct kvm_segment s;
4619
4620         if (to_vmx(vcpu)->rmode.vm86_active) {
4621                 vmx_get_segment(vcpu, &s, seg);
4622                 return s.base;
4623         }
4624         return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
4625 }
4626
4627 static int vmx_get_cpl(struct kvm_vcpu *vcpu)
4628 {
4629         struct vcpu_vmx *vmx = to_vmx(vcpu);
4630
4631         if (unlikely(vmx->rmode.vm86_active))
4632                 return 0;
4633         else {
4634                 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
4635                 return VMX_AR_DPL(ar);
4636         }
4637 }
4638
4639 static u32 vmx_segment_access_rights(struct kvm_segment *var)
4640 {
4641         u32 ar;
4642
4643         if (var->unusable || !var->present)
4644                 ar = 1 << 16;
4645         else {
4646                 ar = var->type & 15;
4647                 ar |= (var->s & 1) << 4;
4648                 ar |= (var->dpl & 3) << 5;
4649                 ar |= (var->present & 1) << 7;
4650                 ar |= (var->avl & 1) << 12;
4651                 ar |= (var->l & 1) << 13;
4652                 ar |= (var->db & 1) << 14;
4653                 ar |= (var->g & 1) << 15;
4654         }
4655
4656         return ar;
4657 }
4658
4659 static void vmx_set_segment(struct kvm_vcpu *vcpu,
4660                             struct kvm_segment *var, int seg)
4661 {
4662         struct vcpu_vmx *vmx = to_vmx(vcpu);
4663         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
4664
4665         vmx_segment_cache_clear(vmx);
4666
4667         if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
4668                 vmx->rmode.segs[seg] = *var;
4669                 if (seg == VCPU_SREG_TR)
4670                         vmcs_write16(sf->selector, var->selector);
4671                 else if (var->s)
4672                         fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
4673                 goto out;
4674         }
4675
4676         vmcs_writel(sf->base, var->base);
4677         vmcs_write32(sf->limit, var->limit);
4678         vmcs_write16(sf->selector, var->selector);
4679
4680         /*
4681          *   Fix the "Accessed" bit in AR field of segment registers for older
4682          * qemu binaries.
4683          *   IA32 arch specifies that at the time of processor reset the
4684          * "Accessed" bit in the AR field of segment registers is 1. And qemu
4685          * is setting it to 0 in the userland code. This causes invalid guest
4686          * state vmexit when "unrestricted guest" mode is turned on.
4687          *    Fix for this setup issue in cpu_reset is being pushed in the qemu
4688          * tree. Newer qemu binaries with that qemu fix would not need this
4689          * kvm hack.
4690          */
4691         if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
4692                 var->type |= 0x1; /* Accessed */
4693
4694         vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
4695
4696 out:
4697         vmx->emulation_required = emulation_required(vcpu);
4698 }
4699
4700 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
4701 {
4702         u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
4703
4704         *db = (ar >> 14) & 1;
4705         *l = (ar >> 13) & 1;
4706 }
4707
4708 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4709 {
4710         dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
4711         dt->address = vmcs_readl(GUEST_IDTR_BASE);
4712 }
4713
4714 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4715 {
4716         vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
4717         vmcs_writel(GUEST_IDTR_BASE, dt->address);
4718 }
4719
4720 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4721 {
4722         dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
4723         dt->address = vmcs_readl(GUEST_GDTR_BASE);
4724 }
4725
4726 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4727 {
4728         vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
4729         vmcs_writel(GUEST_GDTR_BASE, dt->address);
4730 }
4731
4732 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
4733 {
4734         struct kvm_segment var;
4735         u32 ar;
4736
4737         vmx_get_segment(vcpu, &var, seg);
4738         var.dpl = 0x3;
4739         if (seg == VCPU_SREG_CS)
4740                 var.type = 0x3;
4741         ar = vmx_segment_access_rights(&var);
4742
4743         if (var.base != (var.selector << 4))
4744                 return false;
4745         if (var.limit != 0xffff)
4746                 return false;
4747         if (ar != 0xf3)
4748                 return false;
4749
4750         return true;
4751 }
4752
4753 static bool code_segment_valid(struct kvm_vcpu *vcpu)
4754 {
4755         struct kvm_segment cs;
4756         unsigned int cs_rpl;
4757
4758         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
4759         cs_rpl = cs.selector & SEGMENT_RPL_MASK;
4760
4761         if (cs.unusable)
4762                 return false;
4763         if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
4764                 return false;
4765         if (!cs.s)
4766                 return false;
4767         if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
4768                 if (cs.dpl > cs_rpl)
4769                         return false;
4770         } else {
4771                 if (cs.dpl != cs_rpl)
4772                         return false;
4773         }
4774         if (!cs.present)
4775                 return false;
4776
4777         /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
4778         return true;
4779 }
4780
4781 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
4782 {
4783         struct kvm_segment ss;
4784         unsigned int ss_rpl;
4785
4786         vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
4787         ss_rpl = ss.selector & SEGMENT_RPL_MASK;
4788
4789         if (ss.unusable)
4790                 return true;
4791         if (ss.type != 3 && ss.type != 7)
4792                 return false;
4793         if (!ss.s)
4794                 return false;
4795         if (ss.dpl != ss_rpl) /* DPL != RPL */
4796                 return false;
4797         if (!ss.present)
4798                 return false;
4799
4800         return true;
4801 }
4802
4803 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
4804 {
4805         struct kvm_segment var;
4806         unsigned int rpl;
4807
4808         vmx_get_segment(vcpu, &var, seg);
4809         rpl = var.selector & SEGMENT_RPL_MASK;
4810
4811         if (var.unusable)
4812                 return true;
4813         if (!var.s)
4814                 return false;
4815         if (!var.present)
4816                 return false;
4817         if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
4818                 if (var.dpl < rpl) /* DPL < RPL */
4819                         return false;
4820         }
4821
4822         /* TODO: Add other members to kvm_segment_field to allow checking for other access
4823          * rights flags
4824          */
4825         return true;
4826 }
4827
4828 static bool tr_valid(struct kvm_vcpu *vcpu)
4829 {
4830         struct kvm_segment tr;
4831
4832         vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
4833
4834         if (tr.unusable)
4835                 return false;
4836         if (tr.selector & SEGMENT_TI_MASK)      /* TI = 1 */
4837                 return false;
4838         if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
4839                 return false;
4840         if (!tr.present)
4841                 return false;
4842
4843         return true;
4844 }
4845
4846 static bool ldtr_valid(struct kvm_vcpu *vcpu)
4847 {
4848         struct kvm_segment ldtr;
4849
4850         vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
4851
4852         if (ldtr.unusable)
4853                 return true;
4854         if (ldtr.selector & SEGMENT_TI_MASK)    /* TI = 1 */
4855                 return false;
4856         if (ldtr.type != 2)
4857                 return false;
4858         if (!ldtr.present)
4859                 return false;
4860
4861         return true;
4862 }
4863
4864 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
4865 {
4866         struct kvm_segment cs, ss;
4867
4868         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
4869         vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
4870
4871         return ((cs.selector & SEGMENT_RPL_MASK) ==
4872                  (ss.selector & SEGMENT_RPL_MASK));
4873 }
4874
4875 /*
4876  * Check if guest state is valid. Returns true if valid, false if
4877  * not.
4878  * We assume that registers are always usable
4879  */
4880 static bool guest_state_valid(struct kvm_vcpu *vcpu)
4881 {
4882         if (enable_unrestricted_guest)
4883                 return true;
4884
4885         /* real mode guest state checks */
4886         if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
4887                 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
4888                         return false;
4889                 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
4890                         return false;
4891                 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
4892                         return false;
4893                 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
4894                         return false;
4895                 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
4896                         return false;
4897                 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
4898                         return false;
4899         } else {
4900         /* protected mode guest state checks */
4901                 if (!cs_ss_rpl_check(vcpu))
4902                         return false;
4903                 if (!code_segment_valid(vcpu))
4904                         return false;
4905                 if (!stack_segment_valid(vcpu))
4906                         return false;
4907                 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
4908                         return false;
4909                 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
4910                         return false;
4911                 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
4912                         return false;
4913                 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
4914                         return false;
4915                 if (!tr_valid(vcpu))
4916                         return false;
4917                 if (!ldtr_valid(vcpu))
4918                         return false;
4919         }
4920         /* TODO:
4921          * - Add checks on RIP
4922          * - Add checks on RFLAGS
4923          */
4924
4925         return true;
4926 }
4927
4928 static bool page_address_valid(struct kvm_vcpu *vcpu, gpa_t gpa)
4929 {
4930         return PAGE_ALIGNED(gpa) && !(gpa >> cpuid_maxphyaddr(vcpu));
4931 }
4932
4933 static int init_rmode_tss(struct kvm *kvm)
4934 {
4935         gfn_t fn;
4936         u16 data = 0;
4937         int idx, r;
4938
4939         idx = srcu_read_lock(&kvm->srcu);
4940         fn = kvm->arch.tss_addr >> PAGE_SHIFT;
4941         r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
4942         if (r < 0)
4943                 goto out;
4944         data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
4945         r = kvm_write_guest_page(kvm, fn++, &data,
4946                         TSS_IOPB_BASE_OFFSET, sizeof(u16));
4947         if (r < 0)
4948                 goto out;
4949         r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
4950         if (r < 0)
4951                 goto out;
4952         r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
4953         if (r < 0)
4954                 goto out;
4955         data = ~0;
4956         r = kvm_write_guest_page(kvm, fn, &data,
4957                                  RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
4958                                  sizeof(u8));
4959 out:
4960         srcu_read_unlock(&kvm->srcu, idx);
4961         return r;
4962 }
4963
4964 static int init_rmode_identity_map(struct kvm *kvm)
4965 {
4966         int i, idx, r = 0;
4967         kvm_pfn_t identity_map_pfn;
4968         u32 tmp;
4969
4970         /* Protect kvm->arch.ept_identity_pagetable_done. */
4971         mutex_lock(&kvm->slots_lock);
4972
4973         if (likely(kvm->arch.ept_identity_pagetable_done))
4974                 goto out2;
4975
4976         if (!kvm->arch.ept_identity_map_addr)
4977                 kvm->arch.ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
4978         identity_map_pfn = kvm->arch.ept_identity_map_addr >> PAGE_SHIFT;
4979
4980         r = __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
4981                                     kvm->arch.ept_identity_map_addr, PAGE_SIZE);
4982         if (r < 0)
4983                 goto out2;
4984
4985         idx = srcu_read_lock(&kvm->srcu);
4986         r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
4987         if (r < 0)
4988                 goto out;
4989         /* Set up identity-mapping pagetable for EPT in real mode */
4990         for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
4991                 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
4992                         _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
4993                 r = kvm_write_guest_page(kvm, identity_map_pfn,
4994                                 &tmp, i * sizeof(tmp), sizeof(tmp));
4995                 if (r < 0)
4996                         goto out;
4997         }
4998         kvm->arch.ept_identity_pagetable_done = true;
4999
5000 out:
5001         srcu_read_unlock(&kvm->srcu, idx);
5002
5003 out2:
5004         mutex_unlock(&kvm->slots_lock);
5005         return r;
5006 }
5007
5008 static void seg_setup(int seg)
5009 {
5010         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
5011         unsigned int ar;
5012
5013         vmcs_write16(sf->selector, 0);
5014         vmcs_writel(sf->base, 0);
5015         vmcs_write32(sf->limit, 0xffff);
5016         ar = 0x93;
5017         if (seg == VCPU_SREG_CS)
5018                 ar |= 0x08; /* code segment */
5019
5020         vmcs_write32(sf->ar_bytes, ar);
5021 }
5022
5023 static int alloc_apic_access_page(struct kvm *kvm)
5024 {
5025         struct page *page;
5026         int r = 0;
5027
5028         mutex_lock(&kvm->slots_lock);
5029         if (kvm->arch.apic_access_page_done)
5030                 goto out;
5031         r = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
5032                                     APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
5033         if (r)
5034                 goto out;
5035
5036         page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
5037         if (is_error_page(page)) {
5038                 r = -EFAULT;
5039                 goto out;
5040         }
5041
5042         /*
5043          * Do not pin the page in memory, so that memory hot-unplug
5044          * is able to migrate it.
5045          */
5046         put_page(page);
5047         kvm->arch.apic_access_page_done = true;
5048 out:
5049         mutex_unlock(&kvm->slots_lock);
5050         return r;
5051 }
5052
5053 static int allocate_vpid(void)
5054 {
5055         int vpid;
5056
5057         if (!enable_vpid)
5058                 return 0;
5059         spin_lock(&vmx_vpid_lock);
5060         vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
5061         if (vpid < VMX_NR_VPIDS)
5062                 __set_bit(vpid, vmx_vpid_bitmap);
5063         else
5064                 vpid = 0;
5065         spin_unlock(&vmx_vpid_lock);
5066         return vpid;
5067 }
5068
5069 static void free_vpid(int vpid)
5070 {
5071         if (!enable_vpid || vpid == 0)
5072                 return;
5073         spin_lock(&vmx_vpid_lock);
5074         __clear_bit(vpid, vmx_vpid_bitmap);
5075         spin_unlock(&vmx_vpid_lock);
5076 }
5077
5078 static void __always_inline vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
5079                                                           u32 msr, int type)
5080 {
5081         int f = sizeof(unsigned long);
5082
5083         if (!cpu_has_vmx_msr_bitmap())
5084                 return;
5085
5086         /*
5087          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
5088          * have the write-low and read-high bitmap offsets the wrong way round.
5089          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
5090          */
5091         if (msr <= 0x1fff) {
5092                 if (type & MSR_TYPE_R)
5093                         /* read-low */
5094                         __clear_bit(msr, msr_bitmap + 0x000 / f);
5095
5096                 if (type & MSR_TYPE_W)
5097                         /* write-low */
5098                         __clear_bit(msr, msr_bitmap + 0x800 / f);
5099
5100         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
5101                 msr &= 0x1fff;
5102                 if (type & MSR_TYPE_R)
5103                         /* read-high */
5104                         __clear_bit(msr, msr_bitmap + 0x400 / f);
5105
5106                 if (type & MSR_TYPE_W)
5107                         /* write-high */
5108                         __clear_bit(msr, msr_bitmap + 0xc00 / f);
5109
5110         }
5111 }
5112
5113 static void __always_inline vmx_enable_intercept_for_msr(unsigned long *msr_bitmap,
5114                                                          u32 msr, int type)
5115 {
5116         int f = sizeof(unsigned long);
5117
5118         if (!cpu_has_vmx_msr_bitmap())
5119                 return;
5120
5121         /*
5122          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
5123          * have the write-low and read-high bitmap offsets the wrong way round.
5124          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
5125          */
5126         if (msr <= 0x1fff) {
5127                 if (type & MSR_TYPE_R)
5128                         /* read-low */
5129                         __set_bit(msr, msr_bitmap + 0x000 / f);
5130
5131                 if (type & MSR_TYPE_W)
5132                         /* write-low */
5133                         __set_bit(msr, msr_bitmap + 0x800 / f);
5134
5135         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
5136                 msr &= 0x1fff;
5137                 if (type & MSR_TYPE_R)
5138                         /* read-high */
5139                         __set_bit(msr, msr_bitmap + 0x400 / f);
5140
5141                 if (type & MSR_TYPE_W)
5142                         /* write-high */
5143                         __set_bit(msr, msr_bitmap + 0xc00 / f);
5144
5145         }
5146 }
5147
5148 static void __always_inline vmx_set_intercept_for_msr(unsigned long *msr_bitmap,
5149                                                       u32 msr, int type, bool value)
5150 {
5151         if (value)
5152                 vmx_enable_intercept_for_msr(msr_bitmap, msr, type);
5153         else
5154                 vmx_disable_intercept_for_msr(msr_bitmap, msr, type);
5155 }
5156
5157 /*
5158  * If a msr is allowed by L0, we should check whether it is allowed by L1.
5159  * The corresponding bit will be cleared unless both of L0 and L1 allow it.
5160  */
5161 static void nested_vmx_disable_intercept_for_msr(unsigned long *msr_bitmap_l1,
5162                                                unsigned long *msr_bitmap_nested,
5163                                                u32 msr, int type)
5164 {
5165         int f = sizeof(unsigned long);
5166
5167         /*
5168          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
5169          * have the write-low and read-high bitmap offsets the wrong way round.
5170          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
5171          */
5172         if (msr <= 0x1fff) {
5173                 if (type & MSR_TYPE_R &&
5174                    !test_bit(msr, msr_bitmap_l1 + 0x000 / f))
5175                         /* read-low */
5176                         __clear_bit(msr, msr_bitmap_nested + 0x000 / f);
5177
5178                 if (type & MSR_TYPE_W &&
5179                    !test_bit(msr, msr_bitmap_l1 + 0x800 / f))
5180                         /* write-low */
5181                         __clear_bit(msr, msr_bitmap_nested + 0x800 / f);
5182
5183         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
5184                 msr &= 0x1fff;
5185                 if (type & MSR_TYPE_R &&
5186                    !test_bit(msr, msr_bitmap_l1 + 0x400 / f))
5187                         /* read-high */
5188                         __clear_bit(msr, msr_bitmap_nested + 0x400 / f);
5189
5190                 if (type & MSR_TYPE_W &&
5191                    !test_bit(msr, msr_bitmap_l1 + 0xc00 / f))
5192                         /* write-high */
5193                         __clear_bit(msr, msr_bitmap_nested + 0xc00 / f);
5194
5195         }
5196 }
5197
5198 static u8 vmx_msr_bitmap_mode(struct kvm_vcpu *vcpu)
5199 {
5200         u8 mode = 0;
5201
5202         if (cpu_has_secondary_exec_ctrls() &&
5203             (vmcs_read32(SECONDARY_VM_EXEC_CONTROL) &
5204              SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
5205                 mode |= MSR_BITMAP_MODE_X2APIC;
5206                 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
5207                         mode |= MSR_BITMAP_MODE_X2APIC_APICV;
5208         }
5209
5210         if (is_long_mode(vcpu))
5211                 mode |= MSR_BITMAP_MODE_LM;
5212
5213         return mode;
5214 }
5215
5216 #define X2APIC_MSR(r) (APIC_BASE_MSR + ((r) >> 4))
5217
5218 static void vmx_update_msr_bitmap_x2apic(unsigned long *msr_bitmap,
5219                                          u8 mode)
5220 {
5221         int msr;
5222
5223         for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
5224                 unsigned word = msr / BITS_PER_LONG;
5225                 msr_bitmap[word] = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
5226                 msr_bitmap[word + (0x800 / sizeof(long))] = ~0;
5227         }
5228
5229         if (mode & MSR_BITMAP_MODE_X2APIC) {
5230                 /*
5231                  * TPR reads and writes can be virtualized even if virtual interrupt
5232                  * delivery is not in use.
5233                  */
5234                 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW);
5235                 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
5236                         vmx_enable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_R);
5237                         vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
5238                         vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
5239                 }
5240         }
5241 }
5242
5243 static void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu)
5244 {
5245         struct vcpu_vmx *vmx = to_vmx(vcpu);
5246         unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
5247         u8 mode = vmx_msr_bitmap_mode(vcpu);
5248         u8 changed = mode ^ vmx->msr_bitmap_mode;
5249
5250         if (!changed)
5251                 return;
5252
5253         vmx_set_intercept_for_msr(msr_bitmap, MSR_KERNEL_GS_BASE, MSR_TYPE_RW,
5254                                   !(mode & MSR_BITMAP_MODE_LM));
5255
5256         if (changed & (MSR_BITMAP_MODE_X2APIC | MSR_BITMAP_MODE_X2APIC_APICV))
5257                 vmx_update_msr_bitmap_x2apic(msr_bitmap, mode);
5258
5259         vmx->msr_bitmap_mode = mode;
5260 }
5261
5262 static bool vmx_get_enable_apicv(struct kvm_vcpu *vcpu)
5263 {
5264         return enable_apicv;
5265 }
5266
5267 static void nested_mark_vmcs12_pages_dirty(struct kvm_vcpu *vcpu)
5268 {
5269         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5270         gfn_t gfn;
5271
5272         /*
5273          * Don't need to mark the APIC access page dirty; it is never
5274          * written to by the CPU during APIC virtualization.
5275          */
5276
5277         if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
5278                 gfn = vmcs12->virtual_apic_page_addr >> PAGE_SHIFT;
5279                 kvm_vcpu_mark_page_dirty(vcpu, gfn);
5280         }
5281
5282         if (nested_cpu_has_posted_intr(vmcs12)) {
5283                 gfn = vmcs12->posted_intr_desc_addr >> PAGE_SHIFT;
5284                 kvm_vcpu_mark_page_dirty(vcpu, gfn);
5285         }
5286 }
5287
5288
5289 static void vmx_complete_nested_posted_interrupt(struct kvm_vcpu *vcpu)
5290 {
5291         struct vcpu_vmx *vmx = to_vmx(vcpu);
5292         int max_irr;
5293         void *vapic_page;
5294         u16 status;
5295
5296         if (!vmx->nested.pi_desc || !vmx->nested.pi_pending)
5297                 return;
5298
5299         vmx->nested.pi_pending = false;
5300         if (!pi_test_and_clear_on(vmx->nested.pi_desc))
5301                 return;
5302
5303         max_irr = find_last_bit((unsigned long *)vmx->nested.pi_desc->pir, 256);
5304         if (max_irr != 256) {
5305                 vapic_page = kmap(vmx->nested.virtual_apic_page);
5306                 __kvm_apic_update_irr(vmx->nested.pi_desc->pir,
5307                         vapic_page, &max_irr);
5308                 kunmap(vmx->nested.virtual_apic_page);
5309
5310                 status = vmcs_read16(GUEST_INTR_STATUS);
5311                 if ((u8)max_irr > ((u8)status & 0xff)) {
5312                         status &= ~0xff;
5313                         status |= (u8)max_irr;
5314                         vmcs_write16(GUEST_INTR_STATUS, status);
5315                 }
5316         }
5317
5318         nested_mark_vmcs12_pages_dirty(vcpu);
5319 }
5320
5321 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
5322                                                      bool nested)
5323 {
5324 #ifdef CONFIG_SMP
5325         int pi_vec = nested ? POSTED_INTR_NESTED_VECTOR : POSTED_INTR_VECTOR;
5326
5327         if (vcpu->mode == IN_GUEST_MODE) {
5328                 /*
5329                  * The vector of interrupt to be delivered to vcpu had
5330                  * been set in PIR before this function.
5331                  *
5332                  * Following cases will be reached in this block, and
5333                  * we always send a notification event in all cases as
5334                  * explained below.
5335                  *
5336                  * Case 1: vcpu keeps in non-root mode. Sending a
5337                  * notification event posts the interrupt to vcpu.
5338                  *
5339                  * Case 2: vcpu exits to root mode and is still
5340                  * runnable. PIR will be synced to vIRR before the
5341                  * next vcpu entry. Sending a notification event in
5342                  * this case has no effect, as vcpu is not in root
5343                  * mode.
5344                  *
5345                  * Case 3: vcpu exits to root mode and is blocked.
5346                  * vcpu_block() has already synced PIR to vIRR and
5347                  * never blocks vcpu if vIRR is not cleared. Therefore,
5348                  * a blocked vcpu here does not wait for any requested
5349                  * interrupts in PIR, and sending a notification event
5350                  * which has no effect is safe here.
5351                  */
5352
5353                 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
5354                 return true;
5355         }
5356 #endif
5357         return false;
5358 }
5359
5360 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
5361                                                 int vector)
5362 {
5363         struct vcpu_vmx *vmx = to_vmx(vcpu);
5364
5365         if (is_guest_mode(vcpu) &&
5366             vector == vmx->nested.posted_intr_nv) {
5367                 /*
5368                  * If a posted intr is not recognized by hardware,
5369                  * we will accomplish it in the next vmentry.
5370                  */
5371                 vmx->nested.pi_pending = true;
5372                 kvm_make_request(KVM_REQ_EVENT, vcpu);
5373                 /* the PIR and ON have been set by L1. */
5374                 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, true))
5375                         kvm_vcpu_kick(vcpu);
5376                 return 0;
5377         }
5378         return -1;
5379 }
5380 /*
5381  * Send interrupt to vcpu via posted interrupt way.
5382  * 1. If target vcpu is running(non-root mode), send posted interrupt
5383  * notification to vcpu and hardware will sync PIR to vIRR atomically.
5384  * 2. If target vcpu isn't running(root mode), kick it to pick up the
5385  * interrupt from PIR in next vmentry.
5386  */
5387 static void vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
5388 {
5389         struct vcpu_vmx *vmx = to_vmx(vcpu);
5390         int r;
5391
5392         r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
5393         if (!r)
5394                 return;
5395
5396         if (pi_test_and_set_pir(vector, &vmx->pi_desc))
5397                 return;
5398
5399         /* If a previous notification has sent the IPI, nothing to do.  */
5400         if (pi_test_and_set_on(&vmx->pi_desc))
5401                 return;
5402
5403         if (!kvm_vcpu_trigger_posted_interrupt(vcpu, false))
5404                 kvm_vcpu_kick(vcpu);
5405 }
5406
5407 /*
5408  * Set up the vmcs's constant host-state fields, i.e., host-state fields that
5409  * will not change in the lifetime of the guest.
5410  * Note that host-state that does change is set elsewhere. E.g., host-state
5411  * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
5412  */
5413 static void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
5414 {
5415         u32 low32, high32;
5416         unsigned long tmpl;
5417         struct desc_ptr dt;
5418         unsigned long cr0, cr3, cr4;
5419
5420         cr0 = read_cr0();
5421         WARN_ON(cr0 & X86_CR0_TS);
5422         vmcs_writel(HOST_CR0, cr0);  /* 22.2.3 */
5423
5424         /*
5425          * Save the most likely value for this task's CR3 in the VMCS.
5426          * We can't use __get_current_cr3_fast() because we're not atomic.
5427          */
5428         cr3 = __read_cr3();
5429         vmcs_writel(HOST_CR3, cr3);             /* 22.2.3  FIXME: shadow tables */
5430         vmx->loaded_vmcs->vmcs_host_cr3 = cr3;
5431
5432         /* Save the most likely value for this task's CR4 in the VMCS. */
5433         cr4 = cr4_read_shadow();
5434         vmcs_writel(HOST_CR4, cr4);                     /* 22.2.3, 22.2.5 */
5435         vmx->loaded_vmcs->vmcs_host_cr4 = cr4;
5436
5437         vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS);  /* 22.2.4 */
5438 #ifdef CONFIG_X86_64
5439         /*
5440          * Load null selectors, so we can avoid reloading them in
5441          * __vmx_load_host_state(), in case userspace uses the null selectors
5442          * too (the expected case).
5443          */
5444         vmcs_write16(HOST_DS_SELECTOR, 0);
5445         vmcs_write16(HOST_ES_SELECTOR, 0);
5446 #else
5447         vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
5448         vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
5449 #endif
5450         vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
5451         vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8);  /* 22.2.4 */
5452
5453         store_idt(&dt);
5454         vmcs_writel(HOST_IDTR_BASE, dt.address);   /* 22.2.4 */
5455         vmx->host_idt_base = dt.address;
5456
5457         vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */
5458
5459         rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
5460         vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
5461         rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
5462         vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl);   /* 22.2.3 */
5463
5464         if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
5465                 rdmsr(MSR_IA32_CR_PAT, low32, high32);
5466                 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
5467         }
5468 }
5469
5470 static void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
5471 {
5472         vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
5473         if (enable_ept)
5474                 vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
5475         if (is_guest_mode(&vmx->vcpu))
5476                 vmx->vcpu.arch.cr4_guest_owned_bits &=
5477                         ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
5478         vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
5479 }
5480
5481 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
5482 {
5483         u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
5484
5485         if (!kvm_vcpu_apicv_active(&vmx->vcpu))
5486                 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
5487
5488         if (!enable_vnmi)
5489                 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
5490
5491         /* Enable the preemption timer dynamically */
5492         pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
5493         return pin_based_exec_ctrl;
5494 }
5495
5496 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
5497 {
5498         struct vcpu_vmx *vmx = to_vmx(vcpu);
5499
5500         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
5501         if (cpu_has_secondary_exec_ctrls()) {
5502                 if (kvm_vcpu_apicv_active(vcpu))
5503                         vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
5504                                       SECONDARY_EXEC_APIC_REGISTER_VIRT |
5505                                       SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
5506                 else
5507                         vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
5508                                         SECONDARY_EXEC_APIC_REGISTER_VIRT |
5509                                         SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
5510         }
5511
5512         if (cpu_has_vmx_msr_bitmap())
5513                 vmx_update_msr_bitmap(vcpu);
5514 }
5515
5516 static u32 vmx_exec_control(struct vcpu_vmx *vmx)
5517 {
5518         u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
5519
5520         if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
5521                 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
5522
5523         if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
5524                 exec_control &= ~CPU_BASED_TPR_SHADOW;
5525 #ifdef CONFIG_X86_64
5526                 exec_control |= CPU_BASED_CR8_STORE_EXITING |
5527                                 CPU_BASED_CR8_LOAD_EXITING;
5528 #endif
5529         }
5530         if (!enable_ept)
5531                 exec_control |= CPU_BASED_CR3_STORE_EXITING |
5532                                 CPU_BASED_CR3_LOAD_EXITING  |
5533                                 CPU_BASED_INVLPG_EXITING;
5534         return exec_control;
5535 }
5536
5537 static bool vmx_rdrand_supported(void)
5538 {
5539         return vmcs_config.cpu_based_2nd_exec_ctrl &
5540                 SECONDARY_EXEC_RDRAND_EXITING;
5541 }
5542
5543 static bool vmx_rdseed_supported(void)
5544 {
5545         return vmcs_config.cpu_based_2nd_exec_ctrl &
5546                 SECONDARY_EXEC_RDSEED_EXITING;
5547 }
5548
5549 static void vmx_compute_secondary_exec_control(struct vcpu_vmx *vmx)
5550 {
5551         struct kvm_vcpu *vcpu = &vmx->vcpu;
5552
5553         u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
5554
5555         if (!cpu_need_virtualize_apic_accesses(vcpu))
5556                 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
5557         if (vmx->vpid == 0)
5558                 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
5559         if (!enable_ept) {
5560                 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
5561                 enable_unrestricted_guest = 0;
5562                 /* Enable INVPCID for non-ept guests may cause performance regression. */
5563                 exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
5564         }
5565         if (!enable_unrestricted_guest)
5566                 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
5567         if (!ple_gap)
5568                 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
5569         if (!kvm_vcpu_apicv_active(vcpu))
5570                 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
5571                                   SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
5572         exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
5573
5574         /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
5575          * in vmx_set_cr4.  */
5576         exec_control &= ~SECONDARY_EXEC_DESC;
5577
5578         /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
5579            (handle_vmptrld).
5580            We can NOT enable shadow_vmcs here because we don't have yet
5581            a current VMCS12
5582         */
5583         exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
5584
5585         if (!enable_pml)
5586                 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
5587
5588         if (vmx_xsaves_supported()) {
5589                 /* Exposing XSAVES only when XSAVE is exposed */
5590                 bool xsaves_enabled =
5591                         guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
5592                         guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
5593
5594                 if (!xsaves_enabled)
5595                         exec_control &= ~SECONDARY_EXEC_XSAVES;
5596
5597                 if (nested) {
5598                         if (xsaves_enabled)
5599                                 vmx->nested.msrs.secondary_ctls_high |=
5600                                         SECONDARY_EXEC_XSAVES;
5601                         else
5602                                 vmx->nested.msrs.secondary_ctls_high &=
5603                                         ~SECONDARY_EXEC_XSAVES;
5604                 }
5605         }
5606
5607         if (vmx_rdtscp_supported()) {
5608                 bool rdtscp_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP);
5609                 if (!rdtscp_enabled)
5610                         exec_control &= ~SECONDARY_EXEC_RDTSCP;
5611
5612                 if (nested) {
5613                         if (rdtscp_enabled)
5614                                 vmx->nested.msrs.secondary_ctls_high |=
5615                                         SECONDARY_EXEC_RDTSCP;
5616                         else
5617                                 vmx->nested.msrs.secondary_ctls_high &=
5618                                         ~SECONDARY_EXEC_RDTSCP;
5619                 }
5620         }
5621
5622         if (vmx_invpcid_supported()) {
5623                 /* Exposing INVPCID only when PCID is exposed */
5624                 bool invpcid_enabled =
5625                         guest_cpuid_has(vcpu, X86_FEATURE_INVPCID) &&
5626                         guest_cpuid_has(vcpu, X86_FEATURE_PCID);
5627
5628                 if (!invpcid_enabled) {
5629                         exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
5630                         guest_cpuid_clear(vcpu, X86_FEATURE_INVPCID);
5631                 }
5632
5633                 if (nested) {
5634                         if (invpcid_enabled)
5635                                 vmx->nested.msrs.secondary_ctls_high |=
5636                                         SECONDARY_EXEC_ENABLE_INVPCID;
5637                         else
5638                                 vmx->nested.msrs.secondary_ctls_high &=
5639                                         ~SECONDARY_EXEC_ENABLE_INVPCID;
5640                 }
5641         }
5642
5643         if (vmx_rdrand_supported()) {
5644                 bool rdrand_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDRAND);
5645                 if (rdrand_enabled)
5646                         exec_control &= ~SECONDARY_EXEC_RDRAND_EXITING;
5647
5648                 if (nested) {
5649                         if (rdrand_enabled)
5650                                 vmx->nested.msrs.secondary_ctls_high |=
5651                                         SECONDARY_EXEC_RDRAND_EXITING;
5652                         else
5653                                 vmx->nested.msrs.secondary_ctls_high &=
5654                                         ~SECONDARY_EXEC_RDRAND_EXITING;
5655                 }
5656         }
5657
5658         if (vmx_rdseed_supported()) {
5659                 bool rdseed_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDSEED);
5660                 if (rdseed_enabled)
5661                         exec_control &= ~SECONDARY_EXEC_RDSEED_EXITING;
5662
5663                 if (nested) {
5664                         if (rdseed_enabled)
5665                                 vmx->nested.msrs.secondary_ctls_high |=
5666                                         SECONDARY_EXEC_RDSEED_EXITING;
5667                         else
5668                                 vmx->nested.msrs.secondary_ctls_high &=
5669                                         ~SECONDARY_EXEC_RDSEED_EXITING;
5670                 }
5671         }
5672
5673         vmx->secondary_exec_control = exec_control;
5674 }
5675
5676 static void ept_set_mmio_spte_mask(void)
5677 {
5678         /*
5679          * EPT Misconfigurations can be generated if the value of bits 2:0
5680          * of an EPT paging-structure entry is 110b (write/execute).
5681          */
5682         kvm_mmu_set_mmio_spte_mask(VMX_EPT_RWX_MASK,
5683                                    VMX_EPT_MISCONFIG_WX_VALUE);
5684 }
5685
5686 #define VMX_XSS_EXIT_BITMAP 0
5687 /*
5688  * Sets up the vmcs for emulated real mode.
5689  */
5690 static void vmx_vcpu_setup(struct vcpu_vmx *vmx)
5691 {
5692 #ifdef CONFIG_X86_64
5693         unsigned long a;
5694 #endif
5695         int i;
5696
5697         if (enable_shadow_vmcs) {
5698                 vmcs_write64(VMREAD_BITMAP, __pa(vmx_vmread_bitmap));
5699                 vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmwrite_bitmap));
5700         }
5701         if (cpu_has_vmx_msr_bitmap())
5702                 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
5703
5704         vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
5705
5706         /* Control */
5707         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
5708         vmx->hv_deadline_tsc = -1;
5709
5710         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
5711
5712         if (cpu_has_secondary_exec_ctrls()) {
5713                 vmx_compute_secondary_exec_control(vmx);
5714                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
5715                              vmx->secondary_exec_control);
5716         }
5717
5718         if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
5719                 vmcs_write64(EOI_EXIT_BITMAP0, 0);
5720                 vmcs_write64(EOI_EXIT_BITMAP1, 0);
5721                 vmcs_write64(EOI_EXIT_BITMAP2, 0);
5722                 vmcs_write64(EOI_EXIT_BITMAP3, 0);
5723
5724                 vmcs_write16(GUEST_INTR_STATUS, 0);
5725
5726                 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
5727                 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
5728         }
5729
5730         if (ple_gap) {
5731                 vmcs_write32(PLE_GAP, ple_gap);
5732                 vmx->ple_window = ple_window;
5733                 vmx->ple_window_dirty = true;
5734         }
5735
5736         vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
5737         vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
5738         vmcs_write32(CR3_TARGET_COUNT, 0);           /* 22.2.1 */
5739
5740         vmcs_write16(HOST_FS_SELECTOR, 0);            /* 22.2.4 */
5741         vmcs_write16(HOST_GS_SELECTOR, 0);            /* 22.2.4 */
5742         vmx_set_constant_host_state(vmx);
5743 #ifdef CONFIG_X86_64
5744         rdmsrl(MSR_FS_BASE, a);
5745         vmcs_writel(HOST_FS_BASE, a); /* 22.2.4 */
5746         rdmsrl(MSR_GS_BASE, a);
5747         vmcs_writel(HOST_GS_BASE, a); /* 22.2.4 */
5748 #else
5749         vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
5750         vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
5751 #endif
5752
5753         if (cpu_has_vmx_vmfunc())
5754                 vmcs_write64(VM_FUNCTION_CONTROL, 0);
5755
5756         vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
5757         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
5758         vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host));
5759         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
5760         vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest));
5761
5762         if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
5763                 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
5764
5765         for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
5766                 u32 index = vmx_msr_index[i];
5767                 u32 data_low, data_high;
5768                 int j = vmx->nmsrs;
5769
5770                 if (rdmsr_safe(index, &data_low, &data_high) < 0)
5771                         continue;
5772                 if (wrmsr_safe(index, data_low, data_high) < 0)
5773                         continue;
5774                 vmx->guest_msrs[j].index = i;
5775                 vmx->guest_msrs[j].data = 0;
5776                 vmx->guest_msrs[j].mask = -1ull;
5777                 ++vmx->nmsrs;
5778         }
5779
5780         if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES))
5781                 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, vmx->arch_capabilities);
5782
5783         vm_exit_controls_init(vmx, vmcs_config.vmexit_ctrl);
5784
5785         /* 22.2.1, 20.8.1 */
5786         vm_entry_controls_init(vmx, vmcs_config.vmentry_ctrl);
5787
5788         vmx->vcpu.arch.cr0_guest_owned_bits = X86_CR0_TS;
5789         vmcs_writel(CR0_GUEST_HOST_MASK, ~X86_CR0_TS);
5790
5791         set_cr4_guest_host_mask(vmx);
5792
5793         if (vmx_xsaves_supported())
5794                 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
5795
5796         if (enable_pml) {
5797                 ASSERT(vmx->pml_pg);
5798                 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
5799                 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
5800         }
5801 }
5802
5803 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
5804 {
5805         struct vcpu_vmx *vmx = to_vmx(vcpu);
5806         struct msr_data apic_base_msr;
5807         u64 cr0;
5808
5809         vmx->rmode.vm86_active = 0;
5810         vmx->spec_ctrl = 0;
5811
5812         vcpu->arch.microcode_version = 0x100000000ULL;
5813         vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
5814         kvm_set_cr8(vcpu, 0);
5815
5816         if (!init_event) {
5817                 apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
5818                                      MSR_IA32_APICBASE_ENABLE;
5819                 if (kvm_vcpu_is_reset_bsp(vcpu))
5820                         apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
5821                 apic_base_msr.host_initiated = true;
5822                 kvm_set_apic_base(vcpu, &apic_base_msr);
5823         }
5824
5825         vmx_segment_cache_clear(vmx);
5826
5827         seg_setup(VCPU_SREG_CS);
5828         vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
5829         vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
5830
5831         seg_setup(VCPU_SREG_DS);
5832         seg_setup(VCPU_SREG_ES);
5833         seg_setup(VCPU_SREG_FS);
5834         seg_setup(VCPU_SREG_GS);
5835         seg_setup(VCPU_SREG_SS);
5836
5837         vmcs_write16(GUEST_TR_SELECTOR, 0);
5838         vmcs_writel(GUEST_TR_BASE, 0);
5839         vmcs_write32(GUEST_TR_LIMIT, 0xffff);
5840         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
5841
5842         vmcs_write16(GUEST_LDTR_SELECTOR, 0);
5843         vmcs_writel(GUEST_LDTR_BASE, 0);
5844         vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
5845         vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
5846
5847         if (!init_event) {
5848                 vmcs_write32(GUEST_SYSENTER_CS, 0);
5849                 vmcs_writel(GUEST_SYSENTER_ESP, 0);
5850                 vmcs_writel(GUEST_SYSENTER_EIP, 0);
5851                 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
5852         }
5853
5854         kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
5855         kvm_rip_write(vcpu, 0xfff0);
5856
5857         vmcs_writel(GUEST_GDTR_BASE, 0);
5858         vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
5859
5860         vmcs_writel(GUEST_IDTR_BASE, 0);
5861         vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
5862
5863         vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
5864         vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
5865         vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
5866         if (kvm_mpx_supported())
5867                 vmcs_write64(GUEST_BNDCFGS, 0);
5868
5869         setup_msrs(vmx);
5870
5871         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);  /* 22.2.1 */
5872
5873         if (cpu_has_vmx_tpr_shadow() && !init_event) {
5874                 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
5875                 if (cpu_need_tpr_shadow(vcpu))
5876                         vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
5877                                      __pa(vcpu->arch.apic->regs));
5878                 vmcs_write32(TPR_THRESHOLD, 0);
5879         }
5880
5881         kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
5882
5883         if (vmx->vpid != 0)
5884                 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
5885
5886         cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
5887         vmx->vcpu.arch.cr0 = cr0;
5888         vmx_set_cr0(vcpu, cr0); /* enter rmode */
5889         vmx_set_cr4(vcpu, 0);
5890         vmx_set_efer(vcpu, 0);
5891
5892         update_exception_bitmap(vcpu);
5893
5894         vpid_sync_context(vmx->vpid);
5895 }
5896
5897 /*
5898  * In nested virtualization, check if L1 asked to exit on external interrupts.
5899  * For most existing hypervisors, this will always return true.
5900  */
5901 static bool nested_exit_on_intr(struct kvm_vcpu *vcpu)
5902 {
5903         return get_vmcs12(vcpu)->pin_based_vm_exec_control &
5904                 PIN_BASED_EXT_INTR_MASK;
5905 }
5906
5907 /*
5908  * In nested virtualization, check if L1 has set
5909  * VM_EXIT_ACK_INTR_ON_EXIT
5910  */
5911 static bool nested_exit_intr_ack_set(struct kvm_vcpu *vcpu)
5912 {
5913         return get_vmcs12(vcpu)->vm_exit_controls &
5914                 VM_EXIT_ACK_INTR_ON_EXIT;
5915 }
5916
5917 static bool nested_exit_on_nmi(struct kvm_vcpu *vcpu)
5918 {
5919         return nested_cpu_has_nmi_exiting(get_vmcs12(vcpu));
5920 }
5921
5922 static void enable_irq_window(struct kvm_vcpu *vcpu)
5923 {
5924         vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
5925                       CPU_BASED_VIRTUAL_INTR_PENDING);
5926 }
5927
5928 static void enable_nmi_window(struct kvm_vcpu *vcpu)
5929 {
5930         if (!enable_vnmi ||
5931             vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
5932                 enable_irq_window(vcpu);
5933                 return;
5934         }
5935
5936         vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
5937                       CPU_BASED_VIRTUAL_NMI_PENDING);
5938 }
5939
5940 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
5941 {
5942         struct vcpu_vmx *vmx = to_vmx(vcpu);
5943         uint32_t intr;
5944         int irq = vcpu->arch.interrupt.nr;
5945
5946         trace_kvm_inj_virq(irq);
5947
5948         ++vcpu->stat.irq_injections;
5949         if (vmx->rmode.vm86_active) {
5950                 int inc_eip = 0;
5951                 if (vcpu->arch.interrupt.soft)
5952                         inc_eip = vcpu->arch.event_exit_inst_len;
5953                 if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE)
5954                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5955                 return;
5956         }
5957         intr = irq | INTR_INFO_VALID_MASK;
5958         if (vcpu->arch.interrupt.soft) {
5959                 intr |= INTR_TYPE_SOFT_INTR;
5960                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
5961                              vmx->vcpu.arch.event_exit_inst_len);
5962         } else
5963                 intr |= INTR_TYPE_EXT_INTR;
5964         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
5965 }
5966
5967 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
5968 {
5969         struct vcpu_vmx *vmx = to_vmx(vcpu);
5970
5971         if (!enable_vnmi) {
5972                 /*
5973                  * Tracking the NMI-blocked state in software is built upon
5974                  * finding the next open IRQ window. This, in turn, depends on
5975                  * well-behaving guests: They have to keep IRQs disabled at
5976                  * least as long as the NMI handler runs. Otherwise we may
5977                  * cause NMI nesting, maybe breaking the guest. But as this is
5978                  * highly unlikely, we can live with the residual risk.
5979                  */
5980                 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
5981                 vmx->loaded_vmcs->vnmi_blocked_time = 0;
5982         }
5983
5984         ++vcpu->stat.nmi_injections;
5985         vmx->loaded_vmcs->nmi_known_unmasked = false;
5986
5987         if (vmx->rmode.vm86_active) {
5988                 if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE)
5989                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5990                 return;
5991         }
5992
5993         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
5994                         INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
5995 }
5996
5997 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
5998 {
5999         struct vcpu_vmx *vmx = to_vmx(vcpu);
6000         bool masked;
6001
6002         if (!enable_vnmi)
6003                 return vmx->loaded_vmcs->soft_vnmi_blocked;
6004         if (vmx->loaded_vmcs->nmi_known_unmasked)
6005                 return false;
6006         masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
6007         vmx->loaded_vmcs->nmi_known_unmasked = !masked;
6008         return masked;
6009 }
6010
6011 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
6012 {
6013         struct vcpu_vmx *vmx = to_vmx(vcpu);
6014
6015         if (!enable_vnmi) {
6016                 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
6017                         vmx->loaded_vmcs->soft_vnmi_blocked = masked;
6018                         vmx->loaded_vmcs->vnmi_blocked_time = 0;
6019                 }
6020         } else {
6021                 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
6022                 if (masked)
6023                         vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6024                                       GUEST_INTR_STATE_NMI);
6025                 else
6026                         vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
6027                                         GUEST_INTR_STATE_NMI);
6028         }
6029 }
6030
6031 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
6032 {
6033         if (to_vmx(vcpu)->nested.nested_run_pending)
6034                 return 0;
6035
6036         if (!enable_vnmi &&
6037             to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
6038                 return 0;
6039
6040         return  !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
6041                   (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
6042                    | GUEST_INTR_STATE_NMI));
6043 }
6044
6045 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
6046 {
6047         return (!to_vmx(vcpu)->nested.nested_run_pending &&
6048                 vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
6049                 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
6050                         (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
6051 }
6052
6053 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
6054 {
6055         int ret;
6056
6057         if (enable_unrestricted_guest)
6058                 return 0;
6059
6060         ret = x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
6061                                     PAGE_SIZE * 3);
6062         if (ret)
6063                 return ret;
6064         kvm->arch.tss_addr = addr;
6065         return init_rmode_tss(kvm);
6066 }
6067
6068 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
6069 {
6070         switch (vec) {
6071         case BP_VECTOR:
6072                 /*
6073                  * Update instruction length as we may reinject the exception
6074                  * from user space while in guest debugging mode.
6075                  */
6076                 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
6077                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
6078                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
6079                         return false;
6080                 /* fall through */
6081         case DB_VECTOR:
6082                 if (vcpu->guest_debug &
6083                         (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
6084                         return false;
6085                 /* fall through */
6086         case DE_VECTOR:
6087         case OF_VECTOR:
6088         case BR_VECTOR:
6089         case UD_VECTOR:
6090         case DF_VECTOR:
6091         case SS_VECTOR:
6092         case GP_VECTOR:
6093         case MF_VECTOR:
6094                 return true;
6095         break;
6096         }
6097         return false;
6098 }
6099
6100 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
6101                                   int vec, u32 err_code)
6102 {
6103         /*
6104          * Instruction with address size override prefix opcode 0x67
6105          * Cause the #SS fault with 0 error code in VM86 mode.
6106          */
6107         if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
6108                 if (emulate_instruction(vcpu, 0) == EMULATE_DONE) {
6109                         if (vcpu->arch.halt_request) {
6110                                 vcpu->arch.halt_request = 0;
6111                                 return kvm_vcpu_halt(vcpu);
6112                         }
6113                         return 1;
6114                 }
6115                 return 0;
6116         }
6117
6118         /*
6119          * Forward all other exceptions that are valid in real mode.
6120          * FIXME: Breaks guest debugging in real mode, needs to be fixed with
6121          *        the required debugging infrastructure rework.
6122          */
6123         kvm_queue_exception(vcpu, vec);
6124         return 1;
6125 }
6126
6127 /*
6128  * Trigger machine check on the host. We assume all the MSRs are already set up
6129  * by the CPU and that we still run on the same CPU as the MCE occurred on.
6130  * We pass a fake environment to the machine check handler because we want
6131  * the guest to be always treated like user space, no matter what context
6132  * it used internally.
6133  */
6134 static void kvm_machine_check(void)
6135 {
6136 #if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
6137         struct pt_regs regs = {
6138                 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
6139                 .flags = X86_EFLAGS_IF,
6140         };
6141
6142         do_machine_check(&regs, 0);
6143 #endif
6144 }
6145
6146 static int handle_machine_check(struct kvm_vcpu *vcpu)
6147 {
6148         /* already handled by vcpu_run */
6149         return 1;
6150 }
6151
6152 static int handle_exception(struct kvm_vcpu *vcpu)
6153 {
6154         struct vcpu_vmx *vmx = to_vmx(vcpu);
6155         struct kvm_run *kvm_run = vcpu->run;
6156         u32 intr_info, ex_no, error_code;
6157         unsigned long cr2, rip, dr6;
6158         u32 vect_info;
6159         enum emulation_result er;
6160
6161         vect_info = vmx->idt_vectoring_info;
6162         intr_info = vmx->exit_intr_info;
6163
6164         if (is_machine_check(intr_info))
6165                 return handle_machine_check(vcpu);
6166
6167         if (is_nmi(intr_info))
6168                 return 1;  /* already handled by vmx_vcpu_run() */
6169
6170         if (is_invalid_opcode(intr_info)) {
6171                 er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD);
6172                 if (er == EMULATE_USER_EXIT)
6173                         return 0;
6174                 if (er != EMULATE_DONE)
6175                         kvm_queue_exception(vcpu, UD_VECTOR);
6176                 return 1;
6177         }
6178
6179         error_code = 0;
6180         if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
6181                 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
6182
6183         /*
6184          * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
6185          * MMIO, it is better to report an internal error.
6186          * See the comments in vmx_handle_exit.
6187          */
6188         if ((vect_info & VECTORING_INFO_VALID_MASK) &&
6189             !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
6190                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6191                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
6192                 vcpu->run->internal.ndata = 3;
6193                 vcpu->run->internal.data[0] = vect_info;
6194                 vcpu->run->internal.data[1] = intr_info;
6195                 vcpu->run->internal.data[2] = error_code;
6196                 return 0;
6197         }
6198
6199         if (is_page_fault(intr_info)) {
6200                 cr2 = vmcs_readl(EXIT_QUALIFICATION);
6201                 /* EPT won't cause page fault directly */
6202                 WARN_ON_ONCE(!vcpu->arch.apf.host_apf_reason && enable_ept);
6203                 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
6204         }
6205
6206         ex_no = intr_info & INTR_INFO_VECTOR_MASK;
6207
6208         if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
6209                 return handle_rmode_exception(vcpu, ex_no, error_code);
6210
6211         switch (ex_no) {
6212         case AC_VECTOR:
6213                 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
6214                 return 1;
6215         case DB_VECTOR:
6216                 dr6 = vmcs_readl(EXIT_QUALIFICATION);
6217                 if (!(vcpu->guest_debug &
6218                       (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
6219                         vcpu->arch.dr6 &= ~15;
6220                         vcpu->arch.dr6 |= dr6 | DR6_RTM;
6221                         if (!(dr6 & ~DR6_RESERVED)) /* icebp */
6222                                 skip_emulated_instruction(vcpu);
6223
6224                         kvm_queue_exception(vcpu, DB_VECTOR);
6225                         return 1;
6226                 }
6227                 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
6228                 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
6229                 /* fall through */
6230         case BP_VECTOR:
6231                 /*
6232                  * Update instruction length as we may reinject #BP from
6233                  * user space while in guest debugging mode. Reading it for
6234                  * #DB as well causes no harm, it is not used in that case.
6235                  */
6236                 vmx->vcpu.arch.event_exit_inst_len =
6237                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
6238                 kvm_run->exit_reason = KVM_EXIT_DEBUG;
6239                 rip = kvm_rip_read(vcpu);
6240                 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
6241                 kvm_run->debug.arch.exception = ex_no;
6242                 break;
6243         default:
6244                 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
6245                 kvm_run->ex.exception = ex_no;
6246                 kvm_run->ex.error_code = error_code;
6247                 break;
6248         }
6249         return 0;
6250 }
6251
6252 static int handle_external_interrupt(struct kvm_vcpu *vcpu)
6253 {
6254         ++vcpu->stat.irq_exits;
6255         return 1;
6256 }
6257
6258 static int handle_triple_fault(struct kvm_vcpu *vcpu)
6259 {
6260         vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
6261         vcpu->mmio_needed = 0;
6262         return 0;
6263 }
6264
6265 static int handle_io(struct kvm_vcpu *vcpu)
6266 {
6267         unsigned long exit_qualification;
6268         int size, in, string, ret;
6269         unsigned port;
6270
6271         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6272         string = (exit_qualification & 16) != 0;
6273         in = (exit_qualification & 8) != 0;
6274
6275         ++vcpu->stat.io_exits;
6276
6277         if (string || in)
6278                 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
6279
6280         port = exit_qualification >> 16;
6281         size = (exit_qualification & 7) + 1;
6282
6283         ret = kvm_skip_emulated_instruction(vcpu);
6284
6285         /*
6286          * TODO: we might be squashing a KVM_GUESTDBG_SINGLESTEP-triggered
6287          * KVM_EXIT_DEBUG here.
6288          */
6289         return kvm_fast_pio_out(vcpu, size, port) && ret;
6290 }
6291
6292 static void
6293 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
6294 {
6295         /*
6296          * Patch in the VMCALL instruction:
6297          */
6298         hypercall[0] = 0x0f;
6299         hypercall[1] = 0x01;
6300         hypercall[2] = 0xc1;
6301 }
6302
6303 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
6304 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
6305 {
6306         if (is_guest_mode(vcpu)) {
6307                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6308                 unsigned long orig_val = val;
6309
6310                 /*
6311                  * We get here when L2 changed cr0 in a way that did not change
6312                  * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
6313                  * but did change L0 shadowed bits. So we first calculate the
6314                  * effective cr0 value that L1 would like to write into the
6315                  * hardware. It consists of the L2-owned bits from the new
6316                  * value combined with the L1-owned bits from L1's guest_cr0.
6317                  */
6318                 val = (val & ~vmcs12->cr0_guest_host_mask) |
6319                         (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
6320
6321                 if (!nested_guest_cr0_valid(vcpu, val))
6322                         return 1;
6323
6324                 if (kvm_set_cr0(vcpu, val))
6325                         return 1;
6326                 vmcs_writel(CR0_READ_SHADOW, orig_val);
6327                 return 0;
6328         } else {
6329                 if (to_vmx(vcpu)->nested.vmxon &&
6330                     !nested_host_cr0_valid(vcpu, val))
6331                         return 1;
6332
6333                 return kvm_set_cr0(vcpu, val);
6334         }
6335 }
6336
6337 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
6338 {
6339         if (is_guest_mode(vcpu)) {
6340                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6341                 unsigned long orig_val = val;
6342
6343                 /* analogously to handle_set_cr0 */
6344                 val = (val & ~vmcs12->cr4_guest_host_mask) |
6345                         (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
6346                 if (kvm_set_cr4(vcpu, val))
6347                         return 1;
6348                 vmcs_writel(CR4_READ_SHADOW, orig_val);
6349                 return 0;
6350         } else
6351                 return kvm_set_cr4(vcpu, val);
6352 }
6353
6354 static int handle_desc(struct kvm_vcpu *vcpu)
6355 {
6356         WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
6357         return emulate_instruction(vcpu, 0) == EMULATE_DONE;
6358 }
6359
6360 static int handle_cr(struct kvm_vcpu *vcpu)
6361 {
6362         unsigned long exit_qualification, val;
6363         int cr;
6364         int reg;
6365         int err;
6366         int ret;
6367
6368         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6369         cr = exit_qualification & 15;
6370         reg = (exit_qualification >> 8) & 15;
6371         switch ((exit_qualification >> 4) & 3) {
6372         case 0: /* mov to cr */
6373                 val = kvm_register_readl(vcpu, reg);
6374                 trace_kvm_cr_write(cr, val);
6375                 switch (cr) {
6376                 case 0:
6377                         err = handle_set_cr0(vcpu, val);
6378                         return kvm_complete_insn_gp(vcpu, err);
6379                 case 3:
6380                         WARN_ON_ONCE(enable_unrestricted_guest);
6381                         err = kvm_set_cr3(vcpu, val);
6382                         return kvm_complete_insn_gp(vcpu, err);
6383                 case 4:
6384                         err = handle_set_cr4(vcpu, val);
6385                         return kvm_complete_insn_gp(vcpu, err);
6386                 case 8: {
6387                                 u8 cr8_prev = kvm_get_cr8(vcpu);
6388                                 u8 cr8 = (u8)val;
6389                                 err = kvm_set_cr8(vcpu, cr8);
6390                                 ret = kvm_complete_insn_gp(vcpu, err);
6391                                 if (lapic_in_kernel(vcpu))
6392                                         return ret;
6393                                 if (cr8_prev <= cr8)
6394                                         return ret;
6395                                 /*
6396                                  * TODO: we might be squashing a
6397                                  * KVM_GUESTDBG_SINGLESTEP-triggered
6398                                  * KVM_EXIT_DEBUG here.
6399                                  */
6400                                 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
6401                                 return 0;
6402                         }
6403                 }
6404                 break;
6405         case 2: /* clts */
6406                 WARN_ONCE(1, "Guest should always own CR0.TS");
6407                 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
6408                 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
6409                 return kvm_skip_emulated_instruction(vcpu);
6410         case 1: /*mov from cr*/
6411                 switch (cr) {
6412                 case 3:
6413                         WARN_ON_ONCE(enable_unrestricted_guest);
6414                         val = kvm_read_cr3(vcpu);
6415                         kvm_register_write(vcpu, reg, val);
6416                         trace_kvm_cr_read(cr, val);
6417                         return kvm_skip_emulated_instruction(vcpu);
6418                 case 8:
6419                         val = kvm_get_cr8(vcpu);
6420                         kvm_register_write(vcpu, reg, val);
6421                         trace_kvm_cr_read(cr, val);
6422                         return kvm_skip_emulated_instruction(vcpu);
6423                 }
6424                 break;
6425         case 3: /* lmsw */
6426                 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
6427                 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
6428                 kvm_lmsw(vcpu, val);
6429
6430                 return kvm_skip_emulated_instruction(vcpu);
6431         default:
6432                 break;
6433         }
6434         vcpu->run->exit_reason = 0;
6435         vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
6436                (int)(exit_qualification >> 4) & 3, cr);
6437         return 0;
6438 }
6439
6440 static int handle_dr(struct kvm_vcpu *vcpu)
6441 {
6442         unsigned long exit_qualification;
6443         int dr, dr7, reg;
6444
6445         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6446         dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
6447
6448         /* First, if DR does not exist, trigger UD */
6449         if (!kvm_require_dr(vcpu, dr))
6450                 return 1;
6451
6452         /* Do not handle if the CPL > 0, will trigger GP on re-entry */
6453         if (!kvm_require_cpl(vcpu, 0))
6454                 return 1;
6455         dr7 = vmcs_readl(GUEST_DR7);
6456         if (dr7 & DR7_GD) {
6457                 /*
6458                  * As the vm-exit takes precedence over the debug trap, we
6459                  * need to emulate the latter, either for the host or the
6460                  * guest debugging itself.
6461                  */
6462                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
6463                         vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
6464                         vcpu->run->debug.arch.dr7 = dr7;
6465                         vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
6466                         vcpu->run->debug.arch.exception = DB_VECTOR;
6467                         vcpu->run->exit_reason = KVM_EXIT_DEBUG;
6468                         return 0;
6469                 } else {
6470                         vcpu->arch.dr6 &= ~15;
6471                         vcpu->arch.dr6 |= DR6_BD | DR6_RTM;
6472                         kvm_queue_exception(vcpu, DB_VECTOR);
6473                         return 1;
6474                 }
6475         }
6476
6477         if (vcpu->guest_debug == 0) {
6478                 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
6479                                 CPU_BASED_MOV_DR_EXITING);
6480
6481                 /*
6482                  * No more DR vmexits; force a reload of the debug registers
6483                  * and reenter on this instruction.  The next vmexit will
6484                  * retrieve the full state of the debug registers.
6485                  */
6486                 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
6487                 return 1;
6488         }
6489
6490         reg = DEBUG_REG_ACCESS_REG(exit_qualification);
6491         if (exit_qualification & TYPE_MOV_FROM_DR) {
6492                 unsigned long val;
6493
6494                 if (kvm_get_dr(vcpu, dr, &val))
6495                         return 1;
6496                 kvm_register_write(vcpu, reg, val);
6497         } else
6498                 if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
6499                         return 1;
6500
6501         return kvm_skip_emulated_instruction(vcpu);
6502 }
6503
6504 static u64 vmx_get_dr6(struct kvm_vcpu *vcpu)
6505 {
6506         return vcpu->arch.dr6;
6507 }
6508
6509 static void vmx_set_dr6(struct kvm_vcpu *vcpu, unsigned long val)
6510 {
6511 }
6512
6513 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
6514 {
6515         get_debugreg(vcpu->arch.db[0], 0);
6516         get_debugreg(vcpu->arch.db[1], 1);
6517         get_debugreg(vcpu->arch.db[2], 2);
6518         get_debugreg(vcpu->arch.db[3], 3);
6519         get_debugreg(vcpu->arch.dr6, 6);
6520         vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
6521
6522         vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
6523         vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL, CPU_BASED_MOV_DR_EXITING);
6524 }
6525
6526 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
6527 {
6528         vmcs_writel(GUEST_DR7, val);
6529 }
6530
6531 static int handle_cpuid(struct kvm_vcpu *vcpu)
6532 {
6533         return kvm_emulate_cpuid(vcpu);
6534 }
6535
6536 static int handle_rdmsr(struct kvm_vcpu *vcpu)
6537 {
6538         u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
6539         struct msr_data msr_info;
6540
6541         msr_info.index = ecx;
6542         msr_info.host_initiated = false;
6543         if (vmx_get_msr(vcpu, &msr_info)) {
6544                 trace_kvm_msr_read_ex(ecx);
6545                 kvm_inject_gp(vcpu, 0);
6546                 return 1;
6547         }
6548
6549         trace_kvm_msr_read(ecx, msr_info.data);
6550
6551         /* FIXME: handling of bits 32:63 of rax, rdx */
6552         vcpu->arch.regs[VCPU_REGS_RAX] = msr_info.data & -1u;
6553         vcpu->arch.regs[VCPU_REGS_RDX] = (msr_info.data >> 32) & -1u;
6554         return kvm_skip_emulated_instruction(vcpu);
6555 }
6556
6557 static int handle_wrmsr(struct kvm_vcpu *vcpu)
6558 {
6559         struct msr_data msr;
6560         u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
6561         u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
6562                 | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
6563
6564         msr.data = data;
6565         msr.index = ecx;
6566         msr.host_initiated = false;
6567         if (kvm_set_msr(vcpu, &msr) != 0) {
6568                 trace_kvm_msr_write_ex(ecx, data);
6569                 kvm_inject_gp(vcpu, 0);
6570                 return 1;
6571         }
6572
6573         trace_kvm_msr_write(ecx, data);
6574         return kvm_skip_emulated_instruction(vcpu);
6575 }
6576
6577 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
6578 {
6579         kvm_apic_update_ppr(vcpu);
6580         return 1;
6581 }
6582
6583 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
6584 {
6585         vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
6586                         CPU_BASED_VIRTUAL_INTR_PENDING);
6587
6588         kvm_make_request(KVM_REQ_EVENT, vcpu);
6589
6590         ++vcpu->stat.irq_window_exits;
6591         return 1;
6592 }
6593
6594 static int handle_halt(struct kvm_vcpu *vcpu)
6595 {
6596         return kvm_emulate_halt(vcpu);
6597 }
6598
6599 static int handle_vmcall(struct kvm_vcpu *vcpu)
6600 {
6601         return kvm_emulate_hypercall(vcpu);
6602 }
6603
6604 static int handle_invd(struct kvm_vcpu *vcpu)
6605 {
6606         return emulate_instruction(vcpu, 0) == EMULATE_DONE;
6607 }
6608
6609 static int handle_invlpg(struct kvm_vcpu *vcpu)
6610 {
6611         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6612
6613         kvm_mmu_invlpg(vcpu, exit_qualification);
6614         return kvm_skip_emulated_instruction(vcpu);
6615 }
6616
6617 static int handle_rdpmc(struct kvm_vcpu *vcpu)
6618 {
6619         int err;
6620
6621         err = kvm_rdpmc(vcpu);
6622         return kvm_complete_insn_gp(vcpu, err);
6623 }
6624
6625 static int handle_wbinvd(struct kvm_vcpu *vcpu)
6626 {
6627         return kvm_emulate_wbinvd(vcpu);
6628 }
6629
6630 static int handle_xsetbv(struct kvm_vcpu *vcpu)
6631 {
6632         u64 new_bv = kvm_read_edx_eax(vcpu);
6633         u32 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
6634
6635         if (kvm_set_xcr(vcpu, index, new_bv) == 0)
6636                 return kvm_skip_emulated_instruction(vcpu);
6637         return 1;
6638 }
6639
6640 static int handle_xsaves(struct kvm_vcpu *vcpu)
6641 {
6642         kvm_skip_emulated_instruction(vcpu);
6643         WARN(1, "this should never happen\n");
6644         return 1;
6645 }
6646
6647 static int handle_xrstors(struct kvm_vcpu *vcpu)
6648 {
6649         kvm_skip_emulated_instruction(vcpu);
6650         WARN(1, "this should never happen\n");
6651         return 1;
6652 }
6653
6654 static int handle_apic_access(struct kvm_vcpu *vcpu)
6655 {
6656         if (likely(fasteoi)) {
6657                 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6658                 int access_type, offset;
6659
6660                 access_type = exit_qualification & APIC_ACCESS_TYPE;
6661                 offset = exit_qualification & APIC_ACCESS_OFFSET;
6662                 /*
6663                  * Sane guest uses MOV to write EOI, with written value
6664                  * not cared. So make a short-circuit here by avoiding
6665                  * heavy instruction emulation.
6666                  */
6667                 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
6668                     (offset == APIC_EOI)) {
6669                         kvm_lapic_set_eoi(vcpu);
6670                         return kvm_skip_emulated_instruction(vcpu);
6671                 }
6672         }
6673         return emulate_instruction(vcpu, 0) == EMULATE_DONE;
6674 }
6675
6676 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
6677 {
6678         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6679         int vector = exit_qualification & 0xff;
6680
6681         /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
6682         kvm_apic_set_eoi_accelerated(vcpu, vector);
6683         return 1;
6684 }
6685
6686 static int handle_apic_write(struct kvm_vcpu *vcpu)
6687 {
6688         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6689         u32 offset = exit_qualification & 0xfff;
6690
6691         /* APIC-write VM exit is trap-like and thus no need to adjust IP */
6692         kvm_apic_write_nodecode(vcpu, offset);
6693         return 1;
6694 }
6695
6696 static int handle_task_switch(struct kvm_vcpu *vcpu)
6697 {
6698         struct vcpu_vmx *vmx = to_vmx(vcpu);
6699         unsigned long exit_qualification;
6700         bool has_error_code = false;
6701         u32 error_code = 0;
6702         u16 tss_selector;
6703         int reason, type, idt_v, idt_index;
6704
6705         idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
6706         idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
6707         type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
6708
6709         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6710
6711         reason = (u32)exit_qualification >> 30;
6712         if (reason == TASK_SWITCH_GATE && idt_v) {
6713                 switch (type) {
6714                 case INTR_TYPE_NMI_INTR:
6715                         vcpu->arch.nmi_injected = false;
6716                         vmx_set_nmi_mask(vcpu, true);
6717                         break;
6718                 case INTR_TYPE_EXT_INTR:
6719                 case INTR_TYPE_SOFT_INTR:
6720                         kvm_clear_interrupt_queue(vcpu);
6721                         break;
6722                 case INTR_TYPE_HARD_EXCEPTION:
6723                         if (vmx->idt_vectoring_info &
6724                             VECTORING_INFO_DELIVER_CODE_MASK) {
6725                                 has_error_code = true;
6726                                 error_code =
6727                                         vmcs_read32(IDT_VECTORING_ERROR_CODE);
6728                         }
6729                         /* fall through */
6730                 case INTR_TYPE_SOFT_EXCEPTION:
6731                         kvm_clear_exception_queue(vcpu);
6732                         break;
6733                 default:
6734                         break;
6735                 }
6736         }
6737         tss_selector = exit_qualification;
6738
6739         if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
6740                        type != INTR_TYPE_EXT_INTR &&
6741                        type != INTR_TYPE_NMI_INTR))
6742                 skip_emulated_instruction(vcpu);
6743
6744         if (kvm_task_switch(vcpu, tss_selector,
6745                             type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason,
6746                             has_error_code, error_code) == EMULATE_FAIL) {
6747                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6748                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6749                 vcpu->run->internal.ndata = 0;
6750                 return 0;
6751         }
6752
6753         /*
6754          * TODO: What about debug traps on tss switch?
6755          *       Are we supposed to inject them and update dr6?
6756          */
6757
6758         return 1;
6759 }
6760
6761 static int handle_ept_violation(struct kvm_vcpu *vcpu)
6762 {
6763         unsigned long exit_qualification;
6764         gpa_t gpa;
6765         u64 error_code;
6766
6767         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6768
6769         /*
6770          * EPT violation happened while executing iret from NMI,
6771          * "blocked by NMI" bit has to be set before next VM entry.
6772          * There are errata that may cause this bit to not be set:
6773          * AAK134, BY25.
6774          */
6775         if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
6776                         enable_vnmi &&
6777                         (exit_qualification & INTR_INFO_UNBLOCK_NMI))
6778                 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
6779
6780         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6781         trace_kvm_page_fault(gpa, exit_qualification);
6782
6783         /* Is it a read fault? */
6784         error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
6785                      ? PFERR_USER_MASK : 0;
6786         /* Is it a write fault? */
6787         error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
6788                       ? PFERR_WRITE_MASK : 0;
6789         /* Is it a fetch fault? */
6790         error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
6791                       ? PFERR_FETCH_MASK : 0;
6792         /* ept page table entry is present? */
6793         error_code |= (exit_qualification &
6794                        (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
6795                         EPT_VIOLATION_EXECUTABLE))
6796                       ? PFERR_PRESENT_MASK : 0;
6797
6798         error_code |= (exit_qualification & 0x100) != 0 ?
6799                PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
6800
6801         vcpu->arch.exit_qualification = exit_qualification;
6802         return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
6803 }
6804
6805 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
6806 {
6807         int ret;
6808         gpa_t gpa;
6809
6810         /*
6811          * A nested guest cannot optimize MMIO vmexits, because we have an
6812          * nGPA here instead of the required GPA.
6813          */
6814         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6815         if (!is_guest_mode(vcpu) &&
6816             !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
6817                 trace_kvm_fast_mmio(gpa);
6818                 /*
6819                  * Doing kvm_skip_emulated_instruction() depends on undefined
6820                  * behavior: Intel's manual doesn't mandate
6821                  * VM_EXIT_INSTRUCTION_LEN to be set in VMCS when EPT MISCONFIG
6822                  * occurs and while on real hardware it was observed to be set,
6823                  * other hypervisors (namely Hyper-V) don't set it, we end up
6824                  * advancing IP with some random value. Disable fast mmio when
6825                  * running nested and keep it for real hardware in hope that
6826                  * VM_EXIT_INSTRUCTION_LEN will always be set correctly.
6827                  */
6828                 if (!static_cpu_has(X86_FEATURE_HYPERVISOR))
6829                         return kvm_skip_emulated_instruction(vcpu);
6830                 else
6831                         return x86_emulate_instruction(vcpu, gpa, EMULTYPE_SKIP,
6832                                                        NULL, 0) == EMULATE_DONE;
6833         }
6834
6835         ret = kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
6836         if (ret >= 0)
6837                 return ret;
6838
6839         /* It is the real ept misconfig */
6840         WARN_ON(1);
6841
6842         vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
6843         vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_MISCONFIG;
6844
6845         return 0;
6846 }
6847
6848 static int handle_nmi_window(struct kvm_vcpu *vcpu)
6849 {
6850         WARN_ON_ONCE(!enable_vnmi);
6851         vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
6852                         CPU_BASED_VIRTUAL_NMI_PENDING);
6853         ++vcpu->stat.nmi_window_exits;
6854         kvm_make_request(KVM_REQ_EVENT, vcpu);
6855
6856         return 1;
6857 }
6858
6859 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
6860 {
6861         struct vcpu_vmx *vmx = to_vmx(vcpu);
6862         enum emulation_result err = EMULATE_DONE;
6863         int ret = 1;
6864         u32 cpu_exec_ctrl;
6865         bool intr_window_requested;
6866         unsigned count = 130;
6867
6868         /*
6869          * We should never reach the point where we are emulating L2
6870          * due to invalid guest state as that means we incorrectly
6871          * allowed a nested VMEntry with an invalid vmcs12.
6872          */
6873         WARN_ON_ONCE(vmx->emulation_required && vmx->nested.nested_run_pending);
6874
6875         cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
6876         intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
6877
6878         while (vmx->emulation_required && count-- != 0) {
6879                 if (intr_window_requested && vmx_interrupt_allowed(vcpu))
6880                         return handle_interrupt_window(&vmx->vcpu);
6881
6882                 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
6883                         return 1;
6884
6885                 err = emulate_instruction(vcpu, 0);
6886
6887                 if (err == EMULATE_USER_EXIT) {
6888                         ++vcpu->stat.mmio_exits;
6889                         ret = 0;
6890                         goto out;
6891                 }
6892
6893                 if (err != EMULATE_DONE) {
6894                         vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6895                         vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6896                         vcpu->run->internal.ndata = 0;
6897                         return 0;
6898                 }
6899
6900                 if (vcpu->arch.halt_request) {
6901                         vcpu->arch.halt_request = 0;
6902                         ret = kvm_vcpu_halt(vcpu);
6903                         goto out;
6904                 }
6905
6906                 if (signal_pending(current))
6907                         goto out;
6908                 if (need_resched())
6909                         schedule();
6910         }
6911
6912 out:
6913         return ret;
6914 }
6915
6916 static int __grow_ple_window(int val)
6917 {
6918         if (ple_window_grow < 1)
6919                 return ple_window;
6920
6921         val = min(val, ple_window_actual_max);
6922
6923         if (ple_window_grow < ple_window)
6924                 val *= ple_window_grow;
6925         else
6926                 val += ple_window_grow;
6927
6928         return val;
6929 }
6930
6931 static int __shrink_ple_window(int val, int modifier, int minimum)
6932 {
6933         if (modifier < 1)
6934                 return ple_window;
6935
6936         if (modifier < ple_window)
6937                 val /= modifier;
6938         else
6939                 val -= modifier;
6940
6941         return max(val, minimum);
6942 }
6943
6944 static void grow_ple_window(struct kvm_vcpu *vcpu)
6945 {
6946         struct vcpu_vmx *vmx = to_vmx(vcpu);
6947         int old = vmx->ple_window;
6948
6949         vmx->ple_window = __grow_ple_window(old);
6950
6951         if (vmx->ple_window != old)
6952                 vmx->ple_window_dirty = true;
6953
6954         trace_kvm_ple_window_grow(vcpu->vcpu_id, vmx->ple_window, old);
6955 }
6956
6957 static void shrink_ple_window(struct kvm_vcpu *vcpu)
6958 {
6959         struct vcpu_vmx *vmx = to_vmx(vcpu);
6960         int old = vmx->ple_window;
6961
6962         vmx->ple_window = __shrink_ple_window(old,
6963                                               ple_window_shrink, ple_window);
6964
6965         if (vmx->ple_window != old)
6966                 vmx->ple_window_dirty = true;
6967
6968         trace_kvm_ple_window_shrink(vcpu->vcpu_id, vmx->ple_window, old);
6969 }
6970
6971 /*
6972  * ple_window_actual_max is computed to be one grow_ple_window() below
6973  * ple_window_max. (See __grow_ple_window for the reason.)
6974  * This prevents overflows, because ple_window_max is int.
6975  * ple_window_max effectively rounded down to a multiple of ple_window_grow in
6976  * this process.
6977  * ple_window_max is also prevented from setting vmx->ple_window < ple_window.
6978  */
6979 static void update_ple_window_actual_max(void)
6980 {
6981         ple_window_actual_max =
6982                         __shrink_ple_window(max(ple_window_max, ple_window),
6983                                             ple_window_grow, INT_MIN);
6984 }
6985
6986 /*
6987  * Handler for POSTED_INTERRUPT_WAKEUP_VECTOR.
6988  */
6989 static void wakeup_handler(void)
6990 {
6991         struct kvm_vcpu *vcpu;
6992         int cpu = smp_processor_id();
6993
6994         spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
6995         list_for_each_entry(vcpu, &per_cpu(blocked_vcpu_on_cpu, cpu),
6996                         blocked_vcpu_list) {
6997                 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
6998
6999                 if (pi_test_on(pi_desc) == 1)
7000                         kvm_vcpu_kick(vcpu);
7001         }
7002         spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
7003 }
7004
7005 void vmx_enable_tdp(void)
7006 {
7007         kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
7008                 enable_ept_ad_bits ? VMX_EPT_ACCESS_BIT : 0ull,
7009                 enable_ept_ad_bits ? VMX_EPT_DIRTY_BIT : 0ull,
7010                 0ull, VMX_EPT_EXECUTABLE_MASK,
7011                 cpu_has_vmx_ept_execute_only() ? 0ull : VMX_EPT_READABLE_MASK,
7012                 VMX_EPT_RWX_MASK, 0ull);
7013
7014         ept_set_mmio_spte_mask();
7015         kvm_enable_tdp();
7016 }
7017
7018 static __init int hardware_setup(void)
7019 {
7020         int r = -ENOMEM, i;
7021
7022         rdmsrl_safe(MSR_EFER, &host_efer);
7023
7024         for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)
7025                 kvm_define_shared_msr(i, vmx_msr_index[i]);
7026
7027         for (i = 0; i < VMX_BITMAP_NR; i++) {
7028                 vmx_bitmap[i] = (unsigned long *)__get_free_page(GFP_KERNEL);
7029                 if (!vmx_bitmap[i])
7030                         goto out;
7031         }
7032
7033         memset(vmx_vmread_bitmap, 0xff, PAGE_SIZE);
7034         memset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE);
7035
7036         if (setup_vmcs_config(&vmcs_config) < 0) {
7037                 r = -EIO;
7038                 goto out;
7039         }
7040
7041         if (boot_cpu_has(X86_FEATURE_NX))
7042                 kvm_enable_efer_bits(EFER_NX);
7043
7044         if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
7045                 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
7046                 enable_vpid = 0;
7047
7048         if (!cpu_has_vmx_ept() ||
7049             !cpu_has_vmx_ept_4levels() ||
7050             !cpu_has_vmx_ept_mt_wb() ||
7051             !cpu_has_vmx_invept_global())
7052                 enable_ept = 0;
7053
7054         if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
7055                 enable_ept_ad_bits = 0;
7056
7057         if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
7058                 enable_unrestricted_guest = 0;
7059
7060         if (!cpu_has_vmx_flexpriority())
7061                 flexpriority_enabled = 0;
7062
7063         if (!cpu_has_virtual_nmis())
7064                 enable_vnmi = 0;
7065
7066         /*
7067          * set_apic_access_page_addr() is used to reload apic access
7068          * page upon invalidation.  No need to do anything if not
7069          * using the APIC_ACCESS_ADDR VMCS field.
7070          */
7071         if (!flexpriority_enabled)
7072                 kvm_x86_ops->set_apic_access_page_addr = NULL;
7073
7074         if (!cpu_has_vmx_tpr_shadow())
7075                 kvm_x86_ops->update_cr8_intercept = NULL;
7076
7077         if (enable_ept && !cpu_has_vmx_ept_2m_page())
7078                 kvm_disable_largepages();
7079
7080         if (!cpu_has_vmx_ple()) {
7081                 ple_gap = 0;
7082                 ple_window = 0;
7083                 ple_window_grow = 0;
7084                 ple_window_max = 0;
7085                 ple_window_shrink = 0;
7086         }
7087
7088         if (!cpu_has_vmx_apicv()) {
7089                 enable_apicv = 0;
7090                 kvm_x86_ops->sync_pir_to_irr = NULL;
7091         }
7092
7093         if (cpu_has_vmx_tsc_scaling()) {
7094                 kvm_has_tsc_control = true;
7095                 kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
7096                 kvm_tsc_scaling_ratio_frac_bits = 48;
7097         }
7098
7099         set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
7100
7101         if (enable_ept)
7102                 vmx_enable_tdp();
7103         else
7104                 kvm_disable_tdp();
7105
7106         update_ple_window_actual_max();
7107
7108         /*
7109          * Only enable PML when hardware supports PML feature, and both EPT
7110          * and EPT A/D bit features are enabled -- PML depends on them to work.
7111          */
7112         if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
7113                 enable_pml = 0;
7114
7115         if (!enable_pml) {
7116                 kvm_x86_ops->slot_enable_log_dirty = NULL;
7117                 kvm_x86_ops->slot_disable_log_dirty = NULL;
7118                 kvm_x86_ops->flush_log_dirty = NULL;
7119                 kvm_x86_ops->enable_log_dirty_pt_masked = NULL;
7120         }
7121
7122         if (cpu_has_vmx_preemption_timer() && enable_preemption_timer) {
7123                 u64 vmx_msr;
7124
7125                 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
7126                 cpu_preemption_timer_multi =
7127                          vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
7128         } else {
7129                 kvm_x86_ops->set_hv_timer = NULL;
7130                 kvm_x86_ops->cancel_hv_timer = NULL;
7131         }
7132
7133         if (!cpu_has_vmx_shadow_vmcs())
7134                 enable_shadow_vmcs = 0;
7135         if (enable_shadow_vmcs)
7136                 init_vmcs_shadow_fields();
7137
7138         kvm_set_posted_intr_wakeup_handler(wakeup_handler);
7139         nested_vmx_setup_ctls_msrs(&vmcs_config.nested, enable_apicv);
7140
7141         kvm_mce_cap_supported |= MCG_LMCE_P;
7142
7143         return alloc_kvm_area();
7144
7145 out:
7146         for (i = 0; i < VMX_BITMAP_NR; i++)
7147                 free_page((unsigned long)vmx_bitmap[i]);
7148
7149     return r;
7150 }
7151
7152 static __exit void hardware_unsetup(void)
7153 {
7154         int i;
7155
7156         for (i = 0; i < VMX_BITMAP_NR; i++)
7157                 free_page((unsigned long)vmx_bitmap[i]);
7158
7159         free_kvm_area();
7160 }
7161
7162 /*
7163  * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
7164  * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
7165  */
7166 static int handle_pause(struct kvm_vcpu *vcpu)
7167 {
7168         if (ple_gap)
7169                 grow_ple_window(vcpu);
7170
7171         /*
7172          * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
7173          * VM-execution control is ignored if CPL > 0. OTOH, KVM
7174          * never set PAUSE_EXITING and just set PLE if supported,
7175          * so the vcpu must be CPL=0 if it gets a PAUSE exit.
7176          */
7177         kvm_vcpu_on_spin(vcpu, true);
7178         return kvm_skip_emulated_instruction(vcpu);
7179 }
7180
7181 static int handle_nop(struct kvm_vcpu *vcpu)
7182 {
7183         return kvm_skip_emulated_instruction(vcpu);
7184 }
7185
7186 static int handle_mwait(struct kvm_vcpu *vcpu)
7187 {
7188         printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
7189         return handle_nop(vcpu);
7190 }
7191
7192 static int handle_invalid_op(struct kvm_vcpu *vcpu)
7193 {
7194         kvm_queue_exception(vcpu, UD_VECTOR);
7195         return 1;
7196 }
7197
7198 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
7199 {
7200         return 1;
7201 }
7202
7203 static int handle_monitor(struct kvm_vcpu *vcpu)
7204 {
7205         printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
7206         return handle_nop(vcpu);
7207 }
7208
7209 /*
7210  * The following 3 functions, nested_vmx_succeed()/failValid()/failInvalid(),
7211  * set the success or error code of an emulated VMX instruction, as specified
7212  * by Vol 2B, VMX Instruction Reference, "Conventions".
7213  */
7214 static void nested_vmx_succeed(struct kvm_vcpu *vcpu)
7215 {
7216         vmx_set_rflags(vcpu, vmx_get_rflags(vcpu)
7217                         & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
7218                             X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF));
7219 }
7220
7221 static void nested_vmx_failInvalid(struct kvm_vcpu *vcpu)
7222 {
7223         vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
7224                         & ~(X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
7225                             X86_EFLAGS_SF | X86_EFLAGS_OF))
7226                         | X86_EFLAGS_CF);
7227 }
7228
7229 static void nested_vmx_failValid(struct kvm_vcpu *vcpu,
7230                                         u32 vm_instruction_error)
7231 {
7232         if (to_vmx(vcpu)->nested.current_vmptr == -1ull) {
7233                 /*
7234                  * failValid writes the error number to the current VMCS, which
7235                  * can't be done there isn't a current VMCS.
7236                  */
7237                 nested_vmx_failInvalid(vcpu);
7238                 return;
7239         }
7240         vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
7241                         & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
7242                             X86_EFLAGS_SF | X86_EFLAGS_OF))
7243                         | X86_EFLAGS_ZF);
7244         get_vmcs12(vcpu)->vm_instruction_error = vm_instruction_error;
7245         /*
7246          * We don't need to force a shadow sync because
7247          * VM_INSTRUCTION_ERROR is not shadowed
7248          */
7249 }
7250
7251 static void nested_vmx_abort(struct kvm_vcpu *vcpu, u32 indicator)
7252 {
7253         /* TODO: not to reset guest simply here. */
7254         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
7255         pr_debug_ratelimited("kvm: nested vmx abort, indicator %d\n", indicator);
7256 }
7257
7258 static enum hrtimer_restart vmx_preemption_timer_fn(struct hrtimer *timer)
7259 {
7260         struct vcpu_vmx *vmx =
7261                 container_of(timer, struct vcpu_vmx, nested.preemption_timer);
7262
7263         vmx->nested.preemption_timer_expired = true;
7264         kvm_make_request(KVM_REQ_EVENT, &vmx->vcpu);
7265         kvm_vcpu_kick(&vmx->vcpu);
7266
7267         return HRTIMER_NORESTART;
7268 }
7269
7270 /*
7271  * Decode the memory-address operand of a vmx instruction, as recorded on an
7272  * exit caused by such an instruction (run by a guest hypervisor).
7273  * On success, returns 0. When the operand is invalid, returns 1 and throws
7274  * #UD or #GP.
7275  */
7276 static int get_vmx_mem_address(struct kvm_vcpu *vcpu,
7277                                  unsigned long exit_qualification,
7278                                  u32 vmx_instruction_info, bool wr, gva_t *ret)
7279 {
7280         gva_t off;
7281         bool exn;
7282         struct kvm_segment s;
7283
7284         /*
7285          * According to Vol. 3B, "Information for VM Exits Due to Instruction
7286          * Execution", on an exit, vmx_instruction_info holds most of the
7287          * addressing components of the operand. Only the displacement part
7288          * is put in exit_qualification (see 3B, "Basic VM-Exit Information").
7289          * For how an actual address is calculated from all these components,
7290          * refer to Vol. 1, "Operand Addressing".
7291          */
7292         int  scaling = vmx_instruction_info & 3;
7293         int  addr_size = (vmx_instruction_info >> 7) & 7;
7294         bool is_reg = vmx_instruction_info & (1u << 10);
7295         int  seg_reg = (vmx_instruction_info >> 15) & 7;
7296         int  index_reg = (vmx_instruction_info >> 18) & 0xf;
7297         bool index_is_valid = !(vmx_instruction_info & (1u << 22));
7298         int  base_reg       = (vmx_instruction_info >> 23) & 0xf;
7299         bool base_is_valid  = !(vmx_instruction_info & (1u << 27));
7300
7301         if (is_reg) {
7302                 kvm_queue_exception(vcpu, UD_VECTOR);
7303                 return 1;
7304         }
7305
7306         /* Addr = segment_base + offset */
7307         /* offset = base + [index * scale] + displacement */
7308         off = exit_qualification; /* holds the displacement */
7309         if (base_is_valid)
7310                 off += kvm_register_read(vcpu, base_reg);
7311         if (index_is_valid)
7312                 off += kvm_register_read(vcpu, index_reg)<<scaling;
7313         vmx_get_segment(vcpu, &s, seg_reg);
7314         *ret = s.base + off;
7315
7316         if (addr_size == 1) /* 32 bit */
7317                 *ret &= 0xffffffff;
7318
7319         /* Checks for #GP/#SS exceptions. */
7320         exn = false;
7321         if (is_long_mode(vcpu)) {
7322                 /* Long mode: #GP(0)/#SS(0) if the memory address is in a
7323                  * non-canonical form. This is the only check on the memory
7324                  * destination for long mode!
7325                  */
7326                 exn = is_noncanonical_address(*ret, vcpu);
7327         } else if (is_protmode(vcpu)) {
7328                 /* Protected mode: apply checks for segment validity in the
7329                  * following order:
7330                  * - segment type check (#GP(0) may be thrown)
7331                  * - usability check (#GP(0)/#SS(0))
7332                  * - limit check (#GP(0)/#SS(0))
7333                  */
7334                 if (wr)
7335                         /* #GP(0) if the destination operand is located in a
7336                          * read-only data segment or any code segment.
7337                          */
7338                         exn = ((s.type & 0xa) == 0 || (s.type & 8));
7339                 else
7340                         /* #GP(0) if the source operand is located in an
7341                          * execute-only code segment
7342                          */
7343                         exn = ((s.type & 0xa) == 8);
7344                 if (exn) {
7345                         kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
7346                         return 1;
7347                 }
7348                 /* Protected mode: #GP(0)/#SS(0) if the segment is unusable.
7349                  */
7350                 exn = (s.unusable != 0);
7351                 /* Protected mode: #GP(0)/#SS(0) if the memory
7352                  * operand is outside the segment limit.
7353                  */
7354                 exn = exn || (off + sizeof(u64) > s.limit);
7355         }
7356         if (exn) {
7357                 kvm_queue_exception_e(vcpu,
7358                                       seg_reg == VCPU_SREG_SS ?
7359                                                 SS_VECTOR : GP_VECTOR,
7360                                       0);
7361                 return 1;
7362         }
7363
7364         return 0;
7365 }
7366
7367 static int nested_vmx_get_vmptr(struct kvm_vcpu *vcpu, gpa_t *vmpointer)
7368 {
7369         gva_t gva;
7370         struct x86_exception e;
7371
7372         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
7373                         vmcs_read32(VMX_INSTRUCTION_INFO), false, &gva))
7374                 return 1;
7375
7376         if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, vmpointer,
7377                                 sizeof(*vmpointer), &e)) {
7378                 kvm_inject_page_fault(vcpu, &e);
7379                 return 1;
7380         }
7381
7382         return 0;
7383 }
7384
7385 static int enter_vmx_operation(struct kvm_vcpu *vcpu)
7386 {
7387         struct vcpu_vmx *vmx = to_vmx(vcpu);
7388         struct vmcs *shadow_vmcs;
7389         int r;
7390
7391         r = alloc_loaded_vmcs(&vmx->nested.vmcs02);
7392         if (r < 0)
7393                 goto out_vmcs02;
7394
7395         vmx->nested.cached_vmcs12 = kmalloc(VMCS12_SIZE, GFP_KERNEL);
7396         if (!vmx->nested.cached_vmcs12)
7397                 goto out_cached_vmcs12;
7398
7399         if (enable_shadow_vmcs) {
7400                 shadow_vmcs = alloc_vmcs();
7401                 if (!shadow_vmcs)
7402                         goto out_shadow_vmcs;
7403                 /* mark vmcs as shadow */
7404                 shadow_vmcs->revision_id |= (1u << 31);
7405                 /* init shadow vmcs */
7406                 vmcs_clear(shadow_vmcs);
7407                 vmx->vmcs01.shadow_vmcs = shadow_vmcs;
7408         }
7409
7410         hrtimer_init(&vmx->nested.preemption_timer, CLOCK_MONOTONIC,
7411                      HRTIMER_MODE_REL_PINNED);
7412         vmx->nested.preemption_timer.function = vmx_preemption_timer_fn;
7413
7414         vmx->nested.vmxon = true;
7415         return 0;
7416
7417 out_shadow_vmcs:
7418         kfree(vmx->nested.cached_vmcs12);
7419
7420 out_cached_vmcs12:
7421         free_loaded_vmcs(&vmx->nested.vmcs02);
7422
7423 out_vmcs02:
7424         return -ENOMEM;
7425 }
7426
7427 /*
7428  * Emulate the VMXON instruction.
7429  * Currently, we just remember that VMX is active, and do not save or even
7430  * inspect the argument to VMXON (the so-called "VMXON pointer") because we
7431  * do not currently need to store anything in that guest-allocated memory
7432  * region. Consequently, VMCLEAR and VMPTRLD also do not verify that the their
7433  * argument is different from the VMXON pointer (which the spec says they do).
7434  */
7435 static int handle_vmon(struct kvm_vcpu *vcpu)
7436 {
7437         int ret;
7438         gpa_t vmptr;
7439         struct page *page;
7440         struct vcpu_vmx *vmx = to_vmx(vcpu);
7441         const u64 VMXON_NEEDED_FEATURES = FEATURE_CONTROL_LOCKED
7442                 | FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
7443
7444         /*
7445          * The Intel VMX Instruction Reference lists a bunch of bits that are
7446          * prerequisite to running VMXON, most notably cr4.VMXE must be set to
7447          * 1 (see vmx_set_cr4() for when we allow the guest to set this).
7448          * Otherwise, we should fail with #UD.  But most faulting conditions
7449          * have already been checked by hardware, prior to the VM-exit for
7450          * VMXON.  We do test guest cr4.VMXE because processor CR4 always has
7451          * that bit set to 1 in non-root mode.
7452          */
7453         if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE)) {
7454                 kvm_queue_exception(vcpu, UD_VECTOR);
7455                 return 1;
7456         }
7457
7458         if (vmx->nested.vmxon) {
7459                 nested_vmx_failValid(vcpu, VMXERR_VMXON_IN_VMX_ROOT_OPERATION);
7460                 return kvm_skip_emulated_instruction(vcpu);
7461         }
7462
7463         if ((vmx->msr_ia32_feature_control & VMXON_NEEDED_FEATURES)
7464                         != VMXON_NEEDED_FEATURES) {
7465                 kvm_inject_gp(vcpu, 0);
7466                 return 1;
7467         }
7468
7469         if (nested_vmx_get_vmptr(vcpu, &vmptr))
7470                 return 1;
7471
7472         /*
7473          * SDM 3: 24.11.5
7474          * The first 4 bytes of VMXON region contain the supported
7475          * VMCS revision identifier
7476          *
7477          * Note - IA32_VMX_BASIC[48] will never be 1 for the nested case;
7478          * which replaces physical address width with 32
7479          */
7480         if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {
7481                 nested_vmx_failInvalid(vcpu);
7482                 return kvm_skip_emulated_instruction(vcpu);
7483         }
7484
7485         page = kvm_vcpu_gpa_to_page(vcpu, vmptr);
7486         if (is_error_page(page)) {
7487                 nested_vmx_failInvalid(vcpu);
7488                 return kvm_skip_emulated_instruction(vcpu);
7489         }
7490         if (*(u32 *)kmap(page) != VMCS12_REVISION) {
7491                 kunmap(page);
7492                 kvm_release_page_clean(page);
7493                 nested_vmx_failInvalid(vcpu);
7494                 return kvm_skip_emulated_instruction(vcpu);
7495         }
7496         kunmap(page);
7497         kvm_release_page_clean(page);
7498
7499         vmx->nested.vmxon_ptr = vmptr;
7500         ret = enter_vmx_operation(vcpu);
7501         if (ret)
7502                 return ret;
7503
7504         nested_vmx_succeed(vcpu);
7505         return kvm_skip_emulated_instruction(vcpu);
7506 }
7507
7508 /*
7509  * Intel's VMX Instruction Reference specifies a common set of prerequisites
7510  * for running VMX instructions (except VMXON, whose prerequisites are
7511  * slightly different). It also specifies what exception to inject otherwise.
7512  * Note that many of these exceptions have priority over VM exits, so they
7513  * don't have to be checked again here.
7514  */
7515 static int nested_vmx_check_permission(struct kvm_vcpu *vcpu)
7516 {
7517         if (!to_vmx(vcpu)->nested.vmxon) {
7518                 kvm_queue_exception(vcpu, UD_VECTOR);
7519                 return 0;
7520         }
7521         return 1;
7522 }
7523
7524 static void vmx_disable_shadow_vmcs(struct vcpu_vmx *vmx)
7525 {
7526         vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL, SECONDARY_EXEC_SHADOW_VMCS);
7527         vmcs_write64(VMCS_LINK_POINTER, -1ull);
7528 }
7529
7530 static inline void nested_release_vmcs12(struct vcpu_vmx *vmx)
7531 {
7532         if (vmx->nested.current_vmptr == -1ull)
7533                 return;
7534
7535         if (enable_shadow_vmcs) {
7536                 /* copy to memory all shadowed fields in case
7537                    they were modified */
7538                 copy_shadow_to_vmcs12(vmx);
7539                 vmx->nested.sync_shadow_vmcs = false;
7540                 vmx_disable_shadow_vmcs(vmx);
7541         }
7542         vmx->nested.posted_intr_nv = -1;
7543
7544         /* Flush VMCS12 to guest memory */
7545         kvm_vcpu_write_guest_page(&vmx->vcpu,
7546                                   vmx->nested.current_vmptr >> PAGE_SHIFT,
7547                                   vmx->nested.cached_vmcs12, 0, VMCS12_SIZE);
7548
7549         vmx->nested.current_vmptr = -1ull;
7550 }
7551
7552 /*
7553  * Free whatever needs to be freed from vmx->nested when L1 goes down, or
7554  * just stops using VMX.
7555  */
7556 static void free_nested(struct vcpu_vmx *vmx)
7557 {
7558         if (!vmx->nested.vmxon && !vmx->nested.smm.vmxon)
7559                 return;
7560
7561         vmx->nested.vmxon = false;
7562         vmx->nested.smm.vmxon = false;
7563         free_vpid(vmx->nested.vpid02);
7564         vmx->nested.posted_intr_nv = -1;
7565         vmx->nested.current_vmptr = -1ull;
7566         if (enable_shadow_vmcs) {
7567                 vmx_disable_shadow_vmcs(vmx);
7568                 vmcs_clear(vmx->vmcs01.shadow_vmcs);
7569                 free_vmcs(vmx->vmcs01.shadow_vmcs);
7570                 vmx->vmcs01.shadow_vmcs = NULL;
7571         }
7572         kfree(vmx->nested.cached_vmcs12);
7573         /* Unpin physical memory we referred to in the vmcs02 */
7574         if (vmx->nested.apic_access_page) {
7575                 kvm_release_page_dirty(vmx->nested.apic_access_page);
7576                 vmx->nested.apic_access_page = NULL;
7577         }
7578         if (vmx->nested.virtual_apic_page) {
7579                 kvm_release_page_dirty(vmx->nested.virtual_apic_page);
7580                 vmx->nested.virtual_apic_page = NULL;
7581         }
7582         if (vmx->nested.pi_desc_page) {
7583                 kunmap(vmx->nested.pi_desc_page);
7584                 kvm_release_page_dirty(vmx->nested.pi_desc_page);
7585                 vmx->nested.pi_desc_page = NULL;
7586                 vmx->nested.pi_desc = NULL;
7587         }
7588
7589         free_loaded_vmcs(&vmx->nested.vmcs02);
7590 }
7591
7592 /* Emulate the VMXOFF instruction */
7593 static int handle_vmoff(struct kvm_vcpu *vcpu)
7594 {
7595         if (!nested_vmx_check_permission(vcpu))
7596                 return 1;
7597         free_nested(to_vmx(vcpu));
7598         nested_vmx_succeed(vcpu);
7599         return kvm_skip_emulated_instruction(vcpu);
7600 }
7601
7602 /* Emulate the VMCLEAR instruction */
7603 static int handle_vmclear(struct kvm_vcpu *vcpu)
7604 {
7605         struct vcpu_vmx *vmx = to_vmx(vcpu);
7606         u32 zero = 0;
7607         gpa_t vmptr;
7608
7609         if (!nested_vmx_check_permission(vcpu))
7610                 return 1;
7611
7612         if (nested_vmx_get_vmptr(vcpu, &vmptr))
7613                 return 1;
7614
7615         if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {
7616                 nested_vmx_failValid(vcpu, VMXERR_VMCLEAR_INVALID_ADDRESS);
7617                 return kvm_skip_emulated_instruction(vcpu);
7618         }
7619
7620         if (vmptr == vmx->nested.vmxon_ptr) {
7621                 nested_vmx_failValid(vcpu, VMXERR_VMCLEAR_VMXON_POINTER);
7622                 return kvm_skip_emulated_instruction(vcpu);
7623         }
7624
7625         if (vmptr == vmx->nested.current_vmptr)
7626                 nested_release_vmcs12(vmx);
7627
7628         kvm_vcpu_write_guest(vcpu,
7629                         vmptr + offsetof(struct vmcs12, launch_state),
7630                         &zero, sizeof(zero));
7631
7632         nested_vmx_succeed(vcpu);
7633         return kvm_skip_emulated_instruction(vcpu);
7634 }
7635
7636 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch);
7637
7638 /* Emulate the VMLAUNCH instruction */
7639 static int handle_vmlaunch(struct kvm_vcpu *vcpu)
7640 {
7641         return nested_vmx_run(vcpu, true);
7642 }
7643
7644 /* Emulate the VMRESUME instruction */
7645 static int handle_vmresume(struct kvm_vcpu *vcpu)
7646 {
7647
7648         return nested_vmx_run(vcpu, false);
7649 }
7650
7651 /*
7652  * Read a vmcs12 field. Since these can have varying lengths and we return
7653  * one type, we chose the biggest type (u64) and zero-extend the return value
7654  * to that size. Note that the caller, handle_vmread, might need to use only
7655  * some of the bits we return here (e.g., on 32-bit guests, only 32 bits of
7656  * 64-bit fields are to be returned).
7657  */
7658 static inline int vmcs12_read_any(struct kvm_vcpu *vcpu,
7659                                   unsigned long field, u64 *ret)
7660 {
7661         short offset = vmcs_field_to_offset(field);
7662         char *p;
7663
7664         if (offset < 0)
7665                 return offset;
7666
7667         p = ((char *)(get_vmcs12(vcpu))) + offset;
7668
7669         switch (vmcs_field_width(field)) {
7670         case VMCS_FIELD_WIDTH_NATURAL_WIDTH:
7671                 *ret = *((natural_width *)p);
7672                 return 0;
7673         case VMCS_FIELD_WIDTH_U16:
7674                 *ret = *((u16 *)p);
7675                 return 0;
7676         case VMCS_FIELD_WIDTH_U32:
7677                 *ret = *((u32 *)p);
7678                 return 0;
7679         case VMCS_FIELD_WIDTH_U64:
7680                 *ret = *((u64 *)p);
7681                 return 0;
7682         default:
7683                 WARN_ON(1);
7684                 return -ENOENT;
7685         }
7686 }
7687
7688
7689 static inline int vmcs12_write_any(struct kvm_vcpu *vcpu,
7690                                    unsigned long field, u64 field_value){
7691         short offset = vmcs_field_to_offset(field);
7692         char *p = ((char *) get_vmcs12(vcpu)) + offset;
7693         if (offset < 0)
7694                 return offset;
7695
7696         switch (vmcs_field_width(field)) {
7697         case VMCS_FIELD_WIDTH_U16:
7698                 *(u16 *)p = field_value;
7699                 return 0;
7700         case VMCS_FIELD_WIDTH_U32:
7701                 *(u32 *)p = field_value;
7702                 return 0;
7703         case VMCS_FIELD_WIDTH_U64:
7704                 *(u64 *)p = field_value;
7705                 return 0;
7706         case VMCS_FIELD_WIDTH_NATURAL_WIDTH:
7707                 *(natural_width *)p = field_value;
7708                 return 0;
7709         default:
7710                 WARN_ON(1);
7711                 return -ENOENT;
7712         }
7713
7714 }
7715
7716 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx)
7717 {
7718         int i;
7719         unsigned long field;
7720         u64 field_value;
7721         struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
7722         const u16 *fields = shadow_read_write_fields;
7723         const int num_fields = max_shadow_read_write_fields;
7724
7725         preempt_disable();
7726
7727         vmcs_load(shadow_vmcs);
7728
7729         for (i = 0; i < num_fields; i++) {
7730                 field = fields[i];
7731                 field_value = __vmcs_readl(field);
7732                 vmcs12_write_any(&vmx->vcpu, field, field_value);
7733         }
7734
7735         vmcs_clear(shadow_vmcs);
7736         vmcs_load(vmx->loaded_vmcs->vmcs);
7737
7738         preempt_enable();
7739 }
7740
7741 static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx)
7742 {
7743         const u16 *fields[] = {
7744                 shadow_read_write_fields,
7745                 shadow_read_only_fields
7746         };
7747         const int max_fields[] = {
7748                 max_shadow_read_write_fields,
7749                 max_shadow_read_only_fields
7750         };
7751         int i, q;
7752         unsigned long field;
7753         u64 field_value = 0;
7754         struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
7755
7756         vmcs_load(shadow_vmcs);
7757
7758         for (q = 0; q < ARRAY_SIZE(fields); q++) {
7759                 for (i = 0; i < max_fields[q]; i++) {
7760                         field = fields[q][i];
7761                         vmcs12_read_any(&vmx->vcpu, field, &field_value);
7762                         __vmcs_writel(field, field_value);
7763                 }
7764         }
7765
7766         vmcs_clear(shadow_vmcs);
7767         vmcs_load(vmx->loaded_vmcs->vmcs);
7768 }
7769
7770 /*
7771  * VMX instructions which assume a current vmcs12 (i.e., that VMPTRLD was
7772  * used before) all generate the same failure when it is missing.
7773  */
7774 static int nested_vmx_check_vmcs12(struct kvm_vcpu *vcpu)
7775 {
7776         struct vcpu_vmx *vmx = to_vmx(vcpu);
7777         if (vmx->nested.current_vmptr == -1ull) {
7778                 nested_vmx_failInvalid(vcpu);
7779                 return 0;
7780         }
7781         return 1;
7782 }
7783
7784 static int handle_vmread(struct kvm_vcpu *vcpu)
7785 {
7786         unsigned long field;
7787         u64 field_value;
7788         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7789         u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7790         gva_t gva = 0;
7791
7792         if (!nested_vmx_check_permission(vcpu))
7793                 return 1;
7794
7795         if (!nested_vmx_check_vmcs12(vcpu))
7796                 return kvm_skip_emulated_instruction(vcpu);
7797
7798         /* Decode instruction info and find the field to read */
7799         field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
7800         /* Read the field, zero-extended to a u64 field_value */
7801         if (vmcs12_read_any(vcpu, field, &field_value) < 0) {
7802                 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
7803                 return kvm_skip_emulated_instruction(vcpu);
7804         }
7805         /*
7806          * Now copy part of this value to register or memory, as requested.
7807          * Note that the number of bits actually copied is 32 or 64 depending
7808          * on the guest's mode (32 or 64 bit), not on the given field's length.
7809          */
7810         if (vmx_instruction_info & (1u << 10)) {
7811                 kvm_register_writel(vcpu, (((vmx_instruction_info) >> 3) & 0xf),
7812                         field_value);
7813         } else {
7814                 if (get_vmx_mem_address(vcpu, exit_qualification,
7815                                 vmx_instruction_info, true, &gva))
7816                         return 1;
7817                 /* _system ok, as hardware has verified cpl=0 */
7818                 kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, gva,
7819                              &field_value, (is_long_mode(vcpu) ? 8 : 4), NULL);
7820         }
7821
7822         nested_vmx_succeed(vcpu);
7823         return kvm_skip_emulated_instruction(vcpu);
7824 }
7825
7826
7827 static int handle_vmwrite(struct kvm_vcpu *vcpu)
7828 {
7829         unsigned long field;
7830         gva_t gva;
7831         struct vcpu_vmx *vmx = to_vmx(vcpu);
7832         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7833         u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7834
7835         /* The value to write might be 32 or 64 bits, depending on L1's long
7836          * mode, and eventually we need to write that into a field of several
7837          * possible lengths. The code below first zero-extends the value to 64
7838          * bit (field_value), and then copies only the appropriate number of
7839          * bits into the vmcs12 field.
7840          */
7841         u64 field_value = 0;
7842         struct x86_exception e;
7843
7844         if (!nested_vmx_check_permission(vcpu))
7845                 return 1;
7846
7847         if (!nested_vmx_check_vmcs12(vcpu))
7848                 return kvm_skip_emulated_instruction(vcpu);
7849
7850         if (vmx_instruction_info & (1u << 10))
7851                 field_value = kvm_register_readl(vcpu,
7852                         (((vmx_instruction_info) >> 3) & 0xf));
7853         else {
7854                 if (get_vmx_mem_address(vcpu, exit_qualification,
7855                                 vmx_instruction_info, false, &gva))
7856                         return 1;
7857                 if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva,
7858                            &field_value, (is_64_bit_mode(vcpu) ? 8 : 4), &e)) {
7859                         kvm_inject_page_fault(vcpu, &e);
7860                         return 1;
7861                 }
7862         }
7863
7864
7865         field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
7866         if (vmcs_field_readonly(field)) {
7867                 nested_vmx_failValid(vcpu,
7868                         VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT);
7869                 return kvm_skip_emulated_instruction(vcpu);
7870         }
7871
7872         if (vmcs12_write_any(vcpu, field, field_value) < 0) {
7873                 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
7874                 return kvm_skip_emulated_instruction(vcpu);
7875         }
7876
7877         switch (field) {
7878 #define SHADOW_FIELD_RW(x) case x:
7879 #include "vmx_shadow_fields.h"
7880                 /*
7881                  * The fields that can be updated by L1 without a vmexit are
7882                  * always updated in the vmcs02, the others go down the slow
7883                  * path of prepare_vmcs02.
7884                  */
7885                 break;
7886         default:
7887                 vmx->nested.dirty_vmcs12 = true;
7888                 break;
7889         }
7890
7891         nested_vmx_succeed(vcpu);
7892         return kvm_skip_emulated_instruction(vcpu);
7893 }
7894
7895 static void set_current_vmptr(struct vcpu_vmx *vmx, gpa_t vmptr)
7896 {
7897         vmx->nested.current_vmptr = vmptr;
7898         if (enable_shadow_vmcs) {
7899                 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
7900                               SECONDARY_EXEC_SHADOW_VMCS);
7901                 vmcs_write64(VMCS_LINK_POINTER,
7902                              __pa(vmx->vmcs01.shadow_vmcs));
7903                 vmx->nested.sync_shadow_vmcs = true;
7904         }
7905         vmx->nested.dirty_vmcs12 = true;
7906 }
7907
7908 /* Emulate the VMPTRLD instruction */
7909 static int handle_vmptrld(struct kvm_vcpu *vcpu)
7910 {
7911         struct vcpu_vmx *vmx = to_vmx(vcpu);
7912         gpa_t vmptr;
7913
7914         if (!nested_vmx_check_permission(vcpu))
7915                 return 1;
7916
7917         if (nested_vmx_get_vmptr(vcpu, &vmptr))
7918                 return 1;
7919
7920         if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {
7921                 nested_vmx_failValid(vcpu, VMXERR_VMPTRLD_INVALID_ADDRESS);
7922                 return kvm_skip_emulated_instruction(vcpu);
7923         }
7924
7925         if (vmptr == vmx->nested.vmxon_ptr) {
7926                 nested_vmx_failValid(vcpu, VMXERR_VMPTRLD_VMXON_POINTER);
7927                 return kvm_skip_emulated_instruction(vcpu);
7928         }
7929
7930         if (vmx->nested.current_vmptr != vmptr) {
7931                 struct vmcs12 *new_vmcs12;
7932                 struct page *page;
7933                 page = kvm_vcpu_gpa_to_page(vcpu, vmptr);
7934                 if (is_error_page(page)) {
7935                         nested_vmx_failInvalid(vcpu);
7936                         return kvm_skip_emulated_instruction(vcpu);
7937                 }
7938                 new_vmcs12 = kmap(page);
7939                 if (new_vmcs12->revision_id != VMCS12_REVISION) {
7940                         kunmap(page);
7941                         kvm_release_page_clean(page);
7942                         nested_vmx_failValid(vcpu,
7943                                 VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
7944                         return kvm_skip_emulated_instruction(vcpu);
7945                 }
7946
7947                 nested_release_vmcs12(vmx);
7948                 /*
7949                  * Load VMCS12 from guest memory since it is not already
7950                  * cached.
7951                  */
7952                 memcpy(vmx->nested.cached_vmcs12, new_vmcs12, VMCS12_SIZE);
7953                 kunmap(page);
7954                 kvm_release_page_clean(page);
7955
7956                 set_current_vmptr(vmx, vmptr);
7957         }
7958
7959         nested_vmx_succeed(vcpu);
7960         return kvm_skip_emulated_instruction(vcpu);
7961 }
7962
7963 /* Emulate the VMPTRST instruction */
7964 static int handle_vmptrst(struct kvm_vcpu *vcpu)
7965 {
7966         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7967         u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7968         gva_t vmcs_gva;
7969         struct x86_exception e;
7970
7971         if (!nested_vmx_check_permission(vcpu))
7972                 return 1;
7973
7974         if (get_vmx_mem_address(vcpu, exit_qualification,
7975                         vmx_instruction_info, true, &vmcs_gva))
7976                 return 1;
7977         /* ok to use *_system, as hardware has verified cpl=0 */
7978         if (kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, vmcs_gva,
7979                                  (void *)&to_vmx(vcpu)->nested.current_vmptr,
7980                                  sizeof(u64), &e)) {
7981                 kvm_inject_page_fault(vcpu, &e);
7982                 return 1;
7983         }
7984         nested_vmx_succeed(vcpu);
7985         return kvm_skip_emulated_instruction(vcpu);
7986 }
7987
7988 /* Emulate the INVEPT instruction */
7989 static int handle_invept(struct kvm_vcpu *vcpu)
7990 {
7991         struct vcpu_vmx *vmx = to_vmx(vcpu);
7992         u32 vmx_instruction_info, types;
7993         unsigned long type;
7994         gva_t gva;
7995         struct x86_exception e;
7996         struct {
7997                 u64 eptp, gpa;
7998         } operand;
7999
8000         if (!(vmx->nested.msrs.secondary_ctls_high &
8001               SECONDARY_EXEC_ENABLE_EPT) ||
8002             !(vmx->nested.msrs.ept_caps & VMX_EPT_INVEPT_BIT)) {
8003                 kvm_queue_exception(vcpu, UD_VECTOR);
8004                 return 1;
8005         }
8006
8007         if (!nested_vmx_check_permission(vcpu))
8008                 return 1;
8009
8010         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
8011         type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
8012
8013         types = (vmx->nested.msrs.ept_caps >> VMX_EPT_EXTENT_SHIFT) & 6;
8014
8015         if (type >= 32 || !(types & (1 << type))) {
8016                 nested_vmx_failValid(vcpu,
8017                                 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
8018                 return kvm_skip_emulated_instruction(vcpu);
8019         }
8020
8021         /* According to the Intel VMX instruction reference, the memory
8022          * operand is read even if it isn't needed (e.g., for type==global)
8023          */
8024         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
8025                         vmx_instruction_info, false, &gva))
8026                 return 1;
8027         if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &operand,
8028                                 sizeof(operand), &e)) {
8029                 kvm_inject_page_fault(vcpu, &e);
8030                 return 1;
8031         }
8032
8033         switch (type) {
8034         case VMX_EPT_EXTENT_GLOBAL:
8035         /*
8036          * TODO: track mappings and invalidate
8037          * single context requests appropriately
8038          */
8039         case VMX_EPT_EXTENT_CONTEXT:
8040                 kvm_mmu_sync_roots(vcpu);
8041                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
8042                 nested_vmx_succeed(vcpu);
8043                 break;
8044         default:
8045                 BUG_ON(1);
8046                 break;
8047         }
8048
8049         return kvm_skip_emulated_instruction(vcpu);
8050 }
8051
8052 static int handle_invvpid(struct kvm_vcpu *vcpu)
8053 {
8054         struct vcpu_vmx *vmx = to_vmx(vcpu);
8055         u32 vmx_instruction_info;
8056         unsigned long type, types;
8057         gva_t gva;
8058         struct x86_exception e;
8059         struct {
8060                 u64 vpid;
8061                 u64 gla;
8062         } operand;
8063
8064         if (!(vmx->nested.msrs.secondary_ctls_high &
8065               SECONDARY_EXEC_ENABLE_VPID) ||
8066                         !(vmx->nested.msrs.vpid_caps & VMX_VPID_INVVPID_BIT)) {
8067                 kvm_queue_exception(vcpu, UD_VECTOR);
8068                 return 1;
8069         }
8070
8071         if (!nested_vmx_check_permission(vcpu))
8072                 return 1;
8073
8074         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
8075         type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
8076
8077         types = (vmx->nested.msrs.vpid_caps &
8078                         VMX_VPID_EXTENT_SUPPORTED_MASK) >> 8;
8079
8080         if (type >= 32 || !(types & (1 << type))) {
8081                 nested_vmx_failValid(vcpu,
8082                         VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
8083                 return kvm_skip_emulated_instruction(vcpu);
8084         }
8085
8086         /* according to the intel vmx instruction reference, the memory
8087          * operand is read even if it isn't needed (e.g., for type==global)
8088          */
8089         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
8090                         vmx_instruction_info, false, &gva))
8091                 return 1;
8092         if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &operand,
8093                                 sizeof(operand), &e)) {
8094                 kvm_inject_page_fault(vcpu, &e);
8095                 return 1;
8096         }
8097         if (operand.vpid >> 16) {
8098                 nested_vmx_failValid(vcpu,
8099                         VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
8100                 return kvm_skip_emulated_instruction(vcpu);
8101         }
8102
8103         switch (type) {
8104         case VMX_VPID_EXTENT_INDIVIDUAL_ADDR:
8105                 if (is_noncanonical_address(operand.gla, vcpu)) {
8106                         nested_vmx_failValid(vcpu,
8107                                 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
8108                         return kvm_skip_emulated_instruction(vcpu);
8109                 }
8110                 /* fall through */
8111         case VMX_VPID_EXTENT_SINGLE_CONTEXT:
8112         case VMX_VPID_EXTENT_SINGLE_NON_GLOBAL:
8113                 if (!operand.vpid) {
8114                         nested_vmx_failValid(vcpu,
8115                                 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
8116                         return kvm_skip_emulated_instruction(vcpu);
8117                 }
8118                 break;
8119         case VMX_VPID_EXTENT_ALL_CONTEXT:
8120                 break;
8121         default:
8122                 WARN_ON_ONCE(1);
8123                 return kvm_skip_emulated_instruction(vcpu);
8124         }
8125
8126         __vmx_flush_tlb(vcpu, vmx->nested.vpid02, true);
8127         nested_vmx_succeed(vcpu);
8128
8129         return kvm_skip_emulated_instruction(vcpu);
8130 }
8131
8132 static int handle_pml_full(struct kvm_vcpu *vcpu)
8133 {
8134         unsigned long exit_qualification;
8135
8136         trace_kvm_pml_full(vcpu->vcpu_id);
8137
8138         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8139
8140         /*
8141          * PML buffer FULL happened while executing iret from NMI,
8142          * "blocked by NMI" bit has to be set before next VM entry.
8143          */
8144         if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
8145                         enable_vnmi &&
8146                         (exit_qualification & INTR_INFO_UNBLOCK_NMI))
8147                 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
8148                                 GUEST_INTR_STATE_NMI);
8149
8150         /*
8151          * PML buffer already flushed at beginning of VMEXIT. Nothing to do
8152          * here.., and there's no userspace involvement needed for PML.
8153          */
8154         return 1;
8155 }
8156
8157 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
8158 {
8159         kvm_lapic_expired_hv_timer(vcpu);
8160         return 1;
8161 }
8162
8163 static bool valid_ept_address(struct kvm_vcpu *vcpu, u64 address)
8164 {
8165         struct vcpu_vmx *vmx = to_vmx(vcpu);
8166         int maxphyaddr = cpuid_maxphyaddr(vcpu);
8167
8168         /* Check for memory type validity */
8169         switch (address & VMX_EPTP_MT_MASK) {
8170         case VMX_EPTP_MT_UC:
8171                 if (!(vmx->nested.msrs.ept_caps & VMX_EPTP_UC_BIT))
8172                         return false;
8173                 break;
8174         case VMX_EPTP_MT_WB:
8175                 if (!(vmx->nested.msrs.ept_caps & VMX_EPTP_WB_BIT))
8176                         return false;
8177                 break;
8178         default:
8179                 return false;
8180         }
8181
8182         /* only 4 levels page-walk length are valid */
8183         if ((address & VMX_EPTP_PWL_MASK) != VMX_EPTP_PWL_4)
8184                 return false;
8185
8186         /* Reserved bits should not be set */
8187         if (address >> maxphyaddr || ((address >> 7) & 0x1f))
8188                 return false;
8189
8190         /* AD, if set, should be supported */
8191         if (address & VMX_EPTP_AD_ENABLE_BIT) {
8192                 if (!(vmx->nested.msrs.ept_caps & VMX_EPT_AD_BIT))
8193                         return false;
8194         }
8195
8196         return true;
8197 }
8198
8199 static int nested_vmx_eptp_switching(struct kvm_vcpu *vcpu,
8200                                      struct vmcs12 *vmcs12)
8201 {
8202         u32 index = vcpu->arch.regs[VCPU_REGS_RCX];
8203         u64 address;
8204         bool accessed_dirty;
8205         struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
8206
8207         if (!nested_cpu_has_eptp_switching(vmcs12) ||
8208             !nested_cpu_has_ept(vmcs12))
8209                 return 1;
8210
8211         if (index >= VMFUNC_EPTP_ENTRIES)
8212                 return 1;
8213
8214
8215         if (kvm_vcpu_read_guest_page(vcpu, vmcs12->eptp_list_address >> PAGE_SHIFT,
8216                                      &address, index * 8, 8))
8217                 return 1;
8218
8219         accessed_dirty = !!(address & VMX_EPTP_AD_ENABLE_BIT);
8220
8221         /*
8222          * If the (L2) guest does a vmfunc to the currently
8223          * active ept pointer, we don't have to do anything else
8224          */
8225         if (vmcs12->ept_pointer != address) {
8226                 if (!valid_ept_address(vcpu, address))
8227                         return 1;
8228
8229                 kvm_mmu_unload(vcpu);
8230                 mmu->ept_ad = accessed_dirty;
8231                 mmu->base_role.ad_disabled = !accessed_dirty;
8232                 vmcs12->ept_pointer = address;
8233                 /*
8234                  * TODO: Check what's the correct approach in case
8235                  * mmu reload fails. Currently, we just let the next
8236                  * reload potentially fail
8237                  */
8238                 kvm_mmu_reload(vcpu);
8239         }
8240
8241         return 0;
8242 }
8243
8244 static int handle_vmfunc(struct kvm_vcpu *vcpu)
8245 {
8246         struct vcpu_vmx *vmx = to_vmx(vcpu);
8247         struct vmcs12 *vmcs12;
8248         u32 function = vcpu->arch.regs[VCPU_REGS_RAX];
8249
8250         /*
8251          * VMFUNC is only supported for nested guests, but we always enable the
8252          * secondary control for simplicity; for non-nested mode, fake that we
8253          * didn't by injecting #UD.
8254          */
8255         if (!is_guest_mode(vcpu)) {
8256                 kvm_queue_exception(vcpu, UD_VECTOR);
8257                 return 1;
8258         }
8259
8260         vmcs12 = get_vmcs12(vcpu);
8261         if ((vmcs12->vm_function_control & (1 << function)) == 0)
8262                 goto fail;
8263
8264         switch (function) {
8265         case 0:
8266                 if (nested_vmx_eptp_switching(vcpu, vmcs12))
8267                         goto fail;
8268                 break;
8269         default:
8270                 goto fail;
8271         }
8272         return kvm_skip_emulated_instruction(vcpu);
8273
8274 fail:
8275         nested_vmx_vmexit(vcpu, vmx->exit_reason,
8276                           vmcs_read32(VM_EXIT_INTR_INFO),
8277                           vmcs_readl(EXIT_QUALIFICATION));
8278         return 1;
8279 }
8280
8281 /*
8282  * The exit handlers return 1 if the exit was handled fully and guest execution
8283  * may resume.  Otherwise they set the kvm_run parameter to indicate what needs
8284  * to be done to userspace and return 0.
8285  */
8286 static int (*const kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
8287         [EXIT_REASON_EXCEPTION_NMI]           = handle_exception,
8288         [EXIT_REASON_EXTERNAL_INTERRUPT]      = handle_external_interrupt,
8289         [EXIT_REASON_TRIPLE_FAULT]            = handle_triple_fault,
8290         [EXIT_REASON_NMI_WINDOW]              = handle_nmi_window,
8291         [EXIT_REASON_IO_INSTRUCTION]          = handle_io,
8292         [EXIT_REASON_CR_ACCESS]               = handle_cr,
8293         [EXIT_REASON_DR_ACCESS]               = handle_dr,
8294         [EXIT_REASON_CPUID]                   = handle_cpuid,
8295         [EXIT_REASON_MSR_READ]                = handle_rdmsr,
8296         [EXIT_REASON_MSR_WRITE]               = handle_wrmsr,
8297         [EXIT_REASON_PENDING_INTERRUPT]       = handle_interrupt_window,
8298         [EXIT_REASON_HLT]                     = handle_halt,
8299         [EXIT_REASON_INVD]                    = handle_invd,
8300         [EXIT_REASON_INVLPG]                  = handle_invlpg,
8301         [EXIT_REASON_RDPMC]                   = handle_rdpmc,
8302         [EXIT_REASON_VMCALL]                  = handle_vmcall,
8303         [EXIT_REASON_VMCLEAR]                 = handle_vmclear,
8304         [EXIT_REASON_VMLAUNCH]                = handle_vmlaunch,
8305         [EXIT_REASON_VMPTRLD]                 = handle_vmptrld,
8306         [EXIT_REASON_VMPTRST]                 = handle_vmptrst,
8307         [EXIT_REASON_VMREAD]                  = handle_vmread,
8308         [EXIT_REASON_VMRESUME]                = handle_vmresume,
8309         [EXIT_REASON_VMWRITE]                 = handle_vmwrite,
8310         [EXIT_REASON_VMOFF]                   = handle_vmoff,
8311         [EXIT_REASON_VMON]                    = handle_vmon,
8312         [EXIT_REASON_TPR_BELOW_THRESHOLD]     = handle_tpr_below_threshold,
8313         [EXIT_REASON_APIC_ACCESS]             = handle_apic_access,
8314         [EXIT_REASON_APIC_WRITE]              = handle_apic_write,
8315         [EXIT_REASON_EOI_INDUCED]             = handle_apic_eoi_induced,
8316         [EXIT_REASON_WBINVD]                  = handle_wbinvd,
8317         [EXIT_REASON_XSETBV]                  = handle_xsetbv,
8318         [EXIT_REASON_TASK_SWITCH]             = handle_task_switch,
8319         [EXIT_REASON_MCE_DURING_VMENTRY]      = handle_machine_check,
8320         [EXIT_REASON_GDTR_IDTR]               = handle_desc,
8321         [EXIT_REASON_LDTR_TR]                 = handle_desc,
8322         [EXIT_REASON_EPT_VIOLATION]           = handle_ept_violation,
8323         [EXIT_REASON_EPT_MISCONFIG]           = handle_ept_misconfig,
8324         [EXIT_REASON_PAUSE_INSTRUCTION]       = handle_pause,
8325         [EXIT_REASON_MWAIT_INSTRUCTION]       = handle_mwait,
8326         [EXIT_REASON_MONITOR_TRAP_FLAG]       = handle_monitor_trap,
8327         [EXIT_REASON_MONITOR_INSTRUCTION]     = handle_monitor,
8328         [EXIT_REASON_INVEPT]                  = handle_invept,
8329         [EXIT_REASON_INVVPID]                 = handle_invvpid,
8330         [EXIT_REASON_RDRAND]                  = handle_invalid_op,
8331         [EXIT_REASON_RDSEED]                  = handle_invalid_op,
8332         [EXIT_REASON_XSAVES]                  = handle_xsaves,
8333         [EXIT_REASON_XRSTORS]                 = handle_xrstors,
8334         [EXIT_REASON_PML_FULL]                = handle_pml_full,
8335         [EXIT_REASON_VMFUNC]                  = handle_vmfunc,
8336         [EXIT_REASON_PREEMPTION_TIMER]        = handle_preemption_timer,
8337 };
8338
8339 static const int kvm_vmx_max_exit_handlers =
8340         ARRAY_SIZE(kvm_vmx_exit_handlers);
8341
8342 static bool nested_vmx_exit_handled_io(struct kvm_vcpu *vcpu,
8343                                        struct vmcs12 *vmcs12)
8344 {
8345         unsigned long exit_qualification;
8346         gpa_t bitmap, last_bitmap;
8347         unsigned int port;
8348         int size;
8349         u8 b;
8350
8351         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
8352                 return nested_cpu_has(vmcs12, CPU_BASED_UNCOND_IO_EXITING);
8353
8354         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8355
8356         port = exit_qualification >> 16;
8357         size = (exit_qualification & 7) + 1;
8358
8359         last_bitmap = (gpa_t)-1;
8360         b = -1;
8361
8362         while (size > 0) {
8363                 if (port < 0x8000)
8364                         bitmap = vmcs12->io_bitmap_a;
8365                 else if (port < 0x10000)
8366                         bitmap = vmcs12->io_bitmap_b;
8367                 else
8368                         return true;
8369                 bitmap += (port & 0x7fff) / 8;
8370
8371                 if (last_bitmap != bitmap)
8372                         if (kvm_vcpu_read_guest(vcpu, bitmap, &b, 1))
8373                                 return true;
8374                 if (b & (1 << (port & 7)))
8375                         return true;
8376
8377                 port++;
8378                 size--;
8379                 last_bitmap = bitmap;
8380         }
8381
8382         return false;
8383 }
8384
8385 /*
8386  * Return 1 if we should exit from L2 to L1 to handle an MSR access access,
8387  * rather than handle it ourselves in L0. I.e., check whether L1 expressed
8388  * disinterest in the current event (read or write a specific MSR) by using an
8389  * MSR bitmap. This may be the case even when L0 doesn't use MSR bitmaps.
8390  */
8391 static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu,
8392         struct vmcs12 *vmcs12, u32 exit_reason)
8393 {
8394         u32 msr_index = vcpu->arch.regs[VCPU_REGS_RCX];
8395         gpa_t bitmap;
8396
8397         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
8398                 return true;
8399
8400         /*
8401          * The MSR_BITMAP page is divided into four 1024-byte bitmaps,
8402          * for the four combinations of read/write and low/high MSR numbers.
8403          * First we need to figure out which of the four to use:
8404          */
8405         bitmap = vmcs12->msr_bitmap;
8406         if (exit_reason == EXIT_REASON_MSR_WRITE)
8407                 bitmap += 2048;
8408         if (msr_index >= 0xc0000000) {
8409                 msr_index -= 0xc0000000;
8410                 bitmap += 1024;
8411         }
8412
8413         /* Then read the msr_index'th bit from this bitmap: */
8414         if (msr_index < 1024*8) {
8415                 unsigned char b;
8416                 if (kvm_vcpu_read_guest(vcpu, bitmap + msr_index/8, &b, 1))
8417                         return true;
8418                 return 1 & (b >> (msr_index & 7));
8419         } else
8420                 return true; /* let L1 handle the wrong parameter */
8421 }
8422
8423 /*
8424  * Return 1 if we should exit from L2 to L1 to handle a CR access exit,
8425  * rather than handle it ourselves in L0. I.e., check if L1 wanted to
8426  * intercept (via guest_host_mask etc.) the current event.
8427  */
8428 static bool nested_vmx_exit_handled_cr(struct kvm_vcpu *vcpu,
8429         struct vmcs12 *vmcs12)
8430 {
8431         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8432         int cr = exit_qualification & 15;
8433         int reg;
8434         unsigned long val;
8435
8436         switch ((exit_qualification >> 4) & 3) {
8437         case 0: /* mov to cr */
8438                 reg = (exit_qualification >> 8) & 15;
8439                 val = kvm_register_readl(vcpu, reg);
8440                 switch (cr) {
8441                 case 0:
8442                         if (vmcs12->cr0_guest_host_mask &
8443                             (val ^ vmcs12->cr0_read_shadow))
8444                                 return true;
8445                         break;
8446                 case 3:
8447                         if ((vmcs12->cr3_target_count >= 1 &&
8448                                         vmcs12->cr3_target_value0 == val) ||
8449                                 (vmcs12->cr3_target_count >= 2 &&
8450                                         vmcs12->cr3_target_value1 == val) ||
8451                                 (vmcs12->cr3_target_count >= 3 &&
8452                                         vmcs12->cr3_target_value2 == val) ||
8453                                 (vmcs12->cr3_target_count >= 4 &&
8454                                         vmcs12->cr3_target_value3 == val))
8455                                 return false;
8456                         if (nested_cpu_has(vmcs12, CPU_BASED_CR3_LOAD_EXITING))
8457                                 return true;
8458                         break;
8459                 case 4:
8460                         if (vmcs12->cr4_guest_host_mask &
8461                             (vmcs12->cr4_read_shadow ^ val))
8462                                 return true;
8463                         break;
8464                 case 8:
8465                         if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING))
8466                                 return true;
8467                         break;
8468                 }
8469                 break;
8470         case 2: /* clts */
8471                 if ((vmcs12->cr0_guest_host_mask & X86_CR0_TS) &&
8472                     (vmcs12->cr0_read_shadow & X86_CR0_TS))
8473                         return true;
8474                 break;
8475         case 1: /* mov from cr */
8476                 switch (cr) {
8477                 case 3:
8478                         if (vmcs12->cpu_based_vm_exec_control &
8479                             CPU_BASED_CR3_STORE_EXITING)
8480                                 return true;
8481                         break;
8482                 case 8:
8483                         if (vmcs12->cpu_based_vm_exec_control &
8484                             CPU_BASED_CR8_STORE_EXITING)
8485                                 return true;
8486                         break;
8487                 }
8488                 break;
8489         case 3: /* lmsw */
8490                 /*
8491                  * lmsw can change bits 1..3 of cr0, and only set bit 0 of
8492                  * cr0. Other attempted changes are ignored, with no exit.
8493                  */
8494                 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
8495                 if (vmcs12->cr0_guest_host_mask & 0xe &
8496                     (val ^ vmcs12->cr0_read_shadow))
8497                         return true;
8498                 if ((vmcs12->cr0_guest_host_mask & 0x1) &&
8499                     !(vmcs12->cr0_read_shadow & 0x1) &&
8500                     (val & 0x1))
8501                         return true;
8502                 break;
8503         }
8504         return false;
8505 }
8506
8507 /*
8508  * Return 1 if we should exit from L2 to L1 to handle an exit, or 0 if we
8509  * should handle it ourselves in L0 (and then continue L2). Only call this
8510  * when in is_guest_mode (L2).
8511  */
8512 static bool nested_vmx_exit_reflected(struct kvm_vcpu *vcpu, u32 exit_reason)
8513 {
8514         u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
8515         struct vcpu_vmx *vmx = to_vmx(vcpu);
8516         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
8517
8518         if (vmx->nested.nested_run_pending)
8519                 return false;
8520
8521         if (unlikely(vmx->fail)) {
8522                 pr_info_ratelimited("%s failed vm entry %x\n", __func__,
8523                                     vmcs_read32(VM_INSTRUCTION_ERROR));
8524                 return true;
8525         }
8526
8527         /*
8528          * The host physical addresses of some pages of guest memory
8529          * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC
8530          * Page). The CPU may write to these pages via their host
8531          * physical address while L2 is running, bypassing any
8532          * address-translation-based dirty tracking (e.g. EPT write
8533          * protection).
8534          *
8535          * Mark them dirty on every exit from L2 to prevent them from
8536          * getting out of sync with dirty tracking.
8537          */
8538         nested_mark_vmcs12_pages_dirty(vcpu);
8539
8540         trace_kvm_nested_vmexit(kvm_rip_read(vcpu), exit_reason,
8541                                 vmcs_readl(EXIT_QUALIFICATION),
8542                                 vmx->idt_vectoring_info,
8543                                 intr_info,
8544                                 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
8545                                 KVM_ISA_VMX);
8546
8547         switch (exit_reason) {
8548         case EXIT_REASON_EXCEPTION_NMI:
8549                 if (is_nmi(intr_info))
8550                         return false;
8551                 else if (is_page_fault(intr_info))
8552                         return !vmx->vcpu.arch.apf.host_apf_reason && enable_ept;
8553                 else if (is_no_device(intr_info) &&
8554                          !(vmcs12->guest_cr0 & X86_CR0_TS))
8555                         return false;
8556                 else if (is_debug(intr_info) &&
8557                          vcpu->guest_debug &
8558                          (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
8559                         return false;
8560                 else if (is_breakpoint(intr_info) &&
8561                          vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
8562                         return false;
8563                 return vmcs12->exception_bitmap &
8564                                 (1u << (intr_info & INTR_INFO_VECTOR_MASK));
8565         case EXIT_REASON_EXTERNAL_INTERRUPT:
8566                 return false;
8567         case EXIT_REASON_TRIPLE_FAULT:
8568                 return true;
8569         case EXIT_REASON_PENDING_INTERRUPT:
8570                 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_INTR_PENDING);
8571         case EXIT_REASON_NMI_WINDOW:
8572                 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING);
8573         case EXIT_REASON_TASK_SWITCH:
8574                 return true;
8575         case EXIT_REASON_CPUID:
8576                 return true;
8577         case EXIT_REASON_HLT:
8578                 return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
8579         case EXIT_REASON_INVD:
8580                 return true;
8581         case EXIT_REASON_INVLPG:
8582                 return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
8583         case EXIT_REASON_RDPMC:
8584                 return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
8585         case EXIT_REASON_RDRAND:
8586                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDRAND_EXITING);
8587         case EXIT_REASON_RDSEED:
8588                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDSEED_EXITING);
8589         case EXIT_REASON_RDTSC: case EXIT_REASON_RDTSCP:
8590                 return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
8591         case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
8592         case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
8593         case EXIT_REASON_VMPTRST: case EXIT_REASON_VMREAD:
8594         case EXIT_REASON_VMRESUME: case EXIT_REASON_VMWRITE:
8595         case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
8596         case EXIT_REASON_INVEPT: case EXIT_REASON_INVVPID:
8597                 /*
8598                  * VMX instructions trap unconditionally. This allows L1 to
8599                  * emulate them for its L2 guest, i.e., allows 3-level nesting!
8600                  */
8601                 return true;
8602         case EXIT_REASON_CR_ACCESS:
8603                 return nested_vmx_exit_handled_cr(vcpu, vmcs12);
8604         case EXIT_REASON_DR_ACCESS:
8605                 return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
8606         case EXIT_REASON_IO_INSTRUCTION:
8607                 return nested_vmx_exit_handled_io(vcpu, vmcs12);
8608         case EXIT_REASON_GDTR_IDTR: case EXIT_REASON_LDTR_TR:
8609                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC);
8610         case EXIT_REASON_MSR_READ:
8611         case EXIT_REASON_MSR_WRITE:
8612                 return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
8613         case EXIT_REASON_INVALID_STATE:
8614                 return true;
8615         case EXIT_REASON_MWAIT_INSTRUCTION:
8616                 return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
8617         case EXIT_REASON_MONITOR_TRAP_FLAG:
8618                 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_TRAP_FLAG);
8619         case EXIT_REASON_MONITOR_INSTRUCTION:
8620                 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
8621         case EXIT_REASON_PAUSE_INSTRUCTION:
8622                 return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
8623                         nested_cpu_has2(vmcs12,
8624                                 SECONDARY_EXEC_PAUSE_LOOP_EXITING);
8625         case EXIT_REASON_MCE_DURING_VMENTRY:
8626                 return false;
8627         case EXIT_REASON_TPR_BELOW_THRESHOLD:
8628                 return nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW);
8629         case EXIT_REASON_APIC_ACCESS:
8630                 return nested_cpu_has2(vmcs12,
8631                         SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
8632         case EXIT_REASON_APIC_WRITE:
8633         case EXIT_REASON_EOI_INDUCED:
8634                 /* apic_write and eoi_induced should exit unconditionally. */
8635                 return true;
8636         case EXIT_REASON_EPT_VIOLATION:
8637                 /*
8638                  * L0 always deals with the EPT violation. If nested EPT is
8639                  * used, and the nested mmu code discovers that the address is
8640                  * missing in the guest EPT table (EPT12), the EPT violation
8641                  * will be injected with nested_ept_inject_page_fault()
8642                  */
8643                 return false;
8644         case EXIT_REASON_EPT_MISCONFIG:
8645                 /*
8646                  * L2 never uses directly L1's EPT, but rather L0's own EPT
8647                  * table (shadow on EPT) or a merged EPT table that L0 built
8648                  * (EPT on EPT). So any problems with the structure of the
8649                  * table is L0's fault.
8650                  */
8651                 return false;
8652         case EXIT_REASON_INVPCID:
8653                 return
8654                         nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_INVPCID) &&
8655                         nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
8656         case EXIT_REASON_WBINVD:
8657                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
8658         case EXIT_REASON_XSETBV:
8659                 return true;
8660         case EXIT_REASON_XSAVES: case EXIT_REASON_XRSTORS:
8661                 /*
8662                  * This should never happen, since it is not possible to
8663                  * set XSS to a non-zero value---neither in L1 nor in L2.
8664                  * If if it were, XSS would have to be checked against
8665                  * the XSS exit bitmap in vmcs12.
8666                  */
8667                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
8668         case EXIT_REASON_PREEMPTION_TIMER:
8669                 return false;
8670         case EXIT_REASON_PML_FULL:
8671                 /* We emulate PML support to L1. */
8672                 return false;
8673         case EXIT_REASON_VMFUNC:
8674                 /* VM functions are emulated through L2->L0 vmexits. */
8675                 return false;
8676         default:
8677                 return true;
8678         }
8679 }
8680
8681 static int nested_vmx_reflect_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason)
8682 {
8683         u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
8684
8685         /*
8686          * At this point, the exit interruption info in exit_intr_info
8687          * is only valid for EXCEPTION_NMI exits.  For EXTERNAL_INTERRUPT
8688          * we need to query the in-kernel LAPIC.
8689          */
8690         WARN_ON(exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT);
8691         if ((exit_intr_info &
8692              (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) ==
8693             (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) {
8694                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
8695                 vmcs12->vm_exit_intr_error_code =
8696                         vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
8697         }
8698
8699         nested_vmx_vmexit(vcpu, exit_reason, exit_intr_info,
8700                           vmcs_readl(EXIT_QUALIFICATION));
8701         return 1;
8702 }
8703
8704 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
8705 {
8706         *info1 = vmcs_readl(EXIT_QUALIFICATION);
8707         *info2 = vmcs_read32(VM_EXIT_INTR_INFO);
8708 }
8709
8710 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
8711 {
8712         if (vmx->pml_pg) {
8713                 __free_page(vmx->pml_pg);
8714                 vmx->pml_pg = NULL;
8715         }
8716 }
8717
8718 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
8719 {
8720         struct vcpu_vmx *vmx = to_vmx(vcpu);
8721         u64 *pml_buf;
8722         u16 pml_idx;
8723
8724         pml_idx = vmcs_read16(GUEST_PML_INDEX);
8725
8726         /* Do nothing if PML buffer is empty */
8727         if (pml_idx == (PML_ENTITY_NUM - 1))
8728                 return;
8729
8730         /* PML index always points to next available PML buffer entity */
8731         if (pml_idx >= PML_ENTITY_NUM)
8732                 pml_idx = 0;
8733         else
8734                 pml_idx++;
8735
8736         pml_buf = page_address(vmx->pml_pg);
8737         for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
8738                 u64 gpa;
8739
8740                 gpa = pml_buf[pml_idx];
8741                 WARN_ON(gpa & (PAGE_SIZE - 1));
8742                 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
8743         }
8744
8745         /* reset PML index */
8746         vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
8747 }
8748
8749 /*
8750  * Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
8751  * Called before reporting dirty_bitmap to userspace.
8752  */
8753 static void kvm_flush_pml_buffers(struct kvm *kvm)
8754 {
8755         int i;
8756         struct kvm_vcpu *vcpu;
8757         /*
8758          * We only need to kick vcpu out of guest mode here, as PML buffer
8759          * is flushed at beginning of all VMEXITs, and it's obvious that only
8760          * vcpus running in guest are possible to have unflushed GPAs in PML
8761          * buffer.
8762          */
8763         kvm_for_each_vcpu(i, vcpu, kvm)
8764                 kvm_vcpu_kick(vcpu);
8765 }
8766
8767 static void vmx_dump_sel(char *name, uint32_t sel)
8768 {
8769         pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
8770                name, vmcs_read16(sel),
8771                vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
8772                vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
8773                vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
8774 }
8775
8776 static void vmx_dump_dtsel(char *name, uint32_t limit)
8777 {
8778         pr_err("%s                           limit=0x%08x, base=0x%016lx\n",
8779                name, vmcs_read32(limit),
8780                vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
8781 }
8782
8783 static void dump_vmcs(void)
8784 {
8785         u32 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
8786         u32 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
8787         u32 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
8788         u32 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
8789         u32 secondary_exec_control = 0;
8790         unsigned long cr4 = vmcs_readl(GUEST_CR4);
8791         u64 efer = vmcs_read64(GUEST_IA32_EFER);
8792         int i, n;
8793
8794         if (cpu_has_secondary_exec_ctrls())
8795                 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
8796
8797         pr_err("*** Guest State ***\n");
8798         pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
8799                vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
8800                vmcs_readl(CR0_GUEST_HOST_MASK));
8801         pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
8802                cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
8803         pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
8804         if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
8805             (cr4 & X86_CR4_PAE) && !(efer & EFER_LMA))
8806         {
8807                 pr_err("PDPTR0 = 0x%016llx  PDPTR1 = 0x%016llx\n",
8808                        vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
8809                 pr_err("PDPTR2 = 0x%016llx  PDPTR3 = 0x%016llx\n",
8810                        vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
8811         }
8812         pr_err("RSP = 0x%016lx  RIP = 0x%016lx\n",
8813                vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
8814         pr_err("RFLAGS=0x%08lx         DR7 = 0x%016lx\n",
8815                vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
8816         pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
8817                vmcs_readl(GUEST_SYSENTER_ESP),
8818                vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
8819         vmx_dump_sel("CS:  ", GUEST_CS_SELECTOR);
8820         vmx_dump_sel("DS:  ", GUEST_DS_SELECTOR);
8821         vmx_dump_sel("SS:  ", GUEST_SS_SELECTOR);
8822         vmx_dump_sel("ES:  ", GUEST_ES_SELECTOR);
8823         vmx_dump_sel("FS:  ", GUEST_FS_SELECTOR);
8824         vmx_dump_sel("GS:  ", GUEST_GS_SELECTOR);
8825         vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
8826         vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
8827         vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
8828         vmx_dump_sel("TR:  ", GUEST_TR_SELECTOR);
8829         if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
8830             (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
8831                 pr_err("EFER =     0x%016llx  PAT = 0x%016llx\n",
8832                        efer, vmcs_read64(GUEST_IA32_PAT));
8833         pr_err("DebugCtl = 0x%016llx  DebugExceptions = 0x%016lx\n",
8834                vmcs_read64(GUEST_IA32_DEBUGCTL),
8835                vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
8836         if (vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
8837                 pr_err("PerfGlobCtl = 0x%016llx\n",
8838                        vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
8839         if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
8840                 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
8841         pr_err("Interruptibility = %08x  ActivityState = %08x\n",
8842                vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
8843                vmcs_read32(GUEST_ACTIVITY_STATE));
8844         if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
8845                 pr_err("InterruptStatus = %04x\n",
8846                        vmcs_read16(GUEST_INTR_STATUS));
8847
8848         pr_err("*** Host State ***\n");
8849         pr_err("RIP = 0x%016lx  RSP = 0x%016lx\n",
8850                vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
8851         pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
8852                vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
8853                vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
8854                vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
8855                vmcs_read16(HOST_TR_SELECTOR));
8856         pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
8857                vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
8858                vmcs_readl(HOST_TR_BASE));
8859         pr_err("GDTBase=%016lx IDTBase=%016lx\n",
8860                vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
8861         pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
8862                vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
8863                vmcs_readl(HOST_CR4));
8864         pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
8865                vmcs_readl(HOST_IA32_SYSENTER_ESP),
8866                vmcs_read32(HOST_IA32_SYSENTER_CS),
8867                vmcs_readl(HOST_IA32_SYSENTER_EIP));
8868         if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
8869                 pr_err("EFER = 0x%016llx  PAT = 0x%016llx\n",
8870                        vmcs_read64(HOST_IA32_EFER),
8871                        vmcs_read64(HOST_IA32_PAT));
8872         if (vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
8873                 pr_err("PerfGlobCtl = 0x%016llx\n",
8874                        vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
8875
8876         pr_err("*** Control State ***\n");
8877         pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
8878                pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
8879         pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
8880         pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
8881                vmcs_read32(EXCEPTION_BITMAP),
8882                vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
8883                vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
8884         pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
8885                vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
8886                vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
8887                vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
8888         pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
8889                vmcs_read32(VM_EXIT_INTR_INFO),
8890                vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
8891                vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
8892         pr_err("        reason=%08x qualification=%016lx\n",
8893                vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
8894         pr_err("IDTVectoring: info=%08x errcode=%08x\n",
8895                vmcs_read32(IDT_VECTORING_INFO_FIELD),
8896                vmcs_read32(IDT_VECTORING_ERROR_CODE));
8897         pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
8898         if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
8899                 pr_err("TSC Multiplier = 0x%016llx\n",
8900                        vmcs_read64(TSC_MULTIPLIER));
8901         if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW)
8902                 pr_err("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
8903         if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
8904                 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
8905         if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
8906                 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
8907         n = vmcs_read32(CR3_TARGET_COUNT);
8908         for (i = 0; i + 1 < n; i += 4)
8909                 pr_err("CR3 target%u=%016lx target%u=%016lx\n",
8910                        i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2),
8911                        i + 1, vmcs_readl(CR3_TARGET_VALUE0 + i * 2 + 2));
8912         if (i < n)
8913                 pr_err("CR3 target%u=%016lx\n",
8914                        i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2));
8915         if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
8916                 pr_err("PLE Gap=%08x Window=%08x\n",
8917                        vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
8918         if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
8919                 pr_err("Virtual processor ID = 0x%04x\n",
8920                        vmcs_read16(VIRTUAL_PROCESSOR_ID));
8921 }
8922
8923 /*
8924  * The guest has exited.  See if we can fix it or if we need userspace
8925  * assistance.
8926  */
8927 static int vmx_handle_exit(struct kvm_vcpu *vcpu)
8928 {
8929         struct vcpu_vmx *vmx = to_vmx(vcpu);
8930         u32 exit_reason = vmx->exit_reason;
8931         u32 vectoring_info = vmx->idt_vectoring_info;
8932
8933         trace_kvm_exit(exit_reason, vcpu, KVM_ISA_VMX);
8934
8935         /*
8936          * Flush logged GPAs PML buffer, this will make dirty_bitmap more
8937          * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
8938          * querying dirty_bitmap, we only need to kick all vcpus out of guest
8939          * mode as if vcpus is in root mode, the PML buffer must has been
8940          * flushed already.
8941          */
8942         if (enable_pml)
8943                 vmx_flush_pml_buffer(vcpu);
8944
8945         /* If guest state is invalid, start emulating */
8946         if (vmx->emulation_required)
8947                 return handle_invalid_guest_state(vcpu);
8948
8949         if (is_guest_mode(vcpu) && nested_vmx_exit_reflected(vcpu, exit_reason))
8950                 return nested_vmx_reflect_vmexit(vcpu, exit_reason);
8951
8952         if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
8953                 dump_vmcs();
8954                 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
8955                 vcpu->run->fail_entry.hardware_entry_failure_reason
8956                         = exit_reason;
8957                 return 0;
8958         }
8959
8960         if (unlikely(vmx->fail)) {
8961                 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
8962                 vcpu->run->fail_entry.hardware_entry_failure_reason
8963                         = vmcs_read32(VM_INSTRUCTION_ERROR);
8964                 return 0;
8965         }
8966
8967         /*
8968          * Note:
8969          * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
8970          * delivery event since it indicates guest is accessing MMIO.
8971          * The vm-exit can be triggered again after return to guest that
8972          * will cause infinite loop.
8973          */
8974         if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
8975                         (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
8976                         exit_reason != EXIT_REASON_EPT_VIOLATION &&
8977                         exit_reason != EXIT_REASON_PML_FULL &&
8978                         exit_reason != EXIT_REASON_TASK_SWITCH)) {
8979                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
8980                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
8981                 vcpu->run->internal.ndata = 3;
8982                 vcpu->run->internal.data[0] = vectoring_info;
8983                 vcpu->run->internal.data[1] = exit_reason;
8984                 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
8985                 if (exit_reason == EXIT_REASON_EPT_MISCONFIG) {
8986                         vcpu->run->internal.ndata++;
8987                         vcpu->run->internal.data[3] =
8988                                 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
8989                 }
8990                 return 0;
8991         }
8992
8993         if (unlikely(!enable_vnmi &&
8994                      vmx->loaded_vmcs->soft_vnmi_blocked)) {
8995                 if (vmx_interrupt_allowed(vcpu)) {
8996                         vmx->loaded_vmcs->soft_vnmi_blocked = 0;
8997                 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
8998                            vcpu->arch.nmi_pending) {
8999                         /*
9000                          * This CPU don't support us in finding the end of an
9001                          * NMI-blocked window if the guest runs with IRQs
9002                          * disabled. So we pull the trigger after 1 s of
9003                          * futile waiting, but inform the user about this.
9004                          */
9005                         printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
9006                                "state on VCPU %d after 1 s timeout\n",
9007                                __func__, vcpu->vcpu_id);
9008                         vmx->loaded_vmcs->soft_vnmi_blocked = 0;
9009                 }
9010         }
9011
9012         if (exit_reason < kvm_vmx_max_exit_handlers
9013             && kvm_vmx_exit_handlers[exit_reason])
9014                 return kvm_vmx_exit_handlers[exit_reason](vcpu);
9015         else {
9016                 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
9017                                 exit_reason);
9018                 kvm_queue_exception(vcpu, UD_VECTOR);
9019                 return 1;
9020         }
9021 }
9022
9023 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
9024 {
9025         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
9026
9027         if (is_guest_mode(vcpu) &&
9028                 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
9029                 return;
9030
9031         if (irr == -1 || tpr < irr) {
9032                 vmcs_write32(TPR_THRESHOLD, 0);
9033                 return;
9034         }
9035
9036         vmcs_write32(TPR_THRESHOLD, irr);
9037 }
9038
9039 static void vmx_set_virtual_x2apic_mode(struct kvm_vcpu *vcpu, bool set)
9040 {
9041         u32 sec_exec_control;
9042
9043         /* Postpone execution until vmcs01 is the current VMCS. */
9044         if (is_guest_mode(vcpu)) {
9045                 to_vmx(vcpu)->nested.change_vmcs01_virtual_x2apic_mode = true;
9046                 return;
9047         }
9048
9049         if (!cpu_has_vmx_virtualize_x2apic_mode())
9050                 return;
9051
9052         if (!cpu_need_tpr_shadow(vcpu))
9053                 return;
9054
9055         sec_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
9056
9057         if (set) {
9058                 sec_exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
9059                 sec_exec_control |= SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
9060         } else {
9061                 sec_exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
9062                 sec_exec_control |= SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
9063                 vmx_flush_tlb_ept_only(vcpu);
9064         }
9065         vmcs_write32(SECONDARY_VM_EXEC_CONTROL, sec_exec_control);
9066
9067         vmx_update_msr_bitmap(vcpu);
9068 }
9069
9070 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu, hpa_t hpa)
9071 {
9072         struct vcpu_vmx *vmx = to_vmx(vcpu);
9073
9074         /*
9075          * Currently we do not handle the nested case where L2 has an
9076          * APIC access page of its own; that page is still pinned.
9077          * Hence, we skip the case where the VCPU is in guest mode _and_
9078          * L1 prepared an APIC access page for L2.
9079          *
9080          * For the case where L1 and L2 share the same APIC access page
9081          * (flexpriority=Y but SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES clear
9082          * in the vmcs12), this function will only update either the vmcs01
9083          * or the vmcs02.  If the former, the vmcs02 will be updated by
9084          * prepare_vmcs02.  If the latter, the vmcs01 will be updated in
9085          * the next L2->L1 exit.
9086          */
9087         if (!is_guest_mode(vcpu) ||
9088             !nested_cpu_has2(get_vmcs12(&vmx->vcpu),
9089                              SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
9090                 vmcs_write64(APIC_ACCESS_ADDR, hpa);
9091                 vmx_flush_tlb_ept_only(vcpu);
9092         }
9093 }
9094
9095 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
9096 {
9097         u16 status;
9098         u8 old;
9099
9100         if (max_isr == -1)
9101                 max_isr = 0;
9102
9103         status = vmcs_read16(GUEST_INTR_STATUS);
9104         old = status >> 8;
9105         if (max_isr != old) {
9106                 status &= 0xff;
9107                 status |= max_isr << 8;
9108                 vmcs_write16(GUEST_INTR_STATUS, status);
9109         }
9110 }
9111
9112 static void vmx_set_rvi(int vector)
9113 {
9114         u16 status;
9115         u8 old;
9116
9117         if (vector == -1)
9118                 vector = 0;
9119
9120         status = vmcs_read16(GUEST_INTR_STATUS);
9121         old = (u8)status & 0xff;
9122         if ((u8)vector != old) {
9123                 status &= ~0xff;
9124                 status |= (u8)vector;
9125                 vmcs_write16(GUEST_INTR_STATUS, status);
9126         }
9127 }
9128
9129 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
9130 {
9131         /*
9132          * When running L2, updating RVI is only relevant when
9133          * vmcs12 virtual-interrupt-delivery enabled.
9134          * However, it can be enabled only when L1 also
9135          * intercepts external-interrupts and in that case
9136          * we should not update vmcs02 RVI but instead intercept
9137          * interrupt. Therefore, do nothing when running L2.
9138          */
9139         if (!is_guest_mode(vcpu))
9140                 vmx_set_rvi(max_irr);
9141 }
9142
9143 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
9144 {
9145         struct vcpu_vmx *vmx = to_vmx(vcpu);
9146         int max_irr;
9147         bool max_irr_updated;
9148
9149         WARN_ON(!vcpu->arch.apicv_active);
9150         if (pi_test_on(&vmx->pi_desc)) {
9151                 pi_clear_on(&vmx->pi_desc);
9152                 /*
9153                  * IOMMU can write to PIR.ON, so the barrier matters even on UP.
9154                  * But on x86 this is just a compiler barrier anyway.
9155                  */
9156                 smp_mb__after_atomic();
9157                 max_irr_updated =
9158                         kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
9159
9160                 /*
9161                  * If we are running L2 and L1 has a new pending interrupt
9162                  * which can be injected, we should re-evaluate
9163                  * what should be done with this new L1 interrupt.
9164                  * If L1 intercepts external-interrupts, we should
9165                  * exit from L2 to L1. Otherwise, interrupt should be
9166                  * delivered directly to L2.
9167                  */
9168                 if (is_guest_mode(vcpu) && max_irr_updated) {
9169                         if (nested_exit_on_intr(vcpu))
9170                                 kvm_vcpu_exiting_guest_mode(vcpu);
9171                         else
9172                                 kvm_make_request(KVM_REQ_EVENT, vcpu);
9173                 }
9174         } else {
9175                 max_irr = kvm_lapic_find_highest_irr(vcpu);
9176         }
9177         vmx_hwapic_irr_update(vcpu, max_irr);
9178         return max_irr;
9179 }
9180
9181 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
9182 {
9183         if (!kvm_vcpu_apicv_active(vcpu))
9184                 return;
9185
9186         vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
9187         vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
9188         vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
9189         vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
9190 }
9191
9192 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
9193 {
9194         struct vcpu_vmx *vmx = to_vmx(vcpu);
9195
9196         pi_clear_on(&vmx->pi_desc);
9197         memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
9198 }
9199
9200 static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
9201 {
9202         u32 exit_intr_info = 0;
9203         u16 basic_exit_reason = (u16)vmx->exit_reason;
9204
9205         if (!(basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
9206               || basic_exit_reason == EXIT_REASON_EXCEPTION_NMI))
9207                 return;
9208
9209         if (!(vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
9210                 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
9211         vmx->exit_intr_info = exit_intr_info;
9212
9213         /* if exit due to PF check for async PF */
9214         if (is_page_fault(exit_intr_info))
9215                 vmx->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
9216
9217         /* Handle machine checks before interrupts are enabled */
9218         if (basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY ||
9219             is_machine_check(exit_intr_info))
9220                 kvm_machine_check();
9221
9222         /* We need to handle NMIs before interrupts are enabled */
9223         if (is_nmi(exit_intr_info)) {
9224                 kvm_before_handle_nmi(&vmx->vcpu);
9225                 asm("int $2");
9226                 kvm_after_handle_nmi(&vmx->vcpu);
9227         }
9228 }
9229
9230 static void vmx_handle_external_intr(struct kvm_vcpu *vcpu)
9231 {
9232         u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
9233
9234         if ((exit_intr_info & (INTR_INFO_VALID_MASK | INTR_INFO_INTR_TYPE_MASK))
9235                         == (INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR)) {
9236                 unsigned int vector;
9237                 unsigned long entry;
9238                 gate_desc *desc;
9239                 struct vcpu_vmx *vmx = to_vmx(vcpu);
9240 #ifdef CONFIG_X86_64
9241                 unsigned long tmp;
9242 #endif
9243
9244                 vector =  exit_intr_info & INTR_INFO_VECTOR_MASK;
9245                 desc = (gate_desc *)vmx->host_idt_base + vector;
9246                 entry = gate_offset(desc);
9247                 asm volatile(
9248 #ifdef CONFIG_X86_64
9249                         "mov %%" _ASM_SP ", %[sp]\n\t"
9250                         "and $0xfffffffffffffff0, %%" _ASM_SP "\n\t"
9251                         "push $%c[ss]\n\t"
9252                         "push %[sp]\n\t"
9253 #endif
9254                         "pushf\n\t"
9255                         __ASM_SIZE(push) " $%c[cs]\n\t"
9256                         CALL_NOSPEC
9257                         :
9258 #ifdef CONFIG_X86_64
9259                         [sp]"=&r"(tmp),
9260 #endif
9261                         ASM_CALL_CONSTRAINT
9262                         :
9263                         THUNK_TARGET(entry),
9264                         [ss]"i"(__KERNEL_DS),
9265                         [cs]"i"(__KERNEL_CS)
9266                         );
9267         }
9268 }
9269 STACK_FRAME_NON_STANDARD(vmx_handle_external_intr);
9270
9271 static bool vmx_has_high_real_mode_segbase(void)
9272 {
9273         return enable_unrestricted_guest || emulate_invalid_guest_state;
9274 }
9275
9276 static bool vmx_mpx_supported(void)
9277 {
9278         return (vmcs_config.vmexit_ctrl & VM_EXIT_CLEAR_BNDCFGS) &&
9279                 (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_BNDCFGS);
9280 }
9281
9282 static bool vmx_xsaves_supported(void)
9283 {
9284         return vmcs_config.cpu_based_2nd_exec_ctrl &
9285                 SECONDARY_EXEC_XSAVES;
9286 }
9287
9288 static bool vmx_umip_emulated(void)
9289 {
9290         return vmcs_config.cpu_based_2nd_exec_ctrl &
9291                 SECONDARY_EXEC_DESC;
9292 }
9293
9294 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
9295 {
9296         u32 exit_intr_info;
9297         bool unblock_nmi;
9298         u8 vector;
9299         bool idtv_info_valid;
9300
9301         idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
9302
9303         if (enable_vnmi) {
9304                 if (vmx->loaded_vmcs->nmi_known_unmasked)
9305                         return;
9306                 /*
9307                  * Can't use vmx->exit_intr_info since we're not sure what
9308                  * the exit reason is.
9309                  */
9310                 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
9311                 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
9312                 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
9313                 /*
9314                  * SDM 3: 27.7.1.2 (September 2008)
9315                  * Re-set bit "block by NMI" before VM entry if vmexit caused by
9316                  * a guest IRET fault.
9317                  * SDM 3: 23.2.2 (September 2008)
9318                  * Bit 12 is undefined in any of the following cases:
9319                  *  If the VM exit sets the valid bit in the IDT-vectoring
9320                  *   information field.
9321                  *  If the VM exit is due to a double fault.
9322                  */
9323                 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
9324                     vector != DF_VECTOR && !idtv_info_valid)
9325                         vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
9326                                       GUEST_INTR_STATE_NMI);
9327                 else
9328                         vmx->loaded_vmcs->nmi_known_unmasked =
9329                                 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
9330                                   & GUEST_INTR_STATE_NMI);
9331         } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
9332                 vmx->loaded_vmcs->vnmi_blocked_time +=
9333                         ktime_to_ns(ktime_sub(ktime_get(),
9334                                               vmx->loaded_vmcs->entry_time));
9335 }
9336
9337 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
9338                                       u32 idt_vectoring_info,
9339                                       int instr_len_field,
9340                                       int error_code_field)
9341 {
9342         u8 vector;
9343         int type;
9344         bool idtv_info_valid;
9345
9346         idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
9347
9348         vcpu->arch.nmi_injected = false;
9349         kvm_clear_exception_queue(vcpu);
9350         kvm_clear_interrupt_queue(vcpu);
9351
9352         if (!idtv_info_valid)
9353                 return;
9354
9355         kvm_make_request(KVM_REQ_EVENT, vcpu);
9356
9357         vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
9358         type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
9359
9360         switch (type) {
9361         case INTR_TYPE_NMI_INTR:
9362                 vcpu->arch.nmi_injected = true;
9363                 /*
9364                  * SDM 3: 27.7.1.2 (September 2008)
9365                  * Clear bit "block by NMI" before VM entry if a NMI
9366                  * delivery faulted.
9367                  */
9368                 vmx_set_nmi_mask(vcpu, false);
9369                 break;
9370         case INTR_TYPE_SOFT_EXCEPTION:
9371                 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
9372                 /* fall through */
9373         case INTR_TYPE_HARD_EXCEPTION:
9374                 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
9375                         u32 err = vmcs_read32(error_code_field);
9376                         kvm_requeue_exception_e(vcpu, vector, err);
9377                 } else
9378                         kvm_requeue_exception(vcpu, vector);
9379                 break;
9380         case INTR_TYPE_SOFT_INTR:
9381                 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
9382                 /* fall through */
9383         case INTR_TYPE_EXT_INTR:
9384                 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
9385                 break;
9386         default:
9387                 break;
9388         }
9389 }
9390
9391 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
9392 {
9393         __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
9394                                   VM_EXIT_INSTRUCTION_LEN,
9395                                   IDT_VECTORING_ERROR_CODE);
9396 }
9397
9398 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
9399 {
9400         __vmx_complete_interrupts(vcpu,
9401                                   vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
9402                                   VM_ENTRY_INSTRUCTION_LEN,
9403                                   VM_ENTRY_EXCEPTION_ERROR_CODE);
9404
9405         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
9406 }
9407
9408 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
9409 {
9410         int i, nr_msrs;
9411         struct perf_guest_switch_msr *msrs;
9412
9413         msrs = perf_guest_get_msrs(&nr_msrs);
9414
9415         if (!msrs)
9416                 return;
9417
9418         for (i = 0; i < nr_msrs; i++)
9419                 if (msrs[i].host == msrs[i].guest)
9420                         clear_atomic_switch_msr(vmx, msrs[i].msr);
9421                 else
9422                         add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
9423                                         msrs[i].host);
9424 }
9425
9426 static void vmx_arm_hv_timer(struct kvm_vcpu *vcpu)
9427 {
9428         struct vcpu_vmx *vmx = to_vmx(vcpu);
9429         u64 tscl;
9430         u32 delta_tsc;
9431
9432         if (vmx->hv_deadline_tsc == -1)
9433                 return;
9434
9435         tscl = rdtsc();
9436         if (vmx->hv_deadline_tsc > tscl)
9437                 /* sure to be 32 bit only because checked on set_hv_timer */
9438                 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
9439                         cpu_preemption_timer_multi);
9440         else
9441                 delta_tsc = 0;
9442
9443         vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc);
9444 }
9445
9446 static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
9447 {
9448         struct vcpu_vmx *vmx = to_vmx(vcpu);
9449         unsigned long cr3, cr4;
9450
9451         /* Record the guest's net vcpu time for enforced NMI injections. */
9452         if (unlikely(!enable_vnmi &&
9453                      vmx->loaded_vmcs->soft_vnmi_blocked))
9454                 vmx->loaded_vmcs->entry_time = ktime_get();
9455
9456         /* Don't enter VMX if guest state is invalid, let the exit handler
9457            start emulation until we arrive back to a valid state */
9458         if (vmx->emulation_required)
9459                 return;
9460
9461         if (vmx->ple_window_dirty) {
9462                 vmx->ple_window_dirty = false;
9463                 vmcs_write32(PLE_WINDOW, vmx->ple_window);
9464         }
9465
9466         if (vmx->nested.sync_shadow_vmcs) {
9467                 copy_vmcs12_to_shadow(vmx);
9468                 vmx->nested.sync_shadow_vmcs = false;
9469         }
9470
9471         if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
9472                 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
9473         if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
9474                 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
9475
9476         cr3 = __get_current_cr3_fast();
9477         if (unlikely(cr3 != vmx->loaded_vmcs->vmcs_host_cr3)) {
9478                 vmcs_writel(HOST_CR3, cr3);
9479                 vmx->loaded_vmcs->vmcs_host_cr3 = cr3;
9480         }
9481
9482         cr4 = cr4_read_shadow();
9483         if (unlikely(cr4 != vmx->loaded_vmcs->vmcs_host_cr4)) {
9484                 vmcs_writel(HOST_CR4, cr4);
9485                 vmx->loaded_vmcs->vmcs_host_cr4 = cr4;
9486         }
9487
9488         /* When single-stepping over STI and MOV SS, we must clear the
9489          * corresponding interruptibility bits in the guest state. Otherwise
9490          * vmentry fails as it then expects bit 14 (BS) in pending debug
9491          * exceptions being set, but that's not correct for the guest debugging
9492          * case. */
9493         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
9494                 vmx_set_interrupt_shadow(vcpu, 0);
9495
9496         if (static_cpu_has(X86_FEATURE_PKU) &&
9497             kvm_read_cr4_bits(vcpu, X86_CR4_PKE) &&
9498             vcpu->arch.pkru != vmx->host_pkru)
9499                 __write_pkru(vcpu->arch.pkru);
9500
9501         atomic_switch_perf_msrs(vmx);
9502
9503         vmx_arm_hv_timer(vcpu);
9504
9505         /*
9506          * If this vCPU has touched SPEC_CTRL, restore the guest's value if
9507          * it's non-zero. Since vmentry is serialising on affected CPUs, there
9508          * is no need to worry about the conditional branch over the wrmsr
9509          * being speculatively taken.
9510          */
9511         if (vmx->spec_ctrl)
9512                 native_wrmsrl(MSR_IA32_SPEC_CTRL, vmx->spec_ctrl);
9513
9514         vmx->__launched = vmx->loaded_vmcs->launched;
9515         asm(
9516                 /* Store host registers */
9517                 "push %%" _ASM_DX "; push %%" _ASM_BP ";"
9518                 "push %%" _ASM_CX " \n\t" /* placeholder for guest rcx */
9519                 "push %%" _ASM_CX " \n\t"
9520                 "cmp %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
9521                 "je 1f \n\t"
9522                 "mov %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
9523                 __ex(ASM_VMX_VMWRITE_RSP_RDX) "\n\t"
9524                 "1: \n\t"
9525                 /* Reload cr2 if changed */
9526                 "mov %c[cr2](%0), %%" _ASM_AX " \n\t"
9527                 "mov %%cr2, %%" _ASM_DX " \n\t"
9528                 "cmp %%" _ASM_AX ", %%" _ASM_DX " \n\t"
9529                 "je 2f \n\t"
9530                 "mov %%" _ASM_AX", %%cr2 \n\t"
9531                 "2: \n\t"
9532                 /* Check if vmlaunch of vmresume is needed */
9533                 "cmpl $0, %c[launched](%0) \n\t"
9534                 /* Load guest registers.  Don't clobber flags. */
9535                 "mov %c[rax](%0), %%" _ASM_AX " \n\t"
9536                 "mov %c[rbx](%0), %%" _ASM_BX " \n\t"
9537                 "mov %c[rdx](%0), %%" _ASM_DX " \n\t"
9538                 "mov %c[rsi](%0), %%" _ASM_SI " \n\t"
9539                 "mov %c[rdi](%0), %%" _ASM_DI " \n\t"
9540                 "mov %c[rbp](%0), %%" _ASM_BP " \n\t"
9541 #ifdef CONFIG_X86_64
9542                 "mov %c[r8](%0),  %%r8  \n\t"
9543                 "mov %c[r9](%0),  %%r9  \n\t"
9544                 "mov %c[r10](%0), %%r10 \n\t"
9545                 "mov %c[r11](%0), %%r11 \n\t"
9546                 "mov %c[r12](%0), %%r12 \n\t"
9547                 "mov %c[r13](%0), %%r13 \n\t"
9548                 "mov %c[r14](%0), %%r14 \n\t"
9549                 "mov %c[r15](%0), %%r15 \n\t"
9550 #endif
9551                 "mov %c[rcx](%0), %%" _ASM_CX " \n\t" /* kills %0 (ecx) */
9552
9553                 /* Enter guest mode */
9554                 "jne 1f \n\t"
9555                 __ex(ASM_VMX_VMLAUNCH) "\n\t"
9556                 "jmp 2f \n\t"
9557                 "1: " __ex(ASM_VMX_VMRESUME) "\n\t"
9558                 "2: "
9559                 /* Save guest registers, load host registers, keep flags */
9560                 "mov %0, %c[wordsize](%%" _ASM_SP ") \n\t"
9561                 "pop %0 \n\t"
9562                 "setbe %c[fail](%0)\n\t"
9563                 "mov %%" _ASM_AX ", %c[rax](%0) \n\t"
9564                 "mov %%" _ASM_BX ", %c[rbx](%0) \n\t"
9565                 __ASM_SIZE(pop) " %c[rcx](%0) \n\t"
9566                 "mov %%" _ASM_DX ", %c[rdx](%0) \n\t"
9567                 "mov %%" _ASM_SI ", %c[rsi](%0) \n\t"
9568                 "mov %%" _ASM_DI ", %c[rdi](%0) \n\t"
9569                 "mov %%" _ASM_BP ", %c[rbp](%0) \n\t"
9570 #ifdef CONFIG_X86_64
9571                 "mov %%r8,  %c[r8](%0) \n\t"
9572                 "mov %%r9,  %c[r9](%0) \n\t"
9573                 "mov %%r10, %c[r10](%0) \n\t"
9574                 "mov %%r11, %c[r11](%0) \n\t"
9575                 "mov %%r12, %c[r12](%0) \n\t"
9576                 "mov %%r13, %c[r13](%0) \n\t"
9577                 "mov %%r14, %c[r14](%0) \n\t"
9578                 "mov %%r15, %c[r15](%0) \n\t"
9579                 "xor %%r8d,  %%r8d \n\t"
9580                 "xor %%r9d,  %%r9d \n\t"
9581                 "xor %%r10d, %%r10d \n\t"
9582                 "xor %%r11d, %%r11d \n\t"
9583                 "xor %%r12d, %%r12d \n\t"
9584                 "xor %%r13d, %%r13d \n\t"
9585                 "xor %%r14d, %%r14d \n\t"
9586                 "xor %%r15d, %%r15d \n\t"
9587 #endif
9588                 "mov %%cr2, %%" _ASM_AX "   \n\t"
9589                 "mov %%" _ASM_AX ", %c[cr2](%0) \n\t"
9590
9591                 "xor %%eax, %%eax \n\t"
9592                 "xor %%ebx, %%ebx \n\t"
9593                 "xor %%esi, %%esi \n\t"
9594                 "xor %%edi, %%edi \n\t"
9595                 "pop  %%" _ASM_BP "; pop  %%" _ASM_DX " \n\t"
9596                 ".pushsection .rodata \n\t"
9597                 ".global vmx_return \n\t"
9598                 "vmx_return: " _ASM_PTR " 2b \n\t"
9599                 ".popsection"
9600               : : "c"(vmx), "d"((unsigned long)HOST_RSP),
9601                 [launched]"i"(offsetof(struct vcpu_vmx, __launched)),
9602                 [fail]"i"(offsetof(struct vcpu_vmx, fail)),
9603                 [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)),
9604                 [rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])),
9605                 [rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])),
9606                 [rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])),
9607                 [rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])),
9608                 [rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])),
9609                 [rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])),
9610                 [rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])),
9611 #ifdef CONFIG_X86_64
9612                 [r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])),
9613                 [r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])),
9614                 [r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])),
9615                 [r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])),
9616                 [r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])),
9617                 [r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])),
9618                 [r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])),
9619                 [r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])),
9620 #endif
9621                 [cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2)),
9622                 [wordsize]"i"(sizeof(ulong))
9623               : "cc", "memory"
9624 #ifdef CONFIG_X86_64
9625                 , "rax", "rbx", "rdi", "rsi"
9626                 , "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
9627 #else
9628                 , "eax", "ebx", "edi", "esi"
9629 #endif
9630               );
9631
9632         /*
9633          * We do not use IBRS in the kernel. If this vCPU has used the
9634          * SPEC_CTRL MSR it may have left it on; save the value and
9635          * turn it off. This is much more efficient than blindly adding
9636          * it to the atomic save/restore list. Especially as the former
9637          * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
9638          *
9639          * For non-nested case:
9640          * If the L01 MSR bitmap does not intercept the MSR, then we need to
9641          * save it.
9642          *
9643          * For nested case:
9644          * If the L02 MSR bitmap does not intercept the MSR, then we need to
9645          * save it.
9646          */
9647         if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
9648                 vmx->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
9649
9650         if (vmx->spec_ctrl)
9651                 native_wrmsrl(MSR_IA32_SPEC_CTRL, 0);
9652
9653         /* Eliminate branch target predictions from guest mode */
9654         vmexit_fill_RSB();
9655
9656         /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
9657         if (vmx->host_debugctlmsr)
9658                 update_debugctlmsr(vmx->host_debugctlmsr);
9659
9660 #ifndef CONFIG_X86_64
9661         /*
9662          * The sysexit path does not restore ds/es, so we must set them to
9663          * a reasonable value ourselves.
9664          *
9665          * We can't defer this to vmx_load_host_state() since that function
9666          * may be executed in interrupt context, which saves and restore segments
9667          * around it, nullifying its effect.
9668          */
9669         loadsegment(ds, __USER_DS);
9670         loadsegment(es, __USER_DS);
9671 #endif
9672
9673         vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
9674                                   | (1 << VCPU_EXREG_RFLAGS)
9675                                   | (1 << VCPU_EXREG_PDPTR)
9676                                   | (1 << VCPU_EXREG_SEGMENTS)
9677                                   | (1 << VCPU_EXREG_CR3));
9678         vcpu->arch.regs_dirty = 0;
9679
9680         /*
9681          * eager fpu is enabled if PKEY is supported and CR4 is switched
9682          * back on host, so it is safe to read guest PKRU from current
9683          * XSAVE.
9684          */
9685         if (static_cpu_has(X86_FEATURE_PKU) &&
9686             kvm_read_cr4_bits(vcpu, X86_CR4_PKE)) {
9687                 vcpu->arch.pkru = __read_pkru();
9688                 if (vcpu->arch.pkru != vmx->host_pkru)
9689                         __write_pkru(vmx->host_pkru);
9690         }
9691
9692         /*
9693          * the KVM_REQ_EVENT optimization bit is only on for one entry, and if
9694          * we did not inject a still-pending event to L1 now because of
9695          * nested_run_pending, we need to re-enable this bit.
9696          */
9697         if (vmx->nested.nested_run_pending)
9698                 kvm_make_request(KVM_REQ_EVENT, vcpu);
9699
9700         vmx->nested.nested_run_pending = 0;
9701         vmx->idt_vectoring_info = 0;
9702
9703         vmx->exit_reason = vmx->fail ? 0xdead : vmcs_read32(VM_EXIT_REASON);
9704         if (vmx->fail || (vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
9705                 return;
9706
9707         vmx->loaded_vmcs->launched = 1;
9708         vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
9709
9710         vmx_complete_atomic_exit(vmx);
9711         vmx_recover_nmi_blocking(vmx);
9712         vmx_complete_interrupts(vmx);
9713 }
9714 STACK_FRAME_NON_STANDARD(vmx_vcpu_run);
9715
9716 static void vmx_switch_vmcs(struct kvm_vcpu *vcpu, struct loaded_vmcs *vmcs)
9717 {
9718         struct vcpu_vmx *vmx = to_vmx(vcpu);
9719         int cpu;
9720
9721         if (vmx->loaded_vmcs == vmcs)
9722                 return;
9723
9724         cpu = get_cpu();
9725         vmx->loaded_vmcs = vmcs;
9726         vmx_vcpu_put(vcpu);
9727         vmx_vcpu_load(vcpu, cpu);
9728         put_cpu();
9729 }
9730
9731 /*
9732  * Ensure that the current vmcs of the logical processor is the
9733  * vmcs01 of the vcpu before calling free_nested().
9734  */
9735 static void vmx_free_vcpu_nested(struct kvm_vcpu *vcpu)
9736 {
9737        struct vcpu_vmx *vmx = to_vmx(vcpu);
9738
9739        vcpu_load(vcpu);
9740        vmx_switch_vmcs(vcpu, &vmx->vmcs01);
9741        free_nested(vmx);
9742        vcpu_put(vcpu);
9743 }
9744
9745 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
9746 {
9747         struct vcpu_vmx *vmx = to_vmx(vcpu);
9748
9749         if (enable_pml)
9750                 vmx_destroy_pml_buffer(vmx);
9751         free_vpid(vmx->vpid);
9752         leave_guest_mode(vcpu);
9753         vmx_free_vcpu_nested(vcpu);
9754         free_loaded_vmcs(vmx->loaded_vmcs);
9755         kfree(vmx->guest_msrs);
9756         kvm_vcpu_uninit(vcpu);
9757         kmem_cache_free(kvm_vcpu_cache, vmx);
9758 }
9759
9760 static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
9761 {
9762         int err;
9763         struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
9764         unsigned long *msr_bitmap;
9765         int cpu;
9766
9767         if (!vmx)
9768                 return ERR_PTR(-ENOMEM);
9769
9770         vmx->vpid = allocate_vpid();
9771
9772         err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
9773         if (err)
9774                 goto free_vcpu;
9775
9776         err = -ENOMEM;
9777
9778         /*
9779          * If PML is turned on, failure on enabling PML just results in failure
9780          * of creating the vcpu, therefore we can simplify PML logic (by
9781          * avoiding dealing with cases, such as enabling PML partially on vcpus
9782          * for the guest, etc.
9783          */
9784         if (enable_pml) {
9785                 vmx->pml_pg = alloc_page(GFP_KERNEL | __GFP_ZERO);
9786                 if (!vmx->pml_pg)
9787                         goto uninit_vcpu;
9788         }
9789
9790         vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
9791         BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) * sizeof(vmx->guest_msrs[0])
9792                      > PAGE_SIZE);
9793
9794         if (!vmx->guest_msrs)
9795                 goto free_pml;
9796
9797         err = alloc_loaded_vmcs(&vmx->vmcs01);
9798         if (err < 0)
9799                 goto free_msrs;
9800
9801         msr_bitmap = vmx->vmcs01.msr_bitmap;
9802         vmx_disable_intercept_for_msr(msr_bitmap, MSR_FS_BASE, MSR_TYPE_RW);
9803         vmx_disable_intercept_for_msr(msr_bitmap, MSR_GS_BASE, MSR_TYPE_RW);
9804         vmx_disable_intercept_for_msr(msr_bitmap, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
9805         vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
9806         vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
9807         vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
9808         vmx->msr_bitmap_mode = 0;
9809
9810         vmx->loaded_vmcs = &vmx->vmcs01;
9811         cpu = get_cpu();
9812         vmx_vcpu_load(&vmx->vcpu, cpu);
9813         vmx->vcpu.cpu = cpu;
9814         vmx_vcpu_setup(vmx);
9815         vmx_vcpu_put(&vmx->vcpu);
9816         put_cpu();
9817         if (cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
9818                 err = alloc_apic_access_page(kvm);
9819                 if (err)
9820                         goto free_vmcs;
9821         }
9822
9823         if (enable_ept && !enable_unrestricted_guest) {
9824                 err = init_rmode_identity_map(kvm);
9825                 if (err)
9826                         goto free_vmcs;
9827         }
9828
9829         if (nested) {
9830                 nested_vmx_setup_ctls_msrs(&vmx->nested.msrs,
9831                                            kvm_vcpu_apicv_active(&vmx->vcpu));
9832                 vmx->nested.vpid02 = allocate_vpid();
9833         }
9834
9835         vmx->nested.posted_intr_nv = -1;
9836         vmx->nested.current_vmptr = -1ull;
9837
9838         vmx->msr_ia32_feature_control_valid_bits = FEATURE_CONTROL_LOCKED;
9839
9840         /*
9841          * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
9842          * or POSTED_INTR_WAKEUP_VECTOR.
9843          */
9844         vmx->pi_desc.nv = POSTED_INTR_VECTOR;
9845         vmx->pi_desc.sn = 1;
9846
9847         return &vmx->vcpu;
9848
9849 free_vmcs:
9850         free_vpid(vmx->nested.vpid02);
9851         free_loaded_vmcs(vmx->loaded_vmcs);
9852 free_msrs:
9853         kfree(vmx->guest_msrs);
9854 free_pml:
9855         vmx_destroy_pml_buffer(vmx);
9856 uninit_vcpu:
9857         kvm_vcpu_uninit(&vmx->vcpu);
9858 free_vcpu:
9859         free_vpid(vmx->vpid);
9860         kmem_cache_free(kvm_vcpu_cache, vmx);
9861         return ERR_PTR(err);
9862 }
9863
9864 static void __init vmx_check_processor_compat(void *rtn)
9865 {
9866         struct vmcs_config vmcs_conf;
9867
9868         *(int *)rtn = 0;
9869         if (setup_vmcs_config(&vmcs_conf) < 0)
9870                 *(int *)rtn = -EIO;
9871         nested_vmx_setup_ctls_msrs(&vmcs_conf.nested, enable_apicv);
9872         if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
9873                 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
9874                                 smp_processor_id());
9875                 *(int *)rtn = -EIO;
9876         }
9877 }
9878
9879 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
9880 {
9881         u8 cache;
9882         u64 ipat = 0;
9883
9884         /* For VT-d and EPT combination
9885          * 1. MMIO: always map as UC
9886          * 2. EPT with VT-d:
9887          *   a. VT-d without snooping control feature: can't guarantee the
9888          *      result, try to trust guest.
9889          *   b. VT-d with snooping control feature: snooping control feature of
9890          *      VT-d engine can guarantee the cache correctness. Just set it
9891          *      to WB to keep consistent with host. So the same as item 3.
9892          * 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
9893          *    consistent with host MTRR
9894          */
9895         if (is_mmio) {
9896                 cache = MTRR_TYPE_UNCACHABLE;
9897                 goto exit;
9898         }
9899
9900         if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
9901                 ipat = VMX_EPT_IPAT_BIT;
9902                 cache = MTRR_TYPE_WRBACK;
9903                 goto exit;
9904         }
9905
9906         if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
9907                 ipat = VMX_EPT_IPAT_BIT;
9908                 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
9909                         cache = MTRR_TYPE_WRBACK;
9910                 else
9911                         cache = MTRR_TYPE_UNCACHABLE;
9912                 goto exit;
9913         }
9914
9915         cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
9916
9917 exit:
9918         return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
9919 }
9920
9921 static int vmx_get_lpage_level(void)
9922 {
9923         if (enable_ept && !cpu_has_vmx_ept_1g_page())
9924                 return PT_DIRECTORY_LEVEL;
9925         else
9926                 /* For shadow and EPT supported 1GB page */
9927                 return PT_PDPE_LEVEL;
9928 }
9929
9930 static void vmcs_set_secondary_exec_control(u32 new_ctl)
9931 {
9932         /*
9933          * These bits in the secondary execution controls field
9934          * are dynamic, the others are mostly based on the hypervisor
9935          * architecture and the guest's CPUID.  Do not touch the
9936          * dynamic bits.
9937          */
9938         u32 mask =
9939                 SECONDARY_EXEC_SHADOW_VMCS |
9940                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
9941                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
9942                 SECONDARY_EXEC_DESC;
9943
9944         u32 cur_ctl = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
9945
9946         vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
9947                      (new_ctl & ~mask) | (cur_ctl & mask));
9948 }
9949
9950 /*
9951  * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
9952  * (indicating "allowed-1") if they are supported in the guest's CPUID.
9953  */
9954 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
9955 {
9956         struct vcpu_vmx *vmx = to_vmx(vcpu);
9957         struct kvm_cpuid_entry2 *entry;
9958
9959         vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
9960         vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
9961
9962 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do {            \
9963         if (entry && (entry->_reg & (_cpuid_mask)))                     \
9964                 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask);     \
9965 } while (0)
9966
9967         entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
9968         cr4_fixed1_update(X86_CR4_VME,        edx, bit(X86_FEATURE_VME));
9969         cr4_fixed1_update(X86_CR4_PVI,        edx, bit(X86_FEATURE_VME));
9970         cr4_fixed1_update(X86_CR4_TSD,        edx, bit(X86_FEATURE_TSC));
9971         cr4_fixed1_update(X86_CR4_DE,         edx, bit(X86_FEATURE_DE));
9972         cr4_fixed1_update(X86_CR4_PSE,        edx, bit(X86_FEATURE_PSE));
9973         cr4_fixed1_update(X86_CR4_PAE,        edx, bit(X86_FEATURE_PAE));
9974         cr4_fixed1_update(X86_CR4_MCE,        edx, bit(X86_FEATURE_MCE));
9975         cr4_fixed1_update(X86_CR4_PGE,        edx, bit(X86_FEATURE_PGE));
9976         cr4_fixed1_update(X86_CR4_OSFXSR,     edx, bit(X86_FEATURE_FXSR));
9977         cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, bit(X86_FEATURE_XMM));
9978         cr4_fixed1_update(X86_CR4_VMXE,       ecx, bit(X86_FEATURE_VMX));
9979         cr4_fixed1_update(X86_CR4_SMXE,       ecx, bit(X86_FEATURE_SMX));
9980         cr4_fixed1_update(X86_CR4_PCIDE,      ecx, bit(X86_FEATURE_PCID));
9981         cr4_fixed1_update(X86_CR4_OSXSAVE,    ecx, bit(X86_FEATURE_XSAVE));
9982
9983         entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
9984         cr4_fixed1_update(X86_CR4_FSGSBASE,   ebx, bit(X86_FEATURE_FSGSBASE));
9985         cr4_fixed1_update(X86_CR4_SMEP,       ebx, bit(X86_FEATURE_SMEP));
9986         cr4_fixed1_update(X86_CR4_SMAP,       ebx, bit(X86_FEATURE_SMAP));
9987         cr4_fixed1_update(X86_CR4_PKE,        ecx, bit(X86_FEATURE_PKU));
9988         cr4_fixed1_update(X86_CR4_UMIP,       ecx, bit(X86_FEATURE_UMIP));
9989
9990 #undef cr4_fixed1_update
9991 }
9992
9993 static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
9994 {
9995         struct vcpu_vmx *vmx = to_vmx(vcpu);
9996
9997         if (cpu_has_secondary_exec_ctrls()) {
9998                 vmx_compute_secondary_exec_control(vmx);
9999                 vmcs_set_secondary_exec_control(vmx->secondary_exec_control);
10000         }
10001
10002         if (nested_vmx_allowed(vcpu))
10003                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
10004                         FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
10005         else
10006                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
10007                         ~FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
10008
10009         if (nested_vmx_allowed(vcpu))
10010                 nested_vmx_cr_fixed1_bits_update(vcpu);
10011 }
10012
10013 static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
10014 {
10015         if (func == 1 && nested)
10016                 entry->ecx |= bit(X86_FEATURE_VMX);
10017 }
10018
10019 static void nested_ept_inject_page_fault(struct kvm_vcpu *vcpu,
10020                 struct x86_exception *fault)
10021 {
10022         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
10023         struct vcpu_vmx *vmx = to_vmx(vcpu);
10024         u32 exit_reason;
10025         unsigned long exit_qualification = vcpu->arch.exit_qualification;
10026
10027         if (vmx->nested.pml_full) {
10028                 exit_reason = EXIT_REASON_PML_FULL;
10029                 vmx->nested.pml_full = false;
10030                 exit_qualification &= INTR_INFO_UNBLOCK_NMI;
10031         } else if (fault->error_code & PFERR_RSVD_MASK)
10032                 exit_reason = EXIT_REASON_EPT_MISCONFIG;
10033         else
10034                 exit_reason = EXIT_REASON_EPT_VIOLATION;
10035
10036         nested_vmx_vmexit(vcpu, exit_reason, 0, exit_qualification);
10037         vmcs12->guest_physical_address = fault->address;
10038 }
10039
10040 static bool nested_ept_ad_enabled(struct kvm_vcpu *vcpu)
10041 {
10042         return nested_ept_get_cr3(vcpu) & VMX_EPTP_AD_ENABLE_BIT;
10043 }
10044
10045 /* Callbacks for nested_ept_init_mmu_context: */
10046
10047 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu)
10048 {
10049         /* return the page table to be shadowed - in our case, EPT12 */
10050         return get_vmcs12(vcpu)->ept_pointer;
10051 }
10052
10053 static int nested_ept_init_mmu_context(struct kvm_vcpu *vcpu)
10054 {
10055         WARN_ON(mmu_is_nested(vcpu));
10056         if (!valid_ept_address(vcpu, nested_ept_get_cr3(vcpu)))
10057                 return 1;
10058
10059         kvm_mmu_unload(vcpu);
10060         kvm_init_shadow_ept_mmu(vcpu,
10061                         to_vmx(vcpu)->nested.msrs.ept_caps &
10062                         VMX_EPT_EXECUTE_ONLY_BIT,
10063                         nested_ept_ad_enabled(vcpu));
10064         vcpu->arch.mmu.set_cr3           = vmx_set_cr3;
10065         vcpu->arch.mmu.get_cr3           = nested_ept_get_cr3;
10066         vcpu->arch.mmu.inject_page_fault = nested_ept_inject_page_fault;
10067
10068         vcpu->arch.walk_mmu              = &vcpu->arch.nested_mmu;
10069         return 0;
10070 }
10071
10072 static void nested_ept_uninit_mmu_context(struct kvm_vcpu *vcpu)
10073 {
10074         vcpu->arch.walk_mmu = &vcpu->arch.mmu;
10075 }
10076
10077 static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
10078                                             u16 error_code)
10079 {
10080         bool inequality, bit;
10081
10082         bit = (vmcs12->exception_bitmap & (1u << PF_VECTOR)) != 0;
10083         inequality =
10084                 (error_code & vmcs12->page_fault_error_code_mask) !=
10085                  vmcs12->page_fault_error_code_match;
10086         return inequality ^ bit;
10087 }
10088
10089 static void vmx_inject_page_fault_nested(struct kvm_vcpu *vcpu,
10090                 struct x86_exception *fault)
10091 {
10092         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
10093
10094         WARN_ON(!is_guest_mode(vcpu));
10095
10096         if (nested_vmx_is_page_fault_vmexit(vmcs12, fault->error_code) &&
10097                 !to_vmx(vcpu)->nested.nested_run_pending) {
10098                 vmcs12->vm_exit_intr_error_code = fault->error_code;
10099                 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
10100                                   PF_VECTOR | INTR_TYPE_HARD_EXCEPTION |
10101                                   INTR_INFO_DELIVER_CODE_MASK | INTR_INFO_VALID_MASK,
10102                                   fault->address);
10103         } else {
10104                 kvm_inject_page_fault(vcpu, fault);
10105         }
10106 }
10107
10108 static inline bool nested_vmx_prepare_msr_bitmap(struct kvm_vcpu *vcpu,
10109                                                  struct vmcs12 *vmcs12);
10110
10111 static void nested_get_vmcs12_pages(struct kvm_vcpu *vcpu,
10112                                         struct vmcs12 *vmcs12)
10113 {
10114         struct vcpu_vmx *vmx = to_vmx(vcpu);
10115         struct page *page;
10116         u64 hpa;
10117
10118         if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
10119                 /*
10120                  * Translate L1 physical address to host physical
10121                  * address for vmcs02. Keep the page pinned, so this
10122                  * physical address remains valid. We keep a reference
10123                  * to it so we can release it later.
10124                  */
10125                 if (vmx->nested.apic_access_page) { /* shouldn't happen */
10126                         kvm_release_page_dirty(vmx->nested.apic_access_page);
10127                         vmx->nested.apic_access_page = NULL;
10128                 }
10129                 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->apic_access_addr);
10130                 /*
10131                  * If translation failed, no matter: This feature asks
10132                  * to exit when accessing the given address, and if it
10133                  * can never be accessed, this feature won't do
10134                  * anything anyway.
10135                  */
10136                 if (!is_error_page(page)) {
10137                         vmx->nested.apic_access_page = page;
10138                         hpa = page_to_phys(vmx->nested.apic_access_page);
10139                         vmcs_write64(APIC_ACCESS_ADDR, hpa);
10140                 } else {
10141                         vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
10142                                         SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
10143                 }
10144         } else if (!(nested_cpu_has_virt_x2apic_mode(vmcs12)) &&
10145                    cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
10146                 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
10147                               SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
10148                 kvm_vcpu_reload_apic_access_page(vcpu);
10149         }
10150
10151         if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
10152                 if (vmx->nested.virtual_apic_page) { /* shouldn't happen */
10153                         kvm_release_page_dirty(vmx->nested.virtual_apic_page);
10154                         vmx->nested.virtual_apic_page = NULL;
10155                 }
10156                 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->virtual_apic_page_addr);
10157
10158                 /*
10159                  * If translation failed, VM entry will fail because
10160                  * prepare_vmcs02 set VIRTUAL_APIC_PAGE_ADDR to -1ull.
10161                  * Failing the vm entry is _not_ what the processor
10162                  * does but it's basically the only possibility we
10163                  * have.  We could still enter the guest if CR8 load
10164                  * exits are enabled, CR8 store exits are enabled, and
10165                  * virtualize APIC access is disabled; in this case
10166                  * the processor would never use the TPR shadow and we
10167                  * could simply clear the bit from the execution
10168                  * control.  But such a configuration is useless, so
10169                  * let's keep the code simple.
10170                  */
10171                 if (!is_error_page(page)) {
10172                         vmx->nested.virtual_apic_page = page;
10173                         hpa = page_to_phys(vmx->nested.virtual_apic_page);
10174                         vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, hpa);
10175                 }
10176         }
10177
10178         if (nested_cpu_has_posted_intr(vmcs12)) {
10179                 if (vmx->nested.pi_desc_page) { /* shouldn't happen */
10180                         kunmap(vmx->nested.pi_desc_page);
10181                         kvm_release_page_dirty(vmx->nested.pi_desc_page);
10182                         vmx->nested.pi_desc_page = NULL;
10183                 }
10184                 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->posted_intr_desc_addr);
10185                 if (is_error_page(page))
10186                         return;
10187                 vmx->nested.pi_desc_page = page;
10188                 vmx->nested.pi_desc = kmap(vmx->nested.pi_desc_page);
10189                 vmx->nested.pi_desc =
10190                         (struct pi_desc *)((void *)vmx->nested.pi_desc +
10191                         (unsigned long)(vmcs12->posted_intr_desc_addr &
10192                         (PAGE_SIZE - 1)));
10193                 vmcs_write64(POSTED_INTR_DESC_ADDR,
10194                         page_to_phys(vmx->nested.pi_desc_page) +
10195                         (unsigned long)(vmcs12->posted_intr_desc_addr &
10196                         (PAGE_SIZE - 1)));
10197         }
10198         if (nested_vmx_prepare_msr_bitmap(vcpu, vmcs12))
10199                 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
10200                               CPU_BASED_USE_MSR_BITMAPS);
10201         else
10202                 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
10203                                 CPU_BASED_USE_MSR_BITMAPS);
10204 }
10205
10206 static void vmx_start_preemption_timer(struct kvm_vcpu *vcpu)
10207 {
10208         u64 preemption_timeout = get_vmcs12(vcpu)->vmx_preemption_timer_value;
10209         struct vcpu_vmx *vmx = to_vmx(vcpu);
10210
10211         if (vcpu->arch.virtual_tsc_khz == 0)
10212                 return;
10213
10214         /* Make sure short timeouts reliably trigger an immediate vmexit.
10215          * hrtimer_start does not guarantee this. */
10216         if (preemption_timeout <= 1) {
10217                 vmx_preemption_timer_fn(&vmx->nested.preemption_timer);
10218                 return;
10219         }
10220
10221         preemption_timeout <<= VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
10222         preemption_timeout *= 1000000;
10223         do_div(preemption_timeout, vcpu->arch.virtual_tsc_khz);
10224         hrtimer_start(&vmx->nested.preemption_timer,
10225                       ns_to_ktime(preemption_timeout), HRTIMER_MODE_REL);
10226 }
10227
10228 static int nested_vmx_check_io_bitmap_controls(struct kvm_vcpu *vcpu,
10229                                                struct vmcs12 *vmcs12)
10230 {
10231         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
10232                 return 0;
10233
10234         if (!page_address_valid(vcpu, vmcs12->io_bitmap_a) ||
10235             !page_address_valid(vcpu, vmcs12->io_bitmap_b))
10236                 return -EINVAL;
10237
10238         return 0;
10239 }
10240
10241 static int nested_vmx_check_msr_bitmap_controls(struct kvm_vcpu *vcpu,
10242                                                 struct vmcs12 *vmcs12)
10243 {
10244         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
10245                 return 0;
10246
10247         if (!page_address_valid(vcpu, vmcs12->msr_bitmap))
10248                 return -EINVAL;
10249
10250         return 0;
10251 }
10252
10253 static int nested_vmx_check_tpr_shadow_controls(struct kvm_vcpu *vcpu,
10254                                                 struct vmcs12 *vmcs12)
10255 {
10256         if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
10257                 return 0;
10258
10259         if (!page_address_valid(vcpu, vmcs12->virtual_apic_page_addr))
10260                 return -EINVAL;
10261
10262         return 0;
10263 }
10264
10265 /*
10266  * Merge L0's and L1's MSR bitmap, return false to indicate that
10267  * we do not use the hardware.
10268  */
10269 static inline bool nested_vmx_prepare_msr_bitmap(struct kvm_vcpu *vcpu,
10270                                                  struct vmcs12 *vmcs12)
10271 {
10272         int msr;
10273         struct page *page;
10274         unsigned long *msr_bitmap_l1;
10275         unsigned long *msr_bitmap_l0 = to_vmx(vcpu)->nested.vmcs02.msr_bitmap;
10276         /*
10277          * pred_cmd & spec_ctrl are trying to verify two things:
10278          *
10279          * 1. L0 gave a permission to L1 to actually passthrough the MSR. This
10280          *    ensures that we do not accidentally generate an L02 MSR bitmap
10281          *    from the L12 MSR bitmap that is too permissive.
10282          * 2. That L1 or L2s have actually used the MSR. This avoids
10283          *    unnecessarily merging of the bitmap if the MSR is unused. This
10284          *    works properly because we only update the L01 MSR bitmap lazily.
10285          *    So even if L0 should pass L1 these MSRs, the L01 bitmap is only
10286          *    updated to reflect this when L1 (or its L2s) actually write to
10287          *    the MSR.
10288          */
10289         bool pred_cmd = !msr_write_intercepted_l01(vcpu, MSR_IA32_PRED_CMD);
10290         bool spec_ctrl = !msr_write_intercepted_l01(vcpu, MSR_IA32_SPEC_CTRL);
10291
10292         /* Nothing to do if the MSR bitmap is not in use.  */
10293         if (!cpu_has_vmx_msr_bitmap() ||
10294             !nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
10295                 return false;
10296
10297         if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
10298             !pred_cmd && !spec_ctrl)
10299                 return false;
10300
10301         page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->msr_bitmap);
10302         if (is_error_page(page))
10303                 return false;
10304
10305         msr_bitmap_l1 = (unsigned long *)kmap(page);
10306         if (nested_cpu_has_apic_reg_virt(vmcs12)) {
10307                 /*
10308                  * L0 need not intercept reads for MSRs between 0x800 and 0x8ff, it
10309                  * just lets the processor take the value from the virtual-APIC page;
10310                  * take those 256 bits directly from the L1 bitmap.
10311                  */
10312                 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
10313                         unsigned word = msr / BITS_PER_LONG;
10314                         msr_bitmap_l0[word] = msr_bitmap_l1[word];
10315                         msr_bitmap_l0[word + (0x800 / sizeof(long))] = ~0;
10316                 }
10317         } else {
10318                 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
10319                         unsigned word = msr / BITS_PER_LONG;
10320                         msr_bitmap_l0[word] = ~0;
10321                         msr_bitmap_l0[word + (0x800 / sizeof(long))] = ~0;
10322                 }
10323         }
10324
10325         nested_vmx_disable_intercept_for_msr(
10326                 msr_bitmap_l1, msr_bitmap_l0,
10327                 X2APIC_MSR(APIC_TASKPRI),
10328                 MSR_TYPE_W);
10329
10330         if (nested_cpu_has_vid(vmcs12)) {
10331                 nested_vmx_disable_intercept_for_msr(
10332                         msr_bitmap_l1, msr_bitmap_l0,
10333                         X2APIC_MSR(APIC_EOI),
10334                         MSR_TYPE_W);
10335                 nested_vmx_disable_intercept_for_msr(
10336                         msr_bitmap_l1, msr_bitmap_l0,
10337                         X2APIC_MSR(APIC_SELF_IPI),
10338                         MSR_TYPE_W);
10339         }
10340
10341         if (spec_ctrl)
10342                 nested_vmx_disable_intercept_for_msr(
10343                                         msr_bitmap_l1, msr_bitmap_l0,
10344                                         MSR_IA32_SPEC_CTRL,
10345                                         MSR_TYPE_R | MSR_TYPE_W);
10346
10347         if (pred_cmd)
10348                 nested_vmx_disable_intercept_for_msr(
10349                                         msr_bitmap_l1, msr_bitmap_l0,
10350                                         MSR_IA32_PRED_CMD,
10351                                         MSR_TYPE_W);
10352
10353         kunmap(page);
10354         kvm_release_page_clean(page);
10355
10356         return true;
10357 }
10358
10359 static int nested_vmx_check_apicv_controls(struct kvm_vcpu *vcpu,
10360                                            struct vmcs12 *vmcs12)
10361 {
10362         if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
10363             !nested_cpu_has_apic_reg_virt(vmcs12) &&
10364             !nested_cpu_has_vid(vmcs12) &&
10365             !nested_cpu_has_posted_intr(vmcs12))
10366                 return 0;
10367
10368         /*
10369          * If virtualize x2apic mode is enabled,
10370          * virtualize apic access must be disabled.
10371          */
10372         if (nested_cpu_has_virt_x2apic_mode(vmcs12) &&
10373             nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
10374                 return -EINVAL;
10375
10376         /*
10377          * If virtual interrupt delivery is enabled,
10378          * we must exit on external interrupts.
10379          */
10380         if (nested_cpu_has_vid(vmcs12) &&
10381            !nested_exit_on_intr(vcpu))
10382                 return -EINVAL;
10383
10384         /*
10385          * bits 15:8 should be zero in posted_intr_nv,
10386          * the descriptor address has been already checked
10387          * in nested_get_vmcs12_pages.
10388          */
10389         if (nested_cpu_has_posted_intr(vmcs12) &&
10390            (!nested_cpu_has_vid(vmcs12) ||
10391             !nested_exit_intr_ack_set(vcpu) ||
10392             vmcs12->posted_intr_nv & 0xff00))
10393                 return -EINVAL;
10394
10395         /* tpr shadow is needed by all apicv features. */
10396         if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
10397                 return -EINVAL;
10398
10399         return 0;
10400 }
10401
10402 static int nested_vmx_check_msr_switch(struct kvm_vcpu *vcpu,
10403                                        unsigned long count_field,
10404                                        unsigned long addr_field)
10405 {
10406         int maxphyaddr;
10407         u64 count, addr;
10408
10409         if (vmcs12_read_any(vcpu, count_field, &count) ||
10410             vmcs12_read_any(vcpu, addr_field, &addr)) {
10411                 WARN_ON(1);
10412                 return -EINVAL;
10413         }
10414         if (count == 0)
10415                 return 0;
10416         maxphyaddr = cpuid_maxphyaddr(vcpu);
10417         if (!IS_ALIGNED(addr, 16) || addr >> maxphyaddr ||
10418             (addr + count * sizeof(struct vmx_msr_entry) - 1) >> maxphyaddr) {
10419                 pr_debug_ratelimited(
10420                         "nVMX: invalid MSR switch (0x%lx, %d, %llu, 0x%08llx)",
10421                         addr_field, maxphyaddr, count, addr);
10422                 return -EINVAL;
10423         }
10424         return 0;
10425 }
10426
10427 static int nested_vmx_check_msr_switch_controls(struct kvm_vcpu *vcpu,
10428                                                 struct vmcs12 *vmcs12)
10429 {
10430         if (vmcs12->vm_exit_msr_load_count == 0 &&
10431             vmcs12->vm_exit_msr_store_count == 0 &&
10432             vmcs12->vm_entry_msr_load_count == 0)
10433                 return 0; /* Fast path */
10434         if (nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_LOAD_COUNT,
10435                                         VM_EXIT_MSR_LOAD_ADDR) ||
10436             nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_STORE_COUNT,
10437                                         VM_EXIT_MSR_STORE_ADDR) ||
10438             nested_vmx_check_msr_switch(vcpu, VM_ENTRY_MSR_LOAD_COUNT,
10439                                         VM_ENTRY_MSR_LOAD_ADDR))
10440                 return -EINVAL;
10441         return 0;
10442 }
10443
10444 static int nested_vmx_check_pml_controls(struct kvm_vcpu *vcpu,
10445                                          struct vmcs12 *vmcs12)
10446 {
10447         u64 address = vmcs12->pml_address;
10448         int maxphyaddr = cpuid_maxphyaddr(vcpu);
10449
10450         if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_PML)) {
10451                 if (!nested_cpu_has_ept(vmcs12) ||
10452                     !IS_ALIGNED(address, 4096)  ||
10453                     address >> maxphyaddr)
10454                         return -EINVAL;
10455         }
10456
10457         return 0;
10458 }
10459
10460 static int nested_vmx_msr_check_common(struct kvm_vcpu *vcpu,
10461                                        struct vmx_msr_entry *e)
10462 {
10463         /* x2APIC MSR accesses are not allowed */
10464         if (vcpu->arch.apic_base & X2APIC_ENABLE && e->index >> 8 == 0x8)
10465                 return -EINVAL;
10466         if (e->index == MSR_IA32_UCODE_WRITE || /* SDM Table 35-2 */
10467             e->index == MSR_IA32_UCODE_REV)
10468                 return -EINVAL;
10469         if (e->reserved != 0)
10470                 return -EINVAL;
10471         return 0;
10472 }
10473
10474 static int nested_vmx_load_msr_check(struct kvm_vcpu *vcpu,
10475                                      struct vmx_msr_entry *e)
10476 {
10477         if (e->index == MSR_FS_BASE ||
10478             e->index == MSR_GS_BASE ||
10479             e->index == MSR_IA32_SMM_MONITOR_CTL || /* SMM is not supported */
10480             nested_vmx_msr_check_common(vcpu, e))
10481                 return -EINVAL;
10482         return 0;
10483 }
10484
10485 static int nested_vmx_store_msr_check(struct kvm_vcpu *vcpu,
10486                                       struct vmx_msr_entry *e)
10487 {
10488         if (e->index == MSR_IA32_SMBASE || /* SMM is not supported */
10489             nested_vmx_msr_check_common(vcpu, e))
10490                 return -EINVAL;
10491         return 0;
10492 }
10493
10494 /*
10495  * Load guest's/host's msr at nested entry/exit.
10496  * return 0 for success, entry index for failure.
10497  */
10498 static u32 nested_vmx_load_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
10499 {
10500         u32 i;
10501         struct vmx_msr_entry e;
10502         struct msr_data msr;
10503
10504         msr.host_initiated = false;
10505         for (i = 0; i < count; i++) {
10506                 if (kvm_vcpu_read_guest(vcpu, gpa + i * sizeof(e),
10507                                         &e, sizeof(e))) {
10508                         pr_debug_ratelimited(
10509                                 "%s cannot read MSR entry (%u, 0x%08llx)\n",
10510                                 __func__, i, gpa + i * sizeof(e));
10511                         goto fail;
10512                 }
10513                 if (nested_vmx_load_msr_check(vcpu, &e)) {
10514                         pr_debug_ratelimited(
10515                                 "%s check failed (%u, 0x%x, 0x%x)\n",
10516                                 __func__, i, e.index, e.reserved);
10517                         goto fail;
10518                 }
10519                 msr.index = e.index;
10520                 msr.data = e.value;
10521                 if (kvm_set_msr(vcpu, &msr)) {
10522                         pr_debug_ratelimited(
10523                                 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
10524                                 __func__, i, e.index, e.value);
10525                         goto fail;
10526                 }
10527         }
10528         return 0;
10529 fail:
10530         return i + 1;
10531 }
10532
10533 static int nested_vmx_store_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
10534 {
10535         u32 i;
10536         struct vmx_msr_entry e;
10537
10538         for (i = 0; i < count; i++) {
10539                 struct msr_data msr_info;
10540                 if (kvm_vcpu_read_guest(vcpu,
10541                                         gpa + i * sizeof(e),
10542                                         &e, 2 * sizeof(u32))) {
10543                         pr_debug_ratelimited(
10544                                 "%s cannot read MSR entry (%u, 0x%08llx)\n",
10545                                 __func__, i, gpa + i * sizeof(e));
10546                         return -EINVAL;
10547                 }
10548                 if (nested_vmx_store_msr_check(vcpu, &e)) {
10549                         pr_debug_ratelimited(
10550                                 "%s check failed (%u, 0x%x, 0x%x)\n",
10551                                 __func__, i, e.index, e.reserved);
10552                         return -EINVAL;
10553                 }
10554                 msr_info.host_initiated = false;
10555                 msr_info.index = e.index;
10556                 if (kvm_get_msr(vcpu, &msr_info)) {
10557                         pr_debug_ratelimited(
10558                                 "%s cannot read MSR (%u, 0x%x)\n",
10559                                 __func__, i, e.index);
10560                         return -EINVAL;
10561                 }
10562                 if (kvm_vcpu_write_guest(vcpu,
10563                                          gpa + i * sizeof(e) +
10564                                              offsetof(struct vmx_msr_entry, value),
10565                                          &msr_info.data, sizeof(msr_info.data))) {
10566                         pr_debug_ratelimited(
10567                                 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
10568                                 __func__, i, e.index, msr_info.data);
10569                         return -EINVAL;
10570                 }
10571         }
10572         return 0;
10573 }
10574
10575 static bool nested_cr3_valid(struct kvm_vcpu *vcpu, unsigned long val)
10576 {
10577         unsigned long invalid_mask;
10578
10579         invalid_mask = (~0ULL) << cpuid_maxphyaddr(vcpu);
10580         return (val & invalid_mask) == 0;
10581 }
10582
10583 /*
10584  * Load guest's/host's cr3 at nested entry/exit. nested_ept is true if we are
10585  * emulating VM entry into a guest with EPT enabled.
10586  * Returns 0 on success, 1 on failure. Invalid state exit qualification code
10587  * is assigned to entry_failure_code on failure.
10588  */
10589 static int nested_vmx_load_cr3(struct kvm_vcpu *vcpu, unsigned long cr3, bool nested_ept,
10590                                u32 *entry_failure_code)
10591 {
10592         if (cr3 != kvm_read_cr3(vcpu) || (!nested_ept && pdptrs_changed(vcpu))) {
10593                 if (!nested_cr3_valid(vcpu, cr3)) {
10594                         *entry_failure_code = ENTRY_FAIL_DEFAULT;
10595                         return 1;
10596                 }
10597
10598                 /*
10599                  * If PAE paging and EPT are both on, CR3 is not used by the CPU and
10600                  * must not be dereferenced.
10601                  */
10602                 if (!is_long_mode(vcpu) && is_pae(vcpu) && is_paging(vcpu) &&
10603                     !nested_ept) {
10604                         if (!load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3)) {
10605                                 *entry_failure_code = ENTRY_FAIL_PDPTE;
10606                                 return 1;
10607                         }
10608                 }
10609
10610                 vcpu->arch.cr3 = cr3;
10611                 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
10612         }
10613
10614         kvm_mmu_reset_context(vcpu);
10615         return 0;
10616 }
10617
10618 static void prepare_vmcs02_full(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
10619                                bool from_vmentry)
10620 {
10621         struct vcpu_vmx *vmx = to_vmx(vcpu);
10622
10623         vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
10624         vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
10625         vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
10626         vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
10627         vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
10628         vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
10629         vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
10630         vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
10631         vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
10632         vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
10633         vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
10634         vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
10635         vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
10636         vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
10637         vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
10638         vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
10639         vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
10640         vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
10641         vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
10642         vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
10643         vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
10644         vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
10645         vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
10646         vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
10647         vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
10648         vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
10649         vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
10650         vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
10651         vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
10652         vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
10653         vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
10654
10655         vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
10656         vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
10657                 vmcs12->guest_pending_dbg_exceptions);
10658         vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
10659         vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
10660
10661         if (nested_cpu_has_xsaves(vmcs12))
10662                 vmcs_write64(XSS_EXIT_BITMAP, vmcs12->xss_exit_bitmap);
10663         vmcs_write64(VMCS_LINK_POINTER, -1ull);
10664
10665         if (cpu_has_vmx_posted_intr())
10666                 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_NESTED_VECTOR);
10667
10668         /*
10669          * Whether page-faults are trapped is determined by a combination of
10670          * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.
10671          * If enable_ept, L0 doesn't care about page faults and we should
10672          * set all of these to L1's desires. However, if !enable_ept, L0 does
10673          * care about (at least some) page faults, and because it is not easy
10674          * (if at all possible?) to merge L0 and L1's desires, we simply ask
10675          * to exit on each and every L2 page fault. This is done by setting
10676          * MASK=MATCH=0 and (see below) EB.PF=1.
10677          * Note that below we don't need special code to set EB.PF beyond the
10678          * "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
10679          * vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
10680          * !enable_ept, EB.PF is 1, so the "or" will always be 1.
10681          */
10682         vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK,
10683                 enable_ept ? vmcs12->page_fault_error_code_mask : 0);
10684         vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
10685                 enable_ept ? vmcs12->page_fault_error_code_match : 0);
10686
10687         /* All VMFUNCs are currently emulated through L0 vmexits.  */
10688         if (cpu_has_vmx_vmfunc())
10689                 vmcs_write64(VM_FUNCTION_CONTROL, 0);
10690
10691         if (cpu_has_vmx_apicv()) {
10692                 vmcs_write64(EOI_EXIT_BITMAP0, vmcs12->eoi_exit_bitmap0);
10693                 vmcs_write64(EOI_EXIT_BITMAP1, vmcs12->eoi_exit_bitmap1);
10694                 vmcs_write64(EOI_EXIT_BITMAP2, vmcs12->eoi_exit_bitmap2);
10695                 vmcs_write64(EOI_EXIT_BITMAP3, vmcs12->eoi_exit_bitmap3);
10696         }
10697
10698         /*
10699          * Set host-state according to L0's settings (vmcs12 is irrelevant here)
10700          * Some constant fields are set here by vmx_set_constant_host_state().
10701          * Other fields are different per CPU, and will be set later when
10702          * vmx_vcpu_load() is called, and when vmx_save_host_state() is called.
10703          */
10704         vmx_set_constant_host_state(vmx);
10705
10706         /*
10707          * Set the MSR load/store lists to match L0's settings.
10708          */
10709         vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
10710         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
10711         vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host));
10712         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
10713         vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest));
10714
10715         set_cr4_guest_host_mask(vmx);
10716
10717         if (vmx_mpx_supported())
10718                 vmcs_write64(GUEST_BNDCFGS, vmcs12->guest_bndcfgs);
10719
10720         if (enable_vpid) {
10721                 if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02)
10722                         vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->nested.vpid02);
10723                 else
10724                         vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
10725         }
10726
10727         /*
10728          * L1 may access the L2's PDPTR, so save them to construct vmcs12
10729          */
10730         if (enable_ept) {
10731                 vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
10732                 vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
10733                 vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
10734                 vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
10735         }
10736
10737         if (cpu_has_vmx_msr_bitmap())
10738                 vmcs_write64(MSR_BITMAP, __pa(vmx->nested.vmcs02.msr_bitmap));
10739 }
10740
10741 /*
10742  * prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
10743  * L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
10744  * with L0's requirements for its guest (a.k.a. vmcs01), so we can run the L2
10745  * guest in a way that will both be appropriate to L1's requests, and our
10746  * needs. In addition to modifying the active vmcs (which is vmcs02), this
10747  * function also has additional necessary side-effects, like setting various
10748  * vcpu->arch fields.
10749  * Returns 0 on success, 1 on failure. Invalid state exit qualification code
10750  * is assigned to entry_failure_code on failure.
10751  */
10752 static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
10753                           bool from_vmentry, u32 *entry_failure_code)
10754 {
10755         struct vcpu_vmx *vmx = to_vmx(vcpu);
10756         u32 exec_control, vmcs12_exec_ctrl;
10757
10758         /*
10759          * First, the fields that are shadowed.  This must be kept in sync
10760          * with vmx_shadow_fields.h.
10761          */
10762
10763         vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
10764         vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
10765         vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
10766         vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
10767         vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
10768
10769         /*
10770          * Not in vmcs02: GUEST_PML_INDEX, HOST_FS_SELECTOR, HOST_GS_SELECTOR,
10771          * HOST_FS_BASE, HOST_GS_BASE.
10772          */
10773
10774         if (from_vmentry &&
10775             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS)) {
10776                 kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
10777                 vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
10778         } else {
10779                 kvm_set_dr(vcpu, 7, vcpu->arch.dr7);
10780                 vmcs_write64(GUEST_IA32_DEBUGCTL, vmx->nested.vmcs01_debugctl);
10781         }
10782         if (from_vmentry) {
10783                 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
10784                              vmcs12->vm_entry_intr_info_field);
10785                 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
10786                              vmcs12->vm_entry_exception_error_code);
10787                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
10788                              vmcs12->vm_entry_instruction_len);
10789                 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
10790                              vmcs12->guest_interruptibility_info);
10791                 vmx->loaded_vmcs->nmi_known_unmasked =
10792                         !(vmcs12->guest_interruptibility_info & GUEST_INTR_STATE_NMI);
10793         } else {
10794                 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
10795         }
10796         vmx_set_rflags(vcpu, vmcs12->guest_rflags);
10797
10798         exec_control = vmcs12->pin_based_vm_exec_control;
10799
10800         /* Preemption timer setting is only taken from vmcs01.  */
10801         exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
10802         exec_control |= vmcs_config.pin_based_exec_ctrl;
10803         if (vmx->hv_deadline_tsc == -1)
10804                 exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
10805
10806         /* Posted interrupts setting is only taken from vmcs12.  */
10807         if (nested_cpu_has_posted_intr(vmcs12)) {
10808                 vmx->nested.posted_intr_nv = vmcs12->posted_intr_nv;
10809                 vmx->nested.pi_pending = false;
10810         } else {
10811                 exec_control &= ~PIN_BASED_POSTED_INTR;
10812         }
10813
10814         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, exec_control);
10815
10816         vmx->nested.preemption_timer_expired = false;
10817         if (nested_cpu_has_preemption_timer(vmcs12))
10818                 vmx_start_preemption_timer(vcpu);
10819
10820         if (cpu_has_secondary_exec_ctrls()) {
10821                 exec_control = vmx->secondary_exec_control;
10822
10823                 /* Take the following fields only from vmcs12 */
10824                 exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
10825                                   SECONDARY_EXEC_ENABLE_INVPCID |
10826                                   SECONDARY_EXEC_RDTSCP |
10827                                   SECONDARY_EXEC_XSAVES |
10828                                   SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
10829                                   SECONDARY_EXEC_APIC_REGISTER_VIRT |
10830                                   SECONDARY_EXEC_ENABLE_VMFUNC);
10831                 if (nested_cpu_has(vmcs12,
10832                                    CPU_BASED_ACTIVATE_SECONDARY_CONTROLS)) {
10833                         vmcs12_exec_ctrl = vmcs12->secondary_vm_exec_control &
10834                                 ~SECONDARY_EXEC_ENABLE_PML;
10835                         exec_control |= vmcs12_exec_ctrl;
10836                 }
10837
10838                 if (exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
10839                         vmcs_write16(GUEST_INTR_STATUS,
10840                                 vmcs12->guest_intr_status);
10841
10842                 /*
10843                  * Write an illegal value to APIC_ACCESS_ADDR. Later,
10844                  * nested_get_vmcs12_pages will either fix it up or
10845                  * remove the VM execution control.
10846                  */
10847                 if (exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
10848                         vmcs_write64(APIC_ACCESS_ADDR, -1ull);
10849
10850                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
10851         }
10852
10853         /*
10854          * HOST_RSP is normally set correctly in vmx_vcpu_run() just before
10855          * entry, but only if the current (host) sp changed from the value
10856          * we wrote last (vmx->host_rsp). This cache is no longer relevant
10857          * if we switch vmcs, and rather than hold a separate cache per vmcs,
10858          * here we just force the write to happen on entry.
10859          */
10860         vmx->host_rsp = 0;
10861
10862         exec_control = vmx_exec_control(vmx); /* L0's desires */
10863         exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
10864         exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
10865         exec_control &= ~CPU_BASED_TPR_SHADOW;
10866         exec_control |= vmcs12->cpu_based_vm_exec_control;
10867
10868         /*
10869          * Write an illegal value to VIRTUAL_APIC_PAGE_ADDR. Later, if
10870          * nested_get_vmcs12_pages can't fix it up, the illegal value
10871          * will result in a VM entry failure.
10872          */
10873         if (exec_control & CPU_BASED_TPR_SHADOW) {
10874                 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, -1ull);
10875                 vmcs_write32(TPR_THRESHOLD, vmcs12->tpr_threshold);
10876         } else {
10877 #ifdef CONFIG_X86_64
10878                 exec_control |= CPU_BASED_CR8_LOAD_EXITING |
10879                                 CPU_BASED_CR8_STORE_EXITING;
10880 #endif
10881         }
10882
10883         /*
10884          * A vmexit (to either L1 hypervisor or L0 userspace) is always needed
10885          * for I/O port accesses.
10886          */
10887         exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
10888         exec_control |= CPU_BASED_UNCOND_IO_EXITING;
10889
10890         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
10891
10892         /* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
10893          * bitwise-or of what L1 wants to trap for L2, and what we want to
10894          * trap. Note that CR0.TS also needs updating - we do this later.
10895          */
10896         update_exception_bitmap(vcpu);
10897         vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
10898         vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
10899
10900         /* L2->L1 exit controls are emulated - the hardware exit is to L0 so
10901          * we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER
10902          * bits are further modified by vmx_set_efer() below.
10903          */
10904         vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);
10905
10906         /* vmcs12's VM_ENTRY_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE are
10907          * emulated by vmx_set_efer(), below.
10908          */
10909         vm_entry_controls_init(vmx, 
10910                 (vmcs12->vm_entry_controls & ~VM_ENTRY_LOAD_IA32_EFER &
10911                         ~VM_ENTRY_IA32E_MODE) |
10912                 (vmcs_config.vmentry_ctrl & ~VM_ENTRY_IA32E_MODE));
10913
10914         if (from_vmentry &&
10915             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT)) {
10916                 vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
10917                 vcpu->arch.pat = vmcs12->guest_ia32_pat;
10918         } else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
10919                 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
10920         }
10921
10922         if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
10923                 vmcs_write64(TSC_OFFSET,
10924                         vcpu->arch.tsc_offset + vmcs12->tsc_offset);
10925         else
10926                 vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
10927         if (kvm_has_tsc_control)
10928                 decache_tsc_multiplier(vmx);
10929
10930         if (enable_vpid) {
10931                 /*
10932                  * There is no direct mapping between vpid02 and vpid12, the
10933                  * vpid02 is per-vCPU for L0 and reused while the value of
10934                  * vpid12 is changed w/ one invvpid during nested vmentry.
10935                  * The vpid12 is allocated by L1 for L2, so it will not
10936                  * influence global bitmap(for vpid01 and vpid02 allocation)
10937                  * even if spawn a lot of nested vCPUs.
10938                  */
10939                 if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02) {
10940                         if (vmcs12->virtual_processor_id != vmx->nested.last_vpid) {
10941                                 vmx->nested.last_vpid = vmcs12->virtual_processor_id;
10942                                 __vmx_flush_tlb(vcpu, to_vmx(vcpu)->nested.vpid02, true);
10943                         }
10944                 } else {
10945                         vmx_flush_tlb(vcpu, true);
10946                 }
10947         }
10948
10949         if (enable_pml) {
10950                 /*
10951                  * Conceptually we want to copy the PML address and index from
10952                  * vmcs01 here, and then back to vmcs01 on nested vmexit. But,
10953                  * since we always flush the log on each vmexit, this happens
10954                  * to be equivalent to simply resetting the fields in vmcs02.
10955                  */
10956                 ASSERT(vmx->pml_pg);
10957                 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
10958                 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
10959         }
10960
10961         if (nested_cpu_has_ept(vmcs12)) {
10962                 if (nested_ept_init_mmu_context(vcpu)) {
10963                         *entry_failure_code = ENTRY_FAIL_DEFAULT;
10964                         return 1;
10965                 }
10966         } else if (nested_cpu_has2(vmcs12,
10967                                    SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
10968                 vmx_flush_tlb_ept_only(vcpu);
10969         }
10970
10971         /*
10972          * This sets GUEST_CR0 to vmcs12->guest_cr0, possibly modifying those
10973          * bits which we consider mandatory enabled.
10974          * The CR0_READ_SHADOW is what L2 should have expected to read given
10975          * the specifications by L1; It's not enough to take
10976          * vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we
10977          * have more bits than L1 expected.
10978          */
10979         vmx_set_cr0(vcpu, vmcs12->guest_cr0);
10980         vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
10981
10982         vmx_set_cr4(vcpu, vmcs12->guest_cr4);
10983         vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
10984
10985         if (from_vmentry &&
10986             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER))
10987                 vcpu->arch.efer = vmcs12->guest_ia32_efer;
10988         else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
10989                 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
10990         else
10991                 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
10992         /* Note: modifies VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
10993         vmx_set_efer(vcpu, vcpu->arch.efer);
10994
10995         if (vmx->nested.dirty_vmcs12) {
10996                 prepare_vmcs02_full(vcpu, vmcs12, from_vmentry);
10997                 vmx->nested.dirty_vmcs12 = false;
10998         }
10999
11000         /*
11001          * Guest state is invalid and unrestricted guest is disabled,
11002          * which means L1 attempted VMEntry to L2 with invalid state.
11003          * Fail the VMEntry.
11004          */
11005         if (vmx->emulation_required)
11006                 return 1;
11007
11008         /* Shadow page tables on either EPT or shadow page tables. */
11009         if (nested_vmx_load_cr3(vcpu, vmcs12->guest_cr3, nested_cpu_has_ept(vmcs12),
11010                                 entry_failure_code))
11011                 return 1;
11012
11013         if (!enable_ept)
11014                 vcpu->arch.walk_mmu->inject_page_fault = vmx_inject_page_fault_nested;
11015
11016         kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->guest_rsp);
11017         kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->guest_rip);
11018         return 0;
11019 }
11020
11021 static int nested_vmx_check_nmi_controls(struct vmcs12 *vmcs12)
11022 {
11023         if (!nested_cpu_has_nmi_exiting(vmcs12) &&
11024             nested_cpu_has_virtual_nmis(vmcs12))
11025                 return -EINVAL;
11026
11027         if (!nested_cpu_has_virtual_nmis(vmcs12) &&
11028             nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING))
11029                 return -EINVAL;
11030
11031         return 0;
11032 }
11033
11034 static int check_vmentry_prereqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
11035 {
11036         struct vcpu_vmx *vmx = to_vmx(vcpu);
11037
11038         if (vmcs12->guest_activity_state != GUEST_ACTIVITY_ACTIVE &&
11039             vmcs12->guest_activity_state != GUEST_ACTIVITY_HLT)
11040                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11041
11042         if (nested_vmx_check_io_bitmap_controls(vcpu, vmcs12))
11043                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11044
11045         if (nested_vmx_check_msr_bitmap_controls(vcpu, vmcs12))
11046                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11047
11048         if (nested_vmx_check_tpr_shadow_controls(vcpu, vmcs12))
11049                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11050
11051         if (nested_vmx_check_apicv_controls(vcpu, vmcs12))
11052                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11053
11054         if (nested_vmx_check_msr_switch_controls(vcpu, vmcs12))
11055                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11056
11057         if (nested_vmx_check_pml_controls(vcpu, vmcs12))
11058                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11059
11060         if (!vmx_control_verify(vmcs12->cpu_based_vm_exec_control,
11061                                 vmx->nested.msrs.procbased_ctls_low,
11062                                 vmx->nested.msrs.procbased_ctls_high) ||
11063             (nested_cpu_has(vmcs12, CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
11064              !vmx_control_verify(vmcs12->secondary_vm_exec_control,
11065                                  vmx->nested.msrs.secondary_ctls_low,
11066                                  vmx->nested.msrs.secondary_ctls_high)) ||
11067             !vmx_control_verify(vmcs12->pin_based_vm_exec_control,
11068                                 vmx->nested.msrs.pinbased_ctls_low,
11069                                 vmx->nested.msrs.pinbased_ctls_high) ||
11070             !vmx_control_verify(vmcs12->vm_exit_controls,
11071                                 vmx->nested.msrs.exit_ctls_low,
11072                                 vmx->nested.msrs.exit_ctls_high) ||
11073             !vmx_control_verify(vmcs12->vm_entry_controls,
11074                                 vmx->nested.msrs.entry_ctls_low,
11075                                 vmx->nested.msrs.entry_ctls_high))
11076                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11077
11078         if (nested_vmx_check_nmi_controls(vmcs12))
11079                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11080
11081         if (nested_cpu_has_vmfunc(vmcs12)) {
11082                 if (vmcs12->vm_function_control &
11083                     ~vmx->nested.msrs.vmfunc_controls)
11084                         return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11085
11086                 if (nested_cpu_has_eptp_switching(vmcs12)) {
11087                         if (!nested_cpu_has_ept(vmcs12) ||
11088                             !page_address_valid(vcpu, vmcs12->eptp_list_address))
11089                                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11090                 }
11091         }
11092
11093         if (vmcs12->cr3_target_count > nested_cpu_vmx_misc_cr3_count(vcpu))
11094                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11095
11096         if (!nested_host_cr0_valid(vcpu, vmcs12->host_cr0) ||
11097             !nested_host_cr4_valid(vcpu, vmcs12->host_cr4) ||
11098             !nested_cr3_valid(vcpu, vmcs12->host_cr3))
11099                 return VMXERR_ENTRY_INVALID_HOST_STATE_FIELD;
11100
11101         return 0;
11102 }
11103
11104 static int check_vmentry_postreqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
11105                                   u32 *exit_qual)
11106 {
11107         bool ia32e;
11108
11109         *exit_qual = ENTRY_FAIL_DEFAULT;
11110
11111         if (!nested_guest_cr0_valid(vcpu, vmcs12->guest_cr0) ||
11112             !nested_guest_cr4_valid(vcpu, vmcs12->guest_cr4))
11113                 return 1;
11114
11115         if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_SHADOW_VMCS) &&
11116             vmcs12->vmcs_link_pointer != -1ull) {
11117                 *exit_qual = ENTRY_FAIL_VMCS_LINK_PTR;
11118                 return 1;
11119         }
11120
11121         /*
11122          * If the load IA32_EFER VM-entry control is 1, the following checks
11123          * are performed on the field for the IA32_EFER MSR:
11124          * - Bits reserved in the IA32_EFER MSR must be 0.
11125          * - Bit 10 (corresponding to IA32_EFER.LMA) must equal the value of
11126          *   the IA-32e mode guest VM-exit control. It must also be identical
11127          *   to bit 8 (LME) if bit 31 in the CR0 field (corresponding to
11128          *   CR0.PG) is 1.
11129          */
11130         if (to_vmx(vcpu)->nested.nested_run_pending &&
11131             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)) {
11132                 ia32e = (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) != 0;
11133                 if (!kvm_valid_efer(vcpu, vmcs12->guest_ia32_efer) ||
11134                     ia32e != !!(vmcs12->guest_ia32_efer & EFER_LMA) ||
11135                     ((vmcs12->guest_cr0 & X86_CR0_PG) &&
11136                      ia32e != !!(vmcs12->guest_ia32_efer & EFER_LME)))
11137                         return 1;
11138         }
11139
11140         /*
11141          * If the load IA32_EFER VM-exit control is 1, bits reserved in the
11142          * IA32_EFER MSR must be 0 in the field for that register. In addition,
11143          * the values of the LMA and LME bits in the field must each be that of
11144          * the host address-space size VM-exit control.
11145          */
11146         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) {
11147                 ia32e = (vmcs12->vm_exit_controls &
11148                          VM_EXIT_HOST_ADDR_SPACE_SIZE) != 0;
11149                 if (!kvm_valid_efer(vcpu, vmcs12->host_ia32_efer) ||
11150                     ia32e != !!(vmcs12->host_ia32_efer & EFER_LMA) ||
11151                     ia32e != !!(vmcs12->host_ia32_efer & EFER_LME))
11152                         return 1;
11153         }
11154
11155         if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS) &&
11156                 (is_noncanonical_address(vmcs12->guest_bndcfgs & PAGE_MASK, vcpu) ||
11157                 (vmcs12->guest_bndcfgs & MSR_IA32_BNDCFGS_RSVD)))
11158                         return 1;
11159
11160         return 0;
11161 }
11162
11163 static int enter_vmx_non_root_mode(struct kvm_vcpu *vcpu, bool from_vmentry)
11164 {
11165         struct vcpu_vmx *vmx = to_vmx(vcpu);
11166         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11167         u32 msr_entry_idx;
11168         u32 exit_qual;
11169
11170         enter_guest_mode(vcpu);
11171
11172         if (!(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS))
11173                 vmx->nested.vmcs01_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
11174
11175         vmx_switch_vmcs(vcpu, &vmx->nested.vmcs02);
11176         vmx_segment_cache_clear(vmx);
11177
11178         if (prepare_vmcs02(vcpu, vmcs12, from_vmentry, &exit_qual)) {
11179                 leave_guest_mode(vcpu);
11180                 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
11181                 nested_vmx_entry_failure(vcpu, vmcs12,
11182                                          EXIT_REASON_INVALID_STATE, exit_qual);
11183                 return 1;
11184         }
11185
11186         nested_get_vmcs12_pages(vcpu, vmcs12);
11187
11188         msr_entry_idx = nested_vmx_load_msr(vcpu,
11189                                             vmcs12->vm_entry_msr_load_addr,
11190                                             vmcs12->vm_entry_msr_load_count);
11191         if (msr_entry_idx) {
11192                 leave_guest_mode(vcpu);
11193                 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
11194                 nested_vmx_entry_failure(vcpu, vmcs12,
11195                                 EXIT_REASON_MSR_LOAD_FAIL, msr_entry_idx);
11196                 return 1;
11197         }
11198
11199         /*
11200          * Note no nested_vmx_succeed or nested_vmx_fail here. At this point
11201          * we are no longer running L1, and VMLAUNCH/VMRESUME has not yet
11202          * returned as far as L1 is concerned. It will only return (and set
11203          * the success flag) when L2 exits (see nested_vmx_vmexit()).
11204          */
11205         return 0;
11206 }
11207
11208 /*
11209  * nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1
11210  * for running an L2 nested guest.
11211  */
11212 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
11213 {
11214         struct vmcs12 *vmcs12;
11215         struct vcpu_vmx *vmx = to_vmx(vcpu);
11216         u32 interrupt_shadow = vmx_get_interrupt_shadow(vcpu);
11217         u32 exit_qual;
11218         int ret;
11219
11220         if (!nested_vmx_check_permission(vcpu))
11221                 return 1;
11222
11223         if (!nested_vmx_check_vmcs12(vcpu))
11224                 goto out;
11225
11226         vmcs12 = get_vmcs12(vcpu);
11227
11228         if (enable_shadow_vmcs)
11229                 copy_shadow_to_vmcs12(vmx);
11230
11231         /*
11232          * The nested entry process starts with enforcing various prerequisites
11233          * on vmcs12 as required by the Intel SDM, and act appropriately when
11234          * they fail: As the SDM explains, some conditions should cause the
11235          * instruction to fail, while others will cause the instruction to seem
11236          * to succeed, but return an EXIT_REASON_INVALID_STATE.
11237          * To speed up the normal (success) code path, we should avoid checking
11238          * for misconfigurations which will anyway be caught by the processor
11239          * when using the merged vmcs02.
11240          */
11241         if (interrupt_shadow & KVM_X86_SHADOW_INT_MOV_SS) {
11242                 nested_vmx_failValid(vcpu,
11243                                      VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS);
11244                 goto out;
11245         }
11246
11247         if (vmcs12->launch_state == launch) {
11248                 nested_vmx_failValid(vcpu,
11249                         launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
11250                                : VMXERR_VMRESUME_NONLAUNCHED_VMCS);
11251                 goto out;
11252         }
11253
11254         ret = check_vmentry_prereqs(vcpu, vmcs12);
11255         if (ret) {
11256                 nested_vmx_failValid(vcpu, ret);
11257                 goto out;
11258         }
11259
11260         /*
11261          * After this point, the trap flag no longer triggers a singlestep trap
11262          * on the vm entry instructions; don't call kvm_skip_emulated_instruction.
11263          * This is not 100% correct; for performance reasons, we delegate most
11264          * of the checks on host state to the processor.  If those fail,
11265          * the singlestep trap is missed.
11266          */
11267         skip_emulated_instruction(vcpu);
11268
11269         ret = check_vmentry_postreqs(vcpu, vmcs12, &exit_qual);
11270         if (ret) {
11271                 nested_vmx_entry_failure(vcpu, vmcs12,
11272                                          EXIT_REASON_INVALID_STATE, exit_qual);
11273                 return 1;
11274         }
11275
11276         /*
11277          * We're finally done with prerequisite checking, and can start with
11278          * the nested entry.
11279          */
11280
11281         ret = enter_vmx_non_root_mode(vcpu, true);
11282         if (ret)
11283                 return ret;
11284
11285         /*
11286          * If we're entering a halted L2 vcpu and the L2 vcpu won't be woken
11287          * by event injection, halt vcpu.
11288          */
11289         if ((vmcs12->guest_activity_state == GUEST_ACTIVITY_HLT) &&
11290             !(vmcs12->vm_entry_intr_info_field & INTR_INFO_VALID_MASK))
11291                 return kvm_vcpu_halt(vcpu);
11292
11293         vmx->nested.nested_run_pending = 1;
11294
11295         return 1;
11296
11297 out:
11298         return kvm_skip_emulated_instruction(vcpu);
11299 }
11300
11301 /*
11302  * On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
11303  * because L2 may have changed some cr0 bits directly (CRO_GUEST_HOST_MASK).
11304  * This function returns the new value we should put in vmcs12.guest_cr0.
11305  * It's not enough to just return the vmcs02 GUEST_CR0. Rather,
11306  *  1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
11307  *     available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0
11308  *     didn't trap the bit, because if L1 did, so would L0).
11309  *  2. Bits that L1 asked to trap (and therefore L0 also did) could not have
11310  *     been modified by L2, and L1 knows it. So just leave the old value of
11311  *     the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0
11312  *     isn't relevant, because if L0 traps this bit it can set it to anything.
11313  *  3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have
11314  *     changed these bits, and therefore they need to be updated, but L0
11315  *     didn't necessarily allow them to be changed in GUEST_CR0 - and rather
11316  *     put them in vmcs02 CR0_READ_SHADOW. So take these bits from there.
11317  */
11318 static inline unsigned long
11319 vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
11320 {
11321         return
11322         /*1*/   (vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) |
11323         /*2*/   (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) |
11324         /*3*/   (vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask |
11325                         vcpu->arch.cr0_guest_owned_bits));
11326 }
11327
11328 static inline unsigned long
11329 vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
11330 {
11331         return
11332         /*1*/   (vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) |
11333         /*2*/   (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) |
11334         /*3*/   (vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask |
11335                         vcpu->arch.cr4_guest_owned_bits));
11336 }
11337
11338 static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
11339                                        struct vmcs12 *vmcs12)
11340 {
11341         u32 idt_vectoring;
11342         unsigned int nr;
11343
11344         if (vcpu->arch.exception.injected) {
11345                 nr = vcpu->arch.exception.nr;
11346                 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
11347
11348                 if (kvm_exception_is_soft(nr)) {
11349                         vmcs12->vm_exit_instruction_len =
11350                                 vcpu->arch.event_exit_inst_len;
11351                         idt_vectoring |= INTR_TYPE_SOFT_EXCEPTION;
11352                 } else
11353                         idt_vectoring |= INTR_TYPE_HARD_EXCEPTION;
11354
11355                 if (vcpu->arch.exception.has_error_code) {
11356                         idt_vectoring |= VECTORING_INFO_DELIVER_CODE_MASK;
11357                         vmcs12->idt_vectoring_error_code =
11358                                 vcpu->arch.exception.error_code;
11359                 }
11360
11361                 vmcs12->idt_vectoring_info_field = idt_vectoring;
11362         } else if (vcpu->arch.nmi_injected) {
11363                 vmcs12->idt_vectoring_info_field =
11364                         INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR;
11365         } else if (vcpu->arch.interrupt.pending) {
11366                 nr = vcpu->arch.interrupt.nr;
11367                 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
11368
11369                 if (vcpu->arch.interrupt.soft) {
11370                         idt_vectoring |= INTR_TYPE_SOFT_INTR;
11371                         vmcs12->vm_entry_instruction_len =
11372                                 vcpu->arch.event_exit_inst_len;
11373                 } else
11374                         idt_vectoring |= INTR_TYPE_EXT_INTR;
11375
11376                 vmcs12->idt_vectoring_info_field = idt_vectoring;
11377         }
11378 }
11379
11380 static int vmx_check_nested_events(struct kvm_vcpu *vcpu, bool external_intr)
11381 {
11382         struct vcpu_vmx *vmx = to_vmx(vcpu);
11383         unsigned long exit_qual;
11384         bool block_nested_events =
11385             vmx->nested.nested_run_pending || kvm_event_needs_reinjection(vcpu);
11386
11387         if (vcpu->arch.exception.pending &&
11388                 nested_vmx_check_exception(vcpu, &exit_qual)) {
11389                 if (block_nested_events)
11390                         return -EBUSY;
11391                 nested_vmx_inject_exception_vmexit(vcpu, exit_qual);
11392                 return 0;
11393         }
11394
11395         if (nested_cpu_has_preemption_timer(get_vmcs12(vcpu)) &&
11396             vmx->nested.preemption_timer_expired) {
11397                 if (block_nested_events)
11398                         return -EBUSY;
11399                 nested_vmx_vmexit(vcpu, EXIT_REASON_PREEMPTION_TIMER, 0, 0);
11400                 return 0;
11401         }
11402
11403         if (vcpu->arch.nmi_pending && nested_exit_on_nmi(vcpu)) {
11404                 if (block_nested_events)
11405                         return -EBUSY;
11406                 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
11407                                   NMI_VECTOR | INTR_TYPE_NMI_INTR |
11408                                   INTR_INFO_VALID_MASK, 0);
11409                 /*
11410                  * The NMI-triggered VM exit counts as injection:
11411                  * clear this one and block further NMIs.
11412                  */
11413                 vcpu->arch.nmi_pending = 0;
11414                 vmx_set_nmi_mask(vcpu, true);
11415                 return 0;
11416         }
11417
11418         if ((kvm_cpu_has_interrupt(vcpu) || external_intr) &&
11419             nested_exit_on_intr(vcpu)) {
11420                 if (block_nested_events)
11421                         return -EBUSY;
11422                 nested_vmx_vmexit(vcpu, EXIT_REASON_EXTERNAL_INTERRUPT, 0, 0);
11423                 return 0;
11424         }
11425
11426         vmx_complete_nested_posted_interrupt(vcpu);
11427         return 0;
11428 }
11429
11430 static u32 vmx_get_preemption_timer_value(struct kvm_vcpu *vcpu)
11431 {
11432         ktime_t remaining =
11433                 hrtimer_get_remaining(&to_vmx(vcpu)->nested.preemption_timer);
11434         u64 value;
11435
11436         if (ktime_to_ns(remaining) <= 0)
11437                 return 0;
11438
11439         value = ktime_to_ns(remaining) * vcpu->arch.virtual_tsc_khz;
11440         do_div(value, 1000000);
11441         return value >> VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
11442 }
11443
11444 /*
11445  * Update the guest state fields of vmcs12 to reflect changes that
11446  * occurred while L2 was running. (The "IA-32e mode guest" bit of the
11447  * VM-entry controls is also updated, since this is really a guest
11448  * state bit.)
11449  */
11450 static void sync_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
11451 {
11452         vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12);
11453         vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12);
11454
11455         vmcs12->guest_rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
11456         vmcs12->guest_rip = kvm_register_read(vcpu, VCPU_REGS_RIP);
11457         vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS);
11458
11459         vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR);
11460         vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR);
11461         vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR);
11462         vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR);
11463         vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR);
11464         vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR);
11465         vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR);
11466         vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR);
11467         vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT);
11468         vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT);
11469         vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT);
11470         vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT);
11471         vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT);
11472         vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT);
11473         vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT);
11474         vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT);
11475         vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT);
11476         vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT);
11477         vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES);
11478         vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES);
11479         vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES);
11480         vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES);
11481         vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES);
11482         vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES);
11483         vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES);
11484         vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES);
11485         vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE);
11486         vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE);
11487         vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE);
11488         vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE);
11489         vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE);
11490         vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE);
11491         vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE);
11492         vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE);
11493         vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE);
11494         vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE);
11495
11496         vmcs12->guest_interruptibility_info =
11497                 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
11498         vmcs12->guest_pending_dbg_exceptions =
11499                 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);
11500         if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
11501                 vmcs12->guest_activity_state = GUEST_ACTIVITY_HLT;
11502         else
11503                 vmcs12->guest_activity_state = GUEST_ACTIVITY_ACTIVE;
11504
11505         if (nested_cpu_has_preemption_timer(vmcs12)) {
11506                 if (vmcs12->vm_exit_controls &
11507                     VM_EXIT_SAVE_VMX_PREEMPTION_TIMER)
11508                         vmcs12->vmx_preemption_timer_value =
11509                                 vmx_get_preemption_timer_value(vcpu);
11510                 hrtimer_cancel(&to_vmx(vcpu)->nested.preemption_timer);
11511         }
11512
11513         /*
11514          * In some cases (usually, nested EPT), L2 is allowed to change its
11515          * own CR3 without exiting. If it has changed it, we must keep it.
11516          * Of course, if L0 is using shadow page tables, GUEST_CR3 was defined
11517          * by L0, not L1 or L2, so we mustn't unconditionally copy it to vmcs12.
11518          *
11519          * Additionally, restore L2's PDPTR to vmcs12.
11520          */
11521         if (enable_ept) {
11522                 vmcs12->guest_cr3 = vmcs_readl(GUEST_CR3);
11523                 vmcs12->guest_pdptr0 = vmcs_read64(GUEST_PDPTR0);
11524                 vmcs12->guest_pdptr1 = vmcs_read64(GUEST_PDPTR1);
11525                 vmcs12->guest_pdptr2 = vmcs_read64(GUEST_PDPTR2);
11526                 vmcs12->guest_pdptr3 = vmcs_read64(GUEST_PDPTR3);
11527         }
11528
11529         vmcs12->guest_linear_address = vmcs_readl(GUEST_LINEAR_ADDRESS);
11530
11531         if (nested_cpu_has_vid(vmcs12))
11532                 vmcs12->guest_intr_status = vmcs_read16(GUEST_INTR_STATUS);
11533
11534         vmcs12->vm_entry_controls =
11535                 (vmcs12->vm_entry_controls & ~VM_ENTRY_IA32E_MODE) |
11536                 (vm_entry_controls_get(to_vmx(vcpu)) & VM_ENTRY_IA32E_MODE);
11537
11538         if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_DEBUG_CONTROLS) {
11539                 kvm_get_dr(vcpu, 7, (unsigned long *)&vmcs12->guest_dr7);
11540                 vmcs12->guest_ia32_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
11541         }
11542
11543         /* TODO: These cannot have changed unless we have MSR bitmaps and
11544          * the relevant bit asks not to trap the change */
11545         if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
11546                 vmcs12->guest_ia32_pat = vmcs_read64(GUEST_IA32_PAT);
11547         if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_EFER)
11548                 vmcs12->guest_ia32_efer = vcpu->arch.efer;
11549         vmcs12->guest_sysenter_cs = vmcs_read32(GUEST_SYSENTER_CS);
11550         vmcs12->guest_sysenter_esp = vmcs_readl(GUEST_SYSENTER_ESP);
11551         vmcs12->guest_sysenter_eip = vmcs_readl(GUEST_SYSENTER_EIP);
11552         if (kvm_mpx_supported())
11553                 vmcs12->guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
11554 }
11555
11556 /*
11557  * prepare_vmcs12 is part of what we need to do when the nested L2 guest exits
11558  * and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12),
11559  * and this function updates it to reflect the changes to the guest state while
11560  * L2 was running (and perhaps made some exits which were handled directly by L0
11561  * without going back to L1), and to reflect the exit reason.
11562  * Note that we do not have to copy here all VMCS fields, just those that
11563  * could have changed by the L2 guest or the exit - i.e., the guest-state and
11564  * exit-information fields only. Other fields are modified by L1 with VMWRITE,
11565  * which already writes to vmcs12 directly.
11566  */
11567 static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
11568                            u32 exit_reason, u32 exit_intr_info,
11569                            unsigned long exit_qualification)
11570 {
11571         /* update guest state fields: */
11572         sync_vmcs12(vcpu, vmcs12);
11573
11574         /* update exit information fields: */
11575
11576         vmcs12->vm_exit_reason = exit_reason;
11577         vmcs12->exit_qualification = exit_qualification;
11578         vmcs12->vm_exit_intr_info = exit_intr_info;
11579
11580         vmcs12->idt_vectoring_info_field = 0;
11581         vmcs12->vm_exit_instruction_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
11582         vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
11583
11584         if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY)) {
11585                 vmcs12->launch_state = 1;
11586
11587                 /* vm_entry_intr_info_field is cleared on exit. Emulate this
11588                  * instead of reading the real value. */
11589                 vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK;
11590
11591                 /*
11592                  * Transfer the event that L0 or L1 may wanted to inject into
11593                  * L2 to IDT_VECTORING_INFO_FIELD.
11594                  */
11595                 vmcs12_save_pending_event(vcpu, vmcs12);
11596         }
11597
11598         /*
11599          * Drop what we picked up for L2 via vmx_complete_interrupts. It is
11600          * preserved above and would only end up incorrectly in L1.
11601          */
11602         vcpu->arch.nmi_injected = false;
11603         kvm_clear_exception_queue(vcpu);
11604         kvm_clear_interrupt_queue(vcpu);
11605 }
11606
11607 static void load_vmcs12_mmu_host_state(struct kvm_vcpu *vcpu,
11608                         struct vmcs12 *vmcs12)
11609 {
11610         u32 entry_failure_code;
11611
11612         nested_ept_uninit_mmu_context(vcpu);
11613
11614         /*
11615          * Only PDPTE load can fail as the value of cr3 was checked on entry and
11616          * couldn't have changed.
11617          */
11618         if (nested_vmx_load_cr3(vcpu, vmcs12->host_cr3, false, &entry_failure_code))
11619                 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_PDPTE_FAIL);
11620
11621         if (!enable_ept)
11622                 vcpu->arch.walk_mmu->inject_page_fault = kvm_inject_page_fault;
11623 }
11624
11625 /*
11626  * A part of what we need to when the nested L2 guest exits and we want to
11627  * run its L1 parent, is to reset L1's guest state to the host state specified
11628  * in vmcs12.
11629  * This function is to be called not only on normal nested exit, but also on
11630  * a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry
11631  * Failures During or After Loading Guest State").
11632  * This function should be called when the active VMCS is L1's (vmcs01).
11633  */
11634 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
11635                                    struct vmcs12 *vmcs12)
11636 {
11637         struct kvm_segment seg;
11638
11639         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
11640                 vcpu->arch.efer = vmcs12->host_ia32_efer;
11641         else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
11642                 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
11643         else
11644                 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
11645         vmx_set_efer(vcpu, vcpu->arch.efer);
11646
11647         kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp);
11648         kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip);
11649         vmx_set_rflags(vcpu, X86_EFLAGS_FIXED);
11650         /*
11651          * Note that calling vmx_set_cr0 is important, even if cr0 hasn't
11652          * actually changed, because vmx_set_cr0 refers to efer set above.
11653          *
11654          * CR0_GUEST_HOST_MASK is already set in the original vmcs01
11655          * (KVM doesn't change it);
11656          */
11657         vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
11658         vmx_set_cr0(vcpu, vmcs12->host_cr0);
11659
11660         /* Same as above - no reason to call set_cr4_guest_host_mask().  */
11661         vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
11662         vmx_set_cr4(vcpu, vmcs12->host_cr4);
11663
11664         load_vmcs12_mmu_host_state(vcpu, vmcs12);
11665
11666         if (enable_vpid) {
11667                 /*
11668                  * Trivially support vpid by letting L2s share their parent
11669                  * L1's vpid. TODO: move to a more elaborate solution, giving
11670                  * each L2 its own vpid and exposing the vpid feature to L1.
11671                  */
11672                 vmx_flush_tlb(vcpu, true);
11673         }
11674
11675         vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
11676         vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp);
11677         vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip);
11678         vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base);
11679         vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base);
11680         vmcs_write32(GUEST_IDTR_LIMIT, 0xFFFF);
11681         vmcs_write32(GUEST_GDTR_LIMIT, 0xFFFF);
11682
11683         /* If not VM_EXIT_CLEAR_BNDCFGS, the L2 value propagates to L1.  */
11684         if (vmcs12->vm_exit_controls & VM_EXIT_CLEAR_BNDCFGS)
11685                 vmcs_write64(GUEST_BNDCFGS, 0);
11686
11687         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) {
11688                 vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat);
11689                 vcpu->arch.pat = vmcs12->host_ia32_pat;
11690         }
11691         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
11692                 vmcs_write64(GUEST_IA32_PERF_GLOBAL_CTRL,
11693                         vmcs12->host_ia32_perf_global_ctrl);
11694
11695         /* Set L1 segment info according to Intel SDM
11696             27.5.2 Loading Host Segment and Descriptor-Table Registers */
11697         seg = (struct kvm_segment) {
11698                 .base = 0,
11699                 .limit = 0xFFFFFFFF,
11700                 .selector = vmcs12->host_cs_selector,
11701                 .type = 11,
11702                 .present = 1,
11703                 .s = 1,
11704                 .g = 1
11705         };
11706         if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
11707                 seg.l = 1;
11708         else
11709                 seg.db = 1;
11710         vmx_set_segment(vcpu, &seg, VCPU_SREG_CS);
11711         seg = (struct kvm_segment) {
11712                 .base = 0,
11713                 .limit = 0xFFFFFFFF,
11714                 .type = 3,
11715                 .present = 1,
11716                 .s = 1,
11717                 .db = 1,
11718                 .g = 1
11719         };
11720         seg.selector = vmcs12->host_ds_selector;
11721         vmx_set_segment(vcpu, &seg, VCPU_SREG_DS);
11722         seg.selector = vmcs12->host_es_selector;
11723         vmx_set_segment(vcpu, &seg, VCPU_SREG_ES);
11724         seg.selector = vmcs12->host_ss_selector;
11725         vmx_set_segment(vcpu, &seg, VCPU_SREG_SS);
11726         seg.selector = vmcs12->host_fs_selector;
11727         seg.base = vmcs12->host_fs_base;
11728         vmx_set_segment(vcpu, &seg, VCPU_SREG_FS);
11729         seg.selector = vmcs12->host_gs_selector;
11730         seg.base = vmcs12->host_gs_base;
11731         vmx_set_segment(vcpu, &seg, VCPU_SREG_GS);
11732         seg = (struct kvm_segment) {
11733                 .base = vmcs12->host_tr_base,
11734                 .limit = 0x67,
11735                 .selector = vmcs12->host_tr_selector,
11736                 .type = 11,
11737                 .present = 1
11738         };
11739         vmx_set_segment(vcpu, &seg, VCPU_SREG_TR);
11740
11741         kvm_set_dr(vcpu, 7, 0x400);
11742         vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
11743
11744         if (cpu_has_vmx_msr_bitmap())
11745                 vmx_update_msr_bitmap(vcpu);
11746
11747         if (nested_vmx_load_msr(vcpu, vmcs12->vm_exit_msr_load_addr,
11748                                 vmcs12->vm_exit_msr_load_count))
11749                 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
11750 }
11751
11752 /*
11753  * Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
11754  * and modify vmcs12 to make it see what it would expect to see there if
11755  * L2 was its real guest. Must only be called when in L2 (is_guest_mode())
11756  */
11757 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
11758                               u32 exit_intr_info,
11759                               unsigned long exit_qualification)
11760 {
11761         struct vcpu_vmx *vmx = to_vmx(vcpu);
11762         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11763
11764         /* trying to cancel vmlaunch/vmresume is a bug */
11765         WARN_ON_ONCE(vmx->nested.nested_run_pending);
11766
11767         /*
11768          * The only expected VM-instruction error is "VM entry with
11769          * invalid control field(s)." Anything else indicates a
11770          * problem with L0.
11771          */
11772         WARN_ON_ONCE(vmx->fail && (vmcs_read32(VM_INSTRUCTION_ERROR) !=
11773                                    VMXERR_ENTRY_INVALID_CONTROL_FIELD));
11774
11775         leave_guest_mode(vcpu);
11776
11777         if (likely(!vmx->fail)) {
11778                 if (exit_reason == -1)
11779                         sync_vmcs12(vcpu, vmcs12);
11780                 else
11781                         prepare_vmcs12(vcpu, vmcs12, exit_reason, exit_intr_info,
11782                                        exit_qualification);
11783
11784                 if (nested_vmx_store_msr(vcpu, vmcs12->vm_exit_msr_store_addr,
11785                                          vmcs12->vm_exit_msr_store_count))
11786                         nested_vmx_abort(vcpu, VMX_ABORT_SAVE_GUEST_MSR_FAIL);
11787         }
11788
11789         vmx_switch_vmcs(vcpu, &vmx->vmcs01);
11790         vm_entry_controls_reset_shadow(vmx);
11791         vm_exit_controls_reset_shadow(vmx);
11792         vmx_segment_cache_clear(vmx);
11793
11794         /* Update any VMCS fields that might have changed while L2 ran */
11795         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
11796         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
11797         vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
11798         if (vmx->hv_deadline_tsc == -1)
11799                 vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
11800                                 PIN_BASED_VMX_PREEMPTION_TIMER);
11801         else
11802                 vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
11803                               PIN_BASED_VMX_PREEMPTION_TIMER);
11804         if (kvm_has_tsc_control)
11805                 decache_tsc_multiplier(vmx);
11806
11807         if (vmx->nested.change_vmcs01_virtual_x2apic_mode) {
11808                 vmx->nested.change_vmcs01_virtual_x2apic_mode = false;
11809                 vmx_set_virtual_x2apic_mode(vcpu,
11810                                 vcpu->arch.apic_base & X2APIC_ENABLE);
11811         } else if (!nested_cpu_has_ept(vmcs12) &&
11812                    nested_cpu_has2(vmcs12,
11813                                    SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
11814                 vmx_flush_tlb_ept_only(vcpu);
11815         }
11816
11817         /* This is needed for same reason as it was needed in prepare_vmcs02 */
11818         vmx->host_rsp = 0;
11819
11820         /* Unpin physical memory we referred to in vmcs02 */
11821         if (vmx->nested.apic_access_page) {
11822                 kvm_release_page_dirty(vmx->nested.apic_access_page);
11823                 vmx->nested.apic_access_page = NULL;
11824         }
11825         if (vmx->nested.virtual_apic_page) {
11826                 kvm_release_page_dirty(vmx->nested.virtual_apic_page);
11827                 vmx->nested.virtual_apic_page = NULL;
11828         }
11829         if (vmx->nested.pi_desc_page) {
11830                 kunmap(vmx->nested.pi_desc_page);
11831                 kvm_release_page_dirty(vmx->nested.pi_desc_page);
11832                 vmx->nested.pi_desc_page = NULL;
11833                 vmx->nested.pi_desc = NULL;
11834         }
11835
11836         /*
11837          * We are now running in L2, mmu_notifier will force to reload the
11838          * page's hpa for L2 vmcs. Need to reload it for L1 before entering L1.
11839          */
11840         kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
11841
11842         if (enable_shadow_vmcs && exit_reason != -1)
11843                 vmx->nested.sync_shadow_vmcs = true;
11844
11845         /* in case we halted in L2 */
11846         vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
11847
11848         if (likely(!vmx->fail)) {
11849                 /*
11850                  * TODO: SDM says that with acknowledge interrupt on
11851                  * exit, bit 31 of the VM-exit interrupt information
11852                  * (valid interrupt) is always set to 1 on
11853                  * EXIT_REASON_EXTERNAL_INTERRUPT, so we shouldn't
11854                  * need kvm_cpu_has_interrupt().  See the commit
11855                  * message for details.
11856                  */
11857                 if (nested_exit_intr_ack_set(vcpu) &&
11858                     exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT &&
11859                     kvm_cpu_has_interrupt(vcpu)) {
11860                         int irq = kvm_cpu_get_interrupt(vcpu);
11861                         WARN_ON(irq < 0);
11862                         vmcs12->vm_exit_intr_info = irq |
11863                                 INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR;
11864                 }
11865
11866                 if (exit_reason != -1)
11867                         trace_kvm_nested_vmexit_inject(vmcs12->vm_exit_reason,
11868                                                        vmcs12->exit_qualification,
11869                                                        vmcs12->idt_vectoring_info_field,
11870                                                        vmcs12->vm_exit_intr_info,
11871                                                        vmcs12->vm_exit_intr_error_code,
11872                                                        KVM_ISA_VMX);
11873
11874                 load_vmcs12_host_state(vcpu, vmcs12);
11875
11876                 return;
11877         }
11878         
11879         /*
11880          * After an early L2 VM-entry failure, we're now back
11881          * in L1 which thinks it just finished a VMLAUNCH or
11882          * VMRESUME instruction, so we need to set the failure
11883          * flag and the VM-instruction error field of the VMCS
11884          * accordingly.
11885          */
11886         nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
11887
11888         load_vmcs12_mmu_host_state(vcpu, vmcs12);
11889
11890         /*
11891          * The emulated instruction was already skipped in
11892          * nested_vmx_run, but the updated RIP was never
11893          * written back to the vmcs01.
11894          */
11895         skip_emulated_instruction(vcpu);
11896         vmx->fail = 0;
11897 }
11898
11899 /*
11900  * Forcibly leave nested mode in order to be able to reset the VCPU later on.
11901  */
11902 static void vmx_leave_nested(struct kvm_vcpu *vcpu)
11903 {
11904         if (is_guest_mode(vcpu)) {
11905                 to_vmx(vcpu)->nested.nested_run_pending = 0;
11906                 nested_vmx_vmexit(vcpu, -1, 0, 0);
11907         }
11908         free_nested(to_vmx(vcpu));
11909 }
11910
11911 /*
11912  * L1's failure to enter L2 is a subset of a normal exit, as explained in
11913  * 23.7 "VM-entry failures during or after loading guest state" (this also
11914  * lists the acceptable exit-reason and exit-qualification parameters).
11915  * It should only be called before L2 actually succeeded to run, and when
11916  * vmcs01 is current (it doesn't leave_guest_mode() or switch vmcss).
11917  */
11918 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
11919                         struct vmcs12 *vmcs12,
11920                         u32 reason, unsigned long qualification)
11921 {
11922         load_vmcs12_host_state(vcpu, vmcs12);
11923         vmcs12->vm_exit_reason = reason | VMX_EXIT_REASONS_FAILED_VMENTRY;
11924         vmcs12->exit_qualification = qualification;
11925         nested_vmx_succeed(vcpu);
11926         if (enable_shadow_vmcs)
11927                 to_vmx(vcpu)->nested.sync_shadow_vmcs = true;
11928 }
11929
11930 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
11931                                struct x86_instruction_info *info,
11932                                enum x86_intercept_stage stage)
11933 {
11934         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11935         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
11936
11937         /*
11938          * RDPID causes #UD if disabled through secondary execution controls.
11939          * Because it is marked as EmulateOnUD, we need to intercept it here.
11940          */
11941         if (info->intercept == x86_intercept_rdtscp &&
11942             !nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDTSCP)) {
11943                 ctxt->exception.vector = UD_VECTOR;
11944                 ctxt->exception.error_code_valid = false;
11945                 return X86EMUL_PROPAGATE_FAULT;
11946         }
11947
11948         /* TODO: check more intercepts... */
11949         return X86EMUL_CONTINUE;
11950 }
11951
11952 #ifdef CONFIG_X86_64
11953 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
11954 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
11955                                   u64 divisor, u64 *result)
11956 {
11957         u64 low = a << shift, high = a >> (64 - shift);
11958
11959         /* To avoid the overflow on divq */
11960         if (high >= divisor)
11961                 return 1;
11962
11963         /* Low hold the result, high hold rem which is discarded */
11964         asm("divq %2\n\t" : "=a" (low), "=d" (high) :
11965             "rm" (divisor), "0" (low), "1" (high));
11966         *result = low;
11967
11968         return 0;
11969 }
11970
11971 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc)
11972 {
11973         struct vcpu_vmx *vmx = to_vmx(vcpu);
11974         u64 tscl = rdtsc();
11975         u64 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
11976         u64 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
11977
11978         /* Convert to host delta tsc if tsc scaling is enabled */
11979         if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
11980                         u64_shl_div_u64(delta_tsc,
11981                                 kvm_tsc_scaling_ratio_frac_bits,
11982                                 vcpu->arch.tsc_scaling_ratio,
11983                                 &delta_tsc))
11984                 return -ERANGE;
11985
11986         /*
11987          * If the delta tsc can't fit in the 32 bit after the multi shift,
11988          * we can't use the preemption timer.
11989          * It's possible that it fits on later vmentries, but checking
11990          * on every vmentry is costly so we just use an hrtimer.
11991          */
11992         if (delta_tsc >> (cpu_preemption_timer_multi + 32))
11993                 return -ERANGE;
11994
11995         vmx->hv_deadline_tsc = tscl + delta_tsc;
11996         vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
11997                         PIN_BASED_VMX_PREEMPTION_TIMER);
11998
11999         return delta_tsc == 0;
12000 }
12001
12002 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
12003 {
12004         struct vcpu_vmx *vmx = to_vmx(vcpu);
12005         vmx->hv_deadline_tsc = -1;
12006         vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
12007                         PIN_BASED_VMX_PREEMPTION_TIMER);
12008 }
12009 #endif
12010
12011 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
12012 {
12013         if (ple_gap)
12014                 shrink_ple_window(vcpu);
12015 }
12016
12017 static void vmx_slot_enable_log_dirty(struct kvm *kvm,
12018                                      struct kvm_memory_slot *slot)
12019 {
12020         kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
12021         kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
12022 }
12023
12024 static void vmx_slot_disable_log_dirty(struct kvm *kvm,
12025                                        struct kvm_memory_slot *slot)
12026 {
12027         kvm_mmu_slot_set_dirty(kvm, slot);
12028 }
12029
12030 static void vmx_flush_log_dirty(struct kvm *kvm)
12031 {
12032         kvm_flush_pml_buffers(kvm);
12033 }
12034
12035 static int vmx_write_pml_buffer(struct kvm_vcpu *vcpu)
12036 {
12037         struct vmcs12 *vmcs12;
12038         struct vcpu_vmx *vmx = to_vmx(vcpu);
12039         gpa_t gpa;
12040         struct page *page = NULL;
12041         u64 *pml_address;
12042
12043         if (is_guest_mode(vcpu)) {
12044                 WARN_ON_ONCE(vmx->nested.pml_full);
12045
12046                 /*
12047                  * Check if PML is enabled for the nested guest.
12048                  * Whether eptp bit 6 is set is already checked
12049                  * as part of A/D emulation.
12050                  */
12051                 vmcs12 = get_vmcs12(vcpu);
12052                 if (!nested_cpu_has_pml(vmcs12))
12053                         return 0;
12054
12055                 if (vmcs12->guest_pml_index >= PML_ENTITY_NUM) {
12056                         vmx->nested.pml_full = true;
12057                         return 1;
12058                 }
12059
12060                 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS) & ~0xFFFull;
12061
12062                 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->pml_address);
12063                 if (is_error_page(page))
12064                         return 0;
12065
12066                 pml_address = kmap(page);
12067                 pml_address[vmcs12->guest_pml_index--] = gpa;
12068                 kunmap(page);
12069                 kvm_release_page_clean(page);
12070         }
12071
12072         return 0;
12073 }
12074
12075 static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
12076                                            struct kvm_memory_slot *memslot,
12077                                            gfn_t offset, unsigned long mask)
12078 {
12079         kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
12080 }
12081
12082 static void __pi_post_block(struct kvm_vcpu *vcpu)
12083 {
12084         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
12085         struct pi_desc old, new;
12086         unsigned int dest;
12087
12088         do {
12089                 old.control = new.control = pi_desc->control;
12090                 WARN(old.nv != POSTED_INTR_WAKEUP_VECTOR,
12091                      "Wakeup handler not enabled while the VCPU is blocked\n");
12092
12093                 dest = cpu_physical_id(vcpu->cpu);
12094
12095                 if (x2apic_enabled())
12096                         new.ndst = dest;
12097                 else
12098                         new.ndst = (dest << 8) & 0xFF00;
12099
12100                 /* set 'NV' to 'notification vector' */
12101                 new.nv = POSTED_INTR_VECTOR;
12102         } while (cmpxchg64(&pi_desc->control, old.control,
12103                            new.control) != old.control);
12104
12105         if (!WARN_ON_ONCE(vcpu->pre_pcpu == -1)) {
12106                 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
12107                 list_del(&vcpu->blocked_vcpu_list);
12108                 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
12109                 vcpu->pre_pcpu = -1;
12110         }
12111 }
12112
12113 /*
12114  * This routine does the following things for vCPU which is going
12115  * to be blocked if VT-d PI is enabled.
12116  * - Store the vCPU to the wakeup list, so when interrupts happen
12117  *   we can find the right vCPU to wake up.
12118  * - Change the Posted-interrupt descriptor as below:
12119  *      'NDST' <-- vcpu->pre_pcpu
12120  *      'NV' <-- POSTED_INTR_WAKEUP_VECTOR
12121  * - If 'ON' is set during this process, which means at least one
12122  *   interrupt is posted for this vCPU, we cannot block it, in
12123  *   this case, return 1, otherwise, return 0.
12124  *
12125  */
12126 static int pi_pre_block(struct kvm_vcpu *vcpu)
12127 {
12128         unsigned int dest;
12129         struct pi_desc old, new;
12130         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
12131
12132         if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
12133                 !irq_remapping_cap(IRQ_POSTING_CAP)  ||
12134                 !kvm_vcpu_apicv_active(vcpu))
12135                 return 0;
12136
12137         WARN_ON(irqs_disabled());
12138         local_irq_disable();
12139         if (!WARN_ON_ONCE(vcpu->pre_pcpu != -1)) {
12140                 vcpu->pre_pcpu = vcpu->cpu;
12141                 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
12142                 list_add_tail(&vcpu->blocked_vcpu_list,
12143                               &per_cpu(blocked_vcpu_on_cpu,
12144                                        vcpu->pre_pcpu));
12145                 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
12146         }
12147
12148         do {
12149                 old.control = new.control = pi_desc->control;
12150
12151                 WARN((pi_desc->sn == 1),
12152                      "Warning: SN field of posted-interrupts "
12153                      "is set before blocking\n");
12154
12155                 /*
12156                  * Since vCPU can be preempted during this process,
12157                  * vcpu->cpu could be different with pre_pcpu, we
12158                  * need to set pre_pcpu as the destination of wakeup
12159                  * notification event, then we can find the right vCPU
12160                  * to wakeup in wakeup handler if interrupts happen
12161                  * when the vCPU is in blocked state.
12162                  */
12163                 dest = cpu_physical_id(vcpu->pre_pcpu);
12164
12165                 if (x2apic_enabled())
12166                         new.ndst = dest;
12167                 else
12168                         new.ndst = (dest << 8) & 0xFF00;
12169
12170                 /* set 'NV' to 'wakeup vector' */
12171                 new.nv = POSTED_INTR_WAKEUP_VECTOR;
12172         } while (cmpxchg64(&pi_desc->control, old.control,
12173                            new.control) != old.control);
12174
12175         /* We should not block the vCPU if an interrupt is posted for it.  */
12176         if (pi_test_on(pi_desc) == 1)
12177                 __pi_post_block(vcpu);
12178
12179         local_irq_enable();
12180         return (vcpu->pre_pcpu == -1);
12181 }
12182
12183 static int vmx_pre_block(struct kvm_vcpu *vcpu)
12184 {
12185         if (pi_pre_block(vcpu))
12186                 return 1;
12187
12188         if (kvm_lapic_hv_timer_in_use(vcpu))
12189                 kvm_lapic_switch_to_sw_timer(vcpu);
12190
12191         return 0;
12192 }
12193
12194 static void pi_post_block(struct kvm_vcpu *vcpu)
12195 {
12196         if (vcpu->pre_pcpu == -1)
12197                 return;
12198
12199         WARN_ON(irqs_disabled());
12200         local_irq_disable();
12201         __pi_post_block(vcpu);
12202         local_irq_enable();
12203 }
12204
12205 static void vmx_post_block(struct kvm_vcpu *vcpu)
12206 {
12207         if (kvm_x86_ops->set_hv_timer)
12208                 kvm_lapic_switch_to_hv_timer(vcpu);
12209
12210         pi_post_block(vcpu);
12211 }
12212
12213 /*
12214  * vmx_update_pi_irte - set IRTE for Posted-Interrupts
12215  *
12216  * @kvm: kvm
12217  * @host_irq: host irq of the interrupt
12218  * @guest_irq: gsi of the interrupt
12219  * @set: set or unset PI
12220  * returns 0 on success, < 0 on failure
12221  */
12222 static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
12223                               uint32_t guest_irq, bool set)
12224 {
12225         struct kvm_kernel_irq_routing_entry *e;
12226         struct kvm_irq_routing_table *irq_rt;
12227         struct kvm_lapic_irq irq;
12228         struct kvm_vcpu *vcpu;
12229         struct vcpu_data vcpu_info;
12230         int idx, ret = 0;
12231
12232         if (!kvm_arch_has_assigned_device(kvm) ||
12233                 !irq_remapping_cap(IRQ_POSTING_CAP) ||
12234                 !kvm_vcpu_apicv_active(kvm->vcpus[0]))
12235                 return 0;
12236
12237         idx = srcu_read_lock(&kvm->irq_srcu);
12238         irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
12239         if (guest_irq >= irq_rt->nr_rt_entries ||
12240             hlist_empty(&irq_rt->map[guest_irq])) {
12241                 pr_warn_once("no route for guest_irq %u/%u (broken user space?)\n",
12242                              guest_irq, irq_rt->nr_rt_entries);
12243                 goto out;
12244         }
12245
12246         hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
12247                 if (e->type != KVM_IRQ_ROUTING_MSI)
12248                         continue;
12249                 /*
12250                  * VT-d PI cannot support posting multicast/broadcast
12251                  * interrupts to a vCPU, we still use interrupt remapping
12252                  * for these kind of interrupts.
12253                  *
12254                  * For lowest-priority interrupts, we only support
12255                  * those with single CPU as the destination, e.g. user
12256                  * configures the interrupts via /proc/irq or uses
12257                  * irqbalance to make the interrupts single-CPU.
12258                  *
12259                  * We will support full lowest-priority interrupt later.
12260                  */
12261
12262                 kvm_set_msi_irq(kvm, e, &irq);
12263                 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
12264                         /*
12265                          * Make sure the IRTE is in remapped mode if
12266                          * we don't handle it in posted mode.
12267                          */
12268                         ret = irq_set_vcpu_affinity(host_irq, NULL);
12269                         if (ret < 0) {
12270                                 printk(KERN_INFO
12271                                    "failed to back to remapped mode, irq: %u\n",
12272                                    host_irq);
12273                                 goto out;
12274                         }
12275
12276                         continue;
12277                 }
12278
12279                 vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
12280                 vcpu_info.vector = irq.vector;
12281
12282                 trace_kvm_pi_irte_update(vcpu->vcpu_id, host_irq, e->gsi,
12283                                 vcpu_info.vector, vcpu_info.pi_desc_addr, set);
12284
12285                 if (set)
12286                         ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
12287                 else
12288                         ret = irq_set_vcpu_affinity(host_irq, NULL);
12289
12290                 if (ret < 0) {
12291                         printk(KERN_INFO "%s: failed to update PI IRTE\n",
12292                                         __func__);
12293                         goto out;
12294                 }
12295         }
12296
12297         ret = 0;
12298 out:
12299         srcu_read_unlock(&kvm->irq_srcu, idx);
12300         return ret;
12301 }
12302
12303 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
12304 {
12305         if (vcpu->arch.mcg_cap & MCG_LMCE_P)
12306                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
12307                         FEATURE_CONTROL_LMCE;
12308         else
12309                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
12310                         ~FEATURE_CONTROL_LMCE;
12311 }
12312
12313 static int vmx_smi_allowed(struct kvm_vcpu *vcpu)
12314 {
12315         /* we need a nested vmexit to enter SMM, postpone if run is pending */
12316         if (to_vmx(vcpu)->nested.nested_run_pending)
12317                 return 0;
12318         return 1;
12319 }
12320
12321 static int vmx_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
12322 {
12323         struct vcpu_vmx *vmx = to_vmx(vcpu);
12324
12325         vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
12326         if (vmx->nested.smm.guest_mode)
12327                 nested_vmx_vmexit(vcpu, -1, 0, 0);
12328
12329         vmx->nested.smm.vmxon = vmx->nested.vmxon;
12330         vmx->nested.vmxon = false;
12331         return 0;
12332 }
12333
12334 static int vmx_pre_leave_smm(struct kvm_vcpu *vcpu, u64 smbase)
12335 {
12336         struct vcpu_vmx *vmx = to_vmx(vcpu);
12337         int ret;
12338
12339         if (vmx->nested.smm.vmxon) {
12340                 vmx->nested.vmxon = true;
12341                 vmx->nested.smm.vmxon = false;
12342         }
12343
12344         if (vmx->nested.smm.guest_mode) {
12345                 vcpu->arch.hflags &= ~HF_SMM_MASK;
12346                 ret = enter_vmx_non_root_mode(vcpu, false);
12347                 vcpu->arch.hflags |= HF_SMM_MASK;
12348                 if (ret)
12349                         return ret;
12350
12351                 vmx->nested.smm.guest_mode = false;
12352         }
12353         return 0;
12354 }
12355
12356 static int enable_smi_window(struct kvm_vcpu *vcpu)
12357 {
12358         return 0;
12359 }
12360
12361 static struct kvm_x86_ops vmx_x86_ops __ro_after_init = {
12362         .cpu_has_kvm_support = cpu_has_kvm_support,
12363         .disabled_by_bios = vmx_disabled_by_bios,
12364         .hardware_setup = hardware_setup,
12365         .hardware_unsetup = hardware_unsetup,
12366         .check_processor_compatibility = vmx_check_processor_compat,
12367         .hardware_enable = hardware_enable,
12368         .hardware_disable = hardware_disable,
12369         .cpu_has_accelerated_tpr = report_flexpriority,
12370         .cpu_has_high_real_mode_segbase = vmx_has_high_real_mode_segbase,
12371
12372         .vcpu_create = vmx_create_vcpu,
12373         .vcpu_free = vmx_free_vcpu,
12374         .vcpu_reset = vmx_vcpu_reset,
12375
12376         .prepare_guest_switch = vmx_save_host_state,
12377         .vcpu_load = vmx_vcpu_load,
12378         .vcpu_put = vmx_vcpu_put,
12379
12380         .update_bp_intercept = update_exception_bitmap,
12381         .get_msr_feature = vmx_get_msr_feature,
12382         .get_msr = vmx_get_msr,
12383         .set_msr = vmx_set_msr,
12384         .get_segment_base = vmx_get_segment_base,
12385         .get_segment = vmx_get_segment,
12386         .set_segment = vmx_set_segment,
12387         .get_cpl = vmx_get_cpl,
12388         .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
12389         .decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
12390         .decache_cr3 = vmx_decache_cr3,
12391         .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
12392         .set_cr0 = vmx_set_cr0,
12393         .set_cr3 = vmx_set_cr3,
12394         .set_cr4 = vmx_set_cr4,
12395         .set_efer = vmx_set_efer,
12396         .get_idt = vmx_get_idt,
12397         .set_idt = vmx_set_idt,
12398         .get_gdt = vmx_get_gdt,
12399         .set_gdt = vmx_set_gdt,
12400         .get_dr6 = vmx_get_dr6,
12401         .set_dr6 = vmx_set_dr6,
12402         .set_dr7 = vmx_set_dr7,
12403         .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
12404         .cache_reg = vmx_cache_reg,
12405         .get_rflags = vmx_get_rflags,
12406         .set_rflags = vmx_set_rflags,
12407
12408         .tlb_flush = vmx_flush_tlb,
12409
12410         .run = vmx_vcpu_run,
12411         .handle_exit = vmx_handle_exit,
12412         .skip_emulated_instruction = skip_emulated_instruction,
12413         .set_interrupt_shadow = vmx_set_interrupt_shadow,
12414         .get_interrupt_shadow = vmx_get_interrupt_shadow,
12415         .patch_hypercall = vmx_patch_hypercall,
12416         .set_irq = vmx_inject_irq,
12417         .set_nmi = vmx_inject_nmi,
12418         .queue_exception = vmx_queue_exception,
12419         .cancel_injection = vmx_cancel_injection,
12420         .interrupt_allowed = vmx_interrupt_allowed,
12421         .nmi_allowed = vmx_nmi_allowed,
12422         .get_nmi_mask = vmx_get_nmi_mask,
12423         .set_nmi_mask = vmx_set_nmi_mask,
12424         .enable_nmi_window = enable_nmi_window,
12425         .enable_irq_window = enable_irq_window,
12426         .update_cr8_intercept = update_cr8_intercept,
12427         .set_virtual_x2apic_mode = vmx_set_virtual_x2apic_mode,
12428         .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
12429         .get_enable_apicv = vmx_get_enable_apicv,
12430         .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
12431         .load_eoi_exitmap = vmx_load_eoi_exitmap,
12432         .apicv_post_state_restore = vmx_apicv_post_state_restore,
12433         .hwapic_irr_update = vmx_hwapic_irr_update,
12434         .hwapic_isr_update = vmx_hwapic_isr_update,
12435         .sync_pir_to_irr = vmx_sync_pir_to_irr,
12436         .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
12437
12438         .set_tss_addr = vmx_set_tss_addr,
12439         .get_tdp_level = get_ept_level,
12440         .get_mt_mask = vmx_get_mt_mask,
12441
12442         .get_exit_info = vmx_get_exit_info,
12443
12444         .get_lpage_level = vmx_get_lpage_level,
12445
12446         .cpuid_update = vmx_cpuid_update,
12447
12448         .rdtscp_supported = vmx_rdtscp_supported,
12449         .invpcid_supported = vmx_invpcid_supported,
12450
12451         .set_supported_cpuid = vmx_set_supported_cpuid,
12452
12453         .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
12454
12455         .write_tsc_offset = vmx_write_tsc_offset,
12456
12457         .set_tdp_cr3 = vmx_set_cr3,
12458
12459         .check_intercept = vmx_check_intercept,
12460         .handle_external_intr = vmx_handle_external_intr,
12461         .mpx_supported = vmx_mpx_supported,
12462         .xsaves_supported = vmx_xsaves_supported,
12463         .umip_emulated = vmx_umip_emulated,
12464
12465         .check_nested_events = vmx_check_nested_events,
12466
12467         .sched_in = vmx_sched_in,
12468
12469         .slot_enable_log_dirty = vmx_slot_enable_log_dirty,
12470         .slot_disable_log_dirty = vmx_slot_disable_log_dirty,
12471         .flush_log_dirty = vmx_flush_log_dirty,
12472         .enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
12473         .write_log_dirty = vmx_write_pml_buffer,
12474
12475         .pre_block = vmx_pre_block,
12476         .post_block = vmx_post_block,
12477
12478         .pmu_ops = &intel_pmu_ops,
12479
12480         .update_pi_irte = vmx_update_pi_irte,
12481
12482 #ifdef CONFIG_X86_64
12483         .set_hv_timer = vmx_set_hv_timer,
12484         .cancel_hv_timer = vmx_cancel_hv_timer,
12485 #endif
12486
12487         .setup_mce = vmx_setup_mce,
12488
12489         .smi_allowed = vmx_smi_allowed,
12490         .pre_enter_smm = vmx_pre_enter_smm,
12491         .pre_leave_smm = vmx_pre_leave_smm,
12492         .enable_smi_window = enable_smi_window,
12493 };
12494
12495 static int __init vmx_init(void)
12496 {
12497         int r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
12498                      __alignof__(struct vcpu_vmx), THIS_MODULE);
12499         if (r)
12500                 return r;
12501
12502 #ifdef CONFIG_KEXEC_CORE
12503         rcu_assign_pointer(crash_vmclear_loaded_vmcss,
12504                            crash_vmclear_local_loaded_vmcss);
12505 #endif
12506
12507         return 0;
12508 }
12509
12510 static void __exit vmx_exit(void)
12511 {
12512 #ifdef CONFIG_KEXEC_CORE
12513         RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
12514         synchronize_rcu();
12515 #endif
12516
12517         kvm_exit();
12518 }
12519
12520 module_init(vmx_init)
12521 module_exit(vmx_exit)