Merge branch 'kvm-insert-lfence' into kvm-master
[sfrench/cifs-2.6.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                 return -ENOENT;
904
905         /*
906          * FIXME: Mitigation for CVE-2017-5753.  To be replaced with a
907          * generic mechanism.
908          */
909         asm("lfence");
910
911         if (vmcs_field_to_offset_table[field] == 0)
912                 return -ENOENT;
913
914         return vmcs_field_to_offset_table[field];
915 }
916
917 static inline struct vmcs12 *get_vmcs12(struct kvm_vcpu *vcpu)
918 {
919         return to_vmx(vcpu)->nested.cached_vmcs12;
920 }
921
922 static bool nested_ept_ad_enabled(struct kvm_vcpu *vcpu);
923 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu);
924 static u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa);
925 static bool vmx_xsaves_supported(void);
926 static void vmx_set_segment(struct kvm_vcpu *vcpu,
927                             struct kvm_segment *var, int seg);
928 static void vmx_get_segment(struct kvm_vcpu *vcpu,
929                             struct kvm_segment *var, int seg);
930 static bool guest_state_valid(struct kvm_vcpu *vcpu);
931 static u32 vmx_segment_access_rights(struct kvm_segment *var);
932 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx);
933 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu);
934 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked);
935 static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
936                                             u16 error_code);
937
938 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
939 static DEFINE_PER_CPU(struct vmcs *, current_vmcs);
940 /*
941  * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
942  * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
943  */
944 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
945
946 /*
947  * We maintian a per-CPU linked-list of vCPU, so in wakeup_handler() we
948  * can find which vCPU should be waken up.
949  */
950 static DEFINE_PER_CPU(struct list_head, blocked_vcpu_on_cpu);
951 static DEFINE_PER_CPU(spinlock_t, blocked_vcpu_on_cpu_lock);
952
953 enum {
954         VMX_IO_BITMAP_A,
955         VMX_IO_BITMAP_B,
956         VMX_MSR_BITMAP_LEGACY,
957         VMX_MSR_BITMAP_LONGMODE,
958         VMX_MSR_BITMAP_LEGACY_X2APIC_APICV,
959         VMX_MSR_BITMAP_LONGMODE_X2APIC_APICV,
960         VMX_MSR_BITMAP_LEGACY_X2APIC,
961         VMX_MSR_BITMAP_LONGMODE_X2APIC,
962         VMX_VMREAD_BITMAP,
963         VMX_VMWRITE_BITMAP,
964         VMX_BITMAP_NR
965 };
966
967 static unsigned long *vmx_bitmap[VMX_BITMAP_NR];
968
969 #define vmx_io_bitmap_a                      (vmx_bitmap[VMX_IO_BITMAP_A])
970 #define vmx_io_bitmap_b                      (vmx_bitmap[VMX_IO_BITMAP_B])
971 #define vmx_msr_bitmap_legacy                (vmx_bitmap[VMX_MSR_BITMAP_LEGACY])
972 #define vmx_msr_bitmap_longmode              (vmx_bitmap[VMX_MSR_BITMAP_LONGMODE])
973 #define vmx_msr_bitmap_legacy_x2apic_apicv   (vmx_bitmap[VMX_MSR_BITMAP_LEGACY_X2APIC_APICV])
974 #define vmx_msr_bitmap_longmode_x2apic_apicv (vmx_bitmap[VMX_MSR_BITMAP_LONGMODE_X2APIC_APICV])
975 #define vmx_msr_bitmap_legacy_x2apic         (vmx_bitmap[VMX_MSR_BITMAP_LEGACY_X2APIC])
976 #define vmx_msr_bitmap_longmode_x2apic       (vmx_bitmap[VMX_MSR_BITMAP_LONGMODE_X2APIC])
977 #define vmx_vmread_bitmap                    (vmx_bitmap[VMX_VMREAD_BITMAP])
978 #define vmx_vmwrite_bitmap                   (vmx_bitmap[VMX_VMWRITE_BITMAP])
979
980 static bool cpu_has_load_ia32_efer;
981 static bool cpu_has_load_perf_global_ctrl;
982
983 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
984 static DEFINE_SPINLOCK(vmx_vpid_lock);
985
986 static struct vmcs_config {
987         int size;
988         int order;
989         u32 basic_cap;
990         u32 revision_id;
991         u32 pin_based_exec_ctrl;
992         u32 cpu_based_exec_ctrl;
993         u32 cpu_based_2nd_exec_ctrl;
994         u32 vmexit_ctrl;
995         u32 vmentry_ctrl;
996 } vmcs_config;
997
998 static struct vmx_capability {
999         u32 ept;
1000         u32 vpid;
1001 } vmx_capability;
1002
1003 #define VMX_SEGMENT_FIELD(seg)                                  \
1004         [VCPU_SREG_##seg] = {                                   \
1005                 .selector = GUEST_##seg##_SELECTOR,             \
1006                 .base = GUEST_##seg##_BASE,                     \
1007                 .limit = GUEST_##seg##_LIMIT,                   \
1008                 .ar_bytes = GUEST_##seg##_AR_BYTES,             \
1009         }
1010
1011 static const struct kvm_vmx_segment_field {
1012         unsigned selector;
1013         unsigned base;
1014         unsigned limit;
1015         unsigned ar_bytes;
1016 } kvm_vmx_segment_fields[] = {
1017         VMX_SEGMENT_FIELD(CS),
1018         VMX_SEGMENT_FIELD(DS),
1019         VMX_SEGMENT_FIELD(ES),
1020         VMX_SEGMENT_FIELD(FS),
1021         VMX_SEGMENT_FIELD(GS),
1022         VMX_SEGMENT_FIELD(SS),
1023         VMX_SEGMENT_FIELD(TR),
1024         VMX_SEGMENT_FIELD(LDTR),
1025 };
1026
1027 static u64 host_efer;
1028
1029 static void ept_save_pdptrs(struct kvm_vcpu *vcpu);
1030
1031 /*
1032  * Keep MSR_STAR at the end, as setup_msrs() will try to optimize it
1033  * away by decrementing the array size.
1034  */
1035 static const u32 vmx_msr_index[] = {
1036 #ifdef CONFIG_X86_64
1037         MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
1038 #endif
1039         MSR_EFER, MSR_TSC_AUX, MSR_STAR,
1040 };
1041
1042 static inline bool is_exception_n(u32 intr_info, u8 vector)
1043 {
1044         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1045                              INTR_INFO_VALID_MASK)) ==
1046                 (INTR_TYPE_HARD_EXCEPTION | vector | INTR_INFO_VALID_MASK);
1047 }
1048
1049 static inline bool is_debug(u32 intr_info)
1050 {
1051         return is_exception_n(intr_info, DB_VECTOR);
1052 }
1053
1054 static inline bool is_breakpoint(u32 intr_info)
1055 {
1056         return is_exception_n(intr_info, BP_VECTOR);
1057 }
1058
1059 static inline bool is_page_fault(u32 intr_info)
1060 {
1061         return is_exception_n(intr_info, PF_VECTOR);
1062 }
1063
1064 static inline bool is_no_device(u32 intr_info)
1065 {
1066         return is_exception_n(intr_info, NM_VECTOR);
1067 }
1068
1069 static inline bool is_invalid_opcode(u32 intr_info)
1070 {
1071         return is_exception_n(intr_info, UD_VECTOR);
1072 }
1073
1074 static inline bool is_external_interrupt(u32 intr_info)
1075 {
1076         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1077                 == (INTR_TYPE_EXT_INTR | INTR_INFO_VALID_MASK);
1078 }
1079
1080 static inline bool is_machine_check(u32 intr_info)
1081 {
1082         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1083                              INTR_INFO_VALID_MASK)) ==
1084                 (INTR_TYPE_HARD_EXCEPTION | MC_VECTOR | INTR_INFO_VALID_MASK);
1085 }
1086
1087 static inline bool cpu_has_vmx_msr_bitmap(void)
1088 {
1089         return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_USE_MSR_BITMAPS;
1090 }
1091
1092 static inline bool cpu_has_vmx_tpr_shadow(void)
1093 {
1094         return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW;
1095 }
1096
1097 static inline bool cpu_need_tpr_shadow(struct kvm_vcpu *vcpu)
1098 {
1099         return cpu_has_vmx_tpr_shadow() && lapic_in_kernel(vcpu);
1100 }
1101
1102 static inline bool cpu_has_secondary_exec_ctrls(void)
1103 {
1104         return vmcs_config.cpu_based_exec_ctrl &
1105                 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
1106 }
1107
1108 static inline bool cpu_has_vmx_virtualize_apic_accesses(void)
1109 {
1110         return vmcs_config.cpu_based_2nd_exec_ctrl &
1111                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
1112 }
1113
1114 static inline bool cpu_has_vmx_virtualize_x2apic_mode(void)
1115 {
1116         return vmcs_config.cpu_based_2nd_exec_ctrl &
1117                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
1118 }
1119
1120 static inline bool cpu_has_vmx_apic_register_virt(void)
1121 {
1122         return vmcs_config.cpu_based_2nd_exec_ctrl &
1123                 SECONDARY_EXEC_APIC_REGISTER_VIRT;
1124 }
1125
1126 static inline bool cpu_has_vmx_virtual_intr_delivery(void)
1127 {
1128         return vmcs_config.cpu_based_2nd_exec_ctrl &
1129                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY;
1130 }
1131
1132 /*
1133  * Comment's format: document - errata name - stepping - processor name.
1134  * Refer from
1135  * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
1136  */
1137 static u32 vmx_preemption_cpu_tfms[] = {
1138 /* 323344.pdf - BA86   - D0 - Xeon 7500 Series */
1139 0x000206E6,
1140 /* 323056.pdf - AAX65  - C2 - Xeon L3406 */
1141 /* 322814.pdf - AAT59  - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
1142 /* 322911.pdf - AAU65  - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
1143 0x00020652,
1144 /* 322911.pdf - AAU65  - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
1145 0x00020655,
1146 /* 322373.pdf - AAO95  - B1 - Xeon 3400 Series */
1147 /* 322166.pdf - AAN92  - B1 - i7-800 and i5-700 Desktop */
1148 /*
1149  * 320767.pdf - AAP86  - B1 -
1150  * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
1151  */
1152 0x000106E5,
1153 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
1154 0x000106A0,
1155 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
1156 0x000106A1,
1157 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
1158 0x000106A4,
1159  /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
1160  /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
1161  /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
1162 0x000106A5,
1163 };
1164
1165 static inline bool cpu_has_broken_vmx_preemption_timer(void)
1166 {
1167         u32 eax = cpuid_eax(0x00000001), i;
1168
1169         /* Clear the reserved bits */
1170         eax &= ~(0x3U << 14 | 0xfU << 28);
1171         for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
1172                 if (eax == vmx_preemption_cpu_tfms[i])
1173                         return true;
1174
1175         return false;
1176 }
1177
1178 static inline bool cpu_has_vmx_preemption_timer(void)
1179 {
1180         return vmcs_config.pin_based_exec_ctrl &
1181                 PIN_BASED_VMX_PREEMPTION_TIMER;
1182 }
1183
1184 static inline bool cpu_has_vmx_posted_intr(void)
1185 {
1186         return IS_ENABLED(CONFIG_X86_LOCAL_APIC) &&
1187                 vmcs_config.pin_based_exec_ctrl & PIN_BASED_POSTED_INTR;
1188 }
1189
1190 static inline bool cpu_has_vmx_apicv(void)
1191 {
1192         return cpu_has_vmx_apic_register_virt() &&
1193                 cpu_has_vmx_virtual_intr_delivery() &&
1194                 cpu_has_vmx_posted_intr();
1195 }
1196
1197 static inline bool cpu_has_vmx_flexpriority(void)
1198 {
1199         return cpu_has_vmx_tpr_shadow() &&
1200                 cpu_has_vmx_virtualize_apic_accesses();
1201 }
1202
1203 static inline bool cpu_has_vmx_ept_execute_only(void)
1204 {
1205         return vmx_capability.ept & VMX_EPT_EXECUTE_ONLY_BIT;
1206 }
1207
1208 static inline bool cpu_has_vmx_ept_2m_page(void)
1209 {
1210         return vmx_capability.ept & VMX_EPT_2MB_PAGE_BIT;
1211 }
1212
1213 static inline bool cpu_has_vmx_ept_1g_page(void)
1214 {
1215         return vmx_capability.ept & VMX_EPT_1GB_PAGE_BIT;
1216 }
1217
1218 static inline bool cpu_has_vmx_ept_4levels(void)
1219 {
1220         return vmx_capability.ept & VMX_EPT_PAGE_WALK_4_BIT;
1221 }
1222
1223 static inline bool cpu_has_vmx_ept_mt_wb(void)
1224 {
1225         return vmx_capability.ept & VMX_EPTP_WB_BIT;
1226 }
1227
1228 static inline bool cpu_has_vmx_ept_5levels(void)
1229 {
1230         return vmx_capability.ept & VMX_EPT_PAGE_WALK_5_BIT;
1231 }
1232
1233 static inline bool cpu_has_vmx_ept_ad_bits(void)
1234 {
1235         return vmx_capability.ept & VMX_EPT_AD_BIT;
1236 }
1237
1238 static inline bool cpu_has_vmx_invept_context(void)
1239 {
1240         return vmx_capability.ept & VMX_EPT_EXTENT_CONTEXT_BIT;
1241 }
1242
1243 static inline bool cpu_has_vmx_invept_global(void)
1244 {
1245         return vmx_capability.ept & VMX_EPT_EXTENT_GLOBAL_BIT;
1246 }
1247
1248 static inline bool cpu_has_vmx_invvpid_single(void)
1249 {
1250         return vmx_capability.vpid & VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT;
1251 }
1252
1253 static inline bool cpu_has_vmx_invvpid_global(void)
1254 {
1255         return vmx_capability.vpid & VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT;
1256 }
1257
1258 static inline bool cpu_has_vmx_invvpid(void)
1259 {
1260         return vmx_capability.vpid & VMX_VPID_INVVPID_BIT;
1261 }
1262
1263 static inline bool cpu_has_vmx_ept(void)
1264 {
1265         return vmcs_config.cpu_based_2nd_exec_ctrl &
1266                 SECONDARY_EXEC_ENABLE_EPT;
1267 }
1268
1269 static inline bool cpu_has_vmx_unrestricted_guest(void)
1270 {
1271         return vmcs_config.cpu_based_2nd_exec_ctrl &
1272                 SECONDARY_EXEC_UNRESTRICTED_GUEST;
1273 }
1274
1275 static inline bool cpu_has_vmx_ple(void)
1276 {
1277         return vmcs_config.cpu_based_2nd_exec_ctrl &
1278                 SECONDARY_EXEC_PAUSE_LOOP_EXITING;
1279 }
1280
1281 static inline bool cpu_has_vmx_basic_inout(void)
1282 {
1283         return  (((u64)vmcs_config.basic_cap << 32) & VMX_BASIC_INOUT);
1284 }
1285
1286 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
1287 {
1288         return flexpriority_enabled && lapic_in_kernel(vcpu);
1289 }
1290
1291 static inline bool cpu_has_vmx_vpid(void)
1292 {
1293         return vmcs_config.cpu_based_2nd_exec_ctrl &
1294                 SECONDARY_EXEC_ENABLE_VPID;
1295 }
1296
1297 static inline bool cpu_has_vmx_rdtscp(void)
1298 {
1299         return vmcs_config.cpu_based_2nd_exec_ctrl &
1300                 SECONDARY_EXEC_RDTSCP;
1301 }
1302
1303 static inline bool cpu_has_vmx_invpcid(void)
1304 {
1305         return vmcs_config.cpu_based_2nd_exec_ctrl &
1306                 SECONDARY_EXEC_ENABLE_INVPCID;
1307 }
1308
1309 static inline bool cpu_has_virtual_nmis(void)
1310 {
1311         return vmcs_config.pin_based_exec_ctrl & PIN_BASED_VIRTUAL_NMIS;
1312 }
1313
1314 static inline bool cpu_has_vmx_wbinvd_exit(void)
1315 {
1316         return vmcs_config.cpu_based_2nd_exec_ctrl &
1317                 SECONDARY_EXEC_WBINVD_EXITING;
1318 }
1319
1320 static inline bool cpu_has_vmx_shadow_vmcs(void)
1321 {
1322         u64 vmx_msr;
1323         rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
1324         /* check if the cpu supports writing r/o exit information fields */
1325         if (!(vmx_msr & MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS))
1326                 return false;
1327
1328         return vmcs_config.cpu_based_2nd_exec_ctrl &
1329                 SECONDARY_EXEC_SHADOW_VMCS;
1330 }
1331
1332 static inline bool cpu_has_vmx_pml(void)
1333 {
1334         return vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_ENABLE_PML;
1335 }
1336
1337 static inline bool cpu_has_vmx_tsc_scaling(void)
1338 {
1339         return vmcs_config.cpu_based_2nd_exec_ctrl &
1340                 SECONDARY_EXEC_TSC_SCALING;
1341 }
1342
1343 static inline bool cpu_has_vmx_vmfunc(void)
1344 {
1345         return vmcs_config.cpu_based_2nd_exec_ctrl &
1346                 SECONDARY_EXEC_ENABLE_VMFUNC;
1347 }
1348
1349 static inline bool report_flexpriority(void)
1350 {
1351         return flexpriority_enabled;
1352 }
1353
1354 static inline unsigned nested_cpu_vmx_misc_cr3_count(struct kvm_vcpu *vcpu)
1355 {
1356         return vmx_misc_cr3_count(to_vmx(vcpu)->nested.nested_vmx_misc_low);
1357 }
1358
1359 static inline bool nested_cpu_has(struct vmcs12 *vmcs12, u32 bit)
1360 {
1361         return vmcs12->cpu_based_vm_exec_control & bit;
1362 }
1363
1364 static inline bool nested_cpu_has2(struct vmcs12 *vmcs12, u32 bit)
1365 {
1366         return (vmcs12->cpu_based_vm_exec_control &
1367                         CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
1368                 (vmcs12->secondary_vm_exec_control & bit);
1369 }
1370
1371 static inline bool nested_cpu_has_preemption_timer(struct vmcs12 *vmcs12)
1372 {
1373         return vmcs12->pin_based_vm_exec_control &
1374                 PIN_BASED_VMX_PREEMPTION_TIMER;
1375 }
1376
1377 static inline int nested_cpu_has_ept(struct vmcs12 *vmcs12)
1378 {
1379         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_EPT);
1380 }
1381
1382 static inline bool nested_cpu_has_xsaves(struct vmcs12 *vmcs12)
1383 {
1384         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
1385 }
1386
1387 static inline bool nested_cpu_has_pml(struct vmcs12 *vmcs12)
1388 {
1389         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_PML);
1390 }
1391
1392 static inline bool nested_cpu_has_virt_x2apic_mode(struct vmcs12 *vmcs12)
1393 {
1394         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
1395 }
1396
1397 static inline bool nested_cpu_has_vpid(struct vmcs12 *vmcs12)
1398 {
1399         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VPID);
1400 }
1401
1402 static inline bool nested_cpu_has_apic_reg_virt(struct vmcs12 *vmcs12)
1403 {
1404         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_APIC_REGISTER_VIRT);
1405 }
1406
1407 static inline bool nested_cpu_has_vid(struct vmcs12 *vmcs12)
1408 {
1409         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
1410 }
1411
1412 static inline bool nested_cpu_has_posted_intr(struct vmcs12 *vmcs12)
1413 {
1414         return vmcs12->pin_based_vm_exec_control & PIN_BASED_POSTED_INTR;
1415 }
1416
1417 static inline bool nested_cpu_has_vmfunc(struct vmcs12 *vmcs12)
1418 {
1419         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VMFUNC);
1420 }
1421
1422 static inline bool nested_cpu_has_eptp_switching(struct vmcs12 *vmcs12)
1423 {
1424         return nested_cpu_has_vmfunc(vmcs12) &&
1425                 (vmcs12->vm_function_control &
1426                  VMX_VMFUNC_EPTP_SWITCHING);
1427 }
1428
1429 static inline bool is_nmi(u32 intr_info)
1430 {
1431         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1432                 == (INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK);
1433 }
1434
1435 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
1436                               u32 exit_intr_info,
1437                               unsigned long exit_qualification);
1438 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
1439                         struct vmcs12 *vmcs12,
1440                         u32 reason, unsigned long qualification);
1441
1442 static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
1443 {
1444         int i;
1445
1446         for (i = 0; i < vmx->nmsrs; ++i)
1447                 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
1448                         return i;
1449         return -1;
1450 }
1451
1452 static inline void __invvpid(int ext, u16 vpid, gva_t gva)
1453 {
1454     struct {
1455         u64 vpid : 16;
1456         u64 rsvd : 48;
1457         u64 gva;
1458     } operand = { vpid, 0, gva };
1459
1460     asm volatile (__ex(ASM_VMX_INVVPID)
1461                   /* CF==1 or ZF==1 --> rc = -1 */
1462                   "; ja 1f ; ud2 ; 1:"
1463                   : : "a"(&operand), "c"(ext) : "cc", "memory");
1464 }
1465
1466 static inline void __invept(int ext, u64 eptp, gpa_t gpa)
1467 {
1468         struct {
1469                 u64 eptp, gpa;
1470         } operand = {eptp, gpa};
1471
1472         asm volatile (__ex(ASM_VMX_INVEPT)
1473                         /* CF==1 or ZF==1 --> rc = -1 */
1474                         "; ja 1f ; ud2 ; 1:\n"
1475                         : : "a" (&operand), "c" (ext) : "cc", "memory");
1476 }
1477
1478 static struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
1479 {
1480         int i;
1481
1482         i = __find_msr_index(vmx, msr);
1483         if (i >= 0)
1484                 return &vmx->guest_msrs[i];
1485         return NULL;
1486 }
1487
1488 static void vmcs_clear(struct vmcs *vmcs)
1489 {
1490         u64 phys_addr = __pa(vmcs);
1491         u8 error;
1492
1493         asm volatile (__ex(ASM_VMX_VMCLEAR_RAX) "; setna %0"
1494                       : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
1495                       : "cc", "memory");
1496         if (error)
1497                 printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n",
1498                        vmcs, phys_addr);
1499 }
1500
1501 static inline void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
1502 {
1503         vmcs_clear(loaded_vmcs->vmcs);
1504         if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
1505                 vmcs_clear(loaded_vmcs->shadow_vmcs);
1506         loaded_vmcs->cpu = -1;
1507         loaded_vmcs->launched = 0;
1508 }
1509
1510 static void vmcs_load(struct vmcs *vmcs)
1511 {
1512         u64 phys_addr = __pa(vmcs);
1513         u8 error;
1514
1515         asm volatile (__ex(ASM_VMX_VMPTRLD_RAX) "; setna %0"
1516                         : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
1517                         : "cc", "memory");
1518         if (error)
1519                 printk(KERN_ERR "kvm: vmptrld %p/%llx failed\n",
1520                        vmcs, phys_addr);
1521 }
1522
1523 #ifdef CONFIG_KEXEC_CORE
1524 /*
1525  * This bitmap is used to indicate whether the vmclear
1526  * operation is enabled on all cpus. All disabled by
1527  * default.
1528  */
1529 static cpumask_t crash_vmclear_enabled_bitmap = CPU_MASK_NONE;
1530
1531 static inline void crash_enable_local_vmclear(int cpu)
1532 {
1533         cpumask_set_cpu(cpu, &crash_vmclear_enabled_bitmap);
1534 }
1535
1536 static inline void crash_disable_local_vmclear(int cpu)
1537 {
1538         cpumask_clear_cpu(cpu, &crash_vmclear_enabled_bitmap);
1539 }
1540
1541 static inline int crash_local_vmclear_enabled(int cpu)
1542 {
1543         return cpumask_test_cpu(cpu, &crash_vmclear_enabled_bitmap);
1544 }
1545
1546 static void crash_vmclear_local_loaded_vmcss(void)
1547 {
1548         int cpu = raw_smp_processor_id();
1549         struct loaded_vmcs *v;
1550
1551         if (!crash_local_vmclear_enabled(cpu))
1552                 return;
1553
1554         list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
1555                             loaded_vmcss_on_cpu_link)
1556                 vmcs_clear(v->vmcs);
1557 }
1558 #else
1559 static inline void crash_enable_local_vmclear(int cpu) { }
1560 static inline void crash_disable_local_vmclear(int cpu) { }
1561 #endif /* CONFIG_KEXEC_CORE */
1562
1563 static void __loaded_vmcs_clear(void *arg)
1564 {
1565         struct loaded_vmcs *loaded_vmcs = arg;
1566         int cpu = raw_smp_processor_id();
1567
1568         if (loaded_vmcs->cpu != cpu)
1569                 return; /* vcpu migration can race with cpu offline */
1570         if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
1571                 per_cpu(current_vmcs, cpu) = NULL;
1572         crash_disable_local_vmclear(cpu);
1573         list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
1574
1575         /*
1576          * we should ensure updating loaded_vmcs->loaded_vmcss_on_cpu_link
1577          * is before setting loaded_vmcs->vcpu to -1 which is done in
1578          * loaded_vmcs_init. Otherwise, other cpu can see vcpu = -1 fist
1579          * then adds the vmcs into percpu list before it is deleted.
1580          */
1581         smp_wmb();
1582
1583         loaded_vmcs_init(loaded_vmcs);
1584         crash_enable_local_vmclear(cpu);
1585 }
1586
1587 static void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
1588 {
1589         int cpu = loaded_vmcs->cpu;
1590
1591         if (cpu != -1)
1592                 smp_call_function_single(cpu,
1593                          __loaded_vmcs_clear, loaded_vmcs, 1);
1594 }
1595
1596 static inline void vpid_sync_vcpu_single(int vpid)
1597 {
1598         if (vpid == 0)
1599                 return;
1600
1601         if (cpu_has_vmx_invvpid_single())
1602                 __invvpid(VMX_VPID_EXTENT_SINGLE_CONTEXT, vpid, 0);
1603 }
1604
1605 static inline void vpid_sync_vcpu_global(void)
1606 {
1607         if (cpu_has_vmx_invvpid_global())
1608                 __invvpid(VMX_VPID_EXTENT_ALL_CONTEXT, 0, 0);
1609 }
1610
1611 static inline void vpid_sync_context(int vpid)
1612 {
1613         if (cpu_has_vmx_invvpid_single())
1614                 vpid_sync_vcpu_single(vpid);
1615         else
1616                 vpid_sync_vcpu_global();
1617 }
1618
1619 static inline void ept_sync_global(void)
1620 {
1621         __invept(VMX_EPT_EXTENT_GLOBAL, 0, 0);
1622 }
1623
1624 static inline void ept_sync_context(u64 eptp)
1625 {
1626         if (cpu_has_vmx_invept_context())
1627                 __invept(VMX_EPT_EXTENT_CONTEXT, eptp, 0);
1628         else
1629                 ept_sync_global();
1630 }
1631
1632 static __always_inline void vmcs_check16(unsigned long field)
1633 {
1634         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
1635                          "16-bit accessor invalid for 64-bit field");
1636         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
1637                          "16-bit accessor invalid for 64-bit high field");
1638         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
1639                          "16-bit accessor invalid for 32-bit high field");
1640         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
1641                          "16-bit accessor invalid for natural width field");
1642 }
1643
1644 static __always_inline void vmcs_check32(unsigned long field)
1645 {
1646         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
1647                          "32-bit accessor invalid for 16-bit field");
1648         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
1649                          "32-bit accessor invalid for natural width field");
1650 }
1651
1652 static __always_inline void vmcs_check64(unsigned long field)
1653 {
1654         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
1655                          "64-bit accessor invalid for 16-bit field");
1656         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
1657                          "64-bit accessor invalid for 64-bit high field");
1658         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
1659                          "64-bit accessor invalid for 32-bit field");
1660         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
1661                          "64-bit accessor invalid for natural width field");
1662 }
1663
1664 static __always_inline void vmcs_checkl(unsigned long field)
1665 {
1666         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
1667                          "Natural width accessor invalid for 16-bit field");
1668         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
1669                          "Natural width accessor invalid for 64-bit field");
1670         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
1671                          "Natural width accessor invalid for 64-bit high field");
1672         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
1673                          "Natural width accessor invalid for 32-bit field");
1674 }
1675
1676 static __always_inline unsigned long __vmcs_readl(unsigned long field)
1677 {
1678         unsigned long value;
1679
1680         asm volatile (__ex_clear(ASM_VMX_VMREAD_RDX_RAX, "%0")
1681                       : "=a"(value) : "d"(field) : "cc");
1682         return value;
1683 }
1684
1685 static __always_inline u16 vmcs_read16(unsigned long field)
1686 {
1687         vmcs_check16(field);
1688         return __vmcs_readl(field);
1689 }
1690
1691 static __always_inline u32 vmcs_read32(unsigned long field)
1692 {
1693         vmcs_check32(field);
1694         return __vmcs_readl(field);
1695 }
1696
1697 static __always_inline u64 vmcs_read64(unsigned long field)
1698 {
1699         vmcs_check64(field);
1700 #ifdef CONFIG_X86_64
1701         return __vmcs_readl(field);
1702 #else
1703         return __vmcs_readl(field) | ((u64)__vmcs_readl(field+1) << 32);
1704 #endif
1705 }
1706
1707 static __always_inline unsigned long vmcs_readl(unsigned long field)
1708 {
1709         vmcs_checkl(field);
1710         return __vmcs_readl(field);
1711 }
1712
1713 static noinline void vmwrite_error(unsigned long field, unsigned long value)
1714 {
1715         printk(KERN_ERR "vmwrite error: reg %lx value %lx (err %d)\n",
1716                field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
1717         dump_stack();
1718 }
1719
1720 static __always_inline void __vmcs_writel(unsigned long field, unsigned long value)
1721 {
1722         u8 error;
1723
1724         asm volatile (__ex(ASM_VMX_VMWRITE_RAX_RDX) "; setna %0"
1725                        : "=q"(error) : "a"(value), "d"(field) : "cc");
1726         if (unlikely(error))
1727                 vmwrite_error(field, value);
1728 }
1729
1730 static __always_inline void vmcs_write16(unsigned long field, u16 value)
1731 {
1732         vmcs_check16(field);
1733         __vmcs_writel(field, value);
1734 }
1735
1736 static __always_inline void vmcs_write32(unsigned long field, u32 value)
1737 {
1738         vmcs_check32(field);
1739         __vmcs_writel(field, value);
1740 }
1741
1742 static __always_inline void vmcs_write64(unsigned long field, u64 value)
1743 {
1744         vmcs_check64(field);
1745         __vmcs_writel(field, value);
1746 #ifndef CONFIG_X86_64
1747         asm volatile ("");
1748         __vmcs_writel(field+1, value >> 32);
1749 #endif
1750 }
1751
1752 static __always_inline void vmcs_writel(unsigned long field, unsigned long value)
1753 {
1754         vmcs_checkl(field);
1755         __vmcs_writel(field, value);
1756 }
1757
1758 static __always_inline void vmcs_clear_bits(unsigned long field, u32 mask)
1759 {
1760         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
1761                          "vmcs_clear_bits does not support 64-bit fields");
1762         __vmcs_writel(field, __vmcs_readl(field) & ~mask);
1763 }
1764
1765 static __always_inline void vmcs_set_bits(unsigned long field, u32 mask)
1766 {
1767         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
1768                          "vmcs_set_bits does not support 64-bit fields");
1769         __vmcs_writel(field, __vmcs_readl(field) | mask);
1770 }
1771
1772 static inline void vm_entry_controls_reset_shadow(struct vcpu_vmx *vmx)
1773 {
1774         vmx->vm_entry_controls_shadow = vmcs_read32(VM_ENTRY_CONTROLS);
1775 }
1776
1777 static inline void vm_entry_controls_init(struct vcpu_vmx *vmx, u32 val)
1778 {
1779         vmcs_write32(VM_ENTRY_CONTROLS, val);
1780         vmx->vm_entry_controls_shadow = val;
1781 }
1782
1783 static inline void vm_entry_controls_set(struct vcpu_vmx *vmx, u32 val)
1784 {
1785         if (vmx->vm_entry_controls_shadow != val)
1786                 vm_entry_controls_init(vmx, val);
1787 }
1788
1789 static inline u32 vm_entry_controls_get(struct vcpu_vmx *vmx)
1790 {
1791         return vmx->vm_entry_controls_shadow;
1792 }
1793
1794
1795 static inline void vm_entry_controls_setbit(struct vcpu_vmx *vmx, u32 val)
1796 {
1797         vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) | val);
1798 }
1799
1800 static inline void vm_entry_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
1801 {
1802         vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) & ~val);
1803 }
1804
1805 static inline void vm_exit_controls_reset_shadow(struct vcpu_vmx *vmx)
1806 {
1807         vmx->vm_exit_controls_shadow = vmcs_read32(VM_EXIT_CONTROLS);
1808 }
1809
1810 static inline void vm_exit_controls_init(struct vcpu_vmx *vmx, u32 val)
1811 {
1812         vmcs_write32(VM_EXIT_CONTROLS, val);
1813         vmx->vm_exit_controls_shadow = val;
1814 }
1815
1816 static inline void vm_exit_controls_set(struct vcpu_vmx *vmx, u32 val)
1817 {
1818         if (vmx->vm_exit_controls_shadow != val)
1819                 vm_exit_controls_init(vmx, val);
1820 }
1821
1822 static inline u32 vm_exit_controls_get(struct vcpu_vmx *vmx)
1823 {
1824         return vmx->vm_exit_controls_shadow;
1825 }
1826
1827
1828 static inline void vm_exit_controls_setbit(struct vcpu_vmx *vmx, u32 val)
1829 {
1830         vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) | val);
1831 }
1832
1833 static inline void vm_exit_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
1834 {
1835         vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) & ~val);
1836 }
1837
1838 static void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
1839 {
1840         vmx->segment_cache.bitmask = 0;
1841 }
1842
1843 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
1844                                        unsigned field)
1845 {
1846         bool ret;
1847         u32 mask = 1 << (seg * SEG_FIELD_NR + field);
1848
1849         if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
1850                 vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
1851                 vmx->segment_cache.bitmask = 0;
1852         }
1853         ret = vmx->segment_cache.bitmask & mask;
1854         vmx->segment_cache.bitmask |= mask;
1855         return ret;
1856 }
1857
1858 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
1859 {
1860         u16 *p = &vmx->segment_cache.seg[seg].selector;
1861
1862         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
1863                 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
1864         return *p;
1865 }
1866
1867 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
1868 {
1869         ulong *p = &vmx->segment_cache.seg[seg].base;
1870
1871         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
1872                 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
1873         return *p;
1874 }
1875
1876 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
1877 {
1878         u32 *p = &vmx->segment_cache.seg[seg].limit;
1879
1880         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
1881                 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
1882         return *p;
1883 }
1884
1885 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
1886 {
1887         u32 *p = &vmx->segment_cache.seg[seg].ar;
1888
1889         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
1890                 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
1891         return *p;
1892 }
1893
1894 static void update_exception_bitmap(struct kvm_vcpu *vcpu)
1895 {
1896         u32 eb;
1897
1898         eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
1899              (1u << DB_VECTOR) | (1u << AC_VECTOR);
1900         if ((vcpu->guest_debug &
1901              (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
1902             (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
1903                 eb |= 1u << BP_VECTOR;
1904         if (to_vmx(vcpu)->rmode.vm86_active)
1905                 eb = ~0;
1906         if (enable_ept)
1907                 eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
1908
1909         /* When we are running a nested L2 guest and L1 specified for it a
1910          * certain exception bitmap, we must trap the same exceptions and pass
1911          * them to L1. When running L2, we will only handle the exceptions
1912          * specified above if L1 did not want them.
1913          */
1914         if (is_guest_mode(vcpu))
1915                 eb |= get_vmcs12(vcpu)->exception_bitmap;
1916
1917         vmcs_write32(EXCEPTION_BITMAP, eb);
1918 }
1919
1920 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
1921                 unsigned long entry, unsigned long exit)
1922 {
1923         vm_entry_controls_clearbit(vmx, entry);
1924         vm_exit_controls_clearbit(vmx, exit);
1925 }
1926
1927 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
1928 {
1929         unsigned i;
1930         struct msr_autoload *m = &vmx->msr_autoload;
1931
1932         switch (msr) {
1933         case MSR_EFER:
1934                 if (cpu_has_load_ia32_efer) {
1935                         clear_atomic_switch_msr_special(vmx,
1936                                         VM_ENTRY_LOAD_IA32_EFER,
1937                                         VM_EXIT_LOAD_IA32_EFER);
1938                         return;
1939                 }
1940                 break;
1941         case MSR_CORE_PERF_GLOBAL_CTRL:
1942                 if (cpu_has_load_perf_global_ctrl) {
1943                         clear_atomic_switch_msr_special(vmx,
1944                                         VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
1945                                         VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
1946                         return;
1947                 }
1948                 break;
1949         }
1950
1951         for (i = 0; i < m->nr; ++i)
1952                 if (m->guest[i].index == msr)
1953                         break;
1954
1955         if (i == m->nr)
1956                 return;
1957         --m->nr;
1958         m->guest[i] = m->guest[m->nr];
1959         m->host[i] = m->host[m->nr];
1960         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
1961         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
1962 }
1963
1964 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
1965                 unsigned long entry, unsigned long exit,
1966                 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
1967                 u64 guest_val, u64 host_val)
1968 {
1969         vmcs_write64(guest_val_vmcs, guest_val);
1970         vmcs_write64(host_val_vmcs, host_val);
1971         vm_entry_controls_setbit(vmx, entry);
1972         vm_exit_controls_setbit(vmx, exit);
1973 }
1974
1975 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
1976                                   u64 guest_val, u64 host_val)
1977 {
1978         unsigned i;
1979         struct msr_autoload *m = &vmx->msr_autoload;
1980
1981         switch (msr) {
1982         case MSR_EFER:
1983                 if (cpu_has_load_ia32_efer) {
1984                         add_atomic_switch_msr_special(vmx,
1985                                         VM_ENTRY_LOAD_IA32_EFER,
1986                                         VM_EXIT_LOAD_IA32_EFER,
1987                                         GUEST_IA32_EFER,
1988                                         HOST_IA32_EFER,
1989                                         guest_val, host_val);
1990                         return;
1991                 }
1992                 break;
1993         case MSR_CORE_PERF_GLOBAL_CTRL:
1994                 if (cpu_has_load_perf_global_ctrl) {
1995                         add_atomic_switch_msr_special(vmx,
1996                                         VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
1997                                         VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
1998                                         GUEST_IA32_PERF_GLOBAL_CTRL,
1999                                         HOST_IA32_PERF_GLOBAL_CTRL,
2000                                         guest_val, host_val);
2001                         return;
2002                 }
2003                 break;
2004         case MSR_IA32_PEBS_ENABLE:
2005                 /* PEBS needs a quiescent period after being disabled (to write
2006                  * a record).  Disabling PEBS through VMX MSR swapping doesn't
2007                  * provide that period, so a CPU could write host's record into
2008                  * guest's memory.
2009                  */
2010                 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
2011         }
2012
2013         for (i = 0; i < m->nr; ++i)
2014                 if (m->guest[i].index == msr)
2015                         break;
2016
2017         if (i == NR_AUTOLOAD_MSRS) {
2018                 printk_once(KERN_WARNING "Not enough msr switch entries. "
2019                                 "Can't add msr %x\n", msr);
2020                 return;
2021         } else if (i == m->nr) {
2022                 ++m->nr;
2023                 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
2024                 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
2025         }
2026
2027         m->guest[i].index = msr;
2028         m->guest[i].value = guest_val;
2029         m->host[i].index = msr;
2030         m->host[i].value = host_val;
2031 }
2032
2033 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
2034 {
2035         u64 guest_efer = vmx->vcpu.arch.efer;
2036         u64 ignore_bits = 0;
2037
2038         if (!enable_ept) {
2039                 /*
2040                  * NX is needed to handle CR0.WP=1, CR4.SMEP=1.  Testing
2041                  * host CPUID is more efficient than testing guest CPUID
2042                  * or CR4.  Host SMEP is anyway a requirement for guest SMEP.
2043                  */
2044                 if (boot_cpu_has(X86_FEATURE_SMEP))
2045                         guest_efer |= EFER_NX;
2046                 else if (!(guest_efer & EFER_NX))
2047                         ignore_bits |= EFER_NX;
2048         }
2049
2050         /*
2051          * LMA and LME handled by hardware; SCE meaningless outside long mode.
2052          */
2053         ignore_bits |= EFER_SCE;
2054 #ifdef CONFIG_X86_64
2055         ignore_bits |= EFER_LMA | EFER_LME;
2056         /* SCE is meaningful only in long mode on Intel */
2057         if (guest_efer & EFER_LMA)
2058                 ignore_bits &= ~(u64)EFER_SCE;
2059 #endif
2060
2061         clear_atomic_switch_msr(vmx, MSR_EFER);
2062
2063         /*
2064          * On EPT, we can't emulate NX, so we must switch EFER atomically.
2065          * On CPUs that support "load IA32_EFER", always switch EFER
2066          * atomically, since it's faster than switching it manually.
2067          */
2068         if (cpu_has_load_ia32_efer ||
2069             (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
2070                 if (!(guest_efer & EFER_LMA))
2071                         guest_efer &= ~EFER_LME;
2072                 if (guest_efer != host_efer)
2073                         add_atomic_switch_msr(vmx, MSR_EFER,
2074                                               guest_efer, host_efer);
2075                 return false;
2076         } else {
2077                 guest_efer &= ~ignore_bits;
2078                 guest_efer |= host_efer & ignore_bits;
2079
2080                 vmx->guest_msrs[efer_offset].data = guest_efer;
2081                 vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
2082
2083                 return true;
2084         }
2085 }
2086
2087 #ifdef CONFIG_X86_32
2088 /*
2089  * On 32-bit kernels, VM exits still load the FS and GS bases from the
2090  * VMCS rather than the segment table.  KVM uses this helper to figure
2091  * out the current bases to poke them into the VMCS before entry.
2092  */
2093 static unsigned long segment_base(u16 selector)
2094 {
2095         struct desc_struct *table;
2096         unsigned long v;
2097
2098         if (!(selector & ~SEGMENT_RPL_MASK))
2099                 return 0;
2100
2101         table = get_current_gdt_ro();
2102
2103         if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
2104                 u16 ldt_selector = kvm_read_ldt();
2105
2106                 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
2107                         return 0;
2108
2109                 table = (struct desc_struct *)segment_base(ldt_selector);
2110         }
2111         v = get_desc_base(&table[selector >> 3]);
2112         return v;
2113 }
2114 #endif
2115
2116 static void vmx_save_host_state(struct kvm_vcpu *vcpu)
2117 {
2118         struct vcpu_vmx *vmx = to_vmx(vcpu);
2119         int i;
2120
2121         if (vmx->host_state.loaded)
2122                 return;
2123
2124         vmx->host_state.loaded = 1;
2125         /*
2126          * Set host fs and gs selectors.  Unfortunately, 22.2.3 does not
2127          * allow segment selectors with cpl > 0 or ti == 1.
2128          */
2129         vmx->host_state.ldt_sel = kvm_read_ldt();
2130         vmx->host_state.gs_ldt_reload_needed = vmx->host_state.ldt_sel;
2131         savesegment(fs, vmx->host_state.fs_sel);
2132         if (!(vmx->host_state.fs_sel & 7)) {
2133                 vmcs_write16(HOST_FS_SELECTOR, vmx->host_state.fs_sel);
2134                 vmx->host_state.fs_reload_needed = 0;
2135         } else {
2136                 vmcs_write16(HOST_FS_SELECTOR, 0);
2137                 vmx->host_state.fs_reload_needed = 1;
2138         }
2139         savesegment(gs, vmx->host_state.gs_sel);
2140         if (!(vmx->host_state.gs_sel & 7))
2141                 vmcs_write16(HOST_GS_SELECTOR, vmx->host_state.gs_sel);
2142         else {
2143                 vmcs_write16(HOST_GS_SELECTOR, 0);
2144                 vmx->host_state.gs_ldt_reload_needed = 1;
2145         }
2146
2147 #ifdef CONFIG_X86_64
2148         savesegment(ds, vmx->host_state.ds_sel);
2149         savesegment(es, vmx->host_state.es_sel);
2150 #endif
2151
2152 #ifdef CONFIG_X86_64
2153         vmcs_writel(HOST_FS_BASE, read_msr(MSR_FS_BASE));
2154         vmcs_writel(HOST_GS_BASE, read_msr(MSR_GS_BASE));
2155 #else
2156         vmcs_writel(HOST_FS_BASE, segment_base(vmx->host_state.fs_sel));
2157         vmcs_writel(HOST_GS_BASE, segment_base(vmx->host_state.gs_sel));
2158 #endif
2159
2160 #ifdef CONFIG_X86_64
2161         rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
2162         if (is_long_mode(&vmx->vcpu))
2163                 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2164 #endif
2165         if (boot_cpu_has(X86_FEATURE_MPX))
2166                 rdmsrl(MSR_IA32_BNDCFGS, vmx->host_state.msr_host_bndcfgs);
2167         for (i = 0; i < vmx->save_nmsrs; ++i)
2168                 kvm_set_shared_msr(vmx->guest_msrs[i].index,
2169                                    vmx->guest_msrs[i].data,
2170                                    vmx->guest_msrs[i].mask);
2171 }
2172
2173 static void __vmx_load_host_state(struct vcpu_vmx *vmx)
2174 {
2175         if (!vmx->host_state.loaded)
2176                 return;
2177
2178         ++vmx->vcpu.stat.host_state_reload;
2179         vmx->host_state.loaded = 0;
2180 #ifdef CONFIG_X86_64
2181         if (is_long_mode(&vmx->vcpu))
2182                 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2183 #endif
2184         if (vmx->host_state.gs_ldt_reload_needed) {
2185                 kvm_load_ldt(vmx->host_state.ldt_sel);
2186 #ifdef CONFIG_X86_64
2187                 load_gs_index(vmx->host_state.gs_sel);
2188 #else
2189                 loadsegment(gs, vmx->host_state.gs_sel);
2190 #endif
2191         }
2192         if (vmx->host_state.fs_reload_needed)
2193                 loadsegment(fs, vmx->host_state.fs_sel);
2194 #ifdef CONFIG_X86_64
2195         if (unlikely(vmx->host_state.ds_sel | vmx->host_state.es_sel)) {
2196                 loadsegment(ds, vmx->host_state.ds_sel);
2197                 loadsegment(es, vmx->host_state.es_sel);
2198         }
2199 #endif
2200         invalidate_tss_limit();
2201 #ifdef CONFIG_X86_64
2202         wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
2203 #endif
2204         if (vmx->host_state.msr_host_bndcfgs)
2205                 wrmsrl(MSR_IA32_BNDCFGS, vmx->host_state.msr_host_bndcfgs);
2206         load_fixmap_gdt(raw_smp_processor_id());
2207 }
2208
2209 static void vmx_load_host_state(struct vcpu_vmx *vmx)
2210 {
2211         preempt_disable();
2212         __vmx_load_host_state(vmx);
2213         preempt_enable();
2214 }
2215
2216 static void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
2217 {
2218         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
2219         struct pi_desc old, new;
2220         unsigned int dest;
2221
2222         /*
2223          * In case of hot-plug or hot-unplug, we may have to undo
2224          * vmx_vcpu_pi_put even if there is no assigned device.  And we
2225          * always keep PI.NDST up to date for simplicity: it makes the
2226          * code easier, and CPU migration is not a fast path.
2227          */
2228         if (!pi_test_sn(pi_desc) && vcpu->cpu == cpu)
2229                 return;
2230
2231         /*
2232          * First handle the simple case where no cmpxchg is necessary; just
2233          * allow posting non-urgent interrupts.
2234          *
2235          * If the 'nv' field is POSTED_INTR_WAKEUP_VECTOR, do not change
2236          * PI.NDST: pi_post_block will do it for us and the wakeup_handler
2237          * expects the VCPU to be on the blocked_vcpu_list that matches
2238          * PI.NDST.
2239          */
2240         if (pi_desc->nv == POSTED_INTR_WAKEUP_VECTOR ||
2241             vcpu->cpu == cpu) {
2242                 pi_clear_sn(pi_desc);
2243                 return;
2244         }
2245
2246         /* The full case.  */
2247         do {
2248                 old.control = new.control = pi_desc->control;
2249
2250                 dest = cpu_physical_id(cpu);
2251
2252                 if (x2apic_enabled())
2253                         new.ndst = dest;
2254                 else
2255                         new.ndst = (dest << 8) & 0xFF00;
2256
2257                 new.sn = 0;
2258         } while (cmpxchg64(&pi_desc->control, old.control,
2259                            new.control) != old.control);
2260 }
2261
2262 static void decache_tsc_multiplier(struct vcpu_vmx *vmx)
2263 {
2264         vmx->current_tsc_ratio = vmx->vcpu.arch.tsc_scaling_ratio;
2265         vmcs_write64(TSC_MULTIPLIER, vmx->current_tsc_ratio);
2266 }
2267
2268 /*
2269  * Switches to specified vcpu, until a matching vcpu_put(), but assumes
2270  * vcpu mutex is already taken.
2271  */
2272 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2273 {
2274         struct vcpu_vmx *vmx = to_vmx(vcpu);
2275         bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
2276
2277         if (!already_loaded) {
2278                 loaded_vmcs_clear(vmx->loaded_vmcs);
2279                 local_irq_disable();
2280                 crash_disable_local_vmclear(cpu);
2281
2282                 /*
2283                  * Read loaded_vmcs->cpu should be before fetching
2284                  * loaded_vmcs->loaded_vmcss_on_cpu_link.
2285                  * See the comments in __loaded_vmcs_clear().
2286                  */
2287                 smp_rmb();
2288
2289                 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
2290                          &per_cpu(loaded_vmcss_on_cpu, cpu));
2291                 crash_enable_local_vmclear(cpu);
2292                 local_irq_enable();
2293         }
2294
2295         if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
2296                 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
2297                 vmcs_load(vmx->loaded_vmcs->vmcs);
2298         }
2299
2300         if (!already_loaded) {
2301                 void *gdt = get_current_gdt_ro();
2302                 unsigned long sysenter_esp;
2303
2304                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2305
2306                 /*
2307                  * Linux uses per-cpu TSS and GDT, so set these when switching
2308                  * processors.  See 22.2.4.
2309                  */
2310                 vmcs_writel(HOST_TR_BASE,
2311                             (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
2312                 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt);   /* 22.2.4 */
2313
2314                 /*
2315                  * VM exits change the host TR limit to 0x67 after a VM
2316                  * exit.  This is okay, since 0x67 covers everything except
2317                  * the IO bitmap and have have code to handle the IO bitmap
2318                  * being lost after a VM exit.
2319                  */
2320                 BUILD_BUG_ON(IO_BITMAP_OFFSET - 1 != 0x67);
2321
2322                 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
2323                 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
2324
2325                 vmx->loaded_vmcs->cpu = cpu;
2326         }
2327
2328         /* Setup TSC multiplier */
2329         if (kvm_has_tsc_control &&
2330             vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
2331                 decache_tsc_multiplier(vmx);
2332
2333         vmx_vcpu_pi_load(vcpu, cpu);
2334         vmx->host_pkru = read_pkru();
2335 }
2336
2337 static void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
2338 {
2339         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
2340
2341         if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
2342                 !irq_remapping_cap(IRQ_POSTING_CAP)  ||
2343                 !kvm_vcpu_apicv_active(vcpu))
2344                 return;
2345
2346         /* Set SN when the vCPU is preempted */
2347         if (vcpu->preempted)
2348                 pi_set_sn(pi_desc);
2349 }
2350
2351 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
2352 {
2353         vmx_vcpu_pi_put(vcpu);
2354
2355         __vmx_load_host_state(to_vmx(vcpu));
2356 }
2357
2358 static bool emulation_required(struct kvm_vcpu *vcpu)
2359 {
2360         return emulate_invalid_guest_state && !guest_state_valid(vcpu);
2361 }
2362
2363 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
2364
2365 /*
2366  * Return the cr0 value that a nested guest would read. This is a combination
2367  * of the real cr0 used to run the guest (guest_cr0), and the bits shadowed by
2368  * its hypervisor (cr0_read_shadow).
2369  */
2370 static inline unsigned long nested_read_cr0(struct vmcs12 *fields)
2371 {
2372         return (fields->guest_cr0 & ~fields->cr0_guest_host_mask) |
2373                 (fields->cr0_read_shadow & fields->cr0_guest_host_mask);
2374 }
2375 static inline unsigned long nested_read_cr4(struct vmcs12 *fields)
2376 {
2377         return (fields->guest_cr4 & ~fields->cr4_guest_host_mask) |
2378                 (fields->cr4_read_shadow & fields->cr4_guest_host_mask);
2379 }
2380
2381 static unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
2382 {
2383         unsigned long rflags, save_rflags;
2384
2385         if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
2386                 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
2387                 rflags = vmcs_readl(GUEST_RFLAGS);
2388                 if (to_vmx(vcpu)->rmode.vm86_active) {
2389                         rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2390                         save_rflags = to_vmx(vcpu)->rmode.save_rflags;
2391                         rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2392                 }
2393                 to_vmx(vcpu)->rflags = rflags;
2394         }
2395         return to_vmx(vcpu)->rflags;
2396 }
2397
2398 static void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
2399 {
2400         unsigned long old_rflags = vmx_get_rflags(vcpu);
2401
2402         __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
2403         to_vmx(vcpu)->rflags = rflags;
2404         if (to_vmx(vcpu)->rmode.vm86_active) {
2405                 to_vmx(vcpu)->rmode.save_rflags = rflags;
2406                 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2407         }
2408         vmcs_writel(GUEST_RFLAGS, rflags);
2409
2410         if ((old_rflags ^ to_vmx(vcpu)->rflags) & X86_EFLAGS_VM)
2411                 to_vmx(vcpu)->emulation_required = emulation_required(vcpu);
2412 }
2413
2414 static u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
2415 {
2416         u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
2417         int ret = 0;
2418
2419         if (interruptibility & GUEST_INTR_STATE_STI)
2420                 ret |= KVM_X86_SHADOW_INT_STI;
2421         if (interruptibility & GUEST_INTR_STATE_MOV_SS)
2422                 ret |= KVM_X86_SHADOW_INT_MOV_SS;
2423
2424         return ret;
2425 }
2426
2427 static void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
2428 {
2429         u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
2430         u32 interruptibility = interruptibility_old;
2431
2432         interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
2433
2434         if (mask & KVM_X86_SHADOW_INT_MOV_SS)
2435                 interruptibility |= GUEST_INTR_STATE_MOV_SS;
2436         else if (mask & KVM_X86_SHADOW_INT_STI)
2437                 interruptibility |= GUEST_INTR_STATE_STI;
2438
2439         if ((interruptibility != interruptibility_old))
2440                 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
2441 }
2442
2443 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
2444 {
2445         unsigned long rip;
2446
2447         rip = kvm_rip_read(vcpu);
2448         rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
2449         kvm_rip_write(vcpu, rip);
2450
2451         /* skipping an emulated instruction also counts */
2452         vmx_set_interrupt_shadow(vcpu, 0);
2453 }
2454
2455 static void nested_vmx_inject_exception_vmexit(struct kvm_vcpu *vcpu,
2456                                                unsigned long exit_qual)
2457 {
2458         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
2459         unsigned int nr = vcpu->arch.exception.nr;
2460         u32 intr_info = nr | INTR_INFO_VALID_MASK;
2461
2462         if (vcpu->arch.exception.has_error_code) {
2463                 vmcs12->vm_exit_intr_error_code = vcpu->arch.exception.error_code;
2464                 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
2465         }
2466
2467         if (kvm_exception_is_soft(nr))
2468                 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
2469         else
2470                 intr_info |= INTR_TYPE_HARD_EXCEPTION;
2471
2472         if (!(vmcs12->idt_vectoring_info_field & VECTORING_INFO_VALID_MASK) &&
2473             vmx_get_nmi_mask(vcpu))
2474                 intr_info |= INTR_INFO_UNBLOCK_NMI;
2475
2476         nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI, intr_info, exit_qual);
2477 }
2478
2479 /*
2480  * KVM wants to inject page-faults which it got to the guest. This function
2481  * checks whether in a nested guest, we need to inject them to L1 or L2.
2482  */
2483 static int nested_vmx_check_exception(struct kvm_vcpu *vcpu, unsigned long *exit_qual)
2484 {
2485         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
2486         unsigned int nr = vcpu->arch.exception.nr;
2487
2488         if (nr == PF_VECTOR) {
2489                 if (vcpu->arch.exception.nested_apf) {
2490                         *exit_qual = vcpu->arch.apf.nested_apf_token;
2491                         return 1;
2492                 }
2493                 /*
2494                  * FIXME: we must not write CR2 when L1 intercepts an L2 #PF exception.
2495                  * The fix is to add the ancillary datum (CR2 or DR6) to structs
2496                  * kvm_queued_exception and kvm_vcpu_events, so that CR2 and DR6
2497                  * can be written only when inject_pending_event runs.  This should be
2498                  * conditional on a new capability---if the capability is disabled,
2499                  * kvm_multiple_exception would write the ancillary information to
2500                  * CR2 or DR6, for backwards ABI-compatibility.
2501                  */
2502                 if (nested_vmx_is_page_fault_vmexit(vmcs12,
2503                                                     vcpu->arch.exception.error_code)) {
2504                         *exit_qual = vcpu->arch.cr2;
2505                         return 1;
2506                 }
2507         } else {
2508                 if (vmcs12->exception_bitmap & (1u << nr)) {
2509                         if (nr == DB_VECTOR)
2510                                 *exit_qual = vcpu->arch.dr6;
2511                         else
2512                                 *exit_qual = 0;
2513                         return 1;
2514                 }
2515         }
2516
2517         return 0;
2518 }
2519
2520 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
2521 {
2522         struct vcpu_vmx *vmx = to_vmx(vcpu);
2523         unsigned nr = vcpu->arch.exception.nr;
2524         bool has_error_code = vcpu->arch.exception.has_error_code;
2525         u32 error_code = vcpu->arch.exception.error_code;
2526         u32 intr_info = nr | INTR_INFO_VALID_MASK;
2527
2528         if (has_error_code) {
2529                 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
2530                 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
2531         }
2532
2533         if (vmx->rmode.vm86_active) {
2534                 int inc_eip = 0;
2535                 if (kvm_exception_is_soft(nr))
2536                         inc_eip = vcpu->arch.event_exit_inst_len;
2537                 if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
2538                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2539                 return;
2540         }
2541
2542         if (kvm_exception_is_soft(nr)) {
2543                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
2544                              vmx->vcpu.arch.event_exit_inst_len);
2545                 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
2546         } else
2547                 intr_info |= INTR_TYPE_HARD_EXCEPTION;
2548
2549         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
2550 }
2551
2552 static bool vmx_rdtscp_supported(void)
2553 {
2554         return cpu_has_vmx_rdtscp();
2555 }
2556
2557 static bool vmx_invpcid_supported(void)
2558 {
2559         return cpu_has_vmx_invpcid() && enable_ept;
2560 }
2561
2562 /*
2563  * Swap MSR entry in host/guest MSR entry array.
2564  */
2565 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
2566 {
2567         struct shared_msr_entry tmp;
2568
2569         tmp = vmx->guest_msrs[to];
2570         vmx->guest_msrs[to] = vmx->guest_msrs[from];
2571         vmx->guest_msrs[from] = tmp;
2572 }
2573
2574 static void vmx_set_msr_bitmap(struct kvm_vcpu *vcpu)
2575 {
2576         unsigned long *msr_bitmap;
2577
2578         if (is_guest_mode(vcpu))
2579                 msr_bitmap = to_vmx(vcpu)->nested.msr_bitmap;
2580         else if (cpu_has_secondary_exec_ctrls() &&
2581                  (vmcs_read32(SECONDARY_VM_EXEC_CONTROL) &
2582                   SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
2583                 if (enable_apicv && kvm_vcpu_apicv_active(vcpu)) {
2584                         if (is_long_mode(vcpu))
2585                                 msr_bitmap = vmx_msr_bitmap_longmode_x2apic_apicv;
2586                         else
2587                                 msr_bitmap = vmx_msr_bitmap_legacy_x2apic_apicv;
2588                 } else {
2589                         if (is_long_mode(vcpu))
2590                                 msr_bitmap = vmx_msr_bitmap_longmode_x2apic;
2591                         else
2592                                 msr_bitmap = vmx_msr_bitmap_legacy_x2apic;
2593                 }
2594         } else {
2595                 if (is_long_mode(vcpu))
2596                         msr_bitmap = vmx_msr_bitmap_longmode;
2597                 else
2598                         msr_bitmap = vmx_msr_bitmap_legacy;
2599         }
2600
2601         vmcs_write64(MSR_BITMAP, __pa(msr_bitmap));
2602 }
2603
2604 /*
2605  * Set up the vmcs to automatically save and restore system
2606  * msrs.  Don't touch the 64-bit msrs if the guest is in legacy
2607  * mode, as fiddling with msrs is very expensive.
2608  */
2609 static void setup_msrs(struct vcpu_vmx *vmx)
2610 {
2611         int save_nmsrs, index;
2612
2613         save_nmsrs = 0;
2614 #ifdef CONFIG_X86_64
2615         if (is_long_mode(&vmx->vcpu)) {
2616                 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
2617                 if (index >= 0)
2618                         move_msr_up(vmx, index, save_nmsrs++);
2619                 index = __find_msr_index(vmx, MSR_LSTAR);
2620                 if (index >= 0)
2621                         move_msr_up(vmx, index, save_nmsrs++);
2622                 index = __find_msr_index(vmx, MSR_CSTAR);
2623                 if (index >= 0)
2624                         move_msr_up(vmx, index, save_nmsrs++);
2625                 index = __find_msr_index(vmx, MSR_TSC_AUX);
2626                 if (index >= 0 && guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP))
2627                         move_msr_up(vmx, index, save_nmsrs++);
2628                 /*
2629                  * MSR_STAR is only needed on long mode guests, and only
2630                  * if efer.sce is enabled.
2631                  */
2632                 index = __find_msr_index(vmx, MSR_STAR);
2633                 if ((index >= 0) && (vmx->vcpu.arch.efer & EFER_SCE))
2634                         move_msr_up(vmx, index, save_nmsrs++);
2635         }
2636 #endif
2637         index = __find_msr_index(vmx, MSR_EFER);
2638         if (index >= 0 && update_transition_efer(vmx, index))
2639                 move_msr_up(vmx, index, save_nmsrs++);
2640
2641         vmx->save_nmsrs = save_nmsrs;
2642
2643         if (cpu_has_vmx_msr_bitmap())
2644                 vmx_set_msr_bitmap(&vmx->vcpu);
2645 }
2646
2647 /*
2648  * reads and returns guest's timestamp counter "register"
2649  * guest_tsc = (host_tsc * tsc multiplier) >> 48 + tsc_offset
2650  * -- Intel TSC Scaling for Virtualization White Paper, sec 1.3
2651  */
2652 static u64 guest_read_tsc(struct kvm_vcpu *vcpu)
2653 {
2654         u64 host_tsc, tsc_offset;
2655
2656         host_tsc = rdtsc();
2657         tsc_offset = vmcs_read64(TSC_OFFSET);
2658         return kvm_scale_tsc(vcpu, host_tsc) + tsc_offset;
2659 }
2660
2661 /*
2662  * writes 'offset' into guest's timestamp counter offset register
2663  */
2664 static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
2665 {
2666         if (is_guest_mode(vcpu)) {
2667                 /*
2668                  * We're here if L1 chose not to trap WRMSR to TSC. According
2669                  * to the spec, this should set L1's TSC; The offset that L1
2670                  * set for L2 remains unchanged, and still needs to be added
2671                  * to the newly set TSC to get L2's TSC.
2672                  */
2673                 struct vmcs12 *vmcs12;
2674                 /* recalculate vmcs02.TSC_OFFSET: */
2675                 vmcs12 = get_vmcs12(vcpu);
2676                 vmcs_write64(TSC_OFFSET, offset +
2677                         (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETING) ?
2678                          vmcs12->tsc_offset : 0));
2679         } else {
2680                 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
2681                                            vmcs_read64(TSC_OFFSET), offset);
2682                 vmcs_write64(TSC_OFFSET, offset);
2683         }
2684 }
2685
2686 /*
2687  * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
2688  * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
2689  * all guests if the "nested" module option is off, and can also be disabled
2690  * for a single guest by disabling its VMX cpuid bit.
2691  */
2692 static inline bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
2693 {
2694         return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
2695 }
2696
2697 /*
2698  * nested_vmx_setup_ctls_msrs() sets up variables containing the values to be
2699  * returned for the various VMX controls MSRs when nested VMX is enabled.
2700  * The same values should also be used to verify that vmcs12 control fields are
2701  * valid during nested entry from L1 to L2.
2702  * Each of these control msrs has a low and high 32-bit half: A low bit is on
2703  * if the corresponding bit in the (32-bit) control field *must* be on, and a
2704  * bit in the high half is on if the corresponding bit in the control field
2705  * may be on. See also vmx_control_verify().
2706  */
2707 static void nested_vmx_setup_ctls_msrs(struct vcpu_vmx *vmx)
2708 {
2709         /*
2710          * Note that as a general rule, the high half of the MSRs (bits in
2711          * the control fields which may be 1) should be initialized by the
2712          * intersection of the underlying hardware's MSR (i.e., features which
2713          * can be supported) and the list of features we want to expose -
2714          * because they are known to be properly supported in our code.
2715          * Also, usually, the low half of the MSRs (bits which must be 1) can
2716          * be set to 0, meaning that L1 may turn off any of these bits. The
2717          * reason is that if one of these bits is necessary, it will appear
2718          * in vmcs01 and prepare_vmcs02, when it bitwise-or's the control
2719          * fields of vmcs01 and vmcs02, will turn these bits off - and
2720          * nested_vmx_exit_reflected() will not pass related exits to L1.
2721          * These rules have exceptions below.
2722          */
2723
2724         /* pin-based controls */
2725         rdmsr(MSR_IA32_VMX_PINBASED_CTLS,
2726                 vmx->nested.nested_vmx_pinbased_ctls_low,
2727                 vmx->nested.nested_vmx_pinbased_ctls_high);
2728         vmx->nested.nested_vmx_pinbased_ctls_low |=
2729                 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
2730         vmx->nested.nested_vmx_pinbased_ctls_high &=
2731                 PIN_BASED_EXT_INTR_MASK |
2732                 PIN_BASED_NMI_EXITING |
2733                 PIN_BASED_VIRTUAL_NMIS;
2734         vmx->nested.nested_vmx_pinbased_ctls_high |=
2735                 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
2736                 PIN_BASED_VMX_PREEMPTION_TIMER;
2737         if (kvm_vcpu_apicv_active(&vmx->vcpu))
2738                 vmx->nested.nested_vmx_pinbased_ctls_high |=
2739                         PIN_BASED_POSTED_INTR;
2740
2741         /* exit controls */
2742         rdmsr(MSR_IA32_VMX_EXIT_CTLS,
2743                 vmx->nested.nested_vmx_exit_ctls_low,
2744                 vmx->nested.nested_vmx_exit_ctls_high);
2745         vmx->nested.nested_vmx_exit_ctls_low =
2746                 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
2747
2748         vmx->nested.nested_vmx_exit_ctls_high &=
2749 #ifdef CONFIG_X86_64
2750                 VM_EXIT_HOST_ADDR_SPACE_SIZE |
2751 #endif
2752                 VM_EXIT_LOAD_IA32_PAT | VM_EXIT_SAVE_IA32_PAT;
2753         vmx->nested.nested_vmx_exit_ctls_high |=
2754                 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR |
2755                 VM_EXIT_LOAD_IA32_EFER | VM_EXIT_SAVE_IA32_EFER |
2756                 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER | VM_EXIT_ACK_INTR_ON_EXIT;
2757
2758         if (kvm_mpx_supported())
2759                 vmx->nested.nested_vmx_exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
2760
2761         /* We support free control of debug control saving. */
2762         vmx->nested.nested_vmx_exit_ctls_low &= ~VM_EXIT_SAVE_DEBUG_CONTROLS;
2763
2764         /* entry controls */
2765         rdmsr(MSR_IA32_VMX_ENTRY_CTLS,
2766                 vmx->nested.nested_vmx_entry_ctls_low,
2767                 vmx->nested.nested_vmx_entry_ctls_high);
2768         vmx->nested.nested_vmx_entry_ctls_low =
2769                 VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
2770         vmx->nested.nested_vmx_entry_ctls_high &=
2771 #ifdef CONFIG_X86_64
2772                 VM_ENTRY_IA32E_MODE |
2773 #endif
2774                 VM_ENTRY_LOAD_IA32_PAT;
2775         vmx->nested.nested_vmx_entry_ctls_high |=
2776                 (VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR | VM_ENTRY_LOAD_IA32_EFER);
2777         if (kvm_mpx_supported())
2778                 vmx->nested.nested_vmx_entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
2779
2780         /* We support free control of debug control loading. */
2781         vmx->nested.nested_vmx_entry_ctls_low &= ~VM_ENTRY_LOAD_DEBUG_CONTROLS;
2782
2783         /* cpu-based controls */
2784         rdmsr(MSR_IA32_VMX_PROCBASED_CTLS,
2785                 vmx->nested.nested_vmx_procbased_ctls_low,
2786                 vmx->nested.nested_vmx_procbased_ctls_high);
2787         vmx->nested.nested_vmx_procbased_ctls_low =
2788                 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
2789         vmx->nested.nested_vmx_procbased_ctls_high &=
2790                 CPU_BASED_VIRTUAL_INTR_PENDING |
2791                 CPU_BASED_VIRTUAL_NMI_PENDING | CPU_BASED_USE_TSC_OFFSETING |
2792                 CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING |
2793                 CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING |
2794                 CPU_BASED_CR3_STORE_EXITING |
2795 #ifdef CONFIG_X86_64
2796                 CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING |
2797 #endif
2798                 CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING |
2799                 CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_TRAP_FLAG |
2800                 CPU_BASED_MONITOR_EXITING | CPU_BASED_RDPMC_EXITING |
2801                 CPU_BASED_RDTSC_EXITING | CPU_BASED_PAUSE_EXITING |
2802                 CPU_BASED_TPR_SHADOW | CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2803         /*
2804          * We can allow some features even when not supported by the
2805          * hardware. For example, L1 can specify an MSR bitmap - and we
2806          * can use it to avoid exits to L1 - even when L0 runs L2
2807          * without MSR bitmaps.
2808          */
2809         vmx->nested.nested_vmx_procbased_ctls_high |=
2810                 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
2811                 CPU_BASED_USE_MSR_BITMAPS;
2812
2813         /* We support free control of CR3 access interception. */
2814         vmx->nested.nested_vmx_procbased_ctls_low &=
2815                 ~(CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_CR3_STORE_EXITING);
2816
2817         /*
2818          * secondary cpu-based controls.  Do not include those that
2819          * depend on CPUID bits, they are added later by vmx_cpuid_update.
2820          */
2821         rdmsr(MSR_IA32_VMX_PROCBASED_CTLS2,
2822                 vmx->nested.nested_vmx_secondary_ctls_low,
2823                 vmx->nested.nested_vmx_secondary_ctls_high);
2824         vmx->nested.nested_vmx_secondary_ctls_low = 0;
2825         vmx->nested.nested_vmx_secondary_ctls_high &=
2826                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2827                 SECONDARY_EXEC_DESC |
2828                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2829                 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2830                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2831                 SECONDARY_EXEC_WBINVD_EXITING;
2832
2833         if (enable_ept) {
2834                 /* nested EPT: emulate EPT also to L1 */
2835                 vmx->nested.nested_vmx_secondary_ctls_high |=
2836                         SECONDARY_EXEC_ENABLE_EPT;
2837                 vmx->nested.nested_vmx_ept_caps = VMX_EPT_PAGE_WALK_4_BIT |
2838                          VMX_EPTP_WB_BIT | VMX_EPT_INVEPT_BIT;
2839                 if (cpu_has_vmx_ept_execute_only())
2840                         vmx->nested.nested_vmx_ept_caps |=
2841                                 VMX_EPT_EXECUTE_ONLY_BIT;
2842                 vmx->nested.nested_vmx_ept_caps &= vmx_capability.ept;
2843                 vmx->nested.nested_vmx_ept_caps |= VMX_EPT_EXTENT_GLOBAL_BIT |
2844                         VMX_EPT_EXTENT_CONTEXT_BIT | VMX_EPT_2MB_PAGE_BIT |
2845                         VMX_EPT_1GB_PAGE_BIT;
2846                 if (enable_ept_ad_bits) {
2847                         vmx->nested.nested_vmx_secondary_ctls_high |=
2848                                 SECONDARY_EXEC_ENABLE_PML;
2849                         vmx->nested.nested_vmx_ept_caps |= VMX_EPT_AD_BIT;
2850                 }
2851         }
2852
2853         if (cpu_has_vmx_vmfunc()) {
2854                 vmx->nested.nested_vmx_secondary_ctls_high |=
2855                         SECONDARY_EXEC_ENABLE_VMFUNC;
2856                 /*
2857                  * Advertise EPTP switching unconditionally
2858                  * since we emulate it
2859                  */
2860                 if (enable_ept)
2861                         vmx->nested.nested_vmx_vmfunc_controls =
2862                                 VMX_VMFUNC_EPTP_SWITCHING;
2863         }
2864
2865         /*
2866          * Old versions of KVM use the single-context version without
2867          * checking for support, so declare that it is supported even
2868          * though it is treated as global context.  The alternative is
2869          * not failing the single-context invvpid, and it is worse.
2870          */
2871         if (enable_vpid) {
2872                 vmx->nested.nested_vmx_secondary_ctls_high |=
2873                         SECONDARY_EXEC_ENABLE_VPID;
2874                 vmx->nested.nested_vmx_vpid_caps = VMX_VPID_INVVPID_BIT |
2875                         VMX_VPID_EXTENT_SUPPORTED_MASK;
2876         }
2877
2878         if (enable_unrestricted_guest)
2879                 vmx->nested.nested_vmx_secondary_ctls_high |=
2880                         SECONDARY_EXEC_UNRESTRICTED_GUEST;
2881
2882         /* miscellaneous data */
2883         rdmsr(MSR_IA32_VMX_MISC,
2884                 vmx->nested.nested_vmx_misc_low,
2885                 vmx->nested.nested_vmx_misc_high);
2886         vmx->nested.nested_vmx_misc_low &= VMX_MISC_SAVE_EFER_LMA;
2887         vmx->nested.nested_vmx_misc_low |=
2888                 VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE |
2889                 VMX_MISC_ACTIVITY_HLT;
2890         vmx->nested.nested_vmx_misc_high = 0;
2891
2892         /*
2893          * This MSR reports some information about VMX support. We
2894          * should return information about the VMX we emulate for the
2895          * guest, and the VMCS structure we give it - not about the
2896          * VMX support of the underlying hardware.
2897          */
2898         vmx->nested.nested_vmx_basic =
2899                 VMCS12_REVISION |
2900                 VMX_BASIC_TRUE_CTLS |
2901                 ((u64)VMCS12_SIZE << VMX_BASIC_VMCS_SIZE_SHIFT) |
2902                 (VMX_BASIC_MEM_TYPE_WB << VMX_BASIC_MEM_TYPE_SHIFT);
2903
2904         if (cpu_has_vmx_basic_inout())
2905                 vmx->nested.nested_vmx_basic |= VMX_BASIC_INOUT;
2906
2907         /*
2908          * These MSRs specify bits which the guest must keep fixed on
2909          * while L1 is in VMXON mode (in L1's root mode, or running an L2).
2910          * We picked the standard core2 setting.
2911          */
2912 #define VMXON_CR0_ALWAYSON     (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE)
2913 #define VMXON_CR4_ALWAYSON     X86_CR4_VMXE
2914         vmx->nested.nested_vmx_cr0_fixed0 = VMXON_CR0_ALWAYSON;
2915         vmx->nested.nested_vmx_cr4_fixed0 = VMXON_CR4_ALWAYSON;
2916
2917         /* These MSRs specify bits which the guest must keep fixed off. */
2918         rdmsrl(MSR_IA32_VMX_CR0_FIXED1, vmx->nested.nested_vmx_cr0_fixed1);
2919         rdmsrl(MSR_IA32_VMX_CR4_FIXED1, vmx->nested.nested_vmx_cr4_fixed1);
2920
2921         /* highest index: VMX_PREEMPTION_TIMER_VALUE */
2922         vmx->nested.nested_vmx_vmcs_enum = 0x2e;
2923 }
2924
2925 /*
2926  * if fixed0[i] == 1: val[i] must be 1
2927  * if fixed1[i] == 0: val[i] must be 0
2928  */
2929 static inline bool fixed_bits_valid(u64 val, u64 fixed0, u64 fixed1)
2930 {
2931         return ((val & fixed1) | fixed0) == val;
2932 }
2933
2934 static inline bool vmx_control_verify(u32 control, u32 low, u32 high)
2935 {
2936         return fixed_bits_valid(control, low, high);
2937 }
2938
2939 static inline u64 vmx_control_msr(u32 low, u32 high)
2940 {
2941         return low | ((u64)high << 32);
2942 }
2943
2944 static bool is_bitwise_subset(u64 superset, u64 subset, u64 mask)
2945 {
2946         superset &= mask;
2947         subset &= mask;
2948
2949         return (superset | subset) == superset;
2950 }
2951
2952 static int vmx_restore_vmx_basic(struct vcpu_vmx *vmx, u64 data)
2953 {
2954         const u64 feature_and_reserved =
2955                 /* feature (except bit 48; see below) */
2956                 BIT_ULL(49) | BIT_ULL(54) | BIT_ULL(55) |
2957                 /* reserved */
2958                 BIT_ULL(31) | GENMASK_ULL(47, 45) | GENMASK_ULL(63, 56);
2959         u64 vmx_basic = vmx->nested.nested_vmx_basic;
2960
2961         if (!is_bitwise_subset(vmx_basic, data, feature_and_reserved))
2962                 return -EINVAL;
2963
2964         /*
2965          * KVM does not emulate a version of VMX that constrains physical
2966          * addresses of VMX structures (e.g. VMCS) to 32-bits.
2967          */
2968         if (data & BIT_ULL(48))
2969                 return -EINVAL;
2970
2971         if (vmx_basic_vmcs_revision_id(vmx_basic) !=
2972             vmx_basic_vmcs_revision_id(data))
2973                 return -EINVAL;
2974
2975         if (vmx_basic_vmcs_size(vmx_basic) > vmx_basic_vmcs_size(data))
2976                 return -EINVAL;
2977
2978         vmx->nested.nested_vmx_basic = data;
2979         return 0;
2980 }
2981
2982 static int
2983 vmx_restore_control_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
2984 {
2985         u64 supported;
2986         u32 *lowp, *highp;
2987
2988         switch (msr_index) {
2989         case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
2990                 lowp = &vmx->nested.nested_vmx_pinbased_ctls_low;
2991                 highp = &vmx->nested.nested_vmx_pinbased_ctls_high;
2992                 break;
2993         case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
2994                 lowp = &vmx->nested.nested_vmx_procbased_ctls_low;
2995                 highp = &vmx->nested.nested_vmx_procbased_ctls_high;
2996                 break;
2997         case MSR_IA32_VMX_TRUE_EXIT_CTLS:
2998                 lowp = &vmx->nested.nested_vmx_exit_ctls_low;
2999                 highp = &vmx->nested.nested_vmx_exit_ctls_high;
3000                 break;
3001         case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3002                 lowp = &vmx->nested.nested_vmx_entry_ctls_low;
3003                 highp = &vmx->nested.nested_vmx_entry_ctls_high;
3004                 break;
3005         case MSR_IA32_VMX_PROCBASED_CTLS2:
3006                 lowp = &vmx->nested.nested_vmx_secondary_ctls_low;
3007                 highp = &vmx->nested.nested_vmx_secondary_ctls_high;
3008                 break;
3009         default:
3010                 BUG();
3011         }
3012
3013         supported = vmx_control_msr(*lowp, *highp);
3014
3015         /* Check must-be-1 bits are still 1. */
3016         if (!is_bitwise_subset(data, supported, GENMASK_ULL(31, 0)))
3017                 return -EINVAL;
3018
3019         /* Check must-be-0 bits are still 0. */
3020         if (!is_bitwise_subset(supported, data, GENMASK_ULL(63, 32)))
3021                 return -EINVAL;
3022
3023         *lowp = data;
3024         *highp = data >> 32;
3025         return 0;
3026 }
3027
3028 static int vmx_restore_vmx_misc(struct vcpu_vmx *vmx, u64 data)
3029 {
3030         const u64 feature_and_reserved_bits =
3031                 /* feature */
3032                 BIT_ULL(5) | GENMASK_ULL(8, 6) | BIT_ULL(14) | BIT_ULL(15) |
3033                 BIT_ULL(28) | BIT_ULL(29) | BIT_ULL(30) |
3034                 /* reserved */
3035                 GENMASK_ULL(13, 9) | BIT_ULL(31);
3036         u64 vmx_misc;
3037
3038         vmx_misc = vmx_control_msr(vmx->nested.nested_vmx_misc_low,
3039                                    vmx->nested.nested_vmx_misc_high);
3040
3041         if (!is_bitwise_subset(vmx_misc, data, feature_and_reserved_bits))
3042                 return -EINVAL;
3043
3044         if ((vmx->nested.nested_vmx_pinbased_ctls_high &
3045              PIN_BASED_VMX_PREEMPTION_TIMER) &&
3046             vmx_misc_preemption_timer_rate(data) !=
3047             vmx_misc_preemption_timer_rate(vmx_misc))
3048                 return -EINVAL;
3049
3050         if (vmx_misc_cr3_count(data) > vmx_misc_cr3_count(vmx_misc))
3051                 return -EINVAL;
3052
3053         if (vmx_misc_max_msr(data) > vmx_misc_max_msr(vmx_misc))
3054                 return -EINVAL;
3055
3056         if (vmx_misc_mseg_revid(data) != vmx_misc_mseg_revid(vmx_misc))
3057                 return -EINVAL;
3058
3059         vmx->nested.nested_vmx_misc_low = data;
3060         vmx->nested.nested_vmx_misc_high = data >> 32;
3061         return 0;
3062 }
3063
3064 static int vmx_restore_vmx_ept_vpid_cap(struct vcpu_vmx *vmx, u64 data)
3065 {
3066         u64 vmx_ept_vpid_cap;
3067
3068         vmx_ept_vpid_cap = vmx_control_msr(vmx->nested.nested_vmx_ept_caps,
3069                                            vmx->nested.nested_vmx_vpid_caps);
3070
3071         /* Every bit is either reserved or a feature bit. */
3072         if (!is_bitwise_subset(vmx_ept_vpid_cap, data, -1ULL))
3073                 return -EINVAL;
3074
3075         vmx->nested.nested_vmx_ept_caps = data;
3076         vmx->nested.nested_vmx_vpid_caps = data >> 32;
3077         return 0;
3078 }
3079
3080 static int vmx_restore_fixed0_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
3081 {
3082         u64 *msr;
3083
3084         switch (msr_index) {
3085         case MSR_IA32_VMX_CR0_FIXED0:
3086                 msr = &vmx->nested.nested_vmx_cr0_fixed0;
3087                 break;
3088         case MSR_IA32_VMX_CR4_FIXED0:
3089                 msr = &vmx->nested.nested_vmx_cr4_fixed0;
3090                 break;
3091         default:
3092                 BUG();
3093         }
3094
3095         /*
3096          * 1 bits (which indicates bits which "must-be-1" during VMX operation)
3097          * must be 1 in the restored value.
3098          */
3099         if (!is_bitwise_subset(data, *msr, -1ULL))
3100                 return -EINVAL;
3101
3102         *msr = data;
3103         return 0;
3104 }
3105
3106 /*
3107  * Called when userspace is restoring VMX MSRs.
3108  *
3109  * Returns 0 on success, non-0 otherwise.
3110  */
3111 static int vmx_set_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
3112 {
3113         struct vcpu_vmx *vmx = to_vmx(vcpu);
3114
3115         switch (msr_index) {
3116         case MSR_IA32_VMX_BASIC:
3117                 return vmx_restore_vmx_basic(vmx, data);
3118         case MSR_IA32_VMX_PINBASED_CTLS:
3119         case MSR_IA32_VMX_PROCBASED_CTLS:
3120         case MSR_IA32_VMX_EXIT_CTLS:
3121         case MSR_IA32_VMX_ENTRY_CTLS:
3122                 /*
3123                  * The "non-true" VMX capability MSRs are generated from the
3124                  * "true" MSRs, so we do not support restoring them directly.
3125                  *
3126                  * If userspace wants to emulate VMX_BASIC[55]=0, userspace
3127                  * should restore the "true" MSRs with the must-be-1 bits
3128                  * set according to the SDM Vol 3. A.2 "RESERVED CONTROLS AND
3129                  * DEFAULT SETTINGS".
3130                  */
3131                 return -EINVAL;
3132         case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3133         case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3134         case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3135         case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3136         case MSR_IA32_VMX_PROCBASED_CTLS2:
3137                 return vmx_restore_control_msr(vmx, msr_index, data);
3138         case MSR_IA32_VMX_MISC:
3139                 return vmx_restore_vmx_misc(vmx, data);
3140         case MSR_IA32_VMX_CR0_FIXED0:
3141         case MSR_IA32_VMX_CR4_FIXED0:
3142                 return vmx_restore_fixed0_msr(vmx, msr_index, data);
3143         case MSR_IA32_VMX_CR0_FIXED1:
3144         case MSR_IA32_VMX_CR4_FIXED1:
3145                 /*
3146                  * These MSRs are generated based on the vCPU's CPUID, so we
3147                  * do not support restoring them directly.
3148                  */
3149                 return -EINVAL;
3150         case MSR_IA32_VMX_EPT_VPID_CAP:
3151                 return vmx_restore_vmx_ept_vpid_cap(vmx, data);
3152         case MSR_IA32_VMX_VMCS_ENUM:
3153                 vmx->nested.nested_vmx_vmcs_enum = data;
3154                 return 0;
3155         default:
3156                 /*
3157                  * The rest of the VMX capability MSRs do not support restore.
3158                  */
3159                 return -EINVAL;
3160         }
3161 }
3162
3163 /* Returns 0 on success, non-0 otherwise. */
3164 static int vmx_get_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
3165 {
3166         struct vcpu_vmx *vmx = to_vmx(vcpu);
3167
3168         switch (msr_index) {
3169         case MSR_IA32_VMX_BASIC:
3170                 *pdata = vmx->nested.nested_vmx_basic;
3171                 break;
3172         case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3173         case MSR_IA32_VMX_PINBASED_CTLS:
3174                 *pdata = vmx_control_msr(
3175                         vmx->nested.nested_vmx_pinbased_ctls_low,
3176                         vmx->nested.nested_vmx_pinbased_ctls_high);
3177                 if (msr_index == MSR_IA32_VMX_PINBASED_CTLS)
3178                         *pdata |= PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3179                 break;
3180         case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3181         case MSR_IA32_VMX_PROCBASED_CTLS:
3182                 *pdata = vmx_control_msr(
3183                         vmx->nested.nested_vmx_procbased_ctls_low,
3184                         vmx->nested.nested_vmx_procbased_ctls_high);
3185                 if (msr_index == MSR_IA32_VMX_PROCBASED_CTLS)
3186                         *pdata |= CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3187                 break;
3188         case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3189         case MSR_IA32_VMX_EXIT_CTLS:
3190                 *pdata = vmx_control_msr(
3191                         vmx->nested.nested_vmx_exit_ctls_low,
3192                         vmx->nested.nested_vmx_exit_ctls_high);
3193                 if (msr_index == MSR_IA32_VMX_EXIT_CTLS)
3194                         *pdata |= VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
3195                 break;
3196         case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3197         case MSR_IA32_VMX_ENTRY_CTLS:
3198                 *pdata = vmx_control_msr(
3199                         vmx->nested.nested_vmx_entry_ctls_low,
3200                         vmx->nested.nested_vmx_entry_ctls_high);
3201                 if (msr_index == MSR_IA32_VMX_ENTRY_CTLS)
3202                         *pdata |= VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
3203                 break;
3204         case MSR_IA32_VMX_MISC:
3205                 *pdata = vmx_control_msr(
3206                         vmx->nested.nested_vmx_misc_low,
3207                         vmx->nested.nested_vmx_misc_high);
3208                 break;
3209         case MSR_IA32_VMX_CR0_FIXED0:
3210                 *pdata = vmx->nested.nested_vmx_cr0_fixed0;
3211                 break;
3212         case MSR_IA32_VMX_CR0_FIXED1:
3213                 *pdata = vmx->nested.nested_vmx_cr0_fixed1;
3214                 break;
3215         case MSR_IA32_VMX_CR4_FIXED0:
3216                 *pdata = vmx->nested.nested_vmx_cr4_fixed0;
3217                 break;
3218         case MSR_IA32_VMX_CR4_FIXED1:
3219                 *pdata = vmx->nested.nested_vmx_cr4_fixed1;
3220                 break;
3221         case MSR_IA32_VMX_VMCS_ENUM:
3222                 *pdata = vmx->nested.nested_vmx_vmcs_enum;
3223                 break;
3224         case MSR_IA32_VMX_PROCBASED_CTLS2:
3225                 *pdata = vmx_control_msr(
3226                         vmx->nested.nested_vmx_secondary_ctls_low,
3227                         vmx->nested.nested_vmx_secondary_ctls_high);
3228                 break;
3229         case MSR_IA32_VMX_EPT_VPID_CAP:
3230                 *pdata = vmx->nested.nested_vmx_ept_caps |
3231                         ((u64)vmx->nested.nested_vmx_vpid_caps << 32);
3232                 break;
3233         case MSR_IA32_VMX_VMFUNC:
3234                 *pdata = vmx->nested.nested_vmx_vmfunc_controls;
3235                 break;
3236         default:
3237                 return 1;
3238         }
3239
3240         return 0;
3241 }
3242
3243 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
3244                                                  uint64_t val)
3245 {
3246         uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
3247
3248         return !(val & ~valid_bits);
3249 }
3250
3251 /*
3252  * Reads an msr value (of 'msr_index') into 'pdata'.
3253  * Returns 0 on success, non-0 otherwise.
3254  * Assumes vcpu_load() was already called.
3255  */
3256 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3257 {
3258         struct shared_msr_entry *msr;
3259
3260         switch (msr_info->index) {
3261 #ifdef CONFIG_X86_64
3262         case MSR_FS_BASE:
3263                 msr_info->data = vmcs_readl(GUEST_FS_BASE);
3264                 break;
3265         case MSR_GS_BASE:
3266                 msr_info->data = vmcs_readl(GUEST_GS_BASE);
3267                 break;
3268         case MSR_KERNEL_GS_BASE:
3269                 vmx_load_host_state(to_vmx(vcpu));
3270                 msr_info->data = to_vmx(vcpu)->msr_guest_kernel_gs_base;
3271                 break;
3272 #endif
3273         case MSR_EFER:
3274                 return kvm_get_msr_common(vcpu, msr_info);
3275         case MSR_IA32_TSC:
3276                 msr_info->data = guest_read_tsc(vcpu);
3277                 break;
3278         case MSR_IA32_SYSENTER_CS:
3279                 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
3280                 break;
3281         case MSR_IA32_SYSENTER_EIP:
3282                 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
3283                 break;
3284         case MSR_IA32_SYSENTER_ESP:
3285                 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
3286                 break;
3287         case MSR_IA32_BNDCFGS:
3288                 if (!kvm_mpx_supported() ||
3289                     (!msr_info->host_initiated &&
3290                      !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
3291                         return 1;
3292                 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
3293                 break;
3294         case MSR_IA32_MCG_EXT_CTL:
3295                 if (!msr_info->host_initiated &&
3296                     !(to_vmx(vcpu)->msr_ia32_feature_control &
3297                       FEATURE_CONTROL_LMCE))
3298                         return 1;
3299                 msr_info->data = vcpu->arch.mcg_ext_ctl;
3300                 break;
3301         case MSR_IA32_FEATURE_CONTROL:
3302                 msr_info->data = to_vmx(vcpu)->msr_ia32_feature_control;
3303                 break;
3304         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
3305                 if (!nested_vmx_allowed(vcpu))
3306                         return 1;
3307                 return vmx_get_vmx_msr(vcpu, msr_info->index, &msr_info->data);
3308         case MSR_IA32_XSS:
3309                 if (!vmx_xsaves_supported())
3310                         return 1;
3311                 msr_info->data = vcpu->arch.ia32_xss;
3312                 break;
3313         case MSR_TSC_AUX:
3314                 if (!msr_info->host_initiated &&
3315                     !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
3316                         return 1;
3317                 /* Otherwise falls through */
3318         default:
3319                 msr = find_msr_entry(to_vmx(vcpu), msr_info->index);
3320                 if (msr) {
3321                         msr_info->data = msr->data;
3322                         break;
3323                 }
3324                 return kvm_get_msr_common(vcpu, msr_info);
3325         }
3326
3327         return 0;
3328 }
3329
3330 static void vmx_leave_nested(struct kvm_vcpu *vcpu);
3331
3332 /*
3333  * Writes msr value into into the appropriate "register".
3334  * Returns 0 on success, non-0 otherwise.
3335  * Assumes vcpu_load() was already called.
3336  */
3337 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3338 {
3339         struct vcpu_vmx *vmx = to_vmx(vcpu);
3340         struct shared_msr_entry *msr;
3341         int ret = 0;
3342         u32 msr_index = msr_info->index;
3343         u64 data = msr_info->data;
3344
3345         switch (msr_index) {
3346         case MSR_EFER:
3347                 ret = kvm_set_msr_common(vcpu, msr_info);
3348                 break;
3349 #ifdef CONFIG_X86_64
3350         case MSR_FS_BASE:
3351                 vmx_segment_cache_clear(vmx);
3352                 vmcs_writel(GUEST_FS_BASE, data);
3353                 break;
3354         case MSR_GS_BASE:
3355                 vmx_segment_cache_clear(vmx);
3356                 vmcs_writel(GUEST_GS_BASE, data);
3357                 break;
3358         case MSR_KERNEL_GS_BASE:
3359                 vmx_load_host_state(vmx);
3360                 vmx->msr_guest_kernel_gs_base = data;
3361                 break;
3362 #endif
3363         case MSR_IA32_SYSENTER_CS:
3364                 vmcs_write32(GUEST_SYSENTER_CS, data);
3365                 break;
3366         case MSR_IA32_SYSENTER_EIP:
3367                 vmcs_writel(GUEST_SYSENTER_EIP, data);
3368                 break;
3369         case MSR_IA32_SYSENTER_ESP:
3370                 vmcs_writel(GUEST_SYSENTER_ESP, data);
3371                 break;
3372         case MSR_IA32_BNDCFGS:
3373                 if (!kvm_mpx_supported() ||
3374                     (!msr_info->host_initiated &&
3375                      !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
3376                         return 1;
3377                 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
3378                     (data & MSR_IA32_BNDCFGS_RSVD))
3379                         return 1;
3380                 vmcs_write64(GUEST_BNDCFGS, data);
3381                 break;
3382         case MSR_IA32_TSC:
3383                 kvm_write_tsc(vcpu, msr_info);
3384                 break;
3385         case MSR_IA32_CR_PAT:
3386                 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
3387                         if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
3388                                 return 1;
3389                         vmcs_write64(GUEST_IA32_PAT, data);
3390                         vcpu->arch.pat = data;
3391                         break;
3392                 }
3393                 ret = kvm_set_msr_common(vcpu, msr_info);
3394                 break;
3395         case MSR_IA32_TSC_ADJUST:
3396                 ret = kvm_set_msr_common(vcpu, msr_info);
3397                 break;
3398         case MSR_IA32_MCG_EXT_CTL:
3399                 if ((!msr_info->host_initiated &&
3400                      !(to_vmx(vcpu)->msr_ia32_feature_control &