X86/nVMX: Properly set spec_ctrl and pred_cmd before merging MSRs
[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/nospec-branch.h>
55
56 #include "trace.h"
57 #include "pmu.h"
58
59 #define __ex(x) __kvm_handle_fault_on_reboot(x)
60 #define __ex_clear(x, reg) \
61         ____kvm_handle_fault_on_reboot(x, "xor " reg " , " reg)
62
63 MODULE_AUTHOR("Qumranet");
64 MODULE_LICENSE("GPL");
65
66 static const struct x86_cpu_id vmx_cpu_id[] = {
67         X86_FEATURE_MATCH(X86_FEATURE_VMX),
68         {}
69 };
70 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
71
72 static bool __read_mostly enable_vpid = 1;
73 module_param_named(vpid, enable_vpid, bool, 0444);
74
75 static bool __read_mostly flexpriority_enabled = 1;
76 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
77
78 static bool __read_mostly enable_ept = 1;
79 module_param_named(ept, enable_ept, bool, S_IRUGO);
80
81 static bool __read_mostly enable_unrestricted_guest = 1;
82 module_param_named(unrestricted_guest,
83                         enable_unrestricted_guest, bool, S_IRUGO);
84
85 static bool __read_mostly enable_ept_ad_bits = 1;
86 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
87
88 static bool __read_mostly emulate_invalid_guest_state = true;
89 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
90
91 static bool __read_mostly fasteoi = 1;
92 module_param(fasteoi, bool, S_IRUGO);
93
94 static bool __read_mostly enable_apicv = 1;
95 module_param(enable_apicv, bool, S_IRUGO);
96
97 static bool __read_mostly enable_shadow_vmcs = 1;
98 module_param_named(enable_shadow_vmcs, enable_shadow_vmcs, bool, S_IRUGO);
99 /*
100  * If nested=1, nested virtualization is supported, i.e., guests may use
101  * VMX and be a hypervisor for its own guests. If nested=0, guests may not
102  * use VMX instructions.
103  */
104 static bool __read_mostly nested = 0;
105 module_param(nested, bool, S_IRUGO);
106
107 static u64 __read_mostly host_xss;
108
109 static bool __read_mostly enable_pml = 1;
110 module_param_named(pml, enable_pml, bool, S_IRUGO);
111
112 #define MSR_TYPE_R      1
113 #define MSR_TYPE_W      2
114 #define MSR_TYPE_RW     3
115
116 #define MSR_BITMAP_MODE_X2APIC          1
117 #define MSR_BITMAP_MODE_X2APIC_APICV    2
118 #define MSR_BITMAP_MODE_LM              4
119
120 #define KVM_VMX_TSC_MULTIPLIER_MAX     0xffffffffffffffffULL
121
122 /* Guest_tsc -> host_tsc conversion requires 64-bit division.  */
123 static int __read_mostly cpu_preemption_timer_multi;
124 static bool __read_mostly enable_preemption_timer = 1;
125 #ifdef CONFIG_X86_64
126 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
127 #endif
128
129 #define KVM_GUEST_CR0_MASK (X86_CR0_NW | X86_CR0_CD)
130 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST (X86_CR0_WP | X86_CR0_NE)
131 #define KVM_VM_CR0_ALWAYS_ON                                            \
132         (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE)
133 #define KVM_CR4_GUEST_OWNED_BITS                                      \
134         (X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR      \
135          | X86_CR4_OSXMMEXCPT | X86_CR4_LA57 | X86_CR4_TSD)
136
137 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
138 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
139
140 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
141
142 #define VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE 5
143
144 /*
145  * Hyper-V requires all of these, so mark them as supported even though
146  * they are just treated the same as all-context.
147  */
148 #define VMX_VPID_EXTENT_SUPPORTED_MASK          \
149         (VMX_VPID_EXTENT_INDIVIDUAL_ADDR_BIT |  \
150         VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT |    \
151         VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT |    \
152         VMX_VPID_EXTENT_SINGLE_NON_GLOBAL_BIT)
153
154 /*
155  * These 2 parameters are used to config the controls for Pause-Loop Exiting:
156  * ple_gap:    upper bound on the amount of time between two successive
157  *             executions of PAUSE in a loop. Also indicate if ple enabled.
158  *             According to test, this time is usually smaller than 128 cycles.
159  * ple_window: upper bound on the amount of time a guest is allowed to execute
160  *             in a PAUSE loop. Tests indicate that most spinlocks are held for
161  *             less than 2^12 cycles
162  * Time is measured based on a counter that runs at the same rate as the TSC,
163  * refer SDM volume 3b section 21.6.13 & 22.1.3.
164  */
165 #define KVM_VMX_DEFAULT_PLE_GAP           128
166 #define KVM_VMX_DEFAULT_PLE_WINDOW        4096
167 #define KVM_VMX_DEFAULT_PLE_WINDOW_GROW   2
168 #define KVM_VMX_DEFAULT_PLE_WINDOW_SHRINK 0
169 #define KVM_VMX_DEFAULT_PLE_WINDOW_MAX    \
170                 INT_MAX / KVM_VMX_DEFAULT_PLE_WINDOW_GROW
171
172 static int ple_gap = KVM_VMX_DEFAULT_PLE_GAP;
173 module_param(ple_gap, int, S_IRUGO);
174
175 static int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
176 module_param(ple_window, int, S_IRUGO);
177
178 /* Default doubles per-vcpu window every exit. */
179 static int ple_window_grow = KVM_VMX_DEFAULT_PLE_WINDOW_GROW;
180 module_param(ple_window_grow, int, S_IRUGO);
181
182 /* Default resets per-vcpu window every exit to ple_window. */
183 static int ple_window_shrink = KVM_VMX_DEFAULT_PLE_WINDOW_SHRINK;
184 module_param(ple_window_shrink, int, S_IRUGO);
185
186 /* Default is to compute the maximum so we can never overflow. */
187 static int ple_window_actual_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
188 static int ple_window_max        = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
189 module_param(ple_window_max, int, S_IRUGO);
190
191 extern const ulong vmx_return;
192
193 #define NR_AUTOLOAD_MSRS 8
194
195 struct vmcs {
196         u32 revision_id;
197         u32 abort;
198         char data[0];
199 };
200
201 /*
202  * Track a VMCS that may be loaded on a certain CPU. If it is (cpu!=-1), also
203  * remember whether it was VMLAUNCHed, and maintain a linked list of all VMCSs
204  * loaded on this CPU (so we can clear them if the CPU goes down).
205  */
206 struct loaded_vmcs {
207         struct vmcs *vmcs;
208         struct vmcs *shadow_vmcs;
209         int cpu;
210         bool launched;
211         bool nmi_known_unmasked;
212         unsigned long vmcs_host_cr3;    /* May not match real cr3 */
213         unsigned long vmcs_host_cr4;    /* May not match real cr4 */
214         /* Support for vnmi-less CPUs */
215         int soft_vnmi_blocked;
216         ktime_t entry_time;
217         s64 vnmi_blocked_time;
218         unsigned long *msr_bitmap;
219         struct list_head loaded_vmcss_on_cpu_link;
220 };
221
222 struct shared_msr_entry {
223         unsigned index;
224         u64 data;
225         u64 mask;
226 };
227
228 /*
229  * struct vmcs12 describes the state that our guest hypervisor (L1) keeps for a
230  * single nested guest (L2), hence the name vmcs12. Any VMX implementation has
231  * a VMCS structure, and vmcs12 is our emulated VMX's VMCS. This structure is
232  * stored in guest memory specified by VMPTRLD, but is opaque to the guest,
233  * which must access it using VMREAD/VMWRITE/VMCLEAR instructions.
234  * More than one of these structures may exist, if L1 runs multiple L2 guests.
235  * nested_vmx_run() will use the data here to build the vmcs02: a VMCS for the
236  * underlying hardware which will be used to run L2.
237  * This structure is packed to ensure that its layout is identical across
238  * machines (necessary for live migration).
239  * If there are changes in this struct, VMCS12_REVISION must be changed.
240  */
241 typedef u64 natural_width;
242 struct __packed vmcs12 {
243         /* According to the Intel spec, a VMCS region must start with the
244          * following two fields. Then follow implementation-specific data.
245          */
246         u32 revision_id;
247         u32 abort;
248
249         u32 launch_state; /* set to 0 by VMCLEAR, to 1 by VMLAUNCH */
250         u32 padding[7]; /* room for future expansion */
251
252         u64 io_bitmap_a;
253         u64 io_bitmap_b;
254         u64 msr_bitmap;
255         u64 vm_exit_msr_store_addr;
256         u64 vm_exit_msr_load_addr;
257         u64 vm_entry_msr_load_addr;
258         u64 tsc_offset;
259         u64 virtual_apic_page_addr;
260         u64 apic_access_addr;
261         u64 posted_intr_desc_addr;
262         u64 vm_function_control;
263         u64 ept_pointer;
264         u64 eoi_exit_bitmap0;
265         u64 eoi_exit_bitmap1;
266         u64 eoi_exit_bitmap2;
267         u64 eoi_exit_bitmap3;
268         u64 eptp_list_address;
269         u64 xss_exit_bitmap;
270         u64 guest_physical_address;
271         u64 vmcs_link_pointer;
272         u64 pml_address;
273         u64 guest_ia32_debugctl;
274         u64 guest_ia32_pat;
275         u64 guest_ia32_efer;
276         u64 guest_ia32_perf_global_ctrl;
277         u64 guest_pdptr0;
278         u64 guest_pdptr1;
279         u64 guest_pdptr2;
280         u64 guest_pdptr3;
281         u64 guest_bndcfgs;
282         u64 host_ia32_pat;
283         u64 host_ia32_efer;
284         u64 host_ia32_perf_global_ctrl;
285         u64 padding64[8]; /* room for future expansion */
286         /*
287          * To allow migration of L1 (complete with its L2 guests) between
288          * machines of different natural widths (32 or 64 bit), we cannot have
289          * unsigned long fields with no explict size. We use u64 (aliased
290          * natural_width) instead. Luckily, x86 is little-endian.
291          */
292         natural_width cr0_guest_host_mask;
293         natural_width cr4_guest_host_mask;
294         natural_width cr0_read_shadow;
295         natural_width cr4_read_shadow;
296         natural_width cr3_target_value0;
297         natural_width cr3_target_value1;
298         natural_width cr3_target_value2;
299         natural_width cr3_target_value3;
300         natural_width exit_qualification;
301         natural_width guest_linear_address;
302         natural_width guest_cr0;
303         natural_width guest_cr3;
304         natural_width guest_cr4;
305         natural_width guest_es_base;
306         natural_width guest_cs_base;
307         natural_width guest_ss_base;
308         natural_width guest_ds_base;
309         natural_width guest_fs_base;
310         natural_width guest_gs_base;
311         natural_width guest_ldtr_base;
312         natural_width guest_tr_base;
313         natural_width guest_gdtr_base;
314         natural_width guest_idtr_base;
315         natural_width guest_dr7;
316         natural_width guest_rsp;
317         natural_width guest_rip;
318         natural_width guest_rflags;
319         natural_width guest_pending_dbg_exceptions;
320         natural_width guest_sysenter_esp;
321         natural_width guest_sysenter_eip;
322         natural_width host_cr0;
323         natural_width host_cr3;
324         natural_width host_cr4;
325         natural_width host_fs_base;
326         natural_width host_gs_base;
327         natural_width host_tr_base;
328         natural_width host_gdtr_base;
329         natural_width host_idtr_base;
330         natural_width host_ia32_sysenter_esp;
331         natural_width host_ia32_sysenter_eip;
332         natural_width host_rsp;
333         natural_width host_rip;
334         natural_width paddingl[8]; /* room for future expansion */
335         u32 pin_based_vm_exec_control;
336         u32 cpu_based_vm_exec_control;
337         u32 exception_bitmap;
338         u32 page_fault_error_code_mask;
339         u32 page_fault_error_code_match;
340         u32 cr3_target_count;
341         u32 vm_exit_controls;
342         u32 vm_exit_msr_store_count;
343         u32 vm_exit_msr_load_count;
344         u32 vm_entry_controls;
345         u32 vm_entry_msr_load_count;
346         u32 vm_entry_intr_info_field;
347         u32 vm_entry_exception_error_code;
348         u32 vm_entry_instruction_len;
349         u32 tpr_threshold;
350         u32 secondary_vm_exec_control;
351         u32 vm_instruction_error;
352         u32 vm_exit_reason;
353         u32 vm_exit_intr_info;
354         u32 vm_exit_intr_error_code;
355         u32 idt_vectoring_info_field;
356         u32 idt_vectoring_error_code;
357         u32 vm_exit_instruction_len;
358         u32 vmx_instruction_info;
359         u32 guest_es_limit;
360         u32 guest_cs_limit;
361         u32 guest_ss_limit;
362         u32 guest_ds_limit;
363         u32 guest_fs_limit;
364         u32 guest_gs_limit;
365         u32 guest_ldtr_limit;
366         u32 guest_tr_limit;
367         u32 guest_gdtr_limit;
368         u32 guest_idtr_limit;
369         u32 guest_es_ar_bytes;
370         u32 guest_cs_ar_bytes;
371         u32 guest_ss_ar_bytes;
372         u32 guest_ds_ar_bytes;
373         u32 guest_fs_ar_bytes;
374         u32 guest_gs_ar_bytes;
375         u32 guest_ldtr_ar_bytes;
376         u32 guest_tr_ar_bytes;
377         u32 guest_interruptibility_info;
378         u32 guest_activity_state;
379         u32 guest_sysenter_cs;
380         u32 host_ia32_sysenter_cs;
381         u32 vmx_preemption_timer_value;
382         u32 padding32[7]; /* room for future expansion */
383         u16 virtual_processor_id;
384         u16 posted_intr_nv;
385         u16 guest_es_selector;
386         u16 guest_cs_selector;
387         u16 guest_ss_selector;
388         u16 guest_ds_selector;
389         u16 guest_fs_selector;
390         u16 guest_gs_selector;
391         u16 guest_ldtr_selector;
392         u16 guest_tr_selector;
393         u16 guest_intr_status;
394         u16 guest_pml_index;
395         u16 host_es_selector;
396         u16 host_cs_selector;
397         u16 host_ss_selector;
398         u16 host_ds_selector;
399         u16 host_fs_selector;
400         u16 host_gs_selector;
401         u16 host_tr_selector;
402 };
403
404 /*
405  * VMCS12_REVISION is an arbitrary id that should be changed if the content or
406  * layout of struct vmcs12 is changed. MSR_IA32_VMX_BASIC returns this id, and
407  * VMPTRLD verifies that the VMCS region that L1 is loading contains this id.
408  */
409 #define VMCS12_REVISION 0x11e57ed0
410
411 /*
412  * VMCS12_SIZE is the number of bytes L1 should allocate for the VMXON region
413  * and any VMCS region. Although only sizeof(struct vmcs12) are used by the
414  * current implementation, 4K are reserved to avoid future complications.
415  */
416 #define VMCS12_SIZE 0x1000
417
418 /*
419  * The nested_vmx structure is part of vcpu_vmx, and holds information we need
420  * for correct emulation of VMX (i.e., nested VMX) on this vcpu.
421  */
422 struct nested_vmx {
423         /* Has the level1 guest done vmxon? */
424         bool vmxon;
425         gpa_t vmxon_ptr;
426         bool pml_full;
427
428         /* The guest-physical address of the current VMCS L1 keeps for L2 */
429         gpa_t current_vmptr;
430         /*
431          * Cache of the guest's VMCS, existing outside of guest memory.
432          * Loaded from guest memory during VMPTRLD. Flushed to guest
433          * memory during VMCLEAR and VMPTRLD.
434          */
435         struct vmcs12 *cached_vmcs12;
436         /*
437          * Indicates if the shadow vmcs must be updated with the
438          * data hold by vmcs12
439          */
440         bool sync_shadow_vmcs;
441
442         bool change_vmcs01_virtual_x2apic_mode;
443         /* L2 must run next, and mustn't decide to exit to L1. */
444         bool nested_run_pending;
445
446         struct loaded_vmcs vmcs02;
447
448         /*
449          * Guest pages referred to in the vmcs02 with host-physical
450          * pointers, so we must keep them pinned while L2 runs.
451          */
452         struct page *apic_access_page;
453         struct page *virtual_apic_page;
454         struct page *pi_desc_page;
455         struct pi_desc *pi_desc;
456         bool pi_pending;
457         u16 posted_intr_nv;
458
459         struct hrtimer preemption_timer;
460         bool preemption_timer_expired;
461
462         /* to migrate it to L2 if VM_ENTRY_LOAD_DEBUG_CONTROLS is off */
463         u64 vmcs01_debugctl;
464
465         u16 vpid02;
466         u16 last_vpid;
467
468         /*
469          * We only store the "true" versions of the VMX capability MSRs. We
470          * generate the "non-true" versions by setting the must-be-1 bits
471          * according to the SDM.
472          */
473         u32 nested_vmx_procbased_ctls_low;
474         u32 nested_vmx_procbased_ctls_high;
475         u32 nested_vmx_secondary_ctls_low;
476         u32 nested_vmx_secondary_ctls_high;
477         u32 nested_vmx_pinbased_ctls_low;
478         u32 nested_vmx_pinbased_ctls_high;
479         u32 nested_vmx_exit_ctls_low;
480         u32 nested_vmx_exit_ctls_high;
481         u32 nested_vmx_entry_ctls_low;
482         u32 nested_vmx_entry_ctls_high;
483         u32 nested_vmx_misc_low;
484         u32 nested_vmx_misc_high;
485         u32 nested_vmx_ept_caps;
486         u32 nested_vmx_vpid_caps;
487         u64 nested_vmx_basic;
488         u64 nested_vmx_cr0_fixed0;
489         u64 nested_vmx_cr0_fixed1;
490         u64 nested_vmx_cr4_fixed0;
491         u64 nested_vmx_cr4_fixed1;
492         u64 nested_vmx_vmcs_enum;
493         u64 nested_vmx_vmfunc_controls;
494 };
495
496 #define POSTED_INTR_ON  0
497 #define POSTED_INTR_SN  1
498
499 /* Posted-Interrupt Descriptor */
500 struct pi_desc {
501         u32 pir[8];     /* Posted interrupt requested */
502         union {
503                 struct {
504                                 /* bit 256 - Outstanding Notification */
505                         u16     on      : 1,
506                                 /* bit 257 - Suppress Notification */
507                                 sn      : 1,
508                                 /* bit 271:258 - Reserved */
509                                 rsvd_1  : 14;
510                                 /* bit 279:272 - Notification Vector */
511                         u8      nv;
512                                 /* bit 287:280 - Reserved */
513                         u8      rsvd_2;
514                                 /* bit 319:288 - Notification Destination */
515                         u32     ndst;
516                 };
517                 u64 control;
518         };
519         u32 rsvd[6];
520 } __aligned(64);
521
522 static bool pi_test_and_set_on(struct pi_desc *pi_desc)
523 {
524         return test_and_set_bit(POSTED_INTR_ON,
525                         (unsigned long *)&pi_desc->control);
526 }
527
528 static bool pi_test_and_clear_on(struct pi_desc *pi_desc)
529 {
530         return test_and_clear_bit(POSTED_INTR_ON,
531                         (unsigned long *)&pi_desc->control);
532 }
533
534 static int pi_test_and_set_pir(int vector, struct pi_desc *pi_desc)
535 {
536         return test_and_set_bit(vector, (unsigned long *)pi_desc->pir);
537 }
538
539 static inline void pi_clear_sn(struct pi_desc *pi_desc)
540 {
541         return clear_bit(POSTED_INTR_SN,
542                         (unsigned long *)&pi_desc->control);
543 }
544
545 static inline void pi_set_sn(struct pi_desc *pi_desc)
546 {
547         return set_bit(POSTED_INTR_SN,
548                         (unsigned long *)&pi_desc->control);
549 }
550
551 static inline void pi_clear_on(struct pi_desc *pi_desc)
552 {
553         clear_bit(POSTED_INTR_ON,
554                   (unsigned long *)&pi_desc->control);
555 }
556
557 static inline int pi_test_on(struct pi_desc *pi_desc)
558 {
559         return test_bit(POSTED_INTR_ON,
560                         (unsigned long *)&pi_desc->control);
561 }
562
563 static inline int pi_test_sn(struct pi_desc *pi_desc)
564 {
565         return test_bit(POSTED_INTR_SN,
566                         (unsigned long *)&pi_desc->control);
567 }
568
569 struct vcpu_vmx {
570         struct kvm_vcpu       vcpu;
571         unsigned long         host_rsp;
572         u8                    fail;
573         u8                    msr_bitmap_mode;
574         u32                   exit_intr_info;
575         u32                   idt_vectoring_info;
576         ulong                 rflags;
577         struct shared_msr_entry *guest_msrs;
578         int                   nmsrs;
579         int                   save_nmsrs;
580         unsigned long         host_idt_base;
581 #ifdef CONFIG_X86_64
582         u64                   msr_host_kernel_gs_base;
583         u64                   msr_guest_kernel_gs_base;
584 #endif
585
586         u64                   arch_capabilities;
587         u64                   spec_ctrl;
588
589         u32 vm_entry_controls_shadow;
590         u32 vm_exit_controls_shadow;
591         u32 secondary_exec_control;
592
593         /*
594          * loaded_vmcs points to the VMCS currently used in this vcpu. For a
595          * non-nested (L1) guest, it always points to vmcs01. For a nested
596          * guest (L2), it points to a different VMCS.
597          */
598         struct loaded_vmcs    vmcs01;
599         struct loaded_vmcs   *loaded_vmcs;
600         bool                  __launched; /* temporary, used in vmx_vcpu_run */
601         struct msr_autoload {
602                 unsigned nr;
603                 struct vmx_msr_entry guest[NR_AUTOLOAD_MSRS];
604                 struct vmx_msr_entry host[NR_AUTOLOAD_MSRS];
605         } msr_autoload;
606         struct {
607                 int           loaded;
608                 u16           fs_sel, gs_sel, ldt_sel;
609 #ifdef CONFIG_X86_64
610                 u16           ds_sel, es_sel;
611 #endif
612                 int           gs_ldt_reload_needed;
613                 int           fs_reload_needed;
614                 u64           msr_host_bndcfgs;
615         } host_state;
616         struct {
617                 int vm86_active;
618                 ulong save_rflags;
619                 struct kvm_segment segs[8];
620         } rmode;
621         struct {
622                 u32 bitmask; /* 4 bits per segment (1 bit per field) */
623                 struct kvm_save_segment {
624                         u16 selector;
625                         unsigned long base;
626                         u32 limit;
627                         u32 ar;
628                 } seg[8];
629         } segment_cache;
630         int vpid;
631         bool emulation_required;
632
633         u32 exit_reason;
634
635         /* Posted interrupt descriptor */
636         struct pi_desc pi_desc;
637
638         /* Support for a guest hypervisor (nested VMX) */
639         struct nested_vmx nested;
640
641         /* Dynamic PLE window. */
642         int ple_window;
643         bool ple_window_dirty;
644
645         /* Support for PML */
646 #define PML_ENTITY_NUM          512
647         struct page *pml_pg;
648
649         /* apic deadline value in host tsc */
650         u64 hv_deadline_tsc;
651
652         u64 current_tsc_ratio;
653
654         u32 host_pkru;
655
656         /*
657          * Only bits masked by msr_ia32_feature_control_valid_bits can be set in
658          * msr_ia32_feature_control. FEATURE_CONTROL_LOCKED is always included
659          * in msr_ia32_feature_control_valid_bits.
660          */
661         u64 msr_ia32_feature_control;
662         u64 msr_ia32_feature_control_valid_bits;
663 };
664
665 enum segment_cache_field {
666         SEG_FIELD_SEL = 0,
667         SEG_FIELD_BASE = 1,
668         SEG_FIELD_LIMIT = 2,
669         SEG_FIELD_AR = 3,
670
671         SEG_FIELD_NR = 4
672 };
673
674 static inline struct vcpu_vmx *to_vmx(struct kvm_vcpu *vcpu)
675 {
676         return container_of(vcpu, struct vcpu_vmx, vcpu);
677 }
678
679 static struct pi_desc *vcpu_to_pi_desc(struct kvm_vcpu *vcpu)
680 {
681         return &(to_vmx(vcpu)->pi_desc);
682 }
683
684 #define VMCS12_OFFSET(x) offsetof(struct vmcs12, x)
685 #define FIELD(number, name)     [number] = VMCS12_OFFSET(name)
686 #define FIELD64(number, name)   [number] = VMCS12_OFFSET(name), \
687                                 [number##_HIGH] = VMCS12_OFFSET(name)+4
688
689
690 static unsigned long shadow_read_only_fields[] = {
691         /*
692          * We do NOT shadow fields that are modified when L0
693          * traps and emulates any vmx instruction (e.g. VMPTRLD,
694          * VMXON...) executed by L1.
695          * For example, VM_INSTRUCTION_ERROR is read
696          * by L1 if a vmx instruction fails (part of the error path).
697          * Note the code assumes this logic. If for some reason
698          * we start shadowing these fields then we need to
699          * force a shadow sync when L0 emulates vmx instructions
700          * (e.g. force a sync if VM_INSTRUCTION_ERROR is modified
701          * by nested_vmx_failValid)
702          */
703         VM_EXIT_REASON,
704         VM_EXIT_INTR_INFO,
705         VM_EXIT_INSTRUCTION_LEN,
706         IDT_VECTORING_INFO_FIELD,
707         IDT_VECTORING_ERROR_CODE,
708         VM_EXIT_INTR_ERROR_CODE,
709         EXIT_QUALIFICATION,
710         GUEST_LINEAR_ADDRESS,
711         GUEST_PHYSICAL_ADDRESS
712 };
713 static int max_shadow_read_only_fields =
714         ARRAY_SIZE(shadow_read_only_fields);
715
716 static unsigned long shadow_read_write_fields[] = {
717         TPR_THRESHOLD,
718         GUEST_RIP,
719         GUEST_RSP,
720         GUEST_CR0,
721         GUEST_CR3,
722         GUEST_CR4,
723         GUEST_INTERRUPTIBILITY_INFO,
724         GUEST_RFLAGS,
725         GUEST_CS_SELECTOR,
726         GUEST_CS_AR_BYTES,
727         GUEST_CS_LIMIT,
728         GUEST_CS_BASE,
729         GUEST_ES_BASE,
730         GUEST_BNDCFGS,
731         CR0_GUEST_HOST_MASK,
732         CR0_READ_SHADOW,
733         CR4_READ_SHADOW,
734         TSC_OFFSET,
735         EXCEPTION_BITMAP,
736         CPU_BASED_VM_EXEC_CONTROL,
737         VM_ENTRY_EXCEPTION_ERROR_CODE,
738         VM_ENTRY_INTR_INFO_FIELD,
739         VM_ENTRY_INSTRUCTION_LEN,
740         VM_ENTRY_EXCEPTION_ERROR_CODE,
741         HOST_FS_BASE,
742         HOST_GS_BASE,
743         HOST_FS_SELECTOR,
744         HOST_GS_SELECTOR
745 };
746 static int max_shadow_read_write_fields =
747         ARRAY_SIZE(shadow_read_write_fields);
748
749 static const unsigned short vmcs_field_to_offset_table[] = {
750         FIELD(VIRTUAL_PROCESSOR_ID, virtual_processor_id),
751         FIELD(POSTED_INTR_NV, posted_intr_nv),
752         FIELD(GUEST_ES_SELECTOR, guest_es_selector),
753         FIELD(GUEST_CS_SELECTOR, guest_cs_selector),
754         FIELD(GUEST_SS_SELECTOR, guest_ss_selector),
755         FIELD(GUEST_DS_SELECTOR, guest_ds_selector),
756         FIELD(GUEST_FS_SELECTOR, guest_fs_selector),
757         FIELD(GUEST_GS_SELECTOR, guest_gs_selector),
758         FIELD(GUEST_LDTR_SELECTOR, guest_ldtr_selector),
759         FIELD(GUEST_TR_SELECTOR, guest_tr_selector),
760         FIELD(GUEST_INTR_STATUS, guest_intr_status),
761         FIELD(GUEST_PML_INDEX, guest_pml_index),
762         FIELD(HOST_ES_SELECTOR, host_es_selector),
763         FIELD(HOST_CS_SELECTOR, host_cs_selector),
764         FIELD(HOST_SS_SELECTOR, host_ss_selector),
765         FIELD(HOST_DS_SELECTOR, host_ds_selector),
766         FIELD(HOST_FS_SELECTOR, host_fs_selector),
767         FIELD(HOST_GS_SELECTOR, host_gs_selector),
768         FIELD(HOST_TR_SELECTOR, host_tr_selector),
769         FIELD64(IO_BITMAP_A, io_bitmap_a),
770         FIELD64(IO_BITMAP_B, io_bitmap_b),
771         FIELD64(MSR_BITMAP, msr_bitmap),
772         FIELD64(VM_EXIT_MSR_STORE_ADDR, vm_exit_msr_store_addr),
773         FIELD64(VM_EXIT_MSR_LOAD_ADDR, vm_exit_msr_load_addr),
774         FIELD64(VM_ENTRY_MSR_LOAD_ADDR, vm_entry_msr_load_addr),
775         FIELD64(TSC_OFFSET, tsc_offset),
776         FIELD64(VIRTUAL_APIC_PAGE_ADDR, virtual_apic_page_addr),
777         FIELD64(APIC_ACCESS_ADDR, apic_access_addr),
778         FIELD64(POSTED_INTR_DESC_ADDR, posted_intr_desc_addr),
779         FIELD64(VM_FUNCTION_CONTROL, vm_function_control),
780         FIELD64(EPT_POINTER, ept_pointer),
781         FIELD64(EOI_EXIT_BITMAP0, eoi_exit_bitmap0),
782         FIELD64(EOI_EXIT_BITMAP1, eoi_exit_bitmap1),
783         FIELD64(EOI_EXIT_BITMAP2, eoi_exit_bitmap2),
784         FIELD64(EOI_EXIT_BITMAP3, eoi_exit_bitmap3),
785         FIELD64(EPTP_LIST_ADDRESS, eptp_list_address),
786         FIELD64(XSS_EXIT_BITMAP, xss_exit_bitmap),
787         FIELD64(GUEST_PHYSICAL_ADDRESS, guest_physical_address),
788         FIELD64(VMCS_LINK_POINTER, vmcs_link_pointer),
789         FIELD64(PML_ADDRESS, pml_address),
790         FIELD64(GUEST_IA32_DEBUGCTL, guest_ia32_debugctl),
791         FIELD64(GUEST_IA32_PAT, guest_ia32_pat),
792         FIELD64(GUEST_IA32_EFER, guest_ia32_efer),
793         FIELD64(GUEST_IA32_PERF_GLOBAL_CTRL, guest_ia32_perf_global_ctrl),
794         FIELD64(GUEST_PDPTR0, guest_pdptr0),
795         FIELD64(GUEST_PDPTR1, guest_pdptr1),
796         FIELD64(GUEST_PDPTR2, guest_pdptr2),
797         FIELD64(GUEST_PDPTR3, guest_pdptr3),
798         FIELD64(GUEST_BNDCFGS, guest_bndcfgs),
799         FIELD64(HOST_IA32_PAT, host_ia32_pat),
800         FIELD64(HOST_IA32_EFER, host_ia32_efer),
801         FIELD64(HOST_IA32_PERF_GLOBAL_CTRL, host_ia32_perf_global_ctrl),
802         FIELD(PIN_BASED_VM_EXEC_CONTROL, pin_based_vm_exec_control),
803         FIELD(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control),
804         FIELD(EXCEPTION_BITMAP, exception_bitmap),
805         FIELD(PAGE_FAULT_ERROR_CODE_MASK, page_fault_error_code_mask),
806         FIELD(PAGE_FAULT_ERROR_CODE_MATCH, page_fault_error_code_match),
807         FIELD(CR3_TARGET_COUNT, cr3_target_count),
808         FIELD(VM_EXIT_CONTROLS, vm_exit_controls),
809         FIELD(VM_EXIT_MSR_STORE_COUNT, vm_exit_msr_store_count),
810         FIELD(VM_EXIT_MSR_LOAD_COUNT, vm_exit_msr_load_count),
811         FIELD(VM_ENTRY_CONTROLS, vm_entry_controls),
812         FIELD(VM_ENTRY_MSR_LOAD_COUNT, vm_entry_msr_load_count),
813         FIELD(VM_ENTRY_INTR_INFO_FIELD, vm_entry_intr_info_field),
814         FIELD(VM_ENTRY_EXCEPTION_ERROR_CODE, vm_entry_exception_error_code),
815         FIELD(VM_ENTRY_INSTRUCTION_LEN, vm_entry_instruction_len),
816         FIELD(TPR_THRESHOLD, tpr_threshold),
817         FIELD(SECONDARY_VM_EXEC_CONTROL, secondary_vm_exec_control),
818         FIELD(VM_INSTRUCTION_ERROR, vm_instruction_error),
819         FIELD(VM_EXIT_REASON, vm_exit_reason),
820         FIELD(VM_EXIT_INTR_INFO, vm_exit_intr_info),
821         FIELD(VM_EXIT_INTR_ERROR_CODE, vm_exit_intr_error_code),
822         FIELD(IDT_VECTORING_INFO_FIELD, idt_vectoring_info_field),
823         FIELD(IDT_VECTORING_ERROR_CODE, idt_vectoring_error_code),
824         FIELD(VM_EXIT_INSTRUCTION_LEN, vm_exit_instruction_len),
825         FIELD(VMX_INSTRUCTION_INFO, vmx_instruction_info),
826         FIELD(GUEST_ES_LIMIT, guest_es_limit),
827         FIELD(GUEST_CS_LIMIT, guest_cs_limit),
828         FIELD(GUEST_SS_LIMIT, guest_ss_limit),
829         FIELD(GUEST_DS_LIMIT, guest_ds_limit),
830         FIELD(GUEST_FS_LIMIT, guest_fs_limit),
831         FIELD(GUEST_GS_LIMIT, guest_gs_limit),
832         FIELD(GUEST_LDTR_LIMIT, guest_ldtr_limit),
833         FIELD(GUEST_TR_LIMIT, guest_tr_limit),
834         FIELD(GUEST_GDTR_LIMIT, guest_gdtr_limit),
835         FIELD(GUEST_IDTR_LIMIT, guest_idtr_limit),
836         FIELD(GUEST_ES_AR_BYTES, guest_es_ar_bytes),
837         FIELD(GUEST_CS_AR_BYTES, guest_cs_ar_bytes),
838         FIELD(GUEST_SS_AR_BYTES, guest_ss_ar_bytes),
839         FIELD(GUEST_DS_AR_BYTES, guest_ds_ar_bytes),
840         FIELD(GUEST_FS_AR_BYTES, guest_fs_ar_bytes),
841         FIELD(GUEST_GS_AR_BYTES, guest_gs_ar_bytes),
842         FIELD(GUEST_LDTR_AR_BYTES, guest_ldtr_ar_bytes),
843         FIELD(GUEST_TR_AR_BYTES, guest_tr_ar_bytes),
844         FIELD(GUEST_INTERRUPTIBILITY_INFO, guest_interruptibility_info),
845         FIELD(GUEST_ACTIVITY_STATE, guest_activity_state),
846         FIELD(GUEST_SYSENTER_CS, guest_sysenter_cs),
847         FIELD(HOST_IA32_SYSENTER_CS, host_ia32_sysenter_cs),
848         FIELD(VMX_PREEMPTION_TIMER_VALUE, vmx_preemption_timer_value),
849         FIELD(CR0_GUEST_HOST_MASK, cr0_guest_host_mask),
850         FIELD(CR4_GUEST_HOST_MASK, cr4_guest_host_mask),
851         FIELD(CR0_READ_SHADOW, cr0_read_shadow),
852         FIELD(CR4_READ_SHADOW, cr4_read_shadow),
853         FIELD(CR3_TARGET_VALUE0, cr3_target_value0),
854         FIELD(CR3_TARGET_VALUE1, cr3_target_value1),
855         FIELD(CR3_TARGET_VALUE2, cr3_target_value2),
856         FIELD(CR3_TARGET_VALUE3, cr3_target_value3),
857         FIELD(EXIT_QUALIFICATION, exit_qualification),
858         FIELD(GUEST_LINEAR_ADDRESS, guest_linear_address),
859         FIELD(GUEST_CR0, guest_cr0),
860         FIELD(GUEST_CR3, guest_cr3),
861         FIELD(GUEST_CR4, guest_cr4),
862         FIELD(GUEST_ES_BASE, guest_es_base),
863         FIELD(GUEST_CS_BASE, guest_cs_base),
864         FIELD(GUEST_SS_BASE, guest_ss_base),
865         FIELD(GUEST_DS_BASE, guest_ds_base),
866         FIELD(GUEST_FS_BASE, guest_fs_base),
867         FIELD(GUEST_GS_BASE, guest_gs_base),
868         FIELD(GUEST_LDTR_BASE, guest_ldtr_base),
869         FIELD(GUEST_TR_BASE, guest_tr_base),
870         FIELD(GUEST_GDTR_BASE, guest_gdtr_base),
871         FIELD(GUEST_IDTR_BASE, guest_idtr_base),
872         FIELD(GUEST_DR7, guest_dr7),
873         FIELD(GUEST_RSP, guest_rsp),
874         FIELD(GUEST_RIP, guest_rip),
875         FIELD(GUEST_RFLAGS, guest_rflags),
876         FIELD(GUEST_PENDING_DBG_EXCEPTIONS, guest_pending_dbg_exceptions),
877         FIELD(GUEST_SYSENTER_ESP, guest_sysenter_esp),
878         FIELD(GUEST_SYSENTER_EIP, guest_sysenter_eip),
879         FIELD(HOST_CR0, host_cr0),
880         FIELD(HOST_CR3, host_cr3),
881         FIELD(HOST_CR4, host_cr4),
882         FIELD(HOST_FS_BASE, host_fs_base),
883         FIELD(HOST_GS_BASE, host_gs_base),
884         FIELD(HOST_TR_BASE, host_tr_base),
885         FIELD(HOST_GDTR_BASE, host_gdtr_base),
886         FIELD(HOST_IDTR_BASE, host_idtr_base),
887         FIELD(HOST_IA32_SYSENTER_ESP, host_ia32_sysenter_esp),
888         FIELD(HOST_IA32_SYSENTER_EIP, host_ia32_sysenter_eip),
889         FIELD(HOST_RSP, host_rsp),
890         FIELD(HOST_RIP, host_rip),
891 };
892
893 static inline short vmcs_field_to_offset(unsigned long field)
894 {
895         const size_t size = ARRAY_SIZE(vmcs_field_to_offset_table);
896         unsigned short offset;
897
898         BUILD_BUG_ON(size > SHRT_MAX);
899         if (field >= size)
900                 return -ENOENT;
901
902         field = array_index_nospec(field, size);
903         offset = vmcs_field_to_offset_table[field];
904         if (offset == 0)
905                 return -ENOENT;
906         return offset;
907 }
908
909 static inline struct vmcs12 *get_vmcs12(struct kvm_vcpu *vcpu)
910 {
911         return to_vmx(vcpu)->nested.cached_vmcs12;
912 }
913
914 static bool nested_ept_ad_enabled(struct kvm_vcpu *vcpu);
915 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu);
916 static u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa);
917 static bool vmx_xsaves_supported(void);
918 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr);
919 static void vmx_set_segment(struct kvm_vcpu *vcpu,
920                             struct kvm_segment *var, int seg);
921 static void vmx_get_segment(struct kvm_vcpu *vcpu,
922                             struct kvm_segment *var, int seg);
923 static bool guest_state_valid(struct kvm_vcpu *vcpu);
924 static u32 vmx_segment_access_rights(struct kvm_segment *var);
925 static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx);
926 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx);
927 static int alloc_identity_pagetable(struct kvm *kvm);
928 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu);
929 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked);
930 static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
931                                             u16 error_code);
932 static void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu);
933 static void __always_inline vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
934                                                           u32 msr, int type);
935
936 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
937 static DEFINE_PER_CPU(struct vmcs *, current_vmcs);
938 /*
939  * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
940  * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
941  */
942 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
943
944 /*
945  * We maintian a per-CPU linked-list of vCPU, so in wakeup_handler() we
946  * can find which vCPU should be waken up.
947  */
948 static DEFINE_PER_CPU(struct list_head, blocked_vcpu_on_cpu);
949 static DEFINE_PER_CPU(spinlock_t, blocked_vcpu_on_cpu_lock);
950
951 enum {
952         VMX_IO_BITMAP_A,
953         VMX_IO_BITMAP_B,
954         VMX_VMREAD_BITMAP,
955         VMX_VMWRITE_BITMAP,
956         VMX_BITMAP_NR
957 };
958
959 static unsigned long *vmx_bitmap[VMX_BITMAP_NR];
960
961 #define vmx_io_bitmap_a                      (vmx_bitmap[VMX_IO_BITMAP_A])
962 #define vmx_io_bitmap_b                      (vmx_bitmap[VMX_IO_BITMAP_B])
963 #define vmx_vmread_bitmap                    (vmx_bitmap[VMX_VMREAD_BITMAP])
964 #define vmx_vmwrite_bitmap                   (vmx_bitmap[VMX_VMWRITE_BITMAP])
965
966 static bool cpu_has_load_ia32_efer;
967 static bool cpu_has_load_perf_global_ctrl;
968
969 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
970 static DEFINE_SPINLOCK(vmx_vpid_lock);
971
972 static struct vmcs_config {
973         int size;
974         int order;
975         u32 basic_cap;
976         u32 revision_id;
977         u32 pin_based_exec_ctrl;
978         u32 cpu_based_exec_ctrl;
979         u32 cpu_based_2nd_exec_ctrl;
980         u32 vmexit_ctrl;
981         u32 vmentry_ctrl;
982 } vmcs_config;
983
984 static struct vmx_capability {
985         u32 ept;
986         u32 vpid;
987 } vmx_capability;
988
989 #define VMX_SEGMENT_FIELD(seg)                                  \
990         [VCPU_SREG_##seg] = {                                   \
991                 .selector = GUEST_##seg##_SELECTOR,             \
992                 .base = GUEST_##seg##_BASE,                     \
993                 .limit = GUEST_##seg##_LIMIT,                   \
994                 .ar_bytes = GUEST_##seg##_AR_BYTES,             \
995         }
996
997 static const struct kvm_vmx_segment_field {
998         unsigned selector;
999         unsigned base;
1000         unsigned limit;
1001         unsigned ar_bytes;
1002 } kvm_vmx_segment_fields[] = {
1003         VMX_SEGMENT_FIELD(CS),
1004         VMX_SEGMENT_FIELD(DS),
1005         VMX_SEGMENT_FIELD(ES),
1006         VMX_SEGMENT_FIELD(FS),
1007         VMX_SEGMENT_FIELD(GS),
1008         VMX_SEGMENT_FIELD(SS),
1009         VMX_SEGMENT_FIELD(TR),
1010         VMX_SEGMENT_FIELD(LDTR),
1011 };
1012
1013 static u64 host_efer;
1014
1015 static void ept_save_pdptrs(struct kvm_vcpu *vcpu);
1016
1017 /*
1018  * Keep MSR_STAR at the end, as setup_msrs() will try to optimize it
1019  * away by decrementing the array size.
1020  */
1021 static const u32 vmx_msr_index[] = {
1022 #ifdef CONFIG_X86_64
1023         MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
1024 #endif
1025         MSR_EFER, MSR_TSC_AUX, MSR_STAR,
1026 };
1027
1028 static inline bool is_exception_n(u32 intr_info, u8 vector)
1029 {
1030         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1031                              INTR_INFO_VALID_MASK)) ==
1032                 (INTR_TYPE_HARD_EXCEPTION | vector | INTR_INFO_VALID_MASK);
1033 }
1034
1035 static inline bool is_debug(u32 intr_info)
1036 {
1037         return is_exception_n(intr_info, DB_VECTOR);
1038 }
1039
1040 static inline bool is_breakpoint(u32 intr_info)
1041 {
1042         return is_exception_n(intr_info, BP_VECTOR);
1043 }
1044
1045 static inline bool is_page_fault(u32 intr_info)
1046 {
1047         return is_exception_n(intr_info, PF_VECTOR);
1048 }
1049
1050 static inline bool is_no_device(u32 intr_info)
1051 {
1052         return is_exception_n(intr_info, NM_VECTOR);
1053 }
1054
1055 static inline bool is_invalid_opcode(u32 intr_info)
1056 {
1057         return is_exception_n(intr_info, UD_VECTOR);
1058 }
1059
1060 static inline bool is_external_interrupt(u32 intr_info)
1061 {
1062         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1063                 == (INTR_TYPE_EXT_INTR | INTR_INFO_VALID_MASK);
1064 }
1065
1066 static inline bool is_machine_check(u32 intr_info)
1067 {
1068         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1069                              INTR_INFO_VALID_MASK)) ==
1070                 (INTR_TYPE_HARD_EXCEPTION | MC_VECTOR | INTR_INFO_VALID_MASK);
1071 }
1072
1073 static inline bool cpu_has_vmx_msr_bitmap(void)
1074 {
1075         return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_USE_MSR_BITMAPS;
1076 }
1077
1078 static inline bool cpu_has_vmx_tpr_shadow(void)
1079 {
1080         return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW;
1081 }
1082
1083 static inline bool cpu_need_tpr_shadow(struct kvm_vcpu *vcpu)
1084 {
1085         return cpu_has_vmx_tpr_shadow() && lapic_in_kernel(vcpu);
1086 }
1087
1088 static inline bool cpu_has_secondary_exec_ctrls(void)
1089 {
1090         return vmcs_config.cpu_based_exec_ctrl &
1091                 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
1092 }
1093
1094 static inline bool cpu_has_vmx_virtualize_apic_accesses(void)
1095 {
1096         return vmcs_config.cpu_based_2nd_exec_ctrl &
1097                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
1098 }
1099
1100 static inline bool cpu_has_vmx_virtualize_x2apic_mode(void)
1101 {
1102         return vmcs_config.cpu_based_2nd_exec_ctrl &
1103                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
1104 }
1105
1106 static inline bool cpu_has_vmx_apic_register_virt(void)
1107 {
1108         return vmcs_config.cpu_based_2nd_exec_ctrl &
1109                 SECONDARY_EXEC_APIC_REGISTER_VIRT;
1110 }
1111
1112 static inline bool cpu_has_vmx_virtual_intr_delivery(void)
1113 {
1114         return vmcs_config.cpu_based_2nd_exec_ctrl &
1115                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY;
1116 }
1117
1118 /*
1119  * Comment's format: document - errata name - stepping - processor name.
1120  * Refer from
1121  * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
1122  */
1123 static u32 vmx_preemption_cpu_tfms[] = {
1124 /* 323344.pdf - BA86   - D0 - Xeon 7500 Series */
1125 0x000206E6,
1126 /* 323056.pdf - AAX65  - C2 - Xeon L3406 */
1127 /* 322814.pdf - AAT59  - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
1128 /* 322911.pdf - AAU65  - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
1129 0x00020652,
1130 /* 322911.pdf - AAU65  - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
1131 0x00020655,
1132 /* 322373.pdf - AAO95  - B1 - Xeon 3400 Series */
1133 /* 322166.pdf - AAN92  - B1 - i7-800 and i5-700 Desktop */
1134 /*
1135  * 320767.pdf - AAP86  - B1 -
1136  * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
1137  */
1138 0x000106E5,
1139 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
1140 0x000106A0,
1141 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
1142 0x000106A1,
1143 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
1144 0x000106A4,
1145  /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
1146  /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
1147  /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
1148 0x000106A5,
1149 };
1150
1151 static inline bool cpu_has_broken_vmx_preemption_timer(void)
1152 {
1153         u32 eax = cpuid_eax(0x00000001), i;
1154
1155         /* Clear the reserved bits */
1156         eax &= ~(0x3U << 14 | 0xfU << 28);
1157         for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
1158                 if (eax == vmx_preemption_cpu_tfms[i])
1159                         return true;
1160
1161         return false;
1162 }
1163
1164 static inline bool cpu_has_vmx_preemption_timer(void)
1165 {
1166         return vmcs_config.pin_based_exec_ctrl &
1167                 PIN_BASED_VMX_PREEMPTION_TIMER;
1168 }
1169
1170 static inline bool cpu_has_vmx_posted_intr(void)
1171 {
1172         return IS_ENABLED(CONFIG_X86_LOCAL_APIC) &&
1173                 vmcs_config.pin_based_exec_ctrl & PIN_BASED_POSTED_INTR;
1174 }
1175
1176 static inline bool cpu_has_vmx_apicv(void)
1177 {
1178         return cpu_has_vmx_apic_register_virt() &&
1179                 cpu_has_vmx_virtual_intr_delivery() &&
1180                 cpu_has_vmx_posted_intr();
1181 }
1182
1183 static inline bool cpu_has_vmx_flexpriority(void)
1184 {
1185         return cpu_has_vmx_tpr_shadow() &&
1186                 cpu_has_vmx_virtualize_apic_accesses();
1187 }
1188
1189 static inline bool cpu_has_vmx_ept_execute_only(void)
1190 {
1191         return vmx_capability.ept & VMX_EPT_EXECUTE_ONLY_BIT;
1192 }
1193
1194 static inline bool cpu_has_vmx_ept_2m_page(void)
1195 {
1196         return vmx_capability.ept & VMX_EPT_2MB_PAGE_BIT;
1197 }
1198
1199 static inline bool cpu_has_vmx_ept_1g_page(void)
1200 {
1201         return vmx_capability.ept & VMX_EPT_1GB_PAGE_BIT;
1202 }
1203
1204 static inline bool cpu_has_vmx_ept_4levels(void)
1205 {
1206         return vmx_capability.ept & VMX_EPT_PAGE_WALK_4_BIT;
1207 }
1208
1209 static inline bool cpu_has_vmx_ept_mt_wb(void)
1210 {
1211         return vmx_capability.ept & VMX_EPTP_WB_BIT;
1212 }
1213
1214 static inline bool cpu_has_vmx_ept_5levels(void)
1215 {
1216         return vmx_capability.ept & VMX_EPT_PAGE_WALK_5_BIT;
1217 }
1218
1219 static inline bool cpu_has_vmx_ept_ad_bits(void)
1220 {
1221         return vmx_capability.ept & VMX_EPT_AD_BIT;
1222 }
1223
1224 static inline bool cpu_has_vmx_invept_context(void)
1225 {
1226         return vmx_capability.ept & VMX_EPT_EXTENT_CONTEXT_BIT;
1227 }
1228
1229 static inline bool cpu_has_vmx_invept_global(void)
1230 {
1231         return vmx_capability.ept & VMX_EPT_EXTENT_GLOBAL_BIT;
1232 }
1233
1234 static inline bool cpu_has_vmx_invvpid_single(void)
1235 {
1236         return vmx_capability.vpid & VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT;
1237 }
1238
1239 static inline bool cpu_has_vmx_invvpid_global(void)
1240 {
1241         return vmx_capability.vpid & VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT;
1242 }
1243
1244 static inline bool cpu_has_vmx_invvpid(void)
1245 {
1246         return vmx_capability.vpid & VMX_VPID_INVVPID_BIT;
1247 }
1248
1249 static inline bool cpu_has_vmx_ept(void)
1250 {
1251         return vmcs_config.cpu_based_2nd_exec_ctrl &
1252                 SECONDARY_EXEC_ENABLE_EPT;
1253 }
1254
1255 static inline bool cpu_has_vmx_unrestricted_guest(void)
1256 {
1257         return vmcs_config.cpu_based_2nd_exec_ctrl &
1258                 SECONDARY_EXEC_UNRESTRICTED_GUEST;
1259 }
1260
1261 static inline bool cpu_has_vmx_ple(void)
1262 {
1263         return vmcs_config.cpu_based_2nd_exec_ctrl &
1264                 SECONDARY_EXEC_PAUSE_LOOP_EXITING;
1265 }
1266
1267 static inline bool cpu_has_vmx_basic_inout(void)
1268 {
1269         return  (((u64)vmcs_config.basic_cap << 32) & VMX_BASIC_INOUT);
1270 }
1271
1272 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
1273 {
1274         return flexpriority_enabled && lapic_in_kernel(vcpu);
1275 }
1276
1277 static inline bool cpu_has_vmx_vpid(void)
1278 {
1279         return vmcs_config.cpu_based_2nd_exec_ctrl &
1280                 SECONDARY_EXEC_ENABLE_VPID;
1281 }
1282
1283 static inline bool cpu_has_vmx_rdtscp(void)
1284 {
1285         return vmcs_config.cpu_based_2nd_exec_ctrl &
1286                 SECONDARY_EXEC_RDTSCP;
1287 }
1288
1289 static inline bool cpu_has_vmx_invpcid(void)
1290 {
1291         return vmcs_config.cpu_based_2nd_exec_ctrl &
1292                 SECONDARY_EXEC_ENABLE_INVPCID;
1293 }
1294
1295 static inline bool cpu_has_virtual_nmis(void)
1296 {
1297         return vmcs_config.pin_based_exec_ctrl & PIN_BASED_VIRTUAL_NMIS;
1298 }
1299
1300 static inline bool cpu_has_vmx_wbinvd_exit(void)
1301 {
1302         return vmcs_config.cpu_based_2nd_exec_ctrl &
1303                 SECONDARY_EXEC_WBINVD_EXITING;
1304 }
1305
1306 static inline bool cpu_has_vmx_shadow_vmcs(void)
1307 {
1308         u64 vmx_msr;
1309         rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
1310         /* check if the cpu supports writing r/o exit information fields */
1311         if (!(vmx_msr & MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS))
1312                 return false;
1313
1314         return vmcs_config.cpu_based_2nd_exec_ctrl &
1315                 SECONDARY_EXEC_SHADOW_VMCS;
1316 }
1317
1318 static inline bool cpu_has_vmx_pml(void)
1319 {
1320         return vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_ENABLE_PML;
1321 }
1322
1323 static inline bool cpu_has_vmx_tsc_scaling(void)
1324 {
1325         return vmcs_config.cpu_based_2nd_exec_ctrl &
1326                 SECONDARY_EXEC_TSC_SCALING;
1327 }
1328
1329 static inline bool cpu_has_vmx_vmfunc(void)
1330 {
1331         return vmcs_config.cpu_based_2nd_exec_ctrl &
1332                 SECONDARY_EXEC_ENABLE_VMFUNC;
1333 }
1334
1335 static inline bool report_flexpriority(void)
1336 {
1337         return flexpriority_enabled;
1338 }
1339
1340 static inline unsigned nested_cpu_vmx_misc_cr3_count(struct kvm_vcpu *vcpu)
1341 {
1342         return vmx_misc_cr3_count(to_vmx(vcpu)->nested.nested_vmx_misc_low);
1343 }
1344
1345 static inline bool nested_cpu_has(struct vmcs12 *vmcs12, u32 bit)
1346 {
1347         return vmcs12->cpu_based_vm_exec_control & bit;
1348 }
1349
1350 static inline bool nested_cpu_has2(struct vmcs12 *vmcs12, u32 bit)
1351 {
1352         return (vmcs12->cpu_based_vm_exec_control &
1353                         CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
1354                 (vmcs12->secondary_vm_exec_control & bit);
1355 }
1356
1357 static inline bool nested_cpu_has_preemption_timer(struct vmcs12 *vmcs12)
1358 {
1359         return vmcs12->pin_based_vm_exec_control &
1360                 PIN_BASED_VMX_PREEMPTION_TIMER;
1361 }
1362
1363 static inline int nested_cpu_has_ept(struct vmcs12 *vmcs12)
1364 {
1365         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_EPT);
1366 }
1367
1368 static inline bool nested_cpu_has_xsaves(struct vmcs12 *vmcs12)
1369 {
1370         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
1371 }
1372
1373 static inline bool nested_cpu_has_pml(struct vmcs12 *vmcs12)
1374 {
1375         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_PML);
1376 }
1377
1378 static inline bool nested_cpu_has_virt_x2apic_mode(struct vmcs12 *vmcs12)
1379 {
1380         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
1381 }
1382
1383 static inline bool nested_cpu_has_vpid(struct vmcs12 *vmcs12)
1384 {
1385         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VPID);
1386 }
1387
1388 static inline bool nested_cpu_has_apic_reg_virt(struct vmcs12 *vmcs12)
1389 {
1390         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_APIC_REGISTER_VIRT);
1391 }
1392
1393 static inline bool nested_cpu_has_vid(struct vmcs12 *vmcs12)
1394 {
1395         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
1396 }
1397
1398 static inline bool nested_cpu_has_posted_intr(struct vmcs12 *vmcs12)
1399 {
1400         return vmcs12->pin_based_vm_exec_control & PIN_BASED_POSTED_INTR;
1401 }
1402
1403 static inline bool nested_cpu_has_vmfunc(struct vmcs12 *vmcs12)
1404 {
1405         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VMFUNC);
1406 }
1407
1408 static inline bool nested_cpu_has_eptp_switching(struct vmcs12 *vmcs12)
1409 {
1410         return nested_cpu_has_vmfunc(vmcs12) &&
1411                 (vmcs12->vm_function_control &
1412                  VMX_VMFUNC_EPTP_SWITCHING);
1413 }
1414
1415 static inline bool is_nmi(u32 intr_info)
1416 {
1417         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1418                 == (INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK);
1419 }
1420
1421 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
1422                               u32 exit_intr_info,
1423                               unsigned long exit_qualification);
1424 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
1425                         struct vmcs12 *vmcs12,
1426                         u32 reason, unsigned long qualification);
1427
1428 static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
1429 {
1430         int i;
1431
1432         for (i = 0; i < vmx->nmsrs; ++i)
1433                 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
1434                         return i;
1435         return -1;
1436 }
1437
1438 static inline void __invvpid(int ext, u16 vpid, gva_t gva)
1439 {
1440     struct {
1441         u64 vpid : 16;
1442         u64 rsvd : 48;
1443         u64 gva;
1444     } operand = { vpid, 0, gva };
1445
1446     asm volatile (__ex(ASM_VMX_INVVPID)
1447                   /* CF==1 or ZF==1 --> rc = -1 */
1448                   "; ja 1f ; ud2 ; 1:"
1449                   : : "a"(&operand), "c"(ext) : "cc", "memory");
1450 }
1451
1452 static inline void __invept(int ext, u64 eptp, gpa_t gpa)
1453 {
1454         struct {
1455                 u64 eptp, gpa;
1456         } operand = {eptp, gpa};
1457
1458         asm volatile (__ex(ASM_VMX_INVEPT)
1459                         /* CF==1 or ZF==1 --> rc = -1 */
1460                         "; ja 1f ; ud2 ; 1:\n"
1461                         : : "a" (&operand), "c" (ext) : "cc", "memory");
1462 }
1463
1464 static struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
1465 {
1466         int i;
1467
1468         i = __find_msr_index(vmx, msr);
1469         if (i >= 0)
1470                 return &vmx->guest_msrs[i];
1471         return NULL;
1472 }
1473
1474 static void vmcs_clear(struct vmcs *vmcs)
1475 {
1476         u64 phys_addr = __pa(vmcs);
1477         u8 error;
1478
1479         asm volatile (__ex(ASM_VMX_VMCLEAR_RAX) "; setna %0"
1480                       : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
1481                       : "cc", "memory");
1482         if (error)
1483                 printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n",
1484                        vmcs, phys_addr);
1485 }
1486
1487 static inline void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
1488 {
1489         vmcs_clear(loaded_vmcs->vmcs);
1490         if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
1491                 vmcs_clear(loaded_vmcs->shadow_vmcs);
1492         loaded_vmcs->cpu = -1;
1493         loaded_vmcs->launched = 0;
1494 }
1495
1496 static void vmcs_load(struct vmcs *vmcs)
1497 {
1498         u64 phys_addr = __pa(vmcs);
1499         u8 error;
1500
1501         asm volatile (__ex(ASM_VMX_VMPTRLD_RAX) "; setna %0"
1502                         : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
1503                         : "cc", "memory");
1504         if (error)
1505                 printk(KERN_ERR "kvm: vmptrld %p/%llx failed\n",
1506                        vmcs, phys_addr);
1507 }
1508
1509 #ifdef CONFIG_KEXEC_CORE
1510 /*
1511  * This bitmap is used to indicate whether the vmclear
1512  * operation is enabled on all cpus. All disabled by
1513  * default.
1514  */
1515 static cpumask_t crash_vmclear_enabled_bitmap = CPU_MASK_NONE;
1516
1517 static inline void crash_enable_local_vmclear(int cpu)
1518 {
1519         cpumask_set_cpu(cpu, &crash_vmclear_enabled_bitmap);
1520 }
1521
1522 static inline void crash_disable_local_vmclear(int cpu)
1523 {
1524         cpumask_clear_cpu(cpu, &crash_vmclear_enabled_bitmap);
1525 }
1526
1527 static inline int crash_local_vmclear_enabled(int cpu)
1528 {
1529         return cpumask_test_cpu(cpu, &crash_vmclear_enabled_bitmap);
1530 }
1531
1532 static void crash_vmclear_local_loaded_vmcss(void)
1533 {
1534         int cpu = raw_smp_processor_id();
1535         struct loaded_vmcs *v;
1536
1537         if (!crash_local_vmclear_enabled(cpu))
1538                 return;
1539
1540         list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
1541                             loaded_vmcss_on_cpu_link)
1542                 vmcs_clear(v->vmcs);
1543 }
1544 #else
1545 static inline void crash_enable_local_vmclear(int cpu) { }
1546 static inline void crash_disable_local_vmclear(int cpu) { }
1547 #endif /* CONFIG_KEXEC_CORE */
1548
1549 static void __loaded_vmcs_clear(void *arg)
1550 {
1551         struct loaded_vmcs *loaded_vmcs = arg;
1552         int cpu = raw_smp_processor_id();
1553
1554         if (loaded_vmcs->cpu != cpu)
1555                 return; /* vcpu migration can race with cpu offline */
1556         if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
1557                 per_cpu(current_vmcs, cpu) = NULL;
1558         crash_disable_local_vmclear(cpu);
1559         list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
1560
1561         /*
1562          * we should ensure updating loaded_vmcs->loaded_vmcss_on_cpu_link
1563          * is before setting loaded_vmcs->vcpu to -1 which is done in
1564          * loaded_vmcs_init. Otherwise, other cpu can see vcpu = -1 fist
1565          * then adds the vmcs into percpu list before it is deleted.
1566          */
1567         smp_wmb();
1568
1569         loaded_vmcs_init(loaded_vmcs);
1570         crash_enable_local_vmclear(cpu);
1571 }
1572
1573 static void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
1574 {
1575         int cpu = loaded_vmcs->cpu;
1576
1577         if (cpu != -1)
1578                 smp_call_function_single(cpu,
1579                          __loaded_vmcs_clear, loaded_vmcs, 1);
1580 }
1581
1582 static inline void vpid_sync_vcpu_single(int vpid)
1583 {
1584         if (vpid == 0)
1585                 return;
1586
1587         if (cpu_has_vmx_invvpid_single())
1588                 __invvpid(VMX_VPID_EXTENT_SINGLE_CONTEXT, vpid, 0);
1589 }
1590
1591 static inline void vpid_sync_vcpu_global(void)
1592 {
1593         if (cpu_has_vmx_invvpid_global())
1594                 __invvpid(VMX_VPID_EXTENT_ALL_CONTEXT, 0, 0);
1595 }
1596
1597 static inline void vpid_sync_context(int vpid)
1598 {
1599         if (cpu_has_vmx_invvpid_single())
1600                 vpid_sync_vcpu_single(vpid);
1601         else
1602                 vpid_sync_vcpu_global();
1603 }
1604
1605 static inline void ept_sync_global(void)
1606 {
1607         if (cpu_has_vmx_invept_global())
1608                 __invept(VMX_EPT_EXTENT_GLOBAL, 0, 0);
1609 }
1610
1611 static inline void ept_sync_context(u64 eptp)
1612 {
1613         if (enable_ept) {
1614                 if (cpu_has_vmx_invept_context())
1615                         __invept(VMX_EPT_EXTENT_CONTEXT, eptp, 0);
1616                 else
1617                         ept_sync_global();
1618         }
1619 }
1620
1621 static __always_inline void vmcs_check16(unsigned long field)
1622 {
1623         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
1624                          "16-bit accessor invalid for 64-bit field");
1625         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
1626                          "16-bit accessor invalid for 64-bit high field");
1627         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
1628                          "16-bit accessor invalid for 32-bit high field");
1629         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
1630                          "16-bit accessor invalid for natural width field");
1631 }
1632
1633 static __always_inline void vmcs_check32(unsigned long field)
1634 {
1635         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
1636                          "32-bit accessor invalid for 16-bit field");
1637         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
1638                          "32-bit accessor invalid for natural width field");
1639 }
1640
1641 static __always_inline void vmcs_check64(unsigned long field)
1642 {
1643         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
1644                          "64-bit accessor invalid for 16-bit field");
1645         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
1646                          "64-bit accessor invalid for 64-bit high field");
1647         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
1648                          "64-bit accessor invalid for 32-bit field");
1649         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
1650                          "64-bit accessor invalid for natural width field");
1651 }
1652
1653 static __always_inline void vmcs_checkl(unsigned long field)
1654 {
1655         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
1656                          "Natural width accessor invalid for 16-bit field");
1657         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
1658                          "Natural width accessor invalid for 64-bit field");
1659         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
1660                          "Natural width accessor invalid for 64-bit high field");
1661         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
1662                          "Natural width accessor invalid for 32-bit field");
1663 }
1664
1665 static __always_inline unsigned long __vmcs_readl(unsigned long field)
1666 {
1667         unsigned long value;
1668
1669         asm volatile (__ex_clear(ASM_VMX_VMREAD_RDX_RAX, "%0")
1670                       : "=a"(value) : "d"(field) : "cc");
1671         return value;
1672 }
1673
1674 static __always_inline u16 vmcs_read16(unsigned long field)
1675 {
1676         vmcs_check16(field);
1677         return __vmcs_readl(field);
1678 }
1679
1680 static __always_inline u32 vmcs_read32(unsigned long field)
1681 {
1682         vmcs_check32(field);
1683         return __vmcs_readl(field);
1684 }
1685
1686 static __always_inline u64 vmcs_read64(unsigned long field)
1687 {
1688         vmcs_check64(field);
1689 #ifdef CONFIG_X86_64
1690         return __vmcs_readl(field);
1691 #else
1692         return __vmcs_readl(field) | ((u64)__vmcs_readl(field+1) << 32);
1693 #endif
1694 }
1695
1696 static __always_inline unsigned long vmcs_readl(unsigned long field)
1697 {
1698         vmcs_checkl(field);
1699         return __vmcs_readl(field);
1700 }
1701
1702 static noinline void vmwrite_error(unsigned long field, unsigned long value)
1703 {
1704         printk(KERN_ERR "vmwrite error: reg %lx value %lx (err %d)\n",
1705                field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
1706         dump_stack();
1707 }
1708
1709 static __always_inline void __vmcs_writel(unsigned long field, unsigned long value)
1710 {
1711         u8 error;
1712
1713         asm volatile (__ex(ASM_VMX_VMWRITE_RAX_RDX) "; setna %0"
1714                        : "=q"(error) : "a"(value), "d"(field) : "cc");
1715         if (unlikely(error))
1716                 vmwrite_error(field, value);
1717 }
1718
1719 static __always_inline void vmcs_write16(unsigned long field, u16 value)
1720 {
1721         vmcs_check16(field);
1722         __vmcs_writel(field, value);
1723 }
1724
1725 static __always_inline void vmcs_write32(unsigned long field, u32 value)
1726 {
1727         vmcs_check32(field);
1728         __vmcs_writel(field, value);
1729 }
1730
1731 static __always_inline void vmcs_write64(unsigned long field, u64 value)
1732 {
1733         vmcs_check64(field);
1734         __vmcs_writel(field, value);
1735 #ifndef CONFIG_X86_64
1736         asm volatile ("");
1737         __vmcs_writel(field+1, value >> 32);
1738 #endif
1739 }
1740
1741 static __always_inline void vmcs_writel(unsigned long field, unsigned long value)
1742 {
1743         vmcs_checkl(field);
1744         __vmcs_writel(field, value);
1745 }
1746
1747 static __always_inline void vmcs_clear_bits(unsigned long field, u32 mask)
1748 {
1749         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
1750                          "vmcs_clear_bits does not support 64-bit fields");
1751         __vmcs_writel(field, __vmcs_readl(field) & ~mask);
1752 }
1753
1754 static __always_inline void vmcs_set_bits(unsigned long field, u32 mask)
1755 {
1756         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
1757                          "vmcs_set_bits does not support 64-bit fields");
1758         __vmcs_writel(field, __vmcs_readl(field) | mask);
1759 }
1760
1761 static inline void vm_entry_controls_reset_shadow(struct vcpu_vmx *vmx)
1762 {
1763         vmx->vm_entry_controls_shadow = vmcs_read32(VM_ENTRY_CONTROLS);
1764 }
1765
1766 static inline void vm_entry_controls_init(struct vcpu_vmx *vmx, u32 val)
1767 {
1768         vmcs_write32(VM_ENTRY_CONTROLS, val);
1769         vmx->vm_entry_controls_shadow = val;
1770 }
1771
1772 static inline void vm_entry_controls_set(struct vcpu_vmx *vmx, u32 val)
1773 {
1774         if (vmx->vm_entry_controls_shadow != val)
1775                 vm_entry_controls_init(vmx, val);
1776 }
1777
1778 static inline u32 vm_entry_controls_get(struct vcpu_vmx *vmx)
1779 {
1780         return vmx->vm_entry_controls_shadow;
1781 }
1782
1783
1784 static inline void vm_entry_controls_setbit(struct vcpu_vmx *vmx, u32 val)
1785 {
1786         vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) | val);
1787 }
1788
1789 static inline void vm_entry_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
1790 {
1791         vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) & ~val);
1792 }
1793
1794 static inline void vm_exit_controls_reset_shadow(struct vcpu_vmx *vmx)
1795 {
1796         vmx->vm_exit_controls_shadow = vmcs_read32(VM_EXIT_CONTROLS);
1797 }
1798
1799 static inline void vm_exit_controls_init(struct vcpu_vmx *vmx, u32 val)
1800 {
1801         vmcs_write32(VM_EXIT_CONTROLS, val);
1802         vmx->vm_exit_controls_shadow = val;
1803 }
1804
1805 static inline void vm_exit_controls_set(struct vcpu_vmx *vmx, u32 val)
1806 {
1807         if (vmx->vm_exit_controls_shadow != val)
1808                 vm_exit_controls_init(vmx, val);
1809 }
1810
1811 static inline u32 vm_exit_controls_get(struct vcpu_vmx *vmx)
1812 {
1813         return vmx->vm_exit_controls_shadow;
1814 }
1815
1816
1817 static inline void vm_exit_controls_setbit(struct vcpu_vmx *vmx, u32 val)
1818 {
1819         vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) | val);
1820 }
1821
1822 static inline void vm_exit_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
1823 {
1824         vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) & ~val);
1825 }
1826
1827 static void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
1828 {
1829         vmx->segment_cache.bitmask = 0;
1830 }
1831
1832 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
1833                                        unsigned field)
1834 {
1835         bool ret;
1836         u32 mask = 1 << (seg * SEG_FIELD_NR + field);
1837
1838         if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
1839                 vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
1840                 vmx->segment_cache.bitmask = 0;
1841         }
1842         ret = vmx->segment_cache.bitmask & mask;
1843         vmx->segment_cache.bitmask |= mask;
1844         return ret;
1845 }
1846
1847 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
1848 {
1849         u16 *p = &vmx->segment_cache.seg[seg].selector;
1850
1851         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
1852                 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
1853         return *p;
1854 }
1855
1856 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
1857 {
1858         ulong *p = &vmx->segment_cache.seg[seg].base;
1859
1860         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
1861                 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
1862         return *p;
1863 }
1864
1865 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
1866 {
1867         u32 *p = &vmx->segment_cache.seg[seg].limit;
1868
1869         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
1870                 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
1871         return *p;
1872 }
1873
1874 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
1875 {
1876         u32 *p = &vmx->segment_cache.seg[seg].ar;
1877
1878         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
1879                 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
1880         return *p;
1881 }
1882
1883 static void update_exception_bitmap(struct kvm_vcpu *vcpu)
1884 {
1885         u32 eb;
1886
1887         eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
1888              (1u << DB_VECTOR) | (1u << AC_VECTOR);
1889         if ((vcpu->guest_debug &
1890              (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
1891             (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
1892                 eb |= 1u << BP_VECTOR;
1893         if (to_vmx(vcpu)->rmode.vm86_active)
1894                 eb = ~0;
1895         if (enable_ept)
1896                 eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
1897
1898         /* When we are running a nested L2 guest and L1 specified for it a
1899          * certain exception bitmap, we must trap the same exceptions and pass
1900          * them to L1. When running L2, we will only handle the exceptions
1901          * specified above if L1 did not want them.
1902          */
1903         if (is_guest_mode(vcpu))
1904                 eb |= get_vmcs12(vcpu)->exception_bitmap;
1905
1906         vmcs_write32(EXCEPTION_BITMAP, eb);
1907 }
1908
1909 /*
1910  * Check if MSR is intercepted for currently loaded MSR bitmap.
1911  */
1912 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
1913 {
1914         unsigned long *msr_bitmap;
1915         int f = sizeof(unsigned long);
1916
1917         if (!cpu_has_vmx_msr_bitmap())
1918                 return true;
1919
1920         msr_bitmap = to_vmx(vcpu)->loaded_vmcs->msr_bitmap;
1921
1922         if (msr <= 0x1fff) {
1923                 return !!test_bit(msr, msr_bitmap + 0x800 / f);
1924         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
1925                 msr &= 0x1fff;
1926                 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
1927         }
1928
1929         return true;
1930 }
1931
1932 /*
1933  * Check if MSR is intercepted for L01 MSR bitmap.
1934  */
1935 static bool msr_write_intercepted_l01(struct kvm_vcpu *vcpu, u32 msr)
1936 {
1937         unsigned long *msr_bitmap;
1938         int f = sizeof(unsigned long);
1939
1940         if (!cpu_has_vmx_msr_bitmap())
1941                 return true;
1942
1943         msr_bitmap = to_vmx(vcpu)->vmcs01.msr_bitmap;
1944
1945         if (msr <= 0x1fff) {
1946                 return !!test_bit(msr, msr_bitmap + 0x800 / f);
1947         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
1948                 msr &= 0x1fff;
1949                 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
1950         }
1951
1952         return true;
1953 }
1954
1955 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
1956                 unsigned long entry, unsigned long exit)
1957 {
1958         vm_entry_controls_clearbit(vmx, entry);
1959         vm_exit_controls_clearbit(vmx, exit);
1960 }
1961
1962 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
1963 {
1964         unsigned i;
1965         struct msr_autoload *m = &vmx->msr_autoload;
1966
1967         switch (msr) {
1968         case MSR_EFER:
1969                 if (cpu_has_load_ia32_efer) {
1970                         clear_atomic_switch_msr_special(vmx,
1971                                         VM_ENTRY_LOAD_IA32_EFER,
1972                                         VM_EXIT_LOAD_IA32_EFER);
1973                         return;
1974                 }
1975                 break;
1976         case MSR_CORE_PERF_GLOBAL_CTRL:
1977                 if (cpu_has_load_perf_global_ctrl) {
1978                         clear_atomic_switch_msr_special(vmx,
1979                                         VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
1980                                         VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
1981                         return;
1982                 }
1983                 break;
1984         }
1985
1986         for (i = 0; i < m->nr; ++i)
1987                 if (m->guest[i].index == msr)
1988                         break;
1989
1990         if (i == m->nr)
1991                 return;
1992         --m->nr;
1993         m->guest[i] = m->guest[m->nr];
1994         m->host[i] = m->host[m->nr];
1995         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
1996         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
1997 }
1998
1999 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
2000                 unsigned long entry, unsigned long exit,
2001                 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
2002                 u64 guest_val, u64 host_val)
2003 {
2004         vmcs_write64(guest_val_vmcs, guest_val);
2005         vmcs_write64(host_val_vmcs, host_val);
2006         vm_entry_controls_setbit(vmx, entry);
2007         vm_exit_controls_setbit(vmx, exit);
2008 }
2009
2010 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
2011                                   u64 guest_val, u64 host_val)
2012 {
2013         unsigned i;
2014         struct msr_autoload *m = &vmx->msr_autoload;
2015
2016         switch (msr) {
2017         case MSR_EFER:
2018                 if (cpu_has_load_ia32_efer) {
2019                         add_atomic_switch_msr_special(vmx,
2020                                         VM_ENTRY_LOAD_IA32_EFER,
2021                                         VM_EXIT_LOAD_IA32_EFER,
2022                                         GUEST_IA32_EFER,
2023                                         HOST_IA32_EFER,
2024                                         guest_val, host_val);
2025                         return;
2026                 }
2027                 break;
2028         case MSR_CORE_PERF_GLOBAL_CTRL:
2029                 if (cpu_has_load_perf_global_ctrl) {
2030                         add_atomic_switch_msr_special(vmx,
2031                                         VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
2032                                         VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
2033                                         GUEST_IA32_PERF_GLOBAL_CTRL,
2034                                         HOST_IA32_PERF_GLOBAL_CTRL,
2035                                         guest_val, host_val);
2036                         return;
2037                 }
2038                 break;
2039         case MSR_IA32_PEBS_ENABLE:
2040                 /* PEBS needs a quiescent period after being disabled (to write
2041                  * a record).  Disabling PEBS through VMX MSR swapping doesn't
2042                  * provide that period, so a CPU could write host's record into
2043                  * guest's memory.
2044                  */
2045                 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
2046         }
2047
2048         for (i = 0; i < m->nr; ++i)
2049                 if (m->guest[i].index == msr)
2050                         break;
2051
2052         if (i == NR_AUTOLOAD_MSRS) {
2053                 printk_once(KERN_WARNING "Not enough msr switch entries. "
2054                                 "Can't add msr %x\n", msr);
2055                 return;
2056         } else if (i == m->nr) {
2057                 ++m->nr;
2058                 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
2059                 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
2060         }
2061
2062         m->guest[i].index = msr;
2063         m->guest[i].value = guest_val;
2064         m->host[i].index = msr;
2065         m->host[i].value = host_val;
2066 }
2067
2068 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
2069 {
2070         u64 guest_efer = vmx->vcpu.arch.efer;
2071         u64 ignore_bits = 0;
2072
2073         if (!enable_ept) {
2074                 /*
2075                  * NX is needed to handle CR0.WP=1, CR4.SMEP=1.  Testing
2076                  * host CPUID is more efficient than testing guest CPUID
2077                  * or CR4.  Host SMEP is anyway a requirement for guest SMEP.
2078                  */
2079                 if (boot_cpu_has(X86_FEATURE_SMEP))
2080                         guest_efer |= EFER_NX;
2081                 else if (!(guest_efer & EFER_NX))
2082                         ignore_bits |= EFER_NX;
2083         }
2084
2085         /*
2086          * LMA and LME handled by hardware; SCE meaningless outside long mode.
2087          */
2088         ignore_bits |= EFER_SCE;
2089 #ifdef CONFIG_X86_64
2090         ignore_bits |= EFER_LMA | EFER_LME;
2091         /* SCE is meaningful only in long mode on Intel */
2092         if (guest_efer & EFER_LMA)
2093                 ignore_bits &= ~(u64)EFER_SCE;
2094 #endif
2095
2096         clear_atomic_switch_msr(vmx, MSR_EFER);
2097
2098         /*
2099          * On EPT, we can't emulate NX, so we must switch EFER atomically.
2100          * On CPUs that support "load IA32_EFER", always switch EFER
2101          * atomically, since it's faster than switching it manually.
2102          */
2103         if (cpu_has_load_ia32_efer ||
2104             (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
2105                 if (!(guest_efer & EFER_LMA))
2106                         guest_efer &= ~EFER_LME;
2107                 if (guest_efer != host_efer)
2108                         add_atomic_switch_msr(vmx, MSR_EFER,
2109                                               guest_efer, host_efer);
2110                 return false;
2111         } else {
2112                 guest_efer &= ~ignore_bits;
2113                 guest_efer |= host_efer & ignore_bits;
2114
2115                 vmx->guest_msrs[efer_offset].data = guest_efer;
2116                 vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
2117
2118                 return true;
2119         }
2120 }
2121
2122 #ifdef CONFIG_X86_32
2123 /*
2124  * On 32-bit kernels, VM exits still load the FS and GS bases from the
2125  * VMCS rather than the segment table.  KVM uses this helper to figure
2126  * out the current bases to poke them into the VMCS before entry.
2127  */
2128 static unsigned long segment_base(u16 selector)
2129 {
2130         struct desc_struct *table;
2131         unsigned long v;
2132
2133         if (!(selector & ~SEGMENT_RPL_MASK))
2134                 return 0;
2135
2136         table = get_current_gdt_ro();
2137
2138         if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
2139                 u16 ldt_selector = kvm_read_ldt();
2140
2141                 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
2142                         return 0;
2143
2144                 table = (struct desc_struct *)segment_base(ldt_selector);
2145         }
2146         v = get_desc_base(&table[selector >> 3]);
2147         return v;
2148 }
2149 #endif
2150
2151 static void vmx_save_host_state(struct kvm_vcpu *vcpu)
2152 {
2153         struct vcpu_vmx *vmx = to_vmx(vcpu);
2154         int i;
2155
2156         if (vmx->host_state.loaded)
2157                 return;
2158
2159         vmx->host_state.loaded = 1;
2160         /*
2161          * Set host fs and gs selectors.  Unfortunately, 22.2.3 does not
2162          * allow segment selectors with cpl > 0 or ti == 1.
2163          */
2164         vmx->host_state.ldt_sel = kvm_read_ldt();
2165         vmx->host_state.gs_ldt_reload_needed = vmx->host_state.ldt_sel;
2166         savesegment(fs, vmx->host_state.fs_sel);
2167         if (!(vmx->host_state.fs_sel & 7)) {
2168                 vmcs_write16(HOST_FS_SELECTOR, vmx->host_state.fs_sel);
2169                 vmx->host_state.fs_reload_needed = 0;
2170         } else {
2171                 vmcs_write16(HOST_FS_SELECTOR, 0);
2172                 vmx->host_state.fs_reload_needed = 1;
2173         }
2174         savesegment(gs, vmx->host_state.gs_sel);
2175         if (!(vmx->host_state.gs_sel & 7))
2176                 vmcs_write16(HOST_GS_SELECTOR, vmx->host_state.gs_sel);
2177         else {
2178                 vmcs_write16(HOST_GS_SELECTOR, 0);
2179                 vmx->host_state.gs_ldt_reload_needed = 1;
2180         }
2181
2182 #ifdef CONFIG_X86_64
2183         savesegment(ds, vmx->host_state.ds_sel);
2184         savesegment(es, vmx->host_state.es_sel);
2185 #endif
2186
2187 #ifdef CONFIG_X86_64
2188         vmcs_writel(HOST_FS_BASE, read_msr(MSR_FS_BASE));
2189         vmcs_writel(HOST_GS_BASE, read_msr(MSR_GS_BASE));
2190 #else
2191         vmcs_writel(HOST_FS_BASE, segment_base(vmx->host_state.fs_sel));
2192         vmcs_writel(HOST_GS_BASE, segment_base(vmx->host_state.gs_sel));
2193 #endif
2194
2195 #ifdef CONFIG_X86_64
2196         rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
2197         if (is_long_mode(&vmx->vcpu))
2198                 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2199 #endif
2200         if (boot_cpu_has(X86_FEATURE_MPX))
2201                 rdmsrl(MSR_IA32_BNDCFGS, vmx->host_state.msr_host_bndcfgs);
2202         for (i = 0; i < vmx->save_nmsrs; ++i)
2203                 kvm_set_shared_msr(vmx->guest_msrs[i].index,
2204                                    vmx->guest_msrs[i].data,
2205                                    vmx->guest_msrs[i].mask);
2206 }
2207
2208 static void __vmx_load_host_state(struct vcpu_vmx *vmx)
2209 {
2210         if (!vmx->host_state.loaded)
2211                 return;
2212
2213         ++vmx->vcpu.stat.host_state_reload;
2214         vmx->host_state.loaded = 0;
2215 #ifdef CONFIG_X86_64
2216         if (is_long_mode(&vmx->vcpu))
2217                 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2218 #endif
2219         if (vmx->host_state.gs_ldt_reload_needed) {
2220                 kvm_load_ldt(vmx->host_state.ldt_sel);
2221 #ifdef CONFIG_X86_64
2222                 load_gs_index(vmx->host_state.gs_sel);
2223 #else
2224                 loadsegment(gs, vmx->host_state.gs_sel);
2225 #endif
2226         }
2227         if (vmx->host_state.fs_reload_needed)
2228                 loadsegment(fs, vmx->host_state.fs_sel);
2229 #ifdef CONFIG_X86_64
2230         if (unlikely(vmx->host_state.ds_sel | vmx->host_state.es_sel)) {
2231                 loadsegment(ds, vmx->host_state.ds_sel);
2232                 loadsegment(es, vmx->host_state.es_sel);
2233         }
2234 #endif
2235         invalidate_tss_limit();
2236 #ifdef CONFIG_X86_64
2237         wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
2238 #endif
2239         if (vmx->host_state.msr_host_bndcfgs)
2240                 wrmsrl(MSR_IA32_BNDCFGS, vmx->host_state.msr_host_bndcfgs);
2241         load_fixmap_gdt(raw_smp_processor_id());
2242 }
2243
2244 static void vmx_load_host_state(struct vcpu_vmx *vmx)
2245 {
2246         preempt_disable();
2247         __vmx_load_host_state(vmx);
2248         preempt_enable();
2249 }
2250
2251 static void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
2252 {
2253         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
2254         struct pi_desc old, new;
2255         unsigned int dest;
2256
2257         /*
2258          * In case of hot-plug or hot-unplug, we may have to undo
2259          * vmx_vcpu_pi_put even if there is no assigned device.  And we
2260          * always keep PI.NDST up to date for simplicity: it makes the
2261          * code easier, and CPU migration is not a fast path.
2262          */
2263         if (!pi_test_sn(pi_desc) && vcpu->cpu == cpu)
2264                 return;
2265
2266         /*
2267          * First handle the simple case where no cmpxchg is necessary; just
2268          * allow posting non-urgent interrupts.
2269          *
2270          * If the 'nv' field is POSTED_INTR_WAKEUP_VECTOR, do not change
2271          * PI.NDST: pi_post_block will do it for us and the wakeup_handler
2272          * expects the VCPU to be on the blocked_vcpu_list that matches
2273          * PI.NDST.
2274          */
2275         if (pi_desc->nv == POSTED_INTR_WAKEUP_VECTOR ||
2276             vcpu->cpu == cpu) {
2277                 pi_clear_sn(pi_desc);
2278                 return;
2279         }
2280
2281         /* The full case.  */
2282         do {
2283                 old.control = new.control = pi_desc->control;
2284
2285                 dest = cpu_physical_id(cpu);
2286
2287                 if (x2apic_enabled())
2288                         new.ndst = dest;
2289                 else
2290                         new.ndst = (dest << 8) & 0xFF00;
2291
2292                 new.sn = 0;
2293         } while (cmpxchg64(&pi_desc->control, old.control,
2294                            new.control) != old.control);
2295 }
2296
2297 static void decache_tsc_multiplier(struct vcpu_vmx *vmx)
2298 {
2299         vmx->current_tsc_ratio = vmx->vcpu.arch.tsc_scaling_ratio;
2300         vmcs_write64(TSC_MULTIPLIER, vmx->current_tsc_ratio);
2301 }
2302
2303 /*
2304  * Switches to specified vcpu, until a matching vcpu_put(), but assumes
2305  * vcpu mutex is already taken.
2306  */
2307 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2308 {
2309         struct vcpu_vmx *vmx = to_vmx(vcpu);
2310         bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
2311
2312         if (!already_loaded) {
2313                 loaded_vmcs_clear(vmx->loaded_vmcs);
2314                 local_irq_disable();
2315                 crash_disable_local_vmclear(cpu);
2316
2317                 /*
2318                  * Read loaded_vmcs->cpu should be before fetching
2319                  * loaded_vmcs->loaded_vmcss_on_cpu_link.
2320                  * See the comments in __loaded_vmcs_clear().
2321                  */
2322                 smp_rmb();
2323
2324                 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
2325                          &per_cpu(loaded_vmcss_on_cpu, cpu));
2326                 crash_enable_local_vmclear(cpu);
2327                 local_irq_enable();
2328         }
2329
2330         if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
2331                 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
2332                 vmcs_load(vmx->loaded_vmcs->vmcs);
2333                 indirect_branch_prediction_barrier();
2334         }
2335
2336         if (!already_loaded) {
2337                 void *gdt = get_current_gdt_ro();
2338                 unsigned long sysenter_esp;
2339
2340                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2341
2342                 /*
2343                  * Linux uses per-cpu TSS and GDT, so set these when switching
2344                  * processors.  See 22.2.4.
2345                  */
2346                 vmcs_writel(HOST_TR_BASE,
2347                             (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
2348                 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt);   /* 22.2.4 */
2349
2350                 /*
2351                  * VM exits change the host TR limit to 0x67 after a VM
2352                  * exit.  This is okay, since 0x67 covers everything except
2353                  * the IO bitmap and have have code to handle the IO bitmap
2354                  * being lost after a VM exit.
2355                  */
2356                 BUILD_BUG_ON(IO_BITMAP_OFFSET - 1 != 0x67);
2357
2358                 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
2359                 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
2360
2361                 vmx->loaded_vmcs->cpu = cpu;
2362         }
2363
2364         /* Setup TSC multiplier */
2365         if (kvm_has_tsc_control &&
2366             vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
2367                 decache_tsc_multiplier(vmx);
2368
2369         vmx_vcpu_pi_load(vcpu, cpu);
2370         vmx->host_pkru = read_pkru();
2371 }
2372
2373 static void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
2374 {
2375         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
2376
2377         if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
2378                 !irq_remapping_cap(IRQ_POSTING_CAP)  ||
2379                 !kvm_vcpu_apicv_active(vcpu))
2380                 return;
2381
2382         /* Set SN when the vCPU is preempted */
2383         if (vcpu->preempted)
2384                 pi_set_sn(pi_desc);
2385 }
2386
2387 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
2388 {
2389         vmx_vcpu_pi_put(vcpu);
2390
2391         __vmx_load_host_state(to_vmx(vcpu));
2392 }
2393
2394 static bool emulation_required(struct kvm_vcpu *vcpu)
2395 {
2396         return emulate_invalid_guest_state && !guest_state_valid(vcpu);
2397 }
2398
2399 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
2400
2401 /*
2402  * Return the cr0 value that a nested guest would read. This is a combination
2403  * of the real cr0 used to run the guest (guest_cr0), and the bits shadowed by
2404  * its hypervisor (cr0_read_shadow).
2405  */
2406 static inline unsigned long nested_read_cr0(struct vmcs12 *fields)
2407 {
2408         return (fields->guest_cr0 & ~fields->cr0_guest_host_mask) |
2409                 (fields->cr0_read_shadow & fields->cr0_guest_host_mask);
2410 }
2411 static inline unsigned long nested_read_cr4(struct vmcs12 *fields)
2412 {
2413         return (fields->guest_cr4 & ~fields->cr4_guest_host_mask) |
2414                 (fields->cr4_read_shadow & fields->cr4_guest_host_mask);
2415 }
2416
2417 static unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
2418 {
2419         unsigned long rflags, save_rflags;
2420
2421         if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
2422                 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
2423                 rflags = vmcs_readl(GUEST_RFLAGS);
2424                 if (to_vmx(vcpu)->rmode.vm86_active) {
2425                         rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2426                         save_rflags = to_vmx(vcpu)->rmode.save_rflags;
2427                         rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2428                 }
2429                 to_vmx(vcpu)->rflags = rflags;
2430         }
2431         return to_vmx(vcpu)->rflags;
2432 }
2433
2434 static void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
2435 {
2436         unsigned long old_rflags = vmx_get_rflags(vcpu);
2437
2438         __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
2439         to_vmx(vcpu)->rflags = rflags;
2440         if (to_vmx(vcpu)->rmode.vm86_active) {
2441                 to_vmx(vcpu)->rmode.save_rflags = rflags;
2442                 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2443         }
2444         vmcs_writel(GUEST_RFLAGS, rflags);
2445
2446         if ((old_rflags ^ to_vmx(vcpu)->rflags) & X86_EFLAGS_VM)
2447                 to_vmx(vcpu)->emulation_required = emulation_required(vcpu);
2448 }
2449
2450 static u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
2451 {
2452         u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
2453         int ret = 0;
2454
2455         if (interruptibility & GUEST_INTR_STATE_STI)
2456                 ret |= KVM_X86_SHADOW_INT_STI;
2457         if (interruptibility & GUEST_INTR_STATE_MOV_SS)
2458                 ret |= KVM_X86_SHADOW_INT_MOV_SS;
2459
2460         return ret;
2461 }
2462
2463 static void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
2464 {
2465         u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
2466         u32 interruptibility = interruptibility_old;
2467
2468         interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
2469
2470         if (mask & KVM_X86_SHADOW_INT_MOV_SS)
2471                 interruptibility |= GUEST_INTR_STATE_MOV_SS;
2472         else if (mask & KVM_X86_SHADOW_INT_STI)
2473                 interruptibility |= GUEST_INTR_STATE_STI;
2474
2475         if ((interruptibility != interruptibility_old))
2476                 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
2477 }
2478
2479 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
2480 {
2481         unsigned long rip;
2482
2483         rip = kvm_rip_read(vcpu);
2484         rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
2485         kvm_rip_write(vcpu, rip);
2486
2487         /* skipping an emulated instruction also counts */
2488         vmx_set_interrupt_shadow(vcpu, 0);
2489 }
2490
2491 static void nested_vmx_inject_exception_vmexit(struct kvm_vcpu *vcpu,
2492                                                unsigned long exit_qual)
2493 {
2494         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
2495         unsigned int nr = vcpu->arch.exception.nr;
2496         u32 intr_info = nr | INTR_INFO_VALID_MASK;
2497
2498         if (vcpu->arch.exception.has_error_code) {
2499                 vmcs12->vm_exit_intr_error_code = vcpu->arch.exception.error_code;
2500                 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
2501         }
2502
2503         if (kvm_exception_is_soft(nr))
2504                 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
2505         else
2506                 intr_info |= INTR_TYPE_HARD_EXCEPTION;
2507
2508         if (!(vmcs12->idt_vectoring_info_field & VECTORING_INFO_VALID_MASK) &&
2509             vmx_get_nmi_mask(vcpu))
2510                 intr_info |= INTR_INFO_UNBLOCK_NMI;
2511
2512         nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI, intr_info, exit_qual);
2513 }
2514
2515 /*
2516  * KVM wants to inject page-faults which it got to the guest. This function
2517  * checks whether in a nested guest, we need to inject them to L1 or L2.
2518  */
2519 static int nested_vmx_check_exception(struct kvm_vcpu *vcpu, unsigned long *exit_qual)
2520 {
2521         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
2522         unsigned int nr = vcpu->arch.exception.nr;
2523
2524         if (nr == PF_VECTOR) {
2525                 if (vcpu->arch.exception.nested_apf) {
2526                         *exit_qual = vcpu->arch.apf.nested_apf_token;
2527                         return 1;
2528                 }
2529                 /*
2530                  * FIXME: we must not write CR2 when L1 intercepts an L2 #PF exception.
2531                  * The fix is to add the ancillary datum (CR2 or DR6) to structs
2532                  * kvm_queued_exception and kvm_vcpu_events, so that CR2 and DR6
2533                  * can be written only when inject_pending_event runs.  This should be
2534                  * conditional on a new capability---if the capability is disabled,
2535                  * kvm_multiple_exception would write the ancillary information to
2536                  * CR2 or DR6, for backwards ABI-compatibility.
2537                  */
2538                 if (nested_vmx_is_page_fault_vmexit(vmcs12,
2539                                                     vcpu->arch.exception.error_code)) {
2540                         *exit_qual = vcpu->arch.cr2;
2541                         return 1;
2542                 }
2543         } else {
2544                 if (vmcs12->exception_bitmap & (1u << nr)) {
2545                         if (nr == DB_VECTOR)
2546                                 *exit_qual = vcpu->arch.dr6;
2547                         else
2548                                 *exit_qual = 0;
2549                         return 1;
2550                 }
2551         }
2552
2553         return 0;
2554 }
2555
2556 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
2557 {
2558         struct vcpu_vmx *vmx = to_vmx(vcpu);
2559         unsigned nr = vcpu->arch.exception.nr;
2560         bool has_error_code = vcpu->arch.exception.has_error_code;
2561         u32 error_code = vcpu->arch.exception.error_code;
2562         u32 intr_info = nr | INTR_INFO_VALID_MASK;
2563
2564         if (has_error_code) {
2565                 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
2566                 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
2567         }
2568
2569         if (vmx->rmode.vm86_active) {
2570                 int inc_eip = 0;
2571                 if (kvm_exception_is_soft(nr))
2572                         inc_eip = vcpu->arch.event_exit_inst_len;
2573                 if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
2574                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2575                 return;
2576         }
2577
2578         if (kvm_exception_is_soft(nr)) {
2579                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
2580                              vmx->vcpu.arch.event_exit_inst_len);
2581                 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
2582         } else
2583                 intr_info |= INTR_TYPE_HARD_EXCEPTION;
2584
2585         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
2586 }
2587
2588 static bool vmx_rdtscp_supported(void)
2589 {
2590         return cpu_has_vmx_rdtscp();
2591 }
2592
2593 static bool vmx_invpcid_supported(void)
2594 {
2595         return cpu_has_vmx_invpcid() && enable_ept;
2596 }
2597
2598 /*
2599  * Swap MSR entry in host/guest MSR entry array.
2600  */
2601 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
2602 {
2603         struct shared_msr_entry tmp;
2604
2605         tmp = vmx->guest_msrs[to];
2606         vmx->guest_msrs[to] = vmx->guest_msrs[from];
2607         vmx->guest_msrs[from] = tmp;
2608 }
2609
2610 /*
2611  * Set up the vmcs to automatically save and restore system
2612  * msrs.  Don't touch the 64-bit msrs if the guest is in legacy
2613  * mode, as fiddling with msrs is very expensive.
2614  */
2615 static void setup_msrs(struct vcpu_vmx *vmx)
2616 {
2617         int save_nmsrs, index;
2618
2619         save_nmsrs = 0;
2620 #ifdef CONFIG_X86_64
2621         if (is_long_mode(&vmx->vcpu)) {
2622                 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
2623                 if (index >= 0)
2624                         move_msr_up(vmx, index, save_nmsrs++);
2625                 index = __find_msr_index(vmx, MSR_LSTAR);
2626                 if (index >= 0)
2627                         move_msr_up(vmx, index, save_nmsrs++);
2628                 index = __find_msr_index(vmx, MSR_CSTAR);
2629                 if (index >= 0)
2630                         move_msr_up(vmx, index, save_nmsrs++);
2631                 index = __find_msr_index(vmx, MSR_TSC_AUX);
2632                 if (index >= 0 && guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP))
2633                         move_msr_up(vmx, index, save_nmsrs++);
2634                 /*
2635                  * MSR_STAR is only needed on long mode guests, and only
2636                  * if efer.sce is enabled.
2637                  */
2638                 index = __find_msr_index(vmx, MSR_STAR);
2639                 if ((index >= 0) && (vmx->vcpu.arch.efer & EFER_SCE))
2640                         move_msr_up(vmx, index, save_nmsrs++);
2641         }
2642 #endif
2643         index = __find_msr_index(vmx, MSR_EFER);
2644         if (index >= 0 && update_transition_efer(vmx, index))
2645                 move_msr_up(vmx, index, save_nmsrs++);
2646
2647         vmx->save_nmsrs = save_nmsrs;
2648
2649         if (cpu_has_vmx_msr_bitmap())
2650                 vmx_update_msr_bitmap(&vmx->vcpu);
2651 }
2652
2653 /*
2654  * reads and returns guest's timestamp counter "register"
2655  * guest_tsc = (host_tsc * tsc multiplier) >> 48 + tsc_offset
2656  * -- Intel TSC Scaling for Virtualization White Paper, sec 1.3
2657  */
2658 static u64 guest_read_tsc(struct kvm_vcpu *vcpu)
2659 {
2660         u64 host_tsc, tsc_offset;
2661
2662         host_tsc = rdtsc();
2663         tsc_offset = vmcs_read64(TSC_OFFSET);
2664         return kvm_scale_tsc(vcpu, host_tsc) + tsc_offset;
2665 }
2666
2667 /*
2668  * writes 'offset' into guest's timestamp counter offset register
2669  */
2670 static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
2671 {
2672         if (is_guest_mode(vcpu)) {
2673                 /*
2674                  * We're here if L1 chose not to trap WRMSR to TSC. According
2675                  * to the spec, this should set L1's TSC; The offset that L1
2676                  * set for L2 remains unchanged, and still needs to be added
2677                  * to the newly set TSC to get L2's TSC.
2678                  */
2679                 struct vmcs12 *vmcs12;
2680                 /* recalculate vmcs02.TSC_OFFSET: */
2681                 vmcs12 = get_vmcs12(vcpu);
2682                 vmcs_write64(TSC_OFFSET, offset +
2683                         (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETING) ?
2684                          vmcs12->tsc_offset : 0));
2685         } else {
2686                 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
2687                                            vmcs_read64(TSC_OFFSET), offset);
2688                 vmcs_write64(TSC_OFFSET, offset);
2689         }
2690 }
2691
2692 /*
2693  * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
2694  * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
2695  * all guests if the "nested" module option is off, and can also be disabled
2696  * for a single guest by disabling its VMX cpuid bit.
2697  */
2698 static inline bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
2699 {
2700         return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
2701 }
2702
2703 /*
2704  * nested_vmx_setup_ctls_msrs() sets up variables containing the values to be
2705  * returned for the various VMX controls MSRs when nested VMX is enabled.
2706  * The same values should also be used to verify that vmcs12 control fields are
2707  * valid during nested entry from L1 to L2.
2708  * Each of these control msrs has a low and high 32-bit half: A low bit is on
2709  * if the corresponding bit in the (32-bit) control field *must* be on, and a
2710  * bit in the high half is on if the corresponding bit in the control field
2711  * may be on. See also vmx_control_verify().
2712  */
2713 static void nested_vmx_setup_ctls_msrs(struct vcpu_vmx *vmx)
2714 {
2715         /*
2716          * Note that as a general rule, the high half of the MSRs (bits in
2717          * the control fields which may be 1) should be initialized by the
2718          * intersection of the underlying hardware's MSR (i.e., features which
2719          * can be supported) and the list of features we want to expose -
2720          * because they are known to be properly supported in our code.
2721          * Also, usually, the low half of the MSRs (bits which must be 1) can
2722          * be set to 0, meaning that L1 may turn off any of these bits. The
2723          * reason is that if one of these bits is necessary, it will appear
2724          * in vmcs01 and prepare_vmcs02, when it bitwise-or's the control
2725          * fields of vmcs01 and vmcs02, will turn these bits off - and
2726          * nested_vmx_exit_reflected() will not pass related exits to L1.
2727          * These rules have exceptions below.
2728          */
2729
2730         /* pin-based controls */
2731         rdmsr(MSR_IA32_VMX_PINBASED_CTLS,
2732                 vmx->nested.nested_vmx_pinbased_ctls_low,
2733                 vmx->nested.nested_vmx_pinbased_ctls_high);
2734         vmx->nested.nested_vmx_pinbased_ctls_low |=
2735                 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
2736         vmx->nested.nested_vmx_pinbased_ctls_high &=
2737                 PIN_BASED_EXT_INTR_MASK |
2738                 PIN_BASED_NMI_EXITING |
2739                 PIN_BASED_VIRTUAL_NMIS;
2740         vmx->nested.nested_vmx_pinbased_ctls_high |=
2741                 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
2742                 PIN_BASED_VMX_PREEMPTION_TIMER;
2743         if (kvm_vcpu_apicv_active(&vmx->vcpu))
2744                 vmx->nested.nested_vmx_pinbased_ctls_high |=
2745                         PIN_BASED_POSTED_INTR;
2746
2747         /* exit controls */
2748         rdmsr(MSR_IA32_VMX_EXIT_CTLS,
2749                 vmx->nested.nested_vmx_exit_ctls_low,
2750                 vmx->nested.nested_vmx_exit_ctls_high);
2751         vmx->nested.nested_vmx_exit_ctls_low =
2752                 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
2753
2754         vmx->nested.nested_vmx_exit_ctls_high &=
2755 #ifdef CONFIG_X86_64
2756                 VM_EXIT_HOST_ADDR_SPACE_SIZE |
2757 #endif
2758                 VM_EXIT_LOAD_IA32_PAT | VM_EXIT_SAVE_IA32_PAT;
2759         vmx->nested.nested_vmx_exit_ctls_high |=
2760                 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR |
2761                 VM_EXIT_LOAD_IA32_EFER | VM_EXIT_SAVE_IA32_EFER |
2762                 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER | VM_EXIT_ACK_INTR_ON_EXIT;
2763
2764         if (kvm_mpx_supported())
2765                 vmx->nested.nested_vmx_exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
2766
2767         /* We support free control of debug control saving. */
2768         vmx->nested.nested_vmx_exit_ctls_low &= ~VM_EXIT_SAVE_DEBUG_CONTROLS;
2769
2770         /* entry controls */
2771         rdmsr(MSR_IA32_VMX_ENTRY_CTLS,
2772                 vmx->nested.nested_vmx_entry_ctls_low,
2773                 vmx->nested.nested_vmx_entry_ctls_high);
2774         vmx->nested.nested_vmx_entry_ctls_low =
2775                 VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
2776         vmx->nested.nested_vmx_entry_ctls_high &=
2777 #ifdef CONFIG_X86_64
2778                 VM_ENTRY_IA32E_MODE |
2779 #endif
2780                 VM_ENTRY_LOAD_IA32_PAT;
2781         vmx->nested.nested_vmx_entry_ctls_high |=
2782                 (VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR | VM_ENTRY_LOAD_IA32_EFER);
2783         if (kvm_mpx_supported())
2784                 vmx->nested.nested_vmx_entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
2785
2786         /* We support free control of debug control loading. */
2787         vmx->nested.nested_vmx_entry_ctls_low &= ~VM_ENTRY_LOAD_DEBUG_CONTROLS;
2788
2789         /* cpu-based controls */
2790         rdmsr(MSR_IA32_VMX_PROCBASED_CTLS,
2791                 vmx->nested.nested_vmx_procbased_ctls_low,
2792                 vmx->nested.nested_vmx_procbased_ctls_high);
2793         vmx->nested.nested_vmx_procbased_ctls_low =
2794                 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
2795         vmx->nested.nested_vmx_procbased_ctls_high &=
2796                 CPU_BASED_VIRTUAL_INTR_PENDING |
2797                 CPU_BASED_VIRTUAL_NMI_PENDING | CPU_BASED_USE_TSC_OFFSETING |
2798                 CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING |
2799                 CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING |
2800                 CPU_BASED_CR3_STORE_EXITING |
2801 #ifdef CONFIG_X86_64
2802                 CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING |
2803 #endif
2804                 CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING |
2805                 CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_TRAP_FLAG |
2806                 CPU_BASED_MONITOR_EXITING | CPU_BASED_RDPMC_EXITING |
2807                 CPU_BASED_RDTSC_EXITING | CPU_BASED_PAUSE_EXITING |
2808                 CPU_BASED_TPR_SHADOW | CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2809         /*
2810          * We can allow some features even when not supported by the
2811          * hardware. For example, L1 can specify an MSR bitmap - and we
2812          * can use it to avoid exits to L1 - even when L0 runs L2
2813          * without MSR bitmaps.
2814          */
2815         vmx->nested.nested_vmx_procbased_ctls_high |=
2816                 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
2817                 CPU_BASED_USE_MSR_BITMAPS;
2818
2819         /* We support free control of CR3 access interception. */
2820         vmx->nested.nested_vmx_procbased_ctls_low &=
2821                 ~(CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_CR3_STORE_EXITING);
2822
2823         /*
2824          * secondary cpu-based controls.  Do not include those that
2825          * depend on CPUID bits, they are added later by vmx_cpuid_update.
2826          */
2827         rdmsr(MSR_IA32_VMX_PROCBASED_CTLS2,
2828                 vmx->nested.nested_vmx_secondary_ctls_low,
2829                 vmx->nested.nested_vmx_secondary_ctls_high);
2830         vmx->nested.nested_vmx_secondary_ctls_low = 0;
2831         vmx->nested.nested_vmx_secondary_ctls_high &=
2832                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2833                 SECONDARY_EXEC_DESC |
2834                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2835                 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2836                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2837                 SECONDARY_EXEC_WBINVD_EXITING;
2838
2839         if (enable_ept) {
2840                 /* nested EPT: emulate EPT also to L1 */
2841                 vmx->nested.nested_vmx_secondary_ctls_high |=
2842                         SECONDARY_EXEC_ENABLE_EPT;
2843                 vmx->nested.nested_vmx_ept_caps = VMX_EPT_PAGE_WALK_4_BIT |
2844                          VMX_EPTP_WB_BIT | VMX_EPT_INVEPT_BIT;
2845                 if (cpu_has_vmx_ept_execute_only())
2846                         vmx->nested.nested_vmx_ept_caps |=
2847                                 VMX_EPT_EXECUTE_ONLY_BIT;
2848                 vmx->nested.nested_vmx_ept_caps &= vmx_capability.ept;
2849                 vmx->nested.nested_vmx_ept_caps |= VMX_EPT_EXTENT_GLOBAL_BIT |
2850                         VMX_EPT_EXTENT_CONTEXT_BIT | VMX_EPT_2MB_PAGE_BIT |
2851                         VMX_EPT_1GB_PAGE_BIT;
2852                 if (enable_ept_ad_bits) {
2853                         vmx->nested.nested_vmx_secondary_ctls_high |=
2854                                 SECONDARY_EXEC_ENABLE_PML;
2855                         vmx->nested.nested_vmx_ept_caps |= VMX_EPT_AD_BIT;
2856                 }
2857         } else
2858                 vmx->nested.nested_vmx_ept_caps = 0;
2859
2860         if (cpu_has_vmx_vmfunc()) {
2861                 vmx->nested.nested_vmx_secondary_ctls_high |=
2862                         SECONDARY_EXEC_ENABLE_VMFUNC;
2863                 /*
2864                  * Advertise EPTP switching unconditionally
2865                  * since we emulate it
2866                  */
2867                 if (enable_ept)
2868                         vmx->nested.nested_vmx_vmfunc_controls =
2869                                 VMX_VMFUNC_EPTP_SWITCHING;
2870         }
2871
2872         /*
2873          * Old versions of KVM use the single-context version without
2874          * checking for support, so declare that it is supported even
2875          * though it is treated as global context.  The alternative is
2876          * not failing the single-context invvpid, and it is worse.
2877          */
2878         if (enable_vpid) {
2879                 vmx->nested.nested_vmx_secondary_ctls_high |=
2880                         SECONDARY_EXEC_ENABLE_VPID;
2881                 vmx->nested.nested_vmx_vpid_caps = VMX_VPID_INVVPID_BIT |
2882                         VMX_VPID_EXTENT_SUPPORTED_MASK;
2883         } else
2884                 vmx->nested.nested_vmx_vpid_caps = 0;
2885
2886         if (enable_unrestricted_guest)
2887                 vmx->nested.nested_vmx_secondary_ctls_high |=
2888                         SECONDARY_EXEC_UNRESTRICTED_GUEST;
2889
2890         /* miscellaneous data */
2891         rdmsr(MSR_IA32_VMX_MISC,
2892                 vmx->nested.nested_vmx_misc_low,
2893                 vmx->nested.nested_vmx_misc_high);
2894         vmx->nested.nested_vmx_misc_low &= VMX_MISC_SAVE_EFER_LMA;
2895         vmx->nested.nested_vmx_misc_low |=
2896                 VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE |
2897                 VMX_MISC_ACTIVITY_HLT;
2898         vmx->nested.nested_vmx_misc_high = 0;
2899
2900         /*
2901          * This MSR reports some information about VMX support. We
2902          * should return information about the VMX we emulate for the
2903          * guest, and the VMCS structure we give it - not about the
2904          * VMX support of the underlying hardware.
2905          */
2906         vmx->nested.nested_vmx_basic =
2907                 VMCS12_REVISION |
2908                 VMX_BASIC_TRUE_CTLS |
2909                 ((u64)VMCS12_SIZE << VMX_BASIC_VMCS_SIZE_SHIFT) |
2910                 (VMX_BASIC_MEM_TYPE_WB << VMX_BASIC_MEM_TYPE_SHIFT);
2911
2912         if (cpu_has_vmx_basic_inout())
2913                 vmx->nested.nested_vmx_basic |= VMX_BASIC_INOUT;
2914
2915         /*
2916          * These MSRs specify bits which the guest must keep fixed on
2917          * while L1 is in VMXON mode (in L1's root mode, or running an L2).
2918          * We picked the standard core2 setting.
2919          */
2920 #define VMXON_CR0_ALWAYSON     (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE)
2921 #define VMXON_CR4_ALWAYSON     X86_CR4_VMXE
2922         vmx->nested.nested_vmx_cr0_fixed0 = VMXON_CR0_ALWAYSON;
2923         vmx->nested.nested_vmx_cr4_fixed0 = VMXON_CR4_ALWAYSON;
2924
2925         /* These MSRs specify bits which the guest must keep fixed off. */
2926         rdmsrl(MSR_IA32_VMX_CR0_FIXED1, vmx->nested.nested_vmx_cr0_fixed1);
2927         rdmsrl(MSR_IA32_VMX_CR4_FIXED1, vmx->nested.nested_vmx_cr4_fixed1);
2928
2929         /* highest index: VMX_PREEMPTION_TIMER_VALUE */
2930         vmx->nested.nested_vmx_vmcs_enum = 0x2e;
2931 }
2932
2933 /*
2934  * if fixed0[i] == 1: val[i] must be 1
2935  * if fixed1[i] == 0: val[i] must be 0
2936  */
2937 static inline bool fixed_bits_valid(u64 val, u64 fixed0, u64 fixed1)
2938 {
2939         return ((val & fixed1) | fixed0) == val;
2940 }
2941
2942 static inline bool vmx_control_verify(u32 control, u32 low, u32 high)
2943 {
2944         return fixed_bits_valid(control, low, high);
2945 }
2946
2947 static inline u64 vmx_control_msr(u32 low, u32 high)
2948 {
2949         return low | ((u64)high << 32);
2950 }
2951
2952 static bool is_bitwise_subset(u64 superset, u64 subset, u64 mask)
2953 {
2954         superset &= mask;
2955         subset &= mask;
2956
2957         return (superset | subset) == superset;
2958 }
2959
2960 static int vmx_restore_vmx_basic(struct vcpu_vmx *vmx, u64 data)
2961 {
2962         const u64 feature_and_reserved =
2963                 /* feature (except bit 48; see below) */
2964                 BIT_ULL(49) | BIT_ULL(54) | BIT_ULL(55) |
2965                 /* reserved */
2966                 BIT_ULL(31) | GENMASK_ULL(47, 45) | GENMASK_ULL(63, 56);
2967         u64 vmx_basic = vmx->nested.nested_vmx_basic;
2968
2969         if (!is_bitwise_subset(vmx_basic, data, feature_and_reserved))
2970                 return -EINVAL;
2971
2972         /*
2973          * KVM does not emulate a version of VMX that constrains physical
2974          * addresses of VMX structures (e.g. VMCS) to 32-bits.
2975          */
2976         if (data & BIT_ULL(48))
2977                 return -EINVAL;
2978
2979         if (vmx_basic_vmcs_revision_id(vmx_basic) !=
2980             vmx_basic_vmcs_revision_id(data))
2981                 return -EINVAL;
2982
2983         if (vmx_basic_vmcs_size(vmx_basic) > vmx_basic_vmcs_size(data))
2984                 return -EINVAL;
2985
2986         vmx->nested.nested_vmx_basic = data;
2987         return 0;
2988 }
2989
2990 static int
2991 vmx_restore_control_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
2992 {
2993         u64 supported;
2994         u32 *lowp, *highp;
2995
2996         switch (msr_index) {
2997         case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
2998                 lowp = &vmx->nested.nested_vmx_pinbased_ctls_low;
2999                 highp = &vmx->nested.nested_vmx_pinbased_ctls_high;
3000                 break;
3001         case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3002                 lowp = &vmx->nested.nested_vmx_procbased_ctls_low;
3003                 highp = &vmx->nested.nested_vmx_procbased_ctls_high;
3004                 break;
3005         case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3006                 lowp = &vmx->nested.nested_vmx_exit_ctls_low;
3007                 highp = &vmx->nested.nested_vmx_exit_ctls_high;
3008                 break;
3009         case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3010                 lowp = &vmx->nested.nested_vmx_entry_ctls_low;
3011                 highp = &vmx->nested.nested_vmx_entry_ctls_high;
3012                 break;
3013         case MSR_IA32_VMX_PROCBASED_CTLS2:
3014                 lowp = &vmx->nested.nested_vmx_secondary_ctls_low;
3015                 highp = &vmx->nested.nested_vmx_secondary_ctls_high;
3016                 break;
3017         default:
3018                 BUG();
3019         }
3020
3021         supported = vmx_control_msr(*lowp, *highp);
3022
3023         /* Check must-be-1 bits are still 1. */
3024         if (!is_bitwise_subset(data, supported, GENMASK_ULL(31, 0)))
3025                 return -EINVAL;
3026
3027         /* Check must-be-0 bits are still 0. */
3028         if (!is_bitwise_subset(supported, data, GENMASK_ULL(63, 32)))
3029                 return -EINVAL;
3030
3031         *lowp = data;
3032         *highp = data >> 32;
3033         return 0;
3034 }
3035
3036 static int vmx_restore_vmx_misc(struct vcpu_vmx *vmx, u64 data)
3037 {
3038         const u64 feature_and_reserved_bits =
3039                 /* feature */
3040                 BIT_ULL(5) | GENMASK_ULL(8, 6) | BIT_ULL(14) | BIT_ULL(15) |
3041                 BIT_ULL(28) | BIT_ULL(29) | BIT_ULL(30) |
3042                 /* reserved */
3043                 GENMASK_ULL(13, 9) | BIT_ULL(31);
3044         u64 vmx_misc;
3045
3046         vmx_misc = vmx_control_msr(vmx->nested.nested_vmx_misc_low,
3047                                    vmx->nested.nested_vmx_misc_high);
3048
3049         if (!is_bitwise_subset(vmx_misc, data, feature_and_reserved_bits))
3050                 return -EINVAL;
3051
3052         if ((vmx->nested.nested_vmx_pinbased_ctls_high &
3053              PIN_BASED_VMX_PREEMPTION_TIMER) &&
3054             vmx_misc_preemption_timer_rate(data) !=
3055             vmx_misc_preemption_timer_rate(vmx_misc))
3056                 return -EINVAL;
3057
3058         if (vmx_misc_cr3_count(data) > vmx_misc_cr3_count(vmx_misc))
3059                 return -EINVAL;
3060
3061         if (vmx_misc_max_msr(data) > vmx_misc_max_msr(vmx_misc))
3062                 return -EINVAL;
3063
3064         if (vmx_misc_mseg_revid(data) != vmx_misc_mseg_revid(vmx_misc))
3065                 return -EINVAL;
3066
3067         vmx->nested.nested_vmx_misc_low = data;
3068         vmx->nested.nested_vmx_misc_high = data >> 32;
3069         return 0;
3070 }
3071
3072 static int vmx_restore_vmx_ept_vpid_cap(struct vcpu_vmx *vmx, u64 data)
3073 {
3074         u64 vmx_ept_vpid_cap;
3075
3076         vmx_ept_vpid_cap = vmx_control_msr(vmx->nested.nested_vmx_ept_caps,
3077                                            vmx->nested.nested_vmx_vpid_caps);
3078
3079         /* Every bit is either reserved or a feature bit. */
3080         if (!is_bitwise_subset(vmx_ept_vpid_cap, data, -1ULL))
3081                 return -EINVAL;
3082
3083         vmx->nested.nested_vmx_ept_caps = data;
3084         vmx->nested.nested_vmx_vpid_caps = data >> 32;
3085         return 0;
3086 }
3087
3088 static int vmx_restore_fixed0_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
3089 {
3090         u64 *msr;
3091
3092         switch (msr_index) {
3093         case MSR_IA32_VMX_CR0_FIXED0:
3094                 msr = &vmx->nested.nested_vmx_cr0_fixed0;
3095                 break;
3096         case MSR_IA32_VMX_CR4_FIXED0:
3097                 msr = &vmx->nested.nested_vmx_cr4_fixed0;
3098                 break;
3099         default:
3100                 BUG();
3101         }
3102
3103         /*
3104          * 1 bits (which indicates bits which "must-be-1" during VMX operation)
3105          * must be 1 in the restored value.
3106          */
3107         if (!is_bitwise_subset(data, *msr, -1ULL))
3108                 return -EINVAL;
3109
3110         *msr = data;
3111         return 0;
3112 }
3113
3114 /*
3115  * Called when userspace is restoring VMX MSRs.
3116  *
3117  * Returns 0 on success, non-0 otherwise.
3118  */
3119 static int vmx_set_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
3120 {
3121         struct vcpu_vmx *vmx = to_vmx(vcpu);
3122
3123         switch (msr_index) {
3124         case MSR_IA32_VMX_BASIC:
3125                 return vmx_restore_vmx_basic(vmx, data);
3126         case MSR_IA32_VMX_PINBASED_CTLS:
3127         case MSR_IA32_VMX_PROCBASED_CTLS:
3128         case MSR_IA32_VMX_EXIT_CTLS:
3129         case MSR_IA32_VMX_ENTRY_CTLS:
3130                 /*
3131                  * The "non-true" VMX capability MSRs are generated from the
3132                  * "true" MSRs, so we do not support restoring them directly.
3133                  *
3134                  * If userspace wants to emulate VMX_BASIC[55]=0, userspace
3135                  * should restore the "true" MSRs with the must-be-1 bits
3136                  * set according to the SDM Vol 3. A.2 "RESERVED CONTROLS AND
3137                  * DEFAULT SETTINGS".
3138                  */
3139                 return -EINVAL;
3140         case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3141         case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3142         case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3143         case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3144         case MSR_IA32_VMX_PROCBASED_CTLS2:
3145                 return vmx_restore_control_msr(vmx, msr_index, data);
3146         case MSR_IA32_VMX_MISC:
3147                 return vmx_restore_vmx_misc(vmx, data);
3148         case MSR_IA32_VMX_CR0_FIXED0:
3149         case MSR_IA32_VMX_CR4_FIXED0:
3150                 return vmx_restore_fixed0_msr(vmx, msr_index, data);
3151         case MSR_IA32_VMX_CR0_FIXED1:
3152         case MSR_IA32_VMX_CR4_FIXED1:
3153                 /*
3154                  * These MSRs are generated based on the vCPU's CPUID, so we
3155                  * do not support restoring them directly.
3156                  */
3157                 return -EINVAL;
3158         case MSR_IA32_VMX_EPT_VPID_CAP:
3159                 return vmx_restore_vmx_ept_vpid_cap(vmx, data);
3160         case MSR_IA32_VMX_VMCS_ENUM:
3161                 vmx->nested.nested_vmx_vmcs_enum = data;
3162                 return 0;
3163         default:
3164                 /*
3165                  * The rest of the VMX capability MSRs do not support restore.
3166                  */
3167                 return -EINVAL;
3168         }
3169 }
3170
3171 /* Returns 0 on success, non-0 otherwise. */
3172 static int vmx_get_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
3173 {
3174         struct vcpu_vmx *vmx = to_vmx(vcpu);
3175
3176         switch (msr_index) {
3177         case MSR_IA32_VMX_BASIC:
3178                 *pdata = vmx->nested.nested_vmx_basic;
3179                 break;
3180         case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3181         case MSR_IA32_VMX_PINBASED_CTLS:
3182                 *pdata = vmx_control_msr(
3183                         vmx->nested.nested_vmx_pinbased_ctls_low,
3184                         vmx->nested.nested_vmx_pinbased_ctls_high);
3185                 if (msr_index == MSR_IA32_VMX_PINBASED_CTLS)
3186                         *pdata |= PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3187                 break;
3188         case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3189         case MSR_IA32_VMX_PROCBASED_CTLS:
3190                 *pdata = vmx_control_msr(
3191                         vmx->nested.nested_vmx_procbased_ctls_low,
3192                         vmx->nested.nested_vmx_procbased_ctls_high);
3193                 if (msr_index == MSR_IA32_VMX_PROCBASED_CTLS)
3194                         *pdata |= CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3195                 break;
3196         case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3197         case MSR_IA32_VMX_EXIT_CTLS:
3198                 *pdata = vmx_control_msr(
3199                         vmx->nested.nested_vmx_exit_ctls_low,
3200                         vmx->nested.nested_vmx_exit_ctls_high);
3201                 if (msr_index == MSR_IA32_VMX_EXIT_CTLS)
3202                         *pdata |= VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
3203                 break;
3204         case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3205         case MSR_IA32_VMX_ENTRY_CTLS:
3206                 *pdata = vmx_control_msr(
3207                         vmx->nested.nested_vmx_entry_ctls_low,
3208                         vmx->nested.nested_vmx_entry_ctls_high);
3209                 if (msr_index == MSR_IA32_VMX_ENTRY_CTLS)
3210                         *pdata |= VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
3211                 break;
3212         case MSR_IA32_VMX_MISC:
3213                 *pdata = vmx_control_msr(
3214                         vmx->nested.nested_vmx_misc_low,
3215                         vmx->nested.nested_vmx_misc_high);
3216                 break;
3217         case MSR_IA32_VMX_CR0_FIXED0:
3218                 *pdata = vmx->nested.nested_vmx_cr0_fixed0;
3219                 break;
3220         case MSR_IA32_VMX_CR0_FIXED1:
3221                 *pdata = vmx->nested.nested_vmx_cr0_fixed1;
3222                 break;
3223         case MSR_IA32_VMX_CR4_FIXED0:
3224                 *pdata = vmx->nested.nested_vmx_cr4_fixed0;
3225                 break;
3226         case MSR_IA32_VMX_CR4_FIXED1:
3227                 *pdata = vmx->nested.nested_vmx_cr4_fixed1;
3228                 break;
3229         case MSR_IA32_VMX_VMCS_ENUM:
3230                 *pdata = vmx->nested.nested_vmx_vmcs_enum;
3231                 break;
3232         case MSR_IA32_VMX_PROCBASED_CTLS2:
3233                 *pdata = vmx_control_msr(
3234                         vmx->nested.nested_vmx_secondary_ctls_low,
3235                         vmx->nested.nested_vmx_secondary_ctls_high);
3236                 break;
3237         case MSR_IA32_VMX_EPT_VPID_CAP:
3238                 *pdata = vmx->nested.nested_vmx_ept_caps |
3239                         ((u64)vmx->nested.nested_vmx_vpid_caps << 32);
3240                 break;
3241         case MSR_IA32_VMX_VMFUNC:
3242                 *pdata = vmx->nested.nested_vmx_vmfunc_controls;
3243                 break;
3244         default:
3245                 return 1;
3246         }
3247
3248         return 0;
3249 }
3250
3251 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
3252                                                  uint64_t val)
3253 {
3254         uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
3255
3256         return !(val & ~valid_bits);
3257 }
3258
3259 /*
3260  * Reads an msr value (of 'msr_index') into 'pdata'.
3261  * Returns 0 on success, non-0 otherwise.
3262  * Assumes vcpu_load() was already called.
3263  */
3264 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3265 {
3266         struct shared_msr_entry *msr;
3267
3268         switch (msr_info->index) {
3269 #ifdef CONFIG_X86_64
3270         case MSR_FS_BASE:
3271                 msr_info->data = vmcs_readl(GUEST_FS_BASE);
3272                 break;
3273         case MSR_GS_BASE:
3274                 msr_info->data = vmcs_readl(GUEST_GS_BASE);
3275                 break;
3276         case MSR_KERNEL_GS_BASE:
3277                 vmx_load_host_state(to_vmx(vcpu));
3278                 msr_info->data = to_vmx(vcpu)->msr_guest_kernel_gs_base;
3279                 break;
3280 #endif
3281         case MSR_EFER:
3282                 return kvm_get_msr_common(vcpu, msr_info);
3283         case MSR_IA32_TSC:
3284                 msr_info->data = guest_read_tsc(vcpu);
3285                 break;
3286         case MSR_IA32_SPEC_CTRL:
3287                 if (!msr_info->host_initiated &&
3288                     !guest_cpuid_has(vcpu, X86_FEATURE_IBRS) &&
3289                     !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
3290                         return 1;
3291
3292                 msr_info->data = to_vmx(vcpu)->spec_ctrl;
3293                 break;
3294         case MSR_IA32_ARCH_CAPABILITIES:
3295                 if (!msr_info->host_initiated &&
3296                     !guest_cpuid_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
3297                         return 1;
3298                 msr_info->data = to_vmx(vcpu)->arch_capabilities;
3299                 break;
3300         case MSR_IA32_SYSENTER_CS:
3301                 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
3302                 break;
3303         case MSR_IA32_SYSENTER_EIP:
3304                 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
3305                 break;
3306         case MSR_IA32_SYSENTER_ESP:
3307                 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
3308                 break;
3309         case MSR_IA32_BNDCFGS:
3310                 if (!kvm_mpx_supported() ||
3311                     (!msr_info->host_initiated &&
3312                      !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
3313                         return 1;
3314                 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
3315                 break;
3316         case MSR_IA32_MCG_EXT_CTL:
3317                 if (!msr_info->host_initiated &&
3318                     !(to_vmx(vcpu)->msr_ia32_feature_control &
3319                       FEATURE_CONTROL_LMCE))
3320                         return 1;
3321                 msr_info->data = vcpu->arch.mcg_ext_ctl;
3322                 break;
3323         case MSR_IA32_FEATURE_CONTROL:
3324                 msr_info->data = to_vmx(vcpu)->msr_ia32_feature_control;
3325                 break;
3326         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
3327                 if (!nested_vmx_allowed(vcpu))
3328                         return 1;
3329                 return vmx_get_vmx_msr(vcpu, msr_info->index, &msr_info->data);
3330         case MSR_IA32_XSS:
3331                 if (!vmx_xsaves_supported())
3332                         return 1;
3333                 msr_info->data = vcpu->arch.ia32_xss;
3334                 break;
3335         case MSR_TSC_AUX:
3336                 if (!msr_info->host_initiated &&
3337                     !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
3338                         return 1;
3339                 /* Otherwise falls through */
3340         default:
3341                 msr = find_msr_entry(to_vmx(vcpu), msr_info->index);
3342                 if (msr) {
3343                         msr_info->data = msr->data;
3344                         break;
3345                 }
3346                 return kvm_get_msr_common(vcpu, msr_info);
3347         }
3348
3349         return 0;
3350 }
3351
3352 static void vmx_leave_nested(struct kvm_vcpu *vcpu);
3353
3354 /*
3355  * Writes msr value into into the appropriate "register".
3356  * Returns 0 on success, non-0 otherwise.
3357  * Assumes vcpu_load() was already called.
3358  */
3359 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3360 {
3361         struct vcpu_vmx *vmx = to_vmx(vcpu);
3362         struct shared_msr_entry *msr;
3363         int ret = 0;
3364         u32 msr_index = msr_info->index;
3365         u64 data = msr_info->data;
3366
3367         switch (msr_index) {
3368         case MSR_EFER:
3369                 ret = kvm_set_msr_common(vcpu, msr_info);
3370                 break;
3371 #ifdef CONFIG_X86_64
3372         case MSR_FS_BASE:
3373                 vmx_segment_cache_clear(vmx);
3374                 vmcs_writel(GUEST_FS_BASE, data);
3375                 break;
3376         case MSR_GS_BASE:
3377                 vmx_segment_cache_clear(vmx);
3378                 vmcs_writel(GUEST_GS_BASE, data);
3379                 break;
3380         case MSR_KERNEL_GS_BASE:
3381                 vmx_load_host_state(vmx);
3382                 vmx->msr_guest_kernel_gs_base = data;
3383                 break;
3384 #endif
3385         case MSR_IA32_SYSENTER_CS:
3386                 vmcs_write32(GUEST_SYSENTER_CS, data);
3387                 break;
3388         case MSR_IA32_SYSENTER_EIP:
3389                 vmcs_writel(GUEST_SYSENTER_EIP, data);
3390                 break;
3391         case MSR_IA32_SYSENTER_ESP:
3392                 vmcs_writel(GUEST_SYSENTER_ESP, data);
3393                 break;
3394         case MSR_IA32_BNDCFGS:
3395                 if (!kvm_mpx_supported() ||
3396                     (!msr_info->host_initiated &&
3397                      !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
3398                         return 1;
3399                 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
3400                     (data & MSR_IA32_BNDCFGS_RSVD))
3401                         return 1;
3402                 vmcs_write64(GUEST_BNDCFGS, data);
3403                 break;
3404         case MSR_IA32_TSC:
3405                 kvm_write_tsc(vcpu, msr_info);
3406                 break;
3407         case MSR_IA32_SPEC_CTRL:
3408                 if (!msr_info->host_initiated &&
3409                     !guest_cpuid_has(vcpu, X86_FEATURE_IBRS) &&
3410                     !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
3411                         return 1;
3412
3413                 /* The STIBP bit doesn't fault even if it's not advertised */
3414                 if (data & ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP))
3415                         return 1;
3416
3417                 vmx->spec_ctrl = data;
3418
3419                 if (!data)
3420                         break;
3421
3422                 /*
3423                  * For non-nested:
3424                  * When it's written (to non-zero) for the first time, pass
3425                  * it through.
3426                  *
3427                  * For nested:
3428                  * The handling of the MSR bitmap for L2 guests is done in
3429                  * nested_vmx_merge_msr_bitmap. We should not touch the
3430                  * vmcs02.msr_bitmap here since it gets completely overwritten
3431                  * in the merging. We update the vmcs01 here for L1 as well
3432                  * since it will end up touching the MSR anyway now.
3433                  */
3434                 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap,
3435                                               MSR_IA32_SPEC_CTRL,
3436                                               MSR_TYPE_RW);
3437                 break;
3438         case MSR_IA32_PRED_CMD:
3439                 if (!msr_info->host_initiated &&
3440                     !guest_cpuid_has(vcpu, X86_FEATURE_IBPB) &&
3441                     !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
3442                         return 1;
3443
3444                 if (data & ~PRED_CMD_IBPB)
3445                         return 1;
3446
3447                 if (!data)
3448                         break;
3449
3450                 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
3451
3452                 /*
3453                  * For non-nested:
3454                  * When it's written (to non-zero) for the first time, pass
3455                  * it through.
3456                  *
3457                  * For nested:
3458                  * The handling of the MSR bitmap for L2 guests is done in
3459                  * nested_vmx_merge_msr_bitmap. We should not touch the
3460                  * vmcs02.msr_bitmap here since it gets completely overwritten
3461                  * in the merging.
3462                  */
3463                 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap, MSR_IA32_PRED_CMD,
3464                                               MSR_TYPE_W);
3465                 break;
3466         case MSR_IA32_ARCH_CAPABILITIES:
3467                 if (!msr_info->host_initiated)
3468                         return 1;
3469                 vmx->arch_capabilities = data;
3470                 break;
3471         case MSR_IA32_CR_PAT:
3472                 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
3473                         if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
3474                                 return 1;
3475                         vmcs_write64(GUEST_IA32_PAT, data);
3476                         vcpu->arch.pat = data;
3477                         break;
3478                 }
3479                 ret = kvm_set_msr_common(vcpu, msr_info);
3480                 break;
3481         case MSR_IA32_TSC_ADJUST:
3482                 ret = kvm_set_msr_common(vcpu, msr_info);
3483                 break;
3484         case MSR_IA32_MCG_EXT_CTL:
3485                 if ((!msr_info->host_initiated &&
3486                      !(to_vmx(vcpu)->msr_ia32_feature_control &
3487                        FEATURE_CONTROL_LMCE)) ||
3488                     (data & ~MCG_EXT_CTL_LMCE_EN))
3489                         return 1;
3490                 vcpu->arch.mcg_ext_ctl = data;
3491                 break;
3492         case MSR_IA32_FEATURE_CONTROL:
3493                 if (!vmx_feature_control_msr_valid(vcpu, data) ||
3494                     (to_vmx(vcpu)->msr_ia32_feature_control &
3495                      FEATURE_CONTROL_LOCKED && !msr_info->host_initiated))
3496                         return 1;
3497                 vmx->msr_ia32_feature_control = data;
3498                 if (msr_info->host_initiated && data == 0)
3499                         vmx_leave_nested(vcpu);
3500                 break;
3501         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
3502                 if (!msr_info->host_initiated)
3503                         return 1; /* they are read-only */
3504                 if (!nested_vmx_allowed(vcpu))
3505                         return 1;
3506                 return vmx_set_vmx_msr(vcpu, msr_index, data);
3507         case MSR_IA32_XSS:
3508                 if (!vmx_xsaves_supported())
3509                         return 1;
3510                 /*
3511                  * The only supported bit as of Skylake is bit 8, but
3512                  * it is not supported on KVM.
3513                  */
3514                 if (data != 0)
3515                         return 1;
3516                 vcpu->arch.ia32_xss = data;
3517                 if (vcpu->arch.ia32_xss != host_xss)
3518                         add_atomic_switch_msr(vmx, MSR_IA32_XSS,
3519                                 vcpu->arch.ia32_xss, host_xss);
3520                 else
3521                         clear_atomic_switch_msr(vmx, MSR_IA32_XSS);
3522                 break;
3523         case MSR_TSC_AUX:
3524                 if (!msr_info->host_initiated &&
3525                     !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
3526                         return 1;
3527                 /* Check reserved bit, higher 32 bits should be zero */
3528                 if ((data >> 32) != 0)
3529                         return 1;
3530                 /* Otherwise falls through */
3531         default:
3532                 msr = find_msr_entry(vmx, msr_index);
3533                 if (msr) {
3534                         u64 old_msr_data = msr->data;
3535                         msr->data = data;
3536                         if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
3537                                 preempt_disable();
3538                                 ret = kvm_set_shared_msr(msr->index, msr->data,
3539                                                          msr->mask);
3540                                 preempt_enable();
3541                                 if (ret)
3542                                         msr->data = old_msr_data;
3543                         }
3544                         break;
3545                 }
3546                 ret = kvm_set_msr_common(vcpu, msr_info);
3547         }
3548
3549         return ret;
3550 }
3551
3552 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
3553 {
3554         __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
3555         switch (reg) {
3556         case VCPU_REGS_RSP:
3557                 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
3558                 break;
3559         case VCPU_REGS_RIP:
3560                 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
3561                 break;
3562         case VCPU_EXREG_PDPTR:
3563                 if (enable_ept)
3564                         ept_save_pdptrs(vcpu);
3565                 break;
3566         default:
3567                 break;
3568         }
3569 }
3570
3571 static __init int cpu_has_kvm_support(void)
3572 {
3573         return cpu_has_vmx();
3574 }
3575
3576 static __init int vmx_disabled_by_bios(void)
3577 {
3578         u64 msr;
3579
3580         rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
3581         if (msr & FEATURE_CONTROL_LOCKED) {
3582                 /* launched w/ TXT and VMX disabled */
3583                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
3584                         && tboot_enabled())
3585                         return 1;
3586                 /* launched w/o TXT and VMX only enabled w/ TXT */
3587                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
3588                         && (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
3589                         && !tboot_enabled()) {
3590                         printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
3591                                 "activate TXT before enabling KVM\n");
3592                         return 1;
3593                 }
3594                 /* launched w/o TXT and VMX disabled */
3595                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
3596                         && !tboot_enabled())
3597                         return 1;
3598         }
3599
3600         return 0;
3601 }
3602
3603 static void kvm_cpu_vmxon(u64 addr)
3604 {
3605         cr4_set_bits(X86_CR4_VMXE);
3606         intel_pt_handle_vmx(1);
3607
3608         asm volatile (ASM_VMX_VMXON_RAX
3609                         : : "a"(&addr), "m"(addr)
3610                         : "memory", "cc");
3611 }
3612
3613 static int hardware_enable(void)
3614 {
3615         int cpu = raw_smp_processor_id();
3616         u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
3617         u64 old, test_bits;
3618
3619         if (cr4_read_shadow() & X86_CR4_VMXE)
3620                 return -EBUSY;
3621
3622         INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
3623         INIT_LIST_HEAD(&per_cpu(blocked_vcpu_on_cpu, cpu));
3624         spin_lock_init(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
3625
3626         /*
3627          * Now we can enable the vmclear operation in kdump
3628          * since the loaded_vmcss_on_cpu list on this cpu
3629          * has been initialized.
3630          *
3631          * Though the cpu is not in VMX operation now, there
3632          * is no problem to enable the vmclear operation
3633          * for the loaded_vmcss_on_cpu list is empty!
3634          */
3635         crash_enable_local_vmclear(cpu);
3636
3637         rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
3638
3639         test_bits = FEATURE_CONTROL_LOCKED;
3640         test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
3641         if (tboot_enabled())
3642                 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
3643
3644         if ((old & test_bits) != test_bits) {
3645                 /* enable and lock */
3646                 wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
3647         }
3648         kvm_cpu_vmxon(phys_addr);
3649         ept_sync_global();
3650
3651         return 0;
3652 }
3653
3654 static void vmclear_local_loaded_vmcss(void)
3655 {
3656         int cpu = raw_smp_processor_id();
3657         struct loaded_vmcs *v, *n;
3658
3659         list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
3660                                  loaded_vmcss_on_cpu_link)
3661                 __loaded_vmcs_clear(v);
3662 }
3663
3664
3665 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
3666  * tricks.
3667  */
3668 static void kvm_cpu_vmxoff(void)
3669 {
3670         asm volatile (__ex(ASM_VMX_VMXOFF) : : : "cc");
3671
3672         intel_pt_handle_vmx(0);
3673         cr4_clear_bits(X86_CR4_VMXE);
3674 }
3675
3676 static void hardware_disable(void)
3677 {
3678         vmclear_local_loaded_vmcss();
3679         kvm_cpu_vmxoff();
3680 }
3681
3682 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
3683                                       u32 msr, u32 *result)
3684 {
3685         u32 vmx_msr_low, vmx_msr_high;
3686         u32 ctl = ctl_min | ctl_opt;
3687
3688         rdmsr(msr, vmx_msr_low, vmx_msr_high);
3689
3690         ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
3691         ctl |= vmx_msr_low;  /* bit == 1 in low word  ==> must be one  */
3692
3693         /* Ensure minimum (required) set of control bits are supported. */
3694         if (ctl_min & ~ctl)
3695                 return -EIO;
3696
3697         *result = ctl;
3698         return 0;
3699 }
3700
3701 static __init bool allow_1_setting(u32 msr, u32 ctl)
3702 {
3703         u32 vmx_msr_low, vmx_msr_high;
3704
3705         rdmsr(msr, vmx_msr_low, vmx_msr_high);
3706         return vmx_msr_high & ctl;
3707 }
3708
3709 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
3710 {
3711         u32 vmx_msr_low, vmx_msr_high;
3712         u32 min, opt, min2, opt2;
3713         u32 _pin_based_exec_control = 0;
3714         u32 _cpu_based_exec_control = 0;
3715         u32 _cpu_based_2nd_exec_control = 0;
3716         u32 _vmexit_control = 0;
3717         u32 _vmentry_control = 0;
3718
3719         min = CPU_BASED_HLT_EXITING |
3720 #ifdef CONFIG_X86_64
3721               CPU_BASED_CR8_LOAD_EXITING |
3722               CPU_BASED_CR8_STORE_EXITING |
3723 #endif
3724               CPU_BASED_CR3_LOAD_EXITING |
3725               CPU_BASED_CR3_STORE_EXITING |
3726               CPU_BASED_USE_IO_BITMAPS |
3727               CPU_BASED_MOV_DR_EXITING |
3728               CPU_BASED_USE_TSC_OFFSETING |
3729               CPU_BASED_INVLPG_EXITING |
3730               CPU_BASED_RDPMC_EXITING;
3731
3732         if (!kvm_mwait_in_guest())
3733                 min |= CPU_BASED_MWAIT_EXITING |
3734                         CPU_BASED_MONITOR_EXITING;
3735
3736         opt = CPU_BASED_TPR_SHADOW |
3737               CPU_BASED_USE_MSR_BITMAPS |
3738               CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
3739         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
3740                                 &_cpu_based_exec_control) < 0)
3741                 return -EIO;
3742 #ifdef CONFIG_X86_64
3743         if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
3744                 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
3745                                            ~CPU_BASED_CR8_STORE_EXITING;
3746 #endif
3747         if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
3748                 min2 = 0;
3749                 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
3750                         SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
3751                         SECONDARY_EXEC_WBINVD_EXITING |
3752                         SECONDARY_EXEC_ENABLE_VPID |
3753                         SECONDARY_EXEC_ENABLE_EPT |
3754                         SECONDARY_EXEC_UNRESTRICTED_GUEST |
3755                         SECONDARY_EXEC_PAUSE_LOOP_EXITING |
3756                         SECONDARY_EXEC_RDTSCP |
3757                         SECONDARY_EXEC_ENABLE_INVPCID |
3758                         SECONDARY_EXEC_APIC_REGISTER_VIRT |
3759                         SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
3760                         SECONDARY_EXEC_SHADOW_VMCS |
3761                         SECONDARY_EXEC_XSAVES |
3762                         SECONDARY_EXEC_RDSEED |
3763                         SECONDARY_EXEC_RDRAND |
3764                         SECONDARY_EXEC_ENABLE_PML |
3765                         SECONDARY_EXEC_TSC_SCALING |
3766                         SECONDARY_EXEC_ENABLE_VMFUNC;
3767                 if (adjust_vmx_controls(min2, opt2,
3768                                         MSR_IA32_VMX_PROCBASED_CTLS2,
3769                                         &_cpu_based_2nd_exec_control) < 0)
3770                         return -EIO;
3771         }
3772 #ifndef CONFIG_X86_64
3773         if (!(_cpu_based_2nd_exec_control &
3774                                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
3775                 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
3776 #endif
3777
3778         if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
3779                 _cpu_based_2nd_exec_control &= ~(
3780                                 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3781                                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
3782                                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
3783
3784         if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
3785                 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
3786                    enabled */
3787                 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
3788                                              CPU_BASED_CR3_STORE_EXITING |
3789                                              CPU_BASED_INVLPG_EXITING);
3790                 rdmsr(MSR_IA32_VMX_EPT_VPID_CAP,
3791                       vmx_capability.ept, vmx_capability.vpid);
3792         }
3793
3794         min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
3795 #ifdef CONFIG_X86_64
3796         min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
3797 #endif
3798         opt = VM_EXIT_SAVE_IA32_PAT | VM_EXIT_LOAD_IA32_PAT |
3799                 VM_EXIT_CLEAR_BNDCFGS;
3800         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
3801                                 &_vmexit_control) < 0)
3802                 return -EIO;
3803
3804         min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
3805         opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
3806                  PIN_BASED_VMX_PREEMPTION_TIMER;
3807         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
3808                                 &_pin_based_exec_control) < 0)
3809                 return -EIO;
3810
3811         if (cpu_has_broken_vmx_preemption_timer())
3812                 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
3813         if (!(_cpu_based_2nd_exec_control &
3814                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
3815                 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
3816
3817         min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
3818         opt = VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_BNDCFGS;
3819         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
3820                                 &_vmentry_control) < 0)
3821                 return -EIO;
3822
3823         rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
3824
3825         /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
3826         if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
3827                 return -EIO;
3828
3829 #ifdef CONFIG_X86_64
3830         /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
3831         if (vmx_msr_high & (1u<<16))
3832                 return -EIO;
3833 #endif
3834
3835         /* Require Write-Back (WB) memory type for VMCS accesses. */
3836         if (((vmx_msr_high >> 18) & 15) != 6)
3837                 return -EIO;
3838
3839         vmcs_conf->size = vmx_msr_high & 0x1fff;
3840         vmcs_conf->order = get_order(vmcs_conf->size);
3841         vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
3842         vmcs_conf->revision_id = vmx_msr_low;
3843
3844         vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
3845         vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
3846         vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
3847         vmcs_conf->vmexit_ctrl         = _vmexit_control;
3848         vmcs_conf->vmentry_ctrl        = _vmentry_control;
3849
3850         cpu_has_load_ia32_efer =
3851                 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
3852                                 VM_ENTRY_LOAD_IA32_EFER)
3853                 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
3854                                    VM_EXIT_LOAD_IA32_EFER);
3855
3856         cpu_has_load_perf_global_ctrl =
3857                 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
3858                                 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
3859                 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
3860                                    VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
3861
3862         /*
3863          * Some cpus support VM_ENTRY_(LOAD|SAVE)_IA32_PERF_GLOBAL_CTRL
3864          * but due to errata below it can't be used. Workaround is to use
3865          * msr load mechanism to switch IA32_PERF_GLOBAL_CTRL.
3866          *
3867          * VM Exit May Incorrectly Clear IA32_PERF_GLOBAL_CTRL [34:32]
3868          *
3869          * AAK155             (model 26)
3870          * AAP115             (model 30)
3871          * AAT100             (model 37)
3872          * BC86,AAY89,BD102   (model 44)
3873          * BA97               (model 46)
3874          *
3875          */
3876         if (cpu_has_load_perf_global_ctrl && boot_cpu_data.x86 == 0x6) {
3877                 switch (boot_cpu_data.x86_model) {
3878                 case 26:
3879                 case 30:
3880                 case 37:
3881                 case 44:
3882                 case 46:
3883                         cpu_has_load_perf_global_ctrl = false;
3884                         printk_once(KERN_WARNING"kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
3885                                         "does not work properly. Using workaround\n");
3886                         break;
3887                 default:
3888                         break;
3889                 }
3890         }
3891
3892         if (boot_cpu_has(X86_FEATURE_XSAVES))
3893                 rdmsrl(MSR_IA32_XSS, host_xss);
3894
3895         return 0;
3896 }
3897
3898 static struct vmcs *alloc_vmcs_cpu(int cpu)
3899 {
3900         int node = cpu_to_node(cpu);
3901         struct page *pages;
3902         struct vmcs *vmcs;
3903
3904         pages = __alloc_pages_node(node, GFP_KERNEL, vmcs_config.order);
3905         if (!pages)
3906                 return NULL;
3907         vmcs = page_address(pages);
3908         memset(vmcs, 0, vmcs_config.size);
3909         vmcs->revision_id = vmcs_config.revision_id; /* vmcs revision id */
3910         return vmcs;
3911 }
3912
3913 static void free_vmcs(struct vmcs *vmcs)
3914 {
3915         free_pages((unsigned long)vmcs, vmcs_config.order);
3916 }
3917
3918 /*
3919  * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
3920  */
3921 static void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
3922 {
3923         if (!loaded_vmcs->vmcs)
3924                 return;
3925         loaded_vmcs_clear(loaded_vmcs);
3926         free_vmcs(loaded_vmcs->vmcs);
3927         loaded_vmcs->vmcs = NULL;
3928         if (loaded_vmcs->msr_bitmap)
3929                 free_page((unsigned long)loaded_vmcs->msr_bitmap);
3930         WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
3931 }
3932
3933 static struct vmcs *alloc_vmcs(void)
3934 {
3935         return alloc_vmcs_cpu(raw_smp_processor_id());
3936 }
3937
3938 static int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
3939 {
3940         loaded_vmcs->vmcs = alloc_vmcs();
3941         if (!loaded_vmcs->vmcs)
3942                 return -ENOMEM;
3943
3944         loaded_vmcs->shadow_vmcs = NULL;
3945         loaded_vmcs_init(loaded_vmcs);
3946
3947         if (cpu_has_vmx_msr_bitmap()) {
3948                 loaded_vmcs->msr_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);
3949                 if (!loaded_vmcs->msr_bitmap)
3950                         goto out_vmcs;
3951                 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
3952         }
3953         return 0;
3954
3955 out_vmcs:
3956         free_loaded_vmcs(loaded_vmcs);
3957         return -ENOMEM;
3958 }
3959
3960 static void free_kvm_area(void)
3961 {
3962         int cpu;
3963
3964         for_each_possible_cpu(cpu) {
3965                 free_vmcs(per_cpu(vmxarea, cpu));
3966                 per_cpu(vmxarea, cpu) = NULL;
3967         }
3968 }
3969
3970 enum vmcs_field_type {
3971         VMCS_FIELD_TYPE_U16 = 0,
3972         VMCS_FIELD_TYPE_U64 = 1,
3973         VMCS_FIELD_TYPE_U32 = 2,
3974         VMCS_FIELD_TYPE_NATURAL_WIDTH = 3
3975 };
3976
3977 static inline int vmcs_field_type(unsigned long field)
3978 {
3979         if (0x1 & field)        /* the *_HIGH fields are all 32 bit */
3980                 return VMCS_FIELD_TYPE_U32;
3981         return (field >> 13) & 0x3 ;
3982 }
3983
3984 static inline int vmcs_field_readonly(unsigned long field)
3985 {
3986         return (((field >> 10) & 0x3) == 1);
3987 }
3988
3989 static void init_vmcs_shadow_fields(void)
3990 {
3991         int i, j;
3992
3993         /* No checks for read only fields yet */
3994
3995         for (i = j = 0; i < max_shadow_read_write_fields; i++) {
3996                 switch (shadow_read_write_fields[i]) {
3997                 case GUEST_BNDCFGS:
3998                         if (!kvm_mpx_supported())
3999                                 continue;
4000                         break;
4001                 default:
4002                         break;
4003                 }
4004
4005                 if (j < i)
4006                         shadow_read_write_fields[j] =
4007                                 shadow_read_write_fields[i];
4008                 j++;
4009         }
4010         max_shadow_read_write_fields = j;
4011
4012         /* shadowed fields guest access without vmexit */
4013         for (i = 0; i < max_shadow_read_write_fields; i++) {
4014                 unsigned long field = shadow_read_write_fields[i];
4015
4016                 clear_bit(field, vmx_vmwrite_bitmap);
4017                 clear_bit(field, vmx_vmread_bitmap);
4018                 if (vmcs_field_type(field) == VMCS_FIELD_TYPE_U64) {
4019                         clear_bit(field + 1, vmx_vmwrite_bitmap);
4020                         clear_bit(field + 1, vmx_vmread_bitmap);
4021                 }
4022         }
4023         for (i = 0; i < max_shadow_read_only_fields; i++) {
4024                 unsigned long field = shadow_read_only_fields[i];
4025
4026                 clear_bit(field, vmx_vmread_bitmap);
4027                 if (vmcs_field_type(field) == VMCS_FIELD_TYPE_U64)
4028                         clear_bit(field + 1, vmx_vmread_bitmap);
4029         }
4030 }
4031
4032 static __init int alloc_kvm_area(void)
4033 {
4034         int cpu;
4035
4036         for_each_possible_cpu(cpu) {
4037                 struct vmcs *vmcs;
4038
4039                 vmcs = alloc_vmcs_cpu(cpu);
4040                 if (!vmcs) {
4041                         free_kvm_area();
4042                         return -ENOMEM;
4043                 }
4044
4045                 per_cpu(vmxarea, cpu) = vmcs;
4046         }
4047         return 0;
4048 }
4049
4050 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
4051                 struct kvm_segment *save)
4052 {
4053         if (!emulate_invalid_guest_state) {
4054                 /*
4055                  * CS and SS RPL should be equal during guest entry according
4056                  * to VMX spec, but in reality it is not always so. Since vcpu
4057                  * is in the middle of the transition from real mode to
4058                  * protected mode it is safe to assume that RPL 0 is a good
4059                  * default value.
4060                  */
4061                 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
4062                         save->selector &= ~SEGMENT_RPL_MASK;
4063                 save->dpl = save->selector & SEGMENT_RPL_MASK;
4064                 save->s = 1;
4065         }
4066         vmx_set_segment(vcpu, save, seg);
4067 }
4068
4069 static void enter_pmode(struct kvm_vcpu *vcpu)
4070 {
4071         unsigned long flags;
4072         struct vcpu_vmx *vmx = to_vmx(vcpu);
4073
4074         /*
4075          * Update real mode segment cache. It may be not up-to-date if sement
4076          * register was written while vcpu was in a guest mode.
4077          */
4078         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
4079         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
4080         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
4081         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
4082         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
4083         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
4084
4085         vmx->rmode.vm86_active = 0;
4086
4087         vmx_segment_cache_clear(vmx);
4088
4089         vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
4090
4091         flags = vmcs_readl(GUEST_RFLAGS);
4092         flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
4093         flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
4094         vmcs_writel(GUEST_RFLAGS, flags);
4095
4096         vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
4097                         (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
4098
4099         update_exception_bitmap(vcpu);
4100
4101         fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
4102         fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
4103         fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
4104         fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
4105         fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
4106         fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
4107 }
4108
4109 static void fix_rmode_seg(int seg, struct kvm_segment *save)
4110 {
4111         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
4112         struct kvm_segment var = *save;
4113
4114         var.dpl = 0x3;
4115         if (seg == VCPU_SREG_CS)
4116                 var.type = 0x3;
4117
4118         if (!emulate_invalid_guest_state) {
4119                 var.selector = var.base >> 4;
4120                 var.base = var.base & 0xffff0;
4121                 var.limit = 0xffff;
4122                 var.g = 0;
4123                 var.db = 0;
4124                 var.present = 1;
4125                 var.s = 1;
4126                 var.l = 0;
4127                 var.unusable = 0;
4128                 var.type = 0x3;
4129                 var.avl = 0;
4130                 if (save->base & 0xf)
4131                         printk_once(KERN_WARNING "kvm: segment base is not "
4132                                         "paragraph aligned when entering "
4133                                         "protected mode (seg=%d)", seg);
4134         }
4135
4136         vmcs_write16(sf->selector, var.selector);
4137         vmcs_writel(sf->base, var.base);
4138         vmcs_write32(sf->limit, var.limit);
4139         vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
4140 }
4141
4142 static void enter_rmode(struct kvm_vcpu *vcpu)
4143 {
4144         unsigned long flags;
4145         struct vcpu_vmx *vmx = to_vmx(vcpu);
4146
4147         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
4148         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
4149         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
4150         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
4151         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
4152         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
4153         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
4154
4155         vmx->rmode.vm86_active = 1;
4156
4157         /*
4158          * Very old userspace does not call KVM_SET_TSS_ADDR before entering
4159          * vcpu. Warn the user that an update is overdue.
4160          */
4161         if (!vcpu->kvm->arch.tss_addr)
4162                 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
4163                              "called before entering vcpu\n");
4164
4165         vmx_segment_cache_clear(vmx);
4166
4167         vmcs_writel(GUEST_TR_BASE, vcpu->kvm->arch.tss_addr);
4168         vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
4169         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4170
4171         flags = vmcs_readl(GUEST_RFLAGS);
4172         vmx->rmode.save_rflags = flags;
4173
4174         flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
4175
4176         vmcs_writel(GUEST_RFLAGS, flags);
4177         vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
4178         update_exception_bitmap(vcpu);
4179
4180         fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
4181         fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
4182         fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
4183         fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
4184         fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
4185         fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
4186
4187         kvm_mmu_reset_context(vcpu);
4188 }
4189
4190 static void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
4191 {
4192         struct vcpu_vmx *vmx = to_vmx(vcpu);
4193         struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
4194
4195         if (!msr)
4196                 return;
4197
4198         /*
4199          * Force kernel_gs_base reloading before EFER changes, as control
4200          * of this msr depends on is_long_mode().
4201          */
4202         vmx_load_host_state(to_vmx(vcpu));
4203         vcpu->arch.efer = efer;
4204         if (efer & EFER_LMA) {
4205                 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
4206                 msr->data = efer;
4207         } else {
4208                 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
4209
4210                 msr->data = efer & ~EFER_LME;
4211         }
4212         setup_msrs(vmx);
4213 }
4214
4215 #ifdef CONFIG_X86_64
4216
4217 static void enter_lmode(struct kvm_vcpu *vcpu)
4218 {
4219         u32 guest_tr_ar;
4220
4221         vmx_segment_cache_clear(to_vmx(vcpu));
4222
4223         guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
4224         if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
4225                 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
4226                                      __func__);
4227                 vmcs_write32(GUEST_TR_AR_BYTES,
4228                              (guest_tr_ar & ~VMX_AR_TYPE_MASK)
4229                              | VMX_AR_TYPE_BUSY_64_TSS);
4230         }
4231         vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
4232 }
4233
4234 static void exit_lmode(struct kvm_vcpu *vcpu)
4235 {
4236         vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
4237         vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
4238 }
4239
4240 #endif
4241
4242 static inline void __vmx_flush_tlb(struct kvm_vcpu *vcpu, int vpid)
4243 {
4244         if (enable_ept) {
4245                 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
4246                         return;
4247                 ept_sync_context(construct_eptp(vcpu, vcpu->arch.mmu.root_hpa));
4248         } else {
4249                 vpid_sync_context(vpid);
4250         }
4251 }
4252
4253 static void vmx_flush_tlb(struct kvm_vcpu *vcpu)
4254 {
4255         __vmx_flush_tlb(vcpu, to_vmx(vcpu)->vpid);
4256 }
4257
4258 static void vmx_flush_tlb_ept_only(struct kvm_vcpu *vcpu)
4259 {
4260         if (enable_ept)
4261                 vmx_flush_tlb(vcpu);
4262 }
4263
4264 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
4265 {
4266         ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
4267
4268         vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
4269         vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
4270 }
4271
4272 static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
4273 {
4274         if (enable_ept && is_paging(vcpu))
4275                 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
4276         __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
4277 }
4278
4279 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
4280 {
4281         ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
4282
4283         vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
4284         vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
4285 }
4286
4287 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
4288 {
4289         struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
4290
4291         if (!test_bit(VCPU_EXREG_PDPTR,
4292                       (unsigned long *)&vcpu->arch.regs_dirty))
4293                 return;
4294
4295         if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
4296                 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
4297                 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
4298                 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
4299                 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
4300         }
4301 }
4302
4303 static void ept_save_pdptrs(struct kvm_vcpu *vcpu)
4304 {
4305         struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
4306
4307         if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
4308                 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
4309                 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
4310                 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
4311                 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
4312         }
4313
4314         __set_bit(VCPU_EXREG_PDPTR,
4315                   (unsigned long *)&vcpu->arch.regs_avail);
4316         __set_bit(VCPU_EXREG_PDPTR,
4317                   (unsigned long *)&vcpu->arch.regs_dirty);
4318 }
4319
4320 static bool nested_guest_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
4321 {
4322         u64 fixed0 = to_vmx(vcpu)->nested.nested_vmx_cr0_fixed0;
4323         u64 fixed1 = to_vmx(vcpu)->nested.nested_vmx_cr0_fixed1;
4324         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4325
4326         if (to_vmx(vcpu)->nested.nested_vmx_secondary_ctls_high &
4327                 SECONDARY_EXEC_UNRESTRICTED_GUEST &&
4328             nested_cpu_has2(vmcs12, SECONDARY_EXEC_UNRESTRICTED_GUEST))
4329                 fixed0 &= ~(X86_CR0_PE | X86_CR0_PG);
4330
4331         return fixed_bits_valid(val, fixed0, fixed1);
4332 }
4333
4334 static bool nested_host_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
4335 {
4336         u64 fixed0 = to_vmx(vcpu)->nested.nested_vmx_cr0_fixed0;
4337         u64 fixed1 = to_vmx(vcpu)->nested.nested_vmx_cr0_fixed1;
4338
4339         return fixed_bits_valid(val, fixed0, fixed1);
4340 }
4341
4342 static bool nested_cr4_valid(struct kvm_vcpu *vcpu, unsigned long val)
4343 {
4344         u64 fixed0 = to_vmx(vcpu)->nested.nested_vmx_cr4_fixed0;
4345         u64 fixed1 = to_vmx(vcpu)->nested.nested_vmx_cr4_fixed1;
4346
4347         return fixed_bits_valid(val, fixed0, fixed1);
4348 }
4349
4350 /* No difference in the restrictions on guest and host CR4 in VMX operation. */
4351 #define nested_guest_cr4_valid  nested_cr4_valid
4352 #define nested_host_cr4_valid   nested_cr4_valid
4353
4354 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
4355
4356 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
4357                                         unsigned long cr0,
4358                                         struct kvm_vcpu *vcpu)
4359 {
4360         if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
4361                 vmx_decache_cr3(vcpu);
4362         if (!(cr0 & X86_CR0_PG)) {
4363                 /* From paging/starting to nonpaging */
4364                 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
4365                              vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
4366                              (CPU_BASED_CR3_LOAD_EXITING |
4367                               CPU_BASED_CR3_STORE_EXITING));
4368                 vcpu->arch.cr0 = cr0;
4369                 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
4370         } else if (!is_paging(vcpu)) {
4371                 /* From nonpaging to paging */
4372                 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
4373                              vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
4374                              ~(CPU_BASED_CR3_LOAD_EXITING |
4375                                CPU_BASED_CR3_STORE_EXITING));
4376                 vcpu->arch.cr0 = cr0;
4377                 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
4378         }
4379
4380         if (!(cr0 & X86_CR0_WP))
4381                 *hw_cr0 &= ~X86_CR0_WP;
4382 }
4383
4384 static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
4385 {
4386         struct vcpu_vmx *vmx = to_vmx(vcpu);
4387         unsigned long hw_cr0;
4388
4389         hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK);
4390         if (enable_unrestricted_guest)
4391                 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
4392         else {
4393                 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
4394
4395                 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
4396                         enter_pmode(vcpu);
4397
4398                 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
4399                         enter_rmode(vcpu);
4400         }
4401
4402 #ifdef CONFIG_X86_64
4403         if (vcpu->arch.efer & EFER_LME) {
4404                 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
4405                         enter_lmode(vcpu);
4406                 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
4407                         exit_lmode(vcpu);
4408         }
4409 #endif
4410
4411         if (enable_ept)
4412                 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
4413
4414         vmcs_writel(CR0_READ_SHADOW, cr0);
4415         vmcs_writel(GUEST_CR0, hw_cr0);
4416         vcpu->arch.cr0 = cr0;
4417
4418         /* depends on vcpu->arch.cr0 to be set to a new value */
4419         vmx->emulation_required = emulation_required(vcpu);
4420 }
4421
4422 static int get_ept_level(struct kvm_vcpu *vcpu)
4423 {
4424         if (cpu_has_vmx_ept_5levels() && (cpuid_maxphyaddr(vcpu) > 48))
4425                 return 5;
4426         return 4;
4427 }
4428
4429 static u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa)
4430 {
4431         u64 eptp = VMX_EPTP_MT_WB;
4432
4433         eptp |= (get_ept_level(vcpu) == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
4434
4435         if (enable_ept_ad_bits &&
4436             (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
4437                 eptp |= VMX_EPTP_AD_ENABLE_BIT;
4438         eptp |= (root_hpa & PAGE_MASK);
4439
4440         return eptp;
4441 }
4442
4443 static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
4444 {
4445         unsigned long guest_cr3;
4446         u64 eptp;
4447
4448         guest_cr3 = cr3;
4449         if (enable_ept) {
4450                 eptp = construct_eptp(vcpu, cr3);
4451                 vmcs_write64(EPT_POINTER, eptp);
4452                 if (is_paging(vcpu) || is_guest_mode(vcpu))
4453                         guest_cr3 = kvm_read_cr3(vcpu);
4454                 else
4455                         guest_cr3 = vcpu->kvm->arch.ept_identity_map_addr;
4456                 ept_load_pdptrs(vcpu);
4457         }
4458
4459         vmx_flush_tlb(vcpu);
4460         vmcs_writel(GUEST_CR3, guest_cr3);
4461 }
4462
4463 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
4464 {
4465         /*
4466          * Pass through host's Machine Check Enable value to hw_cr4, which
4467          * is in force while we are in guest mode.  Do not let guests control
4468          * this bit, even if host CR4.MCE == 0.
4469          */
4470         unsigned long hw_cr4 =
4471                 (cr4_read_shadow() & X86_CR4_MCE) |
4472                 (cr4 & ~X86_CR4_MCE) |
4473                 (to_vmx(vcpu)->rmode.vm86_active ?
4474                  KVM_RMODE_VM_CR4_ALWAYS_ON : KVM_PMODE_VM_CR4_ALWAYS_ON);
4475
4476         if (cr4 & X86_CR4_VMXE) {
4477                 /*
4478                  * To use VMXON (and later other VMX instructions), a guest
4479                  * must first be able to turn on cr4.VMXE (see handle_vmon()).
4480                  * So basically the check on whether to allow nested VMX
4481                  * is here.
4482                  */
4483                 if (!nested_vmx_allowed(vcpu))
4484                         return 1;
4485         }
4486
4487         if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
4488                 return 1;
4489
4490         vcpu->arch.cr4 = cr4;
4491         if (enable_ept) {
4492                 if (!is_paging(vcpu)) {
4493                         hw_cr4 &= ~X86_CR4_PAE;
4494                         hw_cr4 |= X86_CR4_PSE;
4495                 } else if (!(cr4 & X86_CR4_PAE)) {
4496                         hw_cr4 &= ~X86_CR4_PAE;
4497                 }
4498         }
4499
4500         if (!enable_unrestricted_guest && !is_paging(vcpu))
4501                 /*
4502                  * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
4503                  * hardware.  To emulate this behavior, SMEP/SMAP/PKU needs
4504                  * to be manually disabled when guest switches to non-paging
4505                  * mode.
4506                  *
4507                  * If !enable_unrestricted_guest, the CPU is always running
4508                  * with CR0.PG=1 and CR4 needs to be modified.
4509                  * If enable_unrestricted_guest, the CPU automatically
4510                  * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
4511                  */
4512                 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
4513
4514         vmcs_writel(CR4_READ_SHADOW, cr4);
4515         vmcs_writel(GUEST_CR4, hw_cr4);
4516         return 0;
4517 }
4518
4519 static void vmx_get_segment(struct kvm_vcpu *vcpu,
4520                             struct kvm_segment *var, int seg)
4521 {
4522         struct vcpu_vmx *vmx = to_vmx(vcpu);
4523         u32 ar;
4524
4525         if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
4526                 *var = vmx->rmode.segs[seg];
4527                 if (seg == VCPU_SREG_TR
4528                     || var->selector == vmx_read_guest_seg_selector(vmx, seg))
4529                         return;
4530                 var->base = vmx_read_guest_seg_base(vmx, seg);
4531                 var->selector = vmx_read_guest_seg_selector(vmx, seg);
4532                 return;
4533         }
4534         var->base = vmx_read_guest_seg_base(vmx, seg);
4535         var->limit = vmx_read_guest_seg_limit(vmx, seg);
4536         var->selector = vmx_read_guest_seg_selector(vmx, seg);
4537         ar = vmx_read_guest_seg_ar(vmx, seg);
4538         var->unusable = (ar >> 16) & 1;
4539         var->type = ar & 15;
4540         var->s = (ar >> 4) & 1;
4541         var->dpl = (ar >> 5) & 3;
4542         /*
4543          * Some userspaces do not preserve unusable property. Since usable
4544          * segment has to be present according to VMX spec we can use present
4545          * property to amend userspace bug by making unusable segment always
4546          * nonpresent. vmx_segment_access_rights() already marks nonpresent
4547          * segment as unusable.
4548          */
4549         var->present = !var->unusable;
4550         var->avl = (ar >> 12) & 1;
4551         var->l = (ar >> 13) & 1;
4552         var->db = (ar >> 14) & 1;
4553         var->g = (ar >> 15) & 1;
4554 }
4555
4556 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
4557 {
4558         struct kvm_segment s;
4559
4560         if (to_vmx(vcpu)->rmode.vm86_active) {
4561                 vmx_get_segment(vcpu, &s, seg);
4562                 return s.base;
4563         }
4564         return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
4565 }
4566
4567 static int vmx_get_cpl(struct kvm_vcpu *vcpu)
4568 {
4569         struct vcpu_vmx *vmx = to_vmx(vcpu);
4570
4571         if (unlikely(vmx->rmode.vm86_active))
4572                 return 0;
4573         else {
4574                 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
4575                 return VMX_AR_DPL(ar);
4576         }
4577 }
4578
4579 static u32 vmx_segment_access_rights(struct kvm_segment *var)
4580 {
4581         u32 ar;
4582
4583         if (var->unusable || !var->present)
4584                 ar = 1 << 16;
4585         else {
4586                 ar = var->type & 15;
4587                 ar |= (var->s & 1) << 4;
4588                 ar |= (var->dpl & 3) << 5;
4589                 ar |= (var->present & 1) << 7;
4590                 ar |= (var->avl & 1) << 12;
4591                 ar |= (var->l & 1) << 13;
4592                 ar |= (var->db & 1) << 14;
4593                 ar |= (var->g & 1) << 15;
4594         }
4595
4596         return ar;
4597 }
4598
4599 static void vmx_set_segment(struct kvm_vcpu *vcpu,
4600                             struct kvm_segment *var, int seg)
4601 {
4602         struct vcpu_vmx *vmx = to_vmx(vcpu);
4603         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
4604
4605         vmx_segment_cache_clear(vmx);
4606
4607         if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
4608                 vmx->rmode.segs[seg] = *var;
4609                 if (seg == VCPU_SREG_TR)
4610                         vmcs_write16(sf->selector, var->selector);
4611                 else if (var->s)
4612                         fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
4613                 goto out;
4614         }
4615
4616         vmcs_writel(sf->base, var->base);
4617         vmcs_write32(sf->limit, var->limit);
4618         vmcs_write16(sf->selector, var->selector);
4619
4620         /*
4621          *   Fix the "Accessed" bit in AR field of segment registers for older
4622          * qemu binaries.
4623          *   IA32 arch specifies that at the time of processor reset the
4624          * "Accessed" bit in the AR field of segment registers is 1. And qemu
4625          * is setting it to 0 in the userland code. This causes invalid guest
4626          * state vmexit when "unrestricted guest" mode is turned on.
4627          *    Fix for this setup issue in cpu_reset is being pushed in the qemu
4628          * tree. Newer qemu binaries with that qemu fix would not need this
4629          * kvm hack.
4630          */
4631         if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
4632                 var->type |= 0x1; /* Accessed */
4633
4634         vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
4635
4636 out:
4637         vmx->emulation_required = emulation_required(vcpu);
4638 }
4639
4640 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
4641 {
4642         u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
4643
4644         *db = (ar >> 14) & 1;
4645         *l = (ar >> 13) & 1;
4646 }
4647
4648 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4649 {
4650         dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
4651         dt->address = vmcs_readl(GUEST_IDTR_BASE);
4652 }
4653
4654 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4655 {
4656         vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
4657         vmcs_writel(GUEST_IDTR_BASE, dt->address);
4658 }
4659
4660 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4661 {
4662         dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
4663         dt->address = vmcs_readl(GUEST_GDTR_BASE);
4664 }
4665
4666 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4667 {
4668         vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
4669         vmcs_writel(GUEST_GDTR_BASE, dt->address);
4670 }
4671
4672 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
4673 {
4674         struct kvm_segment var;
4675         u32 ar;
4676
4677         vmx_get_segment(vcpu, &var, seg);
4678         var.dpl = 0x3;
4679         if (seg == VCPU_SREG_CS)
4680                 var.type = 0x3;
4681         ar = vmx_segment_access_rights(&var);
4682
4683         if (var.base != (var.selector << 4))
4684                 return false;
4685         if (var.limit != 0xffff)
4686                 return false;
4687         if (ar != 0xf3)
4688                 return false;
4689
4690         return true;
4691 }
4692
4693 static bool code_segment_valid(struct kvm_vcpu *vcpu)
4694 {
4695         struct kvm_segment cs;
4696         unsigned int cs_rpl;
4697
4698         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
4699         cs_rpl = cs.selector & SEGMENT_RPL_MASK;
4700
4701         if (cs.unusable)
4702                 return false;
4703         if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
4704                 return false;
4705         if (!cs.s)
4706                 return false;
4707         if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
4708                 if (cs.dpl > cs_rpl)
4709                         return false;
4710         } else {
4711                 if (cs.dpl != cs_rpl)
4712                         return false;
4713         }
4714         if (!cs.present)
4715                 return false;
4716
4717         /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
4718         return true;
4719 }
4720
4721 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
4722 {
4723         struct kvm_segment ss;
4724         unsigned int ss_rpl;
4725
4726         vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
4727         ss_rpl = ss.selector & SEGMENT_RPL_MASK;
4728
4729         if (ss.unusable)
4730                 return true;
4731         if (ss.type != 3 && ss.type != 7)
4732                 return false;
4733         if (!ss.s)
4734                 return false;
4735         if (ss.dpl != ss_rpl) /* DPL != RPL */
4736                 return false;
4737         if (!ss.present)
4738                 return false;
4739
4740         return true;
4741 }
4742
4743 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
4744 {
4745         struct kvm_segment var;
4746         unsigned int rpl;
4747
4748         vmx_get_segment(vcpu, &var, seg);
4749         rpl = var.selector & SEGMENT_RPL_MASK;
4750
4751         if (var.unusable)
4752                 return true;
4753         if (!var.s)
4754                 return false;
4755         if (!var.present)
4756                 return false;
4757         if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
4758                 if (var.dpl < rpl) /* DPL < RPL */
4759                         return false;
4760         }
4761
4762         /* TODO: Add other members to kvm_segment_field to allow checking for other access
4763          * rights flags
4764          */
4765         return true;
4766 }
4767
4768 static bool tr_valid(struct kvm_vcpu *vcpu)
4769 {
4770         struct kvm_segment tr;
4771
4772         vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
4773
4774         if (tr.unusable)
4775                 return false;
4776         if (tr.selector & SEGMENT_TI_MASK)      /* TI = 1 */
4777                 return false;
4778         if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
4779                 return false;
4780         if (!tr.present)
4781                 return false;
4782
4783         return true;
4784 }
4785
4786 static bool ldtr_valid(struct kvm_vcpu *vcpu)
4787 {
4788         struct kvm_segment ldtr;
4789
4790         vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
4791
4792         if (ldtr.unusable)
4793                 return true;
4794         if (ldtr.selector & SEGMENT_TI_MASK)    /* TI = 1 */
4795                 return false;
4796         if (ldtr.type != 2)
4797                 return false;
4798         if (!ldtr.present)
4799                 return false;
4800
4801         return true;
4802 }
4803
4804 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
4805 {
4806         struct kvm_segment cs, ss;
4807
4808         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
4809         vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
4810
4811         return ((cs.selector & SEGMENT_RPL_MASK) ==
4812                  (ss.selector & SEGMENT_RPL_MASK));
4813 }
4814
4815 /*
4816  * Check if guest state is valid. Returns true if valid, false if
4817  * not.
4818  * We assume that registers are always usable
4819  */
4820 static bool guest_state_valid(struct kvm_vcpu *vcpu)
4821 {
4822         if (enable_unrestricted_guest)
4823                 return true;
4824
4825         /* real mode guest state checks */
4826         if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
4827                 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
4828                         return false;
4829                 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
4830                         return false;
4831                 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
4832                         return false;
4833                 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
4834                         return false;
4835                 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
4836                         return false;
4837                 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
4838                         return false;
4839         } else {
4840         /* protected mode guest state checks */
4841                 if (!cs_ss_rpl_check(vcpu))
4842                         return false;
4843                 if (!code_segment_valid(vcpu))
4844                         return false;
4845                 if (!stack_segment_valid(vcpu))
4846                         return false;
4847                 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
4848                         return false;
4849                 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
4850                         return false;
4851                 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
4852                         return false;
4853                 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
4854                         return false;
4855                 if (!tr_valid(vcpu))
4856                         return false;
4857                 if (!ldtr_valid(vcpu))
4858                         return false;
4859         }
4860         /* TODO:
4861          * - Add checks on RIP
4862          * - Add checks on RFLAGS
4863          */
4864
4865         return true;
4866 }
4867
4868 static bool page_address_valid(struct kvm_vcpu *vcpu, gpa_t gpa)
4869 {
4870         return PAGE_ALIGNED(gpa) && !(gpa >> cpuid_maxphyaddr(vcpu));
4871 }
4872
4873 static int init_rmode_tss(struct kvm *kvm)
4874 {
4875         gfn_t fn;
4876         u16 data = 0;
4877         int idx, r;
4878
4879         idx = srcu_read_lock(&kvm->srcu);
4880         fn = kvm->arch.tss_addr >> PAGE_SHIFT;
4881         r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
4882         if (r < 0)
4883                 goto out;
4884         data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
4885         r = kvm_write_guest_page(kvm, fn++, &data,
4886                         TSS_IOPB_BASE_OFFSET, sizeof(u16));
4887         if (r < 0)
4888                 goto out;
4889         r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
4890         if (r < 0)
4891                 goto out;
4892         r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
4893         if (r < 0)
4894                 goto out;
4895         data = ~0;
4896         r = kvm_write_guest_page(kvm, fn, &data,
4897                                  RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
4898                                  sizeof(u8));
4899 out:
4900         srcu_read_unlock(&kvm->srcu, idx);
4901         return r;
4902 }
4903
4904 static int init_rmode_identity_map(struct kvm *kvm)
4905 {
4906         int i, idx, r = 0;
4907         kvm_pfn_t identity_map_pfn;
4908         u32 tmp;
4909
4910         if (!enable_ept)
4911                 return 0;
4912
4913         /* Protect kvm->arch.ept_identity_pagetable_done. */
4914         mutex_lock(&kvm->slots_lock);
4915
4916         if (likely(kvm->arch.ept_identity_pagetable_done))
4917                 goto out2;
4918
4919         identity_map_pfn = kvm->arch.ept_identity_map_addr >> PAGE_SHIFT;
4920
4921         r = alloc_identity_pagetable(kvm);
4922         if (r < 0)
4923                 goto out2;
4924
4925         idx = srcu_read_lock(&kvm->srcu);
4926         r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
4927         if (r < 0)
4928                 goto out;
4929         /* Set up identity-mapping pagetable for EPT in real mode */
4930         for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
4931                 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
4932                         _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
4933                 r = kvm_write_guest_page(kvm, identity_map_pfn,
4934                                 &tmp, i * sizeof(tmp), sizeof(tmp));
4935                 if (r < 0)
4936                         goto out;
4937         }
4938         kvm->arch.ept_identity_pagetable_done = true;
4939
4940 out:
4941         srcu_read_unlock(&kvm->srcu, idx);
4942
4943 out2:
4944         mutex_unlock(&kvm->slots_lock);
4945         return r;
4946 }
4947
4948 static void seg_setup(int seg)
4949 {
4950         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
4951         unsigned int ar;
4952
4953         vmcs_write16(sf->selector, 0);
4954         vmcs_writel(sf->base, 0);
4955         vmcs_write32(sf->limit, 0xffff);
4956         ar = 0x93;
4957         if (seg == VCPU_SREG_CS)
4958                 ar |= 0x08; /* code segment */
4959
4960         vmcs_write32(sf->ar_bytes, ar);
4961 }
4962
4963 static int alloc_apic_access_page(struct kvm *kvm)
4964 {
4965         struct page *page;
4966         int r = 0;
4967
4968         mutex_lock(&kvm->slots_lock);
4969         if (kvm->arch.apic_access_page_done)
4970                 goto out;
4971         r = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
4972                                     APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
4973         if (r)
4974                 goto out;
4975
4976         page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
4977         if (is_error_page(page)) {
4978                 r = -EFAULT;
4979                 goto out;
4980         }
4981
4982         /*
4983          * Do not pin the page in memory, so that memory hot-unplug
4984          * is able to migrate it.
4985          */
4986         put_page(page);
4987         kvm->arch.apic_access_page_done = true;
4988 out:
4989         mutex_unlock(&kvm->slots_lock);
4990         return r;
4991 }
4992
4993 static int alloc_identity_pagetable(struct kvm *kvm)
4994 {
4995         /* Called with kvm->slots_lock held. */
4996
4997         int r = 0;
4998
4999         BUG_ON(kvm->arch.ept_identity_pagetable_done);
5000
5001         r = __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
5002                                     kvm->arch.ept_identity_map_addr, PAGE_SIZE);
5003
5004         return r;
5005 }
5006
5007 static int allocate_vpid(void)
5008 {
5009         int vpid;
5010
5011         if (!enable_vpid)
5012                 return 0;
5013         spin_lock(&vmx_vpid_lock);
5014         vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
5015         if (vpid < VMX_NR_VPIDS)
5016                 __set_bit(vpid, vmx_vpid_bitmap);
5017         else
5018                 vpid = 0;
5019         spin_unlock(&vmx_vpid_lock);
5020         return vpid;
5021 }
5022
5023 static void free_vpid(int vpid)
5024 {
5025         if (!enable_vpid || vpid == 0)
5026                 return;
5027         spin_lock(&vmx_vpid_lock);
5028         __clear_bit(vpid, vmx_vpid_bitmap);
5029         spin_unlock(&vmx_vpid_lock);
5030 }
5031
5032 static void __always_inline vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
5033                                                           u32 msr, int type)
5034 {
5035         int f = sizeof(unsigned long);
5036
5037         if (!cpu_has_vmx_msr_bitmap())
5038                 return;
5039
5040         /*
5041          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
5042          * have the write-low and read-high bitmap offsets the wrong way round.
5043          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
5044          */
5045         if (msr <= 0x1fff) {
5046                 if (type & MSR_TYPE_R)
5047                         /* read-low */
5048                         __clear_bit(msr, msr_bitmap + 0x000 / f);
5049
5050                 if (type & MSR_TYPE_W)
5051                         /* write-low */
5052                         __clear_bit(msr, msr_bitmap + 0x800 / f);
5053
5054         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
5055                 msr &= 0x1fff;
5056                 if (type & MSR_TYPE_R)
5057                         /* read-high */
5058                         __clear_bit(msr, msr_bitmap + 0x400 / f);
5059
5060                 if (type & MSR_TYPE_W)
5061                         /* write-high */
5062                         __clear_bit(msr, msr_bitmap + 0xc00 / f);
5063
5064         }
5065 }
5066
5067 static void __always_inline vmx_enable_intercept_for_msr(unsigned long *msr_bitmap,
5068                                                          u32 msr, int type)
5069 {
5070         int f = sizeof(unsigned long);
5071
5072         if (!cpu_has_vmx_msr_bitmap())
5073                 return;
5074
5075         /*
5076          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
5077          * have the write-low and read-high bitmap offsets the wrong way round.
5078          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
5079          */
5080         if (msr <= 0x1fff) {
5081                 if (type & MSR_TYPE_R)
5082                         /* read-low */
5083                         __set_bit(msr, msr_bitmap + 0x000 / f);
5084
5085                 if (type & MSR_TYPE_W)
5086                         /* write-low */
5087                         __set_bit(msr, msr_bitmap + 0x800 / f);
5088
5089         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
5090                 msr &= 0x1fff;
5091                 if (type & MSR_TYPE_R)
5092                         /* read-high */
5093                         __set_bit(msr, msr_bitmap + 0x400 / f);
5094
5095                 if (type & MSR_TYPE_W)
5096                         /* write-high */
5097                         __set_bit(msr, msr_bitmap + 0xc00 / f);
5098
5099         }
5100 }
5101
5102 static void __always_inline vmx_set_intercept_for_msr(unsigned long *msr_bitmap,
5103                                                       u32 msr, int type, bool value)
5104 {
5105         if (value)
5106                 vmx_enable_intercept_for_msr(msr_bitmap, msr, type);
5107         else
5108                 vmx_disable_intercept_for_msr(msr_bitmap, msr, type);
5109 }
5110
5111 /*
5112  * If a msr is allowed by L0, we should check whether it is allowed by L1.
5113  * The corresponding bit will be cleared unless both of L0 and L1 allow it.
5114  */
5115 static void nested_vmx_disable_intercept_for_msr(unsigned long *msr_bitmap_l1,
5116                                                unsigned long *msr_bitmap_nested,
5117                                                u32 msr, int type)
5118 {
5119         int f = sizeof(unsigned long);
5120
5121         if (!cpu_has_vmx_msr_bitmap()) {
5122                 WARN_ON(1);
5123                 return;
5124         }
5125
5126         /*
5127          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
5128          * have the write-low and read-high bitmap offsets the wrong way round.
5129          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
5130          */
5131         if (msr <= 0x1fff) {
5132                 if (type & MSR_TYPE_R &&
5133                    !test_bit(msr, msr_bitmap_l1 + 0x000 / f))
5134                         /* read-low */
5135                         __clear_bit(msr, msr_bitmap_nested + 0x000 / f);
5136
5137                 if (type & MSR_TYPE_W &&
5138                    !test_bit(msr, msr_bitmap_l1 + 0x800 / f))
5139                         /* write-low */
5140                         __clear_bit(msr, msr_bitmap_nested + 0x800 / f);
5141
5142         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
5143                 msr &= 0x1fff;
5144                 if (type & MSR_TYPE_R &&
5145                    !test_bit(msr, msr_bitmap_l1 + 0x400 / f))
5146                         /* read-high */
5147                         __clear_bit(msr, msr_bitmap_nested + 0x400 / f);
5148
5149                 if (type & MSR_TYPE_W &&
5150                    !test_bit(msr, msr_bitmap_l1 + 0xc00 / f))
5151                         /* write-high */
5152                         __clear_bit(msr, msr_bitmap_nested + 0xc00 / f);
5153
5154         }
5155 }
5156
5157 static u8 vmx_msr_bitmap_mode(struct kvm_vcpu *vcpu)
5158 {
5159         u8 mode = 0;
5160
5161         if (cpu_has_secondary_exec_ctrls() &&
5162             (vmcs_read32(SECONDARY_VM_EXEC_CONTROL) &
5163              SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
5164                 mode |= MSR_BITMAP_MODE_X2APIC;
5165                 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
5166                         mode |= MSR_BITMAP_MODE_X2APIC_APICV;
5167         }
5168
5169         if (is_long_mode(vcpu))
5170                 mode |= MSR_BITMAP_MODE_LM;
5171
5172         return mode;
5173 }
5174
5175 #define X2APIC_MSR(r) (APIC_BASE_MSR + ((r) >> 4))
5176
5177 static void vmx_update_msr_bitmap_x2apic(unsigned long *msr_bitmap,
5178                                          u8 mode)
5179 {
5180         int msr;
5181
5182         for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
5183                 unsigned word = msr / BITS_PER_LONG;
5184                 msr_bitmap[word] = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
5185                 msr_bitmap[word + (0x800 / sizeof(long))] = ~0;
5186         }
5187
5188         if (mode & MSR_BITMAP_MODE_X2APIC) {
5189                 /*
5190                  * TPR reads and writes can be virtualized even if virtual interrupt
5191                  * delivery is not in use.
5192                  */
5193                 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW);
5194                 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
5195                         vmx_enable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_R);
5196                         vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
5197                         vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
5198                 }
5199         }
5200 }
5201
5202 static void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu)
5203 {
5204         struct vcpu_vmx *vmx = to_vmx(vcpu);
5205         unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
5206         u8 mode = vmx_msr_bitmap_mode(vcpu);
5207         u8 changed = mode ^ vmx->msr_bitmap_mode;
5208
5209         if (!changed)
5210                 return;
5211
5212         vmx_set_intercept_for_msr(msr_bitmap, MSR_KERNEL_GS_BASE, MSR_TYPE_RW,
5213                                   !(mode & MSR_BITMAP_MODE_LM));
5214
5215         if (changed & (MSR_BITMAP_MODE_X2APIC | MSR_BITMAP_MODE_X2APIC_APICV))
5216                 vmx_update_msr_bitmap_x2apic(msr_bitmap, mode);
5217
5218         vmx->msr_bitmap_mode = mode;
5219 }
5220
5221 static bool vmx_get_enable_apicv(struct kvm_vcpu *vcpu)
5222 {
5223         return enable_apicv;
5224 }
5225
5226 static void nested_mark_vmcs12_pages_dirty(struct kvm_vcpu *vcpu)
5227 {
5228         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5229         gfn_t gfn;
5230
5231         /*
5232          * Don't need to mark the APIC access page dirty; it is never
5233          * written to by the CPU during APIC virtualization.
5234          */
5235
5236         if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
5237                 gfn = vmcs12->virtual_apic_page_addr >> PAGE_SHIFT;
5238                 kvm_vcpu_mark_page_dirty(vcpu, gfn);
5239         }
5240
5241         if (nested_cpu_has_posted_intr(vmcs12)) {
5242                 gfn = vmcs12->posted_intr_desc_addr >> PAGE_SHIFT;
5243                 kvm_vcpu_mark_page_dirty(vcpu, gfn);
5244         }
5245 }
5246
5247
5248 static void vmx_complete_nested_posted_interrupt(struct kvm_vcpu *vcpu)
5249 {
5250         struct vcpu_vmx *vmx = to_vmx(vcpu);
5251         int max_irr;
5252         void *vapic_page;
5253         u16 status;
5254
5255         if (!vmx->nested.pi_desc || !vmx->nested.pi_pending)
5256                 return;
5257
5258         vmx->nested.pi_pending = false;
5259         if (!pi_test_and_clear_on(vmx->nested.pi_desc))
5260                 return;
5261
5262         max_irr = find_last_bit((unsigned long *)vmx->nested.pi_desc->pir, 256);
5263         if (max_irr != 256) {
5264                 vapic_page = kmap(vmx->nested.virtual_apic_page);
5265                 __kvm_apic_update_irr(vmx->nested.pi_desc->pir, vapic_page);
5266                 kunmap(vmx->nested.virtual_apic_page);
5267
5268                 status = vmcs_read16(GUEST_INTR_STATUS);
5269                 if ((u8)max_irr > ((u8)status & 0xff)) {
5270                         status &= ~0xff;
5271                         status |= (u8)max_irr;
5272                         vmcs_write16(GUEST_INTR_STATUS, status);
5273                 }
5274         }
5275
5276         nested_mark_vmcs12_pages_dirty(vcpu);
5277 }
5278
5279 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
5280                                                      bool nested)
5281 {
5282 #ifdef CONFIG_SMP
5283         int pi_vec = nested ? POSTED_INTR_NESTED_VECTOR : POSTED_INTR_VECTOR;
5284
5285         if (vcpu->mode == IN_GUEST_MODE) {
5286                 /*
5287                  * The vector of interrupt to be delivered to vcpu had
5288                  * been set in PIR before this function.
5289                  *
5290                  * Following cases will be reached in this block, and
5291                  * we always send a notification event in all cases as
5292                  * explained below.
5293                  *
5294                  * Case 1: vcpu keeps in non-root mode. Sending a
5295                  * notification event posts the interrupt to vcpu.
5296                  *
5297                  * Case 2: vcpu exits to root mode and is still
5298                  * runnable. PIR will be synced to vIRR before the
5299                  * next vcpu entry. Sending a notification event in
5300                  * this case has no effect, as vcpu is not in root
5301                  * mode.
5302                  *
5303                  * Case 3: vcpu exits to root mode and is blocked.
5304                  * vcpu_block() has already synced PIR to vIRR and
5305                  * never blocks vcpu if vIRR is not cleared. Therefore,
5306                  * a blocked vcpu here does not wait for any requested
5307                  * interrupts in PIR, and sending a notification event
5308                  * which has no effect is safe here.
5309                  */
5310
5311                 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
5312                 return true;
5313         }
5314 #endif
5315         return false;
5316 }
5317
5318 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
5319                                                 int vector)
5320 {
5321         struct vcpu_vmx *vmx = to_vmx(vcpu);
5322
5323         if (is_guest_mode(vcpu) &&
5324             vector == vmx->nested.posted_intr_nv) {
5325                 /*
5326                  * If a posted intr is not recognized by hardware,
5327                  * we will accomplish it in the next vmentry.
5328                  */
5329                 vmx->nested.pi_pending = true;
5330                 kvm_make_request(KVM_REQ_EVENT, vcpu);
5331                 /* the PIR and ON have been set by L1. */
5332                 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, true))
5333                         kvm_vcpu_kick(vcpu);
5334                 return 0;
5335         }
5336         return -1;
5337 }
5338 /*
5339  * Send interrupt to vcpu via posted interrupt way.
5340  * 1. If target vcpu is running(non-root mode), send posted interrupt
5341  * notification to vcpu and hardware will sync PIR to vIRR atomically.
5342  * 2. If target vcpu isn't running(root mode), kick it to pick up the
5343  * interrupt from PIR in next vmentry.
5344  */
5345 static void vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
5346 {
5347         struct vcpu_vmx *vmx = to_vmx(vcpu);
5348         int r;
5349
5350         r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
5351         if (!r)
5352                 return;
5353
5354         if (pi_test_and_set_pir(vector, &vmx->pi_desc))
5355                 return;
5356
5357         /* If a previous notification has sent the IPI, nothing to do.  */
5358         if (pi_test_and_set_on(&vmx->pi_desc))
5359                 return;
5360
5361         if (!kvm_vcpu_trigger_posted_interrupt(vcpu, false))
5362                 kvm_vcpu_kick(vcpu);
5363 }
5364
5365 /*
5366  * Set up the vmcs's constant host-state fields, i.e., host-state fields that
5367  * will not change in the lifetime of the guest.
5368  * Note that host-state that does change is set elsewhere. E.g., host-state
5369  * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
5370  */
5371 static void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
5372 {
5373         u32 low32, high32;
5374         unsigned long tmpl;
5375         struct desc_ptr dt;
5376         unsigned long cr0, cr3, cr4;
5377
5378         cr0 = read_cr0();
5379         WARN_ON(cr0 & X86_CR0_TS);
5380         vmcs_writel(HOST_CR0, cr0);  /* 22.2.3 */
5381
5382         /*
5383          * Save the most likely value for this task's CR3 in the VMCS.
5384          * We can't use __get_current_cr3_fast() because we're not atomic.
5385          */
5386         cr3 = __read_cr3();
5387         vmcs_writel(HOST_CR3, cr3);             /* 22.2.3  FIXME: shadow tables */
5388         vmx->loaded_vmcs->vmcs_host_cr3 = cr3;
5389
5390         /* Save the most likely value for this task's CR4 in the VMCS. */
5391         cr4 = cr4_read_shadow();
5392         vmcs_writel(HOST_CR4, cr4);                     /* 22.2.3, 22.2.5 */
5393         vmx->loaded_vmcs->vmcs_host_cr4 = cr4;
5394
5395         vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS);  /* 22.2.4 */
5396 #ifdef CONFIG_X86_64
5397         /*
5398          * Load null selectors, so we can avoid reloading them in
5399          * __vmx_load_host_state(), in case userspace uses the null selectors
5400          * too (the expected case).
5401          */
5402         vmcs_write16(HOST_DS_SELECTOR, 0);
5403         vmcs_write16(HOST_ES_SELECTOR, 0);
5404 #else
5405         vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
5406         vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
5407 #endif
5408         vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
5409         vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8);  /* 22.2.4 */
5410
5411         store_idt(&dt);
5412         vmcs_writel(HOST_IDTR_BASE, dt.address);   /* 22.2.4 */
5413         vmx->host_idt_base = dt.address;
5414
5415         vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */
5416
5417         rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
5418         vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
5419         rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
5420         vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl);   /* 22.2.3 */
5421
5422         if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
5423                 rdmsr(MSR_IA32_CR_PAT, low32, high32);
5424                 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
5425         }
5426 }
5427
5428 static void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
5429 {
5430         vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
5431         if (enable_ept)
5432                 vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
5433         if (is_guest_mode(&vmx->vcpu))
5434                 vmx->vcpu.arch.cr4_guest_owned_bits &=
5435                         ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
5436         vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
5437 }
5438
5439 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
5440 {
5441         u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
5442
5443         if (!kvm_vcpu_apicv_active(&vmx->vcpu))
5444                 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
5445         /* Enable the preemption timer dynamically */
5446         pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
5447         return pin_based_exec_ctrl;
5448 }
5449
5450 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
5451 {
5452         struct vcpu_vmx *vmx = to_vmx(vcpu);
5453
5454         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
5455         if (cpu_has_secondary_exec_ctrls()) {
5456                 if (kvm_vcpu_apicv_active(vcpu))
5457                         vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
5458                                       SECONDARY_EXEC_APIC_REGISTER_VIRT |
5459                                       SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
5460                 else
5461                         vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
5462                                         SECONDARY_EXEC_APIC_REGISTER_VIRT |
5463                                         SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
5464         }
5465
5466         if (cpu_has_vmx_msr_bitmap())
5467                 vmx_update_msr_bitmap(vcpu);
5468 }
5469
5470 static u32 vmx_exec_control(struct vcpu_vmx *vmx)
5471 {
5472         u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
5473
5474         if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
5475                 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
5476
5477         if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
5478                 exec_control &= ~CPU_BASED_TPR_SHADOW;
5479 #ifdef CONFIG_X86_64
5480                 exec_control |= CPU_BASED_CR8_STORE_EXITING |
5481                                 CPU_BASED_CR8_LOAD_EXITING;
5482 #endif
5483         }
5484         if (!enable_ept)
5485                 exec_control |= CPU_BASED_CR3_STORE_EXITING |
5486                                 CPU_BASED_CR3_LOAD_EXITING  |
5487                                 CPU_BASED_INVLPG_EXITING;
5488         return exec_control;
5489 }
5490
5491 static bool vmx_rdrand_supported(void)
5492 {
5493         return vmcs_config.cpu_based_2nd_exec_ctrl &
5494                 SECONDARY_EXEC_RDRAND;
5495 }
5496
5497 static bool vmx_rdseed_supported(void)
5498 {
5499         return vmcs_config.cpu_based_2nd_exec_ctrl &
5500                 SECONDARY_EXEC_RDSEED;
5501 }
5502
5503 static void vmx_compute_secondary_exec_control(struct vcpu_vmx *vmx)
5504 {
5505         struct kvm_vcpu *vcpu = &vmx->vcpu;
5506
5507         u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
5508         if (!cpu_need_virtualize_apic_accesses(vcpu))
5509                 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
5510         if (vmx->vpid == 0)
5511                 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
5512         if (!enable_ept) {
5513                 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
5514                 enable_unrestricted_guest = 0;
5515                 /* Enable INVPCID for non-ept guests may cause performance regression. */
5516                 exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
5517         }
5518         if (!enable_unrestricted_guest)
5519                 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
5520         if (!ple_gap)
5521                 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
5522         if (!kvm_vcpu_apicv_active(vcpu))
5523                 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
5524                                   SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
5525         exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
5526         /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
5527            (handle_vmptrld).
5528            We can NOT enable shadow_vmcs here because we don't have yet
5529            a current VMCS12
5530         */
5531         exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
5532
5533         if (!enable_pml)
5534                 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
5535
5536         if (vmx_xsaves_supported()) {
5537                 /* Exposing XSAVES only when XSAVE is exposed */
5538                 bool xsaves_enabled =
5539                         guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
5540                         guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
5541
5542                 if (!xsaves_enabled)
5543                         exec_control &= ~SECONDARY_EXEC_XSAVES;
5544
5545                 if (nested) {
5546                         if (xsaves_enabled)
5547                                 vmx->nested.nested_vmx_secondary_ctls_high |=
5548                                         SECONDARY_EXEC_XSAVES;
5549                         else
5550                                 vmx->nested.nested_vmx_secondary_ctls_high &=
5551                                         ~SECONDARY_EXEC_XSAVES;
5552                 }
5553         }
5554
5555         if (vmx_rdtscp_supported()) {
5556                 bool rdtscp_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP);
5557                 if (!rdtscp_enabled)
5558                         exec_control &= ~SECONDARY_EXEC_RDTSCP;
5559
5560                 if (nested) {
5561                         if (rdtscp_enabled)
5562                                 vmx->nested.nested_vmx_secondary_ctls_high |=
5563                                         SECONDARY_EXEC_RDTSCP;
5564                         else
5565                                 vmx->nested.nested_vmx_secondary_ctls_high &=
5566                                         ~SECONDARY_EXEC_RDTSCP;
5567                 }
5568         }
5569
5570         if (vmx_invpcid_supported()) {
5571                 /* Exposing INVPCID only when PCID is exposed */
5572                 bool invpcid_enabled =
5573                         guest_cpuid_has(vcpu, X86_FEATURE_INVPCID) &&
5574                         guest_cpuid_has(vcpu, X86_FEATURE_PCID);
5575
5576                 if (!invpcid_enabled) {
5577                         exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
5578                         guest_cpuid_clear(vcpu, X86_FEATURE_INVPCID);
5579                 }
5580
5581                 if (nested) {
5582                         if (invpcid_enabled)
5583                                 vmx->nested.nested_vmx_secondary_ctls_high |=
5584                                         SECONDARY_EXEC_ENABLE_INVPCID;
5585                         else
5586                                 vmx->nested.nested_vmx_secondary_ctls_high &=
5587                                         ~SECONDARY_EXEC_ENABLE_INVPCID;
5588                 }
5589         }
5590
5591         if (vmx_rdrand_supported()) {
5592                 bool rdrand_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDRAND);
5593                 if (rdrand_enabled)
5594                         exec_control &= ~SECONDARY_EXEC_RDRAND;
5595
5596                 if (nested) {
5597                         if (rdrand_enabled)
5598                                 vmx->nested.nested_vmx_secondary_ctls_high |=
5599                                         SECONDARY_EXEC_RDRAND;
5600                         else
5601                                 vmx->nested.nested_vmx_secondary_ctls_high &=
5602                                         ~SECONDARY_EXEC_RDRAND;
5603                 }
5604         }
5605
5606         if (vmx_rdseed_supported()) {
5607                 bool rdseed_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDSEED);
5608                 if (rdseed_enabled)
5609                         exec_control &= ~SECONDARY_EXEC_RDSEED;
5610
5611                 if (nested) {
5612                         if (rdseed_enabled)
5613                                 vmx->nested.nested_vmx_secondary_ctls_high |=
5614                                         SECONDARY_EXEC_RDSEED;
5615                         else
5616                                 vmx->nested.nested_vmx_secondary_ctls_high &=
5617                                         ~SECONDARY_EXEC_RDSEED;
5618                 }
5619         }
5620
5621         vmx->secondary_exec_control = exec_control;
5622 }
5623
5624 static void ept_set_mmio_spte_mask(void)
5625 {
5626         /*
5627          * EPT Misconfigurations can be generated if the value of bits 2:0
5628          * of an EPT paging-structure entry is 110b (write/execute).
5629          */
5630         kvm_mmu_set_mmio_spte_mask(VMX_EPT_RWX_MASK,
5631                                    VMX_EPT_MISCONFIG_WX_VALUE);
5632 }
5633
5634 #define VMX_XSS_EXIT_BITMAP 0
5635 /*
5636  * Sets up the vmcs for emulated real mode.
5637  */
5638 static int vmx_vcpu_setup(struct vcpu_vmx *vmx)
5639 {
5640 #ifdef CONFIG_X86_64
5641         unsigned long a;
5642 #endif
5643         int i;
5644
5645         /* I/O */
5646         vmcs_write64(IO_BITMAP_A, __pa(vmx_io_bitmap_a));
5647         vmcs_write64(IO_BITMAP_B, __pa(vmx_io_bitmap_b));
5648
5649         if (enable_shadow_vmcs) {
5650                 vmcs_write64(VMREAD_BITMAP, __pa(vmx_vmread_bitmap));
5651                 vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmwrite_bitmap));
5652         }
5653         if (cpu_has_vmx_msr_bitmap())
5654                 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
5655
5656         vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
5657
5658         /* Control */
5659         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
5660         vmx->hv_deadline_tsc = -1;
5661
5662         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
5663
5664         if (cpu_has_secondary_exec_ctrls()) {
5665                 vmx_compute_secondary_exec_control(vmx);
5666                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
5667                              vmx->secondary_exec_control);
5668         }
5669
5670         if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
5671                 vmcs_write64(EOI_EXIT_BITMAP0, 0);
5672                 vmcs_write64(EOI_EXIT_BITMAP1, 0);
5673                 vmcs_write64(EOI_EXIT_BITMAP2, 0);
5674                 vmcs_write64(EOI_EXIT_BITMAP3, 0);
5675
5676                 vmcs_write16(GUEST_INTR_STATUS, 0);
5677
5678                 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
5679                 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
5680         }
5681
5682         if (ple_gap) {
5683                 vmcs_write32(PLE_GAP, ple_gap);
5684                 vmx->ple_window = ple_window;
5685                 vmx->ple_window_dirty = true;
5686         }
5687
5688         vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
5689         vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
5690         vmcs_write32(CR3_TARGET_COUNT, 0);           /* 22.2.1 */
5691
5692         vmcs_write16(HOST_FS_SELECTOR, 0);            /* 22.2.4 */
5693         vmcs_write16(HOST_GS_SELECTOR, 0);            /* 22.2.4 */
5694         vmx_set_constant_host_state(vmx);
5695 #ifdef CONFIG_X86_64
5696         rdmsrl(MSR_FS_BASE, a);
5697         vmcs_writel(HOST_FS_BASE, a); /* 22.2.4 */
5698         rdmsrl(MSR_GS_BASE, a);
5699         vmcs_writel(HOST_GS_BASE, a); /* 22.2.4 */
5700 #else
5701         vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
5702         vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
5703 #endif
5704
5705         if (cpu_has_vmx_vmfunc())
5706                 vmcs_write64(VM_FUNCTION_CONTROL, 0);
5707
5708         vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
5709         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
5710         vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host));
5711         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
5712         vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest));
5713
5714         if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
5715                 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
5716
5717         for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
5718                 u32 index = vmx_msr_index[i];
5719                 u32 data_low, data_high;
5720                 int j = vmx->nmsrs;
5721
5722                 if (rdmsr_safe(index, &data_low, &data_high) < 0)
5723                         continue;
5724                 if (wrmsr_safe(index, data_low, data_high) < 0)
5725                         continue;
5726                 vmx->guest_msrs[j].index = i;
5727                 vmx->guest_msrs[j].data = 0;
5728                 vmx->guest_msrs[j].mask = -1ull;
5729                 ++vmx->nmsrs;
5730         }
5731
5732         if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES))
5733                 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, vmx->arch_capabilities);
5734
5735         vm_exit_controls_init(vmx, vmcs_config.vmexit_ctrl);
5736
5737         /* 22.2.1, 20.8.1 */
5738         vm_entry_controls_init(vmx, vmcs_config.vmentry_ctrl);
5739
5740         vmx->vcpu.arch.cr0_guest_owned_bits = X86_CR0_TS;
5741         vmcs_writel(CR0_GUEST_HOST_MASK, ~X86_CR0_TS);
5742
5743         set_cr4_guest_host_mask(vmx);
5744
5745         if (vmx_xsaves_supported())
5746                 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
5747
5748         if (enable_pml) {
5749                 ASSERT(vmx->pml_pg);
5750                 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
5751                 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
5752         }
5753
5754         return 0;
5755 }
5756
5757 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
5758 {
5759         struct vcpu_vmx *vmx = to_vmx(vcpu);
5760         struct msr_data apic_base_msr;
5761         u64 cr0;
5762
5763         vmx->rmode.vm86_active = 0;
5764         vmx->spec_ctrl = 0;
5765
5766         vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
5767         kvm_set_cr8(vcpu, 0);
5768
5769         if (!init_event) {
5770                 apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
5771                                      MSR_IA32_APICBASE_ENABLE;
5772                 if (kvm_vcpu_is_reset_bsp(vcpu))
5773                         apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
5774                 apic_base_msr.host_initiated = true;
5775                 kvm_set_apic_base(vcpu, &apic_base_msr);
5776         }
5777
5778         vmx_segment_cache_clear(vmx);
5779
5780         seg_setup(VCPU_SREG_CS);
5781         vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
5782         vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
5783
5784         seg_setup(VCPU_SREG_DS);
5785         seg_setup(VCPU_SREG_ES);
5786         seg_setup(VCPU_SREG_FS);
5787         seg_setup(VCPU_SREG_GS);
5788         seg_setup(VCPU_SREG_SS);
5789
5790         vmcs_write16(GUEST_TR_SELECTOR, 0);
5791         vmcs_writel(GUEST_TR_BASE, 0);
5792         vmcs_write32(GUEST_TR_LIMIT, 0xffff);
5793         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
5794
5795         vmcs_write16(GUEST_LDTR_SELECTOR, 0);
5796         vmcs_writel(GUEST_LDTR_BASE, 0);
5797         vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
5798         vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
5799
5800         if (!init_event) {
5801                 vmcs_write32(GUEST_SYSENTER_CS, 0);
5802                 vmcs_writel(GUEST_SYSENTER_ESP, 0);
5803                 vmcs_writel(GUEST_SYSENTER_EIP, 0);
5804                 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
5805         }
5806
5807         kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
5808         kvm_rip_write(vcpu, 0xfff0);
5809
5810         vmcs_writel(GUEST_GDTR_BASE, 0);
5811         vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
5812
5813         vmcs_writel(GUEST_IDTR_BASE, 0);
5814         vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
5815
5816         vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
5817         vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
5818         vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
5819
5820         setup_msrs(vmx);
5821
5822         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);  /* 22.2.1 */
5823
5824         if (cpu_has_vmx_tpr_shadow() && !init_event) {
5825                 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
5826                 if (cpu_need_tpr_shadow(vcpu))
5827                         vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
5828                                      __pa(vcpu->arch.apic->regs));
5829                 vmcs_write32(TPR_THRESHOLD, 0);
5830         }
5831
5832         kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
5833
5834         if (vmx->vpid != 0)
5835                 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
5836
5837         cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
5838         vmx->vcpu.arch.cr0 = cr0;
5839         vmx_set_cr0(vcpu, cr0); /* enter rmode */
5840         vmx_set_cr4(vcpu, 0);
5841         vmx_set_efer(vcpu, 0);
5842
5843         update_exception_bitmap(vcpu);
5844
5845         vpid_sync_context(vmx->vpid);
5846 }
5847
5848 /*
5849  * In nested virtualization, check if L1 asked to exit on external interrupts.
5850  * For most existing hypervisors, this will always return true.
5851  */
5852 static bool nested_exit_on_intr(struct kvm_vcpu *vcpu)
5853 {
5854         return get_vmcs12(vcpu)->pin_based_vm_exec_control &
5855                 PIN_BASED_EXT_INTR_MASK;
5856 }
5857
5858 /*
5859  * In nested virtualization, check if L1 has set
5860  * VM_EXIT_ACK_INTR_ON_EXIT
5861  */
5862 static bool nested_exit_intr_ack_set(struct kvm_vcpu *vcpu)
5863 {
5864         return get_vmcs12(vcpu)->vm_exit_controls &
5865                 VM_EXIT_ACK_INTR_ON_EXIT;
5866 }
5867
5868 static bool nested_exit_on_nmi(struct kvm_vcpu *vcpu)
5869 {
5870         return get_vmcs12(vcpu)->pin_based_vm_exec_control &
5871                 PIN_BASED_NMI_EXITING;
5872 }
5873
5874 static void enable_irq_window(struct kvm_vcpu *vcpu)
5875 {
5876         vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
5877                       CPU_BASED_VIRTUAL_INTR_PENDING);
5878 }
5879
5880 static void enable_nmi_window(struct kvm_vcpu *vcpu)
5881 {
5882         if (!cpu_has_virtual_nmis() ||
5883             vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
5884                 enable_irq_window(vcpu);
5885                 return;
5886         }
5887
5888         vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
5889                       CPU_BASED_VIRTUAL_NMI_PENDING);
5890 }
5891
5892 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
5893 {
5894         struct vcpu_vmx *vmx = to_vmx(vcpu);
5895         uint32_t intr;
5896         int irq = vcpu->arch.interrupt.nr;
5897
5898         trace_kvm_inj_virq(irq);
5899
5900         ++vcpu->stat.irq_injections;
5901         if (vmx->rmode.vm86_active) {
5902                 int inc_eip = 0;
5903                 if (vcpu->arch.interrupt.soft)
5904                         inc_eip = vcpu->arch.event_exit_inst_len;
5905                 if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE)
5906                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5907                 return;
5908         }
5909         intr = irq | INTR_INFO_VALID_MASK;
5910         if (vcpu->arch.interrupt.soft) {
5911                 intr |= INTR_TYPE_SOFT_INTR;
5912                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
5913                              vmx->vcpu.arch.event_exit_inst_len);
5914         } else
5915                 intr |= INTR_TYPE_EXT_INTR;
5916         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
5917 }
5918
5919 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
5920 {
5921         struct vcpu_vmx *vmx = to_vmx(vcpu);
5922
5923         if (!cpu_has_virtual_nmis()) {
5924                 /*
5925                  * Tracking the NMI-blocked state in software is built upon
5926                  * finding the next open IRQ window. This, in turn, depends on
5927                  * well-behaving guests: They have to keep IRQs disabled at
5928                  * least as long as the NMI handler runs. Otherwise we may
5929                  * cause NMI nesting, maybe breaking the guest. But as this is
5930                  * highly unlikely, we can live with the residual risk.
5931                  */
5932                 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
5933                 vmx->loaded_vmcs->vnmi_blocked_time = 0;
5934         }
5935
5936         ++vcpu->stat.nmi_injections;
5937         vmx->loaded_vmcs->nmi_known_unmasked = false;
5938
5939         if (vmx->rmode.vm86_active) {
5940                 if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE)
5941                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5942                 return;
5943         }
5944
5945         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
5946                         INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
5947 }
5948
5949 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
5950 {
5951         struct vcpu_vmx *vmx = to_vmx(vcpu);
5952         bool masked;
5953
5954         if (!cpu_has_virtual_nmis())
5955                 return vmx->loaded_vmcs->soft_vnmi_blocked;
5956         if (vmx->loaded_vmcs->nmi_known_unmasked)
5957                 return false;
5958         masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
5959         vmx->loaded_vmcs->nmi_known_unmasked = !masked;
5960         return masked;
5961 }
5962
5963 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
5964 {
5965         struct vcpu_vmx *vmx = to_vmx(vcpu);
5966
5967         if (!cpu_has_virtual_nmis()) {
5968                 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
5969                         vmx->loaded_vmcs->soft_vnmi_blocked = masked;
5970                         vmx->loaded_vmcs->vnmi_blocked_time = 0;
5971                 }
5972         } else {
5973                 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
5974                 if (masked)
5975                         vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5976                                       GUEST_INTR_STATE_NMI);
5977                 else
5978                         vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
5979                                         GUEST_INTR_STATE_NMI);
5980         }
5981 }
5982
5983 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
5984 {
5985         if (to_vmx(vcpu)->nested.nested_run_pending)
5986                 return 0;
5987
5988         if (!cpu_has_virtual_nmis() &&
5989             to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
5990                 return 0;
5991
5992         return  !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
5993                   (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
5994                    | GUEST_INTR_STATE_NMI));
5995 }
5996
5997 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
5998 {
5999         return (!to_vmx(vcpu)->nested.nested_run_pending &&
6000                 vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
6001                 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
6002                         (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
6003 }
6004
6005 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
6006 {
6007         int ret;
6008
6009         ret = x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
6010                                     PAGE_SIZE * 3);
6011         if (ret)
6012                 return ret;
6013         kvm->arch.tss_addr = addr;
6014         return init_rmode_tss(kvm);
6015 }
6016
6017 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
6018 {
6019         switch (vec) {
6020         case BP_VECTOR:
6021                 /*
6022                  * Update instruction length as we may reinject the exception
6023                  * from user space while in guest debugging mode.
6024                  */
6025                 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
6026                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
6027                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
6028                         return false;
6029                 /* fall through */
6030         case DB_VECTOR:
6031                 if (vcpu->guest_debug &
6032                         (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
6033                         return false;
6034                 /* fall through */
6035         case DE_VECTOR:
6036         case OF_VECTOR:
6037         case BR_VECTOR:
6038         case UD_VECTOR:
6039         case DF_VECTOR:
6040         case SS_VECTOR:
6041         case GP_VECTOR:
6042         case MF_VECTOR:
6043                 return true;
6044         break;
6045         }
6046         return false;
6047 }
6048
6049 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
6050                                   int vec, u32 err_code)
6051 {
6052         /*
6053          * Instruction with address size override prefix opcode 0x67
6054          * Cause the #SS fault with 0 error code in VM86 mode.
6055          */
6056         if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
6057                 if (emulate_instruction(vcpu, 0) == EMULATE_DONE) {
6058                         if (vcpu->arch.halt_request) {
6059                                 vcpu->arch.halt_request = 0;
6060                                 return kvm_vcpu_halt(vcpu);
6061                         }
6062                         return 1;
6063                 }
6064                 return 0;
6065         }
6066
6067         /*
6068          * Forward all other exceptions that are valid in real mode.
6069          * FIXME: Breaks guest debugging in real mode, needs to be fixed with
6070          *        the required debugging infrastructure rework.
6071          */
6072         kvm_queue_exception(vcpu, vec);
6073         return 1;
6074 }
6075
6076 /*
6077  * Trigger machine check on the host. We assume all the MSRs are already set up
6078  * by the CPU and that we still run on the same CPU as the MCE occurred on.
6079  * We pass a fake environment to the machine check handler because we want
6080  * the guest to be always treated like user space, no matter what context
6081  * it used internally.
6082  */
6083 static void kvm_machine_check(void)
6084 {
6085 #if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
6086         struct pt_regs regs = {
6087                 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
6088                 .flags = X86_EFLAGS_IF,
6089         };
6090
6091         do_machine_check(&regs, 0);
6092 #endif
6093 }
6094
6095 static int handle_machine_check(struct kvm_vcpu *vcpu)
6096 {
6097         /* already handled by vcpu_run */
6098         return 1;
6099 }
6100
6101 static int handle_exception(struct kvm_vcpu *vcpu)
6102 {
6103         struct vcpu_vmx *vmx = to_vmx(vcpu);
6104         struct kvm_run *kvm_run = vcpu->run;
6105         u32 intr_info, ex_no, error_code;
6106         unsigned long cr2, rip, dr6;
6107         u32 vect_info;
6108         enum emulation_result er;
6109
6110         vect_info = vmx->idt_vectoring_info;
6111         intr_info = vmx->exit_intr_info;
6112
6113         if (is_machine_check(intr_info))
6114                 return handle_machine_check(vcpu);
6115
6116         if (is_nmi(intr_info))
6117                 return 1;  /* already handled by vmx_vcpu_run() */
6118
6119         if (is_invalid_opcode(intr_info)) {
6120                 er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD);
6121                 if (er == EMULATE_USER_EXIT)
6122                         return 0;
6123                 if (er != EMULATE_DONE)
6124                         kvm_queue_exception(vcpu, UD_VECTOR);
6125                 return 1;
6126         }
6127
6128         error_code = 0;
6129         if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
6130                 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
6131
6132         /*
6133          * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
6134          * MMIO, it is better to report an internal error.
6135          * See the comments in vmx_handle_exit.
6136          */
6137         if ((vect_info & VECTORING_INFO_VALID_MASK) &&
6138             !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
6139                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6140                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
6141                 vcpu->run->internal.ndata = 3;
6142                 vcpu->run->internal.data[0] = vect_info;
6143                 vcpu->run->internal.data[1] = intr_info;
6144                 vcpu->run->internal.data[2] = error_code;
6145                 return 0;
6146         }
6147
6148         if (is_page_fault(intr_info)) {
6149                 cr2 = vmcs_readl(EXIT_QUALIFICATION);
6150                 /* EPT won't cause page fault directly */
6151                 WARN_ON_ONCE(!vcpu->arch.apf.host_apf_reason && enable_ept);
6152                 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0,
6153                                 true);
6154         }
6155
6156         ex_no = intr_info & INTR_INFO_VECTOR_MASK;
6157
6158         if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
6159                 return handle_rmode_exception(vcpu, ex_no, error_code);
6160
6161         switch (ex_no) {
6162         case AC_VECTOR:
6163                 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
6164                 return 1;
6165         case DB_VECTOR:
6166                 dr6 = vmcs_readl(EXIT_QUALIFICATION);
6167                 if (!(vcpu->guest_debug &
6168                       (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
6169                         vcpu->arch.dr6 &= ~15;
6170                         vcpu->arch.dr6 |= dr6 | DR6_RTM;
6171                         if (!(dr6 & ~DR6_RESERVED)) /* icebp */
6172                                 skip_emulated_instruction(vcpu);
6173
6174                         kvm_queue_exception(vcpu, DB_VECTOR);
6175                         return 1;
6176                 }
6177                 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
6178                 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
6179                 /* fall through */
6180         case BP_VECTOR:
6181                 /*
6182                  * Update instruction length as we may reinject #BP from
6183                  * user space while in guest debugging mode. Reading it for
6184                  * #DB as well causes no harm, it is not used in that case.
6185                  */
6186                 vmx->vcpu.arch.event_exit_inst_len =
6187                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
6188                 kvm_run->exit_reason = KVM_EXIT_DEBUG;
6189                 rip = kvm_rip_read(vcpu);
6190                 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
6191                 kvm_run->debug.arch.exception = ex_no;
6192                 break;
6193         default:
6194                 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
6195                 kvm_run->ex.exception = ex_no;
6196                 kvm_run->ex.error_code = error_code;
6197                 break;
6198         }
6199         return 0;
6200 }
6201
6202 static int handle_external_interrupt(struct kvm_vcpu *vcpu)
6203 {
6204         ++vcpu->stat.irq_exits;
6205         return 1;
6206 }
6207
6208 static int handle_triple_fault(struct kvm_vcpu *vcpu)
6209 {
6210         vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
6211         vcpu->mmio_needed = 0;
6212         return 0;
6213 }
6214
6215 static int handle_io(struct kvm_vcpu *vcpu)
6216 {
6217         unsigned long exit_qualification;
6218         int size, in, string, ret;
6219         unsigned port;
6220
6221         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6222         string = (exit_qualification & 16) != 0;
6223         in = (exit_qualification & 8) != 0;
6224
6225         ++vcpu->stat.io_exits;
6226
6227         if (string || in)
6228                 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
6229
6230         port = exit_qualification >> 16;
6231         size = (exit_qualification & 7) + 1;
6232
6233         ret = kvm_skip_emulated_instruction(vcpu);
6234
6235         /*
6236          * TODO: we might be squashing a KVM_GUESTDBG_SINGLESTEP-triggered
6237          * KVM_EXIT_DEBUG here.
6238          */
6239         return kvm_fast_pio_out(vcpu, size, port) && ret;
6240 }
6241
6242 static void
6243 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
6244 {
6245         /*
6246          * Patch in the VMCALL instruction:
6247          */
6248         hypercall[0] = 0x0f;
6249         hypercall[1] = 0x01;
6250         hypercall[2] = 0xc1;
6251 }
6252
6253 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
6254 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
6255 {
6256         if (is_guest_mode(vcpu)) {
6257                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6258                 unsigned long orig_val = val;
6259
6260                 /*
6261                  * We get here when L2 changed cr0 in a way that did not change
6262                  * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
6263                  * but did change L0 shadowed bits. So we first calculate the
6264                  * effective cr0 value that L1 would like to write into the
6265                  * hardware. It consists of the L2-owned bits from the new
6266                  * value combined with the L1-owned bits from L1's guest_cr0.
6267                  */
6268                 val = (val & ~vmcs12->cr0_guest_host_mask) |
6269                         (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
6270
6271                 if (!nested_guest_cr0_valid(vcpu, val))
6272                         return 1;
6273
6274                 if (kvm_set_cr0(vcpu, val))
6275                         return 1;
6276                 vmcs_writel(CR0_READ_SHADOW, orig_val);
6277                 return 0;
6278         } else {
6279                 if (to_vmx(vcpu)->nested.vmxon &&
6280                     !nested_host_cr0_valid(vcpu, val))
6281                         return 1;
6282
6283                 return kvm_set_cr0(vcpu, val);
6284         }
6285 }
6286
6287 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
6288 {
6289         if (is_guest_mode(vcpu)) {
6290                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6291                 unsigned long orig_val = val;
6292
6293                 /* analogously to handle_set_cr0 */
6294                 val = (val & ~vmcs12->cr4_guest_host_mask) |
6295                         (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
6296                 if (kvm_set_cr4(vcpu, val))
6297                         return 1;
6298                 vmcs_writel(CR4_READ_SHADOW, orig_val);
6299                 return 0;
6300         } else
6301                 return kvm_set_cr4(vcpu, val);
6302 }
6303
6304 static int handle_cr(struct kvm_vcpu *vcpu)
6305 {
6306         unsigned long exit_qualification, val;
6307         int cr;
6308         int reg;
6309         int err;
6310         int ret;
6311
6312         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6313         cr = exit_qualification & 15;
6314         reg = (exit_qualification >> 8) & 15;
6315         switch ((exit_qualification >> 4) & 3) {
6316         case 0: /* mov to cr */
6317                 val = kvm_register_readl(vcpu, reg);
6318                 trace_kvm_cr_write(cr, val);
6319                 switch (cr) {
6320                 case 0:
6321                         err = handle_set_cr0(vcpu, val);
6322                         return kvm_complete_insn_gp(vcpu, err);
6323                 case 3:
6324                         err = kvm_set_cr3(vcpu, val);
6325                         return kvm_complete_insn_gp(vcpu, err);
6326                 case 4:
6327                         err = handle_set_cr4(vcpu, val);
6328                         return kvm_complete_insn_gp(vcpu, err);
6329                 case 8: {
6330                                 u8 cr8_prev = kvm_get_cr8(vcpu);
6331                                 u8 cr8 = (u8)val;
6332                                 err = kvm_set_cr8(vcpu, cr8);
6333                                 ret = kvm_complete_insn_gp(vcpu, err);
6334                                 if (lapic_in_kernel(vcpu))
6335                                         return ret;
6336                                 if (cr8_prev <= cr8)
6337                                         return ret;
6338                                 /*
6339                                  * TODO: we might be squashing a
6340                                  * KVM_GUESTDBG_SINGLESTEP-triggered
6341                                  * KVM_EXIT_DEBUG here.
6342                                  */
6343                                 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
6344                                 return 0;
6345                         }
6346                 }
6347                 break;
6348         case 2: /* clts */
6349                 WARN_ONCE(1, "Guest should always own CR0.TS");
6350                 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
6351                 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
6352                 return kvm_skip_emulated_instruction(vcpu);
6353         case 1: /*mov from cr*/
6354                 switch (cr) {
6355                 case 3:
6356                         val = kvm_read_cr3(vcpu);
6357                         kvm_register_write(vcpu, reg, val);
6358                         trace_kvm_cr_read(cr, val);
6359                         return kvm_skip_emulated_instruction(vcpu);
6360                 case 8:
6361                         val = kvm_get_cr8(vcpu);
6362                         kvm_register_write(vcpu, reg, val);
6363                         trace_kvm_cr_read(cr, val);
6364                         return kvm_skip_emulated_instruction(vcpu);
6365                 }
6366                 break;
6367         case 3: /* lmsw */
6368                 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
6369                 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
6370                 kvm_lmsw(vcpu, val);
6371
6372                 return kvm_skip_emulated_instruction(vcpu);
6373         default:
6374                 break;
6375         }
6376         vcpu->run->exit_reason = 0;
6377         vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
6378                (int)(exit_qualification >> 4) & 3, cr);
6379         return 0;
6380 }
6381
6382 static int handle_dr(struct kvm_vcpu *vcpu)
6383 {
6384         unsigned long exit_qualification;
6385         int dr, dr7, reg;
6386
6387         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6388         dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
6389
6390         /* First, if DR does not exist, trigger UD */
6391         if (!kvm_require_dr(vcpu, dr))
6392                 return 1;
6393
6394         /* Do not handle if the CPL > 0, will trigger GP on re-entry */
6395         if (!kvm_require_cpl(vcpu, 0))
6396                 return 1;
6397         dr7 = vmcs_readl(GUEST_DR7);
6398         if (dr7 & DR7_GD) {
6399                 /*
6400                  * As the vm-exit takes precedence over the debug trap, we
6401                  * need to emulate the latter, either for the host or the
6402                  * guest debugging itself.
6403                  */
6404                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
6405                         vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
6406                         vcpu->run->debug.arch.dr7 = dr7;
6407                         vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
6408                         vcpu->run->debug.arch.exception = DB_VECTOR;
6409                         vcpu->run->exit_reason = KVM_EXIT_DEBUG;
6410                         return 0;
6411                 } else {
6412                         vcpu->arch.dr6 &= ~15;
6413                         vcpu->arch.dr6 |= DR6_BD | DR6_RTM;
6414                         kvm_queue_exception(vcpu, DB_VECTOR);
6415                         return 1;
6416                 }
6417         }
6418
6419         if (vcpu->guest_debug == 0) {
6420                 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
6421                                 CPU_BASED_MOV_DR_EXITING);
6422
6423                 /*
6424                  * No more DR vmexits; force a reload of the debug registers
6425                  * and reenter on this instruction.  The next vmexit will
6426                  * retrieve the full state of the debug registers.
6427                  */
6428                 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
6429                 return 1;
6430         }
6431
6432         reg = DEBUG_REG_ACCESS_REG(exit_qualification);
6433         if (exit_qualification & TYPE_MOV_FROM_DR) {
6434                 unsigned long val;
6435
6436                 if (kvm_get_dr(vcpu, dr, &val))
6437                         return 1;
6438                 kvm_register_write(vcpu, reg, val);
6439         } else
6440                 if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
6441                         return 1;
6442
6443         return kvm_skip_emulated_instruction(vcpu);
6444 }
6445
6446 static u64 vmx_get_dr6(struct kvm_vcpu *vcpu)
6447 {
6448         return vcpu->arch.dr6;
6449 }
6450
6451 static void vmx_set_dr6(struct kvm_vcpu *vcpu, unsigned long val)
6452 {
6453 }
6454
6455 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
6456 {
6457         get_debugreg(vcpu->arch.db[0], 0);
6458         get_debugreg(vcpu->arch.db[1], 1);
6459         get_debugreg(vcpu->arch.db[2], 2);
6460         get_debugreg(vcpu->arch.db[3], 3);
6461         get_debugreg(vcpu->arch.dr6, 6);
6462         vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
6463
6464         vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
6465         vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL, CPU_BASED_MOV_DR_EXITING);
6466 }
6467
6468 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
6469 {
6470         vmcs_writel(GUEST_DR7, val);
6471 }
6472
6473 static int handle_cpuid(struct kvm_vcpu *vcpu)
6474 {
6475         return kvm_emulate_cpuid(vcpu);
6476 }
6477
6478 static int handle_rdmsr(struct kvm_vcpu *vcpu)
6479 {
6480         u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
6481         struct msr_data msr_info;
6482
6483         msr_info.index = ecx;
6484         msr_info.host_initiated = false;
6485         if (vmx_get_msr(vcpu, &msr_info)) {
6486                 trace_kvm_msr_read_ex(ecx);
6487                 kvm_inject_gp(vcpu, 0);
6488                 return 1;
6489         }
6490
6491         trace_kvm_msr_read(ecx, msr_info.data);
6492
6493         /* FIXME: handling of bits 32:63 of rax, rdx */
6494         vcpu->arch.regs[VCPU_REGS_RAX] = msr_info.data & -1u;
6495         vcpu->arch.regs[VCPU_REGS_RDX] = (msr_info.data >> 32) & -1u;
6496         return kvm_skip_emulated_instruction(vcpu);
6497 }
6498
6499 static int handle_wrmsr(struct kvm_vcpu *vcpu)
6500 {
6501         struct msr_data msr;
6502         u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
6503         u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
6504                 | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
6505
6506         msr.data = data;
6507         msr.index = ecx;
6508         msr.host_initiated = false;
6509         if (kvm_set_msr(vcpu, &msr) != 0) {
6510                 trace_kvm_msr_write_ex(ecx, data);
6511                 kvm_inject_gp(vcpu, 0);
6512                 return 1;
6513         }
6514
6515         trace_kvm_msr_write(ecx, data);
6516         return kvm_skip_emulated_instruction(vcpu);
6517 }
6518
6519 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
6520 {
6521         kvm_apic_update_ppr(vcpu);
6522         return 1;
6523 }
6524
6525 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
6526 {
6527         vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
6528                         CPU_BASED_VIRTUAL_INTR_PENDING);
6529
6530         kvm_make_request(KVM_REQ_EVENT, vcpu);
6531
6532         ++vcpu->stat.irq_window_exits;
6533         return 1;
6534 }
6535
6536 static int handle_halt(struct kvm_vcpu *vcpu)
6537 {
6538         return kvm_emulate_halt(vcpu);
6539 }
6540
6541 static int handle_vmcall(struct kvm_vcpu *vcpu)
6542 {
6543         return kvm_emulate_hypercall(vcpu);
6544 }
6545
6546 static int handle_invd(struct kvm_vcpu *vcpu)
6547 {
6548         return emulate_instruction(vcpu, 0) == EMULATE_DONE;
6549 }
6550
6551 static int handle_invlpg(struct kvm_vcpu *vcpu)
6552 {
6553         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6554
6555         kvm_mmu_invlpg(vcpu, exit_qualification);
6556         return kvm_skip_emulated_instruction(vcpu);
6557 }
6558
6559 static int handle_rdpmc(struct kvm_vcpu *vcpu)
6560 {
6561         int err;
6562
6563         err = kvm_rdpmc(vcpu);
6564         return kvm_complete_insn_gp(vcpu, err);
6565 }
6566
6567 static int handle_wbinvd(struct kvm_vcpu *vcpu)
6568 {
6569         return kvm_emulate_wbinvd(vcpu);
6570 }
6571
6572 static int handle_xsetbv(struct kvm_vcpu *vcpu)
6573 {
6574         u64 new_bv = kvm_read_edx_eax(vcpu);
6575         u32 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
6576
6577         if (kvm_set_xcr(vcpu, index, new_bv) == 0)
6578                 return kvm_skip_emulated_instruction(vcpu);
6579         return 1;
6580 }
6581
6582 static int handle_xsaves(struct kvm_vcpu *vcpu)
6583 {
6584         kvm_skip_emulated_instruction(vcpu);
6585         WARN(1, "this should never happen\n");
6586         return 1;
6587 }
6588
6589 static int handle_xrstors(struct kvm_vcpu *vcpu)
6590 {
6591         kvm_skip_emulated_instruction(vcpu);
6592         WARN(1, "this should never happen\n");
6593         return 1;
6594 }
6595
6596 static int handle_apic_access(struct kvm_vcpu *vcpu)
6597 {
6598         if (likely(fasteoi)) {
6599                 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6600                 int access_type, offset;
6601
6602                 access_type = exit_qualification & APIC_ACCESS_TYPE;
6603                 offset = exit_qualification & APIC_ACCESS_OFFSET;
6604                 /*
6605                  * Sane guest uses MOV to write EOI, with written value
6606                  * not cared. So make a short-circuit here by avoiding
6607                  * heavy instruction emulation.
6608                  */
6609                 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
6610                     (offset == APIC_EOI)) {
6611                         kvm_lapic_set_eoi(vcpu);
6612                         return kvm_skip_emulated_instruction(vcpu);
6613                 }
6614         }
6615         return emulate_instruction(vcpu, 0) == EMULATE_DONE;
6616 }
6617
6618 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
6619 {
6620         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6621         int vector = exit_qualification & 0xff;
6622
6623         /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
6624         kvm_apic_set_eoi_accelerated(vcpu, vector);
6625         return 1;
6626 }
6627
6628 static int handle_apic_write(struct kvm_vcpu *vcpu)
6629 {
6630         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6631         u32 offset = exit_qualification & 0xfff;
6632
6633         /* APIC-write VM exit is trap-like and thus no need to adjust IP */
6634         kvm_apic_write_nodecode(vcpu, offset);
6635         return 1;
6636 }
6637
6638 static int handle_task_switch(struct kvm_vcpu *vcpu)
6639 {
6640         struct vcpu_vmx *vmx = to_vmx(vcpu);
6641         unsigned long exit_qualification;
6642         bool has_error_code = false;
6643         u32 error_code = 0;
6644         u16 tss_selector;
6645         int reason, type, idt_v, idt_index;
6646
6647         idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
6648         idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
6649         type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
6650
6651         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6652
6653         reason = (u32)exit_qualification >> 30;
6654         if (reason == TASK_SWITCH_GATE && idt_v) {
6655                 switch (type) {
6656                 case INTR_TYPE_NMI_INTR:
6657                         vcpu->arch.nmi_injected = false;
6658                         vmx_set_nmi_mask(vcpu, true);
6659                         break;
6660                 case INTR_TYPE_EXT_INTR:
6661                 case INTR_TYPE_SOFT_INTR:
6662                         kvm_clear_interrupt_queue(vcpu);
6663                         break;
6664                 case INTR_TYPE_HARD_EXCEPTION:
6665                         if (vmx->idt_vectoring_info &
6666                             VECTORING_INFO_DELIVER_CODE_MASK) {
6667                                 has_error_code = true;
6668                                 error_code =
6669                                         vmcs_read32(IDT_VECTORING_ERROR_CODE);
6670                         }
6671                         /* fall through */
6672                 case INTR_TYPE_SOFT_EXCEPTION:
6673                         kvm_clear_exception_queue(vcpu);
6674                         break;
6675                 default:
6676                         break;
6677                 }
6678         }
6679         tss_selector = exit_qualification;
6680
6681         if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
6682                        type != INTR_TYPE_EXT_INTR &&
6683                        type != INTR_TYPE_NMI_INTR))
6684                 skip_emulated_instruction(vcpu);
6685
6686         if (kvm_task_switch(vcpu, tss_selector,
6687                             type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason,
6688                             has_error_code, error_code) == EMULATE_FAIL) {
6689                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6690                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6691                 vcpu->run->internal.ndata = 0;
6692                 return 0;
6693         }
6694
6695         /*
6696          * TODO: What about debug traps on tss switch?
6697          *       Are we supposed to inject them and update dr6?
6698          */
6699
6700         return 1;
6701 }
6702
6703 static int handle_ept_violation(struct kvm_vcpu *vcpu)
6704 {
6705         unsigned long exit_qualification;
6706         gpa_t gpa;
6707         u64 error_code;
6708
6709         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6710
6711         /*
6712          * EPT violation happened while executing iret from NMI,
6713          * "blocked by NMI" bit has to be set before next VM entry.
6714          * There are errata that may cause this bit to not be set:
6715          * AAK134, BY25.
6716          */
6717         if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
6718                         cpu_has_virtual_nmis() &&
6719                         (exit_qualification & INTR_INFO_UNBLOCK_NMI))
6720                 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
6721
6722         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6723         trace_kvm_page_fault(gpa, exit_qualification);
6724
6725         /* Is it a read fault? */
6726         error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
6727                      ? PFERR_USER_MASK : 0;
6728         /* Is it a write fault? */
6729         error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
6730                       ? PFERR_WRITE_MASK : 0;
6731         /* Is it a fetch fault? */
6732         error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
6733                       ? PFERR_FETCH_MASK : 0;
6734         /* ept page table entry is present? */
6735         error_code |= (exit_qualification &
6736                        (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
6737                         EPT_VIOLATION_EXECUTABLE))
6738                       ? PFERR_PRESENT_MASK : 0;
6739
6740         error_code |= (exit_qualification & 0x100) != 0 ?
6741                PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
6742
6743         vcpu->arch.exit_qualification = exit_qualification;
6744         return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
6745 }
6746
6747 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
6748 {
6749         int ret;
6750         gpa_t gpa;
6751
6752         /*
6753          * A nested guest cannot optimize MMIO vmexits, because we have an
6754          * nGPA here instead of the required GPA.
6755          */
6756         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6757         if (!is_guest_mode(vcpu) &&
6758             !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
6759                 trace_kvm_fast_mmio(gpa);
6760                 return kvm_skip_emulated_instruction(vcpu);
6761         }
6762
6763         ret = kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
6764         if (ret >= 0)
6765                 return ret;
6766
6767         /* It is the real ept misconfig */
6768         WARN_ON(1);
6769
6770         vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
6771         vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_MISCONFIG;
6772
6773         return 0;
6774 }
6775
6776 static int handle_nmi_window(struct kvm_vcpu *vcpu)
6777 {
6778         vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
6779                         CPU_BASED_VIRTUAL_NMI_PENDING);
6780         ++vcpu->stat.nmi_window_exits;
6781         kvm_make_request(KVM_REQ_EVENT, vcpu);
6782
6783         return 1;
6784 }
6785
6786 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
6787 {
6788         struct vcpu_vmx *vmx = to_vmx(vcpu);
6789         enum emulation_result err = EMULATE_DONE;
6790         int ret = 1;
6791         u32 cpu_exec_ctrl;
6792         bool intr_window_requested;
6793         unsigned count = 130;
6794
6795         cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
6796         intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
6797
6798         while (vmx->emulation_required && count-- != 0) {
6799                 if (intr_window_requested && vmx_interrupt_allowed(vcpu))
6800                         return handle_interrupt_window(&vmx->vcpu);
6801
6802                 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
6803                         return 1;
6804
6805                 err = emulate_instruction(vcpu, 0);
6806
6807                 if (err == EMULATE_USER_EXIT) {
6808                         ++vcpu->stat.mmio_exits;
6809                         ret = 0;
6810                         goto out;
6811                 }
6812
6813                 if (err != EMULATE_DONE) {
6814                         vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6815                         vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6816                         vcpu->run->internal.ndata = 0;
6817                         return 0;
6818                 }
6819
6820                 if (vcpu->arch.halt_request) {
6821                         vcpu->arch.halt_request = 0;
6822                         ret = kvm_vcpu_halt(vcpu);
6823                         goto out;
6824                 }
6825
6826                 if (signal_pending(current))
6827                         goto out;
6828                 if (need_resched())
6829                         schedule();
6830         }
6831
6832 out:
6833         return ret;
6834 }
6835
6836 static int __grow_ple_window(int val)
6837 {
6838         if (ple_window_grow < 1)
6839                 return ple_window;
6840
6841         val = min(val, ple_window_actual_max);
6842
6843         if (ple_window_grow < ple_window)
6844                 val *= ple_window_grow;
6845         else
6846                 val += ple_window_grow;
6847
6848         return val;
6849 }
6850
6851 static int __shrink_ple_window(int val, int modifier, int minimum)
6852 {
6853         if (modifier < 1)
6854                 return ple_window;
6855
6856         if (modifier < ple_window)
6857                 val /= modifier;
6858         else
6859                 val -= modifier;
6860
6861         return max(val, minimum);
6862 }
6863
6864 static void grow_ple_window(struct kvm_vcpu *vcpu)
6865 {
6866         struct vcpu_vmx *vmx = to_vmx(vcpu);
6867         int old = vmx->ple_window;
6868
6869         vmx->ple_window = __grow_ple_window(old);
6870
6871         if (vmx->ple_window != old)
6872                 vmx->ple_window_dirty = true;
6873
6874         trace_kvm_ple_window_grow(vcpu->vcpu_id, vmx->ple_window, old);
6875 }
6876
6877 static void shrink_ple_window(struct kvm_vcpu *vcpu)
6878 {
6879         struct vcpu_vmx *vmx = to_vmx(vcpu);
6880         int old = vmx->ple_window;
6881
6882         vmx->ple_window = __shrink_ple_window(old,
6883                                               ple_window_shrink, ple_window);
6884
6885         if (vmx->ple_window != old)
6886                 vmx->ple_window_dirty = true;
6887
6888         trace_kvm_ple_window_shrink(vcpu->vcpu_id, vmx->ple_window, old);
6889 }
6890
6891 /*
6892  * ple_window_actual_max is computed to be one grow_ple_window() below
6893  * ple_window_max. (See __grow_ple_window for the reason.)
6894  * This prevents overflows, because ple_window_max is int.
6895  * ple_window_max effectively rounded down to a multiple of ple_window_grow in
6896  * this process.
6897  * ple_window_max is also prevented from setting vmx->ple_window < ple_window.
6898  */
6899 static void update_ple_window_actual_max(void)
6900 {
6901         ple_window_actual_max =
6902                         __shrink_ple_window(max(ple_window_max, ple_window),
6903                                             ple_window_grow, INT_MIN);
6904 }
6905
6906 /*
6907  * Handler for POSTED_INTERRUPT_WAKEUP_VECTOR.
6908  */
6909 static void wakeup_handler(void)
6910 {
6911         struct kvm_vcpu *vcpu;
6912         int cpu = smp_processor_id();
6913
6914         spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
6915         list_for_each_entry(vcpu, &per_cpu(blocked_vcpu_on_cpu, cpu),
6916                         blocked_vcpu_list) {
6917                 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
6918
6919                 if (pi_test_on(pi_desc) == 1)
6920                         kvm_vcpu_kick(vcpu);
6921         }
6922         spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
6923 }
6924
6925 void vmx_enable_tdp(void)
6926 {
6927         kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
6928                 enable_ept_ad_bits ? VMX_EPT_ACCESS_BIT : 0ull,
6929                 enable_ept_ad_bits ? VMX_EPT_DIRTY_BIT : 0ull,
6930                 0ull, VMX_EPT_EXECUTABLE_MASK,
6931                 cpu_has_vmx_ept_execute_only() ? 0ull : VMX_EPT_READABLE_MASK,
6932                 VMX_EPT_RWX_MASK, 0ull);
6933
6934         ept_set_mmio_spte_mask();
6935         kvm_enable_tdp();
6936 }
6937
6938 static __init int hardware_setup(void)
6939 {
6940         int r = -ENOMEM, i;
6941
6942         rdmsrl_safe(MSR_EFER, &host_efer);
6943
6944         for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)
6945                 kvm_define_shared_msr(i, vmx_msr_index[i]);
6946
6947         for (i = 0; i < VMX_BITMAP_NR; i++) {
6948                 vmx_bitmap[i] = (unsigned long *)__get_free_page(GFP_KERNEL);
6949                 if (!vmx_bitmap[i])
6950                         goto out;
6951         }
6952
6953         vmx_io_bitmap_b = (unsigned long *)__get_free_page(GFP_KERNEL);
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                 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 (!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL))
9571                 rdmsrl(MSR_IA32_SPEC_CTRL, vmx->spec_ctrl);
9572
9573         if (vmx->spec_ctrl)
9574                 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                 ;
10131         else
10132                 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
10133                                 CPU_BASED_USE_MSR_BITMAPS);
10134 }
10135
10136 static void vmx_start_preemption_timer(struct kvm_vcpu *vcpu)
10137 {
10138         u64 preemption_timeout = get_vmcs12(vcpu)->vmx_preemption_timer_value;
10139         struct vcpu_vmx *vmx = to_vmx(vcpu);
10140
10141         if (vcpu->arch.virtual_tsc_khz == 0)
10142                 return;
10143
10144         /* Make sure short timeouts reliably trigger an immediate vmexit.
10145          * hrtimer_start does not guarantee this. */
10146         if (preemption_timeout <= 1) {
10147                 vmx_preemption_timer_fn(&vmx->nested.preemption_timer);
10148                 return;
10149         }
10150
10151         preemption_timeout <<= VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
10152         preemption_timeout *= 1000000;
10153         do_div(preemption_timeout, vcpu->arch.virtual_tsc_khz);
10154         hrtimer_start(&vmx->nested.preemption_timer,
10155                       ns_to_ktime(preemption_timeout), HRTIMER_MODE_REL);
10156 }
10157
10158 static int nested_vmx_check_io_bitmap_controls(struct kvm_vcpu *vcpu,
10159                                                struct vmcs12 *vmcs12)
10160 {
10161         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
10162                 return 0;
10163
10164         if (!page_address_valid(vcpu, vmcs12->io_bitmap_a) ||
10165             !page_address_valid(vcpu, vmcs12->io_bitmap_b))
10166                 return -EINVAL;
10167
10168         return 0;
10169 }
10170
10171 static int nested_vmx_check_msr_bitmap_controls(struct kvm_vcpu *vcpu,
10172                                                 struct vmcs12 *vmcs12)
10173 {
10174         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
10175                 return 0;
10176
10177         if (!page_address_valid(vcpu, vmcs12->msr_bitmap))
10178                 return -EINVAL;
10179
10180         return 0;
10181 }
10182
10183 static int nested_vmx_check_tpr_shadow_controls(struct kvm_vcpu *vcpu,
10184                                                 struct vmcs12 *vmcs12)
10185 {
10186         if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
10187                 return 0;
10188
10189         if (!page_address_valid(vcpu, vmcs12->virtual_apic_page_addr))
10190                 return -EINVAL;
10191
10192         return 0;
10193 }
10194
10195 /*
10196  * Merge L0's and L1's MSR bitmap, return false to indicate that
10197  * we do not use the hardware.
10198  */
10199 static inline bool nested_vmx_merge_msr_bitmap(struct kvm_vcpu *vcpu,
10200                                                struct vmcs12 *vmcs12)
10201 {
10202         int msr;
10203         struct page *page;
10204         unsigned long *msr_bitmap_l1;
10205         unsigned long *msr_bitmap_l0 = to_vmx(vcpu)->nested.vmcs02.msr_bitmap;
10206         /*
10207          * pred_cmd & spec_ctrl are trying to verify two things:
10208          *
10209          * 1. L0 gave a permission to L1 to actually passthrough the MSR. This
10210          *    ensures that we do not accidentally generate an L02 MSR bitmap
10211          *    from the L12 MSR bitmap that is too permissive.
10212          * 2. That L1 or L2s have actually used the MSR. This avoids
10213          *    unnecessarily merging of the bitmap if the MSR is unused. This
10214          *    works properly because we only update the L01 MSR bitmap lazily.
10215          *    So even if L0 should pass L1 these MSRs, the L01 bitmap is only
10216          *    updated to reflect this when L1 (or its L2s) actually write to
10217          *    the MSR.
10218          */
10219         bool pred_cmd = !msr_write_intercepted_l01(vcpu, MSR_IA32_PRED_CMD);
10220         bool spec_ctrl = !msr_write_intercepted_l01(vcpu, MSR_IA32_SPEC_CTRL);
10221
10222         if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
10223             !pred_cmd && !spec_ctrl)
10224                 return false;
10225
10226         page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->msr_bitmap);
10227         if (is_error_page(page))
10228                 return false;
10229         msr_bitmap_l1 = (unsigned long *)kmap(page);
10230
10231         memset(msr_bitmap_l0, 0xff, PAGE_SIZE);
10232
10233         if (nested_cpu_has_virt_x2apic_mode(vmcs12)) {
10234                 if (nested_cpu_has_apic_reg_virt(vmcs12))
10235                         for (msr = 0x800; msr <= 0x8ff; msr++)
10236                                 nested_vmx_disable_intercept_for_msr(
10237                                         msr_bitmap_l1, msr_bitmap_l0,
10238                                         msr, MSR_TYPE_R);
10239
10240                 nested_vmx_disable_intercept_for_msr(
10241                                 msr_bitmap_l1, msr_bitmap_l0,
10242                                 APIC_BASE_MSR + (APIC_TASKPRI >> 4),
10243                                 MSR_TYPE_R | MSR_TYPE_W);
10244
10245                 if (nested_cpu_has_vid(vmcs12)) {
10246                         nested_vmx_disable_intercept_for_msr(
10247                                 msr_bitmap_l1, msr_bitmap_l0,
10248                                 APIC_BASE_MSR + (APIC_EOI >> 4),
10249                                 MSR_TYPE_W);
10250                         nested_vmx_disable_intercept_for_msr(
10251                                 msr_bitmap_l1, msr_bitmap_l0,
10252                                 APIC_BASE_MSR + (APIC_SELF_IPI >> 4),
10253                                 MSR_TYPE_W);
10254                 }
10255         }
10256
10257         if (spec_ctrl)
10258                 nested_vmx_disable_intercept_for_msr(
10259                                         msr_bitmap_l1, msr_bitmap_l0,
10260                                         MSR_IA32_SPEC_CTRL,
10261                                         MSR_TYPE_R | MSR_TYPE_W);
10262
10263         if (pred_cmd)
10264                 nested_vmx_disable_intercept_for_msr(
10265                                         msr_bitmap_l1, msr_bitmap_l0,
10266                                         MSR_IA32_PRED_CMD,
10267                                         MSR_TYPE_W);
10268
10269         kunmap(page);
10270         kvm_release_page_clean(page);
10271
10272         return true;
10273 }
10274
10275 static int nested_vmx_check_apicv_controls(struct kvm_vcpu *vcpu,
10276                                            struct vmcs12 *vmcs12)
10277 {
10278         if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
10279             !nested_cpu_has_apic_reg_virt(vmcs12) &&
10280             !nested_cpu_has_vid(vmcs12) &&
10281             !nested_cpu_has_posted_intr(vmcs12))
10282                 return 0;
10283
10284         /*
10285          * If virtualize x2apic mode is enabled,
10286          * virtualize apic access must be disabled.
10287          */
10288         if (nested_cpu_has_virt_x2apic_mode(vmcs12) &&
10289             nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
10290                 return -EINVAL;
10291
10292         /*
10293          * If virtual interrupt delivery is enabled,
10294          * we must exit on external interrupts.
10295          */
10296         if (nested_cpu_has_vid(vmcs12) &&
10297            !nested_exit_on_intr(vcpu))
10298                 return -EINVAL;
10299
10300         /*
10301          * bits 15:8 should be zero in posted_intr_nv,
10302          * the descriptor address has been already checked
10303          * in nested_get_vmcs12_pages.
10304          */
10305         if (nested_cpu_has_posted_intr(vmcs12) &&
10306            (!nested_cpu_has_vid(vmcs12) ||
10307             !nested_exit_intr_ack_set(vcpu) ||
10308             vmcs12->posted_intr_nv & 0xff00))
10309                 return -EINVAL;
10310
10311         /* tpr shadow is needed by all apicv features. */
10312         if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
10313                 return -EINVAL;
10314
10315         return 0;
10316 }
10317
10318 static int nested_vmx_check_msr_switch(struct kvm_vcpu *vcpu,
10319                                        unsigned long count_field,
10320                                        unsigned long addr_field)
10321 {
10322         int maxphyaddr;
10323         u64 count, addr;
10324
10325         if (vmcs12_read_any(vcpu, count_field, &count) ||
10326             vmcs12_read_any(vcpu, addr_field, &addr)) {
10327                 WARN_ON(1);
10328                 return -EINVAL;
10329         }
10330         if (count == 0)
10331                 return 0;
10332         maxphyaddr = cpuid_maxphyaddr(vcpu);
10333         if (!IS_ALIGNED(addr, 16) || addr >> maxphyaddr ||
10334             (addr + count * sizeof(struct vmx_msr_entry) - 1) >> maxphyaddr) {
10335                 pr_debug_ratelimited(
10336                         "nVMX: invalid MSR switch (0x%lx, %d, %llu, 0x%08llx)",
10337                         addr_field, maxphyaddr, count, addr);
10338                 return -EINVAL;
10339         }
10340         return 0;
10341 }
10342
10343 static int nested_vmx_check_msr_switch_controls(struct kvm_vcpu *vcpu,
10344                                                 struct vmcs12 *vmcs12)
10345 {
10346         if (vmcs12->vm_exit_msr_load_count == 0 &&
10347             vmcs12->vm_exit_msr_store_count == 0 &&
10348             vmcs12->vm_entry_msr_load_count == 0)
10349                 return 0; /* Fast path */
10350         if (nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_LOAD_COUNT,
10351                                         VM_EXIT_MSR_LOAD_ADDR) ||
10352             nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_STORE_COUNT,
10353                                         VM_EXIT_MSR_STORE_ADDR) ||
10354             nested_vmx_check_msr_switch(vcpu, VM_ENTRY_MSR_LOAD_COUNT,
10355                                         VM_ENTRY_MSR_LOAD_ADDR))
10356                 return -EINVAL;
10357         return 0;
10358 }
10359
10360 static int nested_vmx_check_pml_controls(struct kvm_vcpu *vcpu,
10361                                          struct vmcs12 *vmcs12)
10362 {
10363         u64 address = vmcs12->pml_address;
10364         int maxphyaddr = cpuid_maxphyaddr(vcpu);
10365
10366         if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_PML)) {
10367                 if (!nested_cpu_has_ept(vmcs12) ||
10368                     !IS_ALIGNED(address, 4096)  ||
10369                     address >> maxphyaddr)
10370                         return -EINVAL;
10371         }
10372
10373         return 0;
10374 }
10375
10376 static int nested_vmx_msr_check_common(struct kvm_vcpu *vcpu,
10377                                        struct vmx_msr_entry *e)
10378 {
10379         /* x2APIC MSR accesses are not allowed */
10380         if (vcpu->arch.apic_base & X2APIC_ENABLE && e->index >> 8 == 0x8)
10381                 return -EINVAL;
10382         if (e->index == MSR_IA32_UCODE_WRITE || /* SDM Table 35-2 */
10383             e->index == MSR_IA32_UCODE_REV)
10384                 return -EINVAL;
10385         if (e->reserved != 0)
10386                 return -EINVAL;
10387         return 0;
10388 }
10389
10390 static int nested_vmx_load_msr_check(struct kvm_vcpu *vcpu,
10391                                      struct vmx_msr_entry *e)
10392 {
10393         if (e->index == MSR_FS_BASE ||
10394             e->index == MSR_GS_BASE ||
10395             e->index == MSR_IA32_SMM_MONITOR_CTL || /* SMM is not supported */
10396             nested_vmx_msr_check_common(vcpu, e))
10397                 return -EINVAL;
10398         return 0;
10399 }
10400
10401 static int nested_vmx_store_msr_check(struct kvm_vcpu *vcpu,
10402                                       struct vmx_msr_entry *e)
10403 {
10404         if (e->index == MSR_IA32_SMBASE || /* SMM is not supported */
10405             nested_vmx_msr_check_common(vcpu, e))
10406                 return -EINVAL;
10407         return 0;
10408 }
10409
10410 /*
10411  * Load guest's/host's msr at nested entry/exit.
10412  * return 0 for success, entry index for failure.
10413  */
10414 static u32 nested_vmx_load_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
10415 {
10416         u32 i;
10417         struct vmx_msr_entry e;
10418         struct msr_data msr;
10419
10420         msr.host_initiated = false;
10421         for (i = 0; i < count; i++) {
10422                 if (kvm_vcpu_read_guest(vcpu, gpa + i * sizeof(e),
10423                                         &e, sizeof(e))) {
10424                         pr_debug_ratelimited(
10425                                 "%s cannot read MSR entry (%u, 0x%08llx)\n",
10426                                 __func__, i, gpa + i * sizeof(e));
10427                         goto fail;
10428                 }
10429                 if (nested_vmx_load_msr_check(vcpu, &e)) {
10430                         pr_debug_ratelimited(
10431                                 "%s check failed (%u, 0x%x, 0x%x)\n",
10432                                 __func__, i, e.index, e.reserved);
10433                         goto fail;
10434                 }
10435                 msr.index = e.index;
10436                 msr.data = e.value;
10437                 if (kvm_set_msr(vcpu, &msr)) {
10438                         pr_debug_ratelimited(
10439                                 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
10440                                 __func__, i, e.index, e.value);
10441                         goto fail;
10442                 }
10443         }
10444         return 0;
10445 fail:
10446         return i + 1;
10447 }
10448
10449 static int nested_vmx_store_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
10450 {
10451         u32 i;
10452         struct vmx_msr_entry e;
10453
10454         for (i = 0; i < count; i++) {
10455                 struct msr_data msr_info;
10456                 if (kvm_vcpu_read_guest(vcpu,
10457                                         gpa + i * sizeof(e),
10458                                         &e, 2 * sizeof(u32))) {
10459                         pr_debug_ratelimited(
10460                                 "%s cannot read MSR entry (%u, 0x%08llx)\n",
10461                                 __func__, i, gpa + i * sizeof(e));
10462                         return -EINVAL;
10463                 }
10464                 if (nested_vmx_store_msr_check(vcpu, &e)) {
10465                         pr_debug_ratelimited(
10466                                 "%s check failed (%u, 0x%x, 0x%x)\n",
10467                                 __func__, i, e.index, e.reserved);
10468                         return -EINVAL;
10469                 }
10470                 msr_info.host_initiated = false;
10471                 msr_info.index = e.index;
10472                 if (kvm_get_msr(vcpu, &msr_info)) {
10473                         pr_debug_ratelimited(
10474                                 "%s cannot read MSR (%u, 0x%x)\n",
10475                                 __func__, i, e.index);
10476                         return -EINVAL;
10477                 }
10478                 if (kvm_vcpu_write_guest(vcpu,
10479                                          gpa + i * sizeof(e) +
10480                                              offsetof(struct vmx_msr_entry, value),
10481                                          &msr_info.data, sizeof(msr_info.data))) {
10482                         pr_debug_ratelimited(
10483                                 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
10484                                 __func__, i, e.index, msr_info.data);
10485                         return -EINVAL;
10486                 }
10487         }
10488         return 0;
10489 }
10490
10491 static bool nested_cr3_valid(struct kvm_vcpu *vcpu, unsigned long val)
10492 {
10493         unsigned long invalid_mask;
10494
10495         invalid_mask = (~0ULL) << cpuid_maxphyaddr(vcpu);
10496         return (val & invalid_mask) == 0;
10497 }
10498
10499 /*
10500  * Load guest's/host's cr3 at nested entry/exit. nested_ept is true if we are
10501  * emulating VM entry into a guest with EPT enabled.
10502  * Returns 0 on success, 1 on failure. Invalid state exit qualification code
10503  * is assigned to entry_failure_code on failure.
10504  */
10505 static int nested_vmx_load_cr3(struct kvm_vcpu *vcpu, unsigned long cr3, bool nested_ept,
10506                                u32 *entry_failure_code)
10507 {
10508         if (cr3 != kvm_read_cr3(vcpu) || (!nested_ept && pdptrs_changed(vcpu))) {
10509                 if (!nested_cr3_valid(vcpu, cr3)) {
10510                         *entry_failure_code = ENTRY_FAIL_DEFAULT;
10511                         return 1;
10512                 }
10513
10514                 /*
10515                  * If PAE paging and EPT are both on, CR3 is not used by the CPU and
10516                  * must not be dereferenced.
10517                  */
10518                 if (!is_long_mode(vcpu) && is_pae(vcpu) && is_paging(vcpu) &&
10519                     !nested_ept) {
10520                         if (!load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3)) {
10521                                 *entry_failure_code = ENTRY_FAIL_PDPTE;
10522                                 return 1;
10523                         }
10524                 }
10525
10526                 vcpu->arch.cr3 = cr3;
10527                 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
10528         }
10529
10530         kvm_mmu_reset_context(vcpu);
10531         return 0;
10532 }
10533
10534 /*
10535  * prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
10536  * L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
10537  * with L0's requirements for its guest (a.k.a. vmcs01), so we can run the L2
10538  * guest in a way that will both be appropriate to L1's requests, and our
10539  * needs. In addition to modifying the active vmcs (which is vmcs02), this
10540  * function also has additional necessary side-effects, like setting various
10541  * vcpu->arch fields.
10542  * Returns 0 on success, 1 on failure. Invalid state exit qualification code
10543  * is assigned to entry_failure_code on failure.
10544  */
10545 static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
10546                           bool from_vmentry, u32 *entry_failure_code)
10547 {
10548         struct vcpu_vmx *vmx = to_vmx(vcpu);
10549         u32 exec_control, vmcs12_exec_ctrl;
10550
10551         vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
10552         vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
10553         vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
10554         vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
10555         vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
10556         vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
10557         vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
10558         vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
10559         vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
10560         vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
10561         vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
10562         vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
10563         vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
10564         vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
10565         vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
10566         vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
10567         vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
10568         vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
10569         vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
10570         vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
10571         vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
10572         vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
10573         vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
10574         vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
10575         vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
10576         vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
10577         vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
10578         vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
10579         vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
10580         vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
10581         vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
10582         vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
10583         vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
10584         vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
10585         vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
10586         vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
10587
10588         if (from_vmentry &&
10589             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS)) {
10590                 kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
10591                 vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
10592         } else {
10593                 kvm_set_dr(vcpu, 7, vcpu->arch.dr7);
10594                 vmcs_write64(GUEST_IA32_DEBUGCTL, vmx->nested.vmcs01_debugctl);
10595         }
10596         if (from_vmentry) {
10597                 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
10598                              vmcs12->vm_entry_intr_info_field);
10599                 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
10600                              vmcs12->vm_entry_exception_error_code);
10601                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
10602                              vmcs12->vm_entry_instruction_len);
10603                 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
10604                              vmcs12->guest_interruptibility_info);
10605                 vmx->loaded_vmcs->nmi_known_unmasked =
10606                         !(vmcs12->guest_interruptibility_info & GUEST_INTR_STATE_NMI);
10607         } else {
10608                 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
10609         }
10610         vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
10611         vmx_set_rflags(vcpu, vmcs12->guest_rflags);
10612         vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
10613                 vmcs12->guest_pending_dbg_exceptions);
10614         vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
10615         vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
10616
10617         if (nested_cpu_has_xsaves(vmcs12))
10618                 vmcs_write64(XSS_EXIT_BITMAP, vmcs12->xss_exit_bitmap);
10619         vmcs_write64(VMCS_LINK_POINTER, -1ull);
10620
10621         exec_control = vmcs12->pin_based_vm_exec_control;
10622
10623         /* Preemption timer setting is only taken from vmcs01.  */
10624         exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
10625         exec_control |= vmcs_config.pin_based_exec_ctrl;
10626         if (vmx->hv_deadline_tsc == -1)
10627                 exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
10628
10629         /* Posted interrupts setting is only taken from vmcs12.  */
10630         if (nested_cpu_has_posted_intr(vmcs12)) {
10631                 vmx->nested.posted_intr_nv = vmcs12->posted_intr_nv;
10632                 vmx->nested.pi_pending = false;
10633                 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_NESTED_VECTOR);
10634         } else {
10635                 exec_control &= ~PIN_BASED_POSTED_INTR;
10636         }
10637
10638         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, exec_control);
10639
10640         vmx->nested.preemption_timer_expired = false;
10641         if (nested_cpu_has_preemption_timer(vmcs12))
10642                 vmx_start_preemption_timer(vcpu);
10643
10644         /*
10645          * Whether page-faults are trapped is determined by a combination of
10646          * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.
10647          * If enable_ept, L0 doesn't care about page faults and we should
10648          * set all of these to L1's desires. However, if !enable_ept, L0 does
10649          * care about (at least some) page faults, and because it is not easy
10650          * (if at all possible?) to merge L0 and L1's desires, we simply ask
10651          * to exit on each and every L2 page fault. This is done by setting
10652          * MASK=MATCH=0 and (see below) EB.PF=1.
10653          * Note that below we don't need special code to set EB.PF beyond the
10654          * "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
10655          * vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
10656          * !enable_ept, EB.PF is 1, so the "or" will always be 1.
10657          */
10658         vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK,
10659                 enable_ept ? vmcs12->page_fault_error_code_mask : 0);
10660         vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
10661                 enable_ept ? vmcs12->page_fault_error_code_match : 0);
10662
10663         if (cpu_has_secondary_exec_ctrls()) {
10664                 exec_control = vmx->secondary_exec_control;
10665
10666                 /* Take the following fields only from vmcs12 */
10667                 exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
10668                                   SECONDARY_EXEC_ENABLE_INVPCID |
10669                                   SECONDARY_EXEC_RDTSCP |
10670                                   SECONDARY_EXEC_XSAVES |
10671                                   SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
10672                                   SECONDARY_EXEC_APIC_REGISTER_VIRT |
10673                                   SECONDARY_EXEC_ENABLE_VMFUNC);
10674                 if (nested_cpu_has(vmcs12,
10675                                    CPU_BASED_ACTIVATE_SECONDARY_CONTROLS)) {
10676                         vmcs12_exec_ctrl = vmcs12->secondary_vm_exec_control &
10677                                 ~SECONDARY_EXEC_ENABLE_PML;
10678                         exec_control |= vmcs12_exec_ctrl;
10679                 }
10680
10681                 /* All VMFUNCs are currently emulated through L0 vmexits.  */
10682                 if (exec_control & SECONDARY_EXEC_ENABLE_VMFUNC)
10683                         vmcs_write64(VM_FUNCTION_CONTROL, 0);
10684
10685                 if (exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
10686                         vmcs_write64(EOI_EXIT_BITMAP0,
10687                                 vmcs12->eoi_exit_bitmap0);
10688                         vmcs_write64(EOI_EXIT_BITMAP1,
10689                                 vmcs12->eoi_exit_bitmap1);
10690                         vmcs_write64(EOI_EXIT_BITMAP2,
10691                                 vmcs12->eoi_exit_bitmap2);
10692                         vmcs_write64(EOI_EXIT_BITMAP3,
10693                                 vmcs12->eoi_exit_bitmap3);
10694                         vmcs_write16(GUEST_INTR_STATUS,
10695                                 vmcs12->guest_intr_status);
10696                 }
10697
10698                 /*
10699                  * Write an illegal value to APIC_ACCESS_ADDR. Later,
10700                  * nested_get_vmcs12_pages will either fix it up or
10701                  * remove the VM execution control.
10702                  */
10703                 if (exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
10704                         vmcs_write64(APIC_ACCESS_ADDR, -1ull);
10705
10706                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
10707         }
10708
10709
10710         /*
10711          * Set host-state according to L0's settings (vmcs12 is irrelevant here)
10712          * Some constant fields are set here by vmx_set_constant_host_state().
10713          * Other fields are different per CPU, and will be set later when
10714          * vmx_vcpu_load() is called, and when vmx_save_host_state() is called.
10715          */
10716         vmx_set_constant_host_state(vmx);
10717
10718         /*
10719          * Set the MSR load/store lists to match L0's settings.
10720          */
10721         vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
10722         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
10723         vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host));
10724         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
10725         vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest));
10726
10727         /*
10728          * HOST_RSP is normally set correctly in vmx_vcpu_run() just before
10729          * entry, but only if the current (host) sp changed from the value
10730          * we wrote last (vmx->host_rsp). This cache is no longer relevant
10731          * if we switch vmcs, and rather than hold a separate cache per vmcs,
10732          * here we just force the write to happen on entry.
10733          */
10734         vmx->host_rsp = 0;
10735
10736         exec_control = vmx_exec_control(vmx); /* L0's desires */
10737         exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
10738         exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
10739         exec_control &= ~CPU_BASED_TPR_SHADOW;
10740         exec_control |= vmcs12->cpu_based_vm_exec_control;
10741
10742         /*
10743          * Write an illegal value to VIRTUAL_APIC_PAGE_ADDR. Later, if
10744          * nested_get_vmcs12_pages can't fix it up, the illegal value
10745          * will result in a VM entry failure.
10746          */
10747         if (exec_control & CPU_BASED_TPR_SHADOW) {
10748                 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, -1ull);
10749                 vmcs_write32(TPR_THRESHOLD, vmcs12->tpr_threshold);
10750         } else {
10751 #ifdef CONFIG_X86_64
10752                 exec_control |= CPU_BASED_CR8_LOAD_EXITING |
10753                                 CPU_BASED_CR8_STORE_EXITING;
10754 #endif
10755         }
10756
10757         /*
10758          * Merging of IO bitmap not currently supported.
10759          * Rather, exit every time.
10760          */
10761         exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
10762         exec_control |= CPU_BASED_UNCOND_IO_EXITING;
10763
10764         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
10765
10766         /* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
10767          * bitwise-or of what L1 wants to trap for L2, and what we want to
10768          * trap. Note that CR0.TS also needs updating - we do this later.
10769          */
10770         update_exception_bitmap(vcpu);
10771         vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
10772         vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
10773
10774         /* L2->L1 exit controls are emulated - the hardware exit is to L0 so
10775          * we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER
10776          * bits are further modified by vmx_set_efer() below.
10777          */
10778         vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);
10779
10780         /* vmcs12's VM_ENTRY_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE are
10781          * emulated by vmx_set_efer(), below.
10782          */
10783         vm_entry_controls_init(vmx, 
10784                 (vmcs12->vm_entry_controls & ~VM_ENTRY_LOAD_IA32_EFER &
10785                         ~VM_ENTRY_IA32E_MODE) |
10786                 (vmcs_config.vmentry_ctrl & ~VM_ENTRY_IA32E_MODE));
10787
10788         if (from_vmentry &&
10789             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT)) {
10790                 vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
10791                 vcpu->arch.pat = vmcs12->guest_ia32_pat;
10792         } else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
10793                 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
10794         }
10795
10796         set_cr4_guest_host_mask(vmx);
10797
10798         if (from_vmentry &&
10799             vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS)
10800                 vmcs_write64(GUEST_BNDCFGS, vmcs12->guest_bndcfgs);
10801
10802         if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
10803                 vmcs_write64(TSC_OFFSET,
10804                         vcpu->arch.tsc_offset + vmcs12->tsc_offset);
10805         else
10806                 vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
10807         if (kvm_has_tsc_control)
10808                 decache_tsc_multiplier(vmx);
10809
10810         if (cpu_has_vmx_msr_bitmap())
10811                 vmcs_write64(MSR_BITMAP, __pa(vmx->nested.vmcs02.msr_bitmap));
10812
10813         if (enable_vpid) {
10814                 /*
10815                  * There is no direct mapping between vpid02 and vpid12, the
10816                  * vpid02 is per-vCPU for L0 and reused while the value of
10817                  * vpid12 is changed w/ one invvpid during nested vmentry.
10818                  * The vpid12 is allocated by L1 for L2, so it will not
10819                  * influence global bitmap(for vpid01 and vpid02 allocation)
10820                  * even if spawn a lot of nested vCPUs.
10821                  */
10822                 if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02) {
10823                         vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->nested.vpid02);
10824                         if (vmcs12->virtual_processor_id != vmx->nested.last_vpid) {
10825                                 vmx->nested.last_vpid = vmcs12->virtual_processor_id;
10826                                 __vmx_flush_tlb(vcpu, to_vmx(vcpu)->nested.vpid02);
10827                         }
10828                 } else {
10829                         vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
10830                         vmx_flush_tlb(vcpu);
10831                 }
10832
10833         }
10834
10835         if (enable_pml) {
10836                 /*
10837                  * Conceptually we want to copy the PML address and index from
10838                  * vmcs01 here, and then back to vmcs01 on nested vmexit. But,
10839                  * since we always flush the log on each vmexit, this happens
10840                  * to be equivalent to simply resetting the fields in vmcs02.
10841                  */
10842                 ASSERT(vmx->pml_pg);
10843                 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
10844                 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
10845         }
10846
10847         if (nested_cpu_has_ept(vmcs12)) {
10848                 if (nested_ept_init_mmu_context(vcpu)) {
10849                         *entry_failure_code = ENTRY_FAIL_DEFAULT;
10850                         return 1;
10851                 }
10852         } else if (nested_cpu_has2(vmcs12,
10853                                    SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
10854                 vmx_flush_tlb_ept_only(vcpu);
10855         }
10856
10857         /*
10858          * This sets GUEST_CR0 to vmcs12->guest_cr0, possibly modifying those
10859          * bits which we consider mandatory enabled.
10860          * The CR0_READ_SHADOW is what L2 should have expected to read given
10861          * the specifications by L1; It's not enough to take
10862          * vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we
10863          * have more bits than L1 expected.
10864          */
10865         vmx_set_cr0(vcpu, vmcs12->guest_cr0);
10866         vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
10867
10868         vmx_set_cr4(vcpu, vmcs12->guest_cr4);
10869         vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
10870
10871         if (from_vmentry &&
10872             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER))
10873                 vcpu->arch.efer = vmcs12->guest_ia32_efer;
10874         else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
10875                 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
10876         else
10877                 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
10878         /* Note: modifies VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
10879         vmx_set_efer(vcpu, vcpu->arch.efer);
10880
10881         /* Shadow page tables on either EPT or shadow page tables. */
10882         if (nested_vmx_load_cr3(vcpu, vmcs12->guest_cr3, nested_cpu_has_ept(vmcs12),
10883                                 entry_failure_code))
10884                 return 1;
10885
10886         if (!enable_ept)
10887                 vcpu->arch.walk_mmu->inject_page_fault = vmx_inject_page_fault_nested;
10888
10889         /*
10890          * L1 may access the L2's PDPTR, so save them to construct vmcs12
10891          */
10892         if (enable_ept) {
10893                 vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
10894                 vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
10895                 vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
10896                 vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
10897         }
10898
10899         kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->guest_rsp);
10900         kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->guest_rip);
10901         return 0;
10902 }
10903
10904 static int check_vmentry_prereqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
10905 {
10906         struct vcpu_vmx *vmx = to_vmx(vcpu);
10907
10908         if (vmcs12->guest_activity_state != GUEST_ACTIVITY_ACTIVE &&
10909             vmcs12->guest_activity_state != GUEST_ACTIVITY_HLT)
10910                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10911
10912         if (nested_vmx_check_io_bitmap_controls(vcpu, vmcs12))
10913                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10914
10915         if (nested_vmx_check_msr_bitmap_controls(vcpu, vmcs12))
10916                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10917
10918         if (nested_vmx_check_tpr_shadow_controls(vcpu, vmcs12))
10919                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10920
10921         if (nested_vmx_check_apicv_controls(vcpu, vmcs12))
10922                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10923
10924         if (nested_vmx_check_msr_switch_controls(vcpu, vmcs12))
10925                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10926
10927         if (nested_vmx_check_pml_controls(vcpu, vmcs12))
10928                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10929
10930         if (!vmx_control_verify(vmcs12->cpu_based_vm_exec_control,
10931                                 vmx->nested.nested_vmx_procbased_ctls_low,
10932                                 vmx->nested.nested_vmx_procbased_ctls_high) ||
10933             (nested_cpu_has(vmcs12, CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
10934              !vmx_control_verify(vmcs12->secondary_vm_exec_control,
10935                                  vmx->nested.nested_vmx_secondary_ctls_low,
10936                                  vmx->nested.nested_vmx_secondary_ctls_high)) ||
10937             !vmx_control_verify(vmcs12->pin_based_vm_exec_control,
10938                                 vmx->nested.nested_vmx_pinbased_ctls_low,
10939                                 vmx->nested.nested_vmx_pinbased_ctls_high) ||
10940             !vmx_control_verify(vmcs12->vm_exit_controls,
10941                                 vmx->nested.nested_vmx_exit_ctls_low,
10942                                 vmx->nested.nested_vmx_exit_ctls_high) ||
10943             !vmx_control_verify(vmcs12->vm_entry_controls,
10944                                 vmx->nested.nested_vmx_entry_ctls_low,
10945                                 vmx->nested.nested_vmx_entry_ctls_high))
10946                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10947
10948         if (nested_cpu_has_vmfunc(vmcs12)) {
10949                 if (vmcs12->vm_function_control &
10950                     ~vmx->nested.nested_vmx_vmfunc_controls)
10951                         return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10952
10953                 if (nested_cpu_has_eptp_switching(vmcs12)) {
10954                         if (!nested_cpu_has_ept(vmcs12) ||
10955                             !page_address_valid(vcpu, vmcs12->eptp_list_address))
10956                                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10957                 }
10958         }
10959
10960         if (vmcs12->cr3_target_count > nested_cpu_vmx_misc_cr3_count(vcpu))
10961                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10962
10963         if (!nested_host_cr0_valid(vcpu, vmcs12->host_cr0) ||
10964             !nested_host_cr4_valid(vcpu, vmcs12->host_cr4) ||
10965             !nested_cr3_valid(vcpu, vmcs12->host_cr3))
10966                 return VMXERR_ENTRY_INVALID_HOST_STATE_FIELD;
10967
10968         return 0;
10969 }
10970
10971 static int check_vmentry_postreqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
10972                                   u32 *exit_qual)
10973 {
10974         bool ia32e;
10975
10976         *exit_qual = ENTRY_FAIL_DEFAULT;
10977
10978         if (!nested_guest_cr0_valid(vcpu, vmcs12->guest_cr0) ||
10979             !nested_guest_cr4_valid(vcpu, vmcs12->guest_cr4))
10980                 return 1;
10981
10982         if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_SHADOW_VMCS) &&
10983             vmcs12->vmcs_link_pointer != -1ull) {
10984                 *exit_qual = ENTRY_FAIL_VMCS_LINK_PTR;
10985                 return 1;
10986         }
10987
10988         /*
10989          * If the load IA32_EFER VM-entry control is 1, the following checks
10990          * are performed on the field for the IA32_EFER MSR:
10991          * - Bits reserved in the IA32_EFER MSR must be 0.
10992          * - Bit 10 (corresponding to IA32_EFER.LMA) must equal the value of
10993          *   the IA-32e mode guest VM-exit control. It must also be identical
10994          *   to bit 8 (LME) if bit 31 in the CR0 field (corresponding to
10995          *   CR0.PG) is 1.
10996          */
10997         if (to_vmx(vcpu)->nested.nested_run_pending &&
10998             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)) {
10999                 ia32e = (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) != 0;
11000                 if (!kvm_valid_efer(vcpu, vmcs12->guest_ia32_efer) ||
11001                     ia32e != !!(vmcs12->guest_ia32_efer & EFER_LMA) ||
11002                     ((vmcs12->guest_cr0 & X86_CR0_PG) &&
11003                      ia32e != !!(vmcs12->guest_ia32_efer & EFER_LME)))
11004                         return 1;
11005         }
11006
11007         /*
11008          * If the load IA32_EFER VM-exit control is 1, bits reserved in the
11009          * IA32_EFER MSR must be 0 in the field for that register. In addition,
11010          * the values of the LMA and LME bits in the field must each be that of
11011          * the host address-space size VM-exit control.
11012          */
11013         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) {
11014                 ia32e = (vmcs12->vm_exit_controls &
11015                          VM_EXIT_HOST_ADDR_SPACE_SIZE) != 0;
11016                 if (!kvm_valid_efer(vcpu, vmcs12->host_ia32_efer) ||
11017                     ia32e != !!(vmcs12->host_ia32_efer & EFER_LMA) ||
11018                     ia32e != !!(vmcs12->host_ia32_efer & EFER_LME))
11019                         return 1;
11020         }
11021
11022         return 0;
11023 }
11024
11025 static int enter_vmx_non_root_mode(struct kvm_vcpu *vcpu, bool from_vmentry)
11026 {
11027         struct vcpu_vmx *vmx = to_vmx(vcpu);
11028         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11029         u32 msr_entry_idx;
11030         u32 exit_qual;
11031
11032         enter_guest_mode(vcpu);
11033
11034         if (!(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS))
11035                 vmx->nested.vmcs01_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
11036
11037         vmx_switch_vmcs(vcpu, &vmx->nested.vmcs02);
11038         vmx_segment_cache_clear(vmx);
11039
11040         if (prepare_vmcs02(vcpu, vmcs12, from_vmentry, &exit_qual)) {
11041                 leave_guest_mode(vcpu);
11042                 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
11043                 nested_vmx_entry_failure(vcpu, vmcs12,
11044                                          EXIT_REASON_INVALID_STATE, exit_qual);
11045                 return 1;
11046         }
11047
11048         nested_get_vmcs12_pages(vcpu, vmcs12);
11049
11050         msr_entry_idx = nested_vmx_load_msr(vcpu,
11051                                             vmcs12->vm_entry_msr_load_addr,
11052                                             vmcs12->vm_entry_msr_load_count);
11053         if (msr_entry_idx) {
11054                 leave_guest_mode(vcpu);
11055                 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
11056                 nested_vmx_entry_failure(vcpu, vmcs12,
11057                                 EXIT_REASON_MSR_LOAD_FAIL, msr_entry_idx);
11058                 return 1;
11059         }
11060
11061         /*
11062          * Note no nested_vmx_succeed or nested_vmx_fail here. At this point
11063          * we are no longer running L1, and VMLAUNCH/VMRESUME has not yet
11064          * returned as far as L1 is concerned. It will only return (and set
11065          * the success flag) when L2 exits (see nested_vmx_vmexit()).
11066          */
11067         return 0;
11068 }
11069
11070 /*
11071  * nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1
11072  * for running an L2 nested guest.
11073  */
11074 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
11075 {
11076         struct vmcs12 *vmcs12;
11077         struct vcpu_vmx *vmx = to_vmx(vcpu);
11078         u32 interrupt_shadow = vmx_get_interrupt_shadow(vcpu);
11079         u32 exit_qual;
11080         int ret;
11081
11082         if (!nested_vmx_check_permission(vcpu))
11083                 return 1;
11084
11085         if (!nested_vmx_check_vmcs12(vcpu))
11086                 goto out;
11087
11088         vmcs12 = get_vmcs12(vcpu);
11089
11090         if (enable_shadow_vmcs)
11091                 copy_shadow_to_vmcs12(vmx);
11092
11093         /*
11094          * The nested entry process starts with enforcing various prerequisites
11095          * on vmcs12 as required by the Intel SDM, and act appropriately when
11096          * they fail: As the SDM explains, some conditions should cause the
11097          * instruction to fail, while others will cause the instruction to seem
11098          * to succeed, but return an EXIT_REASON_INVALID_STATE.
11099          * To speed up the normal (success) code path, we should avoid checking
11100          * for misconfigurations which will anyway be caught by the processor
11101          * when using the merged vmcs02.
11102          */
11103         if (interrupt_shadow & KVM_X86_SHADOW_INT_MOV_SS) {
11104                 nested_vmx_failValid(vcpu,
11105                                      VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS);
11106                 goto out;
11107         }
11108
11109         if (vmcs12->launch_state == launch) {
11110                 nested_vmx_failValid(vcpu,
11111                         launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
11112                                : VMXERR_VMRESUME_NONLAUNCHED_VMCS);
11113                 goto out;
11114         }
11115
11116         ret = check_vmentry_prereqs(vcpu, vmcs12);
11117         if (ret) {
11118                 nested_vmx_failValid(vcpu, ret);
11119                 goto out;
11120         }
11121
11122         /*
11123          * After this point, the trap flag no longer triggers a singlestep trap
11124          * on the vm entry instructions; don't call kvm_skip_emulated_instruction.
11125          * This is not 100% correct; for performance reasons, we delegate most
11126          * of the checks on host state to the processor.  If those fail,
11127          * the singlestep trap is missed.
11128          */
11129         skip_emulated_instruction(vcpu);
11130
11131         ret = check_vmentry_postreqs(vcpu, vmcs12, &exit_qual);
11132         if (ret) {
11133                 nested_vmx_entry_failure(vcpu, vmcs12,
11134                                          EXIT_REASON_INVALID_STATE, exit_qual);
11135                 return 1;
11136         }
11137
11138         /*
11139          * We're finally done with prerequisite checking, and can start with
11140          * the nested entry.
11141          */
11142
11143         ret = enter_vmx_non_root_mode(vcpu, true);
11144         if (ret)
11145                 return ret;
11146
11147         if (vmcs12->guest_activity_state == GUEST_ACTIVITY_HLT)
11148                 return kvm_vcpu_halt(vcpu);
11149
11150         vmx->nested.nested_run_pending = 1;
11151
11152         return 1;
11153
11154 out:
11155         return kvm_skip_emulated_instruction(vcpu);
11156 }
11157
11158 /*
11159  * On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
11160  * because L2 may have changed some cr0 bits directly (CRO_GUEST_HOST_MASK).
11161  * This function returns the new value we should put in vmcs12.guest_cr0.
11162  * It's not enough to just return the vmcs02 GUEST_CR0. Rather,
11163  *  1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
11164  *     available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0
11165  *     didn't trap the bit, because if L1 did, so would L0).
11166  *  2. Bits that L1 asked to trap (and therefore L0 also did) could not have
11167  *     been modified by L2, and L1 knows it. So just leave the old value of
11168  *     the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0
11169  *     isn't relevant, because if L0 traps this bit it can set it to anything.
11170  *  3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have
11171  *     changed these bits, and therefore they need to be updated, but L0
11172  *     didn't necessarily allow them to be changed in GUEST_CR0 - and rather
11173  *     put them in vmcs02 CR0_READ_SHADOW. So take these bits from there.
11174  */
11175 static inline unsigned long
11176 vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
11177 {
11178         return
11179         /*1*/   (vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) |
11180         /*2*/   (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) |
11181         /*3*/   (vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask |
11182                         vcpu->arch.cr0_guest_owned_bits));
11183 }
11184
11185 static inline unsigned long
11186 vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
11187 {
11188         return
11189         /*1*/   (vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) |
11190         /*2*/   (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) |
11191         /*3*/   (vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask |
11192                         vcpu->arch.cr4_guest_owned_bits));
11193 }
11194
11195 static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
11196                                        struct vmcs12 *vmcs12)
11197 {
11198         u32 idt_vectoring;
11199         unsigned int nr;
11200
11201         if (vcpu->arch.exception.injected) {
11202                 nr = vcpu->arch.exception.nr;
11203                 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
11204
11205                 if (kvm_exception_is_soft(nr)) {
11206                         vmcs12->vm_exit_instruction_len =
11207                                 vcpu->arch.event_exit_inst_len;
11208                         idt_vectoring |= INTR_TYPE_SOFT_EXCEPTION;
11209                 } else
11210                         idt_vectoring |= INTR_TYPE_HARD_EXCEPTION;
11211
11212                 if (vcpu->arch.exception.has_error_code) {
11213                         idt_vectoring |= VECTORING_INFO_DELIVER_CODE_MASK;
11214                         vmcs12->idt_vectoring_error_code =
11215                                 vcpu->arch.exception.error_code;
11216                 }
11217
11218                 vmcs12->idt_vectoring_info_field = idt_vectoring;
11219         } else if (vcpu->arch.nmi_injected) {
11220                 vmcs12->idt_vectoring_info_field =
11221                         INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR;
11222         } else if (vcpu->arch.interrupt.pending) {
11223                 nr = vcpu->arch.interrupt.nr;
11224                 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
11225
11226                 if (vcpu->arch.interrupt.soft) {
11227                         idt_vectoring |= INTR_TYPE_SOFT_INTR;
11228                         vmcs12->vm_entry_instruction_len =
11229                                 vcpu->arch.event_exit_inst_len;
11230                 } else
11231                         idt_vectoring |= INTR_TYPE_EXT_INTR;
11232
11233                 vmcs12->idt_vectoring_info_field = idt_vectoring;
11234         }
11235 }
11236
11237 static int vmx_check_nested_events(struct kvm_vcpu *vcpu, bool external_intr)
11238 {
11239         struct vcpu_vmx *vmx = to_vmx(vcpu);
11240         unsigned long exit_qual;
11241         bool block_nested_events =
11242             vmx->nested.nested_run_pending || kvm_event_needs_reinjection(vcpu);
11243
11244         if (vcpu->arch.exception.pending &&
11245                 nested_vmx_check_exception(vcpu, &exit_qual)) {
11246                 if (block_nested_events)
11247                         return -EBUSY;
11248                 nested_vmx_inject_exception_vmexit(vcpu, exit_qual);
11249                 return 0;
11250         }
11251
11252         if (nested_cpu_has_preemption_timer(get_vmcs12(vcpu)) &&
11253             vmx->nested.preemption_timer_expired) {
11254                 if (block_nested_events)
11255                         return -EBUSY;
11256                 nested_vmx_vmexit(vcpu, EXIT_REASON_PREEMPTION_TIMER, 0, 0);
11257                 return 0;
11258         }
11259
11260         if (vcpu->arch.nmi_pending && nested_exit_on_nmi(vcpu)) {
11261                 if (block_nested_events)
11262                         return -EBUSY;
11263                 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
11264                                   NMI_VECTOR | INTR_TYPE_NMI_INTR |
11265                                   INTR_INFO_VALID_MASK, 0);
11266                 /*
11267                  * The NMI-triggered VM exit counts as injection:
11268                  * clear this one and block further NMIs.
11269                  */
11270                 vcpu->arch.nmi_pending = 0;
11271                 vmx_set_nmi_mask(vcpu, true);
11272                 return 0;
11273         }
11274
11275         if ((kvm_cpu_has_interrupt(vcpu) || external_intr) &&
11276             nested_exit_on_intr(vcpu)) {
11277                 if (block_nested_events)
11278                         return -EBUSY;
11279                 nested_vmx_vmexit(vcpu, EXIT_REASON_EXTERNAL_INTERRUPT, 0, 0);
11280                 return 0;
11281         }
11282
11283         vmx_complete_nested_posted_interrupt(vcpu);
11284         return 0;
11285 }
11286
11287 static u32 vmx_get_preemption_timer_value(struct kvm_vcpu *vcpu)
11288 {
11289         ktime_t remaining =
11290                 hrtimer_get_remaining(&to_vmx(vcpu)->nested.preemption_timer);
11291         u64 value;
11292
11293         if (ktime_to_ns(remaining) <= 0)
11294                 return 0;
11295
11296         value = ktime_to_ns(remaining) * vcpu->arch.virtual_tsc_khz;
11297         do_div(value, 1000000);
11298         return value >> VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
11299 }
11300
11301 /*
11302  * Update the guest state fields of vmcs12 to reflect changes that
11303  * occurred while L2 was running. (The "IA-32e mode guest" bit of the
11304  * VM-entry controls is also updated, since this is really a guest
11305  * state bit.)
11306  */
11307 static void sync_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
11308 {
11309         vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12);
11310         vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12);
11311
11312         vmcs12->guest_rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
11313         vmcs12->guest_rip = kvm_register_read(vcpu, VCPU_REGS_RIP);
11314         vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS);
11315
11316         vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR);
11317         vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR);
11318         vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR);
11319         vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR);
11320         vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR);
11321         vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR);
11322         vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR);
11323         vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR);
11324         vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT);
11325         vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT);
11326         vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT);
11327         vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT);
11328         vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT);
11329         vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT);
11330         vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT);
11331         vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT);
11332         vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT);
11333         vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT);
11334         vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES);
11335         vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES);
11336         vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES);
11337         vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES);
11338         vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES);
11339         vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES);
11340         vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES);
11341         vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES);
11342         vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE);
11343         vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE);
11344         vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE);
11345         vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE);
11346         vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE);
11347         vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE);
11348         vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE);
11349         vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE);
11350         vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE);
11351         vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE);
11352
11353         vmcs12->guest_interruptibility_info =
11354                 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
11355         vmcs12->guest_pending_dbg_exceptions =
11356                 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);
11357         if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
11358                 vmcs12->guest_activity_state = GUEST_ACTIVITY_HLT;
11359         else
11360                 vmcs12->guest_activity_state = GUEST_ACTIVITY_ACTIVE;
11361
11362         if (nested_cpu_has_preemption_timer(vmcs12)) {
11363                 if (vmcs12->vm_exit_controls &
11364                     VM_EXIT_SAVE_VMX_PREEMPTION_TIMER)
11365                         vmcs12->vmx_preemption_timer_value =
11366                                 vmx_get_preemption_timer_value(vcpu);
11367                 hrtimer_cancel(&to_vmx(vcpu)->nested.preemption_timer);
11368         }
11369
11370         /*
11371          * In some cases (usually, nested EPT), L2 is allowed to change its
11372          * own CR3 without exiting. If it has changed it, we must keep it.
11373          * Of course, if L0 is using shadow page tables, GUEST_CR3 was defined
11374          * by L0, not L1 or L2, so we mustn't unconditionally copy it to vmcs12.
11375          *
11376          * Additionally, restore L2's PDPTR to vmcs12.
11377          */
11378         if (enable_ept) {
11379                 vmcs12->guest_cr3 = vmcs_readl(GUEST_CR3);
11380                 vmcs12->guest_pdptr0 = vmcs_read64(GUEST_PDPTR0);
11381                 vmcs12->guest_pdptr1 = vmcs_read64(GUEST_PDPTR1);
11382                 vmcs12->guest_pdptr2 = vmcs_read64(GUEST_PDPTR2);
11383                 vmcs12->guest_pdptr3 = vmcs_read64(GUEST_PDPTR3);
11384         }
11385
11386         vmcs12->guest_linear_address = vmcs_readl(GUEST_LINEAR_ADDRESS);
11387
11388         if (nested_cpu_has_vid(vmcs12))
11389                 vmcs12->guest_intr_status = vmcs_read16(GUEST_INTR_STATUS);
11390
11391         vmcs12->vm_entry_controls =
11392                 (vmcs12->vm_entry_controls & ~VM_ENTRY_IA32E_MODE) |
11393                 (vm_entry_controls_get(to_vmx(vcpu)) & VM_ENTRY_IA32E_MODE);
11394
11395         if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_DEBUG_CONTROLS) {
11396                 kvm_get_dr(vcpu, 7, (unsigned long *)&vmcs12->guest_dr7);
11397                 vmcs12->guest_ia32_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
11398         }
11399
11400         /* TODO: These cannot have changed unless we have MSR bitmaps and
11401          * the relevant bit asks not to trap the change */
11402         if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
11403                 vmcs12->guest_ia32_pat = vmcs_read64(GUEST_IA32_PAT);
11404         if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_EFER)
11405                 vmcs12->guest_ia32_efer = vcpu->arch.efer;
11406         vmcs12->guest_sysenter_cs = vmcs_read32(GUEST_SYSENTER_CS);
11407         vmcs12->guest_sysenter_esp = vmcs_readl(GUEST_SYSENTER_ESP);
11408         vmcs12->guest_sysenter_eip = vmcs_readl(GUEST_SYSENTER_EIP);
11409         if (kvm_mpx_supported())
11410                 vmcs12->guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
11411 }
11412
11413 /*
11414  * prepare_vmcs12 is part of what we need to do when the nested L2 guest exits
11415  * and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12),
11416  * and this function updates it to reflect the changes to the guest state while
11417  * L2 was running (and perhaps made some exits which were handled directly by L0
11418  * without going back to L1), and to reflect the exit reason.
11419  * Note that we do not have to copy here all VMCS fields, just those that
11420  * could have changed by the L2 guest or the exit - i.e., the guest-state and
11421  * exit-information fields only. Other fields are modified by L1 with VMWRITE,
11422  * which already writes to vmcs12 directly.
11423  */
11424 static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
11425                            u32 exit_reason, u32 exit_intr_info,
11426                            unsigned long exit_qualification)
11427 {
11428         /* update guest state fields: */
11429         sync_vmcs12(vcpu, vmcs12);
11430
11431         /* update exit information fields: */
11432
11433         vmcs12->vm_exit_reason = exit_reason;
11434         vmcs12->exit_qualification = exit_qualification;
11435         vmcs12->vm_exit_intr_info = exit_intr_info;
11436
11437         vmcs12->idt_vectoring_info_field = 0;
11438         vmcs12->vm_exit_instruction_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
11439         vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
11440
11441         if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY)) {
11442                 vmcs12->launch_state = 1;
11443
11444                 /* vm_entry_intr_info_field is cleared on exit. Emulate this
11445                  * instead of reading the real value. */
11446                 vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK;
11447
11448                 /*
11449                  * Transfer the event that L0 or L1 may wanted to inject into
11450                  * L2 to IDT_VECTORING_INFO_FIELD.
11451                  */
11452                 vmcs12_save_pending_event(vcpu, vmcs12);
11453         }
11454
11455         /*
11456          * Drop what we picked up for L2 via vmx_complete_interrupts. It is
11457          * preserved above and would only end up incorrectly in L1.
11458          */
11459         vcpu->arch.nmi_injected = false;
11460         kvm_clear_exception_queue(vcpu);
11461         kvm_clear_interrupt_queue(vcpu);
11462 }
11463
11464 static void load_vmcs12_mmu_host_state(struct kvm_vcpu *vcpu,
11465                         struct vmcs12 *vmcs12)
11466 {
11467         u32 entry_failure_code;
11468
11469         nested_ept_uninit_mmu_context(vcpu);
11470
11471         /*
11472          * Only PDPTE load can fail as the value of cr3 was checked on entry and
11473          * couldn't have changed.
11474          */
11475         if (nested_vmx_load_cr3(vcpu, vmcs12->host_cr3, false, &entry_failure_code))
11476                 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_PDPTE_FAIL);
11477
11478         if (!enable_ept)
11479                 vcpu->arch.walk_mmu->inject_page_fault = kvm_inject_page_fault;
11480 }
11481
11482 /*
11483  * A part of what we need to when the nested L2 guest exits and we want to
11484  * run its L1 parent, is to reset L1's guest state to the host state specified
11485  * in vmcs12.
11486  * This function is to be called not only on normal nested exit, but also on
11487  * a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry
11488  * Failures During or After Loading Guest State").
11489  * This function should be called when the active VMCS is L1's (vmcs01).
11490  */
11491 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
11492                                    struct vmcs12 *vmcs12)
11493 {
11494         struct kvm_segment seg;
11495
11496         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
11497                 vcpu->arch.efer = vmcs12->host_ia32_efer;
11498         else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
11499                 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
11500         else
11501                 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
11502         vmx_set_efer(vcpu, vcpu->arch.efer);
11503
11504         kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp);
11505         kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip);
11506         vmx_set_rflags(vcpu, X86_EFLAGS_FIXED);
11507         /*
11508          * Note that calling vmx_set_cr0 is important, even if cr0 hasn't
11509          * actually changed, because vmx_set_cr0 refers to efer set above.
11510          *
11511          * CR0_GUEST_HOST_MASK is already set in the original vmcs01
11512          * (KVM doesn't change it);
11513          */
11514         vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
11515         vmx_set_cr0(vcpu, vmcs12->host_cr0);
11516
11517         /* Same as above - no reason to call set_cr4_guest_host_mask().  */
11518         vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
11519         vmx_set_cr4(vcpu, vmcs12->host_cr4);
11520
11521         load_vmcs12_mmu_host_state(vcpu, vmcs12);
11522
11523         if (enable_vpid) {
11524                 /*
11525                  * Trivially support vpid by letting L2s share their parent
11526                  * L1's vpid. TODO: move to a more elaborate solution, giving
11527                  * each L2 its own vpid and exposing the vpid feature to L1.
11528                  */
11529                 vmx_flush_tlb(vcpu);
11530         }
11531         /* Restore posted intr vector. */
11532         if (nested_cpu_has_posted_intr(vmcs12))
11533                 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
11534
11535         vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
11536         vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp);
11537         vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip);
11538         vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base);
11539         vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base);
11540         vmcs_write32(GUEST_IDTR_LIMIT, 0xFFFF);
11541         vmcs_write32(GUEST_GDTR_LIMIT, 0xFFFF);
11542
11543         /* If not VM_EXIT_CLEAR_BNDCFGS, the L2 value propagates to L1.  */
11544         if (vmcs12->vm_exit_controls & VM_EXIT_CLEAR_BNDCFGS)
11545                 vmcs_write64(GUEST_BNDCFGS, 0);
11546
11547         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) {
11548                 vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat);
11549                 vcpu->arch.pat = vmcs12->host_ia32_pat;
11550         }
11551         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
11552                 vmcs_write64(GUEST_IA32_PERF_GLOBAL_CTRL,
11553                         vmcs12->host_ia32_perf_global_ctrl);
11554
11555         /* Set L1 segment info according to Intel SDM
11556             27.5.2 Loading Host Segment and Descriptor-Table Registers */
11557         seg = (struct kvm_segment) {
11558                 .base = 0,
11559                 .limit = 0xFFFFFFFF,
11560                 .selector = vmcs12->host_cs_selector,
11561                 .type = 11,
11562                 .present = 1,
11563                 .s = 1,
11564                 .g = 1
11565         };
11566         if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
11567                 seg.l = 1;
11568         else
11569                 seg.db = 1;
11570         vmx_set_segment(vcpu, &seg, VCPU_SREG_CS);
11571         seg = (struct kvm_segment) {
11572                 .base = 0,
11573                 .limit = 0xFFFFFFFF,
11574                 .type = 3,
11575                 .present = 1,
11576                 .s = 1,
11577                 .db = 1,
11578                 .g = 1
11579         };
11580         seg.selector = vmcs12->host_ds_selector;
11581         vmx_set_segment(vcpu, &seg, VCPU_SREG_DS);
11582         seg.selector = vmcs12->host_es_selector;
11583         vmx_set_segment(vcpu, &seg, VCPU_SREG_ES);
11584         seg.selector = vmcs12->host_ss_selector;
11585         vmx_set_segment(vcpu, &seg, VCPU_SREG_SS);
11586         seg.selector = vmcs12->host_fs_selector;
11587         seg.base = vmcs12->host_fs_base;
11588         vmx_set_segment(vcpu, &seg, VCPU_SREG_FS);
11589         seg.selector = vmcs12->host_gs_selector;
11590         seg.base = vmcs12->host_gs_base;
11591         vmx_set_segment(vcpu, &seg, VCPU_SREG_GS);
11592         seg = (struct kvm_segment) {
11593                 .base = vmcs12->host_tr_base,
11594                 .limit = 0x67,
11595                 .selector = vmcs12->host_tr_selector,
11596                 .type = 11,
11597                 .present = 1
11598         };
11599         vmx_set_segment(vcpu, &seg, VCPU_SREG_TR);
11600
11601         kvm_set_dr(vcpu, 7, 0x400);
11602         vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
11603
11604         if (cpu_has_vmx_msr_bitmap())
11605                 vmx_update_msr_bitmap(vcpu);
11606
11607         if (nested_vmx_load_msr(vcpu, vmcs12->vm_exit_msr_load_addr,
11608                                 vmcs12->vm_exit_msr_load_count))
11609                 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
11610 }
11611
11612 /*
11613  * Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
11614  * and modify vmcs12 to make it see what it would expect to see there if
11615  * L2 was its real guest. Must only be called when in L2 (is_guest_mode())
11616  */
11617 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
11618                               u32 exit_intr_info,
11619                               unsigned long exit_qualification)
11620 {
11621         struct vcpu_vmx *vmx = to_vmx(vcpu);
11622         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11623
11624         /* trying to cancel vmlaunch/vmresume is a bug */
11625         WARN_ON_ONCE(vmx->nested.nested_run_pending);
11626
11627         /*
11628          * The only expected VM-instruction error is "VM entry with
11629          * invalid control field(s)." Anything else indicates a
11630          * problem with L0.
11631          */
11632         WARN_ON_ONCE(vmx->fail && (vmcs_read32(VM_INSTRUCTION_ERROR) !=
11633                                    VMXERR_ENTRY_INVALID_CONTROL_FIELD));
11634
11635         leave_guest_mode(vcpu);
11636
11637         if (likely(!vmx->fail)) {
11638                 prepare_vmcs12(vcpu, vmcs12, exit_reason, exit_intr_info,
11639                                exit_qualification);
11640
11641                 if (nested_vmx_store_msr(vcpu, vmcs12->vm_exit_msr_store_addr,
11642                                          vmcs12->vm_exit_msr_store_count))
11643                         nested_vmx_abort(vcpu, VMX_ABORT_SAVE_GUEST_MSR_FAIL);
11644         }
11645
11646         vmx_switch_vmcs(vcpu, &vmx->vmcs01);
11647         vm_entry_controls_reset_shadow(vmx);
11648         vm_exit_controls_reset_shadow(vmx);
11649         vmx_segment_cache_clear(vmx);
11650
11651         /* Update any VMCS fields that might have changed while L2 ran */
11652         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
11653         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
11654         vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
11655         if (vmx->hv_deadline_tsc == -1)
11656                 vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
11657                                 PIN_BASED_VMX_PREEMPTION_TIMER);
11658         else
11659                 vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
11660                               PIN_BASED_VMX_PREEMPTION_TIMER);
11661         if (kvm_has_tsc_control)
11662                 decache_tsc_multiplier(vmx);
11663
11664         if (vmx->nested.change_vmcs01_virtual_x2apic_mode) {
11665                 vmx->nested.change_vmcs01_virtual_x2apic_mode = false;
11666                 vmx_set_virtual_x2apic_mode(vcpu,
11667                                 vcpu->arch.apic_base & X2APIC_ENABLE);
11668         } else if (!nested_cpu_has_ept(vmcs12) &&
11669                    nested_cpu_has2(vmcs12,
11670                                    SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
11671                 vmx_flush_tlb_ept_only(vcpu);
11672         }
11673
11674         /* This is needed for same reason as it was needed in prepare_vmcs02 */
11675         vmx->host_rsp = 0;
11676
11677         /* Unpin physical memory we referred to in vmcs02 */
11678         if (vmx->nested.apic_access_page) {
11679                 kvm_release_page_dirty(vmx->nested.apic_access_page);
11680                 vmx->nested.apic_access_page = NULL;
11681         }
11682         if (vmx->nested.virtual_apic_page) {
11683                 kvm_release_page_dirty(vmx->nested.virtual_apic_page);
11684                 vmx->nested.virtual_apic_page = NULL;
11685         }
11686         if (vmx->nested.pi_desc_page) {
11687                 kunmap(vmx->nested.pi_desc_page);
11688                 kvm_release_page_dirty(vmx->nested.pi_desc_page);
11689                 vmx->nested.pi_desc_page = NULL;
11690                 vmx->nested.pi_desc = NULL;
11691         }
11692
11693         /*
11694          * We are now running in L2, mmu_notifier will force to reload the
11695          * page's hpa for L2 vmcs. Need to reload it for L1 before entering L1.
11696          */
11697         kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
11698
11699         if (enable_shadow_vmcs)
11700                 vmx->nested.sync_shadow_vmcs = true;
11701
11702         /* in case we halted in L2 */
11703         vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
11704
11705         if (likely(!vmx->fail)) {
11706                 /*
11707                  * TODO: SDM says that with acknowledge interrupt on
11708                  * exit, bit 31 of the VM-exit interrupt information
11709                  * (valid interrupt) is always set to 1 on
11710                  * EXIT_REASON_EXTERNAL_INTERRUPT, so we shouldn't
11711                  * need kvm_cpu_has_interrupt().  See the commit
11712                  * message for details.
11713                  */
11714                 if (nested_exit_intr_ack_set(vcpu) &&
11715                     exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT &&
11716                     kvm_cpu_has_interrupt(vcpu)) {
11717                         int irq = kvm_cpu_get_interrupt(vcpu);
11718                         WARN_ON(irq < 0);
11719                         vmcs12->vm_exit_intr_info = irq |
11720                                 INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR;
11721                 }
11722
11723                 trace_kvm_nested_vmexit_inject(vmcs12->vm_exit_reason,
11724                                                vmcs12->exit_qualification,
11725                                                vmcs12->idt_vectoring_info_field,
11726                                                vmcs12->vm_exit_intr_info,
11727                                                vmcs12->vm_exit_intr_error_code,
11728                                                KVM_ISA_VMX);
11729
11730                 load_vmcs12_host_state(vcpu, vmcs12);
11731
11732                 return;
11733         }
11734         
11735         /*
11736          * After an early L2 VM-entry failure, we're now back
11737          * in L1 which thinks it just finished a VMLAUNCH or
11738          * VMRESUME instruction, so we need to set the failure
11739          * flag and the VM-instruction error field of the VMCS
11740          * accordingly.
11741          */
11742         nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
11743
11744         load_vmcs12_mmu_host_state(vcpu, vmcs12);
11745
11746         /*
11747          * The emulated instruction was already skipped in
11748          * nested_vmx_run, but the updated RIP was never
11749          * written back to the vmcs01.
11750          */
11751         skip_emulated_instruction(vcpu);
11752         vmx->fail = 0;
11753 }
11754
11755 /*
11756  * Forcibly leave nested mode in order to be able to reset the VCPU later on.
11757  */
11758 static void vmx_leave_nested(struct kvm_vcpu *vcpu)
11759 {
11760         if (is_guest_mode(vcpu)) {
11761                 to_vmx(vcpu)->nested.nested_run_pending = 0;
11762                 nested_vmx_vmexit(vcpu, -1, 0, 0);
11763         }
11764         free_nested(to_vmx(vcpu));
11765 }
11766
11767 /*
11768  * L1's failure to enter L2 is a subset of a normal exit, as explained in
11769  * 23.7 "VM-entry failures during or after loading guest state" (this also
11770  * lists the acceptable exit-reason and exit-qualification parameters).
11771  * It should only be called before L2 actually succeeded to run, and when
11772  * vmcs01 is current (it doesn't leave_guest_mode() or switch vmcss).
11773  */
11774 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
11775                         struct vmcs12 *vmcs12,
11776                         u32 reason, unsigned long qualification)
11777 {
11778         load_vmcs12_host_state(vcpu, vmcs12);
11779         vmcs12->vm_exit_reason = reason | VMX_EXIT_REASONS_FAILED_VMENTRY;
11780         vmcs12->exit_qualification = qualification;
11781         nested_vmx_succeed(vcpu);
11782         if (enable_shadow_vmcs)
11783                 to_vmx(vcpu)->nested.sync_shadow_vmcs = true;
11784 }
11785
11786 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
11787                                struct x86_instruction_info *info,
11788                                enum x86_intercept_stage stage)
11789 {
11790         return X86EMUL_CONTINUE;
11791 }
11792
11793 #ifdef CONFIG_X86_64
11794 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
11795 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
11796                                   u64 divisor, u64 *result)
11797 {
11798         u64 low = a << shift, high = a >> (64 - shift);
11799
11800         /* To avoid the overflow on divq */
11801         if (high >= divisor)
11802                 return 1;
11803
11804         /* Low hold the result, high hold rem which is discarded */
11805         asm("divq %2\n\t" : "=a" (low), "=d" (high) :
11806             "rm" (divisor), "0" (low), "1" (high));
11807         *result = low;
11808
11809         return 0;
11810 }
11811
11812 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc)
11813 {
11814         struct vcpu_vmx *vmx = to_vmx(vcpu);
11815         u64 tscl = rdtsc();
11816         u64 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
11817         u64 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
11818
11819         /* Convert to host delta tsc if tsc scaling is enabled */
11820         if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
11821                         u64_shl_div_u64(delta_tsc,
11822                                 kvm_tsc_scaling_ratio_frac_bits,
11823                                 vcpu->arch.tsc_scaling_ratio,
11824                                 &delta_tsc))
11825                 return -ERANGE;
11826
11827         /*
11828          * If the delta tsc can't fit in the 32 bit after the multi shift,
11829          * we can't use the preemption timer.
11830          * It's possible that it fits on later vmentries, but checking
11831          * on every vmentry is costly so we just use an hrtimer.
11832          */
11833         if (delta_tsc >> (cpu_preemption_timer_multi + 32))
11834                 return -ERANGE;
11835
11836         vmx->hv_deadline_tsc = tscl + delta_tsc;
11837         vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
11838                         PIN_BASED_VMX_PREEMPTION_TIMER);
11839
11840         return delta_tsc == 0;
11841 }
11842
11843 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
11844 {
11845         struct vcpu_vmx *vmx = to_vmx(vcpu);
11846         vmx->hv_deadline_tsc = -1;
11847         vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
11848                         PIN_BASED_VMX_PREEMPTION_TIMER);
11849 }
11850 #endif
11851
11852 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
11853 {
11854         if (ple_gap)
11855                 shrink_ple_window(vcpu);
11856 }
11857
11858 static void vmx_slot_enable_log_dirty(struct kvm *kvm,
11859                                      struct kvm_memory_slot *slot)
11860 {
11861         kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
11862         kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
11863 }
11864
11865 static void vmx_slot_disable_log_dirty(struct kvm *kvm,
11866                                        struct kvm_memory_slot *slot)
11867 {
11868         kvm_mmu_slot_set_dirty(kvm, slot);
11869 }
11870
11871 static void vmx_flush_log_dirty(struct kvm *kvm)
11872 {
11873         kvm_flush_pml_buffers(kvm);
11874 }
11875
11876 static int vmx_write_pml_buffer(struct kvm_vcpu *vcpu)
11877 {
11878         struct vmcs12 *vmcs12;
11879         struct vcpu_vmx *vmx = to_vmx(vcpu);
11880         gpa_t gpa;
11881         struct page *page = NULL;
11882         u64 *pml_address;
11883
11884         if (is_guest_mode(vcpu)) {
11885                 WARN_ON_ONCE(vmx->nested.pml_full);
11886
11887                 /*
11888                  * Check if PML is enabled for the nested guest.
11889                  * Whether eptp bit 6 is set is already checked
11890                  * as part of A/D emulation.
11891                  */
11892                 vmcs12 = get_vmcs12(vcpu);
11893                 if (!nested_cpu_has_pml(vmcs12))
11894                         return 0;
11895
11896                 if (vmcs12->guest_pml_index >= PML_ENTITY_NUM) {
11897                         vmx->nested.pml_full = true;
11898                         return 1;
11899                 }
11900
11901                 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS) & ~0xFFFull;
11902
11903                 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->pml_address);
11904                 if (is_error_page(page))
11905                         return 0;
11906
11907                 pml_address = kmap(page);
11908                 pml_address[vmcs12->guest_pml_index--] = gpa;
11909                 kunmap(page);
11910                 kvm_release_page_clean(page);
11911         }
11912
11913         return 0;
11914 }
11915
11916 static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
11917                                            struct kvm_memory_slot *memslot,
11918                                            gfn_t offset, unsigned long mask)
11919 {
11920         kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
11921 }
11922
11923 static void __pi_post_block(struct kvm_vcpu *vcpu)
11924 {
11925         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
11926         struct pi_desc old, new;
11927         unsigned int dest;
11928
11929         do {
11930                 old.control = new.control = pi_desc->control;
11931                 WARN(old.nv != POSTED_INTR_WAKEUP_VECTOR,
11932                      "Wakeup handler not enabled while the VCPU is blocked\n");
11933
11934                 dest = cpu_physical_id(vcpu->cpu);
11935
11936                 if (x2apic_enabled())
11937                         new.ndst = dest;
11938                 else
11939                         new.ndst = (dest << 8) & 0xFF00;
11940
11941                 /* set 'NV' to 'notification vector' */
11942                 new.nv = POSTED_INTR_VECTOR;
11943         } while (cmpxchg64(&pi_desc->control, old.control,
11944                            new.control) != old.control);
11945
11946         if (!WARN_ON_ONCE(vcpu->pre_pcpu == -1)) {
11947                 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
11948                 list_del(&vcpu->blocked_vcpu_list);
11949                 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
11950                 vcpu->pre_pcpu = -1;
11951         }
11952 }
11953
11954 /*
11955  * This routine does the following things for vCPU which is going
11956  * to be blocked if VT-d PI is enabled.
11957  * - Store the vCPU to the wakeup list, so when interrupts happen
11958  *   we can find the right vCPU to wake up.
11959  * - Change the Posted-interrupt descriptor as below:
11960  *      'NDST' <-- vcpu->pre_pcpu
11961  *      'NV' <-- POSTED_INTR_WAKEUP_VECTOR
11962  * - If 'ON' is set during this process, which means at least one
11963  *   interrupt is posted for this vCPU, we cannot block it, in
11964  *   this case, return 1, otherwise, return 0.
11965  *
11966  */
11967 static int pi_pre_block(struct kvm_vcpu *vcpu)
11968 {
11969         unsigned int dest;
11970         struct pi_desc old, new;
11971         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
11972
11973         if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
11974                 !irq_remapping_cap(IRQ_POSTING_CAP)  ||
11975                 !kvm_vcpu_apicv_active(vcpu))
11976                 return 0;
11977
11978         WARN_ON(irqs_disabled());
11979         local_irq_disable();
11980         if (!WARN_ON_ONCE(vcpu->pre_pcpu != -1)) {
11981                 vcpu->pre_pcpu = vcpu->cpu;
11982                 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
11983                 list_add_tail(&vcpu->blocked_vcpu_list,
11984                               &per_cpu(blocked_vcpu_on_cpu,
11985                                        vcpu->pre_pcpu));
11986                 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
11987         }
11988
11989         do {
11990                 old.control = new.control = pi_desc->control;
11991
11992                 WARN((pi_desc->sn == 1),
11993                      "Warning: SN field of posted-interrupts "
11994                      "is set before blocking\n");
11995
11996                 /*
11997                  * Since vCPU can be preempted during this process,
11998                  * vcpu->cpu could be different with pre_pcpu, we
11999                  * need to set pre_pcpu as the destination of wakeup
12000                  * notification event, then we can find the right vCPU
12001                  * to wakeup in wakeup handler if interrupts happen
12002                  * when the vCPU is in blocked state.
12003                  */
12004                 dest = cpu_physical_id(vcpu->pre_pcpu);
12005
12006                 if (x2apic_enabled())
12007                         new.ndst = dest;
12008                 else
12009                         new.ndst = (dest << 8) & 0xFF00;
12010
12011                 /* set 'NV' to 'wakeup vector' */
12012                 new.nv = POSTED_INTR_WAKEUP_VECTOR;
12013         } while (cmpxchg64(&pi_desc->control, old.control,
12014                            new.control) != old.control);
12015
12016         /* We should not block the vCPU if an interrupt is posted for it.  */
12017         if (pi_test_on(pi_desc) == 1)
12018                 __pi_post_block(vcpu);
12019
12020         local_irq_enable();
12021         return (vcpu->pre_pcpu == -1);
12022 }
12023
12024 static int vmx_pre_block(struct kvm_vcpu *vcpu)
12025 {
12026         if (pi_pre_block(vcpu))
12027                 return 1;
12028
12029         if (kvm_lapic_hv_timer_in_use(vcpu))
12030                 kvm_lapic_switch_to_sw_timer(vcpu);
12031
12032         return 0;
12033 }
12034
12035 static void pi_post_block(struct kvm_vcpu *vcpu)
12036 {
12037         if (vcpu->pre_pcpu == -1)
12038                 return;
12039
12040         WARN_ON(irqs_disabled());
12041         local_irq_disable();
12042         __pi_post_block(vcpu);
12043         local_irq_enable();
12044 }
12045
12046 static void vmx_post_block(struct kvm_vcpu *vcpu)
12047 {
12048         if (kvm_x86_ops->set_hv_timer)
12049                 kvm_lapic_switch_to_hv_timer(vcpu);
12050
12051         pi_post_block(vcpu);
12052 }
12053
12054 /*
12055  * vmx_update_pi_irte - set IRTE for Posted-Interrupts
12056  *
12057  * @kvm: kvm
12058  * @host_irq: host irq of the interrupt
12059  * @guest_irq: gsi of the interrupt
12060  * @set: set or unset PI
12061  * returns 0 on success, < 0 on failure
12062  */
12063 static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
12064                               uint32_t guest_irq, bool set)
12065 {
12066         struct kvm_kernel_irq_routing_entry *e;
12067         struct kvm_irq_routing_table *irq_rt;
12068         struct kvm_lapic_irq irq;
12069         struct kvm_vcpu *vcpu;
12070         struct vcpu_data vcpu_info;
12071         int idx, ret = 0;
12072
12073         if (!kvm_arch_has_assigned_device(kvm) ||
12074                 !irq_remapping_cap(IRQ_POSTING_CAP) ||
12075                 !kvm_vcpu_apicv_active(kvm->vcpus[0]))
12076                 return 0;
12077
12078         idx = srcu_read_lock(&kvm->irq_srcu);
12079         irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
12080         if (guest_irq >= irq_rt->nr_rt_entries ||
12081             hlist_empty(&irq_rt->map[guest_irq])) {
12082                 pr_warn_once("no route for guest_irq %u/%u (broken user space?)\n",
12083                              guest_irq, irq_rt->nr_rt_entries);
12084                 goto out;
12085         }
12086
12087         hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
12088                 if (e->type != KVM_IRQ_ROUTING_MSI)
12089                         continue;
12090                 /*
12091                  * VT-d PI cannot support posting multicast/broadcast
12092                  * interrupts to a vCPU, we still use interrupt remapping
12093                  * for these kind of interrupts.
12094                  *
12095                  * For lowest-priority interrupts, we only support
12096                  * those with single CPU as the destination, e.g. user
12097                  * configures the interrupts via /proc/irq or uses
12098                  * irqbalance to make the interrupts single-CPU.
12099                  *
12100                  * We will support full lowest-priority interrupt later.
12101                  */
12102
12103                 kvm_set_msi_irq(kvm, e, &irq);
12104                 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
12105                         /*
12106                          * Make sure the IRTE is in remapped mode if
12107                          * we don't handle it in posted mode.
12108                          */
12109                         ret = irq_set_vcpu_affinity(host_irq, NULL);
12110                         if (ret < 0) {
12111                                 printk(KERN_INFO
12112                                    "failed to back to remapped mode, irq: %u\n",
12113                                    host_irq);
12114                                 goto out;
12115                         }
12116
12117                         continue;
12118                 }
12119
12120                 vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
12121                 vcpu_info.vector = irq.vector;
12122
12123                 trace_kvm_pi_irte_update(vcpu->vcpu_id, host_irq, e->gsi,
12124                                 vcpu_info.vector, vcpu_info.pi_desc_addr, set);
12125
12126                 if (set)
12127                         ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
12128                 else
12129                         ret = irq_set_vcpu_affinity(host_irq, NULL);
12130
12131                 if (ret < 0) {
12132                         printk(KERN_INFO "%s: failed to update PI IRTE\n",
12133                                         __func__);
12134                         goto out;
12135                 }
12136         }
12137
12138         ret = 0;
12139 out:
12140         srcu_read_unlock(&kvm->irq_srcu, idx);
12141         return ret;
12142 }
12143
12144 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
12145 {
12146         if (vcpu->arch.mcg_cap & MCG_LMCE_P)
12147                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
12148                         FEATURE_CONTROL_LMCE;
12149         else
12150                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
12151                         ~FEATURE_CONTROL_LMCE;
12152 }
12153
12154 static struct kvm_x86_ops vmx_x86_ops __ro_after_init = {
12155         .cpu_has_kvm_support = cpu_has_kvm_support,
12156         .disabled_by_bios = vmx_disabled_by_bios,
12157         .hardware_setup = hardware_setup,
12158         .hardware_unsetup = hardware_unsetup,
12159         .check_processor_compatibility = vmx_check_processor_compat,
12160         .hardware_enable = hardware_enable,
12161         .hardware_disable = hardware_disable,
12162         .cpu_has_accelerated_tpr = report_flexpriority,
12163         .cpu_has_high_real_mode_segbase = vmx_has_high_real_mode_segbase,
12164
12165         .vcpu_create = vmx_create_vcpu,
12166         .vcpu_free = vmx_free_vcpu,
12167         .vcpu_reset = vmx_vcpu_reset,
12168
12169         .prepare_guest_switch = vmx_save_host_state,
12170         .vcpu_load = vmx_vcpu_load,
12171         .vcpu_put = vmx_vcpu_put,
12172
12173         .update_bp_intercept = update_exception_bitmap,
12174         .get_msr = vmx_get_msr,
12175         .set_msr = vmx_set_msr,
12176         .get_segment_base = vmx_get_segment_base,
12177         .get_segment = vmx_get_segment,
12178         .set_segment = vmx_set_segment,
12179         .get_cpl = vmx_get_cpl,
12180         .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
12181         .decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
12182         .decache_cr3 = vmx_decache_cr3,
12183         .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
12184         .set_cr0 = vmx_set_cr0,
12185         .set_cr3 = vmx_set_cr3,
12186         .set_cr4 = vmx_set_cr4,
12187         .set_efer = vmx_set_efer,
12188         .get_idt = vmx_get_idt,
12189         .set_idt = vmx_set_idt,
12190         .get_gdt = vmx_get_gdt,
12191         .set_gdt = vmx_set_gdt,
12192         .get_dr6 = vmx_get_dr6,
12193         .set_dr6 = vmx_set_dr6,
12194         .set_dr7 = vmx_set_dr7,
12195         .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
12196         .cache_reg = vmx_cache_reg,
12197         .get_rflags = vmx_get_rflags,
12198         .set_rflags = vmx_set_rflags,
12199
12200         .tlb_flush = vmx_flush_tlb,
12201
12202         .run = vmx_vcpu_run,
12203         .handle_exit = vmx_handle_exit,
12204         .skip_emulated_instruction = skip_emulated_instruction,
12205         .set_interrupt_shadow = vmx_set_interrupt_shadow,
12206         .get_interrupt_shadow = vmx_get_interrupt_shadow,
12207         .patch_hypercall = vmx_patch_hypercall,
12208         .set_irq = vmx_inject_irq,
12209         .set_nmi = vmx_inject_nmi,
12210         .queue_exception = vmx_queue_exception,
12211         .cancel_injection = vmx_cancel_injection,
12212         .interrupt_allowed = vmx_interrupt_allowed,
12213         .nmi_allowed = vmx_nmi_allowed,
12214         .get_nmi_mask = vmx_get_nmi_mask,
12215         .set_nmi_mask = vmx_set_nmi_mask,
12216         .enable_nmi_window = enable_nmi_window,
12217         .enable_irq_window = enable_irq_window,
12218         .update_cr8_intercept = update_cr8_intercept,
12219         .set_virtual_x2apic_mode = vmx_set_virtual_x2apic_mode,
12220         .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
12221         .get_enable_apicv = vmx_get_enable_apicv,
12222         .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
12223         .load_eoi_exitmap = vmx_load_eoi_exitmap,
12224         .apicv_post_state_restore = vmx_apicv_post_state_restore,
12225         .hwapic_irr_update = vmx_hwapic_irr_update,
12226         .hwapic_isr_update = vmx_hwapic_isr_update,
12227         .sync_pir_to_irr = vmx_sync_pir_to_irr,
12228         .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
12229
12230         .set_tss_addr = vmx_set_tss_addr,
12231         .get_tdp_level = get_ept_level,
12232         .get_mt_mask = vmx_get_mt_mask,
12233
12234         .get_exit_info = vmx_get_exit_info,
12235
12236         .get_lpage_level = vmx_get_lpage_level,
12237
12238         .cpuid_update = vmx_cpuid_update,
12239
12240         .rdtscp_supported = vmx_rdtscp_supported,
12241         .invpcid_supported = vmx_invpcid_supported,
12242
12243         .set_supported_cpuid = vmx_set_supported_cpuid,
12244
12245         .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
12246
12247         .write_tsc_offset = vmx_write_tsc_offset,
12248
12249         .set_tdp_cr3 = vmx_set_cr3,
12250
12251         .check_intercept = vmx_check_intercept,
12252         .handle_external_intr = vmx_handle_external_intr,
12253         .mpx_supported = vmx_mpx_supported,
12254         .xsaves_supported = vmx_xsaves_supported,
12255
12256         .check_nested_events = vmx_check_nested_events,
12257
12258         .sched_in = vmx_sched_in,
12259
12260         .slot_enable_log_dirty = vmx_slot_enable_log_dirty,
12261         .slot_disable_log_dirty = vmx_slot_disable_log_dirty,
12262         .flush_log_dirty = vmx_flush_log_dirty,
12263         .enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
12264         .write_log_dirty = vmx_write_pml_buffer,
12265
12266         .pre_block = vmx_pre_block,
12267         .post_block = vmx_post_block,
12268
12269         .pmu_ops = &intel_pmu_ops,
12270
12271         .update_pi_irte = vmx_update_pi_irte,
12272
12273 #ifdef CONFIG_X86_64
12274         .set_hv_timer = vmx_set_hv_timer,
12275         .cancel_hv_timer = vmx_cancel_hv_timer,
12276 #endif
12277
12278         .setup_mce = vmx_setup_mce,
12279 };
12280
12281 static int __init vmx_init(void)
12282 {
12283         int r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
12284                      __alignof__(struct vcpu_vmx), THIS_MODULE);
12285         if (r)
12286                 return r;
12287
12288 #ifdef CONFIG_KEXEC_CORE
12289         rcu_assign_pointer(crash_vmclear_loaded_vmcss,
12290                            crash_vmclear_local_loaded_vmcss);
12291 #endif
12292
12293         return 0;
12294 }
12295
12296 static void __exit vmx_exit(void)
12297 {
12298 #ifdef CONFIG_KEXEC_CORE
12299         RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
12300         synchronize_rcu();
12301 #endif
12302
12303         kvm_exit();
12304 }
12305
12306 module_init(vmx_init)
12307 module_exit(vmx_exit)