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