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