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