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