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