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