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