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