OSDN Git Service

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