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