OSDN Git Service

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