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