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