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