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