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