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