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