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