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