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