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