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