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