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