kvm: vmx: Reinstate support for CPUs without virtual NMI
[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_DONE)
5918                         kvm_queue_exception(vcpu, UD_VECTOR);
5919                 return 1;
5920         }
5921
5922         error_code = 0;
5923         if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
5924                 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
5925
5926         /*
5927          * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
5928          * MMIO, it is better to report an internal error.
5929          * See the comments in vmx_handle_exit.
5930          */
5931         if ((vect_info & VECTORING_INFO_VALID_MASK) &&
5932             !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
5933                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5934                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
5935                 vcpu->run->internal.ndata = 3;
5936                 vcpu->run->internal.data[0] = vect_info;
5937                 vcpu->run->internal.data[1] = intr_info;
5938                 vcpu->run->internal.data[2] = error_code;
5939                 return 0;
5940         }
5941
5942         if (is_page_fault(intr_info)) {
5943                 cr2 = vmcs_readl(EXIT_QUALIFICATION);
5944                 /* EPT won't cause page fault directly */
5945                 WARN_ON_ONCE(!vcpu->arch.apf.host_apf_reason && enable_ept);
5946                 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0,
5947                                 true);
5948         }
5949
5950         ex_no = intr_info & INTR_INFO_VECTOR_MASK;
5951
5952         if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
5953                 return handle_rmode_exception(vcpu, ex_no, error_code);
5954
5955         switch (ex_no) {
5956         case AC_VECTOR:
5957                 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
5958                 return 1;
5959         case DB_VECTOR:
5960                 dr6 = vmcs_readl(EXIT_QUALIFICATION);
5961                 if (!(vcpu->guest_debug &
5962                       (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
5963                         vcpu->arch.dr6 &= ~15;
5964                         vcpu->arch.dr6 |= dr6 | DR6_RTM;
5965                         if (!(dr6 & ~DR6_RESERVED)) /* icebp */
5966                                 skip_emulated_instruction(vcpu);
5967
5968                         kvm_queue_exception(vcpu, DB_VECTOR);
5969                         return 1;
5970                 }
5971                 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
5972                 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
5973                 /* fall through */
5974         case BP_VECTOR:
5975                 /*
5976                  * Update instruction length as we may reinject #BP from
5977                  * user space while in guest debugging mode. Reading it for
5978                  * #DB as well causes no harm, it is not used in that case.
5979                  */
5980                 vmx->vcpu.arch.event_exit_inst_len =
5981                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
5982                 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5983                 rip = kvm_rip_read(vcpu);
5984                 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
5985                 kvm_run->debug.arch.exception = ex_no;
5986                 break;
5987         default:
5988                 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
5989                 kvm_run->ex.exception = ex_no;
5990                 kvm_run->ex.error_code = error_code;
5991                 break;
5992         }
5993         return 0;
5994 }
5995
5996 static int handle_external_interrupt(struct kvm_vcpu *vcpu)
5997 {
5998         ++vcpu->stat.irq_exits;
5999         return 1;
6000 }
6001
6002 static int handle_triple_fault(struct kvm_vcpu *vcpu)
6003 {
6004         vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
6005         vcpu->mmio_needed = 0;
6006         return 0;
6007 }
6008
6009 static int handle_io(struct kvm_vcpu *vcpu)
6010 {
6011         unsigned long exit_qualification;
6012         int size, in, string, ret;
6013         unsigned port;
6014
6015         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6016         string = (exit_qualification & 16) != 0;
6017         in = (exit_qualification & 8) != 0;
6018
6019         ++vcpu->stat.io_exits;
6020
6021         if (string || in)
6022                 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
6023
6024         port = exit_qualification >> 16;
6025         size = (exit_qualification & 7) + 1;
6026
6027         ret = kvm_skip_emulated_instruction(vcpu);
6028
6029         /*
6030          * TODO: we might be squashing a KVM_GUESTDBG_SINGLESTEP-triggered
6031          * KVM_EXIT_DEBUG here.
6032          */
6033         return kvm_fast_pio_out(vcpu, size, port) && ret;
6034 }
6035
6036 static void
6037 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
6038 {
6039         /*
6040          * Patch in the VMCALL instruction:
6041          */
6042         hypercall[0] = 0x0f;
6043         hypercall[1] = 0x01;
6044         hypercall[2] = 0xc1;
6045 }
6046
6047 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
6048 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
6049 {
6050         if (is_guest_mode(vcpu)) {
6051                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6052                 unsigned long orig_val = val;
6053
6054                 /*
6055                  * We get here when L2 changed cr0 in a way that did not change
6056                  * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
6057                  * but did change L0 shadowed bits. So we first calculate the
6058                  * effective cr0 value that L1 would like to write into the
6059                  * hardware. It consists of the L2-owned bits from the new
6060                  * value combined with the L1-owned bits from L1's guest_cr0.
6061                  */
6062                 val = (val & ~vmcs12->cr0_guest_host_mask) |
6063                         (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
6064
6065                 if (!nested_guest_cr0_valid(vcpu, val))
6066                         return 1;
6067
6068                 if (kvm_set_cr0(vcpu, val))
6069                         return 1;
6070                 vmcs_writel(CR0_READ_SHADOW, orig_val);
6071                 return 0;
6072         } else {
6073                 if (to_vmx(vcpu)->nested.vmxon &&
6074                     !nested_host_cr0_valid(vcpu, val))
6075                         return 1;
6076
6077                 return kvm_set_cr0(vcpu, val);
6078         }
6079 }
6080
6081 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
6082 {
6083         if (is_guest_mode(vcpu)) {
6084                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6085                 unsigned long orig_val = val;
6086
6087                 /* analogously to handle_set_cr0 */
6088                 val = (val & ~vmcs12->cr4_guest_host_mask) |
6089                         (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
6090                 if (kvm_set_cr4(vcpu, val))
6091                         return 1;
6092                 vmcs_writel(CR4_READ_SHADOW, orig_val);
6093                 return 0;
6094         } else
6095                 return kvm_set_cr4(vcpu, val);
6096 }
6097
6098 static int handle_cr(struct kvm_vcpu *vcpu)
6099 {
6100         unsigned long exit_qualification, val;
6101         int cr;
6102         int reg;
6103         int err;
6104         int ret;
6105
6106         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6107         cr = exit_qualification & 15;
6108         reg = (exit_qualification >> 8) & 15;
6109         switch ((exit_qualification >> 4) & 3) {
6110         case 0: /* mov to cr */
6111                 val = kvm_register_readl(vcpu, reg);
6112                 trace_kvm_cr_write(cr, val);
6113                 switch (cr) {
6114                 case 0:
6115                         err = handle_set_cr0(vcpu, val);
6116                         return kvm_complete_insn_gp(vcpu, err);
6117                 case 3:
6118                         err = kvm_set_cr3(vcpu, val);
6119                         return kvm_complete_insn_gp(vcpu, err);
6120                 case 4:
6121                         err = handle_set_cr4(vcpu, val);
6122                         return kvm_complete_insn_gp(vcpu, err);
6123                 case 8: {
6124                                 u8 cr8_prev = kvm_get_cr8(vcpu);
6125                                 u8 cr8 = (u8)val;
6126                                 err = kvm_set_cr8(vcpu, cr8);
6127                                 ret = kvm_complete_insn_gp(vcpu, err);
6128                                 if (lapic_in_kernel(vcpu))
6129                                         return ret;
6130                                 if (cr8_prev <= cr8)
6131                                         return ret;
6132                                 /*
6133                                  * TODO: we might be squashing a
6134                                  * KVM_GUESTDBG_SINGLESTEP-triggered
6135                                  * KVM_EXIT_DEBUG here.
6136                                  */
6137                                 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
6138                                 return 0;
6139                         }
6140                 }
6141                 break;
6142         case 2: /* clts */
6143                 WARN_ONCE(1, "Guest should always own CR0.TS");
6144                 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
6145                 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
6146                 return kvm_skip_emulated_instruction(vcpu);
6147         case 1: /*mov from cr*/
6148                 switch (cr) {
6149                 case 3:
6150                         val = kvm_read_cr3(vcpu);
6151                         kvm_register_write(vcpu, reg, val);
6152                         trace_kvm_cr_read(cr, val);
6153                         return kvm_skip_emulated_instruction(vcpu);
6154                 case 8:
6155                         val = kvm_get_cr8(vcpu);
6156                         kvm_register_write(vcpu, reg, val);
6157                         trace_kvm_cr_read(cr, val);
6158                         return kvm_skip_emulated_instruction(vcpu);
6159                 }
6160                 break;
6161         case 3: /* lmsw */
6162                 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
6163                 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
6164                 kvm_lmsw(vcpu, val);
6165
6166                 return kvm_skip_emulated_instruction(vcpu);
6167         default:
6168                 break;
6169         }
6170         vcpu->run->exit_reason = 0;
6171         vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
6172                (int)(exit_qualification >> 4) & 3, cr);
6173         return 0;
6174 }
6175
6176 static int handle_dr(struct kvm_vcpu *vcpu)
6177 {
6178         unsigned long exit_qualification;
6179         int dr, dr7, reg;
6180
6181         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6182         dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
6183
6184         /* First, if DR does not exist, trigger UD */
6185         if (!kvm_require_dr(vcpu, dr))
6186                 return 1;
6187
6188         /* Do not handle if the CPL > 0, will trigger GP on re-entry */
6189         if (!kvm_require_cpl(vcpu, 0))
6190                 return 1;
6191         dr7 = vmcs_readl(GUEST_DR7);
6192         if (dr7 & DR7_GD) {
6193                 /*
6194                  * As the vm-exit takes precedence over the debug trap, we
6195                  * need to emulate the latter, either for the host or the
6196                  * guest debugging itself.
6197                  */
6198                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
6199                         vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
6200                         vcpu->run->debug.arch.dr7 = dr7;
6201                         vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
6202                         vcpu->run->debug.arch.exception = DB_VECTOR;
6203                         vcpu->run->exit_reason = KVM_EXIT_DEBUG;
6204                         return 0;
6205                 } else {
6206                         vcpu->arch.dr6 &= ~15;
6207                         vcpu->arch.dr6 |= DR6_BD | DR6_RTM;
6208                         kvm_queue_exception(vcpu, DB_VECTOR);
6209                         return 1;
6210                 }
6211         }
6212
6213         if (vcpu->guest_debug == 0) {
6214                 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
6215                                 CPU_BASED_MOV_DR_EXITING);
6216
6217                 /*
6218                  * No more DR vmexits; force a reload of the debug registers
6219                  * and reenter on this instruction.  The next vmexit will
6220                  * retrieve the full state of the debug registers.
6221                  */
6222                 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
6223                 return 1;
6224         }
6225
6226         reg = DEBUG_REG_ACCESS_REG(exit_qualification);
6227         if (exit_qualification & TYPE_MOV_FROM_DR) {
6228                 unsigned long val;
6229
6230                 if (kvm_get_dr(vcpu, dr, &val))
6231                         return 1;
6232                 kvm_register_write(vcpu, reg, val);
6233         } else
6234                 if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
6235                         return 1;
6236
6237         return kvm_skip_emulated_instruction(vcpu);
6238 }
6239
6240 static u64 vmx_get_dr6(struct kvm_vcpu *vcpu)
6241 {
6242         return vcpu->arch.dr6;
6243 }
6244
6245 static void vmx_set_dr6(struct kvm_vcpu *vcpu, unsigned long val)
6246 {
6247 }
6248
6249 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
6250 {
6251         get_debugreg(vcpu->arch.db[0], 0);
6252         get_debugreg(vcpu->arch.db[1], 1);
6253         get_debugreg(vcpu->arch.db[2], 2);
6254         get_debugreg(vcpu->arch.db[3], 3);
6255         get_debugreg(vcpu->arch.dr6, 6);
6256         vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
6257
6258         vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
6259         vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL, CPU_BASED_MOV_DR_EXITING);
6260 }
6261
6262 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
6263 {
6264         vmcs_writel(GUEST_DR7, val);
6265 }
6266
6267 static int handle_cpuid(struct kvm_vcpu *vcpu)
6268 {
6269         return kvm_emulate_cpuid(vcpu);
6270 }
6271
6272 static int handle_rdmsr(struct kvm_vcpu *vcpu)
6273 {
6274         u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
6275         struct msr_data msr_info;
6276
6277         msr_info.index = ecx;
6278         msr_info.host_initiated = false;
6279         if (vmx_get_msr(vcpu, &msr_info)) {
6280                 trace_kvm_msr_read_ex(ecx);
6281                 kvm_inject_gp(vcpu, 0);
6282                 return 1;
6283         }
6284
6285         trace_kvm_msr_read(ecx, msr_info.data);
6286
6287         /* FIXME: handling of bits 32:63 of rax, rdx */
6288         vcpu->arch.regs[VCPU_REGS_RAX] = msr_info.data & -1u;
6289         vcpu->arch.regs[VCPU_REGS_RDX] = (msr_info.data >> 32) & -1u;
6290         return kvm_skip_emulated_instruction(vcpu);
6291 }
6292
6293 static int handle_wrmsr(struct kvm_vcpu *vcpu)
6294 {
6295         struct msr_data msr;
6296         u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
6297         u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
6298                 | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
6299
6300         msr.data = data;
6301         msr.index = ecx;
6302         msr.host_initiated = false;
6303         if (kvm_set_msr(vcpu, &msr) != 0) {
6304                 trace_kvm_msr_write_ex(ecx, data);
6305                 kvm_inject_gp(vcpu, 0);
6306                 return 1;
6307         }
6308
6309         trace_kvm_msr_write(ecx, data);
6310         return kvm_skip_emulated_instruction(vcpu);
6311 }
6312
6313 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
6314 {
6315         kvm_apic_update_ppr(vcpu);
6316         return 1;
6317 }
6318
6319 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
6320 {
6321         vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
6322                         CPU_BASED_VIRTUAL_INTR_PENDING);
6323
6324         kvm_make_request(KVM_REQ_EVENT, vcpu);
6325
6326         ++vcpu->stat.irq_window_exits;
6327         return 1;
6328 }
6329
6330 static int handle_halt(struct kvm_vcpu *vcpu)
6331 {
6332         return kvm_emulate_halt(vcpu);
6333 }
6334
6335 static int handle_vmcall(struct kvm_vcpu *vcpu)
6336 {
6337         return kvm_emulate_hypercall(vcpu);
6338 }
6339
6340 static int handle_invd(struct kvm_vcpu *vcpu)
6341 {
6342         return emulate_instruction(vcpu, 0) == EMULATE_DONE;
6343 }
6344
6345 static int handle_invlpg(struct kvm_vcpu *vcpu)
6346 {
6347         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6348
6349         kvm_mmu_invlpg(vcpu, exit_qualification);
6350         return kvm_skip_emulated_instruction(vcpu);
6351 }
6352
6353 static int handle_rdpmc(struct kvm_vcpu *vcpu)
6354 {
6355         int err;
6356
6357         err = kvm_rdpmc(vcpu);
6358         return kvm_complete_insn_gp(vcpu, err);
6359 }
6360
6361 static int handle_wbinvd(struct kvm_vcpu *vcpu)
6362 {
6363         return kvm_emulate_wbinvd(vcpu);
6364 }
6365
6366 static int handle_xsetbv(struct kvm_vcpu *vcpu)
6367 {
6368         u64 new_bv = kvm_read_edx_eax(vcpu);
6369         u32 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
6370
6371         if (kvm_set_xcr(vcpu, index, new_bv) == 0)
6372                 return kvm_skip_emulated_instruction(vcpu);
6373         return 1;
6374 }
6375
6376 static int handle_xsaves(struct kvm_vcpu *vcpu)
6377 {
6378         kvm_skip_emulated_instruction(vcpu);
6379         WARN(1, "this should never happen\n");
6380         return 1;
6381 }
6382
6383 static int handle_xrstors(struct kvm_vcpu *vcpu)
6384 {
6385         kvm_skip_emulated_instruction(vcpu);
6386         WARN(1, "this should never happen\n");
6387         return 1;
6388 }
6389
6390 static int handle_apic_access(struct kvm_vcpu *vcpu)
6391 {
6392         if (likely(fasteoi)) {
6393                 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6394                 int access_type, offset;
6395
6396                 access_type = exit_qualification & APIC_ACCESS_TYPE;
6397                 offset = exit_qualification & APIC_ACCESS_OFFSET;
6398                 /*
6399                  * Sane guest uses MOV to write EOI, with written value
6400                  * not cared. So make a short-circuit here by avoiding
6401                  * heavy instruction emulation.
6402                  */
6403                 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
6404                     (offset == APIC_EOI)) {
6405                         kvm_lapic_set_eoi(vcpu);
6406                         return kvm_skip_emulated_instruction(vcpu);
6407                 }
6408         }
6409         return emulate_instruction(vcpu, 0) == EMULATE_DONE;
6410 }
6411
6412 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
6413 {
6414         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6415         int vector = exit_qualification & 0xff;
6416
6417         /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
6418         kvm_apic_set_eoi_accelerated(vcpu, vector);
6419         return 1;
6420 }
6421
6422 static int handle_apic_write(struct kvm_vcpu *vcpu)
6423 {
6424         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6425         u32 offset = exit_qualification & 0xfff;
6426
6427         /* APIC-write VM exit is trap-like and thus no need to adjust IP */
6428         kvm_apic_write_nodecode(vcpu, offset);
6429         return 1;
6430 }
6431
6432 static int handle_task_switch(struct kvm_vcpu *vcpu)
6433 {
6434         struct vcpu_vmx *vmx = to_vmx(vcpu);
6435         unsigned long exit_qualification;
6436         bool has_error_code = false;
6437         u32 error_code = 0;
6438         u16 tss_selector;
6439         int reason, type, idt_v, idt_index;
6440
6441         idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
6442         idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
6443         type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
6444
6445         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6446
6447         reason = (u32)exit_qualification >> 30;
6448         if (reason == TASK_SWITCH_GATE && idt_v) {
6449                 switch (type) {
6450                 case INTR_TYPE_NMI_INTR:
6451                         vcpu->arch.nmi_injected = false;
6452                         vmx_set_nmi_mask(vcpu, true);
6453                         break;
6454                 case INTR_TYPE_EXT_INTR:
6455                 case INTR_TYPE_SOFT_INTR:
6456                         kvm_clear_interrupt_queue(vcpu);
6457                         break;
6458                 case INTR_TYPE_HARD_EXCEPTION:
6459                         if (vmx->idt_vectoring_info &
6460                             VECTORING_INFO_DELIVER_CODE_MASK) {
6461                                 has_error_code = true;
6462                                 error_code =
6463                                         vmcs_read32(IDT_VECTORING_ERROR_CODE);
6464                         }
6465                         /* fall through */
6466                 case INTR_TYPE_SOFT_EXCEPTION:
6467                         kvm_clear_exception_queue(vcpu);
6468                         break;
6469                 default:
6470                         break;
6471                 }
6472         }
6473         tss_selector = exit_qualification;
6474
6475         if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
6476                        type != INTR_TYPE_EXT_INTR &&
6477                        type != INTR_TYPE_NMI_INTR))
6478                 skip_emulated_instruction(vcpu);
6479
6480         if (kvm_task_switch(vcpu, tss_selector,
6481                             type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason,
6482                             has_error_code, error_code) == EMULATE_FAIL) {
6483                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6484                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6485                 vcpu->run->internal.ndata = 0;
6486                 return 0;
6487         }
6488
6489         /*
6490          * TODO: What about debug traps on tss switch?
6491          *       Are we supposed to inject them and update dr6?
6492          */
6493
6494         return 1;
6495 }
6496
6497 static int handle_ept_violation(struct kvm_vcpu *vcpu)
6498 {
6499         unsigned long exit_qualification;
6500         gpa_t gpa;
6501         u64 error_code;
6502
6503         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6504
6505         /*
6506          * EPT violation happened while executing iret from NMI,
6507          * "blocked by NMI" bit has to be set before next VM entry.
6508          * There are errata that may cause this bit to not be set:
6509          * AAK134, BY25.
6510          */
6511         if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
6512                         cpu_has_virtual_nmis() &&
6513                         (exit_qualification & INTR_INFO_UNBLOCK_NMI))
6514                 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
6515
6516         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6517         trace_kvm_page_fault(gpa, exit_qualification);
6518
6519         /* Is it a read fault? */
6520         error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
6521                      ? PFERR_USER_MASK : 0;
6522         /* Is it a write fault? */
6523         error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
6524                       ? PFERR_WRITE_MASK : 0;
6525         /* Is it a fetch fault? */
6526         error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
6527                       ? PFERR_FETCH_MASK : 0;
6528         /* ept page table entry is present? */
6529         error_code |= (exit_qualification &
6530                        (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
6531                         EPT_VIOLATION_EXECUTABLE))
6532                       ? PFERR_PRESENT_MASK : 0;
6533
6534         error_code |= (exit_qualification & 0x100) != 0 ?
6535                PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
6536
6537         vcpu->arch.exit_qualification = exit_qualification;
6538         return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
6539 }
6540
6541 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
6542 {
6543         int ret;
6544         gpa_t gpa;
6545
6546         /*
6547          * A nested guest cannot optimize MMIO vmexits, because we have an
6548          * nGPA here instead of the required GPA.
6549          */
6550         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6551         if (!is_guest_mode(vcpu) &&
6552             !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
6553                 trace_kvm_fast_mmio(gpa);
6554                 return kvm_skip_emulated_instruction(vcpu);
6555         }
6556
6557         ret = kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
6558         if (ret >= 0)
6559                 return ret;
6560
6561         /* It is the real ept misconfig */
6562         WARN_ON(1);
6563
6564         vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
6565         vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_MISCONFIG;
6566
6567         return 0;
6568 }
6569
6570 static int handle_nmi_window(struct kvm_vcpu *vcpu)
6571 {
6572         vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
6573                         CPU_BASED_VIRTUAL_NMI_PENDING);
6574         ++vcpu->stat.nmi_window_exits;
6575         kvm_make_request(KVM_REQ_EVENT, vcpu);
6576
6577         return 1;
6578 }
6579
6580 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
6581 {
6582         struct vcpu_vmx *vmx = to_vmx(vcpu);
6583         enum emulation_result err = EMULATE_DONE;
6584         int ret = 1;
6585         u32 cpu_exec_ctrl;
6586         bool intr_window_requested;
6587         unsigned count = 130;
6588
6589         cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
6590         intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
6591
6592         while (vmx->emulation_required && count-- != 0) {
6593                 if (intr_window_requested && vmx_interrupt_allowed(vcpu))
6594                         return handle_interrupt_window(&vmx->vcpu);
6595
6596                 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
6597                         return 1;
6598
6599                 err = emulate_instruction(vcpu, EMULTYPE_NO_REEXECUTE);
6600
6601                 if (err == EMULATE_USER_EXIT) {
6602                         ++vcpu->stat.mmio_exits;
6603                         ret = 0;
6604                         goto out;
6605                 }
6606
6607                 if (err != EMULATE_DONE) {
6608                         vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6609                         vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6610                         vcpu->run->internal.ndata = 0;
6611                         return 0;
6612                 }
6613
6614                 if (vcpu->arch.halt_request) {
6615                         vcpu->arch.halt_request = 0;
6616                         ret = kvm_vcpu_halt(vcpu);
6617                         goto out;
6618                 }
6619
6620                 if (signal_pending(current))
6621                         goto out;
6622                 if (need_resched())
6623                         schedule();
6624         }
6625
6626 out:
6627         return ret;
6628 }
6629
6630 static int __grow_ple_window(int val)
6631 {
6632         if (ple_window_grow < 1)
6633                 return ple_window;
6634
6635         val = min(val, ple_window_actual_max);
6636
6637         if (ple_window_grow < ple_window)
6638                 val *= ple_window_grow;
6639         else
6640                 val += ple_window_grow;
6641
6642         return val;
6643 }
6644
6645 static int __shrink_ple_window(int val, int modifier, int minimum)
6646 {
6647         if (modifier < 1)
6648                 return ple_window;
6649
6650         if (modifier < ple_window)
6651                 val /= modifier;
6652         else
6653                 val -= modifier;
6654
6655         return max(val, minimum);
6656 }
6657
6658 static void grow_ple_window(struct kvm_vcpu *vcpu)
6659 {
6660         struct vcpu_vmx *vmx = to_vmx(vcpu);
6661         int old = vmx->ple_window;
6662
6663         vmx->ple_window = __grow_ple_window(old);
6664
6665         if (vmx->ple_window != old)
6666                 vmx->ple_window_dirty = true;
6667
6668         trace_kvm_ple_window_grow(vcpu->vcpu_id, vmx->ple_window, old);
6669 }
6670
6671 static void shrink_ple_window(struct kvm_vcpu *vcpu)
6672 {
6673         struct vcpu_vmx *vmx = to_vmx(vcpu);
6674         int old = vmx->ple_window;
6675
6676         vmx->ple_window = __shrink_ple_window(old,
6677                                               ple_window_shrink, ple_window);
6678
6679         if (vmx->ple_window != old)
6680                 vmx->ple_window_dirty = true;
6681
6682         trace_kvm_ple_window_shrink(vcpu->vcpu_id, vmx->ple_window, old);
6683 }
6684
6685 /*
6686  * ple_window_actual_max is computed to be one grow_ple_window() below
6687  * ple_window_max. (See __grow_ple_window for the reason.)
6688  * This prevents overflows, because ple_window_max is int.
6689  * ple_window_max effectively rounded down to a multiple of ple_window_grow in
6690  * this process.
6691  * ple_window_max is also prevented from setting vmx->ple_window < ple_window.
6692  */
6693 static void update_ple_window_actual_max(void)
6694 {
6695         ple_window_actual_max =
6696                         __shrink_ple_window(max(ple_window_max, ple_window),
6697                                             ple_window_grow, INT_MIN);
6698 }
6699
6700 /*
6701  * Handler for POSTED_INTERRUPT_WAKEUP_VECTOR.
6702  */
6703 static void wakeup_handler(void)
6704 {
6705         struct kvm_vcpu *vcpu;
6706         int cpu = smp_processor_id();
6707
6708         spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
6709         list_for_each_entry(vcpu, &per_cpu(blocked_vcpu_on_cpu, cpu),
6710                         blocked_vcpu_list) {
6711                 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
6712
6713                 if (pi_test_on(pi_desc) == 1)
6714                         kvm_vcpu_kick(vcpu);
6715         }
6716         spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
6717 }
6718
6719 void vmx_enable_tdp(void)
6720 {
6721         kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
6722                 enable_ept_ad_bits ? VMX_EPT_ACCESS_BIT : 0ull,
6723                 enable_ept_ad_bits ? VMX_EPT_DIRTY_BIT : 0ull,
6724                 0ull, VMX_EPT_EXECUTABLE_MASK,
6725                 cpu_has_vmx_ept_execute_only() ? 0ull : VMX_EPT_READABLE_MASK,
6726                 VMX_EPT_RWX_MASK, 0ull);
6727
6728         ept_set_mmio_spte_mask();
6729         kvm_enable_tdp();
6730 }
6731
6732 static __init int hardware_setup(void)
6733 {
6734         int r = -ENOMEM, i, msr;
6735
6736         rdmsrl_safe(MSR_EFER, &host_efer);
6737
6738         for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)
6739                 kvm_define_shared_msr(i, vmx_msr_index[i]);
6740
6741         for (i = 0; i < VMX_BITMAP_NR; i++) {
6742                 vmx_bitmap[i] = (unsigned long *)__get_free_page(GFP_KERNEL);
6743                 if (!vmx_bitmap[i])
6744                         goto out;
6745         }
6746
6747         vmx_io_bitmap_b = (unsigned long *)__get_free_page(GFP_KERNEL);
6748         memset(vmx_vmread_bitmap, 0xff, PAGE_SIZE);
6749         memset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE);
6750
6751         /*
6752          * Allow direct access to the PC debug port (it is often used for I/O
6753          * delays, but the vmexits simply slow things down).
6754          */
6755         memset(vmx_io_bitmap_a, 0xff, PAGE_SIZE);
6756         clear_bit(0x80, vmx_io_bitmap_a);
6757
6758         memset(vmx_io_bitmap_b, 0xff, PAGE_SIZE);
6759
6760         memset(vmx_msr_bitmap_legacy, 0xff, PAGE_SIZE);
6761         memset(vmx_msr_bitmap_longmode, 0xff, PAGE_SIZE);
6762
6763         if (setup_vmcs_config(&vmcs_config) < 0) {
6764                 r = -EIO;
6765                 goto out;
6766         }
6767
6768         if (boot_cpu_has(X86_FEATURE_NX))
6769                 kvm_enable_efer_bits(EFER_NX);
6770
6771         if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
6772                 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
6773                 enable_vpid = 0;
6774
6775         if (!cpu_has_vmx_shadow_vmcs())
6776                 enable_shadow_vmcs = 0;
6777         if (enable_shadow_vmcs)
6778                 init_vmcs_shadow_fields();
6779
6780         if (!cpu_has_vmx_ept() ||
6781             !cpu_has_vmx_ept_4levels() ||
6782             !cpu_has_vmx_ept_mt_wb()) {
6783                 enable_ept = 0;
6784                 enable_unrestricted_guest = 0;
6785                 enable_ept_ad_bits = 0;
6786         }
6787
6788         if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
6789                 enable_ept_ad_bits = 0;
6790
6791         if (!cpu_has_vmx_unrestricted_guest())
6792                 enable_unrestricted_guest = 0;
6793
6794         if (!cpu_has_vmx_flexpriority())
6795                 flexpriority_enabled = 0;
6796
6797         /*
6798          * set_apic_access_page_addr() is used to reload apic access
6799          * page upon invalidation.  No need to do anything if not
6800          * using the APIC_ACCESS_ADDR VMCS field.
6801          */
6802         if (!flexpriority_enabled)
6803                 kvm_x86_ops->set_apic_access_page_addr = NULL;
6804
6805         if (!cpu_has_vmx_tpr_shadow())
6806                 kvm_x86_ops->update_cr8_intercept = NULL;
6807
6808         if (enable_ept && !cpu_has_vmx_ept_2m_page())
6809                 kvm_disable_largepages();
6810
6811         if (!cpu_has_vmx_ple())
6812                 ple_gap = 0;
6813
6814         if (!cpu_has_vmx_apicv()) {
6815                 enable_apicv = 0;
6816                 kvm_x86_ops->sync_pir_to_irr = NULL;
6817         }
6818
6819         if (cpu_has_vmx_tsc_scaling()) {
6820                 kvm_has_tsc_control = true;
6821                 kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
6822                 kvm_tsc_scaling_ratio_frac_bits = 48;
6823         }
6824
6825         vmx_disable_intercept_for_msr(MSR_FS_BASE, false);
6826         vmx_disable_intercept_for_msr(MSR_GS_BASE, false);
6827         vmx_disable_intercept_for_msr(MSR_KERNEL_GS_BASE, true);
6828         vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_CS, false);
6829         vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_ESP, false);
6830         vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_EIP, false);
6831
6832         memcpy(vmx_msr_bitmap_legacy_x2apic_apicv,
6833                         vmx_msr_bitmap_legacy, PAGE_SIZE);
6834         memcpy(vmx_msr_bitmap_longmode_x2apic_apicv,
6835                         vmx_msr_bitmap_longmode, PAGE_SIZE);
6836         memcpy(vmx_msr_bitmap_legacy_x2apic,
6837                         vmx_msr_bitmap_legacy, PAGE_SIZE);
6838         memcpy(vmx_msr_bitmap_longmode_x2apic,
6839                         vmx_msr_bitmap_longmode, PAGE_SIZE);
6840
6841         set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
6842
6843         for (msr = 0x800; msr <= 0x8ff; msr++) {
6844                 if (msr == 0x839 /* TMCCT */)
6845                         continue;
6846                 vmx_disable_intercept_msr_x2apic(msr, MSR_TYPE_R, true);
6847         }
6848
6849         /*
6850          * TPR reads and writes can be virtualized even if virtual interrupt
6851          * delivery is not in use.
6852          */
6853         vmx_disable_intercept_msr_x2apic(0x808, MSR_TYPE_W, true);
6854         vmx_disable_intercept_msr_x2apic(0x808, MSR_TYPE_R | MSR_TYPE_W, false);
6855
6856         /* EOI */
6857         vmx_disable_intercept_msr_x2apic(0x80b, MSR_TYPE_W, true);
6858         /* SELF-IPI */
6859         vmx_disable_intercept_msr_x2apic(0x83f, MSR_TYPE_W, true);
6860
6861         if (enable_ept)
6862                 vmx_enable_tdp();
6863         else
6864                 kvm_disable_tdp();
6865
6866         update_ple_window_actual_max();
6867
6868         /*
6869          * Only enable PML when hardware supports PML feature, and both EPT
6870          * and EPT A/D bit features are enabled -- PML depends on them to work.
6871          */
6872         if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
6873                 enable_pml = 0;
6874
6875         if (!enable_pml) {
6876                 kvm_x86_ops->slot_enable_log_dirty = NULL;
6877                 kvm_x86_ops->slot_disable_log_dirty = NULL;
6878                 kvm_x86_ops->flush_log_dirty = NULL;
6879                 kvm_x86_ops->enable_log_dirty_pt_masked = NULL;
6880         }
6881
6882         if (cpu_has_vmx_preemption_timer() && enable_preemption_timer) {
6883                 u64 vmx_msr;
6884
6885                 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
6886                 cpu_preemption_timer_multi =
6887                          vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
6888         } else {
6889                 kvm_x86_ops->set_hv_timer = NULL;
6890                 kvm_x86_ops->cancel_hv_timer = NULL;
6891         }
6892
6893         kvm_set_posted_intr_wakeup_handler(wakeup_handler);
6894
6895         kvm_mce_cap_supported |= MCG_LMCE_P;
6896
6897         return alloc_kvm_area();
6898
6899 out:
6900         for (i = 0; i < VMX_BITMAP_NR; i++)
6901                 free_page((unsigned long)vmx_bitmap[i]);
6902
6903     return r;
6904 }
6905
6906 static __exit void hardware_unsetup(void)
6907 {
6908         int i;
6909
6910         for (i = 0; i < VMX_BITMAP_NR; i++)
6911                 free_page((unsigned long)vmx_bitmap[i]);
6912
6913         free_kvm_area();
6914 }
6915
6916 /*
6917  * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
6918  * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
6919  */
6920 static int handle_pause(struct kvm_vcpu *vcpu)
6921 {
6922         if (ple_gap)
6923                 grow_ple_window(vcpu);
6924
6925         /*
6926          * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
6927          * VM-execution control is ignored if CPL > 0. OTOH, KVM
6928          * never set PAUSE_EXITING and just set PLE if supported,
6929          * so the vcpu must be CPL=0 if it gets a PAUSE exit.
6930          */
6931         kvm_vcpu_on_spin(vcpu, true);
6932         return kvm_skip_emulated_instruction(vcpu);
6933 }
6934
6935 static int handle_nop(struct kvm_vcpu *vcpu)
6936 {
6937         return kvm_skip_emulated_instruction(vcpu);
6938 }
6939
6940 static int handle_mwait(struct kvm_vcpu *vcpu)
6941 {
6942         printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
6943         return handle_nop(vcpu);
6944 }
6945
6946 static int handle_invalid_op(struct kvm_vcpu *vcpu)
6947 {
6948         kvm_queue_exception(vcpu, UD_VECTOR);
6949         return 1;
6950 }
6951
6952 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
6953 {
6954         return 1;
6955 }
6956
6957 static int handle_monitor(struct kvm_vcpu *vcpu)
6958 {
6959         printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
6960         return handle_nop(vcpu);
6961 }
6962
6963 /*
6964  * To run an L2 guest, we need a vmcs02 based on the L1-specified vmcs12.
6965  * We could reuse a single VMCS for all the L2 guests, but we also want the
6966  * option to allocate a separate vmcs02 for each separate loaded vmcs12 - this
6967  * allows keeping them loaded on the processor, and in the future will allow
6968  * optimizations where prepare_vmcs02 doesn't need to set all the fields on
6969  * every entry if they never change.
6970  * So we keep, in vmx->nested.vmcs02_pool, a cache of size VMCS02_POOL_SIZE
6971  * (>=0) with a vmcs02 for each recently loaded vmcs12s, most recent first.
6972  *
6973  * The following functions allocate and free a vmcs02 in this pool.
6974  */
6975
6976 /* Get a VMCS from the pool to use as vmcs02 for the current vmcs12. */
6977 static struct loaded_vmcs *nested_get_current_vmcs02(struct vcpu_vmx *vmx)
6978 {
6979         struct vmcs02_list *item;
6980         list_for_each_entry(item, &vmx->nested.vmcs02_pool, list)
6981                 if (item->vmptr == vmx->nested.current_vmptr) {
6982                         list_move(&item->list, &vmx->nested.vmcs02_pool);
6983                         return &item->vmcs02;
6984                 }
6985
6986         if (vmx->nested.vmcs02_num >= max(VMCS02_POOL_SIZE, 1)) {
6987                 /* Recycle the least recently used VMCS. */
6988                 item = list_last_entry(&vmx->nested.vmcs02_pool,
6989                                        struct vmcs02_list, list);
6990                 item->vmptr = vmx->nested.current_vmptr;
6991                 list_move(&item->list, &vmx->nested.vmcs02_pool);
6992                 return &item->vmcs02;
6993         }
6994
6995         /* Create a new VMCS */
6996         item = kzalloc(sizeof(struct vmcs02_list), GFP_KERNEL);
6997         if (!item)
6998                 return NULL;
6999         item->vmcs02.vmcs = alloc_vmcs();
7000         item->vmcs02.shadow_vmcs = NULL;
7001         if (!item->vmcs02.vmcs) {
7002                 kfree(item);
7003                 return NULL;
7004         }
7005         loaded_vmcs_init(&item->vmcs02);
7006         item->vmptr = vmx->nested.current_vmptr;
7007         list_add(&(item->list), &(vmx->nested.vmcs02_pool));
7008         vmx->nested.vmcs02_num++;
7009         return &item->vmcs02;
7010 }
7011
7012 /* Free and remove from pool a vmcs02 saved for a vmcs12 (if there is one) */
7013 static void nested_free_vmcs02(struct vcpu_vmx *vmx, gpa_t vmptr)
7014 {
7015         struct vmcs02_list *item;
7016         list_for_each_entry(item, &vmx->nested.vmcs02_pool, list)
7017                 if (item->vmptr == vmptr) {
7018                         free_loaded_vmcs(&item->vmcs02);
7019                         list_del(&item->list);
7020                         kfree(item);
7021                         vmx->nested.vmcs02_num--;
7022                         return;
7023                 }
7024 }
7025
7026 /*
7027  * Free all VMCSs saved for this vcpu, except the one pointed by
7028  * vmx->loaded_vmcs. We must be running L1, so vmx->loaded_vmcs
7029  * must be &vmx->vmcs01.
7030  */
7031 static void nested_free_all_saved_vmcss(struct vcpu_vmx *vmx)
7032 {
7033         struct vmcs02_list *item, *n;
7034
7035         WARN_ON(vmx->loaded_vmcs != &vmx->vmcs01);
7036         list_for_each_entry_safe(item, n, &vmx->nested.vmcs02_pool, list) {
7037                 /*
7038                  * Something will leak if the above WARN triggers.  Better than
7039                  * a use-after-free.
7040                  */
7041                 if (vmx->loaded_vmcs == &item->vmcs02)
7042                         continue;
7043
7044                 free_loaded_vmcs(&item->vmcs02);
7045                 list_del(&item->list);
7046                 kfree(item);
7047                 vmx->nested.vmcs02_num--;
7048         }
7049 }
7050
7051 /*
7052  * The following 3 functions, nested_vmx_succeed()/failValid()/failInvalid(),
7053  * set the success or error code of an emulated VMX instruction, as specified
7054  * by Vol 2B, VMX Instruction Reference, "Conventions".
7055  */
7056 static void nested_vmx_succeed(struct kvm_vcpu *vcpu)
7057 {
7058         vmx_set_rflags(vcpu, vmx_get_rflags(vcpu)
7059                         & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
7060                             X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF));
7061 }
7062
7063 static void nested_vmx_failInvalid(struct kvm_vcpu *vcpu)
7064 {
7065         vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
7066                         & ~(X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
7067                             X86_EFLAGS_SF | X86_EFLAGS_OF))
7068                         | X86_EFLAGS_CF);
7069 }
7070
7071 static void nested_vmx_failValid(struct kvm_vcpu *vcpu,
7072                                         u32 vm_instruction_error)
7073 {
7074         if (to_vmx(vcpu)->nested.current_vmptr == -1ull) {
7075                 /*
7076                  * failValid writes the error number to the current VMCS, which
7077                  * can't be done there isn't a current VMCS.
7078                  */
7079                 nested_vmx_failInvalid(vcpu);
7080                 return;
7081         }
7082         vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
7083                         & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
7084                             X86_EFLAGS_SF | X86_EFLAGS_OF))
7085                         | X86_EFLAGS_ZF);
7086         get_vmcs12(vcpu)->vm_instruction_error = vm_instruction_error;
7087         /*
7088          * We don't need to force a shadow sync because
7089          * VM_INSTRUCTION_ERROR is not shadowed
7090          */
7091 }
7092
7093 static void nested_vmx_abort(struct kvm_vcpu *vcpu, u32 indicator)
7094 {
7095         /* TODO: not to reset guest simply here. */
7096         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
7097         pr_debug_ratelimited("kvm: nested vmx abort, indicator %d\n", indicator);
7098 }
7099
7100 static enum hrtimer_restart vmx_preemption_timer_fn(struct hrtimer *timer)
7101 {
7102         struct vcpu_vmx *vmx =
7103                 container_of(timer, struct vcpu_vmx, nested.preemption_timer);
7104
7105         vmx->nested.preemption_timer_expired = true;
7106         kvm_make_request(KVM_REQ_EVENT, &vmx->vcpu);
7107         kvm_vcpu_kick(&vmx->vcpu);
7108
7109         return HRTIMER_NORESTART;
7110 }
7111
7112 /*
7113  * Decode the memory-address operand of a vmx instruction, as recorded on an
7114  * exit caused by such an instruction (run by a guest hypervisor).
7115  * On success, returns 0. When the operand is invalid, returns 1 and throws
7116  * #UD or #GP.
7117  */
7118 static int get_vmx_mem_address(struct kvm_vcpu *vcpu,
7119                                  unsigned long exit_qualification,
7120                                  u32 vmx_instruction_info, bool wr, gva_t *ret)
7121 {
7122         gva_t off;
7123         bool exn;
7124         struct kvm_segment s;
7125
7126         /*
7127          * According to Vol. 3B, "Information for VM Exits Due to Instruction
7128          * Execution", on an exit, vmx_instruction_info holds most of the
7129          * addressing components of the operand. Only the displacement part
7130          * is put in exit_qualification (see 3B, "Basic VM-Exit Information").
7131          * For how an actual address is calculated from all these components,
7132          * refer to Vol. 1, "Operand Addressing".
7133          */
7134         int  scaling = vmx_instruction_info & 3;
7135         int  addr_size = (vmx_instruction_info >> 7) & 7;
7136         bool is_reg = vmx_instruction_info & (1u << 10);
7137         int  seg_reg = (vmx_instruction_info >> 15) & 7;
7138         int  index_reg = (vmx_instruction_info >> 18) & 0xf;
7139         bool index_is_valid = !(vmx_instruction_info & (1u << 22));
7140         int  base_reg       = (vmx_instruction_info >> 23) & 0xf;
7141         bool base_is_valid  = !(vmx_instruction_info & (1u << 27));
7142
7143         if (is_reg) {
7144                 kvm_queue_exception(vcpu, UD_VECTOR);
7145                 return 1;
7146         }
7147
7148         /* Addr = segment_base + offset */
7149         /* offset = base + [index * scale] + displacement */
7150         off = exit_qualification; /* holds the displacement */
7151         if (base_is_valid)
7152                 off += kvm_register_read(vcpu, base_reg);
7153         if (index_is_valid)
7154                 off += kvm_register_read(vcpu, index_reg)<<scaling;
7155         vmx_get_segment(vcpu, &s, seg_reg);
7156         *ret = s.base + off;
7157
7158         if (addr_size == 1) /* 32 bit */
7159                 *ret &= 0xffffffff;
7160
7161         /* Checks for #GP/#SS exceptions. */
7162         exn = false;
7163         if (is_long_mode(vcpu)) {
7164                 /* Long mode: #GP(0)/#SS(0) if the memory address is in a
7165                  * non-canonical form. This is the only check on the memory
7166                  * destination for long mode!
7167                  */
7168                 exn = is_noncanonical_address(*ret, vcpu);
7169         } else if (is_protmode(vcpu)) {
7170                 /* Protected mode: apply checks for segment validity in the
7171                  * following order:
7172                  * - segment type check (#GP(0) may be thrown)
7173                  * - usability check (#GP(0)/#SS(0))
7174                  * - limit check (#GP(0)/#SS(0))
7175                  */
7176                 if (wr)
7177                         /* #GP(0) if the destination operand is located in a
7178                          * read-only data segment or any code segment.
7179                          */
7180                         exn = ((s.type & 0xa) == 0 || (s.type & 8));
7181                 else
7182                         /* #GP(0) if the source operand is located in an
7183                          * execute-only code segment
7184                          */
7185                         exn = ((s.type & 0xa) == 8);
7186                 if (exn) {
7187                         kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
7188                         return 1;
7189                 }
7190                 /* Protected mode: #GP(0)/#SS(0) if the segment is unusable.
7191                  */
7192                 exn = (s.unusable != 0);
7193                 /* Protected mode: #GP(0)/#SS(0) if the memory
7194                  * operand is outside the segment limit.
7195                  */
7196                 exn = exn || (off + sizeof(u64) > s.limit);
7197         }
7198         if (exn) {
7199                 kvm_queue_exception_e(vcpu,
7200                                       seg_reg == VCPU_SREG_SS ?
7201                                                 SS_VECTOR : GP_VECTOR,
7202                                       0);
7203                 return 1;
7204         }
7205
7206         return 0;
7207 }
7208
7209 static int nested_vmx_get_vmptr(struct kvm_vcpu *vcpu, gpa_t *vmpointer)
7210 {
7211         gva_t gva;
7212         struct x86_exception e;
7213
7214         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
7215                         vmcs_read32(VMX_INSTRUCTION_INFO), false, &gva))
7216                 return 1;
7217
7218         if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, vmpointer,
7219                                 sizeof(*vmpointer), &e)) {
7220                 kvm_inject_page_fault(vcpu, &e);
7221                 return 1;
7222         }
7223
7224         return 0;
7225 }
7226
7227 static int enter_vmx_operation(struct kvm_vcpu *vcpu)
7228 {
7229         struct vcpu_vmx *vmx = to_vmx(vcpu);
7230         struct vmcs *shadow_vmcs;
7231
7232         if (cpu_has_vmx_msr_bitmap()) {
7233                 vmx->nested.msr_bitmap =
7234                                 (unsigned long *)__get_free_page(GFP_KERNEL);
7235                 if (!vmx->nested.msr_bitmap)
7236                         goto out_msr_bitmap;
7237         }
7238
7239         vmx->nested.cached_vmcs12 = kmalloc(VMCS12_SIZE, GFP_KERNEL);
7240         if (!vmx->nested.cached_vmcs12)
7241                 goto out_cached_vmcs12;
7242
7243         if (enable_shadow_vmcs) {
7244                 shadow_vmcs = alloc_vmcs();
7245                 if (!shadow_vmcs)
7246                         goto out_shadow_vmcs;
7247                 /* mark vmcs as shadow */
7248                 shadow_vmcs->revision_id |= (1u << 31);
7249                 /* init shadow vmcs */
7250                 vmcs_clear(shadow_vmcs);
7251                 vmx->vmcs01.shadow_vmcs = shadow_vmcs;
7252         }
7253
7254         INIT_LIST_HEAD(&(vmx->nested.vmcs02_pool));
7255         vmx->nested.vmcs02_num = 0;
7256
7257         hrtimer_init(&vmx->nested.preemption_timer, CLOCK_MONOTONIC,
7258                      HRTIMER_MODE_REL_PINNED);
7259         vmx->nested.preemption_timer.function = vmx_preemption_timer_fn;
7260
7261         vmx->nested.vmxon = true;
7262         return 0;
7263
7264 out_shadow_vmcs:
7265         kfree(vmx->nested.cached_vmcs12);
7266
7267 out_cached_vmcs12:
7268         free_page((unsigned long)vmx->nested.msr_bitmap);
7269
7270 out_msr_bitmap:
7271         return -ENOMEM;
7272 }
7273
7274 /*
7275  * Emulate the VMXON instruction.
7276  * Currently, we just remember that VMX is active, and do not save or even
7277  * inspect the argument to VMXON (the so-called "VMXON pointer") because we
7278  * do not currently need to store anything in that guest-allocated memory
7279  * region. Consequently, VMCLEAR and VMPTRLD also do not verify that the their
7280  * argument is different from the VMXON pointer (which the spec says they do).
7281  */
7282 static int handle_vmon(struct kvm_vcpu *vcpu)
7283 {
7284         int ret;
7285         gpa_t vmptr;
7286         struct page *page;
7287         struct vcpu_vmx *vmx = to_vmx(vcpu);
7288         const u64 VMXON_NEEDED_FEATURES = FEATURE_CONTROL_LOCKED
7289                 | FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
7290
7291         /*
7292          * The Intel VMX Instruction Reference lists a bunch of bits that are
7293          * prerequisite to running VMXON, most notably cr4.VMXE must be set to
7294          * 1 (see vmx_set_cr4() for when we allow the guest to set this).
7295          * Otherwise, we should fail with #UD.  But most faulting conditions
7296          * have already been checked by hardware, prior to the VM-exit for
7297          * VMXON.  We do test guest cr4.VMXE because processor CR4 always has
7298          * that bit set to 1 in non-root mode.
7299          */
7300         if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE)) {
7301                 kvm_queue_exception(vcpu, UD_VECTOR);
7302                 return 1;
7303         }
7304
7305         if (vmx->nested.vmxon) {
7306                 nested_vmx_failValid(vcpu, VMXERR_VMXON_IN_VMX_ROOT_OPERATION);
7307                 return kvm_skip_emulated_instruction(vcpu);
7308         }
7309
7310         if ((vmx->msr_ia32_feature_control & VMXON_NEEDED_FEATURES)
7311                         != VMXON_NEEDED_FEATURES) {
7312                 kvm_inject_gp(vcpu, 0);
7313                 return 1;
7314         }
7315
7316         if (nested_vmx_get_vmptr(vcpu, &vmptr))
7317                 return 1;
7318
7319         /*
7320          * SDM 3: 24.11.5
7321          * The first 4 bytes of VMXON region contain the supported
7322          * VMCS revision identifier
7323          *
7324          * Note - IA32_VMX_BASIC[48] will never be 1 for the nested case;
7325          * which replaces physical address width with 32
7326          */
7327         if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {
7328                 nested_vmx_failInvalid(vcpu);
7329                 return kvm_skip_emulated_instruction(vcpu);
7330         }
7331
7332         page = kvm_vcpu_gpa_to_page(vcpu, vmptr);
7333         if (is_error_page(page)) {
7334                 nested_vmx_failInvalid(vcpu);
7335                 return kvm_skip_emulated_instruction(vcpu);
7336         }
7337         if (*(u32 *)kmap(page) != VMCS12_REVISION) {
7338                 kunmap(page);
7339                 kvm_release_page_clean(page);
7340                 nested_vmx_failInvalid(vcpu);
7341                 return kvm_skip_emulated_instruction(vcpu);
7342         }
7343         kunmap(page);
7344         kvm_release_page_clean(page);
7345
7346         vmx->nested.vmxon_ptr = vmptr;
7347         ret = enter_vmx_operation(vcpu);
7348         if (ret)
7349                 return ret;
7350
7351         nested_vmx_succeed(vcpu);
7352         return kvm_skip_emulated_instruction(vcpu);
7353 }
7354
7355 /*
7356  * Intel's VMX Instruction Reference specifies a common set of prerequisites
7357  * for running VMX instructions (except VMXON, whose prerequisites are
7358  * slightly different). It also specifies what exception to inject otherwise.
7359  * Note that many of these exceptions have priority over VM exits, so they
7360  * don't have to be checked again here.
7361  */
7362 static int nested_vmx_check_permission(struct kvm_vcpu *vcpu)
7363 {
7364         if (!to_vmx(vcpu)->nested.vmxon) {
7365                 kvm_queue_exception(vcpu, UD_VECTOR);
7366                 return 0;
7367         }
7368         return 1;
7369 }
7370
7371 static void vmx_disable_shadow_vmcs(struct vcpu_vmx *vmx)
7372 {
7373         vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL, SECONDARY_EXEC_SHADOW_VMCS);
7374         vmcs_write64(VMCS_LINK_POINTER, -1ull);
7375 }
7376
7377 static inline void nested_release_vmcs12(struct vcpu_vmx *vmx)
7378 {
7379         if (vmx->nested.current_vmptr == -1ull)
7380                 return;
7381
7382         if (enable_shadow_vmcs) {
7383                 /* copy to memory all shadowed fields in case
7384                    they were modified */
7385                 copy_shadow_to_vmcs12(vmx);
7386                 vmx->nested.sync_shadow_vmcs = false;
7387                 vmx_disable_shadow_vmcs(vmx);
7388         }
7389         vmx->nested.posted_intr_nv = -1;
7390
7391         /* Flush VMCS12 to guest memory */
7392         kvm_vcpu_write_guest_page(&vmx->vcpu,
7393                                   vmx->nested.current_vmptr >> PAGE_SHIFT,
7394                                   vmx->nested.cached_vmcs12, 0, VMCS12_SIZE);
7395
7396         vmx->nested.current_vmptr = -1ull;
7397 }
7398
7399 /*
7400  * Free whatever needs to be freed from vmx->nested when L1 goes down, or
7401  * just stops using VMX.
7402  */
7403 static void free_nested(struct vcpu_vmx *vmx)
7404 {
7405         if (!vmx->nested.vmxon)
7406                 return;
7407
7408         vmx->nested.vmxon = false;
7409         free_vpid(vmx->nested.vpid02);
7410         vmx->nested.posted_intr_nv = -1;
7411         vmx->nested.current_vmptr = -1ull;
7412         if (vmx->nested.msr_bitmap) {
7413                 free_page((unsigned long)vmx->nested.msr_bitmap);
7414                 vmx->nested.msr_bitmap = NULL;
7415         }
7416         if (enable_shadow_vmcs) {
7417                 vmx_disable_shadow_vmcs(vmx);
7418                 vmcs_clear(vmx->vmcs01.shadow_vmcs);
7419                 free_vmcs(vmx->vmcs01.shadow_vmcs);
7420                 vmx->vmcs01.shadow_vmcs = NULL;
7421         }
7422         kfree(vmx->nested.cached_vmcs12);
7423         /* Unpin physical memory we referred to in current vmcs02 */
7424         if (vmx->nested.apic_access_page) {
7425                 kvm_release_page_dirty(vmx->nested.apic_access_page);
7426                 vmx->nested.apic_access_page = NULL;
7427         }
7428         if (vmx->nested.virtual_apic_page) {
7429                 kvm_release_page_dirty(vmx->nested.virtual_apic_page);
7430                 vmx->nested.virtual_apic_page = NULL;
7431         }
7432         if (vmx->nested.pi_desc_page) {
7433                 kunmap(vmx->nested.pi_desc_page);
7434                 kvm_release_page_dirty(vmx->nested.pi_desc_page);
7435                 vmx->nested.pi_desc_page = NULL;
7436                 vmx->nested.pi_desc = NULL;
7437         }
7438
7439         nested_free_all_saved_vmcss(vmx);
7440 }
7441
7442 /* Emulate the VMXOFF instruction */
7443 static int handle_vmoff(struct kvm_vcpu *vcpu)
7444 {
7445         if (!nested_vmx_check_permission(vcpu))
7446                 return 1;
7447         free_nested(to_vmx(vcpu));
7448         nested_vmx_succeed(vcpu);
7449         return kvm_skip_emulated_instruction(vcpu);
7450 }
7451
7452 /* Emulate the VMCLEAR instruction */
7453 static int handle_vmclear(struct kvm_vcpu *vcpu)
7454 {
7455         struct vcpu_vmx *vmx = to_vmx(vcpu);
7456         u32 zero = 0;
7457         gpa_t vmptr;
7458
7459         if (!nested_vmx_check_permission(vcpu))
7460                 return 1;
7461
7462         if (nested_vmx_get_vmptr(vcpu, &vmptr))
7463                 return 1;
7464
7465         if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {
7466                 nested_vmx_failValid(vcpu, VMXERR_VMCLEAR_INVALID_ADDRESS);
7467                 return kvm_skip_emulated_instruction(vcpu);
7468         }
7469
7470         if (vmptr == vmx->nested.vmxon_ptr) {
7471                 nested_vmx_failValid(vcpu, VMXERR_VMCLEAR_VMXON_POINTER);
7472                 return kvm_skip_emulated_instruction(vcpu);
7473         }
7474
7475         if (vmptr == vmx->nested.current_vmptr)
7476                 nested_release_vmcs12(vmx);
7477
7478         kvm_vcpu_write_guest(vcpu,
7479                         vmptr + offsetof(struct vmcs12, launch_state),
7480                         &zero, sizeof(zero));
7481
7482         nested_free_vmcs02(vmx, vmptr);
7483
7484         nested_vmx_succeed(vcpu);
7485         return kvm_skip_emulated_instruction(vcpu);
7486 }
7487
7488 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch);
7489
7490 /* Emulate the VMLAUNCH instruction */
7491 static int handle_vmlaunch(struct kvm_vcpu *vcpu)
7492 {
7493         return nested_vmx_run(vcpu, true);
7494 }
7495
7496 /* Emulate the VMRESUME instruction */
7497 static int handle_vmresume(struct kvm_vcpu *vcpu)
7498 {
7499
7500         return nested_vmx_run(vcpu, false);
7501 }
7502
7503 /*
7504  * Read a vmcs12 field. Since these can have varying lengths and we return
7505  * one type, we chose the biggest type (u64) and zero-extend the return value
7506  * to that size. Note that the caller, handle_vmread, might need to use only
7507  * some of the bits we return here (e.g., on 32-bit guests, only 32 bits of
7508  * 64-bit fields are to be returned).
7509  */
7510 static inline int vmcs12_read_any(struct kvm_vcpu *vcpu,
7511                                   unsigned long field, u64 *ret)
7512 {
7513         short offset = vmcs_field_to_offset(field);
7514         char *p;
7515
7516         if (offset < 0)
7517                 return offset;
7518
7519         p = ((char *)(get_vmcs12(vcpu))) + offset;
7520
7521         switch (vmcs_field_type(field)) {
7522         case VMCS_FIELD_TYPE_NATURAL_WIDTH:
7523                 *ret = *((natural_width *)p);
7524                 return 0;
7525         case VMCS_FIELD_TYPE_U16:
7526                 *ret = *((u16 *)p);
7527                 return 0;
7528         case VMCS_FIELD_TYPE_U32:
7529                 *ret = *((u32 *)p);
7530                 return 0;
7531         case VMCS_FIELD_TYPE_U64:
7532                 *ret = *((u64 *)p);
7533                 return 0;
7534         default:
7535                 WARN_ON(1);
7536                 return -ENOENT;
7537         }
7538 }
7539
7540
7541 static inline int vmcs12_write_any(struct kvm_vcpu *vcpu,
7542                                    unsigned long field, u64 field_value){
7543         short offset = vmcs_field_to_offset(field);
7544         char *p = ((char *) get_vmcs12(vcpu)) + offset;
7545         if (offset < 0)
7546                 return offset;
7547
7548         switch (vmcs_field_type(field)) {
7549         case VMCS_FIELD_TYPE_U16:
7550                 *(u16 *)p = field_value;
7551                 return 0;
7552         case VMCS_FIELD_TYPE_U32:
7553                 *(u32 *)p = field_value;
7554                 return 0;
7555         case VMCS_FIELD_TYPE_U64:
7556                 *(u64 *)p = field_value;
7557                 return 0;
7558         case VMCS_FIELD_TYPE_NATURAL_WIDTH:
7559                 *(natural_width *)p = field_value;
7560                 return 0;
7561         default:
7562                 WARN_ON(1);
7563                 return -ENOENT;
7564         }
7565
7566 }
7567
7568 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx)
7569 {
7570         int i;
7571         unsigned long field;
7572         u64 field_value;
7573         struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
7574         const unsigned long *fields = shadow_read_write_fields;
7575         const int num_fields = max_shadow_read_write_fields;
7576
7577         preempt_disable();
7578
7579         vmcs_load(shadow_vmcs);
7580
7581         for (i = 0; i < num_fields; i++) {
7582                 field = fields[i];
7583                 switch (vmcs_field_type(field)) {
7584                 case VMCS_FIELD_TYPE_U16:
7585                         field_value = vmcs_read16(field);
7586                         break;
7587                 case VMCS_FIELD_TYPE_U32:
7588                         field_value = vmcs_read32(field);
7589                         break;
7590                 case VMCS_FIELD_TYPE_U64:
7591                         field_value = vmcs_read64(field);
7592                         break;
7593                 case VMCS_FIELD_TYPE_NATURAL_WIDTH:
7594                         field_value = vmcs_readl(field);
7595                         break;
7596                 default:
7597                         WARN_ON(1);
7598                         continue;
7599                 }
7600                 vmcs12_write_any(&vmx->vcpu, field, field_value);
7601         }
7602
7603         vmcs_clear(shadow_vmcs);
7604         vmcs_load(vmx->loaded_vmcs->vmcs);
7605
7606         preempt_enable();
7607 }
7608
7609 static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx)
7610 {
7611         const unsigned long *fields[] = {
7612                 shadow_read_write_fields,
7613                 shadow_read_only_fields
7614         };
7615         const int max_fields[] = {
7616                 max_shadow_read_write_fields,
7617                 max_shadow_read_only_fields
7618         };
7619         int i, q;
7620         unsigned long field;
7621         u64 field_value = 0;
7622         struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
7623
7624         vmcs_load(shadow_vmcs);
7625
7626         for (q = 0; q < ARRAY_SIZE(fields); q++) {
7627                 for (i = 0; i < max_fields[q]; i++) {
7628                         field = fields[q][i];
7629                         vmcs12_read_any(&vmx->vcpu, field, &field_value);
7630
7631                         switch (vmcs_field_type(field)) {
7632                         case VMCS_FIELD_TYPE_U16:
7633                                 vmcs_write16(field, (u16)field_value);
7634                                 break;
7635                         case VMCS_FIELD_TYPE_U32:
7636                                 vmcs_write32(field, (u32)field_value);
7637                                 break;
7638                         case VMCS_FIELD_TYPE_U64:
7639                                 vmcs_write64(field, (u64)field_value);
7640                                 break;
7641                         case VMCS_FIELD_TYPE_NATURAL_WIDTH:
7642                                 vmcs_writel(field, (long)field_value);
7643                                 break;
7644                         default:
7645                                 WARN_ON(1);
7646                                 break;
7647                         }
7648                 }
7649         }
7650
7651         vmcs_clear(shadow_vmcs);
7652         vmcs_load(vmx->loaded_vmcs->vmcs);
7653 }
7654
7655 /*
7656  * VMX instructions which assume a current vmcs12 (i.e., that VMPTRLD was
7657  * used before) all generate the same failure when it is missing.
7658  */
7659 static int nested_vmx_check_vmcs12(struct kvm_vcpu *vcpu)
7660 {
7661         struct vcpu_vmx *vmx = to_vmx(vcpu);
7662         if (vmx->nested.current_vmptr == -1ull) {
7663                 nested_vmx_failInvalid(vcpu);
7664                 return 0;
7665         }
7666         return 1;
7667 }
7668
7669 static int handle_vmread(struct kvm_vcpu *vcpu)
7670 {
7671         unsigned long field;
7672         u64 field_value;
7673         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7674         u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7675         gva_t gva = 0;
7676
7677         if (!nested_vmx_check_permission(vcpu))
7678                 return 1;
7679
7680         if (!nested_vmx_check_vmcs12(vcpu))
7681                 return kvm_skip_emulated_instruction(vcpu);
7682
7683         /* Decode instruction info and find the field to read */
7684         field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
7685         /* Read the field, zero-extended to a u64 field_value */
7686         if (vmcs12_read_any(vcpu, field, &field_value) < 0) {
7687                 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
7688                 return kvm_skip_emulated_instruction(vcpu);
7689         }
7690         /*
7691          * Now copy part of this value to register or memory, as requested.
7692          * Note that the number of bits actually copied is 32 or 64 depending
7693          * on the guest's mode (32 or 64 bit), not on the given field's length.
7694          */
7695         if (vmx_instruction_info & (1u << 10)) {
7696                 kvm_register_writel(vcpu, (((vmx_instruction_info) >> 3) & 0xf),
7697                         field_value);
7698         } else {
7699                 if (get_vmx_mem_address(vcpu, exit_qualification,
7700                                 vmx_instruction_info, true, &gva))
7701                         return 1;
7702                 /* _system ok, as hardware has verified cpl=0 */
7703                 kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, gva,
7704                              &field_value, (is_long_mode(vcpu) ? 8 : 4), NULL);
7705         }
7706
7707         nested_vmx_succeed(vcpu);
7708         return kvm_skip_emulated_instruction(vcpu);
7709 }
7710
7711
7712 static int handle_vmwrite(struct kvm_vcpu *vcpu)
7713 {
7714         unsigned long field;
7715         gva_t gva;
7716         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7717         u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7718         /* The value to write might be 32 or 64 bits, depending on L1's long
7719          * mode, and eventually we need to write that into a field of several
7720          * possible lengths. The code below first zero-extends the value to 64
7721          * bit (field_value), and then copies only the appropriate number of
7722          * bits into the vmcs12 field.
7723          */
7724         u64 field_value = 0;
7725         struct x86_exception e;
7726
7727         if (!nested_vmx_check_permission(vcpu))
7728                 return 1;
7729
7730         if (!nested_vmx_check_vmcs12(vcpu))
7731                 return kvm_skip_emulated_instruction(vcpu);
7732
7733         if (vmx_instruction_info & (1u << 10))
7734                 field_value = kvm_register_readl(vcpu,
7735                         (((vmx_instruction_info) >> 3) & 0xf));
7736         else {
7737                 if (get_vmx_mem_address(vcpu, exit_qualification,
7738                                 vmx_instruction_info, false, &gva))
7739                         return 1;
7740                 if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva,
7741                            &field_value, (is_64_bit_mode(vcpu) ? 8 : 4), &e)) {
7742                         kvm_inject_page_fault(vcpu, &e);
7743                         return 1;
7744                 }
7745         }
7746
7747
7748         field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
7749         if (vmcs_field_readonly(field)) {
7750                 nested_vmx_failValid(vcpu,
7751                         VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT);
7752                 return kvm_skip_emulated_instruction(vcpu);
7753         }
7754
7755         if (vmcs12_write_any(vcpu, field, field_value) < 0) {
7756                 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
7757                 return kvm_skip_emulated_instruction(vcpu);
7758         }
7759
7760         nested_vmx_succeed(vcpu);
7761         return kvm_skip_emulated_instruction(vcpu);
7762 }
7763
7764 static void set_current_vmptr(struct vcpu_vmx *vmx, gpa_t vmptr)
7765 {
7766         vmx->nested.current_vmptr = vmptr;
7767         if (enable_shadow_vmcs) {
7768                 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
7769                               SECONDARY_EXEC_SHADOW_VMCS);
7770                 vmcs_write64(VMCS_LINK_POINTER,
7771                              __pa(vmx->vmcs01.shadow_vmcs));
7772                 vmx->nested.sync_shadow_vmcs = true;
7773         }
7774 }
7775
7776 /* Emulate the VMPTRLD instruction */
7777 static int handle_vmptrld(struct kvm_vcpu *vcpu)
7778 {
7779         struct vcpu_vmx *vmx = to_vmx(vcpu);
7780         gpa_t vmptr;
7781
7782         if (!nested_vmx_check_permission(vcpu))
7783                 return 1;
7784
7785         if (nested_vmx_get_vmptr(vcpu, &vmptr))
7786                 return 1;
7787
7788         if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {
7789                 nested_vmx_failValid(vcpu, VMXERR_VMPTRLD_INVALID_ADDRESS);
7790                 return kvm_skip_emulated_instruction(vcpu);
7791         }
7792
7793         if (vmptr == vmx->nested.vmxon_ptr) {
7794                 nested_vmx_failValid(vcpu, VMXERR_VMPTRLD_VMXON_POINTER);
7795                 return kvm_skip_emulated_instruction(vcpu);
7796         }
7797
7798         if (vmx->nested.current_vmptr != vmptr) {
7799                 struct vmcs12 *new_vmcs12;
7800                 struct page *page;
7801                 page = kvm_vcpu_gpa_to_page(vcpu, vmptr);
7802                 if (is_error_page(page)) {
7803                         nested_vmx_failInvalid(vcpu);
7804                         return kvm_skip_emulated_instruction(vcpu);
7805                 }
7806                 new_vmcs12 = kmap(page);
7807                 if (new_vmcs12->revision_id != VMCS12_REVISION) {
7808                         kunmap(page);
7809                         kvm_release_page_clean(page);
7810                         nested_vmx_failValid(vcpu,
7811                                 VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
7812                         return kvm_skip_emulated_instruction(vcpu);
7813                 }
7814
7815                 nested_release_vmcs12(vmx);
7816                 /*
7817                  * Load VMCS12 from guest memory since it is not already
7818                  * cached.
7819                  */
7820                 memcpy(vmx->nested.cached_vmcs12, new_vmcs12, VMCS12_SIZE);
7821                 kunmap(page);
7822                 kvm_release_page_clean(page);
7823
7824                 set_current_vmptr(vmx, vmptr);
7825         }
7826
7827         nested_vmx_succeed(vcpu);
7828         return kvm_skip_emulated_instruction(vcpu);
7829 }
7830
7831 /* Emulate the VMPTRST instruction */
7832 static int handle_vmptrst(struct kvm_vcpu *vcpu)
7833 {
7834         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7835         u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7836         gva_t vmcs_gva;
7837         struct x86_exception e;
7838
7839         if (!nested_vmx_check_permission(vcpu))
7840                 return 1;
7841
7842         if (get_vmx_mem_address(vcpu, exit_qualification,
7843                         vmx_instruction_info, true, &vmcs_gva))
7844                 return 1;
7845         /* ok to use *_system, as hardware has verified cpl=0 */
7846         if (kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, vmcs_gva,
7847                                  (void *)&to_vmx(vcpu)->nested.current_vmptr,
7848                                  sizeof(u64), &e)) {
7849                 kvm_inject_page_fault(vcpu, &e);
7850                 return 1;
7851         }
7852         nested_vmx_succeed(vcpu);
7853         return kvm_skip_emulated_instruction(vcpu);
7854 }
7855
7856 /* Emulate the INVEPT instruction */
7857 static int handle_invept(struct kvm_vcpu *vcpu)
7858 {
7859         struct vcpu_vmx *vmx = to_vmx(vcpu);
7860         u32 vmx_instruction_info, types;
7861         unsigned long type;
7862         gva_t gva;
7863         struct x86_exception e;
7864         struct {
7865                 u64 eptp, gpa;
7866         } operand;
7867
7868         if (!(vmx->nested.nested_vmx_secondary_ctls_high &
7869               SECONDARY_EXEC_ENABLE_EPT) ||
7870             !(vmx->nested.nested_vmx_ept_caps & VMX_EPT_INVEPT_BIT)) {
7871                 kvm_queue_exception(vcpu, UD_VECTOR);
7872                 return 1;
7873         }
7874
7875         if (!nested_vmx_check_permission(vcpu))
7876                 return 1;
7877
7878         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7879         type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
7880
7881         types = (vmx->nested.nested_vmx_ept_caps >> VMX_EPT_EXTENT_SHIFT) & 6;
7882
7883         if (type >= 32 || !(types & (1 << type))) {
7884                 nested_vmx_failValid(vcpu,
7885                                 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
7886                 return kvm_skip_emulated_instruction(vcpu);
7887         }
7888
7889         /* According to the Intel VMX instruction reference, the memory
7890          * operand is read even if it isn't needed (e.g., for type==global)
7891          */
7892         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
7893                         vmx_instruction_info, false, &gva))
7894                 return 1;
7895         if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &operand,
7896                                 sizeof(operand), &e)) {
7897                 kvm_inject_page_fault(vcpu, &e);
7898                 return 1;
7899         }
7900
7901         switch (type) {
7902         case VMX_EPT_EXTENT_GLOBAL:
7903         /*
7904          * TODO: track mappings and invalidate
7905          * single context requests appropriately
7906          */
7907         case VMX_EPT_EXTENT_CONTEXT:
7908                 kvm_mmu_sync_roots(vcpu);
7909                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
7910                 nested_vmx_succeed(vcpu);
7911                 break;
7912         default:
7913                 BUG_ON(1);
7914                 break;
7915         }
7916
7917         return kvm_skip_emulated_instruction(vcpu);
7918 }
7919
7920 static int handle_invvpid(struct kvm_vcpu *vcpu)
7921 {
7922         struct vcpu_vmx *vmx = to_vmx(vcpu);
7923         u32 vmx_instruction_info;
7924         unsigned long type, types;
7925         gva_t gva;
7926         struct x86_exception e;
7927         struct {
7928                 u64 vpid;
7929                 u64 gla;
7930         } operand;
7931
7932         if (!(vmx->nested.nested_vmx_secondary_ctls_high &
7933               SECONDARY_EXEC_ENABLE_VPID) ||
7934                         !(vmx->nested.nested_vmx_vpid_caps & VMX_VPID_INVVPID_BIT)) {
7935                 kvm_queue_exception(vcpu, UD_VECTOR);
7936                 return 1;
7937         }
7938
7939         if (!nested_vmx_check_permission(vcpu))
7940                 return 1;
7941
7942         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7943         type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
7944
7945         types = (vmx->nested.nested_vmx_vpid_caps &
7946                         VMX_VPID_EXTENT_SUPPORTED_MASK) >> 8;
7947
7948         if (type >= 32 || !(types & (1 << type))) {
7949                 nested_vmx_failValid(vcpu,
7950                         VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
7951                 return kvm_skip_emulated_instruction(vcpu);
7952         }
7953
7954         /* according to the intel vmx instruction reference, the memory
7955          * operand is read even if it isn't needed (e.g., for type==global)
7956          */
7957         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
7958                         vmx_instruction_info, false, &gva))
7959                 return 1;
7960         if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &operand,
7961                                 sizeof(operand), &e)) {
7962                 kvm_inject_page_fault(vcpu, &e);
7963                 return 1;
7964         }
7965         if (operand.vpid >> 16) {
7966                 nested_vmx_failValid(vcpu,
7967                         VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
7968                 return kvm_skip_emulated_instruction(vcpu);
7969         }
7970
7971         switch (type) {
7972         case VMX_VPID_EXTENT_INDIVIDUAL_ADDR:
7973                 if (is_noncanonical_address(operand.gla, vcpu)) {
7974                         nested_vmx_failValid(vcpu,
7975                                 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
7976                         return kvm_skip_emulated_instruction(vcpu);
7977                 }
7978                 /* fall through */
7979         case VMX_VPID_EXTENT_SINGLE_CONTEXT:
7980         case VMX_VPID_EXTENT_SINGLE_NON_GLOBAL:
7981                 if (!operand.vpid) {
7982                         nested_vmx_failValid(vcpu,
7983                                 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
7984                         return kvm_skip_emulated_instruction(vcpu);
7985                 }
7986                 break;
7987         case VMX_VPID_EXTENT_ALL_CONTEXT:
7988                 break;
7989         default:
7990                 WARN_ON_ONCE(1);
7991                 return kvm_skip_emulated_instruction(vcpu);
7992         }
7993
7994         __vmx_flush_tlb(vcpu, vmx->nested.vpid02);
7995         nested_vmx_succeed(vcpu);
7996
7997         return kvm_skip_emulated_instruction(vcpu);
7998 }
7999
8000 static int handle_pml_full(struct kvm_vcpu *vcpu)
8001 {
8002         unsigned long exit_qualification;
8003
8004         trace_kvm_pml_full(vcpu->vcpu_id);
8005
8006         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8007
8008         /*
8009          * PML buffer FULL happened while executing iret from NMI,
8010          * "blocked by NMI" bit has to be set before next VM entry.
8011          */
8012         if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
8013                         cpu_has_virtual_nmis() &&
8014                         (exit_qualification & INTR_INFO_UNBLOCK_NMI))
8015                 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
8016                                 GUEST_INTR_STATE_NMI);
8017
8018         /*
8019          * PML buffer already flushed at beginning of VMEXIT. Nothing to do
8020          * here.., and there's no userspace involvement needed for PML.
8021          */
8022         return 1;
8023 }
8024
8025 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
8026 {
8027         kvm_lapic_expired_hv_timer(vcpu);
8028         return 1;
8029 }
8030
8031 static bool valid_ept_address(struct kvm_vcpu *vcpu, u64 address)
8032 {
8033         struct vcpu_vmx *vmx = to_vmx(vcpu);
8034         int maxphyaddr = cpuid_maxphyaddr(vcpu);
8035
8036         /* Check for memory type validity */
8037         switch (address & VMX_EPTP_MT_MASK) {
8038         case VMX_EPTP_MT_UC:
8039                 if (!(vmx->nested.nested_vmx_ept_caps & VMX_EPTP_UC_BIT))
8040                         return false;
8041                 break;
8042         case VMX_EPTP_MT_WB:
8043                 if (!(vmx->nested.nested_vmx_ept_caps & VMX_EPTP_WB_BIT))
8044                         return false;
8045                 break;
8046         default:
8047                 return false;
8048         }
8049
8050         /* only 4 levels page-walk length are valid */
8051         if ((address & VMX_EPTP_PWL_MASK) != VMX_EPTP_PWL_4)
8052                 return false;
8053
8054         /* Reserved bits should not be set */
8055         if (address >> maxphyaddr || ((address >> 7) & 0x1f))
8056                 return false;
8057
8058         /* AD, if set, should be supported */
8059         if (address & VMX_EPTP_AD_ENABLE_BIT) {
8060                 if (!(vmx->nested.nested_vmx_ept_caps & VMX_EPT_AD_BIT))
8061                         return false;
8062         }
8063
8064         return true;
8065 }
8066
8067 static int nested_vmx_eptp_switching(struct kvm_vcpu *vcpu,
8068                                      struct vmcs12 *vmcs12)
8069 {
8070         u32 index = vcpu->arch.regs[VCPU_REGS_RCX];
8071         u64 address;
8072         bool accessed_dirty;
8073         struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
8074
8075         if (!nested_cpu_has_eptp_switching(vmcs12) ||
8076             !nested_cpu_has_ept(vmcs12))
8077                 return 1;
8078
8079         if (index >= VMFUNC_EPTP_ENTRIES)
8080                 return 1;
8081
8082
8083         if (kvm_vcpu_read_guest_page(vcpu, vmcs12->eptp_list_address >> PAGE_SHIFT,
8084                                      &address, index * 8, 8))
8085                 return 1;
8086
8087         accessed_dirty = !!(address & VMX_EPTP_AD_ENABLE_BIT);
8088
8089         /*
8090          * If the (L2) guest does a vmfunc to the currently
8091          * active ept pointer, we don't have to do anything else
8092          */
8093         if (vmcs12->ept_pointer != address) {
8094                 if (!valid_ept_address(vcpu, address))
8095                         return 1;
8096
8097                 kvm_mmu_unload(vcpu);
8098                 mmu->ept_ad = accessed_dirty;
8099                 mmu->base_role.ad_disabled = !accessed_dirty;
8100                 vmcs12->ept_pointer = address;
8101                 /*
8102                  * TODO: Check what's the correct approach in case
8103                  * mmu reload fails. Currently, we just let the next
8104                  * reload potentially fail
8105                  */
8106                 kvm_mmu_reload(vcpu);
8107         }
8108
8109         return 0;
8110 }
8111
8112 static int handle_vmfunc(struct kvm_vcpu *vcpu)
8113 {
8114         struct vcpu_vmx *vmx = to_vmx(vcpu);
8115         struct vmcs12 *vmcs12;
8116         u32 function = vcpu->arch.regs[VCPU_REGS_RAX];
8117
8118         /*
8119          * VMFUNC is only supported for nested guests, but we always enable the
8120          * secondary control for simplicity; for non-nested mode, fake that we
8121          * didn't by injecting #UD.
8122          */
8123         if (!is_guest_mode(vcpu)) {
8124                 kvm_queue_exception(vcpu, UD_VECTOR);
8125                 return 1;
8126         }
8127
8128         vmcs12 = get_vmcs12(vcpu);
8129         if ((vmcs12->vm_function_control & (1 << function)) == 0)
8130                 goto fail;
8131
8132         switch (function) {
8133         case 0:
8134                 if (nested_vmx_eptp_switching(vcpu, vmcs12))
8135                         goto fail;
8136                 break;
8137         default:
8138                 goto fail;
8139         }
8140         return kvm_skip_emulated_instruction(vcpu);
8141
8142 fail:
8143         nested_vmx_vmexit(vcpu, vmx->exit_reason,
8144                           vmcs_read32(VM_EXIT_INTR_INFO),
8145                           vmcs_readl(EXIT_QUALIFICATION));
8146         return 1;
8147 }
8148
8149 /*
8150  * The exit handlers return 1 if the exit was handled fully and guest execution
8151  * may resume.  Otherwise they set the kvm_run parameter to indicate what needs
8152  * to be done to userspace and return 0.
8153  */
8154 static int (*const kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
8155         [EXIT_REASON_EXCEPTION_NMI]           = handle_exception,
8156         [EXIT_REASON_EXTERNAL_INTERRUPT]      = handle_external_interrupt,
8157         [EXIT_REASON_TRIPLE_FAULT]            = handle_triple_fault,
8158         [EXIT_REASON_NMI_WINDOW]              = handle_nmi_window,
8159         [EXIT_REASON_IO_INSTRUCTION]          = handle_io,
8160         [EXIT_REASON_CR_ACCESS]               = handle_cr,
8161         [EXIT_REASON_DR_ACCESS]               = handle_dr,
8162         [EXIT_REASON_CPUID]                   = handle_cpuid,
8163         [EXIT_REASON_MSR_READ]                = handle_rdmsr,
8164         [EXIT_REASON_MSR_WRITE]               = handle_wrmsr,
8165         [EXIT_REASON_PENDING_INTERRUPT]       = handle_interrupt_window,
8166         [EXIT_REASON_HLT]                     = handle_halt,
8167         [EXIT_REASON_INVD]                    = handle_invd,
8168         [EXIT_REASON_INVLPG]                  = handle_invlpg,
8169         [EXIT_REASON_RDPMC]                   = handle_rdpmc,
8170         [EXIT_REASON_VMCALL]                  = handle_vmcall,
8171         [EXIT_REASON_VMCLEAR]                 = handle_vmclear,
8172         [EXIT_REASON_VMLAUNCH]                = handle_vmlaunch,
8173         [EXIT_REASON_VMPTRLD]                 = handle_vmptrld,
8174         [EXIT_REASON_VMPTRST]                 = handle_vmptrst,
8175         [EXIT_REASON_VMREAD]                  = handle_vmread,
8176         [EXIT_REASON_VMRESUME]                = handle_vmresume,
8177         [EXIT_REASON_VMWRITE]                 = handle_vmwrite,
8178         [EXIT_REASON_VMOFF]                   = handle_vmoff,
8179         [EXIT_REASON_VMON]                    = handle_vmon,
8180         [EXIT_REASON_TPR_BELOW_THRESHOLD]     = handle_tpr_below_threshold,
8181         [EXIT_REASON_APIC_ACCESS]             = handle_apic_access,
8182         [EXIT_REASON_APIC_WRITE]              = handle_apic_write,
8183         [EXIT_REASON_EOI_INDUCED]             = handle_apic_eoi_induced,
8184         [EXIT_REASON_WBINVD]                  = handle_wbinvd,
8185         [EXIT_REASON_XSETBV]                  = handle_xsetbv,
8186         [EXIT_REASON_TASK_SWITCH]             = handle_task_switch,
8187         [EXIT_REASON_MCE_DURING_VMENTRY]      = handle_machine_check,
8188         [EXIT_REASON_EPT_VIOLATION]           = handle_ept_violation,
8189         [EXIT_REASON_EPT_MISCONFIG]           = handle_ept_misconfig,
8190         [EXIT_REASON_PAUSE_INSTRUCTION]       = handle_pause,
8191         [EXIT_REASON_MWAIT_INSTRUCTION]       = handle_mwait,
8192         [EXIT_REASON_MONITOR_TRAP_FLAG]       = handle_monitor_trap,
8193         [EXIT_REASON_MONITOR_INSTRUCTION]     = handle_monitor,
8194         [EXIT_REASON_INVEPT]                  = handle_invept,
8195         [EXIT_REASON_INVVPID]                 = handle_invvpid,
8196         [EXIT_REASON_RDRAND]                  = handle_invalid_op,
8197         [EXIT_REASON_RDSEED]                  = handle_invalid_op,
8198         [EXIT_REASON_XSAVES]                  = handle_xsaves,
8199         [EXIT_REASON_XRSTORS]                 = handle_xrstors,
8200         [EXIT_REASON_PML_FULL]                = handle_pml_full,
8201         [EXIT_REASON_VMFUNC]                  = handle_vmfunc,
8202         [EXIT_REASON_PREEMPTION_TIMER]        = handle_preemption_timer,
8203 };
8204
8205 static const int kvm_vmx_max_exit_handlers =
8206         ARRAY_SIZE(kvm_vmx_exit_handlers);
8207
8208 static bool nested_vmx_exit_handled_io(struct kvm_vcpu *vcpu,
8209                                        struct vmcs12 *vmcs12)
8210 {
8211         unsigned long exit_qualification;
8212         gpa_t bitmap, last_bitmap;
8213         unsigned int port;
8214         int size;
8215         u8 b;
8216
8217         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
8218                 return nested_cpu_has(vmcs12, CPU_BASED_UNCOND_IO_EXITING);
8219
8220         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8221
8222         port = exit_qualification >> 16;
8223         size = (exit_qualification & 7) + 1;
8224
8225         last_bitmap = (gpa_t)-1;
8226         b = -1;
8227
8228         while (size > 0) {
8229                 if (port < 0x8000)
8230                         bitmap = vmcs12->io_bitmap_a;
8231                 else if (port < 0x10000)
8232                         bitmap = vmcs12->io_bitmap_b;
8233                 else
8234                         return true;
8235                 bitmap += (port & 0x7fff) / 8;
8236
8237                 if (last_bitmap != bitmap)
8238                         if (kvm_vcpu_read_guest(vcpu, bitmap, &b, 1))
8239                                 return true;
8240                 if (b & (1 << (port & 7)))
8241                         return true;
8242
8243                 port++;
8244                 size--;
8245                 last_bitmap = bitmap;
8246         }
8247
8248         return false;
8249 }
8250
8251 /*
8252  * Return 1 if we should exit from L2 to L1 to handle an MSR access access,
8253  * rather than handle it ourselves in L0. I.e., check whether L1 expressed
8254  * disinterest in the current event (read or write a specific MSR) by using an
8255  * MSR bitmap. This may be the case even when L0 doesn't use MSR bitmaps.
8256  */
8257 static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu,
8258         struct vmcs12 *vmcs12, u32 exit_reason)
8259 {
8260         u32 msr_index = vcpu->arch.regs[VCPU_REGS_RCX];
8261         gpa_t bitmap;
8262
8263         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
8264                 return true;
8265
8266         /*
8267          * The MSR_BITMAP page is divided into four 1024-byte bitmaps,
8268          * for the four combinations of read/write and low/high MSR numbers.
8269          * First we need to figure out which of the four to use:
8270          */
8271         bitmap = vmcs12->msr_bitmap;
8272         if (exit_reason == EXIT_REASON_MSR_WRITE)
8273                 bitmap += 2048;
8274         if (msr_index >= 0xc0000000) {
8275                 msr_index -= 0xc0000000;
8276                 bitmap += 1024;
8277         }
8278
8279         /* Then read the msr_index'th bit from this bitmap: */
8280         if (msr_index < 1024*8) {
8281                 unsigned char b;
8282                 if (kvm_vcpu_read_guest(vcpu, bitmap + msr_index/8, &b, 1))
8283                         return true;
8284                 return 1 & (b >> (msr_index & 7));
8285         } else
8286                 return true; /* let L1 handle the wrong parameter */
8287 }
8288
8289 /*
8290  * Return 1 if we should exit from L2 to L1 to handle a CR access exit,
8291  * rather than handle it ourselves in L0. I.e., check if L1 wanted to
8292  * intercept (via guest_host_mask etc.) the current event.
8293  */
8294 static bool nested_vmx_exit_handled_cr(struct kvm_vcpu *vcpu,
8295         struct vmcs12 *vmcs12)
8296 {
8297         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8298         int cr = exit_qualification & 15;
8299         int reg;
8300         unsigned long val;
8301
8302         switch ((exit_qualification >> 4) & 3) {
8303         case 0: /* mov to cr */
8304                 reg = (exit_qualification >> 8) & 15;
8305                 val = kvm_register_readl(vcpu, reg);
8306                 switch (cr) {
8307                 case 0:
8308                         if (vmcs12->cr0_guest_host_mask &
8309                             (val ^ vmcs12->cr0_read_shadow))
8310                                 return true;
8311                         break;
8312                 case 3:
8313                         if ((vmcs12->cr3_target_count >= 1 &&
8314                                         vmcs12->cr3_target_value0 == val) ||
8315                                 (vmcs12->cr3_target_count >= 2 &&
8316                                         vmcs12->cr3_target_value1 == val) ||
8317                                 (vmcs12->cr3_target_count >= 3 &&
8318                                         vmcs12->cr3_target_value2 == val) ||
8319                                 (vmcs12->cr3_target_count >= 4 &&
8320                                         vmcs12->cr3_target_value3 == val))
8321                                 return false;
8322                         if (nested_cpu_has(vmcs12, CPU_BASED_CR3_LOAD_EXITING))
8323                                 return true;
8324                         break;
8325                 case 4:
8326                         if (vmcs12->cr4_guest_host_mask &
8327                             (vmcs12->cr4_read_shadow ^ val))
8328                                 return true;
8329                         break;
8330                 case 8:
8331                         if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING))
8332                                 return true;
8333                         break;
8334                 }
8335                 break;
8336         case 2: /* clts */
8337                 if ((vmcs12->cr0_guest_host_mask & X86_CR0_TS) &&
8338                     (vmcs12->cr0_read_shadow & X86_CR0_TS))
8339                         return true;
8340                 break;
8341         case 1: /* mov from cr */
8342                 switch (cr) {
8343                 case 3:
8344                         if (vmcs12->cpu_based_vm_exec_control &
8345                             CPU_BASED_CR3_STORE_EXITING)
8346                                 return true;
8347                         break;
8348                 case 8:
8349                         if (vmcs12->cpu_based_vm_exec_control &
8350                             CPU_BASED_CR8_STORE_EXITING)
8351                                 return true;
8352                         break;
8353                 }
8354                 break;
8355         case 3: /* lmsw */
8356                 /*
8357                  * lmsw can change bits 1..3 of cr0, and only set bit 0 of
8358                  * cr0. Other attempted changes are ignored, with no exit.
8359                  */
8360                 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
8361                 if (vmcs12->cr0_guest_host_mask & 0xe &
8362                     (val ^ vmcs12->cr0_read_shadow))
8363                         return true;
8364                 if ((vmcs12->cr0_guest_host_mask & 0x1) &&
8365                     !(vmcs12->cr0_read_shadow & 0x1) &&
8366                     (val & 0x1))
8367                         return true;
8368                 break;
8369         }
8370         return false;
8371 }
8372
8373 /*
8374  * Return 1 if we should exit from L2 to L1 to handle an exit, or 0 if we
8375  * should handle it ourselves in L0 (and then continue L2). Only call this
8376  * when in is_guest_mode (L2).
8377  */
8378 static bool nested_vmx_exit_reflected(struct kvm_vcpu *vcpu, u32 exit_reason)
8379 {
8380         u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
8381         struct vcpu_vmx *vmx = to_vmx(vcpu);
8382         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
8383
8384         if (vmx->nested.nested_run_pending)
8385                 return false;
8386
8387         if (unlikely(vmx->fail)) {
8388                 pr_info_ratelimited("%s failed vm entry %x\n", __func__,
8389                                     vmcs_read32(VM_INSTRUCTION_ERROR));
8390                 return true;
8391         }
8392
8393         /*
8394          * The host physical addresses of some pages of guest memory
8395          * are loaded into VMCS02 (e.g. L1's Virtual APIC Page). The CPU
8396          * may write to these pages via their host physical address while
8397          * L2 is running, bypassing any address-translation-based dirty
8398          * tracking (e.g. EPT write protection).
8399          *
8400          * Mark them dirty on every exit from L2 to prevent them from
8401          * getting out of sync with dirty tracking.
8402          */
8403         nested_mark_vmcs12_pages_dirty(vcpu);
8404
8405         trace_kvm_nested_vmexit(kvm_rip_read(vcpu), exit_reason,
8406                                 vmcs_readl(EXIT_QUALIFICATION),
8407                                 vmx->idt_vectoring_info,
8408                                 intr_info,
8409                                 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
8410                                 KVM_ISA_VMX);
8411
8412         switch (exit_reason) {
8413         case EXIT_REASON_EXCEPTION_NMI:
8414                 if (is_nmi(intr_info))
8415                         return false;
8416                 else if (is_page_fault(intr_info))
8417                         return !vmx->vcpu.arch.apf.host_apf_reason && enable_ept;
8418                 else if (is_no_device(intr_info) &&
8419                          !(vmcs12->guest_cr0 & X86_CR0_TS))
8420                         return false;
8421                 else if (is_debug(intr_info) &&
8422                          vcpu->guest_debug &
8423                          (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
8424                         return false;
8425                 else if (is_breakpoint(intr_info) &&
8426                          vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
8427                         return false;
8428                 return vmcs12->exception_bitmap &
8429                                 (1u << (intr_info & INTR_INFO_VECTOR_MASK));
8430         case EXIT_REASON_EXTERNAL_INTERRUPT:
8431                 return false;
8432         case EXIT_REASON_TRIPLE_FAULT:
8433                 return true;
8434         case EXIT_REASON_PENDING_INTERRUPT:
8435                 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_INTR_PENDING);
8436         case EXIT_REASON_NMI_WINDOW:
8437                 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING);
8438         case EXIT_REASON_TASK_SWITCH:
8439                 return true;
8440         case EXIT_REASON_CPUID:
8441                 return true;
8442         case EXIT_REASON_HLT:
8443                 return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
8444         case EXIT_REASON_INVD:
8445                 return true;
8446         case EXIT_REASON_INVLPG:
8447                 return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
8448         case EXIT_REASON_RDPMC:
8449                 return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
8450         case EXIT_REASON_RDRAND:
8451                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDRAND);
8452         case EXIT_REASON_RDSEED:
8453                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDSEED);
8454         case EXIT_REASON_RDTSC: case EXIT_REASON_RDTSCP:
8455                 return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
8456         case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
8457         case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
8458         case EXIT_REASON_VMPTRST: case EXIT_REASON_VMREAD:
8459         case EXIT_REASON_VMRESUME: case EXIT_REASON_VMWRITE:
8460         case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
8461         case EXIT_REASON_INVEPT: case EXIT_REASON_INVVPID:
8462                 /*
8463                  * VMX instructions trap unconditionally. This allows L1 to
8464                  * emulate them for its L2 guest, i.e., allows 3-level nesting!
8465                  */
8466                 return true;
8467         case EXIT_REASON_CR_ACCESS:
8468                 return nested_vmx_exit_handled_cr(vcpu, vmcs12);
8469         case EXIT_REASON_DR_ACCESS:
8470                 return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
8471         case EXIT_REASON_IO_INSTRUCTION:
8472                 return nested_vmx_exit_handled_io(vcpu, vmcs12);
8473         case EXIT_REASON_GDTR_IDTR: case EXIT_REASON_LDTR_TR:
8474                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC);
8475         case EXIT_REASON_MSR_READ:
8476         case EXIT_REASON_MSR_WRITE:
8477                 return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
8478         case EXIT_REASON_INVALID_STATE:
8479                 return true;
8480         case EXIT_REASON_MWAIT_INSTRUCTION:
8481                 return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
8482         case EXIT_REASON_MONITOR_TRAP_FLAG:
8483                 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_TRAP_FLAG);
8484         case EXIT_REASON_MONITOR_INSTRUCTION:
8485                 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
8486         case EXIT_REASON_PAUSE_INSTRUCTION:
8487                 return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
8488                         nested_cpu_has2(vmcs12,
8489                                 SECONDARY_EXEC_PAUSE_LOOP_EXITING);
8490         case EXIT_REASON_MCE_DURING_VMENTRY:
8491                 return false;
8492         case EXIT_REASON_TPR_BELOW_THRESHOLD:
8493                 return nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW);
8494         case EXIT_REASON_APIC_ACCESS:
8495                 return nested_cpu_has2(vmcs12,
8496                         SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
8497         case EXIT_REASON_APIC_WRITE:
8498         case EXIT_REASON_EOI_INDUCED:
8499                 /* apic_write and eoi_induced should exit unconditionally. */
8500                 return true;
8501         case EXIT_REASON_EPT_VIOLATION:
8502                 /*
8503                  * L0 always deals with the EPT violation. If nested EPT is
8504                  * used, and the nested mmu code discovers that the address is
8505                  * missing in the guest EPT table (EPT12), the EPT violation
8506                  * will be injected with nested_ept_inject_page_fault()
8507                  */
8508                 return false;
8509         case EXIT_REASON_EPT_MISCONFIG:
8510                 /*
8511                  * L2 never uses directly L1's EPT, but rather L0's own EPT
8512                  * table (shadow on EPT) or a merged EPT table that L0 built
8513                  * (EPT on EPT). So any problems with the structure of the
8514                  * table is L0's fault.
8515                  */
8516                 return false;
8517         case EXIT_REASON_INVPCID:
8518                 return
8519                         nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_INVPCID) &&
8520                         nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
8521         case EXIT_REASON_WBINVD:
8522                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
8523         case EXIT_REASON_XSETBV:
8524                 return true;
8525         case EXIT_REASON_XSAVES: case EXIT_REASON_XRSTORS:
8526                 /*
8527                  * This should never happen, since it is not possible to
8528                  * set XSS to a non-zero value---neither in L1 nor in L2.
8529                  * If if it were, XSS would have to be checked against
8530                  * the XSS exit bitmap in vmcs12.
8531                  */
8532                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
8533         case EXIT_REASON_PREEMPTION_TIMER:
8534                 return false;
8535         case EXIT_REASON_PML_FULL:
8536                 /* We emulate PML support to L1. */
8537                 return false;
8538         case EXIT_REASON_VMFUNC:
8539                 /* VM functions are emulated through L2->L0 vmexits. */
8540                 return false;
8541         default:
8542                 return true;
8543         }
8544 }
8545
8546 static int nested_vmx_reflect_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason)
8547 {
8548         u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
8549
8550         /*
8551          * At this point, the exit interruption info in exit_intr_info
8552          * is only valid for EXCEPTION_NMI exits.  For EXTERNAL_INTERRUPT
8553          * we need to query the in-kernel LAPIC.
8554          */
8555         WARN_ON(exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT);
8556         if ((exit_intr_info &
8557              (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) ==
8558             (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) {
8559                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
8560                 vmcs12->vm_exit_intr_error_code =
8561                         vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
8562         }
8563
8564         nested_vmx_vmexit(vcpu, exit_reason, exit_intr_info,
8565                           vmcs_readl(EXIT_QUALIFICATION));
8566         return 1;
8567 }
8568
8569 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
8570 {
8571         *info1 = vmcs_readl(EXIT_QUALIFICATION);
8572         *info2 = vmcs_read32(VM_EXIT_INTR_INFO);
8573 }
8574
8575 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
8576 {
8577         if (vmx->pml_pg) {
8578                 __free_page(vmx->pml_pg);
8579                 vmx->pml_pg = NULL;
8580         }
8581 }
8582
8583 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
8584 {
8585         struct vcpu_vmx *vmx = to_vmx(vcpu);
8586         u64 *pml_buf;
8587         u16 pml_idx;
8588
8589         pml_idx = vmcs_read16(GUEST_PML_INDEX);
8590
8591         /* Do nothing if PML buffer is empty */
8592         if (pml_idx == (PML_ENTITY_NUM - 1))
8593                 return;
8594
8595         /* PML index always points to next available PML buffer entity */
8596         if (pml_idx >= PML_ENTITY_NUM)
8597                 pml_idx = 0;
8598         else
8599                 pml_idx++;
8600
8601         pml_buf = page_address(vmx->pml_pg);
8602         for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
8603                 u64 gpa;
8604
8605                 gpa = pml_buf[pml_idx];
8606                 WARN_ON(gpa & (PAGE_SIZE - 1));
8607                 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
8608         }
8609
8610         /* reset PML index */
8611         vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
8612 }
8613
8614 /*
8615  * Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
8616  * Called before reporting dirty_bitmap to userspace.
8617  */
8618 static void kvm_flush_pml_buffers(struct kvm *kvm)
8619 {
8620         int i;
8621         struct kvm_vcpu *vcpu;
8622         /*
8623          * We only need to kick vcpu out of guest mode here, as PML buffer
8624          * is flushed at beginning of all VMEXITs, and it's obvious that only
8625          * vcpus running in guest are possible to have unflushed GPAs in PML
8626          * buffer.
8627          */
8628         kvm_for_each_vcpu(i, vcpu, kvm)
8629                 kvm_vcpu_kick(vcpu);
8630 }
8631
8632 static void vmx_dump_sel(char *name, uint32_t sel)
8633 {
8634         pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
8635                name, vmcs_read16(sel),
8636                vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
8637                vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
8638                vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
8639 }
8640
8641 static void vmx_dump_dtsel(char *name, uint32_t limit)
8642 {
8643         pr_err("%s                           limit=0x%08x, base=0x%016lx\n",
8644                name, vmcs_read32(limit),
8645                vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
8646 }
8647
8648 static void dump_vmcs(void)
8649 {
8650         u32 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
8651         u32 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
8652         u32 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
8653         u32 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
8654         u32 secondary_exec_control = 0;
8655         unsigned long cr4 = vmcs_readl(GUEST_CR4);
8656         u64 efer = vmcs_read64(GUEST_IA32_EFER);
8657         int i, n;
8658
8659         if (cpu_has_secondary_exec_ctrls())
8660                 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
8661
8662         pr_err("*** Guest State ***\n");
8663         pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
8664                vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
8665                vmcs_readl(CR0_GUEST_HOST_MASK));
8666         pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
8667                cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
8668         pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
8669         if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
8670             (cr4 & X86_CR4_PAE) && !(efer & EFER_LMA))
8671         {
8672                 pr_err("PDPTR0 = 0x%016llx  PDPTR1 = 0x%016llx\n",
8673                        vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
8674                 pr_err("PDPTR2 = 0x%016llx  PDPTR3 = 0x%016llx\n",
8675                        vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
8676         }
8677         pr_err("RSP = 0x%016lx  RIP = 0x%016lx\n",
8678                vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
8679         pr_err("RFLAGS=0x%08lx         DR7 = 0x%016lx\n",
8680                vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
8681         pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
8682                vmcs_readl(GUEST_SYSENTER_ESP),
8683                vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
8684         vmx_dump_sel("CS:  ", GUEST_CS_SELECTOR);
8685         vmx_dump_sel("DS:  ", GUEST_DS_SELECTOR);
8686         vmx_dump_sel("SS:  ", GUEST_SS_SELECTOR);
8687         vmx_dump_sel("ES:  ", GUEST_ES_SELECTOR);
8688         vmx_dump_sel("FS:  ", GUEST_FS_SELECTOR);
8689         vmx_dump_sel("GS:  ", GUEST_GS_SELECTOR);
8690         vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
8691         vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
8692         vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
8693         vmx_dump_sel("TR:  ", GUEST_TR_SELECTOR);
8694         if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
8695             (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
8696                 pr_err("EFER =     0x%016llx  PAT = 0x%016llx\n",
8697                        efer, vmcs_read64(GUEST_IA32_PAT));
8698         pr_err("DebugCtl = 0x%016llx  DebugExceptions = 0x%016lx\n",
8699                vmcs_read64(GUEST_IA32_DEBUGCTL),
8700                vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
8701         if (vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
8702                 pr_err("PerfGlobCtl = 0x%016llx\n",
8703                        vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
8704         if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
8705                 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
8706         pr_err("Interruptibility = %08x  ActivityState = %08x\n",
8707                vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
8708                vmcs_read32(GUEST_ACTIVITY_STATE));
8709         if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
8710                 pr_err("InterruptStatus = %04x\n",
8711                        vmcs_read16(GUEST_INTR_STATUS));
8712
8713         pr_err("*** Host State ***\n");
8714         pr_err("RIP = 0x%016lx  RSP = 0x%016lx\n",
8715                vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
8716         pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
8717                vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
8718                vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
8719                vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
8720                vmcs_read16(HOST_TR_SELECTOR));
8721         pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
8722                vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
8723                vmcs_readl(HOST_TR_BASE));
8724         pr_err("GDTBase=%016lx IDTBase=%016lx\n",
8725                vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
8726         pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
8727                vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
8728                vmcs_readl(HOST_CR4));
8729         pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
8730                vmcs_readl(HOST_IA32_SYSENTER_ESP),
8731                vmcs_read32(HOST_IA32_SYSENTER_CS),
8732                vmcs_readl(HOST_IA32_SYSENTER_EIP));
8733         if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
8734                 pr_err("EFER = 0x%016llx  PAT = 0x%016llx\n",
8735                        vmcs_read64(HOST_IA32_EFER),
8736                        vmcs_read64(HOST_IA32_PAT));
8737         if (vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
8738                 pr_err("PerfGlobCtl = 0x%016llx\n",
8739                        vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
8740
8741         pr_err("*** Control State ***\n");
8742         pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
8743                pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
8744         pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
8745         pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
8746                vmcs_read32(EXCEPTION_BITMAP),
8747                vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
8748                vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
8749         pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
8750                vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
8751                vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
8752                vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
8753         pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
8754                vmcs_read32(VM_EXIT_INTR_INFO),
8755                vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
8756                vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
8757         pr_err("        reason=%08x qualification=%016lx\n",
8758                vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
8759         pr_err("IDTVectoring: info=%08x errcode=%08x\n",
8760                vmcs_read32(IDT_VECTORING_INFO_FIELD),
8761                vmcs_read32(IDT_VECTORING_ERROR_CODE));
8762         pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
8763         if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
8764                 pr_err("TSC Multiplier = 0x%016llx\n",
8765                        vmcs_read64(TSC_MULTIPLIER));
8766         if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW)
8767                 pr_err("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
8768         if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
8769                 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
8770         if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
8771                 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
8772         n = vmcs_read32(CR3_TARGET_COUNT);
8773         for (i = 0; i + 1 < n; i += 4)
8774                 pr_err("CR3 target%u=%016lx target%u=%016lx\n",
8775                        i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2),
8776                        i + 1, vmcs_readl(CR3_TARGET_VALUE0 + i * 2 + 2));
8777         if (i < n)
8778                 pr_err("CR3 target%u=%016lx\n",
8779                        i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2));
8780         if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
8781                 pr_err("PLE Gap=%08x Window=%08x\n",
8782                        vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
8783         if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
8784                 pr_err("Virtual processor ID = 0x%04x\n",
8785                        vmcs_read16(VIRTUAL_PROCESSOR_ID));
8786 }
8787
8788 /*
8789  * The guest has exited.  See if we can fix it or if we need userspace
8790  * assistance.
8791  */
8792 static int vmx_handle_exit(struct kvm_vcpu *vcpu)
8793 {
8794         struct vcpu_vmx *vmx = to_vmx(vcpu);
8795         u32 exit_reason = vmx->exit_reason;
8796         u32 vectoring_info = vmx->idt_vectoring_info;
8797
8798         trace_kvm_exit(exit_reason, vcpu, KVM_ISA_VMX);
8799
8800         /*
8801          * Flush logged GPAs PML buffer, this will make dirty_bitmap more
8802          * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
8803          * querying dirty_bitmap, we only need to kick all vcpus out of guest
8804          * mode as if vcpus is in root mode, the PML buffer must has been
8805          * flushed already.
8806          */
8807         if (enable_pml)
8808                 vmx_flush_pml_buffer(vcpu);
8809
8810         /* If guest state is invalid, start emulating */
8811         if (vmx->emulation_required)
8812                 return handle_invalid_guest_state(vcpu);
8813
8814         if (is_guest_mode(vcpu) && nested_vmx_exit_reflected(vcpu, exit_reason))
8815                 return nested_vmx_reflect_vmexit(vcpu, exit_reason);
8816
8817         if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
8818                 dump_vmcs();
8819                 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
8820                 vcpu->run->fail_entry.hardware_entry_failure_reason
8821                         = exit_reason;
8822                 return 0;
8823         }
8824
8825         if (unlikely(vmx->fail)) {
8826                 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
8827                 vcpu->run->fail_entry.hardware_entry_failure_reason
8828                         = vmcs_read32(VM_INSTRUCTION_ERROR);
8829                 return 0;
8830         }
8831
8832         /*
8833          * Note:
8834          * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
8835          * delivery event since it indicates guest is accessing MMIO.
8836          * The vm-exit can be triggered again after return to guest that
8837          * will cause infinite loop.
8838          */
8839         if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
8840                         (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
8841                         exit_reason != EXIT_REASON_EPT_VIOLATION &&
8842                         exit_reason != EXIT_REASON_PML_FULL &&
8843                         exit_reason != EXIT_REASON_TASK_SWITCH)) {
8844                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
8845                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
8846                 vcpu->run->internal.ndata = 3;
8847                 vcpu->run->internal.data[0] = vectoring_info;
8848                 vcpu->run->internal.data[1] = exit_reason;
8849                 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
8850                 if (exit_reason == EXIT_REASON_EPT_MISCONFIG) {
8851                         vcpu->run->internal.ndata++;
8852                         vcpu->run->internal.data[3] =
8853                                 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
8854                 }
8855                 return 0;
8856         }
8857
8858         if (unlikely(!cpu_has_virtual_nmis() &&
8859                      vmx->loaded_vmcs->soft_vnmi_blocked)) {
8860                 if (vmx_interrupt_allowed(vcpu)) {
8861                         vmx->loaded_vmcs->soft_vnmi_blocked = 0;
8862                 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
8863                            vcpu->arch.nmi_pending) {
8864                         /*
8865                          * This CPU don't support us in finding the end of an
8866                          * NMI-blocked window if the guest runs with IRQs
8867                          * disabled. So we pull the trigger after 1 s of
8868                          * futile waiting, but inform the user about this.
8869                          */
8870                         printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
8871                                "state on VCPU %d after 1 s timeout\n",
8872                                __func__, vcpu->vcpu_id);
8873                         vmx->loaded_vmcs->soft_vnmi_blocked = 0;
8874                 }
8875         }
8876
8877         if (exit_reason < kvm_vmx_max_exit_handlers
8878             && kvm_vmx_exit_handlers[exit_reason])
8879                 return kvm_vmx_exit_handlers[exit_reason](vcpu);
8880         else {
8881                 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
8882                                 exit_reason);
8883                 kvm_queue_exception(vcpu, UD_VECTOR);
8884                 return 1;
8885         }
8886 }
8887
8888 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
8889 {
8890         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
8891
8892         if (is_guest_mode(vcpu) &&
8893                 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
8894                 return;
8895
8896         if (irr == -1 || tpr < irr) {
8897                 vmcs_write32(TPR_THRESHOLD, 0);
8898                 return;
8899         }
8900
8901         vmcs_write32(TPR_THRESHOLD, irr);
8902 }
8903
8904 static void vmx_set_virtual_x2apic_mode(struct kvm_vcpu *vcpu, bool set)
8905 {
8906         u32 sec_exec_control;
8907
8908         /* Postpone execution until vmcs01 is the current VMCS. */
8909         if (is_guest_mode(vcpu)) {
8910                 to_vmx(vcpu)->nested.change_vmcs01_virtual_x2apic_mode = true;
8911                 return;
8912         }
8913
8914         if (!cpu_has_vmx_virtualize_x2apic_mode())
8915                 return;
8916
8917         if (!cpu_need_tpr_shadow(vcpu))
8918                 return;
8919
8920         sec_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
8921
8922         if (set) {
8923                 sec_exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
8924                 sec_exec_control |= SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
8925         } else {
8926                 sec_exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
8927                 sec_exec_control |= SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
8928                 vmx_flush_tlb_ept_only(vcpu);
8929         }
8930         vmcs_write32(SECONDARY_VM_EXEC_CONTROL, sec_exec_control);
8931
8932         vmx_set_msr_bitmap(vcpu);
8933 }
8934
8935 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu, hpa_t hpa)
8936 {
8937         struct vcpu_vmx *vmx = to_vmx(vcpu);
8938
8939         /*
8940          * Currently we do not handle the nested case where L2 has an
8941          * APIC access page of its own; that page is still pinned.
8942          * Hence, we skip the case where the VCPU is in guest mode _and_
8943          * L1 prepared an APIC access page for L2.
8944          *
8945          * For the case where L1 and L2 share the same APIC access page
8946          * (flexpriority=Y but SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES clear
8947          * in the vmcs12), this function will only update either the vmcs01
8948          * or the vmcs02.  If the former, the vmcs02 will be updated by
8949          * prepare_vmcs02.  If the latter, the vmcs01 will be updated in
8950          * the next L2->L1 exit.
8951          */
8952         if (!is_guest_mode(vcpu) ||
8953             !nested_cpu_has2(get_vmcs12(&vmx->vcpu),
8954                              SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
8955                 vmcs_write64(APIC_ACCESS_ADDR, hpa);
8956                 vmx_flush_tlb_ept_only(vcpu);
8957         }
8958 }
8959
8960 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
8961 {
8962         u16 status;
8963         u8 old;
8964
8965         if (max_isr == -1)
8966                 max_isr = 0;
8967
8968         status = vmcs_read16(GUEST_INTR_STATUS);
8969         old = status >> 8;
8970         if (max_isr != old) {
8971                 status &= 0xff;
8972                 status |= max_isr << 8;
8973                 vmcs_write16(GUEST_INTR_STATUS, status);
8974         }
8975 }
8976
8977 static void vmx_set_rvi(int vector)
8978 {
8979         u16 status;
8980         u8 old;
8981
8982         if (vector == -1)
8983                 vector = 0;
8984
8985         status = vmcs_read16(GUEST_INTR_STATUS);
8986         old = (u8)status & 0xff;
8987         if ((u8)vector != old) {
8988                 status &= ~0xff;
8989                 status |= (u8)vector;
8990                 vmcs_write16(GUEST_INTR_STATUS, status);
8991         }
8992 }
8993
8994 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
8995 {
8996         if (!is_guest_mode(vcpu)) {
8997                 vmx_set_rvi(max_irr);
8998                 return;
8999         }
9000
9001         if (max_irr == -1)
9002                 return;
9003
9004         /*
9005          * In guest mode.  If a vmexit is needed, vmx_check_nested_events
9006          * handles it.
9007          */
9008         if (nested_exit_on_intr(vcpu))
9009                 return;
9010
9011         /*
9012          * Else, fall back to pre-APICv interrupt injection since L2
9013          * is run without virtual interrupt delivery.
9014          */
9015         if (!kvm_event_needs_reinjection(vcpu) &&
9016             vmx_interrupt_allowed(vcpu)) {
9017                 kvm_queue_interrupt(vcpu, max_irr, false);
9018                 vmx_inject_irq(vcpu);
9019         }
9020 }
9021
9022 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
9023 {
9024         struct vcpu_vmx *vmx = to_vmx(vcpu);
9025         int max_irr;
9026
9027         WARN_ON(!vcpu->arch.apicv_active);
9028         if (pi_test_on(&vmx->pi_desc)) {
9029                 pi_clear_on(&vmx->pi_desc);
9030                 /*
9031                  * IOMMU can write to PIR.ON, so the barrier matters even on UP.
9032                  * But on x86 this is just a compiler barrier anyway.
9033                  */
9034                 smp_mb__after_atomic();
9035                 max_irr = kvm_apic_update_irr(vcpu, vmx->pi_desc.pir);
9036         } else {
9037                 max_irr = kvm_lapic_find_highest_irr(vcpu);
9038         }
9039         vmx_hwapic_irr_update(vcpu, max_irr);
9040         return max_irr;
9041 }
9042
9043 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
9044 {
9045         if (!kvm_vcpu_apicv_active(vcpu))
9046                 return;
9047
9048         vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
9049         vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
9050         vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
9051         vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
9052 }
9053
9054 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
9055 {
9056         struct vcpu_vmx *vmx = to_vmx(vcpu);
9057
9058         pi_clear_on(&vmx->pi_desc);
9059         memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
9060 }
9061
9062 static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
9063 {
9064         u32 exit_intr_info = 0;
9065         u16 basic_exit_reason = (u16)vmx->exit_reason;
9066
9067         if (!(basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
9068               || basic_exit_reason == EXIT_REASON_EXCEPTION_NMI))
9069                 return;
9070
9071         if (!(vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
9072                 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
9073         vmx->exit_intr_info = exit_intr_info;
9074
9075         /* if exit due to PF check for async PF */
9076         if (is_page_fault(exit_intr_info))
9077                 vmx->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
9078
9079         /* Handle machine checks before interrupts are enabled */
9080         if (basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY ||
9081             is_machine_check(exit_intr_info))
9082                 kvm_machine_check();
9083
9084         /* We need to handle NMIs before interrupts are enabled */
9085         if (is_nmi(exit_intr_info)) {
9086                 kvm_before_handle_nmi(&vmx->vcpu);
9087                 asm("int $2");
9088                 kvm_after_handle_nmi(&vmx->vcpu);
9089         }
9090 }
9091
9092 static void vmx_handle_external_intr(struct kvm_vcpu *vcpu)
9093 {
9094         u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
9095
9096         if ((exit_intr_info & (INTR_INFO_VALID_MASK | INTR_INFO_INTR_TYPE_MASK))
9097                         == (INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR)) {
9098                 unsigned int vector;
9099                 unsigned long entry;
9100                 gate_desc *desc;
9101                 struct vcpu_vmx *vmx = to_vmx(vcpu);
9102 #ifdef CONFIG_X86_64
9103                 unsigned long tmp;
9104 #endif
9105
9106                 vector =  exit_intr_info & INTR_INFO_VECTOR_MASK;
9107                 desc = (gate_desc *)vmx->host_idt_base + vector;
9108                 entry = gate_offset(desc);
9109                 asm volatile(
9110 #ifdef CONFIG_X86_64
9111                         "mov %%" _ASM_SP ", %[sp]\n\t"
9112                         "and $0xfffffffffffffff0, %%" _ASM_SP "\n\t"
9113                         "push $%c[ss]\n\t"
9114                         "push %[sp]\n\t"
9115 #endif
9116                         "pushf\n\t"
9117                         __ASM_SIZE(push) " $%c[cs]\n\t"
9118                         "call *%[entry]\n\t"
9119                         :
9120 #ifdef CONFIG_X86_64
9121                         [sp]"=&r"(tmp),
9122 #endif
9123                         ASM_CALL_CONSTRAINT
9124                         :
9125                         [entry]"r"(entry),
9126                         [ss]"i"(__KERNEL_DS),
9127                         [cs]"i"(__KERNEL_CS)
9128                         );
9129         }
9130 }
9131 STACK_FRAME_NON_STANDARD(vmx_handle_external_intr);
9132
9133 static bool vmx_has_high_real_mode_segbase(void)
9134 {
9135         return enable_unrestricted_guest || emulate_invalid_guest_state;
9136 }
9137
9138 static bool vmx_mpx_supported(void)
9139 {
9140         return (vmcs_config.vmexit_ctrl & VM_EXIT_CLEAR_BNDCFGS) &&
9141                 (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_BNDCFGS);
9142 }
9143
9144 static bool vmx_xsaves_supported(void)
9145 {
9146         return vmcs_config.cpu_based_2nd_exec_ctrl &
9147                 SECONDARY_EXEC_XSAVES;
9148 }
9149
9150 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
9151 {
9152         u32 exit_intr_info;
9153         bool unblock_nmi;
9154         u8 vector;
9155         bool idtv_info_valid;
9156
9157         idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
9158
9159         if (cpu_has_virtual_nmis()) {
9160                 if (vmx->loaded_vmcs->nmi_known_unmasked)
9161                         return;
9162                 /*
9163                  * Can't use vmx->exit_intr_info since we're not sure what
9164                  * the exit reason is.
9165                  */
9166                 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
9167                 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
9168                 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
9169                 /*
9170                  * SDM 3: 27.7.1.2 (September 2008)
9171                  * Re-set bit "block by NMI" before VM entry if vmexit caused by
9172                  * a guest IRET fault.
9173                  * SDM 3: 23.2.2 (September 2008)
9174                  * Bit 12 is undefined in any of the following cases:
9175                  *  If the VM exit sets the valid bit in the IDT-vectoring
9176                  *   information field.
9177                  *  If the VM exit is due to a double fault.
9178                  */
9179                 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
9180                     vector != DF_VECTOR && !idtv_info_valid)
9181                         vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
9182                                       GUEST_INTR_STATE_NMI);
9183                 else
9184                         vmx->loaded_vmcs->nmi_known_unmasked =
9185                                 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
9186                                   & GUEST_INTR_STATE_NMI);
9187         } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
9188                 vmx->loaded_vmcs->vnmi_blocked_time +=
9189                         ktime_to_ns(ktime_sub(ktime_get(),
9190                                               vmx->loaded_vmcs->entry_time));
9191 }
9192
9193 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
9194                                       u32 idt_vectoring_info,
9195                                       int instr_len_field,
9196                                       int error_code_field)
9197 {
9198         u8 vector;
9199         int type;
9200         bool idtv_info_valid;
9201
9202         idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
9203
9204         vcpu->arch.nmi_injected = false;
9205         kvm_clear_exception_queue(vcpu);
9206         kvm_clear_interrupt_queue(vcpu);
9207
9208         if (!idtv_info_valid)
9209                 return;
9210
9211         kvm_make_request(KVM_REQ_EVENT, vcpu);
9212
9213         vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
9214         type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
9215
9216         switch (type) {
9217         case INTR_TYPE_NMI_INTR:
9218                 vcpu->arch.nmi_injected = true;
9219                 /*
9220                  * SDM 3: 27.7.1.2 (September 2008)
9221                  * Clear bit "block by NMI" before VM entry if a NMI
9222                  * delivery faulted.
9223                  */
9224                 vmx_set_nmi_mask(vcpu, false);
9225                 break;
9226         case INTR_TYPE_SOFT_EXCEPTION:
9227                 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
9228                 /* fall through */
9229         case INTR_TYPE_HARD_EXCEPTION:
9230                 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
9231                         u32 err = vmcs_read32(error_code_field);
9232                         kvm_requeue_exception_e(vcpu, vector, err);
9233                 } else
9234                         kvm_requeue_exception(vcpu, vector);
9235                 break;
9236         case INTR_TYPE_SOFT_INTR:
9237                 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
9238                 /* fall through */
9239         case INTR_TYPE_EXT_INTR:
9240                 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
9241                 break;
9242         default:
9243                 break;
9244         }
9245 }
9246
9247 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
9248 {
9249         __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
9250                                   VM_EXIT_INSTRUCTION_LEN,
9251                                   IDT_VECTORING_ERROR_CODE);
9252 }
9253
9254 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
9255 {
9256         __vmx_complete_interrupts(vcpu,
9257                                   vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
9258                                   VM_ENTRY_INSTRUCTION_LEN,
9259                                   VM_ENTRY_EXCEPTION_ERROR_CODE);
9260
9261         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
9262 }
9263
9264 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
9265 {
9266         int i, nr_msrs;
9267         struct perf_guest_switch_msr *msrs;
9268
9269         msrs = perf_guest_get_msrs(&nr_msrs);
9270
9271         if (!msrs)
9272                 return;
9273
9274         for (i = 0; i < nr_msrs; i++)
9275                 if (msrs[i].host == msrs[i].guest)
9276                         clear_atomic_switch_msr(vmx, msrs[i].msr);
9277                 else
9278                         add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
9279                                         msrs[i].host);
9280 }
9281
9282 static void vmx_arm_hv_timer(struct kvm_vcpu *vcpu)
9283 {
9284         struct vcpu_vmx *vmx = to_vmx(vcpu);
9285         u64 tscl;
9286         u32 delta_tsc;
9287
9288         if (vmx->hv_deadline_tsc == -1)
9289                 return;
9290
9291         tscl = rdtsc();
9292         if (vmx->hv_deadline_tsc > tscl)
9293                 /* sure to be 32 bit only because checked on set_hv_timer */
9294                 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
9295                         cpu_preemption_timer_multi);
9296         else
9297                 delta_tsc = 0;
9298
9299         vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc);
9300 }
9301
9302 static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
9303 {
9304         struct vcpu_vmx *vmx = to_vmx(vcpu);
9305         unsigned long debugctlmsr, cr3, cr4;
9306
9307         /* Record the guest's net vcpu time for enforced NMI injections. */
9308         if (unlikely(!cpu_has_virtual_nmis() &&
9309                      vmx->loaded_vmcs->soft_vnmi_blocked))
9310                 vmx->loaded_vmcs->entry_time = ktime_get();
9311
9312         /* Don't enter VMX if guest state is invalid, let the exit handler
9313            start emulation until we arrive back to a valid state */
9314         if (vmx->emulation_required)
9315                 return;
9316
9317         if (vmx->ple_window_dirty) {
9318                 vmx->ple_window_dirty = false;
9319                 vmcs_write32(PLE_WINDOW, vmx->ple_window);
9320         }
9321
9322         if (vmx->nested.sync_shadow_vmcs) {
9323                 copy_vmcs12_to_shadow(vmx);
9324                 vmx->nested.sync_shadow_vmcs = false;
9325         }
9326
9327         if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
9328                 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
9329         if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
9330                 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
9331
9332         cr3 = __get_current_cr3_fast();
9333         if (unlikely(cr3 != vmx->loaded_vmcs->vmcs_host_cr3)) {
9334                 vmcs_writel(HOST_CR3, cr3);
9335                 vmx->loaded_vmcs->vmcs_host_cr3 = cr3;
9336         }
9337
9338         cr4 = cr4_read_shadow();
9339         if (unlikely(cr4 != vmx->loaded_vmcs->vmcs_host_cr4)) {
9340                 vmcs_writel(HOST_CR4, cr4);
9341                 vmx->loaded_vmcs->vmcs_host_cr4 = cr4;
9342         }
9343
9344         /* When single-stepping over STI and MOV SS, we must clear the
9345          * corresponding interruptibility bits in the guest state. Otherwise
9346          * vmentry fails as it then expects bit 14 (BS) in pending debug
9347          * exceptions being set, but that's not correct for the guest debugging
9348          * case. */
9349         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
9350                 vmx_set_interrupt_shadow(vcpu, 0);
9351
9352         if (static_cpu_has(X86_FEATURE_PKU) &&
9353             kvm_read_cr4_bits(vcpu, X86_CR4_PKE) &&
9354             vcpu->arch.pkru != vmx->host_pkru)
9355                 __write_pkru(vcpu->arch.pkru);
9356
9357         atomic_switch_perf_msrs(vmx);
9358         debugctlmsr = get_debugctlmsr();
9359
9360         vmx_arm_hv_timer(vcpu);
9361
9362         vmx->__launched = vmx->loaded_vmcs->launched;
9363         asm(
9364                 /* Store host registers */
9365                 "push %%" _ASM_DX "; push %%" _ASM_BP ";"
9366                 "push %%" _ASM_CX " \n\t" /* placeholder for guest rcx */
9367                 "push %%" _ASM_CX " \n\t"
9368                 "cmp %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
9369                 "je 1f \n\t"
9370                 "mov %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
9371                 __ex(ASM_VMX_VMWRITE_RSP_RDX) "\n\t"
9372                 "1: \n\t"
9373                 /* Reload cr2 if changed */
9374                 "mov %c[cr2](%0), %%" _ASM_AX " \n\t"
9375                 "mov %%cr2, %%" _ASM_DX " \n\t"
9376                 "cmp %%" _ASM_AX ", %%" _ASM_DX " \n\t"
9377                 "je 2f \n\t"
9378                 "mov %%" _ASM_AX", %%cr2 \n\t"
9379                 "2: \n\t"
9380                 /* Check if vmlaunch of vmresume is needed */
9381                 "cmpl $0, %c[launched](%0) \n\t"
9382                 /* Load guest registers.  Don't clobber flags. */
9383                 "mov %c[rax](%0), %%" _ASM_AX " \n\t"
9384                 "mov %c[rbx](%0), %%" _ASM_BX " \n\t"
9385                 "mov %c[rdx](%0), %%" _ASM_DX " \n\t"
9386                 "mov %c[rsi](%0), %%" _ASM_SI " \n\t"
9387                 "mov %c[rdi](%0), %%" _ASM_DI " \n\t"
9388                 "mov %c[rbp](%0), %%" _ASM_BP " \n\t"
9389 #ifdef CONFIG_X86_64
9390                 "mov %c[r8](%0),  %%r8  \n\t"
9391                 "mov %c[r9](%0),  %%r9  \n\t"
9392                 "mov %c[r10](%0), %%r10 \n\t"
9393                 "mov %c[r11](%0), %%r11 \n\t"
9394                 "mov %c[r12](%0), %%r12 \n\t"
9395                 "mov %c[r13](%0), %%r13 \n\t"
9396                 "mov %c[r14](%0), %%r14 \n\t"
9397                 "mov %c[r15](%0), %%r15 \n\t"
9398 #endif
9399                 "mov %c[rcx](%0), %%" _ASM_CX " \n\t" /* kills %0 (ecx) */
9400
9401                 /* Enter guest mode */
9402                 "jne 1f \n\t"
9403                 __ex(ASM_VMX_VMLAUNCH) "\n\t"
9404                 "jmp 2f \n\t"
9405                 "1: " __ex(ASM_VMX_VMRESUME) "\n\t"
9406                 "2: "
9407                 /* Save guest registers, load host registers, keep flags */
9408                 "mov %0, %c[wordsize](%%" _ASM_SP ") \n\t"
9409                 "pop %0 \n\t"
9410                 "mov %%" _ASM_AX ", %c[rax](%0) \n\t"
9411                 "mov %%" _ASM_BX ", %c[rbx](%0) \n\t"
9412                 __ASM_SIZE(pop) " %c[rcx](%0) \n\t"
9413                 "mov %%" _ASM_DX ", %c[rdx](%0) \n\t"
9414                 "mov %%" _ASM_SI ", %c[rsi](%0) \n\t"
9415                 "mov %%" _ASM_DI ", %c[rdi](%0) \n\t"
9416                 "mov %%" _ASM_BP ", %c[rbp](%0) \n\t"
9417 #ifdef CONFIG_X86_64
9418                 "mov %%r8,  %c[r8](%0) \n\t"
9419                 "mov %%r9,  %c[r9](%0) \n\t"
9420                 "mov %%r10, %c[r10](%0) \n\t"
9421                 "mov %%r11, %c[r11](%0) \n\t"
9422                 "mov %%r12, %c[r12](%0) \n\t"
9423                 "mov %%r13, %c[r13](%0) \n\t"
9424                 "mov %%r14, %c[r14](%0) \n\t"
9425                 "mov %%r15, %c[r15](%0) \n\t"
9426 #endif
9427                 "mov %%cr2, %%" _ASM_AX "   \n\t"
9428                 "mov %%" _ASM_AX ", %c[cr2](%0) \n\t"
9429
9430                 "pop  %%" _ASM_BP "; pop  %%" _ASM_DX " \n\t"
9431                 "setbe %c[fail](%0) \n\t"
9432                 ".pushsection .rodata \n\t"
9433                 ".global vmx_return \n\t"
9434                 "vmx_return: " _ASM_PTR " 2b \n\t"
9435                 ".popsection"
9436               : : "c"(vmx), "d"((unsigned long)HOST_RSP),
9437                 [launched]"i"(offsetof(struct vcpu_vmx, __launched)),
9438                 [fail]"i"(offsetof(struct vcpu_vmx, fail)),
9439                 [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)),
9440                 [rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])),
9441                 [rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])),
9442                 [rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])),
9443                 [rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])),
9444                 [rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])),
9445                 [rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])),
9446                 [rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])),
9447 #ifdef CONFIG_X86_64
9448                 [r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])),
9449                 [r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])),
9450                 [r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])),
9451                 [r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])),
9452                 [r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])),
9453                 [r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])),
9454                 [r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])),
9455                 [r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])),
9456 #endif
9457                 [cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2)),
9458                 [wordsize]"i"(sizeof(ulong))
9459               : "cc", "memory"
9460 #ifdef CONFIG_X86_64
9461                 , "rax", "rbx", "rdi", "rsi"
9462                 , "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
9463 #else
9464                 , "eax", "ebx", "edi", "esi"
9465 #endif
9466               );
9467
9468         /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
9469         if (debugctlmsr)
9470                 update_debugctlmsr(debugctlmsr);
9471
9472 #ifndef CONFIG_X86_64
9473         /*
9474          * The sysexit path does not restore ds/es, so we must set them to
9475          * a reasonable value ourselves.
9476          *
9477          * We can't defer this to vmx_load_host_state() since that function
9478          * may be executed in interrupt context, which saves and restore segments
9479          * around it, nullifying its effect.
9480          */
9481         loadsegment(ds, __USER_DS);
9482         loadsegment(es, __USER_DS);
9483 #endif
9484
9485         vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
9486                                   | (1 << VCPU_EXREG_RFLAGS)
9487                                   | (1 << VCPU_EXREG_PDPTR)
9488                                   | (1 << VCPU_EXREG_SEGMENTS)
9489                                   | (1 << VCPU_EXREG_CR3));
9490         vcpu->arch.regs_dirty = 0;
9491
9492         /*
9493          * eager fpu is enabled if PKEY is supported and CR4 is switched
9494          * back on host, so it is safe to read guest PKRU from current
9495          * XSAVE.
9496          */
9497         if (static_cpu_has(X86_FEATURE_PKU) &&
9498             kvm_read_cr4_bits(vcpu, X86_CR4_PKE)) {
9499                 vcpu->arch.pkru = __read_pkru();
9500                 if (vcpu->arch.pkru != vmx->host_pkru)
9501                         __write_pkru(vmx->host_pkru);
9502         }
9503
9504         /*
9505          * the KVM_REQ_EVENT optimization bit is only on for one entry, and if
9506          * we did not inject a still-pending event to L1 now because of
9507          * nested_run_pending, we need to re-enable this bit.
9508          */
9509         if (vmx->nested.nested_run_pending)
9510                 kvm_make_request(KVM_REQ_EVENT, vcpu);
9511
9512         vmx->nested.nested_run_pending = 0;
9513         vmx->idt_vectoring_info = 0;
9514
9515         vmx->exit_reason = vmx->fail ? 0xdead : vmcs_read32(VM_EXIT_REASON);
9516         if (vmx->fail || (vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
9517                 return;
9518
9519         vmx->loaded_vmcs->launched = 1;
9520         vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
9521
9522         vmx_complete_atomic_exit(vmx);
9523         vmx_recover_nmi_blocking(vmx);
9524         vmx_complete_interrupts(vmx);
9525 }
9526 STACK_FRAME_NON_STANDARD(vmx_vcpu_run);
9527
9528 static void vmx_switch_vmcs(struct kvm_vcpu *vcpu, struct loaded_vmcs *vmcs)
9529 {
9530         struct vcpu_vmx *vmx = to_vmx(vcpu);
9531         int cpu;
9532
9533         if (vmx->loaded_vmcs == vmcs)
9534                 return;
9535
9536         cpu = get_cpu();
9537         vmx->loaded_vmcs = vmcs;
9538         vmx_vcpu_put(vcpu);
9539         vmx_vcpu_load(vcpu, cpu);
9540         vcpu->cpu = cpu;
9541         put_cpu();
9542 }
9543
9544 /*
9545  * Ensure that the current vmcs of the logical processor is the
9546  * vmcs01 of the vcpu before calling free_nested().
9547  */
9548 static void vmx_free_vcpu_nested(struct kvm_vcpu *vcpu)
9549 {
9550        struct vcpu_vmx *vmx = to_vmx(vcpu);
9551        int r;
9552
9553        r = vcpu_load(vcpu);
9554        BUG_ON(r);
9555        vmx_switch_vmcs(vcpu, &vmx->vmcs01);
9556        free_nested(vmx);
9557        vcpu_put(vcpu);
9558 }
9559
9560 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
9561 {
9562         struct vcpu_vmx *vmx = to_vmx(vcpu);
9563
9564         if (enable_pml)
9565                 vmx_destroy_pml_buffer(vmx);
9566         free_vpid(vmx->vpid);
9567         leave_guest_mode(vcpu);
9568         vmx_free_vcpu_nested(vcpu);
9569         free_loaded_vmcs(vmx->loaded_vmcs);
9570         kfree(vmx->guest_msrs);
9571         kvm_vcpu_uninit(vcpu);
9572         kmem_cache_free(kvm_vcpu_cache, vmx);
9573 }
9574
9575 static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
9576 {
9577         int err;
9578         struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
9579         int cpu;
9580
9581         if (!vmx)
9582                 return ERR_PTR(-ENOMEM);
9583
9584         vmx->vpid = allocate_vpid();
9585
9586         err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
9587         if (err)
9588                 goto free_vcpu;
9589
9590         err = -ENOMEM;
9591
9592         /*
9593          * If PML is turned on, failure on enabling PML just results in failure
9594          * of creating the vcpu, therefore we can simplify PML logic (by
9595          * avoiding dealing with cases, such as enabling PML partially on vcpus
9596          * for the guest, etc.
9597          */
9598         if (enable_pml) {
9599                 vmx->pml_pg = alloc_page(GFP_KERNEL | __GFP_ZERO);
9600                 if (!vmx->pml_pg)
9601                         goto uninit_vcpu;
9602         }
9603
9604         vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
9605         BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) * sizeof(vmx->guest_msrs[0])
9606                      > PAGE_SIZE);
9607
9608         if (!vmx->guest_msrs)
9609                 goto free_pml;
9610
9611         vmx->loaded_vmcs = &vmx->vmcs01;
9612         vmx->loaded_vmcs->vmcs = alloc_vmcs();
9613         vmx->loaded_vmcs->shadow_vmcs = NULL;
9614         if (!vmx->loaded_vmcs->vmcs)
9615                 goto free_msrs;
9616         loaded_vmcs_init(vmx->loaded_vmcs);
9617
9618         cpu = get_cpu();
9619         vmx_vcpu_load(&vmx->vcpu, cpu);
9620         vmx->vcpu.cpu = cpu;
9621         err = vmx_vcpu_setup(vmx);
9622         vmx_vcpu_put(&vmx->vcpu);
9623         put_cpu();
9624         if (err)
9625                 goto free_vmcs;
9626         if (cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
9627                 err = alloc_apic_access_page(kvm);
9628                 if (err)
9629                         goto free_vmcs;
9630         }
9631
9632         if (enable_ept) {
9633                 if (!kvm->arch.ept_identity_map_addr)
9634                         kvm->arch.ept_identity_map_addr =
9635                                 VMX_EPT_IDENTITY_PAGETABLE_ADDR;
9636                 err = init_rmode_identity_map(kvm);
9637                 if (err)
9638                         goto free_vmcs;
9639         }
9640
9641         if (nested) {
9642                 nested_vmx_setup_ctls_msrs(vmx);
9643                 vmx->nested.vpid02 = allocate_vpid();
9644         }
9645
9646         vmx->nested.posted_intr_nv = -1;
9647         vmx->nested.current_vmptr = -1ull;
9648
9649         vmx->msr_ia32_feature_control_valid_bits = FEATURE_CONTROL_LOCKED;
9650
9651         /*
9652          * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
9653          * or POSTED_INTR_WAKEUP_VECTOR.
9654          */
9655         vmx->pi_desc.nv = POSTED_INTR_VECTOR;
9656         vmx->pi_desc.sn = 1;
9657
9658         return &vmx->vcpu;
9659
9660 free_vmcs:
9661         free_vpid(vmx->nested.vpid02);
9662         free_loaded_vmcs(vmx->loaded_vmcs);
9663 free_msrs:
9664         kfree(vmx->guest_msrs);
9665 free_pml:
9666         vmx_destroy_pml_buffer(vmx);
9667 uninit_vcpu:
9668         kvm_vcpu_uninit(&vmx->vcpu);
9669 free_vcpu:
9670         free_vpid(vmx->vpid);
9671         kmem_cache_free(kvm_vcpu_cache, vmx);
9672         return ERR_PTR(err);
9673 }
9674
9675 static void __init vmx_check_processor_compat(void *rtn)
9676 {
9677         struct vmcs_config vmcs_conf;
9678
9679         *(int *)rtn = 0;
9680         if (setup_vmcs_config(&vmcs_conf) < 0)
9681                 *(int *)rtn = -EIO;
9682         if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
9683                 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
9684                                 smp_processor_id());
9685                 *(int *)rtn = -EIO;
9686         }
9687 }
9688
9689 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
9690 {
9691         u8 cache;
9692         u64 ipat = 0;
9693
9694         /* For VT-d and EPT combination
9695          * 1. MMIO: always map as UC
9696          * 2. EPT with VT-d:
9697          *   a. VT-d without snooping control feature: can't guarantee the
9698          *      result, try to trust guest.
9699          *   b. VT-d with snooping control feature: snooping control feature of
9700          *      VT-d engine can guarantee the cache correctness. Just set it
9701          *      to WB to keep consistent with host. So the same as item 3.
9702          * 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
9703          *    consistent with host MTRR
9704          */
9705         if (is_mmio) {
9706                 cache = MTRR_TYPE_UNCACHABLE;
9707                 goto exit;
9708         }
9709
9710         if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
9711                 ipat = VMX_EPT_IPAT_BIT;
9712                 cache = MTRR_TYPE_WRBACK;
9713                 goto exit;
9714         }
9715
9716         if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
9717                 ipat = VMX_EPT_IPAT_BIT;
9718                 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
9719                         cache = MTRR_TYPE_WRBACK;
9720                 else
9721                         cache = MTRR_TYPE_UNCACHABLE;
9722                 goto exit;
9723         }
9724
9725         cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
9726
9727 exit:
9728         return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
9729 }
9730
9731 static int vmx_get_lpage_level(void)
9732 {
9733         if (enable_ept && !cpu_has_vmx_ept_1g_page())
9734                 return PT_DIRECTORY_LEVEL;
9735         else
9736                 /* For shadow and EPT supported 1GB page */
9737                 return PT_PDPE_LEVEL;
9738 }
9739
9740 static void vmcs_set_secondary_exec_control(u32 new_ctl)
9741 {
9742         /*
9743          * These bits in the secondary execution controls field
9744          * are dynamic, the others are mostly based on the hypervisor
9745          * architecture and the guest's CPUID.  Do not touch the
9746          * dynamic bits.
9747          */
9748         u32 mask =
9749                 SECONDARY_EXEC_SHADOW_VMCS |
9750                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
9751                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
9752
9753         u32 cur_ctl = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
9754
9755         vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
9756                      (new_ctl & ~mask) | (cur_ctl & mask));
9757 }
9758
9759 /*
9760  * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
9761  * (indicating "allowed-1") if they are supported in the guest's CPUID.
9762  */
9763 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
9764 {
9765         struct vcpu_vmx *vmx = to_vmx(vcpu);
9766         struct kvm_cpuid_entry2 *entry;
9767
9768         vmx->nested.nested_vmx_cr0_fixed1 = 0xffffffff;
9769         vmx->nested.nested_vmx_cr4_fixed1 = X86_CR4_PCE;
9770
9771 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do {            \
9772         if (entry && (entry->_reg & (_cpuid_mask)))                     \
9773                 vmx->nested.nested_vmx_cr4_fixed1 |= (_cr4_mask);       \
9774 } while (0)
9775
9776         entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
9777         cr4_fixed1_update(X86_CR4_VME,        edx, bit(X86_FEATURE_VME));
9778         cr4_fixed1_update(X86_CR4_PVI,        edx, bit(X86_FEATURE_VME));
9779         cr4_fixed1_update(X86_CR4_TSD,        edx, bit(X86_FEATURE_TSC));
9780         cr4_fixed1_update(X86_CR4_DE,         edx, bit(X86_FEATURE_DE));
9781         cr4_fixed1_update(X86_CR4_PSE,        edx, bit(X86_FEATURE_PSE));
9782         cr4_fixed1_update(X86_CR4_PAE,        edx, bit(X86_FEATURE_PAE));
9783         cr4_fixed1_update(X86_CR4_MCE,        edx, bit(X86_FEATURE_MCE));
9784         cr4_fixed1_update(X86_CR4_PGE,        edx, bit(X86_FEATURE_PGE));
9785         cr4_fixed1_update(X86_CR4_OSFXSR,     edx, bit(X86_FEATURE_FXSR));
9786         cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, bit(X86_FEATURE_XMM));
9787         cr4_fixed1_update(X86_CR4_VMXE,       ecx, bit(X86_FEATURE_VMX));
9788         cr4_fixed1_update(X86_CR4_SMXE,       ecx, bit(X86_FEATURE_SMX));
9789         cr4_fixed1_update(X86_CR4_PCIDE,      ecx, bit(X86_FEATURE_PCID));
9790         cr4_fixed1_update(X86_CR4_OSXSAVE,    ecx, bit(X86_FEATURE_XSAVE));
9791
9792         entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
9793         cr4_fixed1_update(X86_CR4_FSGSBASE,   ebx, bit(X86_FEATURE_FSGSBASE));
9794         cr4_fixed1_update(X86_CR4_SMEP,       ebx, bit(X86_FEATURE_SMEP));
9795         cr4_fixed1_update(X86_CR4_SMAP,       ebx, bit(X86_FEATURE_SMAP));
9796         cr4_fixed1_update(X86_CR4_PKE,        ecx, bit(X86_FEATURE_PKU));
9797         /* TODO: Use X86_CR4_UMIP and X86_FEATURE_UMIP macros */
9798         cr4_fixed1_update(bit(11),            ecx, bit(2));
9799
9800 #undef cr4_fixed1_update
9801 }
9802
9803 static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
9804 {
9805         struct vcpu_vmx *vmx = to_vmx(vcpu);
9806
9807         if (cpu_has_secondary_exec_ctrls()) {
9808                 vmx_compute_secondary_exec_control(vmx);
9809                 vmcs_set_secondary_exec_control(vmx->secondary_exec_control);
9810         }
9811
9812         if (nested_vmx_allowed(vcpu))
9813                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
9814                         FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
9815         else
9816                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
9817                         ~FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
9818
9819         if (nested_vmx_allowed(vcpu))
9820                 nested_vmx_cr_fixed1_bits_update(vcpu);
9821 }
9822
9823 static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
9824 {
9825         if (func == 1 && nested)
9826                 entry->ecx |= bit(X86_FEATURE_VMX);
9827 }
9828
9829 static void nested_ept_inject_page_fault(struct kvm_vcpu *vcpu,
9830                 struct x86_exception *fault)
9831 {
9832         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
9833         struct vcpu_vmx *vmx = to_vmx(vcpu);
9834         u32 exit_reason;
9835         unsigned long exit_qualification = vcpu->arch.exit_qualification;
9836
9837         if (vmx->nested.pml_full) {
9838                 exit_reason = EXIT_REASON_PML_FULL;
9839                 vmx->nested.pml_full = false;
9840                 exit_qualification &= INTR_INFO_UNBLOCK_NMI;
9841         } else if (fault->error_code & PFERR_RSVD_MASK)
9842                 exit_reason = EXIT_REASON_EPT_MISCONFIG;
9843         else
9844                 exit_reason = EXIT_REASON_EPT_VIOLATION;
9845
9846         nested_vmx_vmexit(vcpu, exit_reason, 0, exit_qualification);
9847         vmcs12->guest_physical_address = fault->address;
9848 }
9849
9850 static bool nested_ept_ad_enabled(struct kvm_vcpu *vcpu)
9851 {
9852         return nested_ept_get_cr3(vcpu) & VMX_EPTP_AD_ENABLE_BIT;
9853 }
9854
9855 /* Callbacks for nested_ept_init_mmu_context: */
9856
9857 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu)
9858 {
9859         /* return the page table to be shadowed - in our case, EPT12 */
9860         return get_vmcs12(vcpu)->ept_pointer;
9861 }
9862
9863 static int nested_ept_init_mmu_context(struct kvm_vcpu *vcpu)
9864 {
9865         WARN_ON(mmu_is_nested(vcpu));
9866         if (!valid_ept_address(vcpu, nested_ept_get_cr3(vcpu)))
9867                 return 1;
9868
9869         kvm_mmu_unload(vcpu);
9870         kvm_init_shadow_ept_mmu(vcpu,
9871                         to_vmx(vcpu)->nested.nested_vmx_ept_caps &
9872                         VMX_EPT_EXECUTE_ONLY_BIT,
9873                         nested_ept_ad_enabled(vcpu));
9874         vcpu->arch.mmu.set_cr3           = vmx_set_cr3;
9875         vcpu->arch.mmu.get_cr3           = nested_ept_get_cr3;
9876         vcpu->arch.mmu.inject_page_fault = nested_ept_inject_page_fault;
9877
9878         vcpu->arch.walk_mmu              = &vcpu->arch.nested_mmu;
9879         return 0;
9880 }
9881
9882 static void nested_ept_uninit_mmu_context(struct kvm_vcpu *vcpu)
9883 {
9884         vcpu->arch.walk_mmu = &vcpu->arch.mmu;
9885 }
9886
9887 static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
9888                                             u16 error_code)
9889 {
9890         bool inequality, bit;
9891
9892         bit = (vmcs12->exception_bitmap & (1u << PF_VECTOR)) != 0;
9893         inequality =
9894                 (error_code & vmcs12->page_fault_error_code_mask) !=
9895                  vmcs12->page_fault_error_code_match;
9896         return inequality ^ bit;
9897 }
9898
9899 static void vmx_inject_page_fault_nested(struct kvm_vcpu *vcpu,
9900                 struct x86_exception *fault)
9901 {
9902         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
9903
9904         WARN_ON(!is_guest_mode(vcpu));
9905
9906         if (nested_vmx_is_page_fault_vmexit(vmcs12, fault->error_code) &&
9907                 !to_vmx(vcpu)->nested.nested_run_pending) {
9908                 vmcs12->vm_exit_intr_error_code = fault->error_code;
9909                 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
9910                                   PF_VECTOR | INTR_TYPE_HARD_EXCEPTION |
9911                                   INTR_INFO_DELIVER_CODE_MASK | INTR_INFO_VALID_MASK,
9912                                   fault->address);
9913         } else {
9914                 kvm_inject_page_fault(vcpu, fault);
9915         }
9916 }
9917
9918 static inline bool nested_vmx_merge_msr_bitmap(struct kvm_vcpu *vcpu,
9919                                                struct vmcs12 *vmcs12);
9920
9921 static void nested_get_vmcs12_pages(struct kvm_vcpu *vcpu,
9922                                         struct vmcs12 *vmcs12)
9923 {
9924         struct vcpu_vmx *vmx = to_vmx(vcpu);
9925         struct page *page;
9926         u64 hpa;
9927
9928         if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
9929                 /*
9930                  * Translate L1 physical address to host physical
9931                  * address for vmcs02. Keep the page pinned, so this
9932                  * physical address remains valid. We keep a reference
9933                  * to it so we can release it later.
9934                  */
9935                 if (vmx->nested.apic_access_page) { /* shouldn't happen */
9936                         kvm_release_page_dirty(vmx->nested.apic_access_page);
9937                         vmx->nested.apic_access_page = NULL;
9938                 }
9939                 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->apic_access_addr);
9940                 /*
9941                  * If translation failed, no matter: This feature asks
9942                  * to exit when accessing the given address, and if it
9943                  * can never be accessed, this feature won't do
9944                  * anything anyway.
9945                  */
9946                 if (!is_error_page(page)) {
9947                         vmx->nested.apic_access_page = page;
9948                         hpa = page_to_phys(vmx->nested.apic_access_page);
9949                         vmcs_write64(APIC_ACCESS_ADDR, hpa);
9950                 } else {
9951                         vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
9952                                         SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
9953                 }
9954         } else if (!(nested_cpu_has_virt_x2apic_mode(vmcs12)) &&
9955                    cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
9956                 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
9957                               SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
9958                 kvm_vcpu_reload_apic_access_page(vcpu);
9959         }
9960
9961         if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
9962                 if (vmx->nested.virtual_apic_page) { /* shouldn't happen */
9963                         kvm_release_page_dirty(vmx->nested.virtual_apic_page);
9964                         vmx->nested.virtual_apic_page = NULL;
9965                 }
9966                 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->virtual_apic_page_addr);
9967
9968                 /*
9969                  * If translation failed, VM entry will fail because
9970                  * prepare_vmcs02 set VIRTUAL_APIC_PAGE_ADDR to -1ull.
9971                  * Failing the vm entry is _not_ what the processor
9972                  * does but it's basically the only possibility we
9973                  * have.  We could still enter the guest if CR8 load
9974                  * exits are enabled, CR8 store exits are enabled, and
9975                  * virtualize APIC access is disabled; in this case
9976                  * the processor would never use the TPR shadow and we
9977                  * could simply clear the bit from the execution
9978                  * control.  But such a configuration is useless, so
9979                  * let's keep the code simple.
9980                  */
9981                 if (!is_error_page(page)) {
9982                         vmx->nested.virtual_apic_page = page;
9983                         hpa = page_to_phys(vmx->nested.virtual_apic_page);
9984                         vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, hpa);
9985                 }
9986         }
9987
9988         if (nested_cpu_has_posted_intr(vmcs12)) {
9989                 if (vmx->nested.pi_desc_page) { /* shouldn't happen */
9990                         kunmap(vmx->nested.pi_desc_page);
9991                         kvm_release_page_dirty(vmx->nested.pi_desc_page);
9992                         vmx->nested.pi_desc_page = NULL;
9993                 }
9994                 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->posted_intr_desc_addr);
9995                 if (is_error_page(page))
9996                         return;
9997                 vmx->nested.pi_desc_page = page;
9998                 vmx->nested.pi_desc = kmap(vmx->nested.pi_desc_page);
9999                 vmx->nested.pi_desc =
10000                         (struct pi_desc *)((void *)vmx->nested.pi_desc +
10001                         (unsigned long)(vmcs12->posted_intr_desc_addr &
10002                         (PAGE_SIZE - 1)));
10003                 vmcs_write64(POSTED_INTR_DESC_ADDR,
10004                         page_to_phys(vmx->nested.pi_desc_page) +
10005                         (unsigned long)(vmcs12->posted_intr_desc_addr &
10006                         (PAGE_SIZE - 1)));
10007         }
10008         if (cpu_has_vmx_msr_bitmap() &&
10009             nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS) &&
10010             nested_vmx_merge_msr_bitmap(vcpu, vmcs12))
10011                 ;
10012         else
10013                 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
10014                                 CPU_BASED_USE_MSR_BITMAPS);
10015 }
10016
10017 static void vmx_start_preemption_timer(struct kvm_vcpu *vcpu)
10018 {
10019         u64 preemption_timeout = get_vmcs12(vcpu)->vmx_preemption_timer_value;
10020         struct vcpu_vmx *vmx = to_vmx(vcpu);
10021
10022         if (vcpu->arch.virtual_tsc_khz == 0)
10023                 return;
10024
10025         /* Make sure short timeouts reliably trigger an immediate vmexit.
10026          * hrtimer_start does not guarantee this. */
10027         if (preemption_timeout <= 1) {
10028                 vmx_preemption_timer_fn(&vmx->nested.preemption_timer);
10029                 return;
10030         }
10031
10032         preemption_timeout <<= VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
10033         preemption_timeout *= 1000000;
10034         do_div(preemption_timeout, vcpu->arch.virtual_tsc_khz);
10035         hrtimer_start(&vmx->nested.preemption_timer,
10036                       ns_to_ktime(preemption_timeout), HRTIMER_MODE_REL);
10037 }
10038
10039 static int nested_vmx_check_io_bitmap_controls(struct kvm_vcpu *vcpu,
10040                                                struct vmcs12 *vmcs12)
10041 {
10042         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
10043                 return 0;
10044
10045         if (!page_address_valid(vcpu, vmcs12->io_bitmap_a) ||
10046             !page_address_valid(vcpu, vmcs12->io_bitmap_b))
10047                 return -EINVAL;
10048
10049         return 0;
10050 }
10051
10052 static int nested_vmx_check_msr_bitmap_controls(struct kvm_vcpu *vcpu,
10053                                                 struct vmcs12 *vmcs12)
10054 {
10055         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
10056                 return 0;
10057
10058         if (!page_address_valid(vcpu, vmcs12->msr_bitmap))
10059                 return -EINVAL;
10060
10061         return 0;
10062 }
10063
10064 static int nested_vmx_check_tpr_shadow_controls(struct kvm_vcpu *vcpu,
10065                                                 struct vmcs12 *vmcs12)
10066 {
10067         if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
10068                 return 0;
10069
10070         if (!page_address_valid(vcpu, vmcs12->virtual_apic_page_addr))
10071                 return -EINVAL;
10072
10073         return 0;
10074 }
10075
10076 /*
10077  * Merge L0's and L1's MSR bitmap, return false to indicate that
10078  * we do not use the hardware.
10079  */
10080 static inline bool nested_vmx_merge_msr_bitmap(struct kvm_vcpu *vcpu,
10081                                                struct vmcs12 *vmcs12)
10082 {
10083         int msr;
10084         struct page *page;
10085         unsigned long *msr_bitmap_l1;
10086         unsigned long *msr_bitmap_l0 = to_vmx(vcpu)->nested.msr_bitmap;
10087
10088         /* This shortcut is ok because we support only x2APIC MSRs so far. */
10089         if (!nested_cpu_has_virt_x2apic_mode(vmcs12))
10090                 return false;
10091
10092         page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->msr_bitmap);
10093         if (is_error_page(page))
10094                 return false;
10095         msr_bitmap_l1 = (unsigned long *)kmap(page);
10096
10097         memset(msr_bitmap_l0, 0xff, PAGE_SIZE);
10098
10099         if (nested_cpu_has_virt_x2apic_mode(vmcs12)) {
10100                 if (nested_cpu_has_apic_reg_virt(vmcs12))
10101                         for (msr = 0x800; msr <= 0x8ff; msr++)
10102                                 nested_vmx_disable_intercept_for_msr(
10103                                         msr_bitmap_l1, msr_bitmap_l0,
10104                                         msr, MSR_TYPE_R);
10105
10106                 nested_vmx_disable_intercept_for_msr(
10107                                 msr_bitmap_l1, msr_bitmap_l0,
10108                                 APIC_BASE_MSR + (APIC_TASKPRI >> 4),
10109                                 MSR_TYPE_R | MSR_TYPE_W);
10110
10111                 if (nested_cpu_has_vid(vmcs12)) {
10112                         nested_vmx_disable_intercept_for_msr(
10113                                 msr_bitmap_l1, msr_bitmap_l0,
10114                                 APIC_BASE_MSR + (APIC_EOI >> 4),
10115                                 MSR_TYPE_W);
10116                         nested_vmx_disable_intercept_for_msr(
10117                                 msr_bitmap_l1, msr_bitmap_l0,
10118                                 APIC_BASE_MSR + (APIC_SELF_IPI >> 4),
10119                                 MSR_TYPE_W);
10120                 }
10121         }
10122         kunmap(page);
10123         kvm_release_page_clean(page);
10124
10125         return true;
10126 }
10127
10128 static int nested_vmx_check_apicv_controls(struct kvm_vcpu *vcpu,
10129                                            struct vmcs12 *vmcs12)
10130 {
10131         if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
10132             !nested_cpu_has_apic_reg_virt(vmcs12) &&
10133             !nested_cpu_has_vid(vmcs12) &&
10134             !nested_cpu_has_posted_intr(vmcs12))
10135                 return 0;
10136
10137         /*
10138          * If virtualize x2apic mode is enabled,
10139          * virtualize apic access must be disabled.
10140          */
10141         if (nested_cpu_has_virt_x2apic_mode(vmcs12) &&
10142             nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
10143                 return -EINVAL;
10144
10145         /*
10146          * If virtual interrupt delivery is enabled,
10147          * we must exit on external interrupts.
10148          */
10149         if (nested_cpu_has_vid(vmcs12) &&
10150            !nested_exit_on_intr(vcpu))
10151                 return -EINVAL;
10152
10153         /*
10154          * bits 15:8 should be zero in posted_intr_nv,
10155          * the descriptor address has been already checked
10156          * in nested_get_vmcs12_pages.
10157          */
10158         if (nested_cpu_has_posted_intr(vmcs12) &&
10159            (!nested_cpu_has_vid(vmcs12) ||
10160             !nested_exit_intr_ack_set(vcpu) ||
10161             vmcs12->posted_intr_nv & 0xff00))
10162                 return -EINVAL;
10163
10164         /* tpr shadow is needed by all apicv features. */
10165         if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
10166                 return -EINVAL;
10167
10168         return 0;
10169 }
10170
10171 static int nested_vmx_check_msr_switch(struct kvm_vcpu *vcpu,
10172                                        unsigned long count_field,
10173                                        unsigned long addr_field)
10174 {
10175         int maxphyaddr;
10176         u64 count, addr;
10177
10178         if (vmcs12_read_any(vcpu, count_field, &count) ||
10179             vmcs12_read_any(vcpu, addr_field, &addr)) {
10180                 WARN_ON(1);
10181                 return -EINVAL;
10182         }
10183         if (count == 0)
10184                 return 0;
10185         maxphyaddr = cpuid_maxphyaddr(vcpu);
10186         if (!IS_ALIGNED(addr, 16) || addr >> maxphyaddr ||
10187             (addr + count * sizeof(struct vmx_msr_entry) - 1) >> maxphyaddr) {
10188                 pr_debug_ratelimited(
10189                         "nVMX: invalid MSR switch (0x%lx, %d, %llu, 0x%08llx)",
10190                         addr_field, maxphyaddr, count, addr);
10191                 return -EINVAL;
10192         }
10193         return 0;
10194 }
10195
10196 static int nested_vmx_check_msr_switch_controls(struct kvm_vcpu *vcpu,
10197                                                 struct vmcs12 *vmcs12)
10198 {
10199         if (vmcs12->vm_exit_msr_load_count == 0 &&
10200             vmcs12->vm_exit_msr_store_count == 0 &&
10201             vmcs12->vm_entry_msr_load_count == 0)
10202                 return 0; /* Fast path */
10203         if (nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_LOAD_COUNT,
10204                                         VM_EXIT_MSR_LOAD_ADDR) ||
10205             nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_STORE_COUNT,
10206                                         VM_EXIT_MSR_STORE_ADDR) ||
10207             nested_vmx_check_msr_switch(vcpu, VM_ENTRY_MSR_LOAD_COUNT,
10208                                         VM_ENTRY_MSR_LOAD_ADDR))
10209                 return -EINVAL;
10210         return 0;
10211 }
10212
10213 static int nested_vmx_check_pml_controls(struct kvm_vcpu *vcpu,
10214                                          struct vmcs12 *vmcs12)
10215 {
10216         u64 address = vmcs12->pml_address;
10217         int maxphyaddr = cpuid_maxphyaddr(vcpu);
10218
10219         if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_PML)) {
10220                 if (!nested_cpu_has_ept(vmcs12) ||
10221                     !IS_ALIGNED(address, 4096)  ||
10222                     address >> maxphyaddr)
10223                         return -EINVAL;
10224         }
10225
10226         return 0;
10227 }
10228
10229 static int nested_vmx_msr_check_common(struct kvm_vcpu *vcpu,
10230                                        struct vmx_msr_entry *e)
10231 {
10232         /* x2APIC MSR accesses are not allowed */
10233         if (vcpu->arch.apic_base & X2APIC_ENABLE && e->index >> 8 == 0x8)
10234                 return -EINVAL;
10235         if (e->index == MSR_IA32_UCODE_WRITE || /* SDM Table 35-2 */
10236             e->index == MSR_IA32_UCODE_REV)
10237                 return -EINVAL;
10238         if (e->reserved != 0)
10239                 return -EINVAL;
10240         return 0;
10241 }
10242
10243 static int nested_vmx_load_msr_check(struct kvm_vcpu *vcpu,
10244                                      struct vmx_msr_entry *e)
10245 {
10246         if (e->index == MSR_FS_BASE ||
10247             e->index == MSR_GS_BASE ||
10248             e->index == MSR_IA32_SMM_MONITOR_CTL || /* SMM is not supported */
10249             nested_vmx_msr_check_common(vcpu, e))
10250                 return -EINVAL;
10251         return 0;
10252 }
10253
10254 static int nested_vmx_store_msr_check(struct kvm_vcpu *vcpu,
10255                                       struct vmx_msr_entry *e)
10256 {
10257         if (e->index == MSR_IA32_SMBASE || /* SMM is not supported */
10258             nested_vmx_msr_check_common(vcpu, e))
10259                 return -EINVAL;
10260         return 0;
10261 }
10262
10263 /*
10264  * Load guest's/host's msr at nested entry/exit.
10265  * return 0 for success, entry index for failure.
10266  */
10267 static u32 nested_vmx_load_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
10268 {
10269         u32 i;
10270         struct vmx_msr_entry e;
10271         struct msr_data msr;
10272
10273         msr.host_initiated = false;
10274         for (i = 0; i < count; i++) {
10275                 if (kvm_vcpu_read_guest(vcpu, gpa + i * sizeof(e),
10276                                         &e, sizeof(e))) {
10277                         pr_debug_ratelimited(
10278                                 "%s cannot read MSR entry (%u, 0x%08llx)\n",
10279                                 __func__, i, gpa + i * sizeof(e));
10280                         goto fail;
10281                 }
10282                 if (nested_vmx_load_msr_check(vcpu, &e)) {
10283                         pr_debug_ratelimited(
10284                                 "%s check failed (%u, 0x%x, 0x%x)\n",
10285                                 __func__, i, e.index, e.reserved);
10286                         goto fail;
10287                 }
10288                 msr.index = e.index;
10289                 msr.data = e.value;
10290                 if (kvm_set_msr(vcpu, &msr)) {
10291                         pr_debug_ratelimited(
10292                                 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
10293                                 __func__, i, e.index, e.value);
10294                         goto fail;
10295                 }
10296         }
10297         return 0;
10298 fail:
10299         return i + 1;
10300 }
10301
10302 static int nested_vmx_store_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
10303 {
10304         u32 i;
10305         struct vmx_msr_entry e;
10306
10307         for (i = 0; i < count; i++) {
10308                 struct msr_data msr_info;
10309                 if (kvm_vcpu_read_guest(vcpu,
10310                                         gpa + i * sizeof(e),
10311                                         &e, 2 * sizeof(u32))) {
10312                         pr_debug_ratelimited(
10313                                 "%s cannot read MSR entry (%u, 0x%08llx)\n",
10314                                 __func__, i, gpa + i * sizeof(e));
10315                         return -EINVAL;
10316                 }
10317                 if (nested_vmx_store_msr_check(vcpu, &e)) {
10318                         pr_debug_ratelimited(
10319                                 "%s check failed (%u, 0x%x, 0x%x)\n",
10320                                 __func__, i, e.index, e.reserved);
10321                         return -EINVAL;
10322                 }
10323                 msr_info.host_initiated = false;
10324                 msr_info.index = e.index;
10325                 if (kvm_get_msr(vcpu, &msr_info)) {
10326                         pr_debug_ratelimited(
10327                                 "%s cannot read MSR (%u, 0x%x)\n",
10328                                 __func__, i, e.index);
10329                         return -EINVAL;
10330                 }
10331                 if (kvm_vcpu_write_guest(vcpu,
10332                                          gpa + i * sizeof(e) +
10333                                              offsetof(struct vmx_msr_entry, value),
10334                                          &msr_info.data, sizeof(msr_info.data))) {
10335                         pr_debug_ratelimited(
10336                                 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
10337                                 __func__, i, e.index, msr_info.data);
10338                         return -EINVAL;
10339                 }
10340         }
10341         return 0;
10342 }
10343
10344 static bool nested_cr3_valid(struct kvm_vcpu *vcpu, unsigned long val)
10345 {
10346         unsigned long invalid_mask;
10347
10348         invalid_mask = (~0ULL) << cpuid_maxphyaddr(vcpu);
10349         return (val & invalid_mask) == 0;
10350 }
10351
10352 /*
10353  * Load guest's/host's cr3 at nested entry/exit. nested_ept is true if we are
10354  * emulating VM entry into a guest with EPT enabled.
10355  * Returns 0 on success, 1 on failure. Invalid state exit qualification code
10356  * is assigned to entry_failure_code on failure.
10357  */
10358 static int nested_vmx_load_cr3(struct kvm_vcpu *vcpu, unsigned long cr3, bool nested_ept,
10359                                u32 *entry_failure_code)
10360 {
10361         if (cr3 != kvm_read_cr3(vcpu) || (!nested_ept && pdptrs_changed(vcpu))) {
10362                 if (!nested_cr3_valid(vcpu, cr3)) {
10363                         *entry_failure_code = ENTRY_FAIL_DEFAULT;
10364                         return 1;
10365                 }
10366
10367                 /*
10368                  * If PAE paging and EPT are both on, CR3 is not used by the CPU and
10369                  * must not be dereferenced.
10370                  */
10371                 if (!is_long_mode(vcpu) && is_pae(vcpu) && is_paging(vcpu) &&
10372                     !nested_ept) {
10373                         if (!load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3)) {
10374                                 *entry_failure_code = ENTRY_FAIL_PDPTE;
10375                                 return 1;
10376                         }
10377                 }
10378
10379                 vcpu->arch.cr3 = cr3;
10380                 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
10381         }
10382
10383         kvm_mmu_reset_context(vcpu);
10384         return 0;
10385 }
10386
10387 /*
10388  * prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
10389  * L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
10390  * with L0's requirements for its guest (a.k.a. vmcs01), so we can run the L2
10391  * guest in a way that will both be appropriate to L1's requests, and our
10392  * needs. In addition to modifying the active vmcs (which is vmcs02), this
10393  * function also has additional necessary side-effects, like setting various
10394  * vcpu->arch fields.
10395  * Returns 0 on success, 1 on failure. Invalid state exit qualification code
10396  * is assigned to entry_failure_code on failure.
10397  */
10398 static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
10399                           bool from_vmentry, u32 *entry_failure_code)
10400 {
10401         struct vcpu_vmx *vmx = to_vmx(vcpu);
10402         u32 exec_control, vmcs12_exec_ctrl;
10403
10404         vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
10405         vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
10406         vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
10407         vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
10408         vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
10409         vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
10410         vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
10411         vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
10412         vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
10413         vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
10414         vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
10415         vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
10416         vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
10417         vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
10418         vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
10419         vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
10420         vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
10421         vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
10422         vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
10423         vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
10424         vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
10425         vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
10426         vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
10427         vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
10428         vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
10429         vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
10430         vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
10431         vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
10432         vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
10433         vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
10434         vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
10435         vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
10436         vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
10437         vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
10438         vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
10439         vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
10440
10441         if (from_vmentry &&
10442             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS)) {
10443                 kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
10444                 vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
10445         } else {
10446                 kvm_set_dr(vcpu, 7, vcpu->arch.dr7);
10447                 vmcs_write64(GUEST_IA32_DEBUGCTL, vmx->nested.vmcs01_debugctl);
10448         }
10449         if (from_vmentry) {
10450                 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
10451                              vmcs12->vm_entry_intr_info_field);
10452                 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
10453                              vmcs12->vm_entry_exception_error_code);
10454                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
10455                              vmcs12->vm_entry_instruction_len);
10456                 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
10457                              vmcs12->guest_interruptibility_info);
10458                 vmx->loaded_vmcs->nmi_known_unmasked =
10459                         !(vmcs12->guest_interruptibility_info & GUEST_INTR_STATE_NMI);
10460         } else {
10461                 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
10462         }
10463         vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
10464         vmx_set_rflags(vcpu, vmcs12->guest_rflags);
10465         vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
10466                 vmcs12->guest_pending_dbg_exceptions);
10467         vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
10468         vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
10469
10470         if (nested_cpu_has_xsaves(vmcs12))
10471                 vmcs_write64(XSS_EXIT_BITMAP, vmcs12->xss_exit_bitmap);
10472         vmcs_write64(VMCS_LINK_POINTER, -1ull);
10473
10474         exec_control = vmcs12->pin_based_vm_exec_control;
10475
10476         /* Preemption timer setting is only taken from vmcs01.  */
10477         exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
10478         exec_control |= vmcs_config.pin_based_exec_ctrl;
10479         if (vmx->hv_deadline_tsc == -1)
10480                 exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
10481
10482         /* Posted interrupts setting is only taken from vmcs12.  */
10483         if (nested_cpu_has_posted_intr(vmcs12)) {
10484                 vmx->nested.posted_intr_nv = vmcs12->posted_intr_nv;
10485                 vmx->nested.pi_pending = false;
10486                 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_NESTED_VECTOR);
10487         } else {
10488                 exec_control &= ~PIN_BASED_POSTED_INTR;
10489         }
10490
10491         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, exec_control);
10492
10493         vmx->nested.preemption_timer_expired = false;
10494         if (nested_cpu_has_preemption_timer(vmcs12))
10495                 vmx_start_preemption_timer(vcpu);
10496
10497         /*
10498          * Whether page-faults are trapped is determined by a combination of
10499          * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.
10500          * If enable_ept, L0 doesn't care about page faults and we should
10501          * set all of these to L1's desires. However, if !enable_ept, L0 does
10502          * care about (at least some) page faults, and because it is not easy
10503          * (if at all possible?) to merge L0 and L1's desires, we simply ask
10504          * to exit on each and every L2 page fault. This is done by setting
10505          * MASK=MATCH=0 and (see below) EB.PF=1.
10506          * Note that below we don't need special code to set EB.PF beyond the
10507          * "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
10508          * vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
10509          * !enable_ept, EB.PF is 1, so the "or" will always be 1.
10510          */
10511         vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK,
10512                 enable_ept ? vmcs12->page_fault_error_code_mask : 0);
10513         vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
10514                 enable_ept ? vmcs12->page_fault_error_code_match : 0);
10515
10516         if (cpu_has_secondary_exec_ctrls()) {
10517                 exec_control = vmx->secondary_exec_control;
10518
10519                 /* Take the following fields only from vmcs12 */
10520                 exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
10521                                   SECONDARY_EXEC_ENABLE_INVPCID |
10522                                   SECONDARY_EXEC_RDTSCP |
10523                                   SECONDARY_EXEC_XSAVES |
10524                                   SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
10525                                   SECONDARY_EXEC_APIC_REGISTER_VIRT |
10526                                   SECONDARY_EXEC_ENABLE_VMFUNC);
10527                 if (nested_cpu_has(vmcs12,
10528                                    CPU_BASED_ACTIVATE_SECONDARY_CONTROLS)) {
10529                         vmcs12_exec_ctrl = vmcs12->secondary_vm_exec_control &
10530                                 ~SECONDARY_EXEC_ENABLE_PML;
10531                         exec_control |= vmcs12_exec_ctrl;
10532                 }
10533
10534                 /* All VMFUNCs are currently emulated through L0 vmexits.  */
10535                 if (exec_control & SECONDARY_EXEC_ENABLE_VMFUNC)
10536                         vmcs_write64(VM_FUNCTION_CONTROL, 0);
10537
10538                 if (exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
10539                         vmcs_write64(EOI_EXIT_BITMAP0,
10540                                 vmcs12->eoi_exit_bitmap0);
10541                         vmcs_write64(EOI_EXIT_BITMAP1,
10542                                 vmcs12->eoi_exit_bitmap1);
10543                         vmcs_write64(EOI_EXIT_BITMAP2,
10544                                 vmcs12->eoi_exit_bitmap2);
10545                         vmcs_write64(EOI_EXIT_BITMAP3,
10546                                 vmcs12->eoi_exit_bitmap3);
10547                         vmcs_write16(GUEST_INTR_STATUS,
10548                                 vmcs12->guest_intr_status);
10549                 }
10550
10551                 /*
10552                  * Write an illegal value to APIC_ACCESS_ADDR. Later,
10553                  * nested_get_vmcs12_pages will either fix it up or
10554                  * remove the VM execution control.
10555                  */
10556                 if (exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
10557                         vmcs_write64(APIC_ACCESS_ADDR, -1ull);
10558
10559                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
10560         }
10561
10562
10563         /*
10564          * Set host-state according to L0's settings (vmcs12 is irrelevant here)
10565          * Some constant fields are set here by vmx_set_constant_host_state().
10566          * Other fields are different per CPU, and will be set later when
10567          * vmx_vcpu_load() is called, and when vmx_save_host_state() is called.
10568          */
10569         vmx_set_constant_host_state(vmx);
10570
10571         /*
10572          * Set the MSR load/store lists to match L0's settings.
10573          */
10574         vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
10575         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
10576         vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host));
10577         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
10578         vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest));
10579
10580         /*
10581          * HOST_RSP is normally set correctly in vmx_vcpu_run() just before
10582          * entry, but only if the current (host) sp changed from the value
10583          * we wrote last (vmx->host_rsp). This cache is no longer relevant
10584          * if we switch vmcs, and rather than hold a separate cache per vmcs,
10585          * here we just force the write to happen on entry.
10586          */
10587         vmx->host_rsp = 0;
10588
10589         exec_control = vmx_exec_control(vmx); /* L0's desires */
10590         exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
10591         exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
10592         exec_control &= ~CPU_BASED_TPR_SHADOW;
10593         exec_control |= vmcs12->cpu_based_vm_exec_control;
10594
10595         /*
10596          * Write an illegal value to VIRTUAL_APIC_PAGE_ADDR. Later, if
10597          * nested_get_vmcs12_pages can't fix it up, the illegal value
10598          * will result in a VM entry failure.
10599          */
10600         if (exec_control & CPU_BASED_TPR_SHADOW) {
10601                 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, -1ull);
10602                 vmcs_write32(TPR_THRESHOLD, vmcs12->tpr_threshold);
10603         } else {
10604 #ifdef CONFIG_X86_64
10605                 exec_control |= CPU_BASED_CR8_LOAD_EXITING |
10606                                 CPU_BASED_CR8_STORE_EXITING;
10607 #endif
10608         }
10609
10610         /*
10611          * Merging of IO bitmap not currently supported.
10612          * Rather, exit every time.
10613          */
10614         exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
10615         exec_control |= CPU_BASED_UNCOND_IO_EXITING;
10616
10617         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
10618
10619         /* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
10620          * bitwise-or of what L1 wants to trap for L2, and what we want to
10621          * trap. Note that CR0.TS also needs updating - we do this later.
10622          */
10623         update_exception_bitmap(vcpu);
10624         vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
10625         vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
10626
10627         /* L2->L1 exit controls are emulated - the hardware exit is to L0 so
10628          * we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER
10629          * bits are further modified by vmx_set_efer() below.
10630          */
10631         vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);
10632
10633         /* vmcs12's VM_ENTRY_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE are
10634          * emulated by vmx_set_efer(), below.
10635          */
10636         vm_entry_controls_init(vmx, 
10637                 (vmcs12->vm_entry_controls & ~VM_ENTRY_LOAD_IA32_EFER &
10638                         ~VM_ENTRY_IA32E_MODE) |
10639                 (vmcs_config.vmentry_ctrl & ~VM_ENTRY_IA32E_MODE));
10640
10641         if (from_vmentry &&
10642             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT)) {
10643                 vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
10644                 vcpu->arch.pat = vmcs12->guest_ia32_pat;
10645         } else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
10646                 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
10647         }
10648
10649         set_cr4_guest_host_mask(vmx);
10650
10651         if (from_vmentry &&
10652             vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS)
10653                 vmcs_write64(GUEST_BNDCFGS, vmcs12->guest_bndcfgs);
10654
10655         if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
10656                 vmcs_write64(TSC_OFFSET,
10657                         vcpu->arch.tsc_offset + vmcs12->tsc_offset);
10658         else
10659                 vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
10660         if (kvm_has_tsc_control)
10661                 decache_tsc_multiplier(vmx);
10662
10663         if (enable_vpid) {
10664                 /*
10665                  * There is no direct mapping between vpid02 and vpid12, the
10666                  * vpid02 is per-vCPU for L0 and reused while the value of
10667                  * vpid12 is changed w/ one invvpid during nested vmentry.
10668                  * The vpid12 is allocated by L1 for L2, so it will not
10669                  * influence global bitmap(for vpid01 and vpid02 allocation)
10670                  * even if spawn a lot of nested vCPUs.
10671                  */
10672                 if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02) {
10673                         vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->nested.vpid02);
10674                         if (vmcs12->virtual_processor_id != vmx->nested.last_vpid) {
10675                                 vmx->nested.last_vpid = vmcs12->virtual_processor_id;
10676                                 __vmx_flush_tlb(vcpu, to_vmx(vcpu)->nested.vpid02);
10677                         }
10678                 } else {
10679                         vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
10680                         vmx_flush_tlb(vcpu);
10681                 }
10682
10683         }
10684
10685         if (enable_pml) {
10686                 /*
10687                  * Conceptually we want to copy the PML address and index from
10688                  * vmcs01 here, and then back to vmcs01 on nested vmexit. But,
10689                  * since we always flush the log on each vmexit, this happens
10690                  * to be equivalent to simply resetting the fields in vmcs02.
10691                  */
10692                 ASSERT(vmx->pml_pg);
10693                 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
10694                 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
10695         }
10696
10697         if (nested_cpu_has_ept(vmcs12)) {
10698                 if (nested_ept_init_mmu_context(vcpu)) {
10699                         *entry_failure_code = ENTRY_FAIL_DEFAULT;
10700                         return 1;
10701                 }
10702         } else if (nested_cpu_has2(vmcs12,
10703                                    SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
10704                 vmx_flush_tlb_ept_only(vcpu);
10705         }
10706
10707         /*
10708          * This sets GUEST_CR0 to vmcs12->guest_cr0, possibly modifying those
10709          * bits which we consider mandatory enabled.
10710          * The CR0_READ_SHADOW is what L2 should have expected to read given
10711          * the specifications by L1; It's not enough to take
10712          * vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we
10713          * have more bits than L1 expected.
10714          */
10715         vmx_set_cr0(vcpu, vmcs12->guest_cr0);
10716         vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
10717
10718         vmx_set_cr4(vcpu, vmcs12->guest_cr4);
10719         vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
10720
10721         if (from_vmentry &&
10722             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER))
10723                 vcpu->arch.efer = vmcs12->guest_ia32_efer;
10724         else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
10725                 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
10726         else
10727                 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
10728         /* Note: modifies VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
10729         vmx_set_efer(vcpu, vcpu->arch.efer);
10730
10731         /* Shadow page tables on either EPT or shadow page tables. */
10732         if (nested_vmx_load_cr3(vcpu, vmcs12->guest_cr3, nested_cpu_has_ept(vmcs12),
10733                                 entry_failure_code))
10734                 return 1;
10735
10736         if (!enable_ept)
10737                 vcpu->arch.walk_mmu->inject_page_fault = vmx_inject_page_fault_nested;
10738
10739         /*
10740          * L1 may access the L2's PDPTR, so save them to construct vmcs12
10741          */
10742         if (enable_ept) {
10743                 vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
10744                 vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
10745                 vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
10746                 vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
10747         }
10748
10749         kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->guest_rsp);
10750         kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->guest_rip);
10751         return 0;
10752 }
10753
10754 static int check_vmentry_prereqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
10755 {
10756         struct vcpu_vmx *vmx = to_vmx(vcpu);
10757
10758         if (vmcs12->guest_activity_state != GUEST_ACTIVITY_ACTIVE &&
10759             vmcs12->guest_activity_state != GUEST_ACTIVITY_HLT)
10760                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10761
10762         if (nested_vmx_check_io_bitmap_controls(vcpu, vmcs12))
10763                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10764
10765         if (nested_vmx_check_msr_bitmap_controls(vcpu, vmcs12))
10766                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10767
10768         if (nested_vmx_check_tpr_shadow_controls(vcpu, vmcs12))
10769                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10770
10771         if (nested_vmx_check_apicv_controls(vcpu, vmcs12))
10772                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10773
10774         if (nested_vmx_check_msr_switch_controls(vcpu, vmcs12))
10775                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10776
10777         if (nested_vmx_check_pml_controls(vcpu, vmcs12))
10778                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10779
10780         if (!vmx_control_verify(vmcs12->cpu_based_vm_exec_control,
10781                                 vmx->nested.nested_vmx_procbased_ctls_low,
10782                                 vmx->nested.nested_vmx_procbased_ctls_high) ||
10783             (nested_cpu_has(vmcs12, CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
10784              !vmx_control_verify(vmcs12->secondary_vm_exec_control,
10785                                  vmx->nested.nested_vmx_secondary_ctls_low,
10786                                  vmx->nested.nested_vmx_secondary_ctls_high)) ||
10787             !vmx_control_verify(vmcs12->pin_based_vm_exec_control,
10788                                 vmx->nested.nested_vmx_pinbased_ctls_low,
10789                                 vmx->nested.nested_vmx_pinbased_ctls_high) ||
10790             !vmx_control_verify(vmcs12->vm_exit_controls,
10791                                 vmx->nested.nested_vmx_exit_ctls_low,
10792                                 vmx->nested.nested_vmx_exit_ctls_high) ||
10793             !vmx_control_verify(vmcs12->vm_entry_controls,
10794                                 vmx->nested.nested_vmx_entry_ctls_low,
10795                                 vmx->nested.nested_vmx_entry_ctls_high))
10796                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10797
10798         if (nested_cpu_has_vmfunc(vmcs12)) {
10799                 if (vmcs12->vm_function_control &
10800                     ~vmx->nested.nested_vmx_vmfunc_controls)
10801                         return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10802
10803                 if (nested_cpu_has_eptp_switching(vmcs12)) {
10804                         if (!nested_cpu_has_ept(vmcs12) ||
10805                             !page_address_valid(vcpu, vmcs12->eptp_list_address))
10806                                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10807                 }
10808         }
10809
10810         if (vmcs12->cr3_target_count > nested_cpu_vmx_misc_cr3_count(vcpu))
10811                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10812
10813         if (!nested_host_cr0_valid(vcpu, vmcs12->host_cr0) ||
10814             !nested_host_cr4_valid(vcpu, vmcs12->host_cr4) ||
10815             !nested_cr3_valid(vcpu, vmcs12->host_cr3))
10816                 return VMXERR_ENTRY_INVALID_HOST_STATE_FIELD;
10817
10818         return 0;
10819 }
10820
10821 static int check_vmentry_postreqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
10822                                   u32 *exit_qual)
10823 {
10824         bool ia32e;
10825
10826         *exit_qual = ENTRY_FAIL_DEFAULT;
10827
10828         if (!nested_guest_cr0_valid(vcpu, vmcs12->guest_cr0) ||
10829             !nested_guest_cr4_valid(vcpu, vmcs12->guest_cr4))
10830                 return 1;
10831
10832         if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_SHADOW_VMCS) &&
10833             vmcs12->vmcs_link_pointer != -1ull) {
10834                 *exit_qual = ENTRY_FAIL_VMCS_LINK_PTR;
10835                 return 1;
10836         }
10837
10838         /*
10839          * If the load IA32_EFER VM-entry control is 1, the following checks
10840          * are performed on the field for the IA32_EFER MSR:
10841          * - Bits reserved in the IA32_EFER MSR must be 0.
10842          * - Bit 10 (corresponding to IA32_EFER.LMA) must equal the value of
10843          *   the IA-32e mode guest VM-exit control. It must also be identical
10844          *   to bit 8 (LME) if bit 31 in the CR0 field (corresponding to
10845          *   CR0.PG) is 1.
10846          */
10847         if (to_vmx(vcpu)->nested.nested_run_pending &&
10848             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)) {
10849                 ia32e = (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) != 0;
10850                 if (!kvm_valid_efer(vcpu, vmcs12->guest_ia32_efer) ||
10851                     ia32e != !!(vmcs12->guest_ia32_efer & EFER_LMA) ||
10852                     ((vmcs12->guest_cr0 & X86_CR0_PG) &&
10853                      ia32e != !!(vmcs12->guest_ia32_efer & EFER_LME)))
10854                         return 1;
10855         }
10856
10857         /*
10858          * If the load IA32_EFER VM-exit control is 1, bits reserved in the
10859          * IA32_EFER MSR must be 0 in the field for that register. In addition,
10860          * the values of the LMA and LME bits in the field must each be that of
10861          * the host address-space size VM-exit control.
10862          */
10863         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) {
10864                 ia32e = (vmcs12->vm_exit_controls &
10865                          VM_EXIT_HOST_ADDR_SPACE_SIZE) != 0;
10866                 if (!kvm_valid_efer(vcpu, vmcs12->host_ia32_efer) ||
10867                     ia32e != !!(vmcs12->host_ia32_efer & EFER_LMA) ||
10868                     ia32e != !!(vmcs12->host_ia32_efer & EFER_LME))
10869                         return 1;
10870         }
10871
10872         return 0;
10873 }
10874
10875 static int enter_vmx_non_root_mode(struct kvm_vcpu *vcpu, bool from_vmentry)
10876 {
10877         struct vcpu_vmx *vmx = to_vmx(vcpu);
10878         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
10879         struct loaded_vmcs *vmcs02;
10880         u32 msr_entry_idx;
10881         u32 exit_qual;
10882
10883         vmcs02 = nested_get_current_vmcs02(vmx);
10884         if (!vmcs02)
10885                 return -ENOMEM;
10886
10887         enter_guest_mode(vcpu);
10888
10889         if (!(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS))
10890                 vmx->nested.vmcs01_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
10891
10892         vmx_switch_vmcs(vcpu, vmcs02);
10893         vmx_segment_cache_clear(vmx);
10894
10895         if (prepare_vmcs02(vcpu, vmcs12, from_vmentry, &exit_qual)) {
10896                 leave_guest_mode(vcpu);
10897                 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
10898                 nested_vmx_entry_failure(vcpu, vmcs12,
10899                                          EXIT_REASON_INVALID_STATE, exit_qual);
10900                 return 1;
10901         }
10902
10903         nested_get_vmcs12_pages(vcpu, vmcs12);
10904
10905         msr_entry_idx = nested_vmx_load_msr(vcpu,
10906                                             vmcs12->vm_entry_msr_load_addr,
10907                                             vmcs12->vm_entry_msr_load_count);
10908         if (msr_entry_idx) {
10909                 leave_guest_mode(vcpu);
10910                 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
10911                 nested_vmx_entry_failure(vcpu, vmcs12,
10912                                 EXIT_REASON_MSR_LOAD_FAIL, msr_entry_idx);
10913                 return 1;
10914         }
10915
10916         /*
10917          * Note no nested_vmx_succeed or nested_vmx_fail here. At this point
10918          * we are no longer running L1, and VMLAUNCH/VMRESUME has not yet
10919          * returned as far as L1 is concerned. It will only return (and set
10920          * the success flag) when L2 exits (see nested_vmx_vmexit()).
10921          */
10922         return 0;
10923 }
10924
10925 /*
10926  * nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1
10927  * for running an L2 nested guest.
10928  */
10929 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
10930 {
10931         struct vmcs12 *vmcs12;
10932         struct vcpu_vmx *vmx = to_vmx(vcpu);
10933         u32 interrupt_shadow = vmx_get_interrupt_shadow(vcpu);
10934         u32 exit_qual;
10935         int ret;
10936
10937         if (!nested_vmx_check_permission(vcpu))
10938                 return 1;
10939
10940         if (!nested_vmx_check_vmcs12(vcpu))
10941                 goto out;
10942
10943         vmcs12 = get_vmcs12(vcpu);
10944
10945         if (enable_shadow_vmcs)
10946                 copy_shadow_to_vmcs12(vmx);
10947
10948         /*
10949          * The nested entry process starts with enforcing various prerequisites
10950          * on vmcs12 as required by the Intel SDM, and act appropriately when
10951          * they fail: As the SDM explains, some conditions should cause the
10952          * instruction to fail, while others will cause the instruction to seem
10953          * to succeed, but return an EXIT_REASON_INVALID_STATE.
10954          * To speed up the normal (success) code path, we should avoid checking
10955          * for misconfigurations which will anyway be caught by the processor
10956          * when using the merged vmcs02.
10957          */
10958         if (interrupt_shadow & KVM_X86_SHADOW_INT_MOV_SS) {
10959                 nested_vmx_failValid(vcpu,
10960                                      VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS);
10961                 goto out;
10962         }
10963
10964         if (vmcs12->launch_state == launch) {
10965                 nested_vmx_failValid(vcpu,
10966                         launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
10967                                : VMXERR_VMRESUME_NONLAUNCHED_VMCS);
10968                 goto out;
10969         }
10970
10971         ret = check_vmentry_prereqs(vcpu, vmcs12);
10972         if (ret) {
10973                 nested_vmx_failValid(vcpu, ret);
10974                 goto out;
10975         }
10976
10977         /*
10978          * After this point, the trap flag no longer triggers a singlestep trap
10979          * on the vm entry instructions; don't call kvm_skip_emulated_instruction.
10980          * This is not 100% correct; for performance reasons, we delegate most
10981          * of the checks on host state to the processor.  If those fail,
10982          * the singlestep trap is missed.
10983          */
10984         skip_emulated_instruction(vcpu);
10985
10986         ret = check_vmentry_postreqs(vcpu, vmcs12, &exit_qual);
10987         if (ret) {
10988                 nested_vmx_entry_failure(vcpu, vmcs12,
10989                                          EXIT_REASON_INVALID_STATE, exit_qual);
10990                 return 1;
10991         }
10992
10993         /*
10994          * We're finally done with prerequisite checking, and can start with
10995          * the nested entry.
10996          */
10997
10998         ret = enter_vmx_non_root_mode(vcpu, true);
10999         if (ret)
11000                 return ret;
11001
11002         if (vmcs12->guest_activity_state == GUEST_ACTIVITY_HLT)
11003                 return kvm_vcpu_halt(vcpu);
11004
11005         vmx->nested.nested_run_pending = 1;
11006
11007         return 1;
11008
11009 out:
11010         return kvm_skip_emulated_instruction(vcpu);
11011 }
11012
11013 /*
11014  * On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
11015  * because L2 may have changed some cr0 bits directly (CRO_GUEST_HOST_MASK).
11016  * This function returns the new value we should put in vmcs12.guest_cr0.
11017  * It's not enough to just return the vmcs02 GUEST_CR0. Rather,
11018  *  1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
11019  *     available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0
11020  *     didn't trap the bit, because if L1 did, so would L0).
11021  *  2. Bits that L1 asked to trap (and therefore L0 also did) could not have
11022  *     been modified by L2, and L1 knows it. So just leave the old value of
11023  *     the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0
11024  *     isn't relevant, because if L0 traps this bit it can set it to anything.
11025  *  3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have
11026  *     changed these bits, and therefore they need to be updated, but L0
11027  *     didn't necessarily allow them to be changed in GUEST_CR0 - and rather
11028  *     put them in vmcs02 CR0_READ_SHADOW. So take these bits from there.
11029  */
11030 static inline unsigned long
11031 vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
11032 {
11033         return
11034         /*1*/   (vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) |
11035         /*2*/   (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) |
11036         /*3*/   (vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask |
11037                         vcpu->arch.cr0_guest_owned_bits));
11038 }
11039
11040 static inline unsigned long
11041 vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
11042 {
11043         return
11044         /*1*/   (vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) |
11045         /*2*/   (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) |
11046         /*3*/   (vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask |
11047                         vcpu->arch.cr4_guest_owned_bits));
11048 }
11049
11050 static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
11051                                        struct vmcs12 *vmcs12)
11052 {
11053         u32 idt_vectoring;
11054         unsigned int nr;
11055
11056         if (vcpu->arch.exception.injected) {
11057                 nr = vcpu->arch.exception.nr;
11058                 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
11059
11060                 if (kvm_exception_is_soft(nr)) {
11061                         vmcs12->vm_exit_instruction_len =
11062                                 vcpu->arch.event_exit_inst_len;
11063                         idt_vectoring |= INTR_TYPE_SOFT_EXCEPTION;
11064                 } else
11065                         idt_vectoring |= INTR_TYPE_HARD_EXCEPTION;
11066
11067                 if (vcpu->arch.exception.has_error_code) {
11068                         idt_vectoring |= VECTORING_INFO_DELIVER_CODE_MASK;
11069                         vmcs12->idt_vectoring_error_code =
11070                                 vcpu->arch.exception.error_code;
11071                 }
11072
11073                 vmcs12->idt_vectoring_info_field = idt_vectoring;
11074         } else if (vcpu->arch.nmi_injected) {
11075                 vmcs12->idt_vectoring_info_field =
11076                         INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR;
11077         } else if (vcpu->arch.interrupt.pending) {
11078                 nr = vcpu->arch.interrupt.nr;
11079                 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
11080
11081                 if (vcpu->arch.interrupt.soft) {
11082                         idt_vectoring |= INTR_TYPE_SOFT_INTR;
11083                         vmcs12->vm_entry_instruction_len =
11084                                 vcpu->arch.event_exit_inst_len;
11085                 } else
11086                         idt_vectoring |= INTR_TYPE_EXT_INTR;
11087
11088                 vmcs12->idt_vectoring_info_field = idt_vectoring;
11089         }
11090 }
11091
11092 static int vmx_check_nested_events(struct kvm_vcpu *vcpu, bool external_intr)
11093 {
11094         struct vcpu_vmx *vmx = to_vmx(vcpu);
11095         unsigned long exit_qual;
11096
11097         if (kvm_event_needs_reinjection(vcpu))
11098                 return -EBUSY;
11099
11100         if (vcpu->arch.exception.pending &&
11101                 nested_vmx_check_exception(vcpu, &exit_qual)) {
11102                 if (vmx->nested.nested_run_pending)
11103                         return -EBUSY;
11104                 nested_vmx_inject_exception_vmexit(vcpu, exit_qual);
11105                 vcpu->arch.exception.pending = false;
11106                 return 0;
11107         }
11108
11109         if (nested_cpu_has_preemption_timer(get_vmcs12(vcpu)) &&
11110             vmx->nested.preemption_timer_expired) {
11111                 if (vmx->nested.nested_run_pending)
11112                         return -EBUSY;
11113                 nested_vmx_vmexit(vcpu, EXIT_REASON_PREEMPTION_TIMER, 0, 0);
11114                 return 0;
11115         }
11116
11117         if (vcpu->arch.nmi_pending && nested_exit_on_nmi(vcpu)) {
11118                 if (vmx->nested.nested_run_pending)
11119                         return -EBUSY;
11120                 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
11121                                   NMI_VECTOR | INTR_TYPE_NMI_INTR |
11122                                   INTR_INFO_VALID_MASK, 0);
11123                 /*
11124                  * The NMI-triggered VM exit counts as injection:
11125                  * clear this one and block further NMIs.
11126                  */
11127                 vcpu->arch.nmi_pending = 0;
11128                 vmx_set_nmi_mask(vcpu, true);
11129                 return 0;
11130         }
11131
11132         if ((kvm_cpu_has_interrupt(vcpu) || external_intr) &&
11133             nested_exit_on_intr(vcpu)) {
11134                 if (vmx->nested.nested_run_pending)
11135                         return -EBUSY;
11136                 nested_vmx_vmexit(vcpu, EXIT_REASON_EXTERNAL_INTERRUPT, 0, 0);
11137                 return 0;
11138         }
11139
11140         vmx_complete_nested_posted_interrupt(vcpu);
11141         return 0;
11142 }
11143
11144 static u32 vmx_get_preemption_timer_value(struct kvm_vcpu *vcpu)
11145 {
11146         ktime_t remaining =
11147                 hrtimer_get_remaining(&to_vmx(vcpu)->nested.preemption_timer);
11148         u64 value;
11149
11150         if (ktime_to_ns(remaining) <= 0)
11151                 return 0;
11152
11153         value = ktime_to_ns(remaining) * vcpu->arch.virtual_tsc_khz;
11154         do_div(value, 1000000);
11155         return value >> VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
11156 }
11157
11158 /*
11159  * Update the guest state fields of vmcs12 to reflect changes that
11160  * occurred while L2 was running. (The "IA-32e mode guest" bit of the
11161  * VM-entry controls is also updated, since this is really a guest
11162  * state bit.)
11163  */
11164 static void sync_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
11165 {
11166         vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12);
11167         vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12);
11168
11169         vmcs12->guest_rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
11170         vmcs12->guest_rip = kvm_register_read(vcpu, VCPU_REGS_RIP);
11171         vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS);
11172
11173         vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR);
11174         vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR);
11175         vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR);
11176         vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR);
11177         vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR);
11178         vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR);
11179         vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR);
11180         vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR);
11181         vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT);
11182         vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT);
11183         vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT);
11184         vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT);
11185         vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT);
11186         vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT);
11187         vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT);
11188         vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT);
11189         vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT);
11190         vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT);
11191         vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES);
11192         vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES);
11193         vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES);
11194         vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES);
11195         vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES);
11196         vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES);
11197         vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES);
11198         vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES);
11199         vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE);
11200         vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE);
11201         vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE);
11202         vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE);
11203         vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE);
11204         vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE);
11205         vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE);
11206         vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE);
11207         vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE);
11208         vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE);
11209
11210         vmcs12->guest_interruptibility_info =
11211                 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
11212         vmcs12->guest_pending_dbg_exceptions =
11213                 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);
11214         if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
11215                 vmcs12->guest_activity_state = GUEST_ACTIVITY_HLT;
11216         else
11217                 vmcs12->guest_activity_state = GUEST_ACTIVITY_ACTIVE;
11218
11219         if (nested_cpu_has_preemption_timer(vmcs12)) {
11220                 if (vmcs12->vm_exit_controls &
11221                     VM_EXIT_SAVE_VMX_PREEMPTION_TIMER)
11222                         vmcs12->vmx_preemption_timer_value =
11223                                 vmx_get_preemption_timer_value(vcpu);
11224                 hrtimer_cancel(&to_vmx(vcpu)->nested.preemption_timer);
11225         }
11226
11227         /*
11228          * In some cases (usually, nested EPT), L2 is allowed to change its
11229          * own CR3 without exiting. If it has changed it, we must keep it.
11230          * Of course, if L0 is using shadow page tables, GUEST_CR3 was defined
11231          * by L0, not L1 or L2, so we mustn't unconditionally copy it to vmcs12.
11232          *
11233          * Additionally, restore L2's PDPTR to vmcs12.
11234          */
11235         if (enable_ept) {
11236                 vmcs12->guest_cr3 = vmcs_readl(GUEST_CR3);
11237                 vmcs12->guest_pdptr0 = vmcs_read64(GUEST_PDPTR0);
11238                 vmcs12->guest_pdptr1 = vmcs_read64(GUEST_PDPTR1);
11239                 vmcs12->guest_pdptr2 = vmcs_read64(GUEST_PDPTR2);
11240                 vmcs12->guest_pdptr3 = vmcs_read64(GUEST_PDPTR3);
11241         }
11242
11243         vmcs12->guest_linear_address = vmcs_readl(GUEST_LINEAR_ADDRESS);
11244
11245         if (nested_cpu_has_vid(vmcs12))
11246                 vmcs12->guest_intr_status = vmcs_read16(GUEST_INTR_STATUS);
11247
11248         vmcs12->vm_entry_controls =
11249                 (vmcs12->vm_entry_controls & ~VM_ENTRY_IA32E_MODE) |
11250                 (vm_entry_controls_get(to_vmx(vcpu)) & VM_ENTRY_IA32E_MODE);
11251
11252         if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_DEBUG_CONTROLS) {
11253                 kvm_get_dr(vcpu, 7, (unsigned long *)&vmcs12->guest_dr7);
11254                 vmcs12->guest_ia32_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
11255         }
11256
11257         /* TODO: These cannot have changed unless we have MSR bitmaps and
11258          * the relevant bit asks not to trap the change */
11259         if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
11260                 vmcs12->guest_ia32_pat = vmcs_read64(GUEST_IA32_PAT);
11261         if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_EFER)
11262                 vmcs12->guest_ia32_efer = vcpu->arch.efer;
11263         vmcs12->guest_sysenter_cs = vmcs_read32(GUEST_SYSENTER_CS);
11264         vmcs12->guest_sysenter_esp = vmcs_readl(GUEST_SYSENTER_ESP);
11265         vmcs12->guest_sysenter_eip = vmcs_readl(GUEST_SYSENTER_EIP);
11266         if (kvm_mpx_supported())
11267                 vmcs12->guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
11268 }
11269
11270 /*
11271  * prepare_vmcs12 is part of what we need to do when the nested L2 guest exits
11272  * and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12),
11273  * and this function updates it to reflect the changes to the guest state while
11274  * L2 was running (and perhaps made some exits which were handled directly by L0
11275  * without going back to L1), and to reflect the exit reason.
11276  * Note that we do not have to copy here all VMCS fields, just those that
11277  * could have changed by the L2 guest or the exit - i.e., the guest-state and
11278  * exit-information fields only. Other fields are modified by L1 with VMWRITE,
11279  * which already writes to vmcs12 directly.
11280  */
11281 static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
11282                            u32 exit_reason, u32 exit_intr_info,
11283                            unsigned long exit_qualification)
11284 {
11285         /* update guest state fields: */
11286         sync_vmcs12(vcpu, vmcs12);
11287
11288         /* update exit information fields: */
11289
11290         vmcs12->vm_exit_reason = exit_reason;
11291         vmcs12->exit_qualification = exit_qualification;
11292         vmcs12->vm_exit_intr_info = exit_intr_info;
11293
11294         vmcs12->idt_vectoring_info_field = 0;
11295         vmcs12->vm_exit_instruction_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
11296         vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
11297
11298         if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY)) {
11299                 vmcs12->launch_state = 1;
11300
11301                 /* vm_entry_intr_info_field is cleared on exit. Emulate this
11302                  * instead of reading the real value. */
11303                 vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK;
11304
11305                 /*
11306                  * Transfer the event that L0 or L1 may wanted to inject into
11307                  * L2 to IDT_VECTORING_INFO_FIELD.
11308                  */
11309                 vmcs12_save_pending_event(vcpu, vmcs12);
11310         }
11311
11312         /*
11313          * Drop what we picked up for L2 via vmx_complete_interrupts. It is
11314          * preserved above and would only end up incorrectly in L1.
11315          */
11316         vcpu->arch.nmi_injected = false;
11317         kvm_clear_exception_queue(vcpu);
11318         kvm_clear_interrupt_queue(vcpu);
11319 }
11320
11321 /*
11322  * A part of what we need to when the nested L2 guest exits and we want to
11323  * run its L1 parent, is to reset L1's guest state to the host state specified
11324  * in vmcs12.
11325  * This function is to be called not only on normal nested exit, but also on
11326  * a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry
11327  * Failures During or After Loading Guest State").
11328  * This function should be called when the active VMCS is L1's (vmcs01).
11329  */
11330 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
11331                                    struct vmcs12 *vmcs12)
11332 {
11333         struct kvm_segment seg;
11334         u32 entry_failure_code;
11335
11336         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
11337                 vcpu->arch.efer = vmcs12->host_ia32_efer;
11338         else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
11339                 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
11340         else
11341                 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
11342         vmx_set_efer(vcpu, vcpu->arch.efer);
11343
11344         kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp);
11345         kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip);
11346         vmx_set_rflags(vcpu, X86_EFLAGS_FIXED);
11347         /*
11348          * Note that calling vmx_set_cr0 is important, even if cr0 hasn't
11349          * actually changed, because vmx_set_cr0 refers to efer set above.
11350          *
11351          * CR0_GUEST_HOST_MASK is already set in the original vmcs01
11352          * (KVM doesn't change it);
11353          */
11354         vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
11355         vmx_set_cr0(vcpu, vmcs12->host_cr0);
11356
11357         /* Same as above - no reason to call set_cr4_guest_host_mask().  */
11358         vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
11359         vmx_set_cr4(vcpu, vmcs12->host_cr4);
11360
11361         nested_ept_uninit_mmu_context(vcpu);
11362
11363         /*
11364          * Only PDPTE load can fail as the value of cr3 was checked on entry and
11365          * couldn't have changed.
11366          */
11367         if (nested_vmx_load_cr3(vcpu, vmcs12->host_cr3, false, &entry_failure_code))
11368                 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_PDPTE_FAIL);
11369
11370         if (!enable_ept)
11371                 vcpu->arch.walk_mmu->inject_page_fault = kvm_inject_page_fault;
11372
11373         if (enable_vpid) {
11374                 /*
11375                  * Trivially support vpid by letting L2s share their parent
11376                  * L1's vpid. TODO: move to a more elaborate solution, giving
11377                  * each L2 its own vpid and exposing the vpid feature to L1.
11378                  */
11379                 vmx_flush_tlb(vcpu);
11380         }
11381         /* Restore posted intr vector. */
11382         if (nested_cpu_has_posted_intr(vmcs12))
11383                 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
11384
11385         vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
11386         vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp);
11387         vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip);
11388         vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base);
11389         vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base);
11390         vmcs_write32(GUEST_IDTR_LIMIT, 0xFFFF);
11391         vmcs_write32(GUEST_GDTR_LIMIT, 0xFFFF);
11392
11393         /* If not VM_EXIT_CLEAR_BNDCFGS, the L2 value propagates to L1.  */
11394         if (vmcs12->vm_exit_controls & VM_EXIT_CLEAR_BNDCFGS)
11395                 vmcs_write64(GUEST_BNDCFGS, 0);
11396
11397         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) {
11398                 vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat);
11399                 vcpu->arch.pat = vmcs12->host_ia32_pat;
11400         }
11401         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
11402                 vmcs_write64(GUEST_IA32_PERF_GLOBAL_CTRL,
11403                         vmcs12->host_ia32_perf_global_ctrl);
11404
11405         /* Set L1 segment info according to Intel SDM
11406             27.5.2 Loading Host Segment and Descriptor-Table Registers */
11407         seg = (struct kvm_segment) {
11408                 .base = 0,
11409                 .limit = 0xFFFFFFFF,
11410                 .selector = vmcs12->host_cs_selector,
11411                 .type = 11,
11412                 .present = 1,
11413                 .s = 1,
11414                 .g = 1
11415         };
11416         if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
11417                 seg.l = 1;
11418         else
11419                 seg.db = 1;
11420         vmx_set_segment(vcpu, &seg, VCPU_SREG_CS);
11421         seg = (struct kvm_segment) {
11422                 .base = 0,
11423                 .limit = 0xFFFFFFFF,
11424                 .type = 3,
11425                 .present = 1,
11426                 .s = 1,
11427                 .db = 1,
11428                 .g = 1
11429         };
11430         seg.selector = vmcs12->host_ds_selector;
11431         vmx_set_segment(vcpu, &seg, VCPU_SREG_DS);
11432         seg.selector = vmcs12->host_es_selector;
11433         vmx_set_segment(vcpu, &seg, VCPU_SREG_ES);
11434         seg.selector = vmcs12->host_ss_selector;
11435         vmx_set_segment(vcpu, &seg, VCPU_SREG_SS);
11436         seg.selector = vmcs12->host_fs_selector;
11437         seg.base = vmcs12->host_fs_base;
11438         vmx_set_segment(vcpu, &seg, VCPU_SREG_FS);
11439         seg.selector = vmcs12->host_gs_selector;
11440         seg.base = vmcs12->host_gs_base;
11441         vmx_set_segment(vcpu, &seg, VCPU_SREG_GS);
11442         seg = (struct kvm_segment) {
11443                 .base = vmcs12->host_tr_base,
11444                 .limit = 0x67,
11445                 .selector = vmcs12->host_tr_selector,
11446                 .type = 11,
11447                 .present = 1
11448         };
11449         vmx_set_segment(vcpu, &seg, VCPU_SREG_TR);
11450
11451         kvm_set_dr(vcpu, 7, 0x400);
11452         vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
11453
11454         if (cpu_has_vmx_msr_bitmap())
11455                 vmx_set_msr_bitmap(vcpu);
11456
11457         if (nested_vmx_load_msr(vcpu, vmcs12->vm_exit_msr_load_addr,
11458                                 vmcs12->vm_exit_msr_load_count))
11459                 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
11460 }
11461
11462 /*
11463  * Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
11464  * and modify vmcs12 to make it see what it would expect to see there if
11465  * L2 was its real guest. Must only be called when in L2 (is_guest_mode())
11466  */
11467 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
11468                               u32 exit_intr_info,
11469                               unsigned long exit_qualification)
11470 {
11471         struct vcpu_vmx *vmx = to_vmx(vcpu);
11472         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11473
11474         /* trying to cancel vmlaunch/vmresume is a bug */
11475         WARN_ON_ONCE(vmx->nested.nested_run_pending);
11476
11477         /*
11478          * The only expected VM-instruction error is "VM entry with
11479          * invalid control field(s)." Anything else indicates a
11480          * problem with L0.
11481          */
11482         WARN_ON_ONCE(vmx->fail && (vmcs_read32(VM_INSTRUCTION_ERROR) !=
11483                                    VMXERR_ENTRY_INVALID_CONTROL_FIELD));
11484
11485         leave_guest_mode(vcpu);
11486
11487         if (likely(!vmx->fail)) {
11488                 prepare_vmcs12(vcpu, vmcs12, exit_reason, exit_intr_info,
11489                                exit_qualification);
11490
11491                 if (nested_vmx_store_msr(vcpu, vmcs12->vm_exit_msr_store_addr,
11492                                          vmcs12->vm_exit_msr_store_count))
11493                         nested_vmx_abort(vcpu, VMX_ABORT_SAVE_GUEST_MSR_FAIL);
11494         }
11495
11496         vmx_switch_vmcs(vcpu, &vmx->vmcs01);
11497         vm_entry_controls_reset_shadow(vmx);
11498         vm_exit_controls_reset_shadow(vmx);
11499         vmx_segment_cache_clear(vmx);
11500
11501         /* if no vmcs02 cache requested, remove the one we used */
11502         if (VMCS02_POOL_SIZE == 0)
11503                 nested_free_vmcs02(vmx, vmx->nested.current_vmptr);
11504
11505         /* Update any VMCS fields that might have changed while L2 ran */
11506         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
11507         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
11508         vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
11509         if (vmx->hv_deadline_tsc == -1)
11510                 vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
11511                                 PIN_BASED_VMX_PREEMPTION_TIMER);
11512         else
11513                 vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
11514                               PIN_BASED_VMX_PREEMPTION_TIMER);
11515         if (kvm_has_tsc_control)
11516                 decache_tsc_multiplier(vmx);
11517
11518         if (vmx->nested.change_vmcs01_virtual_x2apic_mode) {
11519                 vmx->nested.change_vmcs01_virtual_x2apic_mode = false;
11520                 vmx_set_virtual_x2apic_mode(vcpu,
11521                                 vcpu->arch.apic_base & X2APIC_ENABLE);
11522         } else if (!nested_cpu_has_ept(vmcs12) &&
11523                    nested_cpu_has2(vmcs12,
11524                                    SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
11525                 vmx_flush_tlb_ept_only(vcpu);
11526         }
11527
11528         /* This is needed for same reason as it was needed in prepare_vmcs02 */
11529         vmx->host_rsp = 0;
11530
11531         /* Unpin physical memory we referred to in vmcs02 */
11532         if (vmx->nested.apic_access_page) {
11533                 kvm_release_page_dirty(vmx->nested.apic_access_page);
11534                 vmx->nested.apic_access_page = NULL;
11535         }
11536         if (vmx->nested.virtual_apic_page) {
11537                 kvm_release_page_dirty(vmx->nested.virtual_apic_page);
11538                 vmx->nested.virtual_apic_page = NULL;
11539         }
11540         if (vmx->nested.pi_desc_page) {
11541                 kunmap(vmx->nested.pi_desc_page);
11542                 kvm_release_page_dirty(vmx->nested.pi_desc_page);
11543                 vmx->nested.pi_desc_page = NULL;
11544                 vmx->nested.pi_desc = NULL;
11545         }
11546
11547         /*
11548          * We are now running in L2, mmu_notifier will force to reload the
11549          * page's hpa for L2 vmcs. Need to reload it for L1 before entering L1.
11550          */
11551         kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
11552
11553         if (enable_shadow_vmcs)
11554                 vmx->nested.sync_shadow_vmcs = true;
11555
11556         /* in case we halted in L2 */
11557         vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
11558
11559         if (likely(!vmx->fail)) {
11560                 /*
11561                  * TODO: SDM says that with acknowledge interrupt on
11562                  * exit, bit 31 of the VM-exit interrupt information
11563                  * (valid interrupt) is always set to 1 on
11564                  * EXIT_REASON_EXTERNAL_INTERRUPT, so we shouldn't
11565                  * need kvm_cpu_has_interrupt().  See the commit
11566                  * message for details.
11567                  */
11568                 if (nested_exit_intr_ack_set(vcpu) &&
11569                     exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT &&
11570                     kvm_cpu_has_interrupt(vcpu)) {
11571                         int irq = kvm_cpu_get_interrupt(vcpu);
11572                         WARN_ON(irq < 0);
11573                         vmcs12->vm_exit_intr_info = irq |
11574                                 INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR;
11575                 }
11576
11577                 trace_kvm_nested_vmexit_inject(vmcs12->vm_exit_reason,
11578                                                vmcs12->exit_qualification,
11579                                                vmcs12->idt_vectoring_info_field,
11580                                                vmcs12->vm_exit_intr_info,
11581                                                vmcs12->vm_exit_intr_error_code,
11582                                                KVM_ISA_VMX);
11583
11584                 load_vmcs12_host_state(vcpu, vmcs12);
11585
11586                 return;
11587         }
11588         
11589         /*
11590          * After an early L2 VM-entry failure, we're now back
11591          * in L1 which thinks it just finished a VMLAUNCH or
11592          * VMRESUME instruction, so we need to set the failure
11593          * flag and the VM-instruction error field of the VMCS
11594          * accordingly.
11595          */
11596         nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
11597         /*
11598          * The emulated instruction was already skipped in
11599          * nested_vmx_run, but the updated RIP was never
11600          * written back to the vmcs01.
11601          */
11602         skip_emulated_instruction(vcpu);
11603         vmx->fail = 0;
11604 }
11605
11606 /*
11607  * Forcibly leave nested mode in order to be able to reset the VCPU later on.
11608  */
11609 static void vmx_leave_nested(struct kvm_vcpu *vcpu)
11610 {
11611         if (is_guest_mode(vcpu)) {
11612                 to_vmx(vcpu)->nested.nested_run_pending = 0;
11613                 nested_vmx_vmexit(vcpu, -1, 0, 0);
11614         }
11615         free_nested(to_vmx(vcpu));
11616 }
11617
11618 /*
11619  * L1's failure to enter L2 is a subset of a normal exit, as explained in
11620  * 23.7 "VM-entry failures during or after loading guest state" (this also
11621  * lists the acceptable exit-reason and exit-qualification parameters).
11622  * It should only be called before L2 actually succeeded to run, and when
11623  * vmcs01 is current (it doesn't leave_guest_mode() or switch vmcss).
11624  */
11625 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
11626                         struct vmcs12 *vmcs12,
11627                         u32 reason, unsigned long qualification)
11628 {
11629         load_vmcs12_host_state(vcpu, vmcs12);
11630         vmcs12->vm_exit_reason = reason | VMX_EXIT_REASONS_FAILED_VMENTRY;
11631         vmcs12->exit_qualification = qualification;
11632         nested_vmx_succeed(vcpu);
11633         if (enable_shadow_vmcs)
11634                 to_vmx(vcpu)->nested.sync_shadow_vmcs = true;
11635 }
11636
11637 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
11638                                struct x86_instruction_info *info,
11639                                enum x86_intercept_stage stage)
11640 {
11641         return X86EMUL_CONTINUE;
11642 }
11643
11644 #ifdef CONFIG_X86_64
11645 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
11646 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
11647                                   u64 divisor, u64 *result)
11648 {
11649         u64 low = a << shift, high = a >> (64 - shift);
11650
11651         /* To avoid the overflow on divq */
11652         if (high >= divisor)
11653                 return 1;
11654
11655         /* Low hold the result, high hold rem which is discarded */
11656         asm("divq %2\n\t" : "=a" (low), "=d" (high) :
11657             "rm" (divisor), "0" (low), "1" (high));
11658         *result = low;
11659
11660         return 0;
11661 }
11662
11663 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc)
11664 {
11665         struct vcpu_vmx *vmx = to_vmx(vcpu);
11666         u64 tscl = rdtsc();
11667         u64 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
11668         u64 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
11669
11670         /* Convert to host delta tsc if tsc scaling is enabled */
11671         if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
11672                         u64_shl_div_u64(delta_tsc,
11673                                 kvm_tsc_scaling_ratio_frac_bits,
11674                                 vcpu->arch.tsc_scaling_ratio,
11675                                 &delta_tsc))
11676                 return -ERANGE;
11677
11678         /*
11679          * If the delta tsc can't fit in the 32 bit after the multi shift,
11680          * we can't use the preemption timer.
11681          * It's possible that it fits on later vmentries, but checking
11682          * on every vmentry is costly so we just use an hrtimer.
11683          */
11684         if (delta_tsc >> (cpu_preemption_timer_multi + 32))
11685                 return -ERANGE;
11686
11687         vmx->hv_deadline_tsc = tscl + delta_tsc;
11688         vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
11689                         PIN_BASED_VMX_PREEMPTION_TIMER);
11690
11691         return delta_tsc == 0;
11692 }
11693
11694 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
11695 {
11696         struct vcpu_vmx *vmx = to_vmx(vcpu);
11697         vmx->hv_deadline_tsc = -1;
11698         vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
11699                         PIN_BASED_VMX_PREEMPTION_TIMER);
11700 }
11701 #endif
11702
11703 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
11704 {
11705         if (ple_gap)
11706                 shrink_ple_window(vcpu);
11707 }
11708
11709 static void vmx_slot_enable_log_dirty(struct kvm *kvm,
11710                                      struct kvm_memory_slot *slot)
11711 {
11712         kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
11713         kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
11714 }
11715
11716 static void vmx_slot_disable_log_dirty(struct kvm *kvm,
11717                                        struct kvm_memory_slot *slot)
11718 {
11719         kvm_mmu_slot_set_dirty(kvm, slot);
11720 }
11721
11722 static void vmx_flush_log_dirty(struct kvm *kvm)
11723 {
11724         kvm_flush_pml_buffers(kvm);
11725 }
11726
11727 static int vmx_write_pml_buffer(struct kvm_vcpu *vcpu)
11728 {
11729         struct vmcs12 *vmcs12;
11730         struct vcpu_vmx *vmx = to_vmx(vcpu);
11731         gpa_t gpa;
11732         struct page *page = NULL;
11733         u64 *pml_address;
11734
11735         if (is_guest_mode(vcpu)) {
11736                 WARN_ON_ONCE(vmx->nested.pml_full);
11737
11738                 /*
11739                  * Check if PML is enabled for the nested guest.
11740                  * Whether eptp bit 6 is set is already checked
11741                  * as part of A/D emulation.
11742                  */
11743                 vmcs12 = get_vmcs12(vcpu);
11744                 if (!nested_cpu_has_pml(vmcs12))
11745                         return 0;
11746
11747                 if (vmcs12->guest_pml_index >= PML_ENTITY_NUM) {
11748                         vmx->nested.pml_full = true;
11749                         return 1;
11750                 }
11751
11752                 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS) & ~0xFFFull;
11753
11754                 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->pml_address);
11755                 if (is_error_page(page))
11756                         return 0;
11757
11758                 pml_address = kmap(page);
11759                 pml_address[vmcs12->guest_pml_index--] = gpa;
11760                 kunmap(page);
11761                 kvm_release_page_clean(page);
11762         }
11763
11764         return 0;
11765 }
11766
11767 static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
11768                                            struct kvm_memory_slot *memslot,
11769                                            gfn_t offset, unsigned long mask)
11770 {
11771         kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
11772 }
11773
11774 static void __pi_post_block(struct kvm_vcpu *vcpu)
11775 {
11776         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
11777         struct pi_desc old, new;
11778         unsigned int dest;
11779
11780         do {
11781                 old.control = new.control = pi_desc->control;
11782                 WARN(old.nv != POSTED_INTR_WAKEUP_VECTOR,
11783                      "Wakeup handler not enabled while the VCPU is blocked\n");
11784
11785                 dest = cpu_physical_id(vcpu->cpu);
11786
11787                 if (x2apic_enabled())
11788                         new.ndst = dest;
11789                 else
11790                         new.ndst = (dest << 8) & 0xFF00;
11791
11792                 /* set 'NV' to 'notification vector' */
11793                 new.nv = POSTED_INTR_VECTOR;
11794         } while (cmpxchg64(&pi_desc->control, old.control,
11795                            new.control) != old.control);
11796
11797         if (!WARN_ON_ONCE(vcpu->pre_pcpu == -1)) {
11798                 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
11799                 list_del(&vcpu->blocked_vcpu_list);
11800                 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
11801                 vcpu->pre_pcpu = -1;
11802         }
11803 }
11804
11805 /*
11806  * This routine does the following things for vCPU which is going
11807  * to be blocked if VT-d PI is enabled.
11808  * - Store the vCPU to the wakeup list, so when interrupts happen
11809  *   we can find the right vCPU to wake up.
11810  * - Change the Posted-interrupt descriptor as below:
11811  *      'NDST' <-- vcpu->pre_pcpu
11812  *      'NV' <-- POSTED_INTR_WAKEUP_VECTOR
11813  * - If 'ON' is set during this process, which means at least one
11814  *   interrupt is posted for this vCPU, we cannot block it, in
11815  *   this case, return 1, otherwise, return 0.
11816  *
11817  */
11818 static int pi_pre_block(struct kvm_vcpu *vcpu)
11819 {
11820         unsigned int dest;
11821         struct pi_desc old, new;
11822         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
11823
11824         if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
11825                 !irq_remapping_cap(IRQ_POSTING_CAP)  ||
11826                 !kvm_vcpu_apicv_active(vcpu))
11827                 return 0;
11828
11829         WARN_ON(irqs_disabled());
11830         local_irq_disable();
11831         if (!WARN_ON_ONCE(vcpu->pre_pcpu != -1)) {
11832                 vcpu->pre_pcpu = vcpu->cpu;
11833                 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
11834                 list_add_tail(&vcpu->blocked_vcpu_list,
11835                               &per_cpu(blocked_vcpu_on_cpu,
11836                                        vcpu->pre_pcpu));
11837                 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
11838         }
11839
11840         do {
11841                 old.control = new.control = pi_desc->control;
11842
11843                 WARN((pi_desc->sn == 1),
11844                      "Warning: SN field of posted-interrupts "
11845                      "is set before blocking\n");
11846
11847                 /*
11848                  * Since vCPU can be preempted during this process,
11849                  * vcpu->cpu could be different with pre_pcpu, we
11850                  * need to set pre_pcpu as the destination of wakeup
11851                  * notification event, then we can find the right vCPU
11852                  * to wakeup in wakeup handler if interrupts happen
11853                  * when the vCPU is in blocked state.
11854                  */
11855                 dest = cpu_physical_id(vcpu->pre_pcpu);
11856
11857                 if (x2apic_enabled())
11858                         new.ndst = dest;
11859                 else
11860                         new.ndst = (dest << 8) & 0xFF00;
11861
11862                 /* set 'NV' to 'wakeup vector' */
11863                 new.nv = POSTED_INTR_WAKEUP_VECTOR;
11864         } while (cmpxchg64(&pi_desc->control, old.control,
11865                            new.control) != old.control);
11866
11867         /* We should not block the vCPU if an interrupt is posted for it.  */
11868         if (pi_test_on(pi_desc) == 1)
11869                 __pi_post_block(vcpu);
11870
11871         local_irq_enable();
11872         return (vcpu->pre_pcpu == -1);
11873 }
11874
11875 static int vmx_pre_block(struct kvm_vcpu *vcpu)
11876 {
11877         if (pi_pre_block(vcpu))
11878                 return 1;
11879
11880         if (kvm_lapic_hv_timer_in_use(vcpu))
11881                 kvm_lapic_switch_to_sw_timer(vcpu);
11882
11883         return 0;
11884 }
11885
11886 static void pi_post_block(struct kvm_vcpu *vcpu)
11887 {
11888         if (vcpu->pre_pcpu == -1)
11889                 return;
11890
11891         WARN_ON(irqs_disabled());
11892         local_irq_disable();
11893         __pi_post_block(vcpu);
11894         local_irq_enable();
11895 }
11896
11897 static void vmx_post_block(struct kvm_vcpu *vcpu)
11898 {
11899         if (kvm_x86_ops->set_hv_timer)
11900                 kvm_lapic_switch_to_hv_timer(vcpu);
11901
11902         pi_post_block(vcpu);
11903 }
11904
11905 /*
11906  * vmx_update_pi_irte - set IRTE for Posted-Interrupts
11907  *
11908  * @kvm: kvm
11909  * @host_irq: host irq of the interrupt
11910  * @guest_irq: gsi of the interrupt
11911  * @set: set or unset PI
11912  * returns 0 on success, < 0 on failure
11913  */
11914 static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
11915                               uint32_t guest_irq, bool set)
11916 {
11917         struct kvm_kernel_irq_routing_entry *e;
11918         struct kvm_irq_routing_table *irq_rt;
11919         struct kvm_lapic_irq irq;
11920         struct kvm_vcpu *vcpu;
11921         struct vcpu_data vcpu_info;
11922         int idx, ret = 0;
11923
11924         if (!kvm_arch_has_assigned_device(kvm) ||
11925                 !irq_remapping_cap(IRQ_POSTING_CAP) ||
11926                 !kvm_vcpu_apicv_active(kvm->vcpus[0]))
11927                 return 0;
11928
11929         idx = srcu_read_lock(&kvm->irq_srcu);
11930         irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
11931         if (guest_irq >= irq_rt->nr_rt_entries ||
11932             hlist_empty(&irq_rt->map[guest_irq])) {
11933                 pr_warn_once("no route for guest_irq %u/%u (broken user space?)\n",
11934                              guest_irq, irq_rt->nr_rt_entries);
11935                 goto out;
11936         }
11937
11938         hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
11939                 if (e->type != KVM_IRQ_ROUTING_MSI)
11940                         continue;
11941                 /*
11942                  * VT-d PI cannot support posting multicast/broadcast
11943                  * interrupts to a vCPU, we still use interrupt remapping
11944                  * for these kind of interrupts.
11945                  *
11946                  * For lowest-priority interrupts, we only support
11947                  * those with single CPU as the destination, e.g. user
11948                  * configures the interrupts via /proc/irq or uses
11949                  * irqbalance to make the interrupts single-CPU.
11950                  *
11951                  * We will support full lowest-priority interrupt later.
11952                  */
11953
11954                 kvm_set_msi_irq(kvm, e, &irq);
11955                 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
11956                         /*
11957                          * Make sure the IRTE is in remapped mode if
11958                          * we don't handle it in posted mode.
11959                          */
11960                         ret = irq_set_vcpu_affinity(host_irq, NULL);
11961                         if (ret < 0) {
11962                                 printk(KERN_INFO
11963                                    "failed to back to remapped mode, irq: %u\n",
11964                                    host_irq);
11965                                 goto out;
11966                         }
11967
11968                         continue;
11969                 }
11970
11971                 vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
11972                 vcpu_info.vector = irq.vector;
11973
11974                 trace_kvm_pi_irte_update(vcpu->vcpu_id, host_irq, e->gsi,
11975                                 vcpu_info.vector, vcpu_info.pi_desc_addr, set);
11976
11977                 if (set)
11978                         ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
11979                 else
11980                         ret = irq_set_vcpu_affinity(host_irq, NULL);
11981
11982                 if (ret < 0) {
11983                         printk(KERN_INFO "%s: failed to update PI IRTE\n",
11984                                         __func__);
11985                         goto out;
11986                 }
11987         }
11988
11989         ret = 0;
11990 out:
11991         srcu_read_unlock(&kvm->irq_srcu, idx);
11992         return ret;
11993 }
11994
11995 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
11996 {
11997         if (vcpu->arch.mcg_cap & MCG_LMCE_P)
11998                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
11999                         FEATURE_CONTROL_LMCE;
12000         else
12001                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
12002                         ~FEATURE_CONTROL_LMCE;
12003 }
12004
12005 static struct kvm_x86_ops vmx_x86_ops __ro_after_init = {
12006         .cpu_has_kvm_support = cpu_has_kvm_support,
12007         .disabled_by_bios = vmx_disabled_by_bios,
12008         .hardware_setup = hardware_setup,
12009         .hardware_unsetup = hardware_unsetup,
12010         .check_processor_compatibility = vmx_check_processor_compat,
12011         .hardware_enable = hardware_enable,
12012         .hardware_disable = hardware_disable,
12013         .cpu_has_accelerated_tpr = report_flexpriority,
12014         .cpu_has_high_real_mode_segbase = vmx_has_high_real_mode_segbase,
12015
12016         .vcpu_create = vmx_create_vcpu,
12017         .vcpu_free = vmx_free_vcpu,
12018         .vcpu_reset = vmx_vcpu_reset,
12019
12020         .prepare_guest_switch = vmx_save_host_state,
12021         .vcpu_load = vmx_vcpu_load,
12022         .vcpu_put = vmx_vcpu_put,
12023
12024         .update_bp_intercept = update_exception_bitmap,
12025         .get_msr = vmx_get_msr,
12026         .set_msr = vmx_set_msr,
12027         .get_segment_base = vmx_get_segment_base,
12028         .get_segment = vmx_get_segment,
12029         .set_segment = vmx_set_segment,
12030         .get_cpl = vmx_get_cpl,
12031         .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
12032         .decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
12033         .decache_cr3 = vmx_decache_cr3,
12034         .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
12035         .set_cr0 = vmx_set_cr0,
12036         .set_cr3 = vmx_set_cr3,
12037         .set_cr4 = vmx_set_cr4,
12038         .set_efer = vmx_set_efer,
12039         .get_idt = vmx_get_idt,
12040         .set_idt = vmx_set_idt,
12041         .get_gdt = vmx_get_gdt,
12042         .set_gdt = vmx_set_gdt,
12043         .get_dr6 = vmx_get_dr6,
12044         .set_dr6 = vmx_set_dr6,
12045         .set_dr7 = vmx_set_dr7,
12046         .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
12047         .cache_reg = vmx_cache_reg,
12048         .get_rflags = vmx_get_rflags,
12049         .set_rflags = vmx_set_rflags,
12050
12051         .tlb_flush = vmx_flush_tlb,
12052
12053         .run = vmx_vcpu_run,
12054         .handle_exit = vmx_handle_exit,
12055         .skip_emulated_instruction = skip_emulated_instruction,
12056         .set_interrupt_shadow = vmx_set_interrupt_shadow,
12057         .get_interrupt_shadow = vmx_get_interrupt_shadow,
12058         .patch_hypercall = vmx_patch_hypercall,
12059         .set_irq = vmx_inject_irq,
12060         .set_nmi = vmx_inject_nmi,
12061         .queue_exception = vmx_queue_exception,
12062         .cancel_injection = vmx_cancel_injection,
12063         .interrupt_allowed = vmx_interrupt_allowed,
12064         .nmi_allowed = vmx_nmi_allowed,
12065         .get_nmi_mask = vmx_get_nmi_mask,
12066         .set_nmi_mask = vmx_set_nmi_mask,
12067         .enable_nmi_window = enable_nmi_window,
12068         .enable_irq_window = enable_irq_window,
12069         .update_cr8_intercept = update_cr8_intercept,
12070         .set_virtual_x2apic_mode = vmx_set_virtual_x2apic_mode,
12071         .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
12072         .get_enable_apicv = vmx_get_enable_apicv,
12073         .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
12074         .load_eoi_exitmap = vmx_load_eoi_exitmap,
12075         .apicv_post_state_restore = vmx_apicv_post_state_restore,
12076         .hwapic_irr_update = vmx_hwapic_irr_update,
12077         .hwapic_isr_update = vmx_hwapic_isr_update,
12078         .sync_pir_to_irr = vmx_sync_pir_to_irr,
12079         .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
12080
12081         .set_tss_addr = vmx_set_tss_addr,
12082         .get_tdp_level = get_ept_level,
12083         .get_mt_mask = vmx_get_mt_mask,
12084
12085         .get_exit_info = vmx_get_exit_info,
12086
12087         .get_lpage_level = vmx_get_lpage_level,
12088
12089         .cpuid_update = vmx_cpuid_update,
12090
12091         .rdtscp_supported = vmx_rdtscp_supported,
12092         .invpcid_supported = vmx_invpcid_supported,
12093
12094         .set_supported_cpuid = vmx_set_supported_cpuid,
12095
12096         .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
12097
12098         .write_tsc_offset = vmx_write_tsc_offset,
12099
12100         .set_tdp_cr3 = vmx_set_cr3,
12101
12102         .check_intercept = vmx_check_intercept,
12103         .handle_external_intr = vmx_handle_external_intr,
12104         .mpx_supported = vmx_mpx_supported,
12105         .xsaves_supported = vmx_xsaves_supported,
12106
12107         .check_nested_events = vmx_check_nested_events,
12108
12109         .sched_in = vmx_sched_in,
12110
12111         .slot_enable_log_dirty = vmx_slot_enable_log_dirty,
12112         .slot_disable_log_dirty = vmx_slot_disable_log_dirty,
12113         .flush_log_dirty = vmx_flush_log_dirty,
12114         .enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
12115         .write_log_dirty = vmx_write_pml_buffer,
12116
12117         .pre_block = vmx_pre_block,
12118         .post_block = vmx_post_block,
12119
12120         .pmu_ops = &intel_pmu_ops,
12121
12122         .update_pi_irte = vmx_update_pi_irte,
12123
12124 #ifdef CONFIG_X86_64
12125         .set_hv_timer = vmx_set_hv_timer,
12126         .cancel_hv_timer = vmx_cancel_hv_timer,
12127 #endif
12128
12129         .setup_mce = vmx_setup_mce,
12130 };
12131
12132 static int __init vmx_init(void)
12133 {
12134         int r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
12135                      __alignof__(struct vcpu_vmx), THIS_MODULE);
12136         if (r)
12137                 return r;
12138
12139 #ifdef CONFIG_KEXEC_CORE
12140         rcu_assign_pointer(crash_vmclear_loaded_vmcss,
12141                            crash_vmclear_local_loaded_vmcss);
12142 #endif
12143
12144         return 0;
12145 }
12146
12147 static void __exit vmx_exit(void)
12148 {
12149 #ifdef CONFIG_KEXEC_CORE
12150         RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
12151         synchronize_rcu();
12152 #endif
12153
12154         kvm_exit();
12155 }
12156
12157 module_init(vmx_init)
12158 module_exit(vmx_exit)