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