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