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