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