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