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