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