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