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