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