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