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