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