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