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