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