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