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