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