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