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