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