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