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