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