x86/entry: Fix assumptions that the HW TSS is at the beginning of cpu_tss
[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.x86_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                 if (enable_ept)
2849                         vmx->nested.nested_vmx_vmfunc_controls =
2850                                 VMX_VMFUNC_EPTP_SWITCHING;
2851         }
2852
2853         /*
2854          * Old versions of KVM use the single-context version without
2855          * checking for support, so declare that it is supported even
2856          * though it is treated as global context.  The alternative is
2857          * not failing the single-context invvpid, and it is worse.
2858          */
2859         if (enable_vpid) {
2860                 vmx->nested.nested_vmx_secondary_ctls_high |=
2861                         SECONDARY_EXEC_ENABLE_VPID;
2862                 vmx->nested.nested_vmx_vpid_caps = VMX_VPID_INVVPID_BIT |
2863                         VMX_VPID_EXTENT_SUPPORTED_MASK;
2864         } else
2865                 vmx->nested.nested_vmx_vpid_caps = 0;
2866
2867         if (enable_unrestricted_guest)
2868                 vmx->nested.nested_vmx_secondary_ctls_high |=
2869                         SECONDARY_EXEC_UNRESTRICTED_GUEST;
2870
2871         /* miscellaneous data */
2872         rdmsr(MSR_IA32_VMX_MISC,
2873                 vmx->nested.nested_vmx_misc_low,
2874                 vmx->nested.nested_vmx_misc_high);
2875         vmx->nested.nested_vmx_misc_low &= VMX_MISC_SAVE_EFER_LMA;
2876         vmx->nested.nested_vmx_misc_low |=
2877                 VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE |
2878                 VMX_MISC_ACTIVITY_HLT;
2879         vmx->nested.nested_vmx_misc_high = 0;
2880
2881         /*
2882          * This MSR reports some information about VMX support. We
2883          * should return information about the VMX we emulate for the
2884          * guest, and the VMCS structure we give it - not about the
2885          * VMX support of the underlying hardware.
2886          */
2887         vmx->nested.nested_vmx_basic =
2888                 VMCS12_REVISION |
2889                 VMX_BASIC_TRUE_CTLS |
2890                 ((u64)VMCS12_SIZE << VMX_BASIC_VMCS_SIZE_SHIFT) |
2891                 (VMX_BASIC_MEM_TYPE_WB << VMX_BASIC_MEM_TYPE_SHIFT);
2892
2893         if (cpu_has_vmx_basic_inout())
2894                 vmx->nested.nested_vmx_basic |= VMX_BASIC_INOUT;
2895
2896         /*
2897          * These MSRs specify bits which the guest must keep fixed on
2898          * while L1 is in VMXON mode (in L1's root mode, or running an L2).
2899          * We picked the standard core2 setting.
2900          */
2901 #define VMXON_CR0_ALWAYSON     (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE)
2902 #define VMXON_CR4_ALWAYSON     X86_CR4_VMXE
2903         vmx->nested.nested_vmx_cr0_fixed0 = VMXON_CR0_ALWAYSON;
2904         vmx->nested.nested_vmx_cr4_fixed0 = VMXON_CR4_ALWAYSON;
2905
2906         /* These MSRs specify bits which the guest must keep fixed off. */
2907         rdmsrl(MSR_IA32_VMX_CR0_FIXED1, vmx->nested.nested_vmx_cr0_fixed1);
2908         rdmsrl(MSR_IA32_VMX_CR4_FIXED1, vmx->nested.nested_vmx_cr4_fixed1);
2909
2910         /* highest index: VMX_PREEMPTION_TIMER_VALUE */
2911         vmx->nested.nested_vmx_vmcs_enum = 0x2e;
2912 }
2913
2914 /*
2915  * if fixed0[i] == 1: val[i] must be 1
2916  * if fixed1[i] == 0: val[i] must be 0
2917  */
2918 static inline bool fixed_bits_valid(u64 val, u64 fixed0, u64 fixed1)
2919 {
2920         return ((val & fixed1) | fixed0) == val;
2921 }
2922
2923 static inline bool vmx_control_verify(u32 control, u32 low, u32 high)
2924 {
2925         return fixed_bits_valid(control, low, high);
2926 }
2927
2928 static inline u64 vmx_control_msr(u32 low, u32 high)
2929 {
2930         return low | ((u64)high << 32);
2931 }
2932
2933 static bool is_bitwise_subset(u64 superset, u64 subset, u64 mask)
2934 {
2935         superset &= mask;
2936         subset &= mask;
2937
2938         return (superset | subset) == superset;
2939 }
2940
2941 static int vmx_restore_vmx_basic(struct vcpu_vmx *vmx, u64 data)
2942 {
2943         const u64 feature_and_reserved =
2944                 /* feature (except bit 48; see below) */
2945                 BIT_ULL(49) | BIT_ULL(54) | BIT_ULL(55) |
2946                 /* reserved */
2947                 BIT_ULL(31) | GENMASK_ULL(47, 45) | GENMASK_ULL(63, 56);
2948         u64 vmx_basic = vmx->nested.nested_vmx_basic;
2949
2950         if (!is_bitwise_subset(vmx_basic, data, feature_and_reserved))
2951                 return -EINVAL;
2952
2953         /*
2954          * KVM does not emulate a version of VMX that constrains physical
2955          * addresses of VMX structures (e.g. VMCS) to 32-bits.
2956          */
2957         if (data & BIT_ULL(48))
2958                 return -EINVAL;
2959
2960         if (vmx_basic_vmcs_revision_id(vmx_basic) !=
2961             vmx_basic_vmcs_revision_id(data))
2962                 return -EINVAL;
2963
2964         if (vmx_basic_vmcs_size(vmx_basic) > vmx_basic_vmcs_size(data))
2965                 return -EINVAL;
2966
2967         vmx->nested.nested_vmx_basic = data;
2968         return 0;
2969 }
2970
2971 static int
2972 vmx_restore_control_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
2973 {
2974         u64 supported;
2975         u32 *lowp, *highp;
2976
2977         switch (msr_index) {
2978         case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
2979                 lowp = &vmx->nested.nested_vmx_pinbased_ctls_low;
2980                 highp = &vmx->nested.nested_vmx_pinbased_ctls_high;
2981                 break;
2982         case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
2983                 lowp = &vmx->nested.nested_vmx_procbased_ctls_low;
2984                 highp = &vmx->nested.nested_vmx_procbased_ctls_high;
2985                 break;
2986         case MSR_IA32_VMX_TRUE_EXIT_CTLS:
2987                 lowp = &vmx->nested.nested_vmx_exit_ctls_low;
2988                 highp = &vmx->nested.nested_vmx_exit_ctls_high;
2989                 break;
2990         case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
2991                 lowp = &vmx->nested.nested_vmx_entry_ctls_low;
2992                 highp = &vmx->nested.nested_vmx_entry_ctls_high;
2993                 break;
2994         case MSR_IA32_VMX_PROCBASED_CTLS2:
2995                 lowp = &vmx->nested.nested_vmx_secondary_ctls_low;
2996                 highp = &vmx->nested.nested_vmx_secondary_ctls_high;
2997                 break;
2998         default:
2999                 BUG();
3000         }
3001
3002         supported = vmx_control_msr(*lowp, *highp);
3003
3004         /* Check must-be-1 bits are still 1. */
3005         if (!is_bitwise_subset(data, supported, GENMASK_ULL(31, 0)))
3006                 return -EINVAL;
3007
3008         /* Check must-be-0 bits are still 0. */
3009         if (!is_bitwise_subset(supported, data, GENMASK_ULL(63, 32)))
3010                 return -EINVAL;
3011
3012         *lowp = data;
3013         *highp = data >> 32;
3014         return 0;
3015 }
3016
3017 static int vmx_restore_vmx_misc(struct vcpu_vmx *vmx, u64 data)
3018 {
3019         const u64 feature_and_reserved_bits =
3020                 /* feature */
3021                 BIT_ULL(5) | GENMASK_ULL(8, 6) | BIT_ULL(14) | BIT_ULL(15) |
3022                 BIT_ULL(28) | BIT_ULL(29) | BIT_ULL(30) |
3023                 /* reserved */
3024                 GENMASK_ULL(13, 9) | BIT_ULL(31);
3025         u64 vmx_misc;
3026
3027         vmx_misc = vmx_control_msr(vmx->nested.nested_vmx_misc_low,
3028                                    vmx->nested.nested_vmx_misc_high);
3029
3030         if (!is_bitwise_subset(vmx_misc, data, feature_and_reserved_bits))
3031                 return -EINVAL;
3032
3033         if ((vmx->nested.nested_vmx_pinbased_ctls_high &
3034              PIN_BASED_VMX_PREEMPTION_TIMER) &&
3035             vmx_misc_preemption_timer_rate(data) !=
3036             vmx_misc_preemption_timer_rate(vmx_misc))
3037                 return -EINVAL;
3038
3039         if (vmx_misc_cr3_count(data) > vmx_misc_cr3_count(vmx_misc))
3040                 return -EINVAL;
3041
3042         if (vmx_misc_max_msr(data) > vmx_misc_max_msr(vmx_misc))
3043                 return -EINVAL;
3044
3045         if (vmx_misc_mseg_revid(data) != vmx_misc_mseg_revid(vmx_misc))
3046                 return -EINVAL;
3047
3048         vmx->nested.nested_vmx_misc_low = data;
3049         vmx->nested.nested_vmx_misc_high = data >> 32;
3050         return 0;
3051 }
3052
3053 static int vmx_restore_vmx_ept_vpid_cap(struct vcpu_vmx *vmx, u64 data)
3054 {
3055         u64 vmx_ept_vpid_cap;
3056
3057         vmx_ept_vpid_cap = vmx_control_msr(vmx->nested.nested_vmx_ept_caps,
3058                                            vmx->nested.nested_vmx_vpid_caps);
3059
3060         /* Every bit is either reserved or a feature bit. */
3061         if (!is_bitwise_subset(vmx_ept_vpid_cap, data, -1ULL))
3062                 return -EINVAL;
3063
3064         vmx->nested.nested_vmx_ept_caps = data;
3065         vmx->nested.nested_vmx_vpid_caps = data >> 32;
3066         return 0;
3067 }
3068
3069 static int vmx_restore_fixed0_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
3070 {
3071         u64 *msr;
3072
3073         switch (msr_index) {
3074         case MSR_IA32_VMX_CR0_FIXED0:
3075                 msr = &vmx->nested.nested_vmx_cr0_fixed0;
3076                 break;
3077         case MSR_IA32_VMX_CR4_FIXED0:
3078                 msr = &vmx->nested.nested_vmx_cr4_fixed0;
3079                 break;
3080         default:
3081                 BUG();
3082         }
3083
3084         /*
3085          * 1 bits (which indicates bits which "must-be-1" during VMX operation)
3086          * must be 1 in the restored value.
3087          */
3088         if (!is_bitwise_subset(data, *msr, -1ULL))
3089                 return -EINVAL;
3090
3091         *msr = data;
3092         return 0;
3093 }
3094
3095 /*
3096  * Called when userspace is restoring VMX MSRs.
3097  *
3098  * Returns 0 on success, non-0 otherwise.
3099  */
3100 static int vmx_set_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
3101 {
3102         struct vcpu_vmx *vmx = to_vmx(vcpu);
3103
3104         switch (msr_index) {
3105         case MSR_IA32_VMX_BASIC:
3106                 return vmx_restore_vmx_basic(vmx, data);
3107         case MSR_IA32_VMX_PINBASED_CTLS:
3108         case MSR_IA32_VMX_PROCBASED_CTLS:
3109         case MSR_IA32_VMX_EXIT_CTLS:
3110         case MSR_IA32_VMX_ENTRY_CTLS:
3111                 /*
3112                  * The "non-true" VMX capability MSRs are generated from the
3113                  * "true" MSRs, so we do not support restoring them directly.
3114                  *
3115                  * If userspace wants to emulate VMX_BASIC[55]=0, userspace
3116                  * should restore the "true" MSRs with the must-be-1 bits
3117                  * set according to the SDM Vol 3. A.2 "RESERVED CONTROLS AND
3118                  * DEFAULT SETTINGS".
3119                  */
3120                 return -EINVAL;
3121         case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3122         case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3123         case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3124         case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3125         case MSR_IA32_VMX_PROCBASED_CTLS2:
3126                 return vmx_restore_control_msr(vmx, msr_index, data);
3127         case MSR_IA32_VMX_MISC:
3128                 return vmx_restore_vmx_misc(vmx, data);
3129         case MSR_IA32_VMX_CR0_FIXED0:
3130         case MSR_IA32_VMX_CR4_FIXED0:
3131                 return vmx_restore_fixed0_msr(vmx, msr_index, data);
3132         case MSR_IA32_VMX_CR0_FIXED1:
3133         case MSR_IA32_VMX_CR4_FIXED1:
3134                 /*
3135                  * These MSRs are generated based on the vCPU's CPUID, so we
3136                  * do not support restoring them directly.
3137                  */
3138                 return -EINVAL;
3139         case MSR_IA32_VMX_EPT_VPID_CAP:
3140                 return vmx_restore_vmx_ept_vpid_cap(vmx, data);
3141         case MSR_IA32_VMX_VMCS_ENUM:
3142                 vmx->nested.nested_vmx_vmcs_enum = data;
3143                 return 0;
3144         default:
3145                 /*
3146                  * The rest of the VMX capability MSRs do not support restore.
3147                  */
3148                 return -EINVAL;
3149         }
3150 }
3151
3152 /* Returns 0 on success, non-0 otherwise. */
3153 static int vmx_get_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
3154 {
3155         struct vcpu_vmx *vmx = to_vmx(vcpu);
3156
3157         switch (msr_index) {
3158         case MSR_IA32_VMX_BASIC:
3159                 *pdata = vmx->nested.nested_vmx_basic;
3160                 break;
3161         case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3162         case MSR_IA32_VMX_PINBASED_CTLS:
3163                 *pdata = vmx_control_msr(
3164                         vmx->nested.nested_vmx_pinbased_ctls_low,
3165                         vmx->nested.nested_vmx_pinbased_ctls_high);
3166                 if (msr_index == MSR_IA32_VMX_PINBASED_CTLS)
3167                         *pdata |= PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3168                 break;
3169         case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3170         case MSR_IA32_VMX_PROCBASED_CTLS:
3171                 *pdata = vmx_control_msr(
3172                         vmx->nested.nested_vmx_procbased_ctls_low,
3173                         vmx->nested.nested_vmx_procbased_ctls_high);
3174                 if (msr_index == MSR_IA32_VMX_PROCBASED_CTLS)
3175                         *pdata |= CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3176                 break;
3177         case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3178         case MSR_IA32_VMX_EXIT_CTLS:
3179                 *pdata = vmx_control_msr(
3180                         vmx->nested.nested_vmx_exit_ctls_low,
3181                         vmx->nested.nested_vmx_exit_ctls_high);
3182                 if (msr_index == MSR_IA32_VMX_EXIT_CTLS)
3183                         *pdata |= VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
3184                 break;
3185         case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3186         case MSR_IA32_VMX_ENTRY_CTLS:
3187                 *pdata = vmx_control_msr(
3188                         vmx->nested.nested_vmx_entry_ctls_low,
3189                         vmx->nested.nested_vmx_entry_ctls_high);
3190                 if (msr_index == MSR_IA32_VMX_ENTRY_CTLS)
3191                         *pdata |= VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
3192                 break;
3193         case MSR_IA32_VMX_MISC:
3194                 *pdata = vmx_control_msr(
3195                         vmx->nested.nested_vmx_misc_low,
3196                         vmx->nested.nested_vmx_misc_high);
3197                 break;
3198         case MSR_IA32_VMX_CR0_FIXED0:
3199                 *pdata = vmx->nested.nested_vmx_cr0_fixed0;
3200                 break;
3201         case MSR_IA32_VMX_CR0_FIXED1:
3202                 *pdata = vmx->nested.nested_vmx_cr0_fixed1;
3203                 break;
3204         case MSR_IA32_VMX_CR4_FIXED0:
3205                 *pdata = vmx->nested.nested_vmx_cr4_fixed0;
3206                 break;
3207         case MSR_IA32_VMX_CR4_FIXED1:
3208                 *pdata = vmx->nested.nested_vmx_cr4_fixed1;
3209                 break;
3210         case MSR_IA32_VMX_VMCS_ENUM:
3211                 *pdata = vmx->nested.nested_vmx_vmcs_enum;
3212                 break;
3213         case MSR_IA32_VMX_PROCBASED_CTLS2:
3214                 *pdata = vmx_control_msr(
3215                         vmx->nested.nested_vmx_secondary_ctls_low,
3216                         vmx->nested.nested_vmx_secondary_ctls_high);
3217                 break;
3218         case MSR_IA32_VMX_EPT_VPID_CAP:
3219                 *pdata = vmx->nested.nested_vmx_ept_caps |
3220                         ((u64)vmx->nested.nested_vmx_vpid_caps << 32);
3221                 break;
3222         case MSR_IA32_VMX_VMFUNC:
3223                 *pdata = vmx->nested.nested_vmx_vmfunc_controls;
3224                 break;
3225         default:
3226                 return 1;
3227         }
3228
3229         return 0;
3230 }
3231
3232 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
3233                                                  uint64_t val)
3234 {
3235         uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
3236
3237         return !(val & ~valid_bits);
3238 }
3239
3240 /*
3241  * Reads an msr value (of 'msr_index') into 'pdata'.
3242  * Returns 0 on success, non-0 otherwise.
3243  * Assumes vcpu_load() was already called.
3244  */
3245 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3246 {
3247         struct shared_msr_entry *msr;
3248
3249         switch (msr_info->index) {
3250 #ifdef CONFIG_X86_64
3251         case MSR_FS_BASE:
3252                 msr_info->data = vmcs_readl(GUEST_FS_BASE);
3253                 break;
3254         case MSR_GS_BASE:
3255                 msr_info->data = vmcs_readl(GUEST_GS_BASE);
3256                 break;
3257         case MSR_KERNEL_GS_BASE:
3258                 vmx_load_host_state(to_vmx(vcpu));
3259                 msr_info->data = to_vmx(vcpu)->msr_guest_kernel_gs_base;
3260                 break;
3261 #endif
3262         case MSR_EFER:
3263                 return kvm_get_msr_common(vcpu, msr_info);
3264         case MSR_IA32_TSC:
3265                 msr_info->data = guest_read_tsc(vcpu);
3266                 break;
3267         case MSR_IA32_SYSENTER_CS:
3268                 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
3269                 break;
3270         case MSR_IA32_SYSENTER_EIP:
3271                 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
3272                 break;
3273         case MSR_IA32_SYSENTER_ESP:
3274                 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
3275                 break;
3276         case MSR_IA32_BNDCFGS:
3277                 if (!kvm_mpx_supported() ||
3278                     (!msr_info->host_initiated &&
3279                      !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
3280                         return 1;
3281                 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
3282                 break;
3283         case MSR_IA32_MCG_EXT_CTL:
3284                 if (!msr_info->host_initiated &&
3285                     !(to_vmx(vcpu)->msr_ia32_feature_control &
3286                       FEATURE_CONTROL_LMCE))
3287                         return 1;
3288                 msr_info->data = vcpu->arch.mcg_ext_ctl;
3289                 break;
3290         case MSR_IA32_FEATURE_CONTROL:
3291                 msr_info->data = to_vmx(vcpu)->msr_ia32_feature_control;
3292                 break;
3293         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
3294                 if (!nested_vmx_allowed(vcpu))
3295                         return 1;
3296                 return vmx_get_vmx_msr(vcpu, msr_info->index, &msr_info->data);
3297         case MSR_IA32_XSS:
3298                 if (!vmx_xsaves_supported())
3299                         return 1;
3300                 msr_info->data = vcpu->arch.ia32_xss;
3301                 break;
3302         case MSR_TSC_AUX:
3303                 if (!msr_info->host_initiated &&
3304                     !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
3305                         return 1;
3306                 /* Otherwise falls through */
3307         default:
3308                 msr = find_msr_entry(to_vmx(vcpu), msr_info->index);
3309                 if (msr) {
3310                         msr_info->data = msr->data;
3311                         break;
3312                 }
3313                 return kvm_get_msr_common(vcpu, msr_info);
3314         }
3315
3316         return 0;
3317 }
3318
3319 static void vmx_leave_nested(struct kvm_vcpu *vcpu);
3320
3321 /*
3322  * Writes msr value into into the appropriate "register".
3323  * Returns 0 on success, non-0 otherwise.
3324  * Assumes vcpu_load() was already called.
3325  */
3326 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3327 {
3328         struct vcpu_vmx *vmx = to_vmx(vcpu);
3329         struct shared_msr_entry *msr;
3330         int ret = 0;
3331         u32 msr_index = msr_info->index;
3332         u64 data = msr_info->data;
3333
3334         switch (msr_index) {
3335         case MSR_EFER:
3336                 ret = kvm_set_msr_common(vcpu, msr_info);
3337                 break;
3338 #ifdef CONFIG_X86_64
3339         case MSR_FS_BASE:
3340                 vmx_segment_cache_clear(vmx);
3341                 vmcs_writel(GUEST_FS_BASE, data);
3342                 break;
3343         case MSR_GS_BASE:
3344                 vmx_segment_cache_clear(vmx);
3345                 vmcs_writel(GUEST_GS_BASE, data);
3346                 break;
3347         case MSR_KERNEL_GS_BASE:
3348                 vmx_load_host_state(vmx);
3349                 vmx->msr_guest_kernel_gs_base = data;
3350                 break;
3351 #endif
3352         case MSR_IA32_SYSENTER_CS:
3353                 vmcs_write32(GUEST_SYSENTER_CS, data);
3354                 break;
3355         case MSR_IA32_SYSENTER_EIP:
3356                 vmcs_writel(GUEST_SYSENTER_EIP, data);
3357                 break;
3358         case MSR_IA32_SYSENTER_ESP:
3359                 vmcs_writel(GUEST_SYSENTER_ESP, data);
3360                 break;
3361         case MSR_IA32_BNDCFGS:
3362                 if (!kvm_mpx_supported() ||
3363                     (!msr_info->host_initiated &&
3364                      !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
3365                         return 1;
3366                 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
3367                     (data & MSR_IA32_BNDCFGS_RSVD))
3368                         return 1;
3369                 vmcs_write64(GUEST_BNDCFGS, data);
3370                 break;
3371         case MSR_IA32_TSC:
3372                 kvm_write_tsc(vcpu, msr_info);
3373                 break;
3374         case MSR_IA32_CR_PAT:
3375                 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
3376                         if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
3377                                 return 1;
3378                         vmcs_write64(GUEST_IA32_PAT, data);
3379                         vcpu->arch.pat = data;
3380                         break;
3381                 }
3382                 ret = kvm_set_msr_common(vcpu, msr_info);
3383                 break;
3384         case MSR_IA32_TSC_ADJUST:
3385                 ret = kvm_set_msr_common(vcpu, msr_info);
3386                 break;
3387         case MSR_IA32_MCG_EXT_CTL:
3388                 if ((!msr_info->host_initiated &&
3389                      !(to_vmx(vcpu)->msr_ia32_feature_control &
3390                        FEATURE_CONTROL_LMCE)) ||
3391                     (data & ~MCG_EXT_CTL_LMCE_EN))
3392                         return 1;
3393                 vcpu->arch.mcg_ext_ctl = data;
3394                 break;
3395         case MSR_IA32_FEATURE_CONTROL:
3396                 if (!vmx_feature_control_msr_valid(vcpu, data) ||
3397                     (to_vmx(vcpu)->msr_ia32_feature_control &
3398                      FEATURE_CONTROL_LOCKED && !msr_info->host_initiated))
3399                         return 1;
3400                 vmx->msr_ia32_feature_control = data;
3401                 if (msr_info->host_initiated && data == 0)
3402                         vmx_leave_nested(vcpu);
3403                 break;
3404         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
3405                 if (!msr_info->host_initiated)
3406                         return 1; /* they are read-only */
3407                 if (!nested_vmx_allowed(vcpu))
3408                         return 1;
3409                 return vmx_set_vmx_msr(vcpu, msr_index, data);
3410         case MSR_IA32_XSS:
3411                 if (!vmx_xsaves_supported())
3412                         return 1;
3413                 /*
3414                  * The only supported bit as of Skylake is bit 8, but
3415                  * it is not supported on KVM.
3416                  */
3417                 if (data != 0)
3418                         return 1;
3419                 vcpu->arch.ia32_xss = data;
3420                 if (vcpu->arch.ia32_xss != host_xss)
3421                         add_atomic_switch_msr(vmx, MSR_IA32_XSS,
3422                                 vcpu->arch.ia32_xss, host_xss);
3423                 else
3424                         clear_atomic_switch_msr(vmx, MSR_IA32_XSS);
3425                 break;
3426         case MSR_TSC_AUX:
3427                 if (!msr_info->host_initiated &&
3428                     !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
3429                         return 1;
3430                 /* Check reserved bit, higher 32 bits should be zero */
3431                 if ((data >> 32) != 0)
3432                         return 1;
3433                 /* Otherwise falls through */
3434         default:
3435                 msr = find_msr_entry(vmx, msr_index);
3436                 if (msr) {
3437                         u64 old_msr_data = msr->data;
3438                         msr->data = data;
3439                         if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
3440                                 preempt_disable();
3441                                 ret = kvm_set_shared_msr(msr->index, msr->data,
3442                                                          msr->mask);
3443                                 preempt_enable();
3444                                 if (ret)
3445                                         msr->data = old_msr_data;
3446                         }
3447                         break;
3448                 }
3449                 ret = kvm_set_msr_common(vcpu, msr_info);
3450         }
3451
3452         return ret;
3453 }
3454
3455 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
3456 {
3457         __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
3458         switch (reg) {
3459         case VCPU_REGS_RSP:
3460                 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
3461                 break;
3462         case VCPU_REGS_RIP:
3463                 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
3464                 break;
3465         case VCPU_EXREG_PDPTR:
3466                 if (enable_ept)
3467                         ept_save_pdptrs(vcpu);
3468                 break;
3469         default:
3470                 break;
3471         }
3472 }
3473
3474 static __init int cpu_has_kvm_support(void)
3475 {
3476         return cpu_has_vmx();
3477 }
3478
3479 static __init int vmx_disabled_by_bios(void)
3480 {
3481         u64 msr;
3482
3483         rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
3484         if (msr & FEATURE_CONTROL_LOCKED) {
3485                 /* launched w/ TXT and VMX disabled */
3486                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
3487                         && tboot_enabled())
3488                         return 1;
3489                 /* launched w/o TXT and VMX only enabled w/ TXT */
3490                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
3491                         && (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
3492                         && !tboot_enabled()) {
3493                         printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
3494                                 "activate TXT before enabling KVM\n");
3495                         return 1;
3496                 }
3497                 /* launched w/o TXT and VMX disabled */
3498                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
3499                         && !tboot_enabled())
3500                         return 1;
3501         }
3502
3503         return 0;
3504 }
3505
3506 static void kvm_cpu_vmxon(u64 addr)
3507 {
3508         cr4_set_bits(X86_CR4_VMXE);
3509         intel_pt_handle_vmx(1);
3510
3511         asm volatile (ASM_VMX_VMXON_RAX
3512                         : : "a"(&addr), "m"(addr)
3513                         : "memory", "cc");
3514 }
3515
3516 static int hardware_enable(void)
3517 {
3518         int cpu = raw_smp_processor_id();
3519         u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
3520         u64 old, test_bits;
3521
3522         if (cr4_read_shadow() & X86_CR4_VMXE)
3523                 return -EBUSY;
3524
3525         INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
3526         INIT_LIST_HEAD(&per_cpu(blocked_vcpu_on_cpu, cpu));
3527         spin_lock_init(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
3528
3529         /*
3530          * Now we can enable the vmclear operation in kdump
3531          * since the loaded_vmcss_on_cpu list on this cpu
3532          * has been initialized.
3533          *
3534          * Though the cpu is not in VMX operation now, there
3535          * is no problem to enable the vmclear operation
3536          * for the loaded_vmcss_on_cpu list is empty!
3537          */
3538         crash_enable_local_vmclear(cpu);
3539
3540         rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
3541
3542         test_bits = FEATURE_CONTROL_LOCKED;
3543         test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
3544         if (tboot_enabled())
3545                 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
3546
3547         if ((old & test_bits) != test_bits) {
3548                 /* enable and lock */
3549                 wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
3550         }
3551         kvm_cpu_vmxon(phys_addr);
3552         ept_sync_global();
3553
3554         return 0;
3555 }
3556
3557 static void vmclear_local_loaded_vmcss(void)
3558 {
3559         int cpu = raw_smp_processor_id();
3560         struct loaded_vmcs *v, *n;
3561
3562         list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
3563                                  loaded_vmcss_on_cpu_link)
3564                 __loaded_vmcs_clear(v);
3565 }
3566
3567
3568 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
3569  * tricks.
3570  */
3571 static void kvm_cpu_vmxoff(void)
3572 {
3573         asm volatile (__ex(ASM_VMX_VMXOFF) : : : "cc");
3574
3575         intel_pt_handle_vmx(0);
3576         cr4_clear_bits(X86_CR4_VMXE);
3577 }
3578
3579 static void hardware_disable(void)
3580 {
3581         vmclear_local_loaded_vmcss();
3582         kvm_cpu_vmxoff();
3583 }
3584
3585 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
3586                                       u32 msr, u32 *result)
3587 {
3588         u32 vmx_msr_low, vmx_msr_high;
3589         u32 ctl = ctl_min | ctl_opt;
3590
3591         rdmsr(msr, vmx_msr_low, vmx_msr_high);
3592
3593         ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
3594         ctl |= vmx_msr_low;  /* bit == 1 in low word  ==> must be one  */
3595
3596         /* Ensure minimum (required) set of control bits are supported. */
3597         if (ctl_min & ~ctl)
3598                 return -EIO;
3599
3600         *result = ctl;
3601         return 0;
3602 }
3603
3604 static __init bool allow_1_setting(u32 msr, u32 ctl)
3605 {
3606         u32 vmx_msr_low, vmx_msr_high;
3607
3608         rdmsr(msr, vmx_msr_low, vmx_msr_high);
3609         return vmx_msr_high & ctl;
3610 }
3611
3612 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
3613 {
3614         u32 vmx_msr_low, vmx_msr_high;
3615         u32 min, opt, min2, opt2;
3616         u32 _pin_based_exec_control = 0;
3617         u32 _cpu_based_exec_control = 0;
3618         u32 _cpu_based_2nd_exec_control = 0;
3619         u32 _vmexit_control = 0;
3620         u32 _vmentry_control = 0;
3621
3622         min = CPU_BASED_HLT_EXITING |
3623 #ifdef CONFIG_X86_64
3624               CPU_BASED_CR8_LOAD_EXITING |
3625               CPU_BASED_CR8_STORE_EXITING |
3626 #endif
3627               CPU_BASED_CR3_LOAD_EXITING |
3628               CPU_BASED_CR3_STORE_EXITING |
3629               CPU_BASED_USE_IO_BITMAPS |
3630               CPU_BASED_MOV_DR_EXITING |
3631               CPU_BASED_USE_TSC_OFFSETING |
3632               CPU_BASED_INVLPG_EXITING |
3633               CPU_BASED_RDPMC_EXITING;
3634
3635         if (!kvm_mwait_in_guest())
3636                 min |= CPU_BASED_MWAIT_EXITING |
3637                         CPU_BASED_MONITOR_EXITING;
3638
3639         opt = CPU_BASED_TPR_SHADOW |
3640               CPU_BASED_USE_MSR_BITMAPS |
3641               CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
3642         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
3643                                 &_cpu_based_exec_control) < 0)
3644                 return -EIO;
3645 #ifdef CONFIG_X86_64
3646         if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
3647                 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
3648                                            ~CPU_BASED_CR8_STORE_EXITING;
3649 #endif
3650         if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
3651                 min2 = 0;
3652                 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
3653                         SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
3654                         SECONDARY_EXEC_WBINVD_EXITING |
3655                         SECONDARY_EXEC_ENABLE_VPID |
3656                         SECONDARY_EXEC_ENABLE_EPT |
3657                         SECONDARY_EXEC_UNRESTRICTED_GUEST |
3658                         SECONDARY_EXEC_PAUSE_LOOP_EXITING |
3659                         SECONDARY_EXEC_RDTSCP |
3660                         SECONDARY_EXEC_ENABLE_INVPCID |
3661                         SECONDARY_EXEC_APIC_REGISTER_VIRT |
3662                         SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
3663                         SECONDARY_EXEC_SHADOW_VMCS |
3664                         SECONDARY_EXEC_XSAVES |
3665                         SECONDARY_EXEC_RDSEED |
3666                         SECONDARY_EXEC_RDRAND |
3667                         SECONDARY_EXEC_ENABLE_PML |
3668                         SECONDARY_EXEC_TSC_SCALING |
3669                         SECONDARY_EXEC_ENABLE_VMFUNC;
3670                 if (adjust_vmx_controls(min2, opt2,
3671                                         MSR_IA32_VMX_PROCBASED_CTLS2,
3672                                         &_cpu_based_2nd_exec_control) < 0)
3673                         return -EIO;
3674         }
3675 #ifndef CONFIG_X86_64
3676         if (!(_cpu_based_2nd_exec_control &
3677                                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
3678                 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
3679 #endif
3680
3681         if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
3682                 _cpu_based_2nd_exec_control &= ~(
3683                                 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3684                                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
3685                                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
3686
3687         if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
3688                 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
3689                    enabled */
3690                 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
3691                                              CPU_BASED_CR3_STORE_EXITING |
3692                                              CPU_BASED_INVLPG_EXITING);
3693                 rdmsr(MSR_IA32_VMX_EPT_VPID_CAP,
3694                       vmx_capability.ept, vmx_capability.vpid);
3695         }
3696
3697         min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
3698 #ifdef CONFIG_X86_64
3699         min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
3700 #endif
3701         opt = VM_EXIT_SAVE_IA32_PAT | VM_EXIT_LOAD_IA32_PAT |
3702                 VM_EXIT_CLEAR_BNDCFGS;
3703         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
3704                                 &_vmexit_control) < 0)
3705                 return -EIO;
3706
3707         min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
3708         opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
3709                  PIN_BASED_VMX_PREEMPTION_TIMER;
3710         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
3711                                 &_pin_based_exec_control) < 0)
3712                 return -EIO;
3713
3714         if (cpu_has_broken_vmx_preemption_timer())
3715                 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
3716         if (!(_cpu_based_2nd_exec_control &
3717                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
3718                 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
3719
3720         min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
3721         opt = VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_BNDCFGS;
3722         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
3723                                 &_vmentry_control) < 0)
3724                 return -EIO;
3725
3726         rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
3727
3728         /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
3729         if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
3730                 return -EIO;
3731
3732 #ifdef CONFIG_X86_64
3733         /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
3734         if (vmx_msr_high & (1u<<16))
3735                 return -EIO;
3736 #endif
3737
3738         /* Require Write-Back (WB) memory type for VMCS accesses. */
3739         if (((vmx_msr_high >> 18) & 15) != 6)
3740                 return -EIO;
3741
3742         vmcs_conf->size = vmx_msr_high & 0x1fff;
3743         vmcs_conf->order = get_order(vmcs_conf->size);
3744         vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
3745         vmcs_conf->revision_id = vmx_msr_low;
3746
3747         vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
3748         vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
3749         vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
3750         vmcs_conf->vmexit_ctrl         = _vmexit_control;
3751         vmcs_conf->vmentry_ctrl        = _vmentry_control;
3752
3753         cpu_has_load_ia32_efer =
3754                 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
3755                                 VM_ENTRY_LOAD_IA32_EFER)
3756                 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
3757                                    VM_EXIT_LOAD_IA32_EFER);
3758
3759         cpu_has_load_perf_global_ctrl =
3760                 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
3761                                 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
3762                 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
3763                                    VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
3764
3765         /*
3766          * Some cpus support VM_ENTRY_(LOAD|SAVE)_IA32_PERF_GLOBAL_CTRL
3767          * but due to errata below it can't be used. Workaround is to use
3768          * msr load mechanism to switch IA32_PERF_GLOBAL_CTRL.
3769          *
3770          * VM Exit May Incorrectly Clear IA32_PERF_GLOBAL_CTRL [34:32]
3771          *
3772          * AAK155             (model 26)
3773          * AAP115             (model 30)
3774          * AAT100             (model 37)
3775          * BC86,AAY89,BD102   (model 44)
3776          * BA97               (model 46)
3777          *
3778          */
3779         if (cpu_has_load_perf_global_ctrl && boot_cpu_data.x86 == 0x6) {
3780                 switch (boot_cpu_data.x86_model) {
3781                 case 26:
3782                 case 30:
3783                 case 37:
3784                 case 44:
3785                 case 46:
3786                         cpu_has_load_perf_global_ctrl = false;
3787                         printk_once(KERN_WARNING"kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
3788                                         "does not work properly. Using workaround\n");
3789                         break;
3790                 default:
3791                         break;
3792                 }
3793         }
3794
3795         if (boot_cpu_has(X86_FEATURE_XSAVES))
3796                 rdmsrl(MSR_IA32_XSS, host_xss);
3797
3798         return 0;
3799 }
3800
3801 static struct vmcs *alloc_vmcs_cpu(int cpu)
3802 {
3803         int node = cpu_to_node(cpu);
3804         struct page *pages;
3805         struct vmcs *vmcs;
3806
3807         pages = __alloc_pages_node(node, GFP_KERNEL, vmcs_config.order);
3808         if (!pages)
3809                 return NULL;
3810         vmcs = page_address(pages);
3811         memset(vmcs, 0, vmcs_config.size);
3812         vmcs->revision_id = vmcs_config.revision_id; /* vmcs revision id */
3813         return vmcs;
3814 }
3815
3816 static struct vmcs *alloc_vmcs(void)
3817 {
3818         return alloc_vmcs_cpu(raw_smp_processor_id());
3819 }
3820
3821 static void free_vmcs(struct vmcs *vmcs)
3822 {
3823         free_pages((unsigned long)vmcs, vmcs_config.order);
3824 }
3825
3826 /*
3827  * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
3828  */
3829 static void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
3830 {
3831         if (!loaded_vmcs->vmcs)
3832                 return;
3833         loaded_vmcs_clear(loaded_vmcs);
3834         free_vmcs(loaded_vmcs->vmcs);
3835         loaded_vmcs->vmcs = NULL;
3836         WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
3837 }
3838
3839 static void free_kvm_area(void)
3840 {
3841         int cpu;
3842
3843         for_each_possible_cpu(cpu) {
3844                 free_vmcs(per_cpu(vmxarea, cpu));
3845                 per_cpu(vmxarea, cpu) = NULL;
3846         }
3847 }
3848
3849 enum vmcs_field_type {
3850         VMCS_FIELD_TYPE_U16 = 0,
3851         VMCS_FIELD_TYPE_U64 = 1,
3852         VMCS_FIELD_TYPE_U32 = 2,
3853         VMCS_FIELD_TYPE_NATURAL_WIDTH = 3
3854 };
3855
3856 static inline int vmcs_field_type(unsigned long field)
3857 {
3858         if (0x1 & field)        /* the *_HIGH fields are all 32 bit */
3859                 return VMCS_FIELD_TYPE_U32;
3860         return (field >> 13) & 0x3 ;
3861 }
3862
3863 static inline int vmcs_field_readonly(unsigned long field)
3864 {
3865         return (((field >> 10) & 0x3) == 1);
3866 }
3867
3868 static void init_vmcs_shadow_fields(void)
3869 {
3870         int i, j;
3871
3872         /* No checks for read only fields yet */
3873
3874         for (i = j = 0; i < max_shadow_read_write_fields; i++) {
3875                 switch (shadow_read_write_fields[i]) {
3876                 case GUEST_BNDCFGS:
3877                         if (!kvm_mpx_supported())
3878                                 continue;
3879                         break;
3880                 default:
3881                         break;
3882                 }
3883
3884                 if (j < i)
3885                         shadow_read_write_fields[j] =
3886                                 shadow_read_write_fields[i];
3887                 j++;
3888         }
3889         max_shadow_read_write_fields = j;
3890
3891         /* shadowed fields guest access without vmexit */
3892         for (i = 0; i < max_shadow_read_write_fields; i++) {
3893                 unsigned long field = shadow_read_write_fields[i];
3894
3895                 clear_bit(field, vmx_vmwrite_bitmap);
3896                 clear_bit(field, vmx_vmread_bitmap);
3897                 if (vmcs_field_type(field) == VMCS_FIELD_TYPE_U64) {
3898                         clear_bit(field + 1, vmx_vmwrite_bitmap);
3899                         clear_bit(field + 1, vmx_vmread_bitmap);
3900                 }
3901         }
3902         for (i = 0; i < max_shadow_read_only_fields; i++) {
3903                 unsigned long field = shadow_read_only_fields[i];
3904
3905                 clear_bit(field, vmx_vmread_bitmap);
3906                 if (vmcs_field_type(field) == VMCS_FIELD_TYPE_U64)
3907                         clear_bit(field + 1, vmx_vmread_bitmap);
3908         }
3909 }
3910
3911 static __init int alloc_kvm_area(void)
3912 {
3913         int cpu;
3914
3915         for_each_possible_cpu(cpu) {
3916                 struct vmcs *vmcs;
3917
3918                 vmcs = alloc_vmcs_cpu(cpu);
3919                 if (!vmcs) {
3920                         free_kvm_area();
3921                         return -ENOMEM;
3922                 }
3923
3924                 per_cpu(vmxarea, cpu) = vmcs;
3925         }
3926         return 0;
3927 }
3928
3929 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
3930                 struct kvm_segment *save)
3931 {
3932         if (!emulate_invalid_guest_state) {
3933                 /*
3934                  * CS and SS RPL should be equal during guest entry according
3935                  * to VMX spec, but in reality it is not always so. Since vcpu
3936                  * is in the middle of the transition from real mode to
3937                  * protected mode it is safe to assume that RPL 0 is a good
3938                  * default value.
3939                  */
3940                 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
3941                         save->selector &= ~SEGMENT_RPL_MASK;
3942                 save->dpl = save->selector & SEGMENT_RPL_MASK;
3943                 save->s = 1;
3944         }
3945         vmx_set_segment(vcpu, save, seg);
3946 }
3947
3948 static void enter_pmode(struct kvm_vcpu *vcpu)
3949 {
3950         unsigned long flags;
3951         struct vcpu_vmx *vmx = to_vmx(vcpu);
3952
3953         /*
3954          * Update real mode segment cache. It may be not up-to-date if sement
3955          * register was written while vcpu was in a guest mode.
3956          */
3957         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
3958         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
3959         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
3960         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
3961         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
3962         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
3963
3964         vmx->rmode.vm86_active = 0;
3965
3966         vmx_segment_cache_clear(vmx);
3967
3968         vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
3969
3970         flags = vmcs_readl(GUEST_RFLAGS);
3971         flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
3972         flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
3973         vmcs_writel(GUEST_RFLAGS, flags);
3974
3975         vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
3976                         (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
3977
3978         update_exception_bitmap(vcpu);
3979
3980         fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
3981         fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
3982         fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
3983         fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
3984         fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
3985         fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
3986 }
3987
3988 static void fix_rmode_seg(int seg, struct kvm_segment *save)
3989 {
3990         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3991         struct kvm_segment var = *save;
3992
3993         var.dpl = 0x3;
3994         if (seg == VCPU_SREG_CS)
3995                 var.type = 0x3;
3996
3997         if (!emulate_invalid_guest_state) {
3998                 var.selector = var.base >> 4;
3999                 var.base = var.base & 0xffff0;
4000                 var.limit = 0xffff;
4001                 var.g = 0;
4002                 var.db = 0;
4003                 var.present = 1;
4004                 var.s = 1;
4005                 var.l = 0;
4006                 var.unusable = 0;
4007                 var.type = 0x3;
4008                 var.avl = 0;
4009                 if (save->base & 0xf)
4010                         printk_once(KERN_WARNING "kvm: segment base is not "
4011                                         "paragraph aligned when entering "
4012                                         "protected mode (seg=%d)", seg);
4013         }
4014
4015         vmcs_write16(sf->selector, var.selector);
4016         vmcs_writel(sf->base, var.base);
4017         vmcs_write32(sf->limit, var.limit);
4018         vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
4019 }
4020
4021 static void enter_rmode(struct kvm_vcpu *vcpu)
4022 {
4023         unsigned long flags;
4024         struct vcpu_vmx *vmx = to_vmx(vcpu);
4025
4026         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
4027         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
4028         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
4029         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
4030         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
4031         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
4032         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
4033
4034         vmx->rmode.vm86_active = 1;
4035
4036         /*
4037          * Very old userspace does not call KVM_SET_TSS_ADDR before entering
4038          * vcpu. Warn the user that an update is overdue.
4039          */
4040         if (!vcpu->kvm->arch.tss_addr)
4041                 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
4042                              "called before entering vcpu\n");
4043
4044         vmx_segment_cache_clear(vmx);
4045
4046         vmcs_writel(GUEST_TR_BASE, vcpu->kvm->arch.tss_addr);
4047         vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
4048         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4049
4050         flags = vmcs_readl(GUEST_RFLAGS);
4051         vmx->rmode.save_rflags = flags;
4052
4053         flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
4054
4055         vmcs_writel(GUEST_RFLAGS, flags);
4056         vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
4057         update_exception_bitmap(vcpu);
4058
4059         fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
4060         fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
4061         fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
4062         fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
4063         fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
4064         fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
4065
4066         kvm_mmu_reset_context(vcpu);
4067 }
4068
4069 static void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
4070 {
4071         struct vcpu_vmx *vmx = to_vmx(vcpu);
4072         struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
4073
4074         if (!msr)
4075                 return;
4076
4077         /*
4078          * Force kernel_gs_base reloading before EFER changes, as control
4079          * of this msr depends on is_long_mode().
4080          */
4081         vmx_load_host_state(to_vmx(vcpu));
4082         vcpu->arch.efer = efer;
4083         if (efer & EFER_LMA) {
4084                 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
4085                 msr->data = efer;
4086         } else {
4087                 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
4088
4089                 msr->data = efer & ~EFER_LME;
4090         }
4091         setup_msrs(vmx);
4092 }
4093
4094 #ifdef CONFIG_X86_64
4095
4096 static void enter_lmode(struct kvm_vcpu *vcpu)
4097 {
4098         u32 guest_tr_ar;
4099
4100         vmx_segment_cache_clear(to_vmx(vcpu));
4101
4102         guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
4103         if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
4104                 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
4105                                      __func__);
4106                 vmcs_write32(GUEST_TR_AR_BYTES,
4107                              (guest_tr_ar & ~VMX_AR_TYPE_MASK)
4108                              | VMX_AR_TYPE_BUSY_64_TSS);
4109         }
4110         vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
4111 }
4112
4113 static void exit_lmode(struct kvm_vcpu *vcpu)
4114 {
4115         vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
4116         vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
4117 }
4118
4119 #endif
4120
4121 static inline void __vmx_flush_tlb(struct kvm_vcpu *vcpu, int vpid)
4122 {
4123         if (enable_ept) {
4124                 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
4125                         return;
4126                 ept_sync_context(construct_eptp(vcpu, vcpu->arch.mmu.root_hpa));
4127         } else {
4128                 vpid_sync_context(vpid);
4129         }
4130 }
4131
4132 static void vmx_flush_tlb(struct kvm_vcpu *vcpu)
4133 {
4134         __vmx_flush_tlb(vcpu, to_vmx(vcpu)->vpid);
4135 }
4136
4137 static void vmx_flush_tlb_ept_only(struct kvm_vcpu *vcpu)
4138 {
4139         if (enable_ept)
4140                 vmx_flush_tlb(vcpu);
4141 }
4142
4143 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
4144 {
4145         ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
4146
4147         vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
4148         vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
4149 }
4150
4151 static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
4152 {
4153         if (enable_ept && is_paging(vcpu))
4154                 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
4155         __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
4156 }
4157
4158 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
4159 {
4160         ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
4161
4162         vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
4163         vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
4164 }
4165
4166 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
4167 {
4168         struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
4169
4170         if (!test_bit(VCPU_EXREG_PDPTR,
4171                       (unsigned long *)&vcpu->arch.regs_dirty))
4172                 return;
4173
4174         if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
4175                 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
4176                 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
4177                 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
4178                 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
4179         }
4180 }
4181
4182 static void ept_save_pdptrs(struct kvm_vcpu *vcpu)
4183 {
4184         struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
4185
4186         if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
4187                 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
4188                 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
4189                 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
4190                 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
4191         }
4192
4193         __set_bit(VCPU_EXREG_PDPTR,
4194                   (unsigned long *)&vcpu->arch.regs_avail);
4195         __set_bit(VCPU_EXREG_PDPTR,
4196                   (unsigned long *)&vcpu->arch.regs_dirty);
4197 }
4198
4199 static bool nested_guest_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
4200 {
4201         u64 fixed0 = to_vmx(vcpu)->nested.nested_vmx_cr0_fixed0;
4202         u64 fixed1 = to_vmx(vcpu)->nested.nested_vmx_cr0_fixed1;
4203         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4204
4205         if (to_vmx(vcpu)->nested.nested_vmx_secondary_ctls_high &
4206                 SECONDARY_EXEC_UNRESTRICTED_GUEST &&
4207             nested_cpu_has2(vmcs12, SECONDARY_EXEC_UNRESTRICTED_GUEST))
4208                 fixed0 &= ~(X86_CR0_PE | X86_CR0_PG);
4209
4210         return fixed_bits_valid(val, fixed0, fixed1);
4211 }
4212
4213 static bool nested_host_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
4214 {
4215         u64 fixed0 = to_vmx(vcpu)->nested.nested_vmx_cr0_fixed0;
4216         u64 fixed1 = to_vmx(vcpu)->nested.nested_vmx_cr0_fixed1;
4217
4218         return fixed_bits_valid(val, fixed0, fixed1);
4219 }
4220
4221 static bool nested_cr4_valid(struct kvm_vcpu *vcpu, unsigned long val)
4222 {
4223         u64 fixed0 = to_vmx(vcpu)->nested.nested_vmx_cr4_fixed0;
4224         u64 fixed1 = to_vmx(vcpu)->nested.nested_vmx_cr4_fixed1;
4225
4226         return fixed_bits_valid(val, fixed0, fixed1);
4227 }
4228
4229 /* No difference in the restrictions on guest and host CR4 in VMX operation. */
4230 #define nested_guest_cr4_valid  nested_cr4_valid
4231 #define nested_host_cr4_valid   nested_cr4_valid
4232
4233 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
4234
4235 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
4236                                         unsigned long cr0,
4237                                         struct kvm_vcpu *vcpu)
4238 {
4239         if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
4240                 vmx_decache_cr3(vcpu);
4241         if (!(cr0 & X86_CR0_PG)) {
4242                 /* From paging/starting to nonpaging */
4243                 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
4244                              vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
4245                              (CPU_BASED_CR3_LOAD_EXITING |
4246                               CPU_BASED_CR3_STORE_EXITING));
4247                 vcpu->arch.cr0 = cr0;
4248                 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
4249         } else if (!is_paging(vcpu)) {
4250                 /* From nonpaging to paging */
4251                 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
4252                              vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
4253                              ~(CPU_BASED_CR3_LOAD_EXITING |
4254                                CPU_BASED_CR3_STORE_EXITING));
4255                 vcpu->arch.cr0 = cr0;
4256                 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
4257         }
4258
4259         if (!(cr0 & X86_CR0_WP))
4260                 *hw_cr0 &= ~X86_CR0_WP;
4261 }
4262
4263 static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
4264 {
4265         struct vcpu_vmx *vmx = to_vmx(vcpu);
4266         unsigned long hw_cr0;
4267
4268         hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK);
4269         if (enable_unrestricted_guest)
4270                 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
4271         else {
4272                 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
4273
4274                 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
4275                         enter_pmode(vcpu);
4276
4277                 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
4278                         enter_rmode(vcpu);
4279         }
4280
4281 #ifdef CONFIG_X86_64
4282         if (vcpu->arch.efer & EFER_LME) {
4283                 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
4284                         enter_lmode(vcpu);
4285                 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
4286                         exit_lmode(vcpu);
4287         }
4288 #endif
4289
4290         if (enable_ept)
4291                 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
4292
4293         vmcs_writel(CR0_READ_SHADOW, cr0);
4294         vmcs_writel(GUEST_CR0, hw_cr0);
4295         vcpu->arch.cr0 = cr0;
4296
4297         /* depends on vcpu->arch.cr0 to be set to a new value */
4298         vmx->emulation_required = emulation_required(vcpu);
4299 }
4300
4301 static int get_ept_level(struct kvm_vcpu *vcpu)
4302 {
4303         if (cpu_has_vmx_ept_5levels() && (cpuid_maxphyaddr(vcpu) > 48))
4304                 return 5;
4305         return 4;
4306 }
4307
4308 static u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa)
4309 {
4310         u64 eptp = VMX_EPTP_MT_WB;
4311
4312         eptp |= (get_ept_level(vcpu) == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
4313
4314         if (enable_ept_ad_bits &&
4315             (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
4316                 eptp |= VMX_EPTP_AD_ENABLE_BIT;
4317         eptp |= (root_hpa & PAGE_MASK);
4318
4319         return eptp;
4320 }
4321
4322 static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
4323 {
4324         unsigned long guest_cr3;
4325         u64 eptp;
4326
4327         guest_cr3 = cr3;
4328         if (enable_ept) {
4329                 eptp = construct_eptp(vcpu, cr3);
4330                 vmcs_write64(EPT_POINTER, eptp);
4331                 if (is_paging(vcpu) || is_guest_mode(vcpu))
4332                         guest_cr3 = kvm_read_cr3(vcpu);
4333                 else
4334                         guest_cr3 = vcpu->kvm->arch.ept_identity_map_addr;
4335                 ept_load_pdptrs(vcpu);
4336         }
4337
4338         vmx_flush_tlb(vcpu);
4339         vmcs_writel(GUEST_CR3, guest_cr3);
4340 }
4341
4342 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
4343 {
4344         /*
4345          * Pass through host's Machine Check Enable value to hw_cr4, which
4346          * is in force while we are in guest mode.  Do not let guests control
4347          * this bit, even if host CR4.MCE == 0.
4348          */
4349         unsigned long hw_cr4 =
4350                 (cr4_read_shadow() & X86_CR4_MCE) |
4351                 (cr4 & ~X86_CR4_MCE) |
4352                 (to_vmx(vcpu)->rmode.vm86_active ?
4353                  KVM_RMODE_VM_CR4_ALWAYS_ON : KVM_PMODE_VM_CR4_ALWAYS_ON);
4354
4355         if (cr4 & X86_CR4_VMXE) {
4356                 /*
4357                  * To use VMXON (and later other VMX instructions), a guest
4358                  * must first be able to turn on cr4.VMXE (see handle_vmon()).
4359                  * So basically the check on whether to allow nested VMX
4360                  * is here.
4361                  */
4362                 if (!nested_vmx_allowed(vcpu))
4363                         return 1;
4364         }
4365
4366         if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
4367                 return 1;
4368
4369         vcpu->arch.cr4 = cr4;
4370         if (enable_ept) {
4371                 if (!is_paging(vcpu)) {
4372                         hw_cr4 &= ~X86_CR4_PAE;
4373                         hw_cr4 |= X86_CR4_PSE;
4374                 } else if (!(cr4 & X86_CR4_PAE)) {
4375                         hw_cr4 &= ~X86_CR4_PAE;
4376                 }
4377         }
4378
4379         if (!enable_unrestricted_guest && !is_paging(vcpu))
4380                 /*
4381                  * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
4382                  * hardware.  To emulate this behavior, SMEP/SMAP/PKU needs
4383                  * to be manually disabled when guest switches to non-paging
4384                  * mode.
4385                  *
4386                  * If !enable_unrestricted_guest, the CPU is always running
4387                  * with CR0.PG=1 and CR4 needs to be modified.
4388                  * If enable_unrestricted_guest, the CPU automatically
4389                  * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
4390                  */
4391                 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
4392
4393         vmcs_writel(CR4_READ_SHADOW, cr4);
4394         vmcs_writel(GUEST_CR4, hw_cr4);
4395         return 0;
4396 }
4397
4398 static void vmx_get_segment(struct kvm_vcpu *vcpu,
4399                             struct kvm_segment *var, int seg)
4400 {
4401         struct vcpu_vmx *vmx = to_vmx(vcpu);
4402         u32 ar;
4403
4404         if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
4405                 *var = vmx->rmode.segs[seg];
4406                 if (seg == VCPU_SREG_TR
4407                     || var->selector == vmx_read_guest_seg_selector(vmx, seg))
4408                         return;
4409                 var->base = vmx_read_guest_seg_base(vmx, seg);
4410                 var->selector = vmx_read_guest_seg_selector(vmx, seg);
4411                 return;
4412         }
4413         var->base = vmx_read_guest_seg_base(vmx, seg);
4414         var->limit = vmx_read_guest_seg_limit(vmx, seg);
4415         var->selector = vmx_read_guest_seg_selector(vmx, seg);
4416         ar = vmx_read_guest_seg_ar(vmx, seg);
4417         var->unusable = (ar >> 16) & 1;
4418         var->type = ar & 15;
4419         var->s = (ar >> 4) & 1;
4420         var->dpl = (ar >> 5) & 3;
4421         /*
4422          * Some userspaces do not preserve unusable property. Since usable
4423          * segment has to be present according to VMX spec we can use present
4424          * property to amend userspace bug by making unusable segment always
4425          * nonpresent. vmx_segment_access_rights() already marks nonpresent
4426          * segment as unusable.
4427          */
4428         var->present = !var->unusable;
4429         var->avl = (ar >> 12) & 1;
4430         var->l = (ar >> 13) & 1;
4431         var->db = (ar >> 14) & 1;
4432         var->g = (ar >> 15) & 1;
4433 }
4434
4435 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
4436 {
4437         struct kvm_segment s;
4438
4439         if (to_vmx(vcpu)->rmode.vm86_active) {
4440                 vmx_get_segment(vcpu, &s, seg);
4441                 return s.base;
4442         }
4443         return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
4444 }
4445
4446 static int vmx_get_cpl(struct kvm_vcpu *vcpu)
4447 {
4448         struct vcpu_vmx *vmx = to_vmx(vcpu);
4449
4450         if (unlikely(vmx->rmode.vm86_active))
4451                 return 0;
4452         else {
4453                 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
4454                 return VMX_AR_DPL(ar);
4455         }
4456 }
4457
4458 static u32 vmx_segment_access_rights(struct kvm_segment *var)
4459 {
4460         u32 ar;
4461
4462         if (var->unusable || !var->present)
4463                 ar = 1 << 16;
4464         else {
4465                 ar = var->type & 15;
4466                 ar |= (var->s & 1) << 4;
4467                 ar |= (var->dpl & 3) << 5;
4468                 ar |= (var->present & 1) << 7;
4469                 ar |= (var->avl & 1) << 12;
4470                 ar |= (var->l & 1) << 13;
4471                 ar |= (var->db & 1) << 14;
4472                 ar |= (var->g & 1) << 15;
4473         }
4474
4475         return ar;
4476 }
4477
4478 static void vmx_set_segment(struct kvm_vcpu *vcpu,
4479                             struct kvm_segment *var, int seg)
4480 {
4481         struct vcpu_vmx *vmx = to_vmx(vcpu);
4482         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
4483
4484         vmx_segment_cache_clear(vmx);
4485
4486         if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
4487                 vmx->rmode.segs[seg] = *var;
4488                 if (seg == VCPU_SREG_TR)
4489                         vmcs_write16(sf->selector, var->selector);
4490                 else if (var->s)
4491                         fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
4492                 goto out;
4493         }
4494
4495         vmcs_writel(sf->base, var->base);
4496         vmcs_write32(sf->limit, var->limit);
4497         vmcs_write16(sf->selector, var->selector);
4498
4499         /*
4500          *   Fix the "Accessed" bit in AR field of segment registers for older
4501          * qemu binaries.
4502          *   IA32 arch specifies that at the time of processor reset the
4503          * "Accessed" bit in the AR field of segment registers is 1. And qemu
4504          * is setting it to 0 in the userland code. This causes invalid guest
4505          * state vmexit when "unrestricted guest" mode is turned on.
4506          *    Fix for this setup issue in cpu_reset is being pushed in the qemu
4507          * tree. Newer qemu binaries with that qemu fix would not need this
4508          * kvm hack.
4509          */
4510         if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
4511                 var->type |= 0x1; /* Accessed */
4512
4513         vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
4514
4515 out:
4516         vmx->emulation_required = emulation_required(vcpu);
4517 }
4518
4519 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
4520 {
4521         u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
4522
4523         *db = (ar >> 14) & 1;
4524         *l = (ar >> 13) & 1;
4525 }
4526
4527 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4528 {
4529         dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
4530         dt->address = vmcs_readl(GUEST_IDTR_BASE);
4531 }
4532
4533 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4534 {
4535         vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
4536         vmcs_writel(GUEST_IDTR_BASE, dt->address);
4537 }
4538
4539 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4540 {
4541         dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
4542         dt->address = vmcs_readl(GUEST_GDTR_BASE);
4543 }
4544
4545 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4546 {
4547         vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
4548         vmcs_writel(GUEST_GDTR_BASE, dt->address);
4549 }
4550
4551 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
4552 {
4553         struct kvm_segment var;
4554         u32 ar;
4555
4556         vmx_get_segment(vcpu, &var, seg);
4557         var.dpl = 0x3;
4558         if (seg == VCPU_SREG_CS)
4559                 var.type = 0x3;
4560         ar = vmx_segment_access_rights(&var);
4561
4562         if (var.base != (var.selector << 4))
4563                 return false;
4564         if (var.limit != 0xffff)
4565                 return false;
4566         if (ar != 0xf3)
4567                 return false;
4568
4569         return true;
4570 }
4571
4572 static bool code_segment_valid(struct kvm_vcpu *vcpu)
4573 {
4574         struct kvm_segment cs;
4575         unsigned int cs_rpl;
4576
4577         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
4578         cs_rpl = cs.selector & SEGMENT_RPL_MASK;
4579
4580         if (cs.unusable)
4581                 return false;
4582         if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
4583                 return false;
4584         if (!cs.s)
4585                 return false;
4586         if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
4587                 if (cs.dpl > cs_rpl)
4588                         return false;
4589         } else {
4590                 if (cs.dpl != cs_rpl)
4591                         return false;
4592         }
4593         if (!cs.present)
4594                 return false;
4595
4596         /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
4597         return true;
4598 }
4599
4600 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
4601 {
4602         struct kvm_segment ss;
4603         unsigned int ss_rpl;
4604
4605         vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
4606         ss_rpl = ss.selector & SEGMENT_RPL_MASK;
4607
4608         if (ss.unusable)
4609                 return true;
4610         if (ss.type != 3 && ss.type != 7)
4611                 return false;
4612         if (!ss.s)
4613                 return false;
4614         if (ss.dpl != ss_rpl) /* DPL != RPL */
4615                 return false;
4616         if (!ss.present)
4617                 return false;
4618
4619         return true;
4620 }
4621
4622 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
4623 {
4624         struct kvm_segment var;
4625         unsigned int rpl;
4626
4627         vmx_get_segment(vcpu, &var, seg);
4628         rpl = var.selector & SEGMENT_RPL_MASK;
4629
4630         if (var.unusable)
4631                 return true;
4632         if (!var.s)
4633                 return false;
4634         if (!var.present)
4635                 return false;
4636         if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
4637                 if (var.dpl < rpl) /* DPL < RPL */
4638                         return false;
4639         }
4640
4641         /* TODO: Add other members to kvm_segment_field to allow checking for other access
4642          * rights flags
4643          */
4644         return true;
4645 }
4646
4647 static bool tr_valid(struct kvm_vcpu *vcpu)
4648 {
4649         struct kvm_segment tr;
4650
4651         vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
4652
4653         if (tr.unusable)
4654                 return false;
4655         if (tr.selector & SEGMENT_TI_MASK)      /* TI = 1 */
4656                 return false;
4657         if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
4658                 return false;
4659         if (!tr.present)
4660                 return false;
4661
4662         return true;
4663 }
4664
4665 static bool ldtr_valid(struct kvm_vcpu *vcpu)
4666 {
4667         struct kvm_segment ldtr;
4668
4669         vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
4670
4671         if (ldtr.unusable)
4672                 return true;
4673         if (ldtr.selector & SEGMENT_TI_MASK)    /* TI = 1 */
4674                 return false;
4675         if (ldtr.type != 2)
4676                 return false;
4677         if (!ldtr.present)
4678                 return false;
4679
4680         return true;
4681 }
4682
4683 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
4684 {
4685         struct kvm_segment cs, ss;
4686
4687         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
4688         vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
4689
4690         return ((cs.selector & SEGMENT_RPL_MASK) ==
4691                  (ss.selector & SEGMENT_RPL_MASK));
4692 }
4693
4694 /*
4695  * Check if guest state is valid. Returns true if valid, false if
4696  * not.
4697  * We assume that registers are always usable
4698  */
4699 static bool guest_state_valid(struct kvm_vcpu *vcpu)
4700 {
4701         if (enable_unrestricted_guest)
4702                 return true;
4703
4704         /* real mode guest state checks */
4705         if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
4706                 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
4707                         return false;
4708                 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
4709                         return false;
4710                 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
4711                         return false;
4712                 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
4713                         return false;
4714                 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
4715                         return false;
4716                 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
4717                         return false;
4718         } else {
4719         /* protected mode guest state checks */
4720                 if (!cs_ss_rpl_check(vcpu))
4721                         return false;
4722                 if (!code_segment_valid(vcpu))
4723                         return false;
4724                 if (!stack_segment_valid(vcpu))
4725                         return false;
4726                 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
4727                         return false;
4728                 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
4729                         return false;
4730                 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
4731                         return false;
4732                 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
4733                         return false;
4734                 if (!tr_valid(vcpu))
4735                         return false;
4736                 if (!ldtr_valid(vcpu))
4737                         return false;
4738         }
4739         /* TODO:
4740          * - Add checks on RIP
4741          * - Add checks on RFLAGS
4742          */
4743
4744         return true;
4745 }
4746
4747 static bool page_address_valid(struct kvm_vcpu *vcpu, gpa_t gpa)
4748 {
4749         return PAGE_ALIGNED(gpa) && !(gpa >> cpuid_maxphyaddr(vcpu));
4750 }
4751
4752 static int init_rmode_tss(struct kvm *kvm)
4753 {
4754         gfn_t fn;
4755         u16 data = 0;
4756         int idx, r;
4757
4758         idx = srcu_read_lock(&kvm->srcu);
4759         fn = kvm->arch.tss_addr >> PAGE_SHIFT;
4760         r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
4761         if (r < 0)
4762                 goto out;
4763         data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
4764         r = kvm_write_guest_page(kvm, fn++, &data,
4765                         TSS_IOPB_BASE_OFFSET, sizeof(u16));
4766         if (r < 0)
4767                 goto out;
4768         r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
4769         if (r < 0)
4770                 goto out;
4771         r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
4772         if (r < 0)
4773                 goto out;
4774         data = ~0;
4775         r = kvm_write_guest_page(kvm, fn, &data,
4776                                  RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
4777                                  sizeof(u8));
4778 out:
4779         srcu_read_unlock(&kvm->srcu, idx);
4780         return r;
4781 }
4782
4783 static int init_rmode_identity_map(struct kvm *kvm)
4784 {
4785         int i, idx, r = 0;
4786         kvm_pfn_t identity_map_pfn;
4787         u32 tmp;
4788
4789         if (!enable_ept)
4790                 return 0;
4791
4792         /* Protect kvm->arch.ept_identity_pagetable_done. */
4793         mutex_lock(&kvm->slots_lock);
4794
4795         if (likely(kvm->arch.ept_identity_pagetable_done))
4796                 goto out2;
4797
4798         identity_map_pfn = kvm->arch.ept_identity_map_addr >> PAGE_SHIFT;
4799
4800         r = alloc_identity_pagetable(kvm);
4801         if (r < 0)
4802                 goto out2;
4803
4804         idx = srcu_read_lock(&kvm->srcu);
4805         r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
4806         if (r < 0)
4807                 goto out;
4808         /* Set up identity-mapping pagetable for EPT in real mode */
4809         for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
4810                 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
4811                         _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
4812                 r = kvm_write_guest_page(kvm, identity_map_pfn,
4813                                 &tmp, i * sizeof(tmp), sizeof(tmp));
4814                 if (r < 0)
4815                         goto out;
4816         }
4817         kvm->arch.ept_identity_pagetable_done = true;
4818
4819 out:
4820         srcu_read_unlock(&kvm->srcu, idx);
4821
4822 out2:
4823         mutex_unlock(&kvm->slots_lock);
4824         return r;
4825 }
4826
4827 static void seg_setup(int seg)
4828 {
4829         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
4830         unsigned int ar;
4831
4832         vmcs_write16(sf->selector, 0);
4833         vmcs_writel(sf->base, 0);
4834         vmcs_write32(sf->limit, 0xffff);
4835         ar = 0x93;
4836         if (seg == VCPU_SREG_CS)
4837                 ar |= 0x08; /* code segment */
4838
4839         vmcs_write32(sf->ar_bytes, ar);
4840 }
4841
4842 static int alloc_apic_access_page(struct kvm *kvm)
4843 {
4844         struct page *page;
4845         int r = 0;
4846
4847         mutex_lock(&kvm->slots_lock);
4848         if (kvm->arch.apic_access_page_done)
4849                 goto out;
4850         r = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
4851                                     APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
4852         if (r)
4853                 goto out;
4854
4855         page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
4856         if (is_error_page(page)) {
4857                 r = -EFAULT;
4858                 goto out;
4859         }
4860
4861         /*
4862          * Do not pin the page in memory, so that memory hot-unplug
4863          * is able to migrate it.
4864          */
4865         put_page(page);
4866         kvm->arch.apic_access_page_done = true;
4867 out:
4868         mutex_unlock(&kvm->slots_lock);
4869         return r;
4870 }
4871
4872 static int alloc_identity_pagetable(struct kvm *kvm)
4873 {
4874         /* Called with kvm->slots_lock held. */
4875
4876         int r = 0;
4877
4878         BUG_ON(kvm->arch.ept_identity_pagetable_done);
4879
4880         r = __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
4881                                     kvm->arch.ept_identity_map_addr, PAGE_SIZE);
4882
4883         return r;
4884 }
4885
4886 static int allocate_vpid(void)
4887 {
4888         int vpid;
4889
4890         if (!enable_vpid)
4891                 return 0;
4892         spin_lock(&vmx_vpid_lock);
4893         vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
4894         if (vpid < VMX_NR_VPIDS)
4895                 __set_bit(vpid, vmx_vpid_bitmap);
4896         else
4897                 vpid = 0;
4898         spin_unlock(&vmx_vpid_lock);
4899         return vpid;
4900 }
4901
4902 static void free_vpid(int vpid)
4903 {
4904         if (!enable_vpid || vpid == 0)
4905                 return;
4906         spin_lock(&vmx_vpid_lock);
4907         __clear_bit(vpid, vmx_vpid_bitmap);
4908         spin_unlock(&vmx_vpid_lock);
4909 }
4910
4911 #define MSR_TYPE_R      1
4912 #define MSR_TYPE_W      2
4913 static void __vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
4914                                                 u32 msr, int type)
4915 {
4916         int f = sizeof(unsigned long);
4917
4918         if (!cpu_has_vmx_msr_bitmap())
4919                 return;
4920
4921         /*
4922          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
4923          * have the write-low and read-high bitmap offsets the wrong way round.
4924          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
4925          */
4926         if (msr <= 0x1fff) {
4927                 if (type & MSR_TYPE_R)
4928                         /* read-low */
4929                         __clear_bit(msr, msr_bitmap + 0x000 / f);
4930
4931                 if (type & MSR_TYPE_W)
4932                         /* write-low */
4933                         __clear_bit(msr, msr_bitmap + 0x800 / f);
4934
4935         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
4936                 msr &= 0x1fff;
4937                 if (type & MSR_TYPE_R)
4938                         /* read-high */
4939                         __clear_bit(msr, msr_bitmap + 0x400 / f);
4940
4941                 if (type & MSR_TYPE_W)
4942                         /* write-high */
4943                         __clear_bit(msr, msr_bitmap + 0xc00 / f);
4944
4945         }
4946 }
4947
4948 /*
4949  * If a msr is allowed by L0, we should check whether it is allowed by L1.
4950  * The corresponding bit will be cleared unless both of L0 and L1 allow it.
4951  */
4952 static void nested_vmx_disable_intercept_for_msr(unsigned long *msr_bitmap_l1,
4953                                                unsigned long *msr_bitmap_nested,
4954                                                u32 msr, int type)
4955 {
4956         int f = sizeof(unsigned long);
4957
4958         if (!cpu_has_vmx_msr_bitmap()) {
4959                 WARN_ON(1);
4960                 return;
4961         }
4962
4963         /*
4964          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
4965          * have the write-low and read-high bitmap offsets the wrong way round.
4966          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
4967          */
4968         if (msr <= 0x1fff) {
4969                 if (type & MSR_TYPE_R &&
4970                    !test_bit(msr, msr_bitmap_l1 + 0x000 / f))
4971                         /* read-low */
4972                         __clear_bit(msr, msr_bitmap_nested + 0x000 / f);
4973
4974                 if (type & MSR_TYPE_W &&
4975                    !test_bit(msr, msr_bitmap_l1 + 0x800 / f))
4976                         /* write-low */
4977                         __clear_bit(msr, msr_bitmap_nested + 0x800 / f);
4978
4979         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
4980                 msr &= 0x1fff;
4981                 if (type & MSR_TYPE_R &&
4982                    !test_bit(msr, msr_bitmap_l1 + 0x400 / f))
4983                         /* read-high */
4984                         __clear_bit(msr, msr_bitmap_nested + 0x400 / f);
4985
4986                 if (type & MSR_TYPE_W &&
4987                    !test_bit(msr, msr_bitmap_l1 + 0xc00 / f))
4988                         /* write-high */
4989                         __clear_bit(msr, msr_bitmap_nested + 0xc00 / f);
4990
4991         }
4992 }
4993
4994 static void vmx_disable_intercept_for_msr(u32 msr, bool longmode_only)
4995 {
4996         if (!longmode_only)
4997                 __vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy,
4998                                                 msr, MSR_TYPE_R | MSR_TYPE_W);
4999         __vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode,
5000                                                 msr, MSR_TYPE_R | MSR_TYPE_W);
5001 }
5002
5003 static void vmx_disable_intercept_msr_x2apic(u32 msr, int type, bool apicv_active)
5004 {
5005         if (apicv_active) {
5006                 __vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic_apicv,
5007                                 msr, type);
5008                 __vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic_apicv,
5009                                 msr, type);
5010         } else {
5011                 __vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic,
5012                                 msr, type);
5013                 __vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic,
5014                                 msr, type);
5015         }
5016 }
5017
5018 static bool vmx_get_enable_apicv(struct kvm_vcpu *vcpu)
5019 {
5020         return enable_apicv;
5021 }
5022
5023 static void nested_mark_vmcs12_pages_dirty(struct kvm_vcpu *vcpu)
5024 {
5025         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5026         gfn_t gfn;
5027
5028         /*
5029          * Don't need to mark the APIC access page dirty; it is never
5030          * written to by the CPU during APIC virtualization.
5031          */
5032
5033         if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
5034                 gfn = vmcs12->virtual_apic_page_addr >> PAGE_SHIFT;
5035                 kvm_vcpu_mark_page_dirty(vcpu, gfn);
5036         }
5037
5038         if (nested_cpu_has_posted_intr(vmcs12)) {
5039                 gfn = vmcs12->posted_intr_desc_addr >> PAGE_SHIFT;
5040                 kvm_vcpu_mark_page_dirty(vcpu, gfn);
5041         }
5042 }
5043
5044
5045 static void vmx_complete_nested_posted_interrupt(struct kvm_vcpu *vcpu)
5046 {
5047         struct vcpu_vmx *vmx = to_vmx(vcpu);
5048         int max_irr;
5049         void *vapic_page;
5050         u16 status;
5051
5052         if (!vmx->nested.pi_desc || !vmx->nested.pi_pending)
5053                 return;
5054
5055         vmx->nested.pi_pending = false;
5056         if (!pi_test_and_clear_on(vmx->nested.pi_desc))
5057                 return;
5058
5059         max_irr = find_last_bit((unsigned long *)vmx->nested.pi_desc->pir, 256);
5060         if (max_irr != 256) {
5061                 vapic_page = kmap(vmx->nested.virtual_apic_page);
5062                 __kvm_apic_update_irr(vmx->nested.pi_desc->pir, vapic_page);
5063                 kunmap(vmx->nested.virtual_apic_page);
5064
5065                 status = vmcs_read16(GUEST_INTR_STATUS);
5066                 if ((u8)max_irr > ((u8)status & 0xff)) {
5067                         status &= ~0xff;
5068                         status |= (u8)max_irr;
5069                         vmcs_write16(GUEST_INTR_STATUS, status);
5070                 }
5071         }
5072
5073         nested_mark_vmcs12_pages_dirty(vcpu);
5074 }
5075
5076 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
5077                                                      bool nested)
5078 {
5079 #ifdef CONFIG_SMP
5080         int pi_vec = nested ? POSTED_INTR_NESTED_VECTOR : POSTED_INTR_VECTOR;
5081
5082         if (vcpu->mode == IN_GUEST_MODE) {
5083                 /*
5084                  * The vector of interrupt to be delivered to vcpu had
5085                  * been set in PIR before this function.
5086                  *
5087                  * Following cases will be reached in this block, and
5088                  * we always send a notification event in all cases as
5089                  * explained below.
5090                  *
5091                  * Case 1: vcpu keeps in non-root mode. Sending a
5092                  * notification event posts the interrupt to vcpu.
5093                  *
5094                  * Case 2: vcpu exits to root mode and is still
5095                  * runnable. PIR will be synced to vIRR before the
5096                  * next vcpu entry. Sending a notification event in
5097                  * this case has no effect, as vcpu is not in root
5098                  * mode.
5099                  *
5100                  * Case 3: vcpu exits to root mode and is blocked.
5101                  * vcpu_block() has already synced PIR to vIRR and
5102                  * never blocks vcpu if vIRR is not cleared. Therefore,
5103                  * a blocked vcpu here does not wait for any requested
5104                  * interrupts in PIR, and sending a notification event
5105                  * which has no effect is safe here.
5106                  */
5107
5108                 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
5109                 return true;
5110         }
5111 #endif
5112         return false;
5113 }
5114
5115 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
5116                                                 int vector)
5117 {
5118         struct vcpu_vmx *vmx = to_vmx(vcpu);
5119
5120         if (is_guest_mode(vcpu) &&
5121             vector == vmx->nested.posted_intr_nv) {
5122                 /* the PIR and ON have been set by L1. */
5123                 kvm_vcpu_trigger_posted_interrupt(vcpu, true);
5124                 /*
5125                  * If a posted intr is not recognized by hardware,
5126                  * we will accomplish it in the next vmentry.
5127                  */
5128                 vmx->nested.pi_pending = true;
5129                 kvm_make_request(KVM_REQ_EVENT, vcpu);
5130                 return 0;
5131         }
5132         return -1;
5133 }
5134 /*
5135  * Send interrupt to vcpu via posted interrupt way.
5136  * 1. If target vcpu is running(non-root mode), send posted interrupt
5137  * notification to vcpu and hardware will sync PIR to vIRR atomically.
5138  * 2. If target vcpu isn't running(root mode), kick it to pick up the
5139  * interrupt from PIR in next vmentry.
5140  */
5141 static void vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
5142 {
5143         struct vcpu_vmx *vmx = to_vmx(vcpu);
5144         int r;
5145
5146         r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
5147         if (!r)
5148                 return;
5149
5150         if (pi_test_and_set_pir(vector, &vmx->pi_desc))
5151                 return;
5152
5153         /* If a previous notification has sent the IPI, nothing to do.  */
5154         if (pi_test_and_set_on(&vmx->pi_desc))
5155                 return;
5156
5157         if (!kvm_vcpu_trigger_posted_interrupt(vcpu, false))
5158                 kvm_vcpu_kick(vcpu);
5159 }
5160
5161 /*
5162  * Set up the vmcs's constant host-state fields, i.e., host-state fields that
5163  * will not change in the lifetime of the guest.
5164  * Note that host-state that does change is set elsewhere. E.g., host-state
5165  * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
5166  */
5167 static void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
5168 {
5169         u32 low32, high32;
5170         unsigned long tmpl;
5171         struct desc_ptr dt;
5172         unsigned long cr0, cr3, cr4;
5173
5174         cr0 = read_cr0();
5175         WARN_ON(cr0 & X86_CR0_TS);
5176         vmcs_writel(HOST_CR0, cr0);  /* 22.2.3 */
5177
5178         /*
5179          * Save the most likely value for this task's CR3 in the VMCS.
5180          * We can't use __get_current_cr3_fast() because we're not atomic.
5181          */
5182         cr3 = __read_cr3();
5183         vmcs_writel(HOST_CR3, cr3);             /* 22.2.3  FIXME: shadow tables */
5184         vmx->loaded_vmcs->vmcs_host_cr3 = cr3;
5185
5186         /* Save the most likely value for this task's CR4 in the VMCS. */
5187         cr4 = cr4_read_shadow();
5188         vmcs_writel(HOST_CR4, cr4);                     /* 22.2.3, 22.2.5 */
5189         vmx->loaded_vmcs->vmcs_host_cr4 = cr4;
5190
5191         vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS);  /* 22.2.4 */
5192 #ifdef CONFIG_X86_64
5193         /*
5194          * Load null selectors, so we can avoid reloading them in
5195          * __vmx_load_host_state(), in case userspace uses the null selectors
5196          * too (the expected case).
5197          */
5198         vmcs_write16(HOST_DS_SELECTOR, 0);
5199         vmcs_write16(HOST_ES_SELECTOR, 0);
5200 #else
5201         vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
5202         vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
5203 #endif
5204         vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
5205         vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8);  /* 22.2.4 */
5206
5207         store_idt(&dt);
5208         vmcs_writel(HOST_IDTR_BASE, dt.address);   /* 22.2.4 */
5209         vmx->host_idt_base = dt.address;
5210
5211         vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */
5212
5213         rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
5214         vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
5215         rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
5216         vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl);   /* 22.2.3 */
5217
5218         if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
5219                 rdmsr(MSR_IA32_CR_PAT, low32, high32);
5220                 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
5221         }
5222 }
5223
5224 static void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
5225 {
5226         vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
5227         if (enable_ept)
5228                 vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
5229         if (is_guest_mode(&vmx->vcpu))
5230                 vmx->vcpu.arch.cr4_guest_owned_bits &=
5231                         ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
5232         vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
5233 }
5234
5235 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
5236 {
5237         u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
5238
5239         if (!kvm_vcpu_apicv_active(&vmx->vcpu))
5240                 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
5241         /* Enable the preemption timer dynamically */
5242         pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
5243         return pin_based_exec_ctrl;
5244 }
5245
5246 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
5247 {
5248         struct vcpu_vmx *vmx = to_vmx(vcpu);
5249
5250         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
5251         if (cpu_has_secondary_exec_ctrls()) {
5252                 if (kvm_vcpu_apicv_active(vcpu))
5253                         vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
5254                                       SECONDARY_EXEC_APIC_REGISTER_VIRT |
5255                                       SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
5256                 else
5257                         vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
5258                                         SECONDARY_EXEC_APIC_REGISTER_VIRT |
5259                                         SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
5260         }
5261
5262         if (cpu_has_vmx_msr_bitmap())
5263                 vmx_set_msr_bitmap(vcpu);
5264 }
5265
5266 static u32 vmx_exec_control(struct vcpu_vmx *vmx)
5267 {
5268         u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
5269
5270         if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
5271                 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
5272
5273         if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
5274                 exec_control &= ~CPU_BASED_TPR_SHADOW;
5275 #ifdef CONFIG_X86_64
5276                 exec_control |= CPU_BASED_CR8_STORE_EXITING |
5277                                 CPU_BASED_CR8_LOAD_EXITING;
5278 #endif
5279         }
5280         if (!enable_ept)
5281                 exec_control |= CPU_BASED_CR3_STORE_EXITING |
5282                                 CPU_BASED_CR3_LOAD_EXITING  |
5283                                 CPU_BASED_INVLPG_EXITING;
5284         return exec_control;
5285 }
5286
5287 static bool vmx_rdrand_supported(void)
5288 {
5289         return vmcs_config.cpu_based_2nd_exec_ctrl &
5290                 SECONDARY_EXEC_RDRAND;
5291 }
5292
5293 static bool vmx_rdseed_supported(void)
5294 {
5295         return vmcs_config.cpu_based_2nd_exec_ctrl &
5296                 SECONDARY_EXEC_RDSEED;
5297 }
5298
5299 static void vmx_compute_secondary_exec_control(struct vcpu_vmx *vmx)
5300 {
5301         struct kvm_vcpu *vcpu = &vmx->vcpu;
5302
5303         u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
5304         if (!cpu_need_virtualize_apic_accesses(vcpu))
5305                 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
5306         if (vmx->vpid == 0)
5307                 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
5308         if (!enable_ept) {
5309                 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
5310                 enable_unrestricted_guest = 0;
5311                 /* Enable INVPCID for non-ept guests may cause performance regression. */
5312                 exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
5313         }
5314         if (!enable_unrestricted_guest)
5315                 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
5316         if (!ple_gap)
5317                 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
5318         if (!kvm_vcpu_apicv_active(vcpu))
5319                 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
5320                                   SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
5321         exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
5322         /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
5323            (handle_vmptrld).
5324            We can NOT enable shadow_vmcs here because we don't have yet
5325            a current VMCS12
5326         */
5327         exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
5328
5329         if (!enable_pml)
5330                 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
5331
5332         if (vmx_xsaves_supported()) {
5333                 /* Exposing XSAVES only when XSAVE is exposed */
5334                 bool xsaves_enabled =
5335                         guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
5336                         guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
5337
5338                 if (!xsaves_enabled)
5339                         exec_control &= ~SECONDARY_EXEC_XSAVES;
5340
5341                 if (nested) {
5342                         if (xsaves_enabled)
5343                                 vmx->nested.nested_vmx_secondary_ctls_high |=
5344                                         SECONDARY_EXEC_XSAVES;
5345                         else
5346                                 vmx->nested.nested_vmx_secondary_ctls_high &=
5347                                         ~SECONDARY_EXEC_XSAVES;
5348                 }
5349         }
5350
5351         if (vmx_rdtscp_supported()) {
5352                 bool rdtscp_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP);
5353                 if (!rdtscp_enabled)
5354                         exec_control &= ~SECONDARY_EXEC_RDTSCP;
5355
5356                 if (nested) {
5357                         if (rdtscp_enabled)
5358                                 vmx->nested.nested_vmx_secondary_ctls_high |=
5359                                         SECONDARY_EXEC_RDTSCP;
5360                         else
5361                                 vmx->nested.nested_vmx_secondary_ctls_high &=
5362                                         ~SECONDARY_EXEC_RDTSCP;
5363                 }
5364         }
5365
5366         if (vmx_invpcid_supported()) {
5367                 /* Exposing INVPCID only when PCID is exposed */
5368                 bool invpcid_enabled =
5369                         guest_cpuid_has(vcpu, X86_FEATURE_INVPCID) &&
5370                         guest_cpuid_has(vcpu, X86_FEATURE_PCID);
5371
5372                 if (!invpcid_enabled) {
5373                         exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
5374                         guest_cpuid_clear(vcpu, X86_FEATURE_INVPCID);
5375                 }
5376
5377                 if (nested) {
5378                         if (invpcid_enabled)
5379                                 vmx->nested.nested_vmx_secondary_ctls_high |=
5380                                         SECONDARY_EXEC_ENABLE_INVPCID;
5381                         else
5382                                 vmx->nested.nested_vmx_secondary_ctls_high &=
5383                                         ~SECONDARY_EXEC_ENABLE_INVPCID;
5384                 }
5385         }
5386
5387         if (vmx_rdrand_supported()) {
5388                 bool rdrand_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDRAND);
5389                 if (rdrand_enabled)
5390                         exec_control &= ~SECONDARY_EXEC_RDRAND;
5391
5392                 if (nested) {
5393                         if (rdrand_enabled)
5394                                 vmx->nested.nested_vmx_secondary_ctls_high |=
5395                                         SECONDARY_EXEC_RDRAND;
5396                         else
5397                                 vmx->nested.nested_vmx_secondary_ctls_high &=
5398                                         ~SECONDARY_EXEC_RDRAND;
5399                 }
5400         }
5401
5402         if (vmx_rdseed_supported()) {
5403                 bool rdseed_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDSEED);
5404                 if (rdseed_enabled)
5405                         exec_control &= ~SECONDARY_EXEC_RDSEED;
5406
5407                 if (nested) {
5408                         if (rdseed_enabled)
5409                                 vmx->nested.nested_vmx_secondary_ctls_high |=
5410                                         SECONDARY_EXEC_RDSEED;
5411                         else
5412                                 vmx->nested.nested_vmx_secondary_ctls_high &=
5413                                         ~SECONDARY_EXEC_RDSEED;
5414                 }
5415         }
5416
5417         vmx->secondary_exec_control = exec_control;
5418 }
5419
5420 static void ept_set_mmio_spte_mask(void)
5421 {
5422         /*
5423          * EPT Misconfigurations can be generated if the value of bits 2:0
5424          * of an EPT paging-structure entry is 110b (write/execute).
5425          */
5426         kvm_mmu_set_mmio_spte_mask(VMX_EPT_RWX_MASK,
5427                                    VMX_EPT_MISCONFIG_WX_VALUE);
5428 }
5429
5430 #define VMX_XSS_EXIT_BITMAP 0
5431 /*
5432  * Sets up the vmcs for emulated real mode.
5433  */
5434 static int vmx_vcpu_setup(struct vcpu_vmx *vmx)
5435 {
5436 #ifdef CONFIG_X86_64
5437         unsigned long a;
5438 #endif
5439         int i;
5440
5441         /* I/O */
5442         vmcs_write64(IO_BITMAP_A, __pa(vmx_io_bitmap_a));
5443         vmcs_write64(IO_BITMAP_B, __pa(vmx_io_bitmap_b));
5444
5445         if (enable_shadow_vmcs) {
5446                 vmcs_write64(VMREAD_BITMAP, __pa(vmx_vmread_bitmap));
5447                 vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmwrite_bitmap));
5448         }
5449         if (cpu_has_vmx_msr_bitmap())
5450                 vmcs_write64(MSR_BITMAP, __pa(vmx_msr_bitmap_legacy));
5451
5452         vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
5453
5454         /* Control */
5455         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
5456         vmx->hv_deadline_tsc = -1;
5457
5458         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
5459
5460         if (cpu_has_secondary_exec_ctrls()) {
5461                 vmx_compute_secondary_exec_control(vmx);
5462                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
5463                              vmx->secondary_exec_control);
5464         }
5465
5466         if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
5467                 vmcs_write64(EOI_EXIT_BITMAP0, 0);
5468                 vmcs_write64(EOI_EXIT_BITMAP1, 0);
5469                 vmcs_write64(EOI_EXIT_BITMAP2, 0);
5470                 vmcs_write64(EOI_EXIT_BITMAP3, 0);
5471
5472                 vmcs_write16(GUEST_INTR_STATUS, 0);
5473
5474                 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
5475                 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
5476         }
5477
5478         if (ple_gap) {
5479                 vmcs_write32(PLE_GAP, ple_gap);
5480                 vmx->ple_window = ple_window;
5481                 vmx->ple_window_dirty = true;
5482         }
5483
5484         vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
5485         vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
5486         vmcs_write32(CR3_TARGET_COUNT, 0);           /* 22.2.1 */
5487
5488         vmcs_write16(HOST_FS_SELECTOR, 0);            /* 22.2.4 */
5489         vmcs_write16(HOST_GS_SELECTOR, 0);            /* 22.2.4 */
5490         vmx_set_constant_host_state(vmx);
5491 #ifdef CONFIG_X86_64
5492         rdmsrl(MSR_FS_BASE, a);
5493         vmcs_writel(HOST_FS_BASE, a); /* 22.2.4 */
5494         rdmsrl(MSR_GS_BASE, a);
5495         vmcs_writel(HOST_GS_BASE, a); /* 22.2.4 */
5496 #else
5497         vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
5498         vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
5499 #endif
5500
5501         if (cpu_has_vmx_vmfunc())
5502                 vmcs_write64(VM_FUNCTION_CONTROL, 0);
5503
5504         vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
5505         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
5506         vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host));
5507         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
5508         vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest));
5509
5510         if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
5511                 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
5512
5513         for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
5514                 u32 index = vmx_msr_index[i];
5515                 u32 data_low, data_high;
5516                 int j = vmx->nmsrs;
5517
5518                 if (rdmsr_safe(index, &data_low, &data_high) < 0)
5519                         continue;
5520                 if (wrmsr_safe(index, data_low, data_high) < 0)
5521                         continue;
5522                 vmx->guest_msrs[j].index = i;
5523                 vmx->guest_msrs[j].data = 0;
5524                 vmx->guest_msrs[j].mask = -1ull;
5525                 ++vmx->nmsrs;
5526         }
5527
5528
5529         vm_exit_controls_init(vmx, vmcs_config.vmexit_ctrl);
5530
5531         /* 22.2.1, 20.8.1 */
5532         vm_entry_controls_init(vmx, vmcs_config.vmentry_ctrl);
5533
5534         vmx->vcpu.arch.cr0_guest_owned_bits = X86_CR0_TS;
5535         vmcs_writel(CR0_GUEST_HOST_MASK, ~X86_CR0_TS);
5536
5537         set_cr4_guest_host_mask(vmx);
5538
5539         if (vmx_xsaves_supported())
5540                 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
5541
5542         if (enable_pml) {
5543                 ASSERT(vmx->pml_pg);
5544                 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
5545                 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
5546         }
5547
5548         return 0;
5549 }
5550
5551 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
5552 {
5553         struct vcpu_vmx *vmx = to_vmx(vcpu);
5554         struct msr_data apic_base_msr;
5555         u64 cr0;
5556
5557         vmx->rmode.vm86_active = 0;
5558
5559         vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
5560         kvm_set_cr8(vcpu, 0);
5561
5562         if (!init_event) {
5563                 apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
5564                                      MSR_IA32_APICBASE_ENABLE;
5565                 if (kvm_vcpu_is_reset_bsp(vcpu))
5566                         apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
5567                 apic_base_msr.host_initiated = true;
5568                 kvm_set_apic_base(vcpu, &apic_base_msr);
5569         }
5570
5571         vmx_segment_cache_clear(vmx);
5572
5573         seg_setup(VCPU_SREG_CS);
5574         vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
5575         vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
5576
5577         seg_setup(VCPU_SREG_DS);
5578         seg_setup(VCPU_SREG_ES);
5579         seg_setup(VCPU_SREG_FS);
5580         seg_setup(VCPU_SREG_GS);
5581         seg_setup(VCPU_SREG_SS);
5582
5583         vmcs_write16(GUEST_TR_SELECTOR, 0);
5584         vmcs_writel(GUEST_TR_BASE, 0);
5585         vmcs_write32(GUEST_TR_LIMIT, 0xffff);
5586         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
5587
5588         vmcs_write16(GUEST_LDTR_SELECTOR, 0);
5589         vmcs_writel(GUEST_LDTR_BASE, 0);
5590         vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
5591         vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
5592
5593         if (!init_event) {
5594                 vmcs_write32(GUEST_SYSENTER_CS, 0);
5595                 vmcs_writel(GUEST_SYSENTER_ESP, 0);
5596                 vmcs_writel(GUEST_SYSENTER_EIP, 0);
5597                 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
5598         }
5599
5600         vmcs_writel(GUEST_RFLAGS, 0x02);
5601         kvm_rip_write(vcpu, 0xfff0);
5602
5603         vmcs_writel(GUEST_GDTR_BASE, 0);
5604         vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
5605
5606         vmcs_writel(GUEST_IDTR_BASE, 0);
5607         vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
5608
5609         vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
5610         vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
5611         vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
5612
5613         setup_msrs(vmx);
5614
5615         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);  /* 22.2.1 */
5616
5617         if (cpu_has_vmx_tpr_shadow() && !init_event) {
5618                 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
5619                 if (cpu_need_tpr_shadow(vcpu))
5620                         vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
5621                                      __pa(vcpu->arch.apic->regs));
5622                 vmcs_write32(TPR_THRESHOLD, 0);
5623         }
5624
5625         kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
5626
5627         if (vmx->vpid != 0)
5628                 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
5629
5630         cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
5631         vmx->vcpu.arch.cr0 = cr0;
5632         vmx_set_cr0(vcpu, cr0); /* enter rmode */
5633         vmx_set_cr4(vcpu, 0);
5634         vmx_set_efer(vcpu, 0);
5635
5636         update_exception_bitmap(vcpu);
5637
5638         vpid_sync_context(vmx->vpid);
5639 }
5640
5641 /*
5642  * In nested virtualization, check if L1 asked to exit on external interrupts.
5643  * For most existing hypervisors, this will always return true.
5644  */
5645 static bool nested_exit_on_intr(struct kvm_vcpu *vcpu)
5646 {
5647         return get_vmcs12(vcpu)->pin_based_vm_exec_control &
5648                 PIN_BASED_EXT_INTR_MASK;
5649 }
5650
5651 /*
5652  * In nested virtualization, check if L1 has set
5653  * VM_EXIT_ACK_INTR_ON_EXIT
5654  */
5655 static bool nested_exit_intr_ack_set(struct kvm_vcpu *vcpu)
5656 {
5657         return get_vmcs12(vcpu)->vm_exit_controls &
5658                 VM_EXIT_ACK_INTR_ON_EXIT;
5659 }
5660
5661 static bool nested_exit_on_nmi(struct kvm_vcpu *vcpu)
5662 {
5663         return get_vmcs12(vcpu)->pin_based_vm_exec_control &
5664                 PIN_BASED_NMI_EXITING;
5665 }
5666
5667 static void enable_irq_window(struct kvm_vcpu *vcpu)
5668 {
5669         vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
5670                       CPU_BASED_VIRTUAL_INTR_PENDING);
5671 }
5672
5673 static void enable_nmi_window(struct kvm_vcpu *vcpu)
5674 {
5675         if (!cpu_has_virtual_nmis() ||
5676             vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
5677                 enable_irq_window(vcpu);
5678                 return;
5679         }
5680
5681         vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
5682                       CPU_BASED_VIRTUAL_NMI_PENDING);
5683 }
5684
5685 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
5686 {
5687         struct vcpu_vmx *vmx = to_vmx(vcpu);
5688         uint32_t intr;
5689         int irq = vcpu->arch.interrupt.nr;
5690
5691         trace_kvm_inj_virq(irq);
5692
5693         ++vcpu->stat.irq_injections;
5694         if (vmx->rmode.vm86_active) {
5695                 int inc_eip = 0;
5696                 if (vcpu->arch.interrupt.soft)
5697                         inc_eip = vcpu->arch.event_exit_inst_len;
5698                 if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE)
5699                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5700                 return;
5701         }
5702         intr = irq | INTR_INFO_VALID_MASK;
5703         if (vcpu->arch.interrupt.soft) {
5704                 intr |= INTR_TYPE_SOFT_INTR;
5705                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
5706                              vmx->vcpu.arch.event_exit_inst_len);
5707         } else
5708                 intr |= INTR_TYPE_EXT_INTR;
5709         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
5710 }
5711
5712 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
5713 {
5714         struct vcpu_vmx *vmx = to_vmx(vcpu);
5715
5716         if (!cpu_has_virtual_nmis()) {
5717                 /*
5718                  * Tracking the NMI-blocked state in software is built upon
5719                  * finding the next open IRQ window. This, in turn, depends on
5720                  * well-behaving guests: They have to keep IRQs disabled at
5721                  * least as long as the NMI handler runs. Otherwise we may
5722                  * cause NMI nesting, maybe breaking the guest. But as this is
5723                  * highly unlikely, we can live with the residual risk.
5724                  */
5725                 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
5726                 vmx->loaded_vmcs->vnmi_blocked_time = 0;
5727         }
5728
5729         ++vcpu->stat.nmi_injections;
5730         vmx->loaded_vmcs->nmi_known_unmasked = false;
5731
5732         if (vmx->rmode.vm86_active) {
5733                 if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE)
5734                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5735                 return;
5736         }
5737
5738         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
5739                         INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
5740 }
5741
5742 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
5743 {
5744         struct vcpu_vmx *vmx = to_vmx(vcpu);
5745         bool masked;
5746
5747         if (!cpu_has_virtual_nmis())
5748                 return vmx->loaded_vmcs->soft_vnmi_blocked;
5749         if (vmx->loaded_vmcs->nmi_known_unmasked)
5750                 return false;
5751         masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
5752         vmx->loaded_vmcs->nmi_known_unmasked = !masked;
5753         return masked;
5754 }
5755
5756 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
5757 {
5758         struct vcpu_vmx *vmx = to_vmx(vcpu);
5759
5760         if (!cpu_has_virtual_nmis()) {
5761                 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
5762                         vmx->loaded_vmcs->soft_vnmi_blocked = masked;
5763                         vmx->loaded_vmcs->vnmi_blocked_time = 0;
5764                 }
5765         } else {
5766                 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
5767                 if (masked)
5768                         vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5769                                       GUEST_INTR_STATE_NMI);
5770                 else
5771                         vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
5772                                         GUEST_INTR_STATE_NMI);
5773         }
5774 }
5775
5776 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
5777 {
5778         if (to_vmx(vcpu)->nested.nested_run_pending)
5779                 return 0;
5780
5781         if (!cpu_has_virtual_nmis() &&
5782             to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
5783                 return 0;
5784
5785         return  !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
5786                   (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
5787                    | GUEST_INTR_STATE_NMI));
5788 }
5789
5790 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
5791 {
5792         return (!to_vmx(vcpu)->nested.nested_run_pending &&
5793                 vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
5794                 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
5795                         (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
5796 }
5797
5798 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
5799 {
5800         int ret;
5801
5802         ret = x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
5803                                     PAGE_SIZE * 3);
5804         if (ret)
5805                 return ret;
5806         kvm->arch.tss_addr = addr;
5807         return init_rmode_tss(kvm);
5808 }
5809
5810 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
5811 {
5812         switch (vec) {
5813         case BP_VECTOR:
5814                 /*
5815                  * Update instruction length as we may reinject the exception
5816                  * from user space while in guest debugging mode.
5817                  */
5818                 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
5819                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
5820                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
5821                         return false;
5822                 /* fall through */
5823         case DB_VECTOR:
5824                 if (vcpu->guest_debug &
5825                         (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
5826                         return false;
5827                 /* fall through */
5828         case DE_VECTOR:
5829         case OF_VECTOR:
5830         case BR_VECTOR:
5831         case UD_VECTOR:
5832         case DF_VECTOR:
5833         case SS_VECTOR:
5834         case GP_VECTOR:
5835         case MF_VECTOR:
5836                 return true;
5837         break;
5838         }
5839         return false;
5840 }
5841
5842 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
5843                                   int vec, u32 err_code)
5844 {
5845         /*
5846          * Instruction with address size override prefix opcode 0x67
5847          * Cause the #SS fault with 0 error code in VM86 mode.
5848          */
5849         if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
5850                 if (emulate_instruction(vcpu, 0) == EMULATE_DONE) {
5851                         if (vcpu->arch.halt_request) {
5852                                 vcpu->arch.halt_request = 0;
5853                                 return kvm_vcpu_halt(vcpu);
5854                         }
5855                         return 1;
5856                 }
5857                 return 0;
5858         }
5859
5860         /*
5861          * Forward all other exceptions that are valid in real mode.
5862          * FIXME: Breaks guest debugging in real mode, needs to be fixed with
5863          *        the required debugging infrastructure rework.
5864          */
5865         kvm_queue_exception(vcpu, vec);
5866         return 1;
5867 }
5868
5869 /*
5870  * Trigger machine check on the host. We assume all the MSRs are already set up
5871  * by the CPU and that we still run on the same CPU as the MCE occurred on.
5872  * We pass a fake environment to the machine check handler because we want
5873  * the guest to be always treated like user space, no matter what context
5874  * it used internally.
5875  */
5876 static void kvm_machine_check(void)
5877 {
5878 #if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
5879         struct pt_regs regs = {
5880                 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
5881                 .flags = X86_EFLAGS_IF,
5882         };
5883
5884         do_machine_check(&regs, 0);
5885 #endif
5886 }
5887
5888 static int handle_machine_check(struct kvm_vcpu *vcpu)
5889 {
5890         /* already handled by vcpu_run */
5891         return 1;
5892 }
5893
5894 static int handle_exception(struct kvm_vcpu *vcpu)
5895 {
5896         struct vcpu_vmx *vmx = to_vmx(vcpu);
5897         struct kvm_run *kvm_run = vcpu->run;
5898         u32 intr_info, ex_no, error_code;
5899         unsigned long cr2, rip, dr6;
5900         u32 vect_info;
5901         enum emulation_result er;
5902
5903         vect_info = vmx->idt_vectoring_info;
5904         intr_info = vmx->exit_intr_info;
5905
5906         if (is_machine_check(intr_info))
5907                 return handle_machine_check(vcpu);
5908
5909         if (is_nmi(intr_info))
5910                 return 1;  /* already handled by vmx_vcpu_run() */
5911
5912         if (is_invalid_opcode(intr_info)) {
5913                 if (is_guest_mode(vcpu)) {
5914                         kvm_queue_exception(vcpu, UD_VECTOR);
5915                         return 1;
5916                 }
5917                 er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD);
5918                 if (er == EMULATE_USER_EXIT)
5919                         return 0;
5920                 if (er != EMULATE_DONE)
5921                         kvm_queue_exception(vcpu, UD_VECTOR);
5922                 return 1;
5923         }
5924
5925         error_code = 0;
5926         if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
5927                 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
5928
5929         /*
5930          * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
5931          * MMIO, it is better to report an internal error.
5932          * See the comments in vmx_handle_exit.
5933          */
5934         if ((vect_info & VECTORING_INFO_VALID_MASK) &&
5935             !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
5936                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5937                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
5938                 vcpu->run->internal.ndata = 3;
5939                 vcpu->run->internal.data[0] = vect_info;
5940                 vcpu->run->internal.data[1] = intr_info;
5941                 vcpu->run->internal.data[2] = error_code;
5942                 return 0;
5943         }
5944
5945         if (is_page_fault(intr_info)) {
5946                 cr2 = vmcs_readl(EXIT_QUALIFICATION);
5947                 /* EPT won't cause page fault directly */
5948                 WARN_ON_ONCE(!vcpu->arch.apf.host_apf_reason && enable_ept);
5949                 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0,
5950                                 true);
5951         }
5952
5953         ex_no = intr_info & INTR_INFO_VECTOR_MASK;
5954
5955         if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
5956                 return handle_rmode_exception(vcpu, ex_no, error_code);
5957
5958         switch (ex_no) {
5959         case AC_VECTOR:
5960                 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
5961                 return 1;
5962         case DB_VECTOR:
5963                 dr6 = vmcs_readl(EXIT_QUALIFICATION);
5964                 if (!(vcpu->guest_debug &
5965                       (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
5966                         vcpu->arch.dr6 &= ~15;
5967                         vcpu->arch.dr6 |= dr6 | DR6_RTM;
5968                         if (!(dr6 & ~DR6_RESERVED)) /* icebp */
5969                                 skip_emulated_instruction(vcpu);
5970
5971                         kvm_queue_exception(vcpu, DB_VECTOR);
5972                         return 1;
5973                 }
5974                 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
5975                 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
5976                 /* fall through */
5977         case BP_VECTOR:
5978                 /*
5979                  * Update instruction length as we may reinject #BP from
5980                  * user space while in guest debugging mode. Reading it for
5981                  * #DB as well causes no harm, it is not used in that case.
5982                  */
5983                 vmx->vcpu.arch.event_exit_inst_len =
5984                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
5985                 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5986                 rip = kvm_rip_read(vcpu);
5987                 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
5988                 kvm_run->debug.arch.exception = ex_no;
5989                 break;
5990         default:
5991                 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
5992                 kvm_run->ex.exception = ex_no;
5993                 kvm_run->ex.error_code = error_code;
5994                 break;
5995         }
5996         return 0;
5997 }
5998
5999 static int handle_external_interrupt(struct kvm_vcpu *vcpu)
6000 {
6001         ++vcpu->stat.irq_exits;
6002         return 1;
6003 }
6004
6005 static int handle_triple_fault(struct kvm_vcpu *vcpu)
6006 {
6007         vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
6008         vcpu->mmio_needed = 0;
6009         return 0;
6010 }
6011
6012 static int handle_io(struct kvm_vcpu *vcpu)
6013 {
6014         unsigned long exit_qualification;
6015         int size, in, string, ret;
6016         unsigned port;
6017
6018         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6019         string = (exit_qualification & 16) != 0;
6020         in = (exit_qualification & 8) != 0;
6021
6022         ++vcpu->stat.io_exits;
6023
6024         if (string || in)
6025                 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
6026
6027         port = exit_qualification >> 16;
6028         size = (exit_qualification & 7) + 1;
6029
6030         ret = kvm_skip_emulated_instruction(vcpu);
6031
6032         /*
6033          * TODO: we might be squashing a KVM_GUESTDBG_SINGLESTEP-triggered
6034          * KVM_EXIT_DEBUG here.
6035          */
6036         return kvm_fast_pio_out(vcpu, size, port) && ret;
6037 }
6038
6039 static void
6040 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
6041 {
6042         /*
6043          * Patch in the VMCALL instruction:
6044          */
6045         hypercall[0] = 0x0f;
6046         hypercall[1] = 0x01;
6047         hypercall[2] = 0xc1;
6048 }
6049
6050 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
6051 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
6052 {
6053         if (is_guest_mode(vcpu)) {
6054                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6055                 unsigned long orig_val = val;
6056
6057                 /*
6058                  * We get here when L2 changed cr0 in a way that did not change
6059                  * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
6060                  * but did change L0 shadowed bits. So we first calculate the
6061                  * effective cr0 value that L1 would like to write into the
6062                  * hardware. It consists of the L2-owned bits from the new
6063                  * value combined with the L1-owned bits from L1's guest_cr0.
6064                  */
6065                 val = (val & ~vmcs12->cr0_guest_host_mask) |
6066                         (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
6067
6068                 if (!nested_guest_cr0_valid(vcpu, val))
6069                         return 1;
6070
6071                 if (kvm_set_cr0(vcpu, val))
6072                         return 1;
6073                 vmcs_writel(CR0_READ_SHADOW, orig_val);
6074                 return 0;
6075         } else {
6076                 if (to_vmx(vcpu)->nested.vmxon &&
6077                     !nested_host_cr0_valid(vcpu, val))
6078                         return 1;
6079
6080                 return kvm_set_cr0(vcpu, val);
6081         }
6082 }
6083
6084 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
6085 {
6086         if (is_guest_mode(vcpu)) {
6087                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6088                 unsigned long orig_val = val;
6089
6090                 /* analogously to handle_set_cr0 */
6091                 val = (val & ~vmcs12->cr4_guest_host_mask) |
6092                         (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
6093                 if (kvm_set_cr4(vcpu, val))
6094                         return 1;
6095                 vmcs_writel(CR4_READ_SHADOW, orig_val);
6096                 return 0;
6097         } else
6098                 return kvm_set_cr4(vcpu, val);
6099 }
6100
6101 static int handle_cr(struct kvm_vcpu *vcpu)
6102 {
6103         unsigned long exit_qualification, val;
6104         int cr;
6105         int reg;
6106         int err;
6107         int ret;
6108
6109         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6110         cr = exit_qualification & 15;
6111         reg = (exit_qualification >> 8) & 15;
6112         switch ((exit_qualification >> 4) & 3) {
6113         case 0: /* mov to cr */
6114                 val = kvm_register_readl(vcpu, reg);
6115                 trace_kvm_cr_write(cr, val);
6116                 switch (cr) {
6117                 case 0:
6118                         err = handle_set_cr0(vcpu, val);
6119                         return kvm_complete_insn_gp(vcpu, err);
6120                 case 3:
6121                         err = kvm_set_cr3(vcpu, val);
6122                         return kvm_complete_insn_gp(vcpu, err);
6123                 case 4:
6124                         err = handle_set_cr4(vcpu, val);
6125                         return kvm_complete_insn_gp(vcpu, err);
6126                 case 8: {
6127                                 u8 cr8_prev = kvm_get_cr8(vcpu);
6128                                 u8 cr8 = (u8)val;
6129                                 err = kvm_set_cr8(vcpu, cr8);
6130                                 ret = kvm_complete_insn_gp(vcpu, err);
6131                                 if (lapic_in_kernel(vcpu))
6132                                         return ret;
6133                                 if (cr8_prev <= cr8)
6134                                         return ret;
6135                                 /*
6136                                  * TODO: we might be squashing a
6137                                  * KVM_GUESTDBG_SINGLESTEP-triggered
6138                                  * KVM_EXIT_DEBUG here.
6139                                  */
6140                                 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
6141                                 return 0;
6142                         }
6143                 }
6144                 break;
6145         case 2: /* clts */
6146                 WARN_ONCE(1, "Guest should always own CR0.TS");
6147                 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
6148                 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
6149                 return kvm_skip_emulated_instruction(vcpu);
6150         case 1: /*mov from cr*/
6151                 switch (cr) {
6152                 case 3:
6153                         val = kvm_read_cr3(vcpu);
6154                         kvm_register_write(vcpu, reg, val);
6155                         trace_kvm_cr_read(cr, val);
6156                         return kvm_skip_emulated_instruction(vcpu);
6157                 case 8:
6158                         val = kvm_get_cr8(vcpu);
6159                         kvm_register_write(vcpu, reg, val);
6160                         trace_kvm_cr_read(cr, val);
6161                         return kvm_skip_emulated_instruction(vcpu);
6162                 }
6163                 break;
6164         case 3: /* lmsw */
6165                 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
6166                 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
6167                 kvm_lmsw(vcpu, val);
6168
6169                 return kvm_skip_emulated_instruction(vcpu);
6170         default:
6171                 break;
6172         }
6173         vcpu->run->exit_reason = 0;
6174         vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
6175                (int)(exit_qualification >> 4) & 3, cr);
6176         return 0;
6177 }
6178
6179 static int handle_dr(struct kvm_vcpu *vcpu)
6180 {
6181         unsigned long exit_qualification;
6182         int dr, dr7, reg;
6183
6184         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6185         dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
6186
6187         /* First, if DR does not exist, trigger UD */
6188         if (!kvm_require_dr(vcpu, dr))
6189                 return 1;
6190
6191         /* Do not handle if the CPL > 0, will trigger GP on re-entry */
6192         if (!kvm_require_cpl(vcpu, 0))
6193                 return 1;
6194         dr7 = vmcs_readl(GUEST_DR7);
6195         if (dr7 & DR7_GD) {
6196                 /*
6197                  * As the vm-exit takes precedence over the debug trap, we
6198                  * need to emulate the latter, either for the host or the
6199                  * guest debugging itself.
6200                  */
6201                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
6202                         vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
6203                         vcpu->run->debug.arch.dr7 = dr7;
6204                         vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
6205                         vcpu->run->debug.arch.exception = DB_VECTOR;
6206                         vcpu->run->exit_reason = KVM_EXIT_DEBUG;
6207                         return 0;
6208                 } else {
6209                         vcpu->arch.dr6 &= ~15;
6210                         vcpu->arch.dr6 |= DR6_BD | DR6_RTM;
6211                         kvm_queue_exception(vcpu, DB_VECTOR);
6212                         return 1;
6213                 }
6214         }
6215
6216         if (vcpu->guest_debug == 0) {
6217                 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
6218                                 CPU_BASED_MOV_DR_EXITING);
6219
6220                 /*
6221                  * No more DR vmexits; force a reload of the debug registers
6222                  * and reenter on this instruction.  The next vmexit will
6223                  * retrieve the full state of the debug registers.
6224                  */
6225                 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
6226                 return 1;
6227         }
6228
6229         reg = DEBUG_REG_ACCESS_REG(exit_qualification);
6230         if (exit_qualification & TYPE_MOV_FROM_DR) {
6231                 unsigned long val;
6232
6233                 if (kvm_get_dr(vcpu, dr, &val))
6234                         return 1;
6235                 kvm_register_write(vcpu, reg, val);
6236         } else
6237                 if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
6238                         return 1;
6239
6240         return kvm_skip_emulated_instruction(vcpu);
6241 }
6242
6243 static u64 vmx_get_dr6(struct kvm_vcpu *vcpu)
6244 {
6245         return vcpu->arch.dr6;
6246 }
6247
6248 static void vmx_set_dr6(struct kvm_vcpu *vcpu, unsigned long val)
6249 {
6250 }
6251
6252 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
6253 {
6254         get_debugreg(vcpu->arch.db[0], 0);
6255         get_debugreg(vcpu->arch.db[1], 1);
6256         get_debugreg(vcpu->arch.db[2], 2);
6257         get_debugreg(vcpu->arch.db[3], 3);
6258         get_debugreg(vcpu->arch.dr6, 6);
6259         vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
6260
6261         vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
6262         vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL, CPU_BASED_MOV_DR_EXITING);
6263 }
6264
6265 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
6266 {
6267         vmcs_writel(GUEST_DR7, val);
6268 }
6269
6270 static int handle_cpuid(struct kvm_vcpu *vcpu)
6271 {
6272         return kvm_emulate_cpuid(vcpu);
6273 }
6274
6275 static int handle_rdmsr(struct kvm_vcpu *vcpu)
6276 {
6277         u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
6278         struct msr_data msr_info;
6279
6280         msr_info.index = ecx;
6281         msr_info.host_initiated = false;
6282         if (vmx_get_msr(vcpu, &msr_info)) {
6283                 trace_kvm_msr_read_ex(ecx);
6284                 kvm_inject_gp(vcpu, 0);
6285                 return 1;
6286         }
6287
6288         trace_kvm_msr_read(ecx, msr_info.data);
6289
6290         /* FIXME: handling of bits 32:63 of rax, rdx */
6291         vcpu->arch.regs[VCPU_REGS_RAX] = msr_info.data & -1u;
6292         vcpu->arch.regs[VCPU_REGS_RDX] = (msr_info.data >> 32) & -1u;
6293         return kvm_skip_emulated_instruction(vcpu);
6294 }
6295
6296 static int handle_wrmsr(struct kvm_vcpu *vcpu)
6297 {
6298         struct msr_data msr;
6299         u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
6300         u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
6301                 | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
6302
6303         msr.data = data;
6304         msr.index = ecx;
6305         msr.host_initiated = false;
6306         if (kvm_set_msr(vcpu, &msr) != 0) {
6307                 trace_kvm_msr_write_ex(ecx, data);
6308                 kvm_inject_gp(vcpu, 0);
6309                 return 1;
6310         }
6311
6312         trace_kvm_msr_write(ecx, data);
6313         return kvm_skip_emulated_instruction(vcpu);
6314 }
6315
6316 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
6317 {
6318         kvm_apic_update_ppr(vcpu);
6319         return 1;
6320 }
6321
6322 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
6323 {
6324         vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
6325                         CPU_BASED_VIRTUAL_INTR_PENDING);
6326
6327         kvm_make_request(KVM_REQ_EVENT, vcpu);
6328
6329         ++vcpu->stat.irq_window_exits;
6330         return 1;
6331 }
6332
6333 static int handle_halt(struct kvm_vcpu *vcpu)
6334 {
6335         return kvm_emulate_halt(vcpu);
6336 }
6337
6338 static int handle_vmcall(struct kvm_vcpu *vcpu)
6339 {
6340         return kvm_emulate_hypercall(vcpu);
6341 }
6342
6343 static int handle_invd(struct kvm_vcpu *vcpu)
6344 {
6345         return emulate_instruction(vcpu, 0) == EMULATE_DONE;
6346 }
6347
6348 static int handle_invlpg(struct kvm_vcpu *vcpu)
6349 {
6350         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6351
6352         kvm_mmu_invlpg(vcpu, exit_qualification);
6353         return kvm_skip_emulated_instruction(vcpu);
6354 }
6355
6356 static int handle_rdpmc(struct kvm_vcpu *vcpu)
6357 {
6358         int err;
6359
6360         err = kvm_rdpmc(vcpu);
6361         return kvm_complete_insn_gp(vcpu, err);
6362 }
6363
6364 static int handle_wbinvd(struct kvm_vcpu *vcpu)
6365 {
6366         return kvm_emulate_wbinvd(vcpu);
6367 }
6368
6369 static int handle_xsetbv(struct kvm_vcpu *vcpu)
6370 {
6371         u64 new_bv = kvm_read_edx_eax(vcpu);
6372         u32 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
6373
6374         if (kvm_set_xcr(vcpu, index, new_bv) == 0)
6375                 return kvm_skip_emulated_instruction(vcpu);
6376         return 1;
6377 }
6378
6379 static int handle_xsaves(struct kvm_vcpu *vcpu)
6380 {
6381         kvm_skip_emulated_instruction(vcpu);
6382         WARN(1, "this should never happen\n");
6383         return 1;
6384 }
6385
6386 static int handle_xrstors(struct kvm_vcpu *vcpu)
6387 {
6388         kvm_skip_emulated_instruction(vcpu);
6389         WARN(1, "this should never happen\n");
6390         return 1;
6391 }
6392
6393 static int handle_apic_access(struct kvm_vcpu *vcpu)
6394 {
6395         if (likely(fasteoi)) {
6396                 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6397                 int access_type, offset;
6398
6399                 access_type = exit_qualification & APIC_ACCESS_TYPE;
6400                 offset = exit_qualification & APIC_ACCESS_OFFSET;
6401                 /*
6402                  * Sane guest uses MOV to write EOI, with written value
6403                  * not cared. So make a short-circuit here by avoiding
6404                  * heavy instruction emulation.
6405                  */
6406                 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
6407                     (offset == APIC_EOI)) {
6408                         kvm_lapic_set_eoi(vcpu);
6409                         return kvm_skip_emulated_instruction(vcpu);
6410                 }
6411         }
6412         return emulate_instruction(vcpu, 0) == EMULATE_DONE;
6413 }
6414
6415 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
6416 {
6417         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6418         int vector = exit_qualification & 0xff;
6419
6420         /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
6421         kvm_apic_set_eoi_accelerated(vcpu, vector);
6422         return 1;
6423 }
6424
6425 static int handle_apic_write(struct kvm_vcpu *vcpu)
6426 {
6427         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6428         u32 offset = exit_qualification & 0xfff;
6429
6430         /* APIC-write VM exit is trap-like and thus no need to adjust IP */
6431         kvm_apic_write_nodecode(vcpu, offset);
6432         return 1;
6433 }
6434
6435 static int handle_task_switch(struct kvm_vcpu *vcpu)
6436 {
6437         struct vcpu_vmx *vmx = to_vmx(vcpu);
6438         unsigned long exit_qualification;
6439         bool has_error_code = false;
6440         u32 error_code = 0;
6441         u16 tss_selector;
6442         int reason, type, idt_v, idt_index;
6443
6444         idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
6445         idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
6446         type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
6447
6448         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6449
6450         reason = (u32)exit_qualification >> 30;
6451         if (reason == TASK_SWITCH_GATE && idt_v) {
6452                 switch (type) {
6453                 case INTR_TYPE_NMI_INTR:
6454                         vcpu->arch.nmi_injected = false;
6455                         vmx_set_nmi_mask(vcpu, true);
6456                         break;
6457                 case INTR_TYPE_EXT_INTR:
6458                 case INTR_TYPE_SOFT_INTR:
6459                         kvm_clear_interrupt_queue(vcpu);
6460                         break;
6461                 case INTR_TYPE_HARD_EXCEPTION:
6462                         if (vmx->idt_vectoring_info &
6463                             VECTORING_INFO_DELIVER_CODE_MASK) {
6464                                 has_error_code = true;
6465                                 error_code =
6466                                         vmcs_read32(IDT_VECTORING_ERROR_CODE);
6467                         }
6468                         /* fall through */
6469                 case INTR_TYPE_SOFT_EXCEPTION:
6470                         kvm_clear_exception_queue(vcpu);
6471                         break;
6472                 default:
6473                         break;
6474                 }
6475         }
6476         tss_selector = exit_qualification;
6477
6478         if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
6479                        type != INTR_TYPE_EXT_INTR &&
6480                        type != INTR_TYPE_NMI_INTR))
6481                 skip_emulated_instruction(vcpu);
6482
6483         if (kvm_task_switch(vcpu, tss_selector,
6484                             type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason,
6485                             has_error_code, error_code) == EMULATE_FAIL) {
6486                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6487                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6488                 vcpu->run->internal.ndata = 0;
6489                 return 0;
6490         }
6491
6492         /*
6493          * TODO: What about debug traps on tss switch?
6494          *       Are we supposed to inject them and update dr6?
6495          */
6496
6497         return 1;
6498 }
6499
6500 static int handle_ept_violation(struct kvm_vcpu *vcpu)
6501 {
6502         unsigned long exit_qualification;
6503         gpa_t gpa;
6504         u64 error_code;
6505
6506         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6507
6508         /*
6509          * EPT violation happened while executing iret from NMI,
6510          * "blocked by NMI" bit has to be set before next VM entry.
6511          * There are errata that may cause this bit to not be set:
6512          * AAK134, BY25.
6513          */
6514         if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
6515                         cpu_has_virtual_nmis() &&
6516                         (exit_qualification & INTR_INFO_UNBLOCK_NMI))
6517                 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
6518
6519         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6520         trace_kvm_page_fault(gpa, exit_qualification);
6521
6522         /* Is it a read fault? */
6523         error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
6524                      ? PFERR_USER_MASK : 0;
6525         /* Is it a write fault? */
6526         error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
6527                       ? PFERR_WRITE_MASK : 0;
6528         /* Is it a fetch fault? */
6529         error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
6530                       ? PFERR_FETCH_MASK : 0;
6531         /* ept page table entry is present? */
6532         error_code |= (exit_qualification &
6533                        (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
6534                         EPT_VIOLATION_EXECUTABLE))
6535                       ? PFERR_PRESENT_MASK : 0;
6536
6537         error_code |= (exit_qualification & 0x100) != 0 ?
6538                PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
6539
6540         vcpu->arch.exit_qualification = exit_qualification;
6541         return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
6542 }
6543
6544 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
6545 {
6546         int ret;
6547         gpa_t gpa;
6548
6549         /*
6550          * A nested guest cannot optimize MMIO vmexits, because we have an
6551          * nGPA here instead of the required GPA.
6552          */
6553         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6554         if (!is_guest_mode(vcpu) &&
6555             !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
6556                 trace_kvm_fast_mmio(gpa);
6557                 return kvm_skip_emulated_instruction(vcpu);
6558         }
6559
6560         ret = kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
6561         if (ret >= 0)
6562                 return ret;
6563
6564         /* It is the real ept misconfig */
6565         WARN_ON(1);
6566
6567         vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
6568         vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_MISCONFIG;
6569
6570         return 0;
6571 }
6572
6573 static int handle_nmi_window(struct kvm_vcpu *vcpu)
6574 {
6575         vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
6576                         CPU_BASED_VIRTUAL_NMI_PENDING);
6577         ++vcpu->stat.nmi_window_exits;
6578         kvm_make_request(KVM_REQ_EVENT, vcpu);
6579
6580         return 1;
6581 }
6582
6583 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
6584 {
6585         struct vcpu_vmx *vmx = to_vmx(vcpu);
6586         enum emulation_result err = EMULATE_DONE;
6587         int ret = 1;
6588         u32 cpu_exec_ctrl;
6589         bool intr_window_requested;
6590         unsigned count = 130;
6591
6592         cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
6593         intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
6594
6595         while (vmx->emulation_required && count-- != 0) {
6596                 if (intr_window_requested && vmx_interrupt_allowed(vcpu))
6597                         return handle_interrupt_window(&vmx->vcpu);
6598
6599                 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
6600                         return 1;
6601
6602                 err = emulate_instruction(vcpu, EMULTYPE_NO_REEXECUTE);
6603
6604                 if (err == EMULATE_USER_EXIT) {
6605                         ++vcpu->stat.mmio_exits;
6606                         ret = 0;
6607                         goto out;
6608                 }
6609
6610                 if (err != EMULATE_DONE) {
6611                         vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6612                         vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6613                         vcpu->run->internal.ndata = 0;
6614                         return 0;
6615                 }
6616
6617                 if (vcpu->arch.halt_request) {
6618                         vcpu->arch.halt_request = 0;
6619                         ret = kvm_vcpu_halt(vcpu);
6620                         goto out;
6621                 }
6622
6623                 if (signal_pending(current))
6624                         goto out;
6625                 if (need_resched())
6626                         schedule();
6627         }
6628
6629 out:
6630         return ret;
6631 }
6632
6633 static int __grow_ple_window(int val)
6634 {
6635         if (ple_window_grow < 1)
6636                 return ple_window;
6637
6638         val = min(val, ple_window_actual_max);
6639
6640         if (ple_window_grow < ple_window)
6641                 val *= ple_window_grow;
6642         else
6643                 val += ple_window_grow;
6644
6645         return val;
6646 }
6647
6648 static int __shrink_ple_window(int val, int modifier, int minimum)
6649 {
6650         if (modifier < 1)
6651                 return ple_window;
6652
6653         if (modifier < ple_window)
6654                 val /= modifier;
6655         else
6656                 val -= modifier;
6657
6658         return max(val, minimum);
6659 }
6660
6661 static void grow_ple_window(struct kvm_vcpu *vcpu)
6662 {
6663         struct vcpu_vmx *vmx = to_vmx(vcpu);
6664         int old = vmx->ple_window;
6665
6666         vmx->ple_window = __grow_ple_window(old);
6667
6668         if (vmx->ple_window != old)
6669                 vmx->ple_window_dirty = true;
6670
6671         trace_kvm_ple_window_grow(vcpu->vcpu_id, vmx->ple_window, old);
6672 }
6673
6674 static void shrink_ple_window(struct kvm_vcpu *vcpu)
6675 {
6676         struct vcpu_vmx *vmx = to_vmx(vcpu);
6677         int old = vmx->ple_window;
6678
6679         vmx->ple_window = __shrink_ple_window(old,
6680                                               ple_window_shrink, ple_window);
6681
6682         if (vmx->ple_window != old)
6683                 vmx->ple_window_dirty = true;
6684
6685         trace_kvm_ple_window_shrink(vcpu->vcpu_id, vmx->ple_window, old);
6686 }
6687
6688 /*
6689  * ple_window_actual_max is computed to be one grow_ple_window() below
6690  * ple_window_max. (See __grow_ple_window for the reason.)
6691  * This prevents overflows, because ple_window_max is int.
6692  * ple_window_max effectively rounded down to a multiple of ple_window_grow in
6693  * this process.
6694  * ple_window_max is also prevented from setting vmx->ple_window < ple_window.
6695  */
6696 static void update_ple_window_actual_max(void)
6697 {
6698         ple_window_actual_max =
6699                         __shrink_ple_window(max(ple_window_max, ple_window),
6700                                             ple_window_grow, INT_MIN);
6701 }
6702
6703 /*
6704  * Handler for POSTED_INTERRUPT_WAKEUP_VECTOR.
6705  */
6706 static void wakeup_handler(void)
6707 {
6708         struct kvm_vcpu *vcpu;
6709         int cpu = smp_processor_id();
6710
6711         spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
6712         list_for_each_entry(vcpu, &per_cpu(blocked_vcpu_on_cpu, cpu),
6713                         blocked_vcpu_list) {
6714                 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
6715
6716                 if (pi_test_on(pi_desc) == 1)
6717                         kvm_vcpu_kick(vcpu);
6718         }
6719         spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
6720 }
6721
6722 void vmx_enable_tdp(void)
6723 {
6724         kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
6725                 enable_ept_ad_bits ? VMX_EPT_ACCESS_BIT : 0ull,
6726                 enable_ept_ad_bits ? VMX_EPT_DIRTY_BIT : 0ull,
6727                 0ull, VMX_EPT_EXECUTABLE_MASK,
6728                 cpu_has_vmx_ept_execute_only() ? 0ull : VMX_EPT_READABLE_MASK,
6729                 VMX_EPT_RWX_MASK, 0ull);
6730
6731         ept_set_mmio_spte_mask();
6732         kvm_enable_tdp();
6733 }
6734
6735 static __init int hardware_setup(void)
6736 {
6737         int r = -ENOMEM, i, msr;
6738
6739         rdmsrl_safe(MSR_EFER, &host_efer);
6740
6741         for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)
6742                 kvm_define_shared_msr(i, vmx_msr_index[i]);
6743
6744         for (i = 0; i < VMX_BITMAP_NR; i++) {
6745                 vmx_bitmap[i] = (unsigned long *)__get_free_page(GFP_KERNEL);
6746                 if (!vmx_bitmap[i])
6747                         goto out;
6748         }
6749
6750         vmx_io_bitmap_b = (unsigned long *)__get_free_page(GFP_KERNEL);
6751         memset(vmx_vmread_bitmap, 0xff, PAGE_SIZE);
6752         memset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE);
6753
6754         memset(vmx_io_bitmap_a, 0xff, PAGE_SIZE);
6755
6756         memset(vmx_io_bitmap_b, 0xff, PAGE_SIZE);
6757
6758         memset(vmx_msr_bitmap_legacy, 0xff, PAGE_SIZE);
6759         memset(vmx_msr_bitmap_longmode, 0xff, PAGE_SIZE);
6760
6761         if (setup_vmcs_config(&vmcs_config) < 0) {
6762                 r = -EIO;
6763                 goto out;
6764         }
6765
6766         if (boot_cpu_has(X86_FEATURE_NX))
6767                 kvm_enable_efer_bits(EFER_NX);
6768
6769         if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
6770                 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
6771                 enable_vpid = 0;
6772
6773         if (!cpu_has_vmx_shadow_vmcs())
6774                 enable_shadow_vmcs = 0;
6775         if (enable_shadow_vmcs)
6776                 init_vmcs_shadow_fields();
6777
6778         if (!cpu_has_vmx_ept() ||
6779             !cpu_has_vmx_ept_4levels() ||
6780             !cpu_has_vmx_ept_mt_wb()) {
6781                 enable_ept = 0;
6782                 enable_unrestricted_guest = 0;
6783                 enable_ept_ad_bits = 0;
6784         }
6785
6786         if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
6787                 enable_ept_ad_bits = 0;
6788
6789         if (!cpu_has_vmx_unrestricted_guest())
6790                 enable_unrestricted_guest = 0;
6791
6792         if (!cpu_has_vmx_flexpriority())
6793                 flexpriority_enabled = 0;
6794
6795         /*
6796          * set_apic_access_page_addr() is used to reload apic access
6797          * page upon invalidation.  No need to do anything if not
6798          * using the APIC_ACCESS_ADDR VMCS field.
6799          */
6800         if (!flexpriority_enabled)
6801                 kvm_x86_ops->set_apic_access_page_addr = NULL;
6802
6803         if (!cpu_has_vmx_tpr_shadow())
6804                 kvm_x86_ops->update_cr8_intercept = NULL;
6805
6806         if (enable_ept && !cpu_has_vmx_ept_2m_page())
6807                 kvm_disable_largepages();
6808
6809         if (!cpu_has_vmx_ple())
6810                 ple_gap = 0;
6811
6812         if (!cpu_has_vmx_apicv()) {
6813                 enable_apicv = 0;
6814                 kvm_x86_ops->sync_pir_to_irr = NULL;
6815         }
6816
6817         if (cpu_has_vmx_tsc_scaling()) {
6818                 kvm_has_tsc_control = true;
6819                 kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
6820                 kvm_tsc_scaling_ratio_frac_bits = 48;
6821         }
6822
6823         vmx_disable_intercept_for_msr(MSR_FS_BASE, false);
6824         vmx_disable_intercept_for_msr(MSR_GS_BASE, false);
6825         vmx_disable_intercept_for_msr(MSR_KERNEL_GS_BASE, true);
6826         vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_CS, false);
6827         vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_ESP, false);
6828         vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_EIP, false);
6829
6830         memcpy(vmx_msr_bitmap_legacy_x2apic_apicv,
6831                         vmx_msr_bitmap_legacy, PAGE_SIZE);
6832         memcpy(vmx_msr_bitmap_longmode_x2apic_apicv,
6833                         vmx_msr_bitmap_longmode, PAGE_SIZE);
6834         memcpy(vmx_msr_bitmap_legacy_x2apic,
6835                         vmx_msr_bitmap_legacy, PAGE_SIZE);
6836         memcpy(vmx_msr_bitmap_longmode_x2apic,
6837                         vmx_msr_bitmap_longmode, PAGE_SIZE);
6838
6839         set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
6840
6841         for (msr = 0x800; msr <= 0x8ff; msr++) {
6842                 if (msr == 0x839 /* TMCCT */)
6843                         continue;
6844                 vmx_disable_intercept_msr_x2apic(msr, MSR_TYPE_R, true);
6845         }
6846
6847         /*
6848          * TPR reads and writes can be virtualized even if virtual interrupt
6849          * delivery is not in use.
6850          */
6851         vmx_disable_intercept_msr_x2apic(0x808, MSR_TYPE_W, true);
6852         vmx_disable_intercept_msr_x2apic(0x808, MSR_TYPE_R | MSR_TYPE_W, false);
6853
6854         /* EOI */
6855         vmx_disable_intercept_msr_x2apic(0x80b, MSR_TYPE_W, true);
6856         /* SELF-IPI */
6857         vmx_disable_intercept_msr_x2apic(0x83f, MSR_TYPE_W, true);
6858
6859         if (enable_ept)
6860                 vmx_enable_tdp();
6861         else
6862                 kvm_disable_tdp();
6863
6864         update_ple_window_actual_max();
6865
6866         /*
6867          * Only enable PML when hardware supports PML feature, and both EPT
6868          * and EPT A/D bit features are enabled -- PML depends on them to work.
6869          */
6870         if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
6871                 enable_pml = 0;
6872
6873         if (!enable_pml) {
6874                 kvm_x86_ops->slot_enable_log_dirty = NULL;
6875                 kvm_x86_ops->slot_disable_log_dirty = NULL;
6876                 kvm_x86_ops->flush_log_dirty = NULL;
6877                 kvm_x86_ops->enable_log_dirty_pt_masked = NULL;
6878         }
6879
6880         if (cpu_has_vmx_preemption_timer() && enable_preemption_timer) {
6881                 u64 vmx_msr;
6882
6883                 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
6884                 cpu_preemption_timer_multi =
6885                          vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
6886         } else {
6887                 kvm_x86_ops->set_hv_timer = NULL;
6888                 kvm_x86_ops->cancel_hv_timer = NULL;
6889         }
6890
6891         kvm_set_posted_intr_wakeup_handler(wakeup_handler);
6892
6893         kvm_mce_cap_supported |= MCG_LMCE_P;
6894
6895         return alloc_kvm_area();
6896
6897 out:
6898         for (i = 0; i < VMX_BITMAP_NR; i++)
6899                 free_page((unsigned long)vmx_bitmap[i]);
6900
6901     return r;
6902 }
6903
6904 static __exit void hardware_unsetup(void)
6905 {
6906         int i;
6907
6908         for (i = 0; i < VMX_BITMAP_NR; i++)
6909                 free_page((unsigned long)vmx_bitmap[i]);
6910
6911         free_kvm_area();
6912 }
6913
6914 /*
6915  * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
6916  * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
6917  */
6918 static int handle_pause(struct kvm_vcpu *vcpu)
6919 {
6920         if (ple_gap)
6921                 grow_ple_window(vcpu);
6922
6923         /*
6924          * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
6925          * VM-execution control is ignored if CPL > 0. OTOH, KVM
6926          * never set PAUSE_EXITING and just set PLE if supported,
6927          * so the vcpu must be CPL=0 if it gets a PAUSE exit.
6928          */
6929         kvm_vcpu_on_spin(vcpu, true);
6930         return kvm_skip_emulated_instruction(vcpu);
6931 }
6932
6933 static int handle_nop(struct kvm_vcpu *vcpu)
6934 {
6935         return kvm_skip_emulated_instruction(vcpu);
6936 }
6937
6938 static int handle_mwait(struct kvm_vcpu *vcpu)
6939 {
6940         printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
6941         return handle_nop(vcpu);
6942 }
6943
6944 static int handle_invalid_op(struct kvm_vcpu *vcpu)
6945 {
6946         kvm_queue_exception(vcpu, UD_VECTOR);
6947         return 1;
6948 }
6949
6950 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
6951 {
6952         return 1;
6953 }
6954
6955 static int handle_monitor(struct kvm_vcpu *vcpu)
6956 {
6957         printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
6958         return handle_nop(vcpu);
6959 }
6960
6961 /*
6962  * To run an L2 guest, we need a vmcs02 based on the L1-specified vmcs12.
6963  * We could reuse a single VMCS for all the L2 guests, but we also want the
6964  * option to allocate a separate vmcs02 for each separate loaded vmcs12 - this
6965  * allows keeping them loaded on the processor, and in the future will allow
6966  * optimizations where prepare_vmcs02 doesn't need to set all the fields on
6967  * every entry if they never change.
6968  * So we keep, in vmx->nested.vmcs02_pool, a cache of size VMCS02_POOL_SIZE
6969  * (>=0) with a vmcs02 for each recently loaded vmcs12s, most recent first.
6970  *
6971  * The following functions allocate and free a vmcs02 in this pool.
6972  */
6973
6974 /* Get a VMCS from the pool to use as vmcs02 for the current vmcs12. */
6975 static struct loaded_vmcs *nested_get_current_vmcs02(struct vcpu_vmx *vmx)
6976 {
6977         struct vmcs02_list *item;
6978         list_for_each_entry(item, &vmx->nested.vmcs02_pool, list)
6979                 if (item->vmptr == vmx->nested.current_vmptr) {
6980                         list_move(&item->list, &vmx->nested.vmcs02_pool);
6981                         return &item->vmcs02;
6982                 }
6983
6984         if (vmx->nested.vmcs02_num >= max(VMCS02_POOL_SIZE, 1)) {
6985                 /* Recycle the least recently used VMCS. */
6986                 item = list_last_entry(&vmx->nested.vmcs02_pool,
6987                                        struct vmcs02_list, list);
6988                 item->vmptr = vmx->nested.current_vmptr;
6989                 list_move(&item->list, &vmx->nested.vmcs02_pool);
6990                 return &item->vmcs02;
6991         }
6992
6993         /* Create a new VMCS */
6994         item = kzalloc(sizeof(struct vmcs02_list), GFP_KERNEL);
6995         if (!item)
6996                 return NULL;
6997         item->vmcs02.vmcs = alloc_vmcs();
6998         item->vmcs02.shadow_vmcs = NULL;
6999         if (!item->vmcs02.vmcs) {
7000                 kfree(item);
7001                 return NULL;
7002         }
7003         loaded_vmcs_init(&item->vmcs02);
7004         item->vmptr = vmx->nested.current_vmptr;
7005         list_add(&(item->list), &(vmx->nested.vmcs02_pool));
7006         vmx->nested.vmcs02_num++;
7007         return &item->vmcs02;
7008 }
7009
7010 /* Free and remove from pool a vmcs02 saved for a vmcs12 (if there is one) */
7011 static void nested_free_vmcs02(struct vcpu_vmx *vmx, gpa_t vmptr)
7012 {
7013         struct vmcs02_list *item;
7014         list_for_each_entry(item, &vmx->nested.vmcs02_pool, list)
7015                 if (item->vmptr == vmptr) {
7016                         free_loaded_vmcs(&item->vmcs02);
7017                         list_del(&item->list);
7018                         kfree(item);
7019                         vmx->nested.vmcs02_num--;
7020                         return;
7021                 }
7022 }
7023
7024 /*
7025  * Free all VMCSs saved for this vcpu, except the one pointed by
7026  * vmx->loaded_vmcs. We must be running L1, so vmx->loaded_vmcs
7027  * must be &vmx->vmcs01.
7028  */
7029 static void nested_free_all_saved_vmcss(struct vcpu_vmx *vmx)
7030 {
7031         struct vmcs02_list *item, *n;
7032
7033         WARN_ON(vmx->loaded_vmcs != &vmx->vmcs01);
7034         list_for_each_entry_safe(item, n, &vmx->nested.vmcs02_pool, list) {
7035                 /*
7036                  * Something will leak if the above WARN triggers.  Better than
7037                  * a use-after-free.
7038                  */
7039                 if (vmx->loaded_vmcs == &item->vmcs02)
7040                         continue;
7041
7042                 free_loaded_vmcs(&item->vmcs02);
7043                 list_del(&item->list);
7044                 kfree(item);
7045                 vmx->nested.vmcs02_num--;
7046         }
7047 }
7048
7049 /*
7050  * The following 3 functions, nested_vmx_succeed()/failValid()/failInvalid(),
7051  * set the success or error code of an emulated VMX instruction, as specified
7052  * by Vol 2B, VMX Instruction Reference, "Conventions".
7053  */
7054 static void nested_vmx_succeed(struct kvm_vcpu *vcpu)
7055 {
7056         vmx_set_rflags(vcpu, vmx_get_rflags(vcpu)
7057                         & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
7058                             X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF));
7059 }
7060
7061 static void nested_vmx_failInvalid(struct kvm_vcpu *vcpu)
7062 {
7063         vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
7064                         & ~(X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
7065                             X86_EFLAGS_SF | X86_EFLAGS_OF))
7066                         | X86_EFLAGS_CF);
7067 }
7068
7069 static void nested_vmx_failValid(struct kvm_vcpu *vcpu,
7070                                         u32 vm_instruction_error)
7071 {
7072         if (to_vmx(vcpu)->nested.current_vmptr == -1ull) {
7073                 /*
7074                  * failValid writes the error number to the current VMCS, which
7075                  * can't be done there isn't a current VMCS.
7076                  */
7077                 nested_vmx_failInvalid(vcpu);
7078                 return;
7079         }
7080         vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
7081                         & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
7082                             X86_EFLAGS_SF | X86_EFLAGS_OF))
7083                         | X86_EFLAGS_ZF);
7084         get_vmcs12(vcpu)->vm_instruction_error = vm_instruction_error;
7085         /*
7086          * We don't need to force a shadow sync because
7087          * VM_INSTRUCTION_ERROR is not shadowed
7088          */
7089 }
7090
7091 static void nested_vmx_abort(struct kvm_vcpu *vcpu, u32 indicator)
7092 {
7093         /* TODO: not to reset guest simply here. */
7094         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
7095         pr_debug_ratelimited("kvm: nested vmx abort, indicator %d\n", indicator);
7096 }
7097
7098 static enum hrtimer_restart vmx_preemption_timer_fn(struct hrtimer *timer)
7099 {
7100         struct vcpu_vmx *vmx =
7101                 container_of(timer, struct vcpu_vmx, nested.preemption_timer);
7102
7103         vmx->nested.preemption_timer_expired = true;
7104         kvm_make_request(KVM_REQ_EVENT, &vmx->vcpu);
7105         kvm_vcpu_kick(&vmx->vcpu);
7106
7107         return HRTIMER_NORESTART;
7108 }
7109
7110 /*
7111  * Decode the memory-address operand of a vmx instruction, as recorded on an
7112  * exit caused by such an instruction (run by a guest hypervisor).
7113  * On success, returns 0. When the operand is invalid, returns 1 and throws
7114  * #UD or #GP.
7115  */
7116 static int get_vmx_mem_address(struct kvm_vcpu *vcpu,
7117                                  unsigned long exit_qualification,
7118                                  u32 vmx_instruction_info, bool wr, gva_t *ret)
7119 {
7120         gva_t off;
7121         bool exn;
7122         struct kvm_segment s;
7123
7124         /*
7125          * According to Vol. 3B, "Information for VM Exits Due to Instruction
7126          * Execution", on an exit, vmx_instruction_info holds most of the
7127          * addressing components of the operand. Only the displacement part
7128          * is put in exit_qualification (see 3B, "Basic VM-Exit Information").
7129          * For how an actual address is calculated from all these components,
7130          * refer to Vol. 1, "Operand Addressing".
7131          */
7132         int  scaling = vmx_instruction_info & 3;
7133         int  addr_size = (vmx_instruction_info >> 7) & 7;
7134         bool is_reg = vmx_instruction_info & (1u << 10);
7135         int  seg_reg = (vmx_instruction_info >> 15) & 7;
7136         int  index_reg = (vmx_instruction_info >> 18) & 0xf;
7137         bool index_is_valid = !(vmx_instruction_info & (1u << 22));
7138         int  base_reg       = (vmx_instruction_info >> 23) & 0xf;
7139         bool base_is_valid  = !(vmx_instruction_info & (1u << 27));
7140
7141         if (is_reg) {
7142                 kvm_queue_exception(vcpu, UD_VECTOR);
7143                 return 1;
7144         }
7145
7146         /* Addr = segment_base + offset */
7147         /* offset = base + [index * scale] + displacement */
7148         off = exit_qualification; /* holds the displacement */
7149         if (base_is_valid)
7150                 off += kvm_register_read(vcpu, base_reg);
7151         if (index_is_valid)
7152                 off += kvm_register_read(vcpu, index_reg)<<scaling;
7153         vmx_get_segment(vcpu, &s, seg_reg);
7154         *ret = s.base + off;
7155
7156         if (addr_size == 1) /* 32 bit */
7157                 *ret &= 0xffffffff;
7158
7159         /* Checks for #GP/#SS exceptions. */
7160         exn = false;
7161         if (is_long_mode(vcpu)) {
7162                 /* Long mode: #GP(0)/#SS(0) if the memory address is in a
7163                  * non-canonical form. This is the only check on the memory
7164                  * destination for long mode!
7165                  */
7166                 exn = is_noncanonical_address(*ret, vcpu);
7167         } else if (is_protmode(vcpu)) {
7168                 /* Protected mode: apply checks for segment validity in the
7169                  * following order:
7170                  * - segment type check (#GP(0) may be thrown)
7171                  * - usability check (#GP(0)/#SS(0))
7172                  * - limit check (#GP(0)/#SS(0))
7173                  */
7174                 if (wr)
7175                         /* #GP(0) if the destination operand is located in a
7176                          * read-only data segment or any code segment.
7177                          */
7178                         exn = ((s.type & 0xa) == 0 || (s.type & 8));
7179                 else
7180                         /* #GP(0) if the source operand is located in an
7181                          * execute-only code segment
7182                          */
7183                         exn = ((s.type & 0xa) == 8);
7184                 if (exn) {
7185                         kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
7186                         return 1;
7187                 }
7188                 /* Protected mode: #GP(0)/#SS(0) if the segment is unusable.
7189                  */
7190                 exn = (s.unusable != 0);
7191                 /* Protected mode: #GP(0)/#SS(0) if the memory
7192                  * operand is outside the segment limit.
7193                  */
7194                 exn = exn || (off + sizeof(u64) > s.limit);
7195         }
7196         if (exn) {
7197                 kvm_queue_exception_e(vcpu,
7198                                       seg_reg == VCPU_SREG_SS ?
7199                                                 SS_VECTOR : GP_VECTOR,
7200                                       0);
7201                 return 1;
7202         }
7203
7204         return 0;
7205 }
7206
7207 static int nested_vmx_get_vmptr(struct kvm_vcpu *vcpu, gpa_t *vmpointer)
7208 {
7209         gva_t gva;
7210         struct x86_exception e;
7211
7212         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
7213                         vmcs_read32(VMX_INSTRUCTION_INFO), false, &gva))
7214                 return 1;
7215
7216         if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, vmpointer,
7217                                 sizeof(*vmpointer), &e)) {
7218                 kvm_inject_page_fault(vcpu, &e);
7219                 return 1;
7220         }
7221
7222         return 0;
7223 }
7224
7225 static int enter_vmx_operation(struct kvm_vcpu *vcpu)
7226 {
7227         struct vcpu_vmx *vmx = to_vmx(vcpu);
7228         struct vmcs *shadow_vmcs;
7229
7230         if (cpu_has_vmx_msr_bitmap()) {
7231                 vmx->nested.msr_bitmap =
7232                                 (unsigned long *)__get_free_page(GFP_KERNEL);
7233                 if (!vmx->nested.msr_bitmap)
7234                         goto out_msr_bitmap;
7235         }
7236
7237         vmx->nested.cached_vmcs12 = kmalloc(VMCS12_SIZE, GFP_KERNEL);
7238         if (!vmx->nested.cached_vmcs12)
7239                 goto out_cached_vmcs12;
7240
7241         if (enable_shadow_vmcs) {
7242                 shadow_vmcs = alloc_vmcs();
7243                 if (!shadow_vmcs)
7244                         goto out_shadow_vmcs;
7245                 /* mark vmcs as shadow */
7246                 shadow_vmcs->revision_id |= (1u << 31);
7247                 /* init shadow vmcs */
7248                 vmcs_clear(shadow_vmcs);
7249                 vmx->vmcs01.shadow_vmcs = shadow_vmcs;
7250         }
7251
7252         INIT_LIST_HEAD(&(vmx->nested.vmcs02_pool));
7253         vmx->nested.vmcs02_num = 0;
7254
7255         hrtimer_init(&vmx->nested.preemption_timer, CLOCK_MONOTONIC,
7256                      HRTIMER_MODE_REL_PINNED);
7257         vmx->nested.preemption_timer.function = vmx_preemption_timer_fn;
7258
7259         vmx->nested.vmxon = true;
7260         return 0;
7261
7262 out_shadow_vmcs:
7263         kfree(vmx->nested.cached_vmcs12);
7264
7265 out_cached_vmcs12:
7266         free_page((unsigned long)vmx->nested.msr_bitmap);
7267
7268 out_msr_bitmap:
7269         return -ENOMEM;
7270 }
7271
7272 /*
7273  * Emulate the VMXON instruction.
7274  * Currently, we just remember that VMX is active, and do not save or even
7275  * inspect the argument to VMXON (the so-called "VMXON pointer") because we
7276  * do not currently need to store anything in that guest-allocated memory
7277  * region. Consequently, VMCLEAR and VMPTRLD also do not verify that the their
7278  * argument is different from the VMXON pointer (which the spec says they do).
7279  */
7280 static int handle_vmon(struct kvm_vcpu *vcpu)
7281 {
7282         int ret;
7283         gpa_t vmptr;
7284         struct page *page;
7285         struct vcpu_vmx *vmx = to_vmx(vcpu);
7286         const u64 VMXON_NEEDED_FEATURES = FEATURE_CONTROL_LOCKED
7287                 | FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
7288
7289         /*
7290          * The Intel VMX Instruction Reference lists a bunch of bits that are
7291          * prerequisite to running VMXON, most notably cr4.VMXE must be set to
7292          * 1 (see vmx_set_cr4() for when we allow the guest to set this).
7293          * Otherwise, we should fail with #UD.  But most faulting conditions
7294          * have already been checked by hardware, prior to the VM-exit for
7295          * VMXON.  We do test guest cr4.VMXE because processor CR4 always has
7296          * that bit set to 1 in non-root mode.
7297          */
7298         if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE)) {
7299                 kvm_queue_exception(vcpu, UD_VECTOR);
7300                 return 1;
7301         }
7302
7303         if (vmx->nested.vmxon) {
7304                 nested_vmx_failValid(vcpu, VMXERR_VMXON_IN_VMX_ROOT_OPERATION);
7305                 return kvm_skip_emulated_instruction(vcpu);
7306         }
7307
7308         if ((vmx->msr_ia32_feature_control & VMXON_NEEDED_FEATURES)
7309                         != VMXON_NEEDED_FEATURES) {
7310                 kvm_inject_gp(vcpu, 0);
7311                 return 1;
7312         }
7313
7314         if (nested_vmx_get_vmptr(vcpu, &vmptr))
7315                 return 1;
7316
7317         /*
7318          * SDM 3: 24.11.5
7319          * The first 4 bytes of VMXON region contain the supported
7320          * VMCS revision identifier
7321          *
7322          * Note - IA32_VMX_BASIC[48] will never be 1 for the nested case;
7323          * which replaces physical address width with 32
7324          */
7325         if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {
7326                 nested_vmx_failInvalid(vcpu);
7327                 return kvm_skip_emulated_instruction(vcpu);
7328         }
7329
7330         page = kvm_vcpu_gpa_to_page(vcpu, vmptr);
7331         if (is_error_page(page)) {
7332                 nested_vmx_failInvalid(vcpu);
7333                 return kvm_skip_emulated_instruction(vcpu);
7334         }
7335         if (*(u32 *)kmap(page) != VMCS12_REVISION) {
7336                 kunmap(page);
7337                 kvm_release_page_clean(page);
7338                 nested_vmx_failInvalid(vcpu);
7339                 return kvm_skip_emulated_instruction(vcpu);
7340         }
7341         kunmap(page);
7342         kvm_release_page_clean(page);
7343
7344         vmx->nested.vmxon_ptr = vmptr;
7345         ret = enter_vmx_operation(vcpu);
7346         if (ret)
7347                 return ret;
7348
7349         nested_vmx_succeed(vcpu);
7350         return kvm_skip_emulated_instruction(vcpu);
7351 }
7352
7353 /*
7354  * Intel's VMX Instruction Reference specifies a common set of prerequisites
7355  * for running VMX instructions (except VMXON, whose prerequisites are
7356  * slightly different). It also specifies what exception to inject otherwise.
7357  * Note that many of these exceptions have priority over VM exits, so they
7358  * don't have to be checked again here.
7359  */
7360 static int nested_vmx_check_permission(struct kvm_vcpu *vcpu)
7361 {
7362         if (!to_vmx(vcpu)->nested.vmxon) {
7363                 kvm_queue_exception(vcpu, UD_VECTOR);
7364                 return 0;
7365         }
7366         return 1;
7367 }
7368
7369 static void vmx_disable_shadow_vmcs(struct vcpu_vmx *vmx)
7370 {
7371         vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL, SECONDARY_EXEC_SHADOW_VMCS);
7372         vmcs_write64(VMCS_LINK_POINTER, -1ull);
7373 }
7374
7375 static inline void nested_release_vmcs12(struct vcpu_vmx *vmx)
7376 {
7377         if (vmx->nested.current_vmptr == -1ull)
7378                 return;
7379
7380         if (enable_shadow_vmcs) {
7381                 /* copy to memory all shadowed fields in case
7382                    they were modified */
7383                 copy_shadow_to_vmcs12(vmx);
7384                 vmx->nested.sync_shadow_vmcs = false;
7385                 vmx_disable_shadow_vmcs(vmx);
7386         }
7387         vmx->nested.posted_intr_nv = -1;
7388
7389         /* Flush VMCS12 to guest memory */
7390         kvm_vcpu_write_guest_page(&vmx->vcpu,
7391                                   vmx->nested.current_vmptr >> PAGE_SHIFT,
7392                                   vmx->nested.cached_vmcs12, 0, VMCS12_SIZE);
7393
7394         vmx->nested.current_vmptr = -1ull;
7395 }
7396
7397 /*
7398  * Free whatever needs to be freed from vmx->nested when L1 goes down, or
7399  * just stops using VMX.
7400  */
7401 static void free_nested(struct vcpu_vmx *vmx)
7402 {
7403         if (!vmx->nested.vmxon)
7404                 return;
7405
7406         vmx->nested.vmxon = false;
7407         free_vpid(vmx->nested.vpid02);
7408         vmx->nested.posted_intr_nv = -1;
7409         vmx->nested.current_vmptr = -1ull;
7410         if (vmx->nested.msr_bitmap) {
7411                 free_page((unsigned long)vmx->nested.msr_bitmap);
7412                 vmx->nested.msr_bitmap = NULL;
7413         }
7414         if (enable_shadow_vmcs) {
7415                 vmx_disable_shadow_vmcs(vmx);
7416                 vmcs_clear(vmx->vmcs01.shadow_vmcs);
7417                 free_vmcs(vmx->vmcs01.shadow_vmcs);
7418                 vmx->vmcs01.shadow_vmcs = NULL;
7419         }
7420         kfree(vmx->nested.cached_vmcs12);
7421         /* Unpin physical memory we referred to in current vmcs02 */
7422         if (vmx->nested.apic_access_page) {
7423                 kvm_release_page_dirty(vmx->nested.apic_access_page);
7424                 vmx->nested.apic_access_page = NULL;
7425         }
7426         if (vmx->nested.virtual_apic_page) {
7427                 kvm_release_page_dirty(vmx->nested.virtual_apic_page);
7428                 vmx->nested.virtual_apic_page = NULL;
7429         }
7430         if (vmx->nested.pi_desc_page) {
7431                 kunmap(vmx->nested.pi_desc_page);
7432                 kvm_release_page_dirty(vmx->nested.pi_desc_page);
7433                 vmx->nested.pi_desc_page = NULL;
7434                 vmx->nested.pi_desc = NULL;
7435         }
7436
7437         nested_free_all_saved_vmcss(vmx);
7438 }
7439
7440 /* Emulate the VMXOFF instruction */
7441 static int handle_vmoff(struct kvm_vcpu *vcpu)
7442 {
7443         if (!nested_vmx_check_permission(vcpu))
7444                 return 1;
7445         free_nested(to_vmx(vcpu));
7446         nested_vmx_succeed(vcpu);
7447         return kvm_skip_emulated_instruction(vcpu);
7448 }
7449
7450 /* Emulate the VMCLEAR instruction */
7451 static int handle_vmclear(struct kvm_vcpu *vcpu)
7452 {
7453         struct vcpu_vmx *vmx = to_vmx(vcpu);
7454         u32 zero = 0;
7455         gpa_t vmptr;
7456
7457         if (!nested_vmx_check_permission(vcpu))
7458                 return 1;
7459
7460         if (nested_vmx_get_vmptr(vcpu, &vmptr))
7461                 return 1;
7462
7463         if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {
7464                 nested_vmx_failValid(vcpu, VMXERR_VMCLEAR_INVALID_ADDRESS);
7465                 return kvm_skip_emulated_instruction(vcpu);
7466         }
7467
7468         if (vmptr == vmx->nested.vmxon_ptr) {
7469                 nested_vmx_failValid(vcpu, VMXERR_VMCLEAR_VMXON_POINTER);
7470                 return kvm_skip_emulated_instruction(vcpu);
7471         }
7472
7473         if (vmptr == vmx->nested.current_vmptr)
7474                 nested_release_vmcs12(vmx);
7475
7476         kvm_vcpu_write_guest(vcpu,
7477                         vmptr + offsetof(struct vmcs12, launch_state),
7478                         &zero, sizeof(zero));
7479
7480         nested_free_vmcs02(vmx, vmptr);
7481
7482         nested_vmx_succeed(vcpu);
7483         return kvm_skip_emulated_instruction(vcpu);
7484 }
7485
7486 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch);
7487
7488 /* Emulate the VMLAUNCH instruction */
7489 static int handle_vmlaunch(struct kvm_vcpu *vcpu)
7490 {
7491         return nested_vmx_run(vcpu, true);
7492 }
7493
7494 /* Emulate the VMRESUME instruction */
7495 static int handle_vmresume(struct kvm_vcpu *vcpu)
7496 {
7497
7498         return nested_vmx_run(vcpu, false);
7499 }
7500
7501 /*
7502  * Read a vmcs12 field. Since these can have varying lengths and we return
7503  * one type, we chose the biggest type (u64) and zero-extend the return value
7504  * to that size. Note that the caller, handle_vmread, might need to use only
7505  * some of the bits we return here (e.g., on 32-bit guests, only 32 bits of
7506  * 64-bit fields are to be returned).
7507  */
7508 static inline int vmcs12_read_any(struct kvm_vcpu *vcpu,
7509                                   unsigned long field, u64 *ret)
7510 {
7511         short offset = vmcs_field_to_offset(field);
7512         char *p;
7513
7514         if (offset < 0)
7515                 return offset;
7516
7517         p = ((char *)(get_vmcs12(vcpu))) + offset;
7518
7519         switch (vmcs_field_type(field)) {
7520         case VMCS_FIELD_TYPE_NATURAL_WIDTH:
7521                 *ret = *((natural_width *)p);
7522                 return 0;
7523         case VMCS_FIELD_TYPE_U16:
7524                 *ret = *((u16 *)p);
7525                 return 0;
7526         case VMCS_FIELD_TYPE_U32:
7527                 *ret = *((u32 *)p);
7528                 return 0;
7529         case VMCS_FIELD_TYPE_U64:
7530                 *ret = *((u64 *)p);
7531                 return 0;
7532         default:
7533                 WARN_ON(1);
7534                 return -ENOENT;
7535         }
7536 }
7537
7538
7539 static inline int vmcs12_write_any(struct kvm_vcpu *vcpu,
7540                                    unsigned long field, u64 field_value){
7541         short offset = vmcs_field_to_offset(field);
7542         char *p = ((char *) get_vmcs12(vcpu)) + offset;
7543         if (offset < 0)
7544                 return offset;
7545
7546         switch (vmcs_field_type(field)) {
7547         case VMCS_FIELD_TYPE_U16:
7548                 *(u16 *)p = field_value;
7549                 return 0;
7550         case VMCS_FIELD_TYPE_U32:
7551                 *(u32 *)p = field_value;
7552                 return 0;
7553         case VMCS_FIELD_TYPE_U64:
7554                 *(u64 *)p = field_value;
7555                 return 0;
7556         case VMCS_FIELD_TYPE_NATURAL_WIDTH:
7557                 *(natural_width *)p = field_value;
7558                 return 0;
7559         default:
7560                 WARN_ON(1);
7561                 return -ENOENT;
7562         }
7563
7564 }
7565
7566 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx)
7567 {
7568         int i;
7569         unsigned long field;
7570         u64 field_value;
7571         struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
7572         const unsigned long *fields = shadow_read_write_fields;
7573         const int num_fields = max_shadow_read_write_fields;
7574
7575         preempt_disable();
7576
7577         vmcs_load(shadow_vmcs);
7578
7579         for (i = 0; i < num_fields; i++) {
7580                 field = fields[i];
7581                 switch (vmcs_field_type(field)) {
7582                 case VMCS_FIELD_TYPE_U16:
7583                         field_value = vmcs_read16(field);
7584                         break;
7585                 case VMCS_FIELD_TYPE_U32:
7586                         field_value = vmcs_read32(field);
7587                         break;
7588                 case VMCS_FIELD_TYPE_U64:
7589                         field_value = vmcs_read64(field);
7590                         break;
7591                 case VMCS_FIELD_TYPE_NATURAL_WIDTH:
7592                         field_value = vmcs_readl(field);
7593                         break;
7594                 default:
7595                         WARN_ON(1);
7596                         continue;
7597                 }
7598                 vmcs12_write_any(&vmx->vcpu, field, field_value);
7599         }
7600
7601         vmcs_clear(shadow_vmcs);
7602         vmcs_load(vmx->loaded_vmcs->vmcs);
7603
7604         preempt_enable();
7605 }
7606
7607 static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx)
7608 {
7609         const unsigned long *fields[] = {
7610                 shadow_read_write_fields,
7611                 shadow_read_only_fields
7612         };
7613         const int max_fields[] = {
7614                 max_shadow_read_write_fields,
7615                 max_shadow_read_only_fields
7616         };
7617         int i, q;
7618         unsigned long field;
7619         u64 field_value = 0;
7620         struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
7621
7622         vmcs_load(shadow_vmcs);
7623
7624         for (q = 0; q < ARRAY_SIZE(fields); q++) {
7625                 for (i = 0; i < max_fields[q]; i++) {
7626                         field = fields[q][i];
7627                         vmcs12_read_any(&vmx->vcpu, field, &field_value);
7628
7629                         switch (vmcs_field_type(field)) {
7630                         case VMCS_FIELD_TYPE_U16:
7631                                 vmcs_write16(field, (u16)field_value);
7632                                 break;
7633                         case VMCS_FIELD_TYPE_U32:
7634                                 vmcs_write32(field, (u32)field_value);
7635                                 break;
7636                         case VMCS_FIELD_TYPE_U64:
7637                                 vmcs_write64(field, (u64)field_value);
7638                                 break;
7639                         case VMCS_FIELD_TYPE_NATURAL_WIDTH:
7640                                 vmcs_writel(field, (long)field_value);
7641                                 break;
7642                         default:
7643                                 WARN_ON(1);
7644                                 break;
7645                         }
7646                 }
7647         }
7648
7649         vmcs_clear(shadow_vmcs);
7650         vmcs_load(vmx->loaded_vmcs->vmcs);
7651 }
7652
7653 /*
7654  * VMX instructions which assume a current vmcs12 (i.e., that VMPTRLD was
7655  * used before) all generate the same failure when it is missing.
7656  */
7657 static int nested_vmx_check_vmcs12(struct kvm_vcpu *vcpu)
7658 {
7659         struct vcpu_vmx *vmx = to_vmx(vcpu);
7660         if (vmx->nested.current_vmptr == -1ull) {
7661                 nested_vmx_failInvalid(vcpu);
7662                 return 0;
7663         }
7664         return 1;
7665 }
7666
7667 static int handle_vmread(struct kvm_vcpu *vcpu)
7668 {
7669         unsigned long field;
7670         u64 field_value;
7671         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7672         u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7673         gva_t gva = 0;
7674
7675         if (!nested_vmx_check_permission(vcpu))
7676                 return 1;
7677
7678         if (!nested_vmx_check_vmcs12(vcpu))
7679                 return kvm_skip_emulated_instruction(vcpu);
7680
7681         /* Decode instruction info and find the field to read */
7682         field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
7683         /* Read the field, zero-extended to a u64 field_value */
7684         if (vmcs12_read_any(vcpu, field, &field_value) < 0) {
7685                 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
7686                 return kvm_skip_emulated_instruction(vcpu);
7687         }
7688         /*
7689          * Now copy part of this value to register or memory, as requested.
7690          * Note that the number of bits actually copied is 32 or 64 depending
7691          * on the guest's mode (32 or 64 bit), not on the given field's length.
7692          */
7693         if (vmx_instruction_info & (1u << 10)) {
7694                 kvm_register_writel(vcpu, (((vmx_instruction_info) >> 3) & 0xf),
7695                         field_value);
7696         } else {
7697                 if (get_vmx_mem_address(vcpu, exit_qualification,
7698                                 vmx_instruction_info, true, &gva))
7699                         return 1;
7700                 /* _system ok, as hardware has verified cpl=0 */
7701                 kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, gva,
7702                              &field_value, (is_long_mode(vcpu) ? 8 : 4), NULL);
7703         }
7704
7705         nested_vmx_succeed(vcpu);
7706         return kvm_skip_emulated_instruction(vcpu);
7707 }
7708
7709
7710 static int handle_vmwrite(struct kvm_vcpu *vcpu)
7711 {
7712         unsigned long field;
7713         gva_t gva;
7714         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7715         u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7716         /* The value to write might be 32 or 64 bits, depending on L1's long
7717          * mode, and eventually we need to write that into a field of several
7718          * possible lengths. The code below first zero-extends the value to 64
7719          * bit (field_value), and then copies only the appropriate number of
7720          * bits into the vmcs12 field.
7721          */
7722         u64 field_value = 0;
7723         struct x86_exception e;
7724
7725         if (!nested_vmx_check_permission(vcpu))
7726                 return 1;
7727
7728         if (!nested_vmx_check_vmcs12(vcpu))
7729                 return kvm_skip_emulated_instruction(vcpu);
7730
7731         if (vmx_instruction_info & (1u << 10))
7732                 field_value = kvm_register_readl(vcpu,
7733                         (((vmx_instruction_info) >> 3) & 0xf));
7734         else {
7735                 if (get_vmx_mem_address(vcpu, exit_qualification,
7736                                 vmx_instruction_info, false, &gva))
7737                         return 1;
7738                 if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva,
7739                            &field_value, (is_64_bit_mode(vcpu) ? 8 : 4), &e)) {
7740                         kvm_inject_page_fault(vcpu, &e);
7741                         return 1;
7742                 }
7743         }
7744
7745
7746         field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
7747         if (vmcs_field_readonly(field)) {
7748                 nested_vmx_failValid(vcpu,
7749                         VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT);
7750                 return kvm_skip_emulated_instruction(vcpu);
7751         }
7752
7753         if (vmcs12_write_any(vcpu, field, field_value) < 0) {
7754                 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
7755                 return kvm_skip_emulated_instruction(vcpu);
7756         }
7757
7758         nested_vmx_succeed(vcpu);
7759         return kvm_skip_emulated_instruction(vcpu);
7760 }
7761
7762 static void set_current_vmptr(struct vcpu_vmx *vmx, gpa_t vmptr)
7763 {
7764         vmx->nested.current_vmptr = vmptr;
7765         if (enable_shadow_vmcs) {
7766                 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
7767                               SECONDARY_EXEC_SHADOW_VMCS);
7768                 vmcs_write64(VMCS_LINK_POINTER,
7769                              __pa(vmx->vmcs01.shadow_vmcs));
7770                 vmx->nested.sync_shadow_vmcs = true;
7771         }
7772 }
7773
7774 /* Emulate the VMPTRLD instruction */
7775 static int handle_vmptrld(struct kvm_vcpu *vcpu)
7776 {
7777         struct vcpu_vmx *vmx = to_vmx(vcpu);
7778         gpa_t vmptr;
7779
7780         if (!nested_vmx_check_permission(vcpu))
7781                 return 1;
7782
7783         if (nested_vmx_get_vmptr(vcpu, &vmptr))
7784                 return 1;
7785
7786         if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {
7787                 nested_vmx_failValid(vcpu, VMXERR_VMPTRLD_INVALID_ADDRESS);
7788                 return kvm_skip_emulated_instruction(vcpu);
7789         }
7790
7791         if (vmptr == vmx->nested.vmxon_ptr) {
7792                 nested_vmx_failValid(vcpu, VMXERR_VMPTRLD_VMXON_POINTER);
7793                 return kvm_skip_emulated_instruction(vcpu);
7794         }
7795
7796         if (vmx->nested.current_vmptr != vmptr) {
7797                 struct vmcs12 *new_vmcs12;
7798                 struct page *page;
7799                 page = kvm_vcpu_gpa_to_page(vcpu, vmptr);
7800                 if (is_error_page(page)) {
7801                         nested_vmx_failInvalid(vcpu);
7802                         return kvm_skip_emulated_instruction(vcpu);
7803                 }
7804                 new_vmcs12 = kmap(page);
7805                 if (new_vmcs12->revision_id != VMCS12_REVISION) {
7806                         kunmap(page);
7807                         kvm_release_page_clean(page);
7808                         nested_vmx_failValid(vcpu,
7809                                 VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
7810                         return kvm_skip_emulated_instruction(vcpu);
7811                 }
7812
7813                 nested_release_vmcs12(vmx);
7814                 /*
7815                  * Load VMCS12 from guest memory since it is not already
7816                  * cached.
7817                  */
7818                 memcpy(vmx->nested.cached_vmcs12, new_vmcs12, VMCS12_SIZE);
7819                 kunmap(page);
7820                 kvm_release_page_clean(page);
7821
7822                 set_current_vmptr(vmx, vmptr);
7823         }
7824
7825         nested_vmx_succeed(vcpu);
7826         return kvm_skip_emulated_instruction(vcpu);
7827 }
7828
7829 /* Emulate the VMPTRST instruction */
7830 static int handle_vmptrst(struct kvm_vcpu *vcpu)
7831 {
7832         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7833         u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7834         gva_t vmcs_gva;
7835         struct x86_exception e;
7836
7837         if (!nested_vmx_check_permission(vcpu))
7838                 return 1;
7839
7840         if (get_vmx_mem_address(vcpu, exit_qualification,
7841                         vmx_instruction_info, true, &vmcs_gva))
7842                 return 1;
7843         /* ok to use *_system, as hardware has verified cpl=0 */
7844         if (kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, vmcs_gva,
7845                                  (void *)&to_vmx(vcpu)->nested.current_vmptr,
7846                                  sizeof(u64), &e)) {
7847                 kvm_inject_page_fault(vcpu, &e);
7848                 return 1;
7849         }
7850         nested_vmx_succeed(vcpu);
7851         return kvm_skip_emulated_instruction(vcpu);
7852 }
7853
7854 /* Emulate the INVEPT instruction */
7855 static int handle_invept(struct kvm_vcpu *vcpu)
7856 {
7857         struct vcpu_vmx *vmx = to_vmx(vcpu);
7858         u32 vmx_instruction_info, types;
7859         unsigned long type;
7860         gva_t gva;
7861         struct x86_exception e;
7862         struct {
7863                 u64 eptp, gpa;
7864         } operand;
7865
7866         if (!(vmx->nested.nested_vmx_secondary_ctls_high &
7867               SECONDARY_EXEC_ENABLE_EPT) ||
7868             !(vmx->nested.nested_vmx_ept_caps & VMX_EPT_INVEPT_BIT)) {
7869                 kvm_queue_exception(vcpu, UD_VECTOR);
7870                 return 1;
7871         }
7872
7873         if (!nested_vmx_check_permission(vcpu))
7874                 return 1;
7875
7876         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7877         type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
7878
7879         types = (vmx->nested.nested_vmx_ept_caps >> VMX_EPT_EXTENT_SHIFT) & 6;
7880
7881         if (type >= 32 || !(types & (1 << type))) {
7882                 nested_vmx_failValid(vcpu,
7883                                 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
7884                 return kvm_skip_emulated_instruction(vcpu);
7885         }
7886
7887         /* According to the Intel VMX instruction reference, the memory
7888          * operand is read even if it isn't needed (e.g., for type==global)
7889          */
7890         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
7891                         vmx_instruction_info, false, &gva))
7892                 return 1;
7893         if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &operand,
7894                                 sizeof(operand), &e)) {
7895                 kvm_inject_page_fault(vcpu, &e);
7896                 return 1;
7897         }
7898
7899         switch (type) {
7900         case VMX_EPT_EXTENT_GLOBAL:
7901         /*
7902          * TODO: track mappings and invalidate
7903          * single context requests appropriately
7904          */
7905         case VMX_EPT_EXTENT_CONTEXT:
7906                 kvm_mmu_sync_roots(vcpu);
7907                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
7908                 nested_vmx_succeed(vcpu);
7909                 break;
7910         default:
7911                 BUG_ON(1);
7912                 break;
7913         }
7914
7915         return kvm_skip_emulated_instruction(vcpu);
7916 }
7917
7918 static int handle_invvpid(struct kvm_vcpu *vcpu)
7919 {
7920         struct vcpu_vmx *vmx = to_vmx(vcpu);
7921         u32 vmx_instruction_info;
7922         unsigned long type, types;
7923         gva_t gva;
7924         struct x86_exception e;
7925         struct {
7926                 u64 vpid;
7927                 u64 gla;
7928         } operand;
7929
7930         if (!(vmx->nested.nested_vmx_secondary_ctls_high &
7931               SECONDARY_EXEC_ENABLE_VPID) ||
7932                         !(vmx->nested.nested_vmx_vpid_caps & VMX_VPID_INVVPID_BIT)) {
7933                 kvm_queue_exception(vcpu, UD_VECTOR);
7934                 return 1;
7935         }
7936
7937         if (!nested_vmx_check_permission(vcpu))
7938                 return 1;
7939
7940         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7941         type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
7942
7943         types = (vmx->nested.nested_vmx_vpid_caps &
7944                         VMX_VPID_EXTENT_SUPPORTED_MASK) >> 8;
7945
7946         if (type >= 32 || !(types & (1 << type))) {
7947                 nested_vmx_failValid(vcpu,
7948                         VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
7949                 return kvm_skip_emulated_instruction(vcpu);
7950         }
7951
7952         /* according to the intel vmx instruction reference, the memory
7953          * operand is read even if it isn't needed (e.g., for type==global)
7954          */
7955         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
7956                         vmx_instruction_info, false, &gva))
7957                 return 1;
7958         if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &operand,
7959                                 sizeof(operand), &e)) {
7960                 kvm_inject_page_fault(vcpu, &e);
7961                 return 1;
7962         }
7963         if (operand.vpid >> 16) {
7964                 nested_vmx_failValid(vcpu,
7965                         VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
7966                 return kvm_skip_emulated_instruction(vcpu);
7967         }
7968
7969         switch (type) {
7970         case VMX_VPID_EXTENT_INDIVIDUAL_ADDR:
7971                 if (is_noncanonical_address(operand.gla, vcpu)) {
7972                         nested_vmx_failValid(vcpu,
7973                                 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
7974                         return kvm_skip_emulated_instruction(vcpu);
7975                 }
7976                 /* fall through */
7977         case VMX_VPID_EXTENT_SINGLE_CONTEXT:
7978         case VMX_VPID_EXTENT_SINGLE_NON_GLOBAL:
7979                 if (!operand.vpid) {
7980                         nested_vmx_failValid(vcpu,
7981                                 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
7982                         return kvm_skip_emulated_instruction(vcpu);
7983                 }
7984                 break;
7985         case VMX_VPID_EXTENT_ALL_CONTEXT:
7986                 break;
7987         default:
7988                 WARN_ON_ONCE(1);
7989                 return kvm_skip_emulated_instruction(vcpu);
7990         }
7991
7992         __vmx_flush_tlb(vcpu, vmx->nested.vpid02);
7993         nested_vmx_succeed(vcpu);
7994
7995         return kvm_skip_emulated_instruction(vcpu);
7996 }
7997
7998 static int handle_pml_full(struct kvm_vcpu *vcpu)
7999 {
8000         unsigned long exit_qualification;
8001
8002         trace_kvm_pml_full(vcpu->vcpu_id);
8003
8004         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8005
8006         /*
8007          * PML buffer FULL happened while executing iret from NMI,
8008          * "blocked by NMI" bit has to be set before next VM entry.
8009          */
8010         if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
8011                         cpu_has_virtual_nmis() &&
8012                         (exit_qualification & INTR_INFO_UNBLOCK_NMI))
8013                 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
8014                                 GUEST_INTR_STATE_NMI);
8015
8016         /*
8017          * PML buffer already flushed at beginning of VMEXIT. Nothing to do
8018          * here.., and there's no userspace involvement needed for PML.
8019          */
8020         return 1;
8021 }
8022
8023 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
8024 {
8025         kvm_lapic_expired_hv_timer(vcpu);
8026         return 1;
8027 }
8028
8029 static bool valid_ept_address(struct kvm_vcpu *vcpu, u64 address)
8030 {
8031         struct vcpu_vmx *vmx = to_vmx(vcpu);
8032         int maxphyaddr = cpuid_maxphyaddr(vcpu);
8033
8034         /* Check for memory type validity */
8035         switch (address & VMX_EPTP_MT_MASK) {
8036         case VMX_EPTP_MT_UC:
8037                 if (!(vmx->nested.nested_vmx_ept_caps & VMX_EPTP_UC_BIT))
8038                         return false;
8039                 break;
8040         case VMX_EPTP_MT_WB:
8041                 if (!(vmx->nested.nested_vmx_ept_caps & VMX_EPTP_WB_BIT))
8042                         return false;
8043                 break;
8044         default:
8045                 return false;
8046         }
8047
8048         /* only 4 levels page-walk length are valid */
8049         if ((address & VMX_EPTP_PWL_MASK) != VMX_EPTP_PWL_4)
8050                 return false;
8051
8052         /* Reserved bits should not be set */
8053         if (address >> maxphyaddr || ((address >> 7) & 0x1f))
8054                 return false;
8055
8056         /* AD, if set, should be supported */
8057         if (address & VMX_EPTP_AD_ENABLE_BIT) {
8058                 if (!(vmx->nested.nested_vmx_ept_caps & VMX_EPT_AD_BIT))
8059                         return false;
8060         }
8061
8062         return true;
8063 }
8064
8065 static int nested_vmx_eptp_switching(struct kvm_vcpu *vcpu,
8066                                      struct vmcs12 *vmcs12)
8067 {
8068         u32 index = vcpu->arch.regs[VCPU_REGS_RCX];
8069         u64 address;
8070         bool accessed_dirty;
8071         struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
8072
8073         if (!nested_cpu_has_eptp_switching(vmcs12) ||
8074             !nested_cpu_has_ept(vmcs12))
8075                 return 1;
8076
8077         if (index >= VMFUNC_EPTP_ENTRIES)
8078                 return 1;
8079
8080
8081         if (kvm_vcpu_read_guest_page(vcpu, vmcs12->eptp_list_address >> PAGE_SHIFT,
8082                                      &address, index * 8, 8))
8083                 return 1;
8084
8085         accessed_dirty = !!(address & VMX_EPTP_AD_ENABLE_BIT);
8086
8087         /*
8088          * If the (L2) guest does a vmfunc to the currently
8089          * active ept pointer, we don't have to do anything else
8090          */
8091         if (vmcs12->ept_pointer != address) {
8092                 if (!valid_ept_address(vcpu, address))
8093                         return 1;
8094
8095                 kvm_mmu_unload(vcpu);
8096                 mmu->ept_ad = accessed_dirty;
8097                 mmu->base_role.ad_disabled = !accessed_dirty;
8098                 vmcs12->ept_pointer = address;
8099                 /*
8100                  * TODO: Check what's the correct approach in case
8101                  * mmu reload fails. Currently, we just let the next
8102                  * reload potentially fail
8103                  */
8104                 kvm_mmu_reload(vcpu);
8105         }
8106
8107         return 0;
8108 }
8109
8110 static int handle_vmfunc(struct kvm_vcpu *vcpu)
8111 {
8112         struct vcpu_vmx *vmx = to_vmx(vcpu);
8113         struct vmcs12 *vmcs12;
8114         u32 function = vcpu->arch.regs[VCPU_REGS_RAX];
8115
8116         /*
8117          * VMFUNC is only supported for nested guests, but we always enable the
8118          * secondary control for simplicity; for non-nested mode, fake that we
8119          * didn't by injecting #UD.
8120          */
8121         if (!is_guest_mode(vcpu)) {
8122                 kvm_queue_exception(vcpu, UD_VECTOR);
8123                 return 1;
8124         }
8125
8126         vmcs12 = get_vmcs12(vcpu);
8127         if ((vmcs12->vm_function_control & (1 << function)) == 0)
8128                 goto fail;
8129
8130         switch (function) {
8131         case 0:
8132                 if (nested_vmx_eptp_switching(vcpu, vmcs12))
8133                         goto fail;
8134                 break;
8135         default:
8136                 goto fail;
8137         }
8138         return kvm_skip_emulated_instruction(vcpu);
8139
8140 fail:
8141         nested_vmx_vmexit(vcpu, vmx->exit_reason,
8142                           vmcs_read32(VM_EXIT_INTR_INFO),
8143                           vmcs_readl(EXIT_QUALIFICATION));
8144         return 1;
8145 }
8146
8147 /*
8148  * The exit handlers return 1 if the exit was handled fully and guest execution
8149  * may resume.  Otherwise they set the kvm_run parameter to indicate what needs
8150  * to be done to userspace and return 0.
8151  */
8152 static int (*const kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
8153         [EXIT_REASON_EXCEPTION_NMI]           = handle_exception,
8154         [EXIT_REASON_EXTERNAL_INTERRUPT]      = handle_external_interrupt,
8155         [EXIT_REASON_TRIPLE_FAULT]            = handle_triple_fault,
8156         [EXIT_REASON_NMI_WINDOW]              = handle_nmi_window,
8157         [EXIT_REASON_IO_INSTRUCTION]          = handle_io,
8158         [EXIT_REASON_CR_ACCESS]               = handle_cr,
8159         [EXIT_REASON_DR_ACCESS]               = handle_dr,
8160         [EXIT_REASON_CPUID]                   = handle_cpuid,
8161         [EXIT_REASON_MSR_READ]                = handle_rdmsr,
8162         [EXIT_REASON_MSR_WRITE]               = handle_wrmsr,
8163         [EXIT_REASON_PENDING_INTERRUPT]       = handle_interrupt_window,
8164         [EXIT_REASON_HLT]                     = handle_halt,
8165         [EXIT_REASON_INVD]                    = handle_invd,
8166         [EXIT_REASON_INVLPG]                  = handle_invlpg,
8167         [EXIT_REASON_RDPMC]                   = handle_rdpmc,
8168         [EXIT_REASON_VMCALL]                  = handle_vmcall,
8169         [EXIT_REASON_VMCLEAR]                 = handle_vmclear,
8170         [EXIT_REASON_VMLAUNCH]                = handle_vmlaunch,
8171         [EXIT_REASON_VMPTRLD]                 = handle_vmptrld,
8172         [EXIT_REASON_VMPTRST]                 = handle_vmptrst,
8173         [EXIT_REASON_VMREAD]                  = handle_vmread,
8174         [EXIT_REASON_VMRESUME]                = handle_vmresume,
8175         [EXIT_REASON_VMWRITE]                 = handle_vmwrite,
8176         [EXIT_REASON_VMOFF]                   = handle_vmoff,
8177         [EXIT_REASON_VMON]                    = handle_vmon,
8178         [EXIT_REASON_TPR_BELOW_THRESHOLD]     = handle_tpr_below_threshold,
8179         [EXIT_REASON_APIC_ACCESS]             = handle_apic_access,
8180         [EXIT_REASON_APIC_WRITE]              = handle_apic_write,
8181         [EXIT_REASON_EOI_INDUCED]             = handle_apic_eoi_induced,
8182         [EXIT_REASON_WBINVD]                  = handle_wbinvd,
8183         [EXIT_REASON_XSETBV]                  = handle_xsetbv,
8184         [EXIT_REASON_TASK_SWITCH]             = handle_task_switch,
8185         [EXIT_REASON_MCE_DURING_VMENTRY]      = handle_machine_check,
8186         [EXIT_REASON_EPT_VIOLATION]           = handle_ept_violation,
8187         [EXIT_REASON_EPT_MISCONFIG]           = handle_ept_misconfig,
8188         [EXIT_REASON_PAUSE_INSTRUCTION]       = handle_pause,
8189         [EXIT_REASON_MWAIT_INSTRUCTION]       = handle_mwait,
8190         [EXIT_REASON_MONITOR_TRAP_FLAG]       = handle_monitor_trap,
8191         [EXIT_REASON_MONITOR_INSTRUCTION]     = handle_monitor,
8192         [EXIT_REASON_INVEPT]                  = handle_invept,
8193         [EXIT_REASON_INVVPID]                 = handle_invvpid,
8194         [EXIT_REASON_RDRAND]                  = handle_invalid_op,
8195         [EXIT_REASON_RDSEED]                  = handle_invalid_op,
8196         [EXIT_REASON_XSAVES]                  = handle_xsaves,
8197         [EXIT_REASON_XRSTORS]                 = handle_xrstors,
8198         [EXIT_REASON_PML_FULL]                = handle_pml_full,
8199         [EXIT_REASON_VMFUNC]                  = handle_vmfunc,
8200         [EXIT_REASON_PREEMPTION_TIMER]        = handle_preemption_timer,
8201 };
8202
8203 static const int kvm_vmx_max_exit_handlers =
8204         ARRAY_SIZE(kvm_vmx_exit_handlers);
8205
8206 static bool nested_vmx_exit_handled_io(struct kvm_vcpu *vcpu,
8207                                        struct vmcs12 *vmcs12)
8208 {
8209         unsigned long exit_qualification;
8210         gpa_t bitmap, last_bitmap;
8211         unsigned int port;
8212         int size;
8213         u8 b;
8214
8215         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
8216                 return nested_cpu_has(vmcs12, CPU_BASED_UNCOND_IO_EXITING);
8217
8218         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8219
8220         port = exit_qualification >> 16;
8221         size = (exit_qualification & 7) + 1;
8222
8223         last_bitmap = (gpa_t)-1;
8224         b = -1;
8225
8226         while (size > 0) {
8227                 if (port < 0x8000)
8228                         bitmap = vmcs12->io_bitmap_a;
8229                 else if (port < 0x10000)
8230                         bitmap = vmcs12->io_bitmap_b;
8231                 else
8232                         return true;
8233                 bitmap += (port & 0x7fff) / 8;
8234
8235                 if (last_bitmap != bitmap)
8236                         if (kvm_vcpu_read_guest(vcpu, bitmap, &b, 1))
8237                                 return true;
8238                 if (b & (1 << (port & 7)))
8239                         return true;
8240
8241                 port++;
8242                 size--;
8243                 last_bitmap = bitmap;
8244         }
8245
8246         return false;
8247 }
8248
8249 /*
8250  * Return 1 if we should exit from L2 to L1 to handle an MSR access access,
8251  * rather than handle it ourselves in L0. I.e., check whether L1 expressed
8252  * disinterest in the current event (read or write a specific MSR) by using an
8253  * MSR bitmap. This may be the case even when L0 doesn't use MSR bitmaps.
8254  */
8255 static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu,
8256         struct vmcs12 *vmcs12, u32 exit_reason)
8257 {
8258         u32 msr_index = vcpu->arch.regs[VCPU_REGS_RCX];
8259         gpa_t bitmap;
8260
8261         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
8262                 return true;
8263
8264         /*
8265          * The MSR_BITMAP page is divided into four 1024-byte bitmaps,
8266          * for the four combinations of read/write and low/high MSR numbers.
8267          * First we need to figure out which of the four to use:
8268          */
8269         bitmap = vmcs12->msr_bitmap;
8270         if (exit_reason == EXIT_REASON_MSR_WRITE)
8271                 bitmap += 2048;
8272         if (msr_index >= 0xc0000000) {
8273                 msr_index -= 0xc0000000;
8274                 bitmap += 1024;
8275         }
8276
8277         /* Then read the msr_index'th bit from this bitmap: */
8278         if (msr_index < 1024*8) {
8279                 unsigned char b;
8280                 if (kvm_vcpu_read_guest(vcpu, bitmap + msr_index/8, &b, 1))
8281                         return true;
8282                 return 1 & (b >> (msr_index & 7));
8283         } else
8284                 return true; /* let L1 handle the wrong parameter */
8285 }
8286
8287 /*
8288  * Return 1 if we should exit from L2 to L1 to handle a CR access exit,
8289  * rather than handle it ourselves in L0. I.e., check if L1 wanted to
8290  * intercept (via guest_host_mask etc.) the current event.
8291  */
8292 static bool nested_vmx_exit_handled_cr(struct kvm_vcpu *vcpu,
8293         struct vmcs12 *vmcs12)
8294 {
8295         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8296         int cr = exit_qualification & 15;
8297         int reg;
8298         unsigned long val;
8299
8300         switch ((exit_qualification >> 4) & 3) {
8301         case 0: /* mov to cr */
8302                 reg = (exit_qualification >> 8) & 15;
8303                 val = kvm_register_readl(vcpu, reg);
8304                 switch (cr) {
8305                 case 0:
8306                         if (vmcs12->cr0_guest_host_mask &
8307                             (val ^ vmcs12->cr0_read_shadow))
8308                                 return true;
8309                         break;
8310                 case 3:
8311                         if ((vmcs12->cr3_target_count >= 1 &&
8312                                         vmcs12->cr3_target_value0 == val) ||
8313                                 (vmcs12->cr3_target_count >= 2 &&
8314                                         vmcs12->cr3_target_value1 == val) ||
8315                                 (vmcs12->cr3_target_count >= 3 &&
8316                                         vmcs12->cr3_target_value2 == val) ||
8317                                 (vmcs12->cr3_target_count >= 4 &&
8318                                         vmcs12->cr3_target_value3 == val))
8319                                 return false;
8320                         if (nested_cpu_has(vmcs12, CPU_BASED_CR3_LOAD_EXITING))
8321                                 return true;
8322                         break;
8323                 case 4:
8324                         if (vmcs12->cr4_guest_host_mask &
8325                             (vmcs12->cr4_read_shadow ^ val))
8326                                 return true;
8327                         break;
8328                 case 8:
8329                         if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING))
8330                                 return true;
8331                         break;
8332                 }
8333                 break;
8334         case 2: /* clts */
8335                 if ((vmcs12->cr0_guest_host_mask & X86_CR0_TS) &&
8336                     (vmcs12->cr0_read_shadow & X86_CR0_TS))
8337                         return true;
8338                 break;
8339         case 1: /* mov from cr */
8340                 switch (cr) {
8341                 case 3:
8342                         if (vmcs12->cpu_based_vm_exec_control &
8343                             CPU_BASED_CR3_STORE_EXITING)
8344                                 return true;
8345                         break;
8346                 case 8:
8347                         if (vmcs12->cpu_based_vm_exec_control &
8348                             CPU_BASED_CR8_STORE_EXITING)
8349                                 return true;
8350                         break;
8351                 }
8352                 break;
8353         case 3: /* lmsw */
8354                 /*
8355                  * lmsw can change bits 1..3 of cr0, and only set bit 0 of
8356                  * cr0. Other attempted changes are ignored, with no exit.
8357                  */
8358                 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
8359                 if (vmcs12->cr0_guest_host_mask & 0xe &
8360                     (val ^ vmcs12->cr0_read_shadow))
8361                         return true;
8362                 if ((vmcs12->cr0_guest_host_mask & 0x1) &&
8363                     !(vmcs12->cr0_read_shadow & 0x1) &&
8364                     (val & 0x1))
8365                         return true;
8366                 break;
8367         }
8368         return false;
8369 }
8370
8371 /*
8372  * Return 1 if we should exit from L2 to L1 to handle an exit, or 0 if we
8373  * should handle it ourselves in L0 (and then continue L2). Only call this
8374  * when in is_guest_mode (L2).
8375  */
8376 static bool nested_vmx_exit_reflected(struct kvm_vcpu *vcpu, u32 exit_reason)
8377 {
8378         u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
8379         struct vcpu_vmx *vmx = to_vmx(vcpu);
8380         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
8381
8382         if (vmx->nested.nested_run_pending)
8383                 return false;
8384
8385         if (unlikely(vmx->fail)) {
8386                 pr_info_ratelimited("%s failed vm entry %x\n", __func__,
8387                                     vmcs_read32(VM_INSTRUCTION_ERROR));
8388                 return true;
8389         }
8390
8391         /*
8392          * The host physical addresses of some pages of guest memory
8393          * are loaded into VMCS02 (e.g. L1's Virtual APIC Page). The CPU
8394          * may write to these pages via their host physical address while
8395          * L2 is running, bypassing any address-translation-based dirty
8396          * tracking (e.g. EPT write protection).
8397          *
8398          * Mark them dirty on every exit from L2 to prevent them from
8399          * getting out of sync with dirty tracking.
8400          */
8401         nested_mark_vmcs12_pages_dirty(vcpu);
8402
8403         trace_kvm_nested_vmexit(kvm_rip_read(vcpu), exit_reason,
8404                                 vmcs_readl(EXIT_QUALIFICATION),
8405                                 vmx->idt_vectoring_info,
8406                                 intr_info,
8407                                 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
8408                                 KVM_ISA_VMX);
8409
8410         switch (exit_reason) {
8411         case EXIT_REASON_EXCEPTION_NMI:
8412                 if (is_nmi(intr_info))
8413                         return false;
8414                 else if (is_page_fault(intr_info))
8415                         return !vmx->vcpu.arch.apf.host_apf_reason && enable_ept;
8416                 else if (is_no_device(intr_info) &&
8417                          !(vmcs12->guest_cr0 & X86_CR0_TS))
8418                         return false;
8419                 else if (is_debug(intr_info) &&
8420                          vcpu->guest_debug &
8421                          (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
8422                         return false;
8423                 else if (is_breakpoint(intr_info) &&
8424                          vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
8425                         return false;
8426                 return vmcs12->exception_bitmap &
8427                                 (1u << (intr_info & INTR_INFO_VECTOR_MASK));
8428         case EXIT_REASON_EXTERNAL_INTERRUPT:
8429                 return false;
8430         case EXIT_REASON_TRIPLE_FAULT:
8431                 return true;
8432         case EXIT_REASON_PENDING_INTERRUPT:
8433                 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_INTR_PENDING);
8434         case EXIT_REASON_NMI_WINDOW:
8435                 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING);
8436         case EXIT_REASON_TASK_SWITCH:
8437                 return true;
8438         case EXIT_REASON_CPUID:
8439                 return true;
8440         case EXIT_REASON_HLT:
8441                 return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
8442         case EXIT_REASON_INVD:
8443                 return true;
8444         case EXIT_REASON_INVLPG:
8445                 return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
8446         case EXIT_REASON_RDPMC:
8447                 return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
8448         case EXIT_REASON_RDRAND:
8449                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDRAND);
8450         case EXIT_REASON_RDSEED:
8451                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDSEED);
8452         case EXIT_REASON_RDTSC: case EXIT_REASON_RDTSCP:
8453                 return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
8454         case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
8455         case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
8456         case EXIT_REASON_VMPTRST: case EXIT_REASON_VMREAD:
8457         case EXIT_REASON_VMRESUME: case EXIT_REASON_VMWRITE:
8458         case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
8459         case EXIT_REASON_INVEPT: case EXIT_REASON_INVVPID:
8460                 /*
8461                  * VMX instructions trap unconditionally. This allows L1 to
8462                  * emulate them for its L2 guest, i.e., allows 3-level nesting!
8463                  */
8464                 return true;
8465         case EXIT_REASON_CR_ACCESS:
8466                 return nested_vmx_exit_handled_cr(vcpu, vmcs12);
8467         case EXIT_REASON_DR_ACCESS:
8468                 return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
8469         case EXIT_REASON_IO_INSTRUCTION:
8470                 return nested_vmx_exit_handled_io(vcpu, vmcs12);
8471         case EXIT_REASON_GDTR_IDTR: case EXIT_REASON_LDTR_TR:
8472                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC);
8473         case EXIT_REASON_MSR_READ:
8474         case EXIT_REASON_MSR_WRITE:
8475                 return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
8476         case EXIT_REASON_INVALID_STATE:
8477                 return true;
8478         case EXIT_REASON_MWAIT_INSTRUCTION:
8479                 return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
8480         case EXIT_REASON_MONITOR_TRAP_FLAG:
8481                 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_TRAP_FLAG);
8482         case EXIT_REASON_MONITOR_INSTRUCTION:
8483                 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
8484         case EXIT_REASON_PAUSE_INSTRUCTION:
8485                 return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
8486                         nested_cpu_has2(vmcs12,
8487                                 SECONDARY_EXEC_PAUSE_LOOP_EXITING);
8488         case EXIT_REASON_MCE_DURING_VMENTRY:
8489                 return false;
8490         case EXIT_REASON_TPR_BELOW_THRESHOLD:
8491                 return nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW);
8492         case EXIT_REASON_APIC_ACCESS:
8493                 return nested_cpu_has2(vmcs12,
8494                         SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
8495         case EXIT_REASON_APIC_WRITE:
8496         case EXIT_REASON_EOI_INDUCED:
8497                 /* apic_write and eoi_induced should exit unconditionally. */
8498                 return true;
8499         case EXIT_REASON_EPT_VIOLATION:
8500                 /*
8501                  * L0 always deals with the EPT violation. If nested EPT is
8502                  * used, and the nested mmu code discovers that the address is
8503                  * missing in the guest EPT table (EPT12), the EPT violation
8504                  * will be injected with nested_ept_inject_page_fault()
8505                  */
8506                 return false;
8507         case EXIT_REASON_EPT_MISCONFIG:
8508                 /*
8509                  * L2 never uses directly L1's EPT, but rather L0's own EPT
8510                  * table (shadow on EPT) or a merged EPT table that L0 built
8511                  * (EPT on EPT). So any problems with the structure of the
8512                  * table is L0's fault.
8513                  */
8514                 return false;
8515         case EXIT_REASON_INVPCID:
8516                 return
8517                         nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_INVPCID) &&
8518                         nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
8519         case EXIT_REASON_WBINVD:
8520                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
8521         case EXIT_REASON_XSETBV:
8522                 return true;
8523         case EXIT_REASON_XSAVES: case EXIT_REASON_XRSTORS:
8524                 /*
8525                  * This should never happen, since it is not possible to
8526                  * set XSS to a non-zero value---neither in L1 nor in L2.
8527                  * If if it were, XSS would have to be checked against
8528                  * the XSS exit bitmap in vmcs12.
8529                  */
8530                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
8531         case EXIT_REASON_PREEMPTION_TIMER:
8532                 return false;
8533         case EXIT_REASON_PML_FULL:
8534                 /* We emulate PML support to L1. */
8535                 return false;
8536         case EXIT_REASON_VMFUNC:
8537                 /* VM functions are emulated through L2->L0 vmexits. */
8538                 return false;
8539         default:
8540                 return true;
8541         }
8542 }
8543
8544 static int nested_vmx_reflect_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason)
8545 {
8546         u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
8547
8548         /*
8549          * At this point, the exit interruption info in exit_intr_info
8550          * is only valid for EXCEPTION_NMI exits.  For EXTERNAL_INTERRUPT
8551          * we need to query the in-kernel LAPIC.
8552          */
8553         WARN_ON(exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT);
8554         if ((exit_intr_info &
8555              (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) ==
8556             (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) {
8557                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
8558                 vmcs12->vm_exit_intr_error_code =
8559                         vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
8560         }
8561
8562         nested_vmx_vmexit(vcpu, exit_reason, exit_intr_info,
8563                           vmcs_readl(EXIT_QUALIFICATION));
8564         return 1;
8565 }
8566
8567 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
8568 {
8569         *info1 = vmcs_readl(EXIT_QUALIFICATION);
8570         *info2 = vmcs_read32(VM_EXIT_INTR_INFO);
8571 }
8572
8573 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
8574 {
8575         if (vmx->pml_pg) {
8576                 __free_page(vmx->pml_pg);
8577                 vmx->pml_pg = NULL;
8578         }
8579 }
8580
8581 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
8582 {
8583         struct vcpu_vmx *vmx = to_vmx(vcpu);
8584         u64 *pml_buf;
8585         u16 pml_idx;
8586
8587         pml_idx = vmcs_read16(GUEST_PML_INDEX);
8588
8589         /* Do nothing if PML buffer is empty */
8590         if (pml_idx == (PML_ENTITY_NUM - 1))
8591                 return;
8592
8593         /* PML index always points to next available PML buffer entity */
8594         if (pml_idx >= PML_ENTITY_NUM)
8595                 pml_idx = 0;
8596         else
8597                 pml_idx++;
8598
8599         pml_buf = page_address(vmx->pml_pg);
8600         for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
8601                 u64 gpa;
8602
8603                 gpa = pml_buf[pml_idx];
8604                 WARN_ON(gpa & (PAGE_SIZE - 1));
8605                 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
8606         }
8607
8608         /* reset PML index */
8609         vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
8610 }
8611
8612 /*
8613  * Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
8614  * Called before reporting dirty_bitmap to userspace.
8615  */
8616 static void kvm_flush_pml_buffers(struct kvm *kvm)
8617 {
8618         int i;
8619         struct kvm_vcpu *vcpu;
8620         /*
8621          * We only need to kick vcpu out of guest mode here, as PML buffer
8622          * is flushed at beginning of all VMEXITs, and it's obvious that only
8623          * vcpus running in guest are possible to have unflushed GPAs in PML
8624          * buffer.
8625          */
8626         kvm_for_each_vcpu(i, vcpu, kvm)
8627                 kvm_vcpu_kick(vcpu);
8628 }
8629
8630 static void vmx_dump_sel(char *name, uint32_t sel)
8631 {
8632         pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
8633                name, vmcs_read16(sel),
8634                vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
8635                vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
8636                vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
8637 }
8638
8639 static void vmx_dump_dtsel(char *name, uint32_t limit)
8640 {
8641         pr_err("%s                           limit=0x%08x, base=0x%016lx\n",
8642                name, vmcs_read32(limit),
8643                vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
8644 }
8645
8646 static void dump_vmcs(void)
8647 {
8648         u32 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
8649         u32 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
8650         u32 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
8651         u32 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
8652         u32 secondary_exec_control = 0;
8653         unsigned long cr4 = vmcs_readl(GUEST_CR4);
8654         u64 efer = vmcs_read64(GUEST_IA32_EFER);
8655         int i, n;
8656
8657         if (cpu_has_secondary_exec_ctrls())
8658                 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
8659
8660         pr_err("*** Guest State ***\n");
8661         pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
8662                vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
8663                vmcs_readl(CR0_GUEST_HOST_MASK));
8664         pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
8665                cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
8666         pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
8667         if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
8668             (cr4 & X86_CR4_PAE) && !(efer & EFER_LMA))
8669         {
8670                 pr_err("PDPTR0 = 0x%016llx  PDPTR1 = 0x%016llx\n",
8671                        vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
8672                 pr_err("PDPTR2 = 0x%016llx  PDPTR3 = 0x%016llx\n",
8673                        vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
8674         }
8675         pr_err("RSP = 0x%016lx  RIP = 0x%016lx\n",
8676                vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
8677         pr_err("RFLAGS=0x%08lx         DR7 = 0x%016lx\n",
8678                vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
8679         pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
8680                vmcs_readl(GUEST_SYSENTER_ESP),
8681                vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
8682         vmx_dump_sel("CS:  ", GUEST_CS_SELECTOR);
8683         vmx_dump_sel("DS:  ", GUEST_DS_SELECTOR);
8684         vmx_dump_sel("SS:  ", GUEST_SS_SELECTOR);
8685         vmx_dump_sel("ES:  ", GUEST_ES_SELECTOR);
8686         vmx_dump_sel("FS:  ", GUEST_FS_SELECTOR);
8687         vmx_dump_sel("GS:  ", GUEST_GS_SELECTOR);
8688         vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
8689         vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
8690         vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
8691         vmx_dump_sel("TR:  ", GUEST_TR_SELECTOR);
8692         if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
8693             (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
8694                 pr_err("EFER =     0x%016llx  PAT = 0x%016llx\n",
8695                        efer, vmcs_read64(GUEST_IA32_PAT));
8696         pr_err("DebugCtl = 0x%016llx  DebugExceptions = 0x%016lx\n",
8697                vmcs_read64(GUEST_IA32_DEBUGCTL),
8698                vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
8699         if (vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
8700                 pr_err("PerfGlobCtl = 0x%016llx\n",
8701                        vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
8702         if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
8703                 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
8704         pr_err("Interruptibility = %08x  ActivityState = %08x\n",
8705                vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
8706                vmcs_read32(GUEST_ACTIVITY_STATE));
8707         if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
8708                 pr_err("InterruptStatus = %04x\n",
8709                        vmcs_read16(GUEST_INTR_STATUS));
8710
8711         pr_err("*** Host State ***\n");
8712         pr_err("RIP = 0x%016lx  RSP = 0x%016lx\n",
8713                vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
8714         pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
8715                vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
8716                vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
8717                vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
8718                vmcs_read16(HOST_TR_SELECTOR));
8719         pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
8720                vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
8721                vmcs_readl(HOST_TR_BASE));
8722         pr_err("GDTBase=%016lx IDTBase=%016lx\n",
8723                vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
8724         pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
8725                vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
8726                vmcs_readl(HOST_CR4));
8727         pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
8728                vmcs_readl(HOST_IA32_SYSENTER_ESP),
8729                vmcs_read32(HOST_IA32_SYSENTER_CS),
8730                vmcs_readl(HOST_IA32_SYSENTER_EIP));
8731         if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
8732                 pr_err("EFER = 0x%016llx  PAT = 0x%016llx\n",
8733                        vmcs_read64(HOST_IA32_EFER),
8734                        vmcs_read64(HOST_IA32_PAT));
8735         if (vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
8736                 pr_err("PerfGlobCtl = 0x%016llx\n",
8737                        vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
8738
8739         pr_err("*** Control State ***\n");
8740         pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
8741                pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
8742         pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
8743         pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
8744                vmcs_read32(EXCEPTION_BITMAP),
8745                vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
8746                vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
8747         pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
8748                vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
8749                vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
8750                vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
8751         pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
8752                vmcs_read32(VM_EXIT_INTR_INFO),
8753                vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
8754                vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
8755         pr_err("        reason=%08x qualification=%016lx\n",
8756                vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
8757         pr_err("IDTVectoring: info=%08x errcode=%08x\n",
8758                vmcs_read32(IDT_VECTORING_INFO_FIELD),
8759                vmcs_read32(IDT_VECTORING_ERROR_CODE));
8760         pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
8761         if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
8762                 pr_err("TSC Multiplier = 0x%016llx\n",
8763                        vmcs_read64(TSC_MULTIPLIER));
8764         if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW)
8765                 pr_err("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
8766         if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
8767                 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
8768         if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
8769                 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
8770         n = vmcs_read32(CR3_TARGET_COUNT);
8771         for (i = 0; i + 1 < n; i += 4)
8772                 pr_err("CR3 target%u=%016lx target%u=%016lx\n",
8773                        i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2),
8774                        i + 1, vmcs_readl(CR3_TARGET_VALUE0 + i * 2 + 2));
8775         if (i < n)
8776                 pr_err("CR3 target%u=%016lx\n",
8777                        i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2));
8778         if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
8779                 pr_err("PLE Gap=%08x Window=%08x\n",
8780                        vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
8781         if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
8782                 pr_err("Virtual processor ID = 0x%04x\n",
8783                        vmcs_read16(VIRTUAL_PROCESSOR_ID));
8784 }
8785
8786 /*
8787  * The guest has exited.  See if we can fix it or if we need userspace
8788  * assistance.
8789  */
8790 static int vmx_handle_exit(struct kvm_vcpu *vcpu)
8791 {
8792         struct vcpu_vmx *vmx = to_vmx(vcpu);
8793         u32 exit_reason = vmx->exit_reason;
8794         u32 vectoring_info = vmx->idt_vectoring_info;
8795
8796         trace_kvm_exit(exit_reason, vcpu, KVM_ISA_VMX);
8797
8798         /*
8799          * Flush logged GPAs PML buffer, this will make dirty_bitmap more
8800          * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
8801          * querying dirty_bitmap, we only need to kick all vcpus out of guest
8802          * mode as if vcpus is in root mode, the PML buffer must has been
8803          * flushed already.
8804          */
8805         if (enable_pml)
8806                 vmx_flush_pml_buffer(vcpu);
8807
8808         /* If guest state is invalid, start emulating */
8809         if (vmx->emulation_required)
8810                 return handle_invalid_guest_state(vcpu);
8811
8812         if (is_guest_mode(vcpu) && nested_vmx_exit_reflected(vcpu, exit_reason))
8813                 return nested_vmx_reflect_vmexit(vcpu, exit_reason);
8814
8815         if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
8816                 dump_vmcs();
8817                 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
8818                 vcpu->run->fail_entry.hardware_entry_failure_reason
8819                         = exit_reason;
8820                 return 0;
8821         }
8822
8823         if (unlikely(vmx->fail)) {
8824                 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
8825                 vcpu->run->fail_entry.hardware_entry_failure_reason
8826                         = vmcs_read32(VM_INSTRUCTION_ERROR);
8827                 return 0;
8828         }
8829
8830         /*
8831          * Note:
8832          * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
8833          * delivery event since it indicates guest is accessing MMIO.
8834          * The vm-exit can be triggered again after return to guest that
8835          * will cause infinite loop.
8836          */
8837         if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
8838                         (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
8839                         exit_reason != EXIT_REASON_EPT_VIOLATION &&
8840                         exit_reason != EXIT_REASON_PML_FULL &&
8841                         exit_reason != EXIT_REASON_TASK_SWITCH)) {
8842                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
8843                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
8844                 vcpu->run->internal.ndata = 3;
8845                 vcpu->run->internal.data[0] = vectoring_info;
8846                 vcpu->run->internal.data[1] = exit_reason;
8847                 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
8848                 if (exit_reason == EXIT_REASON_EPT_MISCONFIG) {
8849                         vcpu->run->internal.ndata++;
8850                         vcpu->run->internal.data[3] =
8851                                 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
8852                 }
8853                 return 0;
8854         }
8855
8856         if (unlikely(!cpu_has_virtual_nmis() &&
8857                      vmx->loaded_vmcs->soft_vnmi_blocked)) {
8858                 if (vmx_interrupt_allowed(vcpu)) {
8859                         vmx->loaded_vmcs->soft_vnmi_blocked = 0;
8860                 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
8861                            vcpu->arch.nmi_pending) {
8862                         /*
8863                          * This CPU don't support us in finding the end of an
8864                          * NMI-blocked window if the guest runs with IRQs
8865                          * disabled. So we pull the trigger after 1 s of
8866                          * futile waiting, but inform the user about this.
8867                          */
8868                         printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
8869                                "state on VCPU %d after 1 s timeout\n",
8870                                __func__, vcpu->vcpu_id);
8871                         vmx->loaded_vmcs->soft_vnmi_blocked = 0;
8872                 }
8873         }
8874
8875         if (exit_reason < kvm_vmx_max_exit_handlers
8876             && kvm_vmx_exit_handlers[exit_reason])
8877                 return kvm_vmx_exit_handlers[exit_reason](vcpu);
8878         else {
8879                 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
8880                                 exit_reason);
8881                 kvm_queue_exception(vcpu, UD_VECTOR);
8882                 return 1;
8883         }
8884 }
8885
8886 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
8887 {
8888         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
8889
8890         if (is_guest_mode(vcpu) &&
8891                 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
8892                 return;
8893
8894         if (irr == -1 || tpr < irr) {
8895                 vmcs_write32(TPR_THRESHOLD, 0);
8896                 return;
8897         }
8898
8899         vmcs_write32(TPR_THRESHOLD, irr);
8900 }
8901
8902 static void vmx_set_virtual_x2apic_mode(struct kvm_vcpu *vcpu, bool set)
8903 {
8904         u32 sec_exec_control;
8905
8906         /* Postpone execution until vmcs01 is the current VMCS. */
8907         if (is_guest_mode(vcpu)) {
8908                 to_vmx(vcpu)->nested.change_vmcs01_virtual_x2apic_mode = true;
8909                 return;
8910         }
8911
8912         if (!cpu_has_vmx_virtualize_x2apic_mode())
8913                 return;
8914
8915         if (!cpu_need_tpr_shadow(vcpu))
8916                 return;
8917
8918         sec_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
8919
8920         if (set) {
8921                 sec_exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
8922                 sec_exec_control |= SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
8923         } else {
8924                 sec_exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
8925                 sec_exec_control |= SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
8926                 vmx_flush_tlb_ept_only(vcpu);
8927         }
8928         vmcs_write32(SECONDARY_VM_EXEC_CONTROL, sec_exec_control);
8929
8930         vmx_set_msr_bitmap(vcpu);
8931 }
8932
8933 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu, hpa_t hpa)
8934 {
8935         struct vcpu_vmx *vmx = to_vmx(vcpu);
8936
8937         /*
8938          * Currently we do not handle the nested case where L2 has an
8939          * APIC access page of its own; that page is still pinned.
8940          * Hence, we skip the case where the VCPU is in guest mode _and_
8941          * L1 prepared an APIC access page for L2.
8942          *
8943          * For the case where L1 and L2 share the same APIC access page
8944          * (flexpriority=Y but SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES clear
8945          * in the vmcs12), this function will only update either the vmcs01
8946          * or the vmcs02.  If the former, the vmcs02 will be updated by
8947          * prepare_vmcs02.  If the latter, the vmcs01 will be updated in
8948          * the next L2->L1 exit.
8949          */
8950         if (!is_guest_mode(vcpu) ||
8951             !nested_cpu_has2(get_vmcs12(&vmx->vcpu),
8952                              SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
8953                 vmcs_write64(APIC_ACCESS_ADDR, hpa);
8954                 vmx_flush_tlb_ept_only(vcpu);
8955         }
8956 }
8957
8958 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
8959 {
8960         u16 status;
8961         u8 old;
8962
8963         if (max_isr == -1)
8964                 max_isr = 0;
8965
8966         status = vmcs_read16(GUEST_INTR_STATUS);
8967         old = status >> 8;
8968         if (max_isr != old) {
8969                 status &= 0xff;
8970                 status |= max_isr << 8;
8971                 vmcs_write16(GUEST_INTR_STATUS, status);
8972         }
8973 }
8974
8975 static void vmx_set_rvi(int vector)
8976 {
8977         u16 status;
8978         u8 old;
8979
8980         if (vector == -1)
8981                 vector = 0;
8982
8983         status = vmcs_read16(GUEST_INTR_STATUS);
8984         old = (u8)status & 0xff;
8985         if ((u8)vector != old) {
8986                 status &= ~0xff;
8987                 status |= (u8)vector;
8988                 vmcs_write16(GUEST_INTR_STATUS, status);
8989         }
8990 }
8991
8992 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
8993 {
8994         if (!is_guest_mode(vcpu)) {
8995                 vmx_set_rvi(max_irr);
8996                 return;
8997         }
8998
8999         if (max_irr == -1)
9000                 return;
9001
9002         /*
9003          * In guest mode.  If a vmexit is needed, vmx_check_nested_events
9004          * handles it.
9005          */
9006         if (nested_exit_on_intr(vcpu))
9007                 return;
9008
9009         /*
9010          * Else, fall back to pre-APICv interrupt injection since L2
9011          * is run without virtual interrupt delivery.
9012          */
9013         if (!kvm_event_needs_reinjection(vcpu) &&
9014             vmx_interrupt_allowed(vcpu)) {
9015                 kvm_queue_interrupt(vcpu, max_irr, false);
9016                 vmx_inject_irq(vcpu);
9017         }
9018 }
9019
9020 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
9021 {
9022         struct vcpu_vmx *vmx = to_vmx(vcpu);
9023         int max_irr;
9024
9025         WARN_ON(!vcpu->arch.apicv_active);
9026         if (pi_test_on(&vmx->pi_desc)) {
9027                 pi_clear_on(&vmx->pi_desc);
9028                 /*
9029                  * IOMMU can write to PIR.ON, so the barrier matters even on UP.
9030                  * But on x86 this is just a compiler barrier anyway.
9031                  */
9032                 smp_mb__after_atomic();
9033                 max_irr = kvm_apic_update_irr(vcpu, vmx->pi_desc.pir);
9034         } else {
9035                 max_irr = kvm_lapic_find_highest_irr(vcpu);
9036         }
9037         vmx_hwapic_irr_update(vcpu, max_irr);
9038         return max_irr;
9039 }
9040
9041 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
9042 {
9043         if (!kvm_vcpu_apicv_active(vcpu))
9044                 return;
9045
9046         vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
9047         vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
9048         vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
9049         vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
9050 }
9051
9052 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
9053 {
9054         struct vcpu_vmx *vmx = to_vmx(vcpu);
9055
9056         pi_clear_on(&vmx->pi_desc);
9057         memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
9058 }
9059
9060 static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
9061 {
9062         u32 exit_intr_info = 0;
9063         u16 basic_exit_reason = (u16)vmx->exit_reason;
9064
9065         if (!(basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
9066               || basic_exit_reason == EXIT_REASON_EXCEPTION_NMI))
9067                 return;
9068
9069         if (!(vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
9070                 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
9071         vmx->exit_intr_info = exit_intr_info;
9072
9073         /* if exit due to PF check for async PF */
9074         if (is_page_fault(exit_intr_info))
9075                 vmx->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
9076
9077         /* Handle machine checks before interrupts are enabled */
9078         if (basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY ||
9079             is_machine_check(exit_intr_info))
9080                 kvm_machine_check();
9081
9082         /* We need to handle NMIs before interrupts are enabled */
9083         if (is_nmi(exit_intr_info)) {
9084                 kvm_before_handle_nmi(&vmx->vcpu);
9085                 asm("int $2");
9086                 kvm_after_handle_nmi(&vmx->vcpu);
9087         }
9088 }
9089
9090 static void vmx_handle_external_intr(struct kvm_vcpu *vcpu)
9091 {
9092         u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
9093
9094         if ((exit_intr_info & (INTR_INFO_VALID_MASK | INTR_INFO_INTR_TYPE_MASK))
9095                         == (INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR)) {
9096                 unsigned int vector;
9097                 unsigned long entry;
9098                 gate_desc *desc;
9099                 struct vcpu_vmx *vmx = to_vmx(vcpu);
9100 #ifdef CONFIG_X86_64
9101                 unsigned long tmp;
9102 #endif
9103
9104                 vector =  exit_intr_info & INTR_INFO_VECTOR_MASK;
9105                 desc = (gate_desc *)vmx->host_idt_base + vector;
9106                 entry = gate_offset(desc);
9107                 asm volatile(
9108 #ifdef CONFIG_X86_64
9109                         "mov %%" _ASM_SP ", %[sp]\n\t"
9110                         "and $0xfffffffffffffff0, %%" _ASM_SP "\n\t"
9111                         "push $%c[ss]\n\t"
9112                         "push %[sp]\n\t"
9113 #endif
9114                         "pushf\n\t"
9115                         __ASM_SIZE(push) " $%c[cs]\n\t"
9116                         "call *%[entry]\n\t"
9117                         :
9118 #ifdef CONFIG_X86_64
9119                         [sp]"=&r"(tmp),
9120 #endif
9121                         ASM_CALL_CONSTRAINT
9122                         :
9123                         [entry]"r"(entry),
9124                         [ss]"i"(__KERNEL_DS),
9125                         [cs]"i"(__KERNEL_CS)
9126                         );
9127         }
9128 }
9129 STACK_FRAME_NON_STANDARD(vmx_handle_external_intr);
9130
9131 static bool vmx_has_high_real_mode_segbase(void)
9132 {
9133         return enable_unrestricted_guest || emulate_invalid_guest_state;
9134 }
9135
9136 static bool vmx_mpx_supported(void)
9137 {
9138         return (vmcs_config.vmexit_ctrl & VM_EXIT_CLEAR_BNDCFGS) &&
9139                 (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_BNDCFGS);
9140 }
9141
9142 static bool vmx_xsaves_supported(void)
9143 {
9144         return vmcs_config.cpu_based_2nd_exec_ctrl &
9145                 SECONDARY_EXEC_XSAVES;
9146 }
9147
9148 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
9149 {
9150         u32 exit_intr_info;
9151         bool unblock_nmi;
9152         u8 vector;
9153         bool idtv_info_valid;
9154
9155         idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
9156
9157         if (cpu_has_virtual_nmis()) {
9158                 if (vmx->loaded_vmcs->nmi_known_unmasked)
9159                         return;
9160                 /*
9161                  * Can't use vmx->exit_intr_info since we're not sure what
9162                  * the exit reason is.
9163                  */
9164                 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
9165                 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
9166                 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
9167                 /*
9168                  * SDM 3: 27.7.1.2 (September 2008)
9169                  * Re-set bit "block by NMI" before VM entry if vmexit caused by
9170                  * a guest IRET fault.
9171                  * SDM 3: 23.2.2 (September 2008)
9172                  * Bit 12 is undefined in any of the following cases:
9173                  *  If the VM exit sets the valid bit in the IDT-vectoring
9174                  *   information field.
9175                  *  If the VM exit is due to a double fault.
9176                  */
9177                 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
9178                     vector != DF_VECTOR && !idtv_info_valid)
9179                         vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
9180                                       GUEST_INTR_STATE_NMI);
9181                 else
9182                         vmx->loaded_vmcs->nmi_known_unmasked =
9183                                 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
9184                                   & GUEST_INTR_STATE_NMI);
9185         } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
9186                 vmx->loaded_vmcs->vnmi_blocked_time +=
9187                         ktime_to_ns(ktime_sub(ktime_get(),
9188                                               vmx->loaded_vmcs->entry_time));
9189 }
9190
9191 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
9192                                       u32 idt_vectoring_info,
9193                                       int instr_len_field,
9194                                       int error_code_field)
9195 {
9196         u8 vector;
9197         int type;
9198         bool idtv_info_valid;
9199
9200         idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
9201
9202         vcpu->arch.nmi_injected = false;
9203         kvm_clear_exception_queue(vcpu);
9204         kvm_clear_interrupt_queue(vcpu);
9205
9206         if (!idtv_info_valid)
9207                 return;
9208
9209         kvm_make_request(KVM_REQ_EVENT, vcpu);
9210
9211         vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
9212         type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
9213
9214         switch (type) {
9215         case INTR_TYPE_NMI_INTR:
9216                 vcpu->arch.nmi_injected = true;
9217                 /*
9218                  * SDM 3: 27.7.1.2 (September 2008)
9219                  * Clear bit "block by NMI" before VM entry if a NMI
9220                  * delivery faulted.
9221                  */
9222                 vmx_set_nmi_mask(vcpu, false);
9223                 break;
9224         case INTR_TYPE_SOFT_EXCEPTION:
9225                 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
9226                 /* fall through */
9227         case INTR_TYPE_HARD_EXCEPTION:
9228                 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
9229                         u32 err = vmcs_read32(error_code_field);
9230                         kvm_requeue_exception_e(vcpu, vector, err);
9231                 } else
9232                         kvm_requeue_exception(vcpu, vector);
9233                 break;
9234         case INTR_TYPE_SOFT_INTR:
9235                 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
9236                 /* fall through */
9237         case INTR_TYPE_EXT_INTR:
9238                 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
9239                 break;
9240         default:
9241                 break;
9242         }
9243 }
9244
9245 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
9246 {
9247         __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
9248                                   VM_EXIT_INSTRUCTION_LEN,
9249                                   IDT_VECTORING_ERROR_CODE);
9250 }
9251
9252 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
9253 {
9254         __vmx_complete_interrupts(vcpu,
9255                                   vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
9256                                   VM_ENTRY_INSTRUCTION_LEN,
9257                                   VM_ENTRY_EXCEPTION_ERROR_CODE);
9258
9259         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
9260 }
9261
9262 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
9263 {
9264         int i, nr_msrs;
9265         struct perf_guest_switch_msr *msrs;
9266
9267         msrs = perf_guest_get_msrs(&nr_msrs);
9268
9269         if (!msrs)
9270                 return;
9271
9272         for (i = 0; i < nr_msrs; i++)
9273                 if (msrs[i].host == msrs[i].guest)
9274                         clear_atomic_switch_msr(vmx, msrs[i].msr);
9275                 else
9276                         add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
9277                                         msrs[i].host);
9278 }
9279
9280 static void vmx_arm_hv_timer(struct kvm_vcpu *vcpu)
9281 {
9282         struct vcpu_vmx *vmx = to_vmx(vcpu);
9283         u64 tscl;
9284         u32 delta_tsc;
9285
9286         if (vmx->hv_deadline_tsc == -1)
9287                 return;
9288
9289         tscl = rdtsc();
9290         if (vmx->hv_deadline_tsc > tscl)
9291                 /* sure to be 32 bit only because checked on set_hv_timer */
9292                 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
9293                         cpu_preemption_timer_multi);
9294         else
9295                 delta_tsc = 0;
9296
9297         vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc);
9298 }
9299
9300 static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
9301 {
9302         struct vcpu_vmx *vmx = to_vmx(vcpu);
9303         unsigned long debugctlmsr, cr3, cr4;
9304
9305         /* Record the guest's net vcpu time for enforced NMI injections. */
9306         if (unlikely(!cpu_has_virtual_nmis() &&
9307                      vmx->loaded_vmcs->soft_vnmi_blocked))
9308                 vmx->loaded_vmcs->entry_time = ktime_get();
9309
9310         /* Don't enter VMX if guest state is invalid, let the exit handler
9311            start emulation until we arrive back to a valid state */
9312         if (vmx->emulation_required)
9313                 return;
9314
9315         if (vmx->ple_window_dirty) {
9316                 vmx->ple_window_dirty = false;
9317                 vmcs_write32(PLE_WINDOW, vmx->ple_window);
9318         }
9319
9320         if (vmx->nested.sync_shadow_vmcs) {
9321                 copy_vmcs12_to_shadow(vmx);
9322                 vmx->nested.sync_shadow_vmcs = false;
9323         }
9324
9325         if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
9326                 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
9327         if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
9328                 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
9329
9330         cr3 = __get_current_cr3_fast();
9331         if (unlikely(cr3 != vmx->loaded_vmcs->vmcs_host_cr3)) {
9332                 vmcs_writel(HOST_CR3, cr3);
9333                 vmx->loaded_vmcs->vmcs_host_cr3 = cr3;
9334         }
9335
9336         cr4 = cr4_read_shadow();
9337         if (unlikely(cr4 != vmx->loaded_vmcs->vmcs_host_cr4)) {
9338                 vmcs_writel(HOST_CR4, cr4);
9339                 vmx->loaded_vmcs->vmcs_host_cr4 = cr4;
9340         }
9341
9342         /* When single-stepping over STI and MOV SS, we must clear the
9343          * corresponding interruptibility bits in the guest state. Otherwise
9344          * vmentry fails as it then expects bit 14 (BS) in pending debug
9345          * exceptions being set, but that's not correct for the guest debugging
9346          * case. */
9347         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
9348                 vmx_set_interrupt_shadow(vcpu, 0);
9349
9350         if (static_cpu_has(X86_FEATURE_PKU) &&
9351             kvm_read_cr4_bits(vcpu, X86_CR4_PKE) &&
9352             vcpu->arch.pkru != vmx->host_pkru)
9353                 __write_pkru(vcpu->arch.pkru);
9354
9355         atomic_switch_perf_msrs(vmx);
9356         debugctlmsr = get_debugctlmsr();
9357
9358         vmx_arm_hv_timer(vcpu);
9359
9360         vmx->__launched = vmx->loaded_vmcs->launched;
9361         asm(
9362                 /* Store host registers */
9363                 "push %%" _ASM_DX "; push %%" _ASM_BP ";"
9364                 "push %%" _ASM_CX " \n\t" /* placeholder for guest rcx */
9365                 "push %%" _ASM_CX " \n\t"
9366                 "cmp %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
9367                 "je 1f \n\t"
9368                 "mov %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
9369                 __ex(ASM_VMX_VMWRITE_RSP_RDX) "\n\t"
9370                 "1: \n\t"
9371                 /* Reload cr2 if changed */
9372                 "mov %c[cr2](%0), %%" _ASM_AX " \n\t"
9373                 "mov %%cr2, %%" _ASM_DX " \n\t"
9374                 "cmp %%" _ASM_AX ", %%" _ASM_DX " \n\t"
9375                 "je 2f \n\t"
9376                 "mov %%" _ASM_AX", %%cr2 \n\t"
9377                 "2: \n\t"
9378                 /* Check if vmlaunch of vmresume is needed */
9379                 "cmpl $0, %c[launched](%0) \n\t"
9380                 /* Load guest registers.  Don't clobber flags. */
9381                 "mov %c[rax](%0), %%" _ASM_AX " \n\t"
9382                 "mov %c[rbx](%0), %%" _ASM_BX " \n\t"
9383                 "mov %c[rdx](%0), %%" _ASM_DX " \n\t"
9384                 "mov %c[rsi](%0), %%" _ASM_SI " \n\t"
9385                 "mov %c[rdi](%0), %%" _ASM_DI " \n\t"
9386                 "mov %c[rbp](%0), %%" _ASM_BP " \n\t"
9387 #ifdef CONFIG_X86_64
9388                 "mov %c[r8](%0),  %%r8  \n\t"
9389                 "mov %c[r9](%0),  %%r9  \n\t"
9390                 "mov %c[r10](%0), %%r10 \n\t"
9391                 "mov %c[r11](%0), %%r11 \n\t"
9392                 "mov %c[r12](%0), %%r12 \n\t"
9393                 "mov %c[r13](%0), %%r13 \n\t"
9394                 "mov %c[r14](%0), %%r14 \n\t"
9395                 "mov %c[r15](%0), %%r15 \n\t"
9396 #endif
9397                 "mov %c[rcx](%0), %%" _ASM_CX " \n\t" /* kills %0 (ecx) */
9398
9399                 /* Enter guest mode */
9400                 "jne 1f \n\t"
9401                 __ex(ASM_VMX_VMLAUNCH) "\n\t"
9402                 "jmp 2f \n\t"
9403                 "1: " __ex(ASM_VMX_VMRESUME) "\n\t"
9404                 "2: "
9405                 /* Save guest registers, load host registers, keep flags */
9406                 "mov %0, %c[wordsize](%%" _ASM_SP ") \n\t"
9407                 "pop %0 \n\t"
9408                 "mov %%" _ASM_AX ", %c[rax](%0) \n\t"
9409                 "mov %%" _ASM_BX ", %c[rbx](%0) \n\t"
9410                 __ASM_SIZE(pop) " %c[rcx](%0) \n\t"
9411                 "mov %%" _ASM_DX ", %c[rdx](%0) \n\t"
9412                 "mov %%" _ASM_SI ", %c[rsi](%0) \n\t"
9413                 "mov %%" _ASM_DI ", %c[rdi](%0) \n\t"
9414                 "mov %%" _ASM_BP ", %c[rbp](%0) \n\t"
9415 #ifdef CONFIG_X86_64
9416                 "mov %%r8,  %c[r8](%0) \n\t"
9417                 "mov %%r9,  %c[r9](%0) \n\t"
9418                 "mov %%r10, %c[r10](%0) \n\t"
9419                 "mov %%r11, %c[r11](%0) \n\t"
9420                 "mov %%r12, %c[r12](%0) \n\t"
9421                 "mov %%r13, %c[r13](%0) \n\t"
9422                 "mov %%r14, %c[r14](%0) \n\t"
9423                 "mov %%r15, %c[r15](%0) \n\t"
9424 #endif
9425                 "mov %%cr2, %%" _ASM_AX "   \n\t"
9426                 "mov %%" _ASM_AX ", %c[cr2](%0) \n\t"
9427
9428                 "pop  %%" _ASM_BP "; pop  %%" _ASM_DX " \n\t"
9429                 "setbe %c[fail](%0) \n\t"
9430                 ".pushsection .rodata \n\t"
9431                 ".global vmx_return \n\t"
9432                 "vmx_return: " _ASM_PTR " 2b \n\t"
9433                 ".popsection"
9434               : : "c"(vmx), "d"((unsigned long)HOST_RSP),
9435                 [launched]"i"(offsetof(struct vcpu_vmx, __launched)),
9436                 [fail]"i"(offsetof(struct vcpu_vmx, fail)),
9437                 [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)),
9438                 [rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])),
9439                 [rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])),
9440                 [rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])),
9441                 [rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])),
9442                 [rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])),
9443                 [rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])),
9444                 [rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])),
9445 #ifdef CONFIG_X86_64
9446                 [r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])),
9447                 [r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])),
9448                 [r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])),
9449                 [r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])),
9450                 [r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])),
9451                 [r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])),
9452                 [r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])),
9453                 [r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])),
9454 #endif
9455                 [cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2)),
9456                 [wordsize]"i"(sizeof(ulong))
9457               : "cc", "memory"
9458 #ifdef CONFIG_X86_64
9459                 , "rax", "rbx", "rdi", "rsi"
9460                 , "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
9461 #else
9462                 , "eax", "ebx", "edi", "esi"
9463 #endif
9464               );
9465
9466         /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
9467         if (debugctlmsr)
9468                 update_debugctlmsr(debugctlmsr);
9469
9470 #ifndef CONFIG_X86_64
9471         /*
9472          * The sysexit path does not restore ds/es, so we must set them to
9473          * a reasonable value ourselves.
9474          *
9475          * We can't defer this to vmx_load_host_state() since that function
9476          * may be executed in interrupt context, which saves and restore segments
9477          * around it, nullifying its effect.
9478          */
9479         loadsegment(ds, __USER_DS);
9480         loadsegment(es, __USER_DS);
9481 #endif
9482
9483         vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
9484                                   | (1 << VCPU_EXREG_RFLAGS)
9485                                   | (1 << VCPU_EXREG_PDPTR)
9486                                   | (1 << VCPU_EXREG_SEGMENTS)
9487                                   | (1 << VCPU_EXREG_CR3));
9488         vcpu->arch.regs_dirty = 0;
9489
9490         /*
9491          * eager fpu is enabled if PKEY is supported and CR4 is switched
9492          * back on host, so it is safe to read guest PKRU from current
9493          * XSAVE.
9494          */
9495         if (static_cpu_has(X86_FEATURE_PKU) &&
9496             kvm_read_cr4_bits(vcpu, X86_CR4_PKE)) {
9497                 vcpu->arch.pkru = __read_pkru();
9498                 if (vcpu->arch.pkru != vmx->host_pkru)
9499                         __write_pkru(vmx->host_pkru);
9500         }
9501
9502         /*
9503          * the KVM_REQ_EVENT optimization bit is only on for one entry, and if
9504          * we did not inject a still-pending event to L1 now because of
9505          * nested_run_pending, we need to re-enable this bit.
9506          */
9507         if (vmx->nested.nested_run_pending)
9508                 kvm_make_request(KVM_REQ_EVENT, vcpu);
9509
9510         vmx->nested.nested_run_pending = 0;
9511         vmx->idt_vectoring_info = 0;
9512
9513         vmx->exit_reason = vmx->fail ? 0xdead : vmcs_read32(VM_EXIT_REASON);
9514         if (vmx->fail || (vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
9515                 return;
9516
9517         vmx->loaded_vmcs->launched = 1;
9518         vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
9519
9520         vmx_complete_atomic_exit(vmx);
9521         vmx_recover_nmi_blocking(vmx);
9522         vmx_complete_interrupts(vmx);
9523 }
9524 STACK_FRAME_NON_STANDARD(vmx_vcpu_run);
9525
9526 static void vmx_switch_vmcs(struct kvm_vcpu *vcpu, struct loaded_vmcs *vmcs)
9527 {
9528         struct vcpu_vmx *vmx = to_vmx(vcpu);
9529         int cpu;
9530
9531         if (vmx->loaded_vmcs == vmcs)
9532                 return;
9533
9534         cpu = get_cpu();
9535         vmx->loaded_vmcs = vmcs;
9536         vmx_vcpu_put(vcpu);
9537         vmx_vcpu_load(vcpu, cpu);
9538         vcpu->cpu = cpu;
9539         put_cpu();
9540 }
9541
9542 /*
9543  * Ensure that the current vmcs of the logical processor is the
9544  * vmcs01 of the vcpu before calling free_nested().
9545  */
9546 static void vmx_free_vcpu_nested(struct kvm_vcpu *vcpu)
9547 {
9548        struct vcpu_vmx *vmx = to_vmx(vcpu);
9549        int r;
9550
9551        r = vcpu_load(vcpu);
9552        BUG_ON(r);
9553        vmx_switch_vmcs(vcpu, &vmx->vmcs01);
9554        free_nested(vmx);
9555        vcpu_put(vcpu);
9556 }
9557
9558 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
9559 {
9560         struct vcpu_vmx *vmx = to_vmx(vcpu);
9561
9562         if (enable_pml)
9563                 vmx_destroy_pml_buffer(vmx);
9564         free_vpid(vmx->vpid);
9565         leave_guest_mode(vcpu);
9566         vmx_free_vcpu_nested(vcpu);
9567         free_loaded_vmcs(vmx->loaded_vmcs);
9568         kfree(vmx->guest_msrs);
9569         kvm_vcpu_uninit(vcpu);
9570         kmem_cache_free(kvm_vcpu_cache, vmx);
9571 }
9572
9573 static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
9574 {
9575         int err;
9576         struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
9577         int cpu;
9578
9579         if (!vmx)
9580                 return ERR_PTR(-ENOMEM);
9581
9582         vmx->vpid = allocate_vpid();
9583
9584         err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
9585         if (err)
9586                 goto free_vcpu;
9587
9588         err = -ENOMEM;
9589
9590         /*
9591          * If PML is turned on, failure on enabling PML just results in failure
9592          * of creating the vcpu, therefore we can simplify PML logic (by
9593          * avoiding dealing with cases, such as enabling PML partially on vcpus
9594          * for the guest, etc.
9595          */
9596         if (enable_pml) {
9597                 vmx->pml_pg = alloc_page(GFP_KERNEL | __GFP_ZERO);
9598                 if (!vmx->pml_pg)
9599                         goto uninit_vcpu;
9600         }
9601
9602         vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
9603         BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) * sizeof(vmx->guest_msrs[0])
9604                      > PAGE_SIZE);
9605
9606         if (!vmx->guest_msrs)
9607                 goto free_pml;
9608
9609         vmx->loaded_vmcs = &vmx->vmcs01;
9610         vmx->loaded_vmcs->vmcs = alloc_vmcs();
9611         vmx->loaded_vmcs->shadow_vmcs = NULL;
9612         if (!vmx->loaded_vmcs->vmcs)
9613                 goto free_msrs;
9614         loaded_vmcs_init(vmx->loaded_vmcs);
9615
9616         cpu = get_cpu();
9617         vmx_vcpu_load(&vmx->vcpu, cpu);
9618         vmx->vcpu.cpu = cpu;
9619         err = vmx_vcpu_setup(vmx);
9620         vmx_vcpu_put(&vmx->vcpu);
9621         put_cpu();
9622         if (err)
9623                 goto free_vmcs;
9624         if (cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
9625                 err = alloc_apic_access_page(kvm);
9626                 if (err)
9627                         goto free_vmcs;
9628         }
9629
9630         if (enable_ept) {
9631                 if (!kvm->arch.ept_identity_map_addr)
9632                         kvm->arch.ept_identity_map_addr =
9633                                 VMX_EPT_IDENTITY_PAGETABLE_ADDR;
9634                 err = init_rmode_identity_map(kvm);
9635                 if (err)
9636                         goto free_vmcs;
9637         }
9638
9639         if (nested) {
9640                 nested_vmx_setup_ctls_msrs(vmx);
9641                 vmx->nested.vpid02 = allocate_vpid();
9642         }
9643
9644         vmx->nested.posted_intr_nv = -1;
9645         vmx->nested.current_vmptr = -1ull;
9646
9647         vmx->msr_ia32_feature_control_valid_bits = FEATURE_CONTROL_LOCKED;
9648
9649         /*
9650          * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
9651          * or POSTED_INTR_WAKEUP_VECTOR.
9652          */
9653         vmx->pi_desc.nv = POSTED_INTR_VECTOR;
9654         vmx->pi_desc.sn = 1;
9655
9656         return &vmx->vcpu;
9657
9658 free_vmcs:
9659         free_vpid(vmx->nested.vpid02);
9660         free_loaded_vmcs(vmx->loaded_vmcs);
9661 free_msrs:
9662         kfree(vmx->guest_msrs);
9663 free_pml:
9664         vmx_destroy_pml_buffer(vmx);
9665 uninit_vcpu:
9666         kvm_vcpu_uninit(&vmx->vcpu);
9667 free_vcpu:
9668         free_vpid(vmx->vpid);
9669         kmem_cache_free(kvm_vcpu_cache, vmx);
9670         return ERR_PTR(err);
9671 }
9672
9673 static void __init vmx_check_processor_compat(void *rtn)
9674 {
9675         struct vmcs_config vmcs_conf;
9676
9677         *(int *)rtn = 0;
9678         if (setup_vmcs_config(&vmcs_conf) < 0)
9679                 *(int *)rtn = -EIO;
9680         if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
9681                 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
9682                                 smp_processor_id());
9683                 *(int *)rtn = -EIO;
9684         }
9685 }
9686
9687 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
9688 {
9689         u8 cache;
9690         u64 ipat = 0;
9691
9692         /* For VT-d and EPT combination
9693          * 1. MMIO: always map as UC
9694          * 2. EPT with VT-d:
9695          *   a. VT-d without snooping control feature: can't guarantee the
9696          *      result, try to trust guest.
9697          *   b. VT-d with snooping control feature: snooping control feature of
9698          *      VT-d engine can guarantee the cache correctness. Just set it
9699          *      to WB to keep consistent with host. So the same as item 3.
9700          * 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
9701          *    consistent with host MTRR
9702          */
9703         if (is_mmio) {
9704                 cache = MTRR_TYPE_UNCACHABLE;
9705                 goto exit;
9706         }
9707
9708         if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
9709                 ipat = VMX_EPT_IPAT_BIT;
9710                 cache = MTRR_TYPE_WRBACK;
9711                 goto exit;
9712         }
9713
9714         if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
9715                 ipat = VMX_EPT_IPAT_BIT;
9716                 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
9717                         cache = MTRR_TYPE_WRBACK;
9718                 else
9719                         cache = MTRR_TYPE_UNCACHABLE;
9720                 goto exit;
9721         }
9722
9723         cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
9724
9725 exit:
9726         return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
9727 }
9728
9729 static int vmx_get_lpage_level(void)
9730 {
9731         if (enable_ept && !cpu_has_vmx_ept_1g_page())
9732                 return PT_DIRECTORY_LEVEL;
9733         else
9734                 /* For shadow and EPT supported 1GB page */
9735                 return PT_PDPE_LEVEL;
9736 }
9737
9738 static void vmcs_set_secondary_exec_control(u32 new_ctl)
9739 {
9740         /*
9741          * These bits in the secondary execution controls field
9742          * are dynamic, the others are mostly based on the hypervisor
9743          * architecture and the guest's CPUID.  Do not touch the
9744          * dynamic bits.
9745          */
9746         u32 mask =
9747                 SECONDARY_EXEC_SHADOW_VMCS |
9748                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
9749                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
9750
9751         u32 cur_ctl = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
9752
9753         vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
9754                      (new_ctl & ~mask) | (cur_ctl & mask));
9755 }
9756
9757 /*
9758  * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
9759  * (indicating "allowed-1") if they are supported in the guest's CPUID.
9760  */
9761 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
9762 {
9763         struct vcpu_vmx *vmx = to_vmx(vcpu);
9764         struct kvm_cpuid_entry2 *entry;
9765
9766         vmx->nested.nested_vmx_cr0_fixed1 = 0xffffffff;
9767         vmx->nested.nested_vmx_cr4_fixed1 = X86_CR4_PCE;
9768
9769 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do {            \
9770         if (entry && (entry->_reg & (_cpuid_mask)))                     \
9771                 vmx->nested.nested_vmx_cr4_fixed1 |= (_cr4_mask);       \
9772 } while (0)
9773
9774         entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
9775         cr4_fixed1_update(X86_CR4_VME,        edx, bit(X86_FEATURE_VME));
9776         cr4_fixed1_update(X86_CR4_PVI,        edx, bit(X86_FEATURE_VME));
9777         cr4_fixed1_update(X86_CR4_TSD,        edx, bit(X86_FEATURE_TSC));
9778         cr4_fixed1_update(X86_CR4_DE,         edx, bit(X86_FEATURE_DE));
9779         cr4_fixed1_update(X86_CR4_PSE,        edx, bit(X86_FEATURE_PSE));
9780         cr4_fixed1_update(X86_CR4_PAE,        edx, bit(X86_FEATURE_PAE));
9781         cr4_fixed1_update(X86_CR4_MCE,        edx, bit(X86_FEATURE_MCE));
9782         cr4_fixed1_update(X86_CR4_PGE,        edx, bit(X86_FEATURE_PGE));
9783         cr4_fixed1_update(X86_CR4_OSFXSR,     edx, bit(X86_FEATURE_FXSR));
9784         cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, bit(X86_FEATURE_XMM));
9785         cr4_fixed1_update(X86_CR4_VMXE,       ecx, bit(X86_FEATURE_VMX));
9786         cr4_fixed1_update(X86_CR4_SMXE,       ecx, bit(X86_FEATURE_SMX));
9787         cr4_fixed1_update(X86_CR4_PCIDE,      ecx, bit(X86_FEATURE_PCID));
9788         cr4_fixed1_update(X86_CR4_OSXSAVE,    ecx, bit(X86_FEATURE_XSAVE));
9789
9790         entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
9791         cr4_fixed1_update(X86_CR4_FSGSBASE,   ebx, bit(X86_FEATURE_FSGSBASE));
9792         cr4_fixed1_update(X86_CR4_SMEP,       ebx, bit(X86_FEATURE_SMEP));
9793         cr4_fixed1_update(X86_CR4_SMAP,       ebx, bit(X86_FEATURE_SMAP));
9794         cr4_fixed1_update(X86_CR4_PKE,        ecx, bit(X86_FEATURE_PKU));
9795         /* TODO: Use X86_CR4_UMIP and X86_FEATURE_UMIP macros */
9796         cr4_fixed1_update(bit(11),            ecx, bit(2));
9797
9798 #undef cr4_fixed1_update
9799 }
9800
9801 static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
9802 {
9803         struct vcpu_vmx *vmx = to_vmx(vcpu);
9804
9805         if (cpu_has_secondary_exec_ctrls()) {
9806                 vmx_compute_secondary_exec_control(vmx);
9807                 vmcs_set_secondary_exec_control(vmx->secondary_exec_control);
9808         }
9809
9810         if (nested_vmx_allowed(vcpu))
9811                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
9812                         FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
9813         else
9814                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
9815                         ~FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
9816
9817         if (nested_vmx_allowed(vcpu))
9818                 nested_vmx_cr_fixed1_bits_update(vcpu);
9819 }
9820
9821 static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
9822 {
9823         if (func == 1 && nested)
9824                 entry->ecx |= bit(X86_FEATURE_VMX);
9825 }
9826
9827 static void nested_ept_inject_page_fault(struct kvm_vcpu *vcpu,
9828                 struct x86_exception *fault)
9829 {
9830         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
9831         struct vcpu_vmx *vmx = to_vmx(vcpu);
9832         u32 exit_reason;
9833         unsigned long exit_qualification = vcpu->arch.exit_qualification;
9834
9835         if (vmx->nested.pml_full) {
9836                 exit_reason = EXIT_REASON_PML_FULL;
9837                 vmx->nested.pml_full = false;
9838                 exit_qualification &= INTR_INFO_UNBLOCK_NMI;
9839         } else if (fault->error_code & PFERR_RSVD_MASK)
9840                 exit_reason = EXIT_REASON_EPT_MISCONFIG;
9841         else
9842                 exit_reason = EXIT_REASON_EPT_VIOLATION;
9843
9844         nested_vmx_vmexit(vcpu, exit_reason, 0, exit_qualification);
9845         vmcs12->guest_physical_address = fault->address;
9846 }
9847
9848 static bool nested_ept_ad_enabled(struct kvm_vcpu *vcpu)
9849 {
9850         return nested_ept_get_cr3(vcpu) & VMX_EPTP_AD_ENABLE_BIT;
9851 }
9852
9853 /* Callbacks for nested_ept_init_mmu_context: */
9854
9855 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu)
9856 {
9857         /* return the page table to be shadowed - in our case, EPT12 */
9858         return get_vmcs12(vcpu)->ept_pointer;
9859 }
9860
9861 static int nested_ept_init_mmu_context(struct kvm_vcpu *vcpu)
9862 {
9863         WARN_ON(mmu_is_nested(vcpu));
9864         if (!valid_ept_address(vcpu, nested_ept_get_cr3(vcpu)))
9865                 return 1;
9866
9867         kvm_mmu_unload(vcpu);
9868         kvm_init_shadow_ept_mmu(vcpu,
9869                         to_vmx(vcpu)->nested.nested_vmx_ept_caps &
9870                         VMX_EPT_EXECUTE_ONLY_BIT,
9871                         nested_ept_ad_enabled(vcpu));
9872         vcpu->arch.mmu.set_cr3           = vmx_set_cr3;
9873         vcpu->arch.mmu.get_cr3           = nested_ept_get_cr3;
9874         vcpu->arch.mmu.inject_page_fault = nested_ept_inject_page_fault;
9875
9876         vcpu->arch.walk_mmu              = &vcpu->arch.nested_mmu;
9877         return 0;
9878 }
9879
9880 static void nested_ept_uninit_mmu_context(struct kvm_vcpu *vcpu)
9881 {
9882         vcpu->arch.walk_mmu = &vcpu->arch.mmu;
9883 }
9884
9885 static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
9886                                             u16 error_code)
9887 {
9888         bool inequality, bit;
9889
9890         bit = (vmcs12->exception_bitmap & (1u << PF_VECTOR)) != 0;
9891         inequality =
9892                 (error_code & vmcs12->page_fault_error_code_mask) !=
9893                  vmcs12->page_fault_error_code_match;
9894         return inequality ^ bit;
9895 }
9896
9897 static void vmx_inject_page_fault_nested(struct kvm_vcpu *vcpu,
9898                 struct x86_exception *fault)
9899 {
9900         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
9901
9902         WARN_ON(!is_guest_mode(vcpu));
9903
9904         if (nested_vmx_is_page_fault_vmexit(vmcs12, fault->error_code) &&
9905                 !to_vmx(vcpu)->nested.nested_run_pending) {
9906                 vmcs12->vm_exit_intr_error_code = fault->error_code;
9907                 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
9908                                   PF_VECTOR | INTR_TYPE_HARD_EXCEPTION |
9909                                   INTR_INFO_DELIVER_CODE_MASK | INTR_INFO_VALID_MASK,
9910                                   fault->address);
9911         } else {
9912                 kvm_inject_page_fault(vcpu, fault);
9913         }
9914 }
9915
9916 static inline bool nested_vmx_merge_msr_bitmap(struct kvm_vcpu *vcpu,
9917                                                struct vmcs12 *vmcs12);
9918
9919 static void nested_get_vmcs12_pages(struct kvm_vcpu *vcpu,
9920                                         struct vmcs12 *vmcs12)
9921 {
9922         struct vcpu_vmx *vmx = to_vmx(vcpu);
9923         struct page *page;
9924         u64 hpa;
9925
9926         if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
9927                 /*
9928                  * Translate L1 physical address to host physical
9929                  * address for vmcs02. Keep the page pinned, so this
9930                  * physical address remains valid. We keep a reference
9931                  * to it so we can release it later.
9932                  */
9933                 if (vmx->nested.apic_access_page) { /* shouldn't happen */
9934                         kvm_release_page_dirty(vmx->nested.apic_access_page);
9935                         vmx->nested.apic_access_page = NULL;
9936                 }
9937                 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->apic_access_addr);
9938                 /*
9939                  * If translation failed, no matter: This feature asks
9940                  * to exit when accessing the given address, and if it
9941                  * can never be accessed, this feature won't do
9942                  * anything anyway.
9943                  */
9944                 if (!is_error_page(page)) {
9945                         vmx->nested.apic_access_page = page;
9946                         hpa = page_to_phys(vmx->nested.apic_access_page);
9947                         vmcs_write64(APIC_ACCESS_ADDR, hpa);
9948                 } else {
9949                         vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
9950                                         SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
9951                 }
9952         } else if (!(nested_cpu_has_virt_x2apic_mode(vmcs12)) &&
9953                    cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
9954                 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
9955                               SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
9956                 kvm_vcpu_reload_apic_access_page(vcpu);
9957         }
9958
9959         if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
9960                 if (vmx->nested.virtual_apic_page) { /* shouldn't happen */
9961                         kvm_release_page_dirty(vmx->nested.virtual_apic_page);
9962                         vmx->nested.virtual_apic_page = NULL;
9963                 }
9964                 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->virtual_apic_page_addr);
9965
9966                 /*
9967                  * If translation failed, VM entry will fail because
9968                  * prepare_vmcs02 set VIRTUAL_APIC_PAGE_ADDR to -1ull.
9969                  * Failing the vm entry is _not_ what the processor
9970                  * does but it's basically the only possibility we
9971                  * have.  We could still enter the guest if CR8 load
9972                  * exits are enabled, CR8 store exits are enabled, and
9973                  * virtualize APIC access is disabled; in this case
9974                  * the processor would never use the TPR shadow and we
9975                  * could simply clear the bit from the execution
9976                  * control.  But such a configuration is useless, so
9977                  * let's keep the code simple.
9978                  */
9979                 if (!is_error_page(page)) {
9980                         vmx->nested.virtual_apic_page = page;
9981                         hpa = page_to_phys(vmx->nested.virtual_apic_page);
9982                         vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, hpa);
9983                 }
9984         }
9985
9986         if (nested_cpu_has_posted_intr(vmcs12)) {
9987                 if (vmx->nested.pi_desc_page) { /* shouldn't happen */
9988                         kunmap(vmx->nested.pi_desc_page);
9989                         kvm_release_page_dirty(vmx->nested.pi_desc_page);
9990                         vmx->nested.pi_desc_page = NULL;
9991                 }
9992                 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->posted_intr_desc_addr);
9993                 if (is_error_page(page))
9994                         return;
9995                 vmx->nested.pi_desc_page = page;
9996                 vmx->nested.pi_desc = kmap(vmx->nested.pi_desc_page);
9997                 vmx->nested.pi_desc =
9998                         (struct pi_desc *)((void *)vmx->nested.pi_desc +
9999                         (unsigned long)(vmcs12->posted_intr_desc_addr &
10000                         (PAGE_SIZE - 1)));
10001                 vmcs_write64(POSTED_INTR_DESC_ADDR,
10002                         page_to_phys(vmx->nested.pi_desc_page) +
10003                         (unsigned long)(vmcs12->posted_intr_desc_addr &
10004                         (PAGE_SIZE - 1)));
10005         }
10006         if (cpu_has_vmx_msr_bitmap() &&
10007             nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS) &&
10008             nested_vmx_merge_msr_bitmap(vcpu, vmcs12))
10009                 ;
10010         else
10011                 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
10012                                 CPU_BASED_USE_MSR_BITMAPS);
10013 }
10014
10015 static void vmx_start_preemption_timer(struct kvm_vcpu *vcpu)
10016 {
10017         u64 preemption_timeout = get_vmcs12(vcpu)->vmx_preemption_timer_value;
10018         struct vcpu_vmx *vmx = to_vmx(vcpu);
10019
10020         if (vcpu->arch.virtual_tsc_khz == 0)
10021                 return;
10022
10023         /* Make sure short timeouts reliably trigger an immediate vmexit.
10024          * hrtimer_start does not guarantee this. */
10025         if (preemption_timeout <= 1) {
10026                 vmx_preemption_timer_fn(&vmx->nested.preemption_timer);
10027                 return;
10028         }
10029
10030         preemption_timeout <<= VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
10031         preemption_timeout *= 1000000;
10032         do_div(preemption_timeout, vcpu->arch.virtual_tsc_khz);
10033         hrtimer_start(&vmx->nested.preemption_timer,
10034                       ns_to_ktime(preemption_timeout), HRTIMER_MODE_REL);
10035 }
10036
10037 static int nested_vmx_check_io_bitmap_controls(struct kvm_vcpu *vcpu,
10038                                                struct vmcs12 *vmcs12)
10039 {
10040         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
10041                 return 0;
10042
10043         if (!page_address_valid(vcpu, vmcs12->io_bitmap_a) ||
10044             !page_address_valid(vcpu, vmcs12->io_bitmap_b))
10045                 return -EINVAL;
10046
10047         return 0;
10048 }
10049
10050 static int nested_vmx_check_msr_bitmap_controls(struct kvm_vcpu *vcpu,
10051                                                 struct vmcs12 *vmcs12)
10052 {
10053         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
10054                 return 0;
10055
10056         if (!page_address_valid(vcpu, vmcs12->msr_bitmap))
10057                 return -EINVAL;
10058
10059         return 0;
10060 }
10061
10062 static int nested_vmx_check_tpr_shadow_controls(struct kvm_vcpu *vcpu,
10063                                                 struct vmcs12 *vmcs12)
10064 {
10065         if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
10066                 return 0;
10067
10068         if (!page_address_valid(vcpu, vmcs12->virtual_apic_page_addr))
10069                 return -EINVAL;
10070
10071         return 0;
10072 }
10073
10074 /*
10075  * Merge L0's and L1's MSR bitmap, return false to indicate that
10076  * we do not use the hardware.
10077  */
10078 static inline bool nested_vmx_merge_msr_bitmap(struct kvm_vcpu *vcpu,
10079                                                struct vmcs12 *vmcs12)
10080 {
10081         int msr;
10082         struct page *page;
10083         unsigned long *msr_bitmap_l1;
10084         unsigned long *msr_bitmap_l0 = to_vmx(vcpu)->nested.msr_bitmap;
10085
10086         /* This shortcut is ok because we support only x2APIC MSRs so far. */
10087         if (!nested_cpu_has_virt_x2apic_mode(vmcs12))
10088                 return false;
10089
10090         page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->msr_bitmap);
10091         if (is_error_page(page))
10092                 return false;
10093         msr_bitmap_l1 = (unsigned long *)kmap(page);
10094
10095         memset(msr_bitmap_l0, 0xff, PAGE_SIZE);
10096
10097         if (nested_cpu_has_virt_x2apic_mode(vmcs12)) {
10098                 if (nested_cpu_has_apic_reg_virt(vmcs12))
10099                         for (msr = 0x800; msr <= 0x8ff; msr++)
10100                                 nested_vmx_disable_intercept_for_msr(
10101                                         msr_bitmap_l1, msr_bitmap_l0,
10102                                         msr, MSR_TYPE_R);
10103
10104                 nested_vmx_disable_intercept_for_msr(
10105                                 msr_bitmap_l1, msr_bitmap_l0,
10106                                 APIC_BASE_MSR + (APIC_TASKPRI >> 4),
10107                                 MSR_TYPE_R | MSR_TYPE_W);
10108
10109                 if (nested_cpu_has_vid(vmcs12)) {
10110                         nested_vmx_disable_intercept_for_msr(
10111                                 msr_bitmap_l1, msr_bitmap_l0,
10112                                 APIC_BASE_MSR + (APIC_EOI >> 4),
10113                                 MSR_TYPE_W);
10114                         nested_vmx_disable_intercept_for_msr(
10115                                 msr_bitmap_l1, msr_bitmap_l0,
10116                                 APIC_BASE_MSR + (APIC_SELF_IPI >> 4),
10117                                 MSR_TYPE_W);
10118                 }
10119         }
10120         kunmap(page);
10121         kvm_release_page_clean(page);
10122
10123         return true;
10124 }
10125
10126 static int nested_vmx_check_apicv_controls(struct kvm_vcpu *vcpu,
10127                                            struct vmcs12 *vmcs12)
10128 {
10129         if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
10130             !nested_cpu_has_apic_reg_virt(vmcs12) &&
10131             !nested_cpu_has_vid(vmcs12) &&
10132             !nested_cpu_has_posted_intr(vmcs12))
10133                 return 0;
10134
10135         /*
10136          * If virtualize x2apic mode is enabled,
10137          * virtualize apic access must be disabled.
10138          */
10139         if (nested_cpu_has_virt_x2apic_mode(vmcs12) &&
10140             nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
10141                 return -EINVAL;
10142
10143         /*
10144          * If virtual interrupt delivery is enabled,
10145          * we must exit on external interrupts.
10146          */
10147         if (nested_cpu_has_vid(vmcs12) &&
10148            !nested_exit_on_intr(vcpu))
10149                 return -EINVAL;
10150
10151         /*
10152          * bits 15:8 should be zero in posted_intr_nv,
10153          * the descriptor address has been already checked
10154          * in nested_get_vmcs12_pages.
10155          */
10156         if (nested_cpu_has_posted_intr(vmcs12) &&
10157            (!nested_cpu_has_vid(vmcs12) ||
10158             !nested_exit_intr_ack_set(vcpu) ||
10159             vmcs12->posted_intr_nv & 0xff00))
10160                 return -EINVAL;
10161
10162         /* tpr shadow is needed by all apicv features. */
10163         if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
10164                 return -EINVAL;
10165
10166         return 0;
10167 }
10168
10169 static int nested_vmx_check_msr_switch(struct kvm_vcpu *vcpu,
10170                                        unsigned long count_field,
10171                                        unsigned long addr_field)
10172 {
10173         int maxphyaddr;
10174         u64 count, addr;
10175
10176         if (vmcs12_read_any(vcpu, count_field, &count) ||
10177             vmcs12_read_any(vcpu, addr_field, &addr)) {
10178                 WARN_ON(1);
10179                 return -EINVAL;
10180         }
10181         if (count == 0)
10182                 return 0;
10183         maxphyaddr = cpuid_maxphyaddr(vcpu);
10184         if (!IS_ALIGNED(addr, 16) || addr >> maxphyaddr ||
10185             (addr + count * sizeof(struct vmx_msr_entry) - 1) >> maxphyaddr) {
10186                 pr_debug_ratelimited(
10187                         "nVMX: invalid MSR switch (0x%lx, %d, %llu, 0x%08llx)",
10188                         addr_field, maxphyaddr, count, addr);
10189                 return -EINVAL;
10190         }
10191         return 0;
10192 }
10193
10194 static int nested_vmx_check_msr_switch_controls(struct kvm_vcpu *vcpu,
10195                                                 struct vmcs12 *vmcs12)
10196 {
10197         if (vmcs12->vm_exit_msr_load_count == 0 &&
10198             vmcs12->vm_exit_msr_store_count == 0 &&
10199             vmcs12->vm_entry_msr_load_count == 0)
10200                 return 0; /* Fast path */
10201         if (nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_LOAD_COUNT,
10202                                         VM_EXIT_MSR_LOAD_ADDR) ||
10203             nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_STORE_COUNT,
10204                                         VM_EXIT_MSR_STORE_ADDR) ||
10205             nested_vmx_check_msr_switch(vcpu, VM_ENTRY_MSR_LOAD_COUNT,
10206                                         VM_ENTRY_MSR_LOAD_ADDR))
10207                 return -EINVAL;
10208         return 0;
10209 }
10210
10211 static int nested_vmx_check_pml_controls(struct kvm_vcpu *vcpu,
10212                                          struct vmcs12 *vmcs12)
10213 {
10214         u64 address = vmcs12->pml_address;
10215         int maxphyaddr = cpuid_maxphyaddr(vcpu);
10216
10217         if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_PML)) {
10218                 if (!nested_cpu_has_ept(vmcs12) ||
10219                     !IS_ALIGNED(address, 4096)  ||
10220                     address >> maxphyaddr)
10221                         return -EINVAL;
10222         }
10223
10224         return 0;
10225 }
10226
10227 static int nested_vmx_msr_check_common(struct kvm_vcpu *vcpu,
10228                                        struct vmx_msr_entry *e)
10229 {
10230         /* x2APIC MSR accesses are not allowed */
10231         if (vcpu->arch.apic_base & X2APIC_ENABLE && e->index >> 8 == 0x8)
10232                 return -EINVAL;
10233         if (e->index == MSR_IA32_UCODE_WRITE || /* SDM Table 35-2 */
10234             e->index == MSR_IA32_UCODE_REV)
10235                 return -EINVAL;
10236         if (e->reserved != 0)
10237                 return -EINVAL;
10238         return 0;
10239 }
10240
10241 static int nested_vmx_load_msr_check(struct kvm_vcpu *vcpu,
10242                                      struct vmx_msr_entry *e)
10243 {
10244         if (e->index == MSR_FS_BASE ||
10245             e->index == MSR_GS_BASE ||
10246             e->index == MSR_IA32_SMM_MONITOR_CTL || /* SMM is not supported */
10247             nested_vmx_msr_check_common(vcpu, e))
10248                 return -EINVAL;
10249         return 0;
10250 }
10251
10252 static int nested_vmx_store_msr_check(struct kvm_vcpu *vcpu,
10253                                       struct vmx_msr_entry *e)
10254 {
10255         if (e->index == MSR_IA32_SMBASE || /* SMM is not supported */
10256             nested_vmx_msr_check_common(vcpu, e))
10257                 return -EINVAL;
10258         return 0;
10259 }
10260
10261 /*
10262  * Load guest's/host's msr at nested entry/exit.
10263  * return 0 for success, entry index for failure.
10264  */
10265 static u32 nested_vmx_load_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
10266 {
10267         u32 i;
10268         struct vmx_msr_entry e;
10269         struct msr_data msr;
10270
10271         msr.host_initiated = false;
10272         for (i = 0; i < count; i++) {
10273                 if (kvm_vcpu_read_guest(vcpu, gpa + i * sizeof(e),
10274                                         &e, sizeof(e))) {
10275                         pr_debug_ratelimited(
10276                                 "%s cannot read MSR entry (%u, 0x%08llx)\n",
10277                                 __func__, i, gpa + i * sizeof(e));
10278                         goto fail;
10279                 }
10280                 if (nested_vmx_load_msr_check(vcpu, &e)) {
10281                         pr_debug_ratelimited(
10282                                 "%s check failed (%u, 0x%x, 0x%x)\n",
10283                                 __func__, i, e.index, e.reserved);
10284                         goto fail;
10285                 }
10286                 msr.index = e.index;
10287                 msr.data = e.value;
10288                 if (kvm_set_msr(vcpu, &msr)) {
10289                         pr_debug_ratelimited(
10290                                 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
10291                                 __func__, i, e.index, e.value);
10292                         goto fail;
10293                 }
10294         }
10295         return 0;
10296 fail:
10297         return i + 1;
10298 }
10299
10300 static int nested_vmx_store_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
10301 {
10302         u32 i;
10303         struct vmx_msr_entry e;
10304
10305         for (i = 0; i < count; i++) {
10306                 struct msr_data msr_info;
10307                 if (kvm_vcpu_read_guest(vcpu,
10308                                         gpa + i * sizeof(e),
10309                                         &e, 2 * sizeof(u32))) {
10310                         pr_debug_ratelimited(
10311                                 "%s cannot read MSR entry (%u, 0x%08llx)\n",
10312                                 __func__, i, gpa + i * sizeof(e));
10313                         return -EINVAL;
10314                 }
10315                 if (nested_vmx_store_msr_check(vcpu, &e)) {
10316                         pr_debug_ratelimited(
10317                                 "%s check failed (%u, 0x%x, 0x%x)\n",
10318                                 __func__, i, e.index, e.reserved);
10319                         return -EINVAL;
10320                 }
10321                 msr_info.host_initiated = false;
10322                 msr_info.index = e.index;
10323                 if (kvm_get_msr(vcpu, &msr_info)) {
10324                         pr_debug_ratelimited(
10325                                 "%s cannot read MSR (%u, 0x%x)\n",
10326                                 __func__, i, e.index);
10327                         return -EINVAL;
10328                 }
10329                 if (kvm_vcpu_write_guest(vcpu,
10330                                          gpa + i * sizeof(e) +
10331                                              offsetof(struct vmx_msr_entry, value),
10332                                          &msr_info.data, sizeof(msr_info.data))) {
10333                         pr_debug_ratelimited(
10334                                 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
10335                                 __func__, i, e.index, msr_info.data);
10336                         return -EINVAL;
10337                 }
10338         }
10339         return 0;
10340 }
10341
10342 static bool nested_cr3_valid(struct kvm_vcpu *vcpu, unsigned long val)
10343 {
10344         unsigned long invalid_mask;
10345
10346         invalid_mask = (~0ULL) << cpuid_maxphyaddr(vcpu);
10347         return (val & invalid_mask) == 0;
10348 }
10349
10350 /*
10351  * Load guest's/host's cr3 at nested entry/exit. nested_ept is true if we are
10352  * emulating VM entry into a guest with EPT enabled.
10353  * Returns 0 on success, 1 on failure. Invalid state exit qualification code
10354  * is assigned to entry_failure_code on failure.
10355  */
10356 static int nested_vmx_load_cr3(struct kvm_vcpu *vcpu, unsigned long cr3, bool nested_ept,
10357                                u32 *entry_failure_code)
10358 {
10359         if (cr3 != kvm_read_cr3(vcpu) || (!nested_ept && pdptrs_changed(vcpu))) {
10360                 if (!nested_cr3_valid(vcpu, cr3)) {
10361                         *entry_failure_code = ENTRY_FAIL_DEFAULT;
10362                         return 1;
10363                 }
10364
10365                 /*
10366                  * If PAE paging and EPT are both on, CR3 is not used by the CPU and
10367                  * must not be dereferenced.
10368                  */
10369                 if (!is_long_mode(vcpu) && is_pae(vcpu) && is_paging(vcpu) &&
10370                     !nested_ept) {
10371                         if (!load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3)) {
10372                                 *entry_failure_code = ENTRY_FAIL_PDPTE;
10373                                 return 1;
10374                         }
10375                 }
10376
10377                 vcpu->arch.cr3 = cr3;
10378                 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
10379         }
10380
10381         kvm_mmu_reset_context(vcpu);
10382         return 0;
10383 }
10384
10385 /*
10386  * prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
10387  * L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
10388  * with L0's requirements for its guest (a.k.a. vmcs01), so we can run the L2
10389  * guest in a way that will both be appropriate to L1's requests, and our
10390  * needs. In addition to modifying the active vmcs (which is vmcs02), this
10391  * function also has additional necessary side-effects, like setting various
10392  * vcpu->arch fields.
10393  * Returns 0 on success, 1 on failure. Invalid state exit qualification code
10394  * is assigned to entry_failure_code on failure.
10395  */
10396 static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
10397                           bool from_vmentry, u32 *entry_failure_code)
10398 {
10399         struct vcpu_vmx *vmx = to_vmx(vcpu);
10400         u32 exec_control, vmcs12_exec_ctrl;
10401
10402         vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
10403         vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
10404         vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
10405         vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
10406         vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
10407         vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
10408         vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
10409         vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
10410         vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
10411         vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
10412         vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
10413         vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
10414         vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
10415         vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
10416         vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
10417         vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
10418         vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
10419         vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
10420         vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
10421         vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
10422         vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
10423         vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
10424         vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
10425         vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
10426         vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
10427         vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
10428         vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
10429         vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
10430         vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
10431         vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
10432         vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
10433         vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
10434         vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
10435         vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
10436         vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
10437         vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
10438
10439         if (from_vmentry &&
10440             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS)) {
10441                 kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
10442                 vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
10443         } else {
10444                 kvm_set_dr(vcpu, 7, vcpu->arch.dr7);
10445                 vmcs_write64(GUEST_IA32_DEBUGCTL, vmx->nested.vmcs01_debugctl);
10446         }
10447         if (from_vmentry) {
10448                 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
10449                              vmcs12->vm_entry_intr_info_field);
10450                 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
10451                              vmcs12->vm_entry_exception_error_code);
10452                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
10453                              vmcs12->vm_entry_instruction_len);
10454                 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
10455                              vmcs12->guest_interruptibility_info);
10456                 vmx->loaded_vmcs->nmi_known_unmasked =
10457                         !(vmcs12->guest_interruptibility_info & GUEST_INTR_STATE_NMI);
10458         } else {
10459                 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
10460         }
10461         vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
10462         vmx_set_rflags(vcpu, vmcs12->guest_rflags);
10463         vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
10464                 vmcs12->guest_pending_dbg_exceptions);
10465         vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
10466         vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
10467
10468         if (nested_cpu_has_xsaves(vmcs12))
10469                 vmcs_write64(XSS_EXIT_BITMAP, vmcs12->xss_exit_bitmap);
10470         vmcs_write64(VMCS_LINK_POINTER, -1ull);
10471
10472         exec_control = vmcs12->pin_based_vm_exec_control;
10473
10474         /* Preemption timer setting is only taken from vmcs01.  */
10475         exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
10476         exec_control |= vmcs_config.pin_based_exec_ctrl;
10477         if (vmx->hv_deadline_tsc == -1)
10478                 exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
10479
10480         /* Posted interrupts setting is only taken from vmcs12.  */
10481         if (nested_cpu_has_posted_intr(vmcs12)) {
10482                 vmx->nested.posted_intr_nv = vmcs12->posted_intr_nv;
10483                 vmx->nested.pi_pending = false;
10484                 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_NESTED_VECTOR);
10485         } else {
10486                 exec_control &= ~PIN_BASED_POSTED_INTR;
10487         }
10488
10489         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, exec_control);
10490
10491         vmx->nested.preemption_timer_expired = false;
10492         if (nested_cpu_has_preemption_timer(vmcs12))
10493                 vmx_start_preemption_timer(vcpu);
10494
10495         /*
10496          * Whether page-faults are trapped is determined by a combination of
10497          * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.
10498          * If enable_ept, L0 doesn't care about page faults and we should
10499          * set all of these to L1's desires. However, if !enable_ept, L0 does
10500          * care about (at least some) page faults, and because it is not easy
10501          * (if at all possible?) to merge L0 and L1's desires, we simply ask
10502          * to exit on each and every L2 page fault. This is done by setting
10503          * MASK=MATCH=0 and (see below) EB.PF=1.
10504          * Note that below we don't need special code to set EB.PF beyond the
10505          * "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
10506          * vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
10507          * !enable_ept, EB.PF is 1, so the "or" will always be 1.
10508          */
10509         vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK,
10510                 enable_ept ? vmcs12->page_fault_error_code_mask : 0);
10511         vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
10512                 enable_ept ? vmcs12->page_fault_error_code_match : 0);
10513
10514         if (cpu_has_secondary_exec_ctrls()) {
10515                 exec_control = vmx->secondary_exec_control;
10516
10517                 /* Take the following fields only from vmcs12 */
10518                 exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
10519                                   SECONDARY_EXEC_ENABLE_INVPCID |
10520                                   SECONDARY_EXEC_RDTSCP |
10521                                   SECONDARY_EXEC_XSAVES |
10522                                   SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
10523                                   SECONDARY_EXEC_APIC_REGISTER_VIRT |
10524                                   SECONDARY_EXEC_ENABLE_VMFUNC);
10525                 if (nested_cpu_has(vmcs12,
10526                                    CPU_BASED_ACTIVATE_SECONDARY_CONTROLS)) {
10527                         vmcs12_exec_ctrl = vmcs12->secondary_vm_exec_control &
10528                                 ~SECONDARY_EXEC_ENABLE_PML;
10529                         exec_control |= vmcs12_exec_ctrl;
10530                 }
10531
10532                 /* All VMFUNCs are currently emulated through L0 vmexits.  */
10533                 if (exec_control & SECONDARY_EXEC_ENABLE_VMFUNC)
10534                         vmcs_write64(VM_FUNCTION_CONTROL, 0);
10535
10536                 if (exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
10537                         vmcs_write64(EOI_EXIT_BITMAP0,
10538                                 vmcs12->eoi_exit_bitmap0);
10539                         vmcs_write64(EOI_EXIT_BITMAP1,
10540                                 vmcs12->eoi_exit_bitmap1);
10541                         vmcs_write64(EOI_EXIT_BITMAP2,
10542                                 vmcs12->eoi_exit_bitmap2);
10543                         vmcs_write64(EOI_EXIT_BITMAP3,
10544                                 vmcs12->eoi_exit_bitmap3);
10545                         vmcs_write16(GUEST_INTR_STATUS,
10546                                 vmcs12->guest_intr_status);
10547                 }
10548
10549                 /*
10550                  * Write an illegal value to APIC_ACCESS_ADDR. Later,
10551                  * nested_get_vmcs12_pages will either fix it up or
10552                  * remove the VM execution control.
10553                  */
10554                 if (exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
10555                         vmcs_write64(APIC_ACCESS_ADDR, -1ull);
10556
10557                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
10558         }
10559
10560
10561         /*
10562          * Set host-state according to L0's settings (vmcs12 is irrelevant here)
10563          * Some constant fields are set here by vmx_set_constant_host_state().
10564          * Other fields are different per CPU, and will be set later when
10565          * vmx_vcpu_load() is called, and when vmx_save_host_state() is called.
10566          */
10567         vmx_set_constant_host_state(vmx);
10568
10569         /*
10570          * Set the MSR load/store lists to match L0's settings.
10571          */
10572         vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
10573         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
10574         vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host));
10575         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
10576         vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest));
10577
10578         /*
10579          * HOST_RSP is normally set correctly in vmx_vcpu_run() just before
10580          * entry, but only if the current (host) sp changed from the value
10581          * we wrote last (vmx->host_rsp). This cache is no longer relevant
10582          * if we switch vmcs, and rather than hold a separate cache per vmcs,
10583          * here we just force the write to happen on entry.
10584          */
10585         vmx->host_rsp = 0;
10586
10587         exec_control = vmx_exec_control(vmx); /* L0's desires */
10588         exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
10589         exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
10590         exec_control &= ~CPU_BASED_TPR_SHADOW;
10591         exec_control |= vmcs12->cpu_based_vm_exec_control;
10592
10593         /*
10594          * Write an illegal value to VIRTUAL_APIC_PAGE_ADDR. Later, if
10595          * nested_get_vmcs12_pages can't fix it up, the illegal value
10596          * will result in a VM entry failure.
10597          */
10598         if (exec_control & CPU_BASED_TPR_SHADOW) {
10599                 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, -1ull);
10600                 vmcs_write32(TPR_THRESHOLD, vmcs12->tpr_threshold);
10601         } else {
10602 #ifdef CONFIG_X86_64
10603                 exec_control |= CPU_BASED_CR8_LOAD_EXITING |
10604                                 CPU_BASED_CR8_STORE_EXITING;
10605 #endif
10606         }
10607
10608         /*
10609          * Merging of IO bitmap not currently supported.
10610          * Rather, exit every time.
10611          */
10612         exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
10613         exec_control |= CPU_BASED_UNCOND_IO_EXITING;
10614
10615         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
10616
10617         /* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
10618          * bitwise-or of what L1 wants to trap for L2, and what we want to
10619          * trap. Note that CR0.TS also needs updating - we do this later.
10620          */
10621         update_exception_bitmap(vcpu);
10622         vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
10623         vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
10624
10625         /* L2->L1 exit controls are emulated - the hardware exit is to L0 so
10626          * we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER
10627          * bits are further modified by vmx_set_efer() below.
10628          */
10629         vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);
10630
10631         /* vmcs12's VM_ENTRY_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE are
10632          * emulated by vmx_set_efer(), below.
10633          */
10634         vm_entry_controls_init(vmx, 
10635                 (vmcs12->vm_entry_controls & ~VM_ENTRY_LOAD_IA32_EFER &
10636                         ~VM_ENTRY_IA32E_MODE) |
10637                 (vmcs_config.vmentry_ctrl & ~VM_ENTRY_IA32E_MODE));
10638
10639         if (from_vmentry &&
10640             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT)) {
10641                 vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
10642                 vcpu->arch.pat = vmcs12->guest_ia32_pat;
10643         } else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
10644                 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
10645         }
10646
10647         set_cr4_guest_host_mask(vmx);
10648
10649         if (from_vmentry &&
10650             vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS)
10651                 vmcs_write64(GUEST_BNDCFGS, vmcs12->guest_bndcfgs);
10652
10653         if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
10654                 vmcs_write64(TSC_OFFSET,
10655                         vcpu->arch.tsc_offset + vmcs12->tsc_offset);
10656         else
10657                 vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
10658         if (kvm_has_tsc_control)
10659                 decache_tsc_multiplier(vmx);
10660
10661         if (enable_vpid) {
10662                 /*
10663                  * There is no direct mapping between vpid02 and vpid12, the
10664                  * vpid02 is per-vCPU for L0 and reused while the value of
10665                  * vpid12 is changed w/ one invvpid during nested vmentry.
10666                  * The vpid12 is allocated by L1 for L2, so it will not
10667                  * influence global bitmap(for vpid01 and vpid02 allocation)
10668                  * even if spawn a lot of nested vCPUs.
10669                  */
10670                 if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02) {
10671                         vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->nested.vpid02);
10672                         if (vmcs12->virtual_processor_id != vmx->nested.last_vpid) {
10673                                 vmx->nested.last_vpid = vmcs12->virtual_processor_id;
10674                                 __vmx_flush_tlb(vcpu, to_vmx(vcpu)->nested.vpid02);
10675                         }
10676                 } else {
10677                         vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
10678                         vmx_flush_tlb(vcpu);
10679                 }
10680
10681         }
10682
10683         if (enable_pml) {
10684                 /*
10685                  * Conceptually we want to copy the PML address and index from
10686                  * vmcs01 here, and then back to vmcs01 on nested vmexit. But,
10687                  * since we always flush the log on each vmexit, this happens
10688                  * to be equivalent to simply resetting the fields in vmcs02.
10689                  */
10690                 ASSERT(vmx->pml_pg);
10691                 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
10692                 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
10693         }
10694
10695         if (nested_cpu_has_ept(vmcs12)) {
10696                 if (nested_ept_init_mmu_context(vcpu)) {
10697                         *entry_failure_code = ENTRY_FAIL_DEFAULT;
10698                         return 1;
10699                 }
10700         } else if (nested_cpu_has2(vmcs12,
10701                                    SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
10702                 vmx_flush_tlb_ept_only(vcpu);
10703         }
10704
10705         /*
10706          * This sets GUEST_CR0 to vmcs12->guest_cr0, possibly modifying those
10707          * bits which we consider mandatory enabled.
10708          * The CR0_READ_SHADOW is what L2 should have expected to read given
10709          * the specifications by L1; It's not enough to take
10710          * vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we
10711          * have more bits than L1 expected.
10712          */
10713         vmx_set_cr0(vcpu, vmcs12->guest_cr0);
10714         vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
10715
10716         vmx_set_cr4(vcpu, vmcs12->guest_cr4);
10717         vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
10718
10719         if (from_vmentry &&
10720             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER))
10721                 vcpu->arch.efer = vmcs12->guest_ia32_efer;
10722         else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
10723                 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
10724         else
10725                 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
10726         /* Note: modifies VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
10727         vmx_set_efer(vcpu, vcpu->arch.efer);
10728
10729         /* Shadow page tables on either EPT or shadow page tables. */
10730         if (nested_vmx_load_cr3(vcpu, vmcs12->guest_cr3, nested_cpu_has_ept(vmcs12),
10731                                 entry_failure_code))
10732                 return 1;
10733
10734         if (!enable_ept)
10735                 vcpu->arch.walk_mmu->inject_page_fault = vmx_inject_page_fault_nested;
10736
10737         /*
10738          * L1 may access the L2's PDPTR, so save them to construct vmcs12
10739          */
10740         if (enable_ept) {
10741                 vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
10742                 vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
10743                 vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
10744                 vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
10745         }
10746
10747         kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->guest_rsp);
10748         kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->guest_rip);
10749         return 0;
10750 }
10751
10752 static int check_vmentry_prereqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
10753 {
10754         struct vcpu_vmx *vmx = to_vmx(vcpu);
10755
10756         if (vmcs12->guest_activity_state != GUEST_ACTIVITY_ACTIVE &&
10757             vmcs12->guest_activity_state != GUEST_ACTIVITY_HLT)
10758                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10759
10760         if (nested_vmx_check_io_bitmap_controls(vcpu, vmcs12))
10761                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10762
10763         if (nested_vmx_check_msr_bitmap_controls(vcpu, vmcs12))
10764                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10765
10766         if (nested_vmx_check_tpr_shadow_controls(vcpu, vmcs12))
10767                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10768
10769         if (nested_vmx_check_apicv_controls(vcpu, vmcs12))
10770                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10771
10772         if (nested_vmx_check_msr_switch_controls(vcpu, vmcs12))
10773                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10774
10775         if (nested_vmx_check_pml_controls(vcpu, vmcs12))
10776                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10777
10778         if (!vmx_control_verify(vmcs12->cpu_based_vm_exec_control,
10779                                 vmx->nested.nested_vmx_procbased_ctls_low,
10780                                 vmx->nested.nested_vmx_procbased_ctls_high) ||
10781             (nested_cpu_has(vmcs12, CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
10782              !vmx_control_verify(vmcs12->secondary_vm_exec_control,
10783                                  vmx->nested.nested_vmx_secondary_ctls_low,
10784                                  vmx->nested.nested_vmx_secondary_ctls_high)) ||
10785             !vmx_control_verify(vmcs12->pin_based_vm_exec_control,
10786                                 vmx->nested.nested_vmx_pinbased_ctls_low,
10787                                 vmx->nested.nested_vmx_pinbased_ctls_high) ||
10788             !vmx_control_verify(vmcs12->vm_exit_controls,
10789                                 vmx->nested.nested_vmx_exit_ctls_low,
10790                                 vmx->nested.nested_vmx_exit_ctls_high) ||
10791             !vmx_control_verify(vmcs12->vm_entry_controls,
10792                                 vmx->nested.nested_vmx_entry_ctls_low,
10793                                 vmx->nested.nested_vmx_entry_ctls_high))
10794                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10795
10796         if (nested_cpu_has_vmfunc(vmcs12)) {
10797                 if (vmcs12->vm_function_control &
10798                     ~vmx->nested.nested_vmx_vmfunc_controls)
10799                         return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10800
10801                 if (nested_cpu_has_eptp_switching(vmcs12)) {
10802                         if (!nested_cpu_has_ept(vmcs12) ||
10803                             !page_address_valid(vcpu, vmcs12->eptp_list_address))
10804                                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10805                 }
10806         }
10807
10808         if (vmcs12->cr3_target_count > nested_cpu_vmx_misc_cr3_count(vcpu))
10809                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
10810
10811         if (!nested_host_cr0_valid(vcpu, vmcs12->host_cr0) ||
10812             !nested_host_cr4_valid(vcpu, vmcs12->host_cr4) ||
10813             !nested_cr3_valid(vcpu, vmcs12->host_cr3))
10814                 return VMXERR_ENTRY_INVALID_HOST_STATE_FIELD;
10815
10816         return 0;
10817 }
10818
10819 static int check_vmentry_postreqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
10820                                   u32 *exit_qual)
10821 {
10822         bool ia32e;
10823
10824         *exit_qual = ENTRY_FAIL_DEFAULT;
10825
10826         if (!nested_guest_cr0_valid(vcpu, vmcs12->guest_cr0) ||
10827             !nested_guest_cr4_valid(vcpu, vmcs12->guest_cr4))
10828                 return 1;
10829
10830         if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_SHADOW_VMCS) &&
10831             vmcs12->vmcs_link_pointer != -1ull) {
10832                 *exit_qual = ENTRY_FAIL_VMCS_LINK_PTR;
10833                 return 1;
10834         }
10835
10836         /*
10837          * If the load IA32_EFER VM-entry control is 1, the following checks
10838          * are performed on the field for the IA32_EFER MSR:
10839          * - Bits reserved in the IA32_EFER MSR must be 0.
10840          * - Bit 10 (corresponding to IA32_EFER.LMA) must equal the value of
10841          *   the IA-32e mode guest VM-exit control. It must also be identical
10842          *   to bit 8 (LME) if bit 31 in the CR0 field (corresponding to
10843          *   CR0.PG) is 1.
10844          */
10845         if (to_vmx(vcpu)->nested.nested_run_pending &&
10846             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)) {
10847                 ia32e = (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) != 0;
10848                 if (!kvm_valid_efer(vcpu, vmcs12->guest_ia32_efer) ||
10849                     ia32e != !!(vmcs12->guest_ia32_efer & EFER_LMA) ||
10850                     ((vmcs12->guest_cr0 & X86_CR0_PG) &&
10851                      ia32e != !!(vmcs12->guest_ia32_efer & EFER_LME)))
10852                         return 1;
10853         }
10854
10855         /*
10856          * If the load IA32_EFER VM-exit control is 1, bits reserved in the
10857          * IA32_EFER MSR must be 0 in the field for that register. In addition,
10858          * the values of the LMA and LME bits in the field must each be that of
10859          * the host address-space size VM-exit control.
10860          */
10861         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) {
10862                 ia32e = (vmcs12->vm_exit_controls &
10863                          VM_EXIT_HOST_ADDR_SPACE_SIZE) != 0;
10864                 if (!kvm_valid_efer(vcpu, vmcs12->host_ia32_efer) ||
10865                     ia32e != !!(vmcs12->host_ia32_efer & EFER_LMA) ||
10866                     ia32e != !!(vmcs12->host_ia32_efer & EFER_LME))
10867                         return 1;
10868         }
10869
10870         return 0;
10871 }
10872
10873 static int enter_vmx_non_root_mode(struct kvm_vcpu *vcpu, bool from_vmentry)
10874 {
10875         struct vcpu_vmx *vmx = to_vmx(vcpu);
10876         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
10877         struct loaded_vmcs *vmcs02;
10878         u32 msr_entry_idx;
10879         u32 exit_qual;
10880
10881         vmcs02 = nested_get_current_vmcs02(vmx);
10882         if (!vmcs02)
10883                 return -ENOMEM;
10884
10885         enter_guest_mode(vcpu);
10886
10887         if (!(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS))
10888                 vmx->nested.vmcs01_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
10889
10890         vmx_switch_vmcs(vcpu, vmcs02);
10891         vmx_segment_cache_clear(vmx);
10892
10893         if (prepare_vmcs02(vcpu, vmcs12, from_vmentry, &exit_qual)) {
10894                 leave_guest_mode(vcpu);
10895                 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
10896                 nested_vmx_entry_failure(vcpu, vmcs12,
10897                                          EXIT_REASON_INVALID_STATE, exit_qual);
10898                 return 1;
10899         }
10900
10901         nested_get_vmcs12_pages(vcpu, vmcs12);
10902
10903         msr_entry_idx = nested_vmx_load_msr(vcpu,
10904                                             vmcs12->vm_entry_msr_load_addr,
10905                                             vmcs12->vm_entry_msr_load_count);
10906         if (msr_entry_idx) {
10907                 leave_guest_mode(vcpu);
10908                 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
10909                 nested_vmx_entry_failure(vcpu, vmcs12,
10910                                 EXIT_REASON_MSR_LOAD_FAIL, msr_entry_idx);
10911                 return 1;
10912         }
10913
10914         /*
10915          * Note no nested_vmx_succeed or nested_vmx_fail here. At this point
10916          * we are no longer running L1, and VMLAUNCH/VMRESUME has not yet
10917          * returned as far as L1 is concerned. It will only return (and set
10918          * the success flag) when L2 exits (see nested_vmx_vmexit()).
10919          */
10920         return 0;
10921 }
10922
10923 /*
10924  * nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1
10925  * for running an L2 nested guest.
10926  */
10927 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
10928 {
10929         struct vmcs12 *vmcs12;
10930         struct vcpu_vmx *vmx = to_vmx(vcpu);
10931         u32 interrupt_shadow = vmx_get_interrupt_shadow(vcpu);
10932         u32 exit_qual;
10933         int ret;
10934
10935         if (!nested_vmx_check_permission(vcpu))
10936                 return 1;
10937
10938         if (!nested_vmx_check_vmcs12(vcpu))
10939                 goto out;
10940
10941         vmcs12 = get_vmcs12(vcpu);
10942
10943         if (enable_shadow_vmcs)
10944                 copy_shadow_to_vmcs12(vmx);
10945
10946         /*
10947          * The nested entry process starts with enforcing various prerequisites
10948          * on vmcs12 as required by the Intel SDM, and act appropriately when
10949          * they fail: As the SDM explains, some conditions should cause the
10950          * instruction to fail, while others will cause the instruction to seem
10951          * to succeed, but return an EXIT_REASON_INVALID_STATE.
10952          * To speed up the normal (success) code path, we should avoid checking
10953          * for misconfigurations which will anyway be caught by the processor
10954          * when using the merged vmcs02.
10955          */
10956         if (interrupt_shadow & KVM_X86_SHADOW_INT_MOV_SS) {
10957                 nested_vmx_failValid(vcpu,
10958                                      VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS);
10959                 goto out;
10960         }
10961
10962         if (vmcs12->launch_state == launch) {
10963                 nested_vmx_failValid(vcpu,
10964                         launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
10965                                : VMXERR_VMRESUME_NONLAUNCHED_VMCS);
10966                 goto out;
10967         }
10968
10969         ret = check_vmentry_prereqs(vcpu, vmcs12);
10970         if (ret) {
10971                 nested_vmx_failValid(vcpu, ret);
10972                 goto out;
10973         }
10974
10975         /*
10976          * After this point, the trap flag no longer triggers a singlestep trap
10977          * on the vm entry instructions; don't call kvm_skip_emulated_instruction.
10978          * This is not 100% correct; for performance reasons, we delegate most
10979          * of the checks on host state to the processor.  If those fail,
10980          * the singlestep trap is missed.
10981          */
10982         skip_emulated_instruction(vcpu);
10983
10984         ret = check_vmentry_postreqs(vcpu, vmcs12, &exit_qual);
10985         if (ret) {
10986                 nested_vmx_entry_failure(vcpu, vmcs12,
10987                                          EXIT_REASON_INVALID_STATE, exit_qual);
10988                 return 1;
10989         }
10990
10991         /*
10992          * We're finally done with prerequisite checking, and can start with
10993          * the nested entry.
10994          */
10995
10996         ret = enter_vmx_non_root_mode(vcpu, true);
10997         if (ret)
10998                 return ret;
10999
11000         if (vmcs12->guest_activity_state == GUEST_ACTIVITY_HLT)
11001                 return kvm_vcpu_halt(vcpu);
11002
11003         vmx->nested.nested_run_pending = 1;
11004
11005         return 1;
11006
11007 out:
11008         return kvm_skip_emulated_instruction(vcpu);
11009 }
11010
11011 /*
11012  * On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
11013  * because L2 may have changed some cr0 bits directly (CRO_GUEST_HOST_MASK).
11014  * This function returns the new value we should put in vmcs12.guest_cr0.
11015  * It's not enough to just return the vmcs02 GUEST_CR0. Rather,
11016  *  1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
11017  *     available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0
11018  *     didn't trap the bit, because if L1 did, so would L0).
11019  *  2. Bits that L1 asked to trap (and therefore L0 also did) could not have
11020  *     been modified by L2, and L1 knows it. So just leave the old value of
11021  *     the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0
11022  *     isn't relevant, because if L0 traps this bit it can set it to anything.
11023  *  3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have
11024  *     changed these bits, and therefore they need to be updated, but L0
11025  *     didn't necessarily allow them to be changed in GUEST_CR0 - and rather
11026  *     put them in vmcs02 CR0_READ_SHADOW. So take these bits from there.
11027  */
11028 static inline unsigned long
11029 vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
11030 {
11031         return
11032         /*1*/   (vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) |
11033         /*2*/   (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) |
11034         /*3*/   (vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask |
11035                         vcpu->arch.cr0_guest_owned_bits));
11036 }
11037
11038 static inline unsigned long
11039 vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
11040 {
11041         return
11042         /*1*/   (vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) |
11043         /*2*/   (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) |
11044         /*3*/   (vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask |
11045                         vcpu->arch.cr4_guest_owned_bits));
11046 }
11047
11048 static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
11049                                        struct vmcs12 *vmcs12)
11050 {
11051         u32 idt_vectoring;
11052         unsigned int nr;
11053
11054         if (vcpu->arch.exception.injected) {
11055                 nr = vcpu->arch.exception.nr;
11056                 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
11057
11058                 if (kvm_exception_is_soft(nr)) {
11059                         vmcs12->vm_exit_instruction_len =
11060                                 vcpu->arch.event_exit_inst_len;
11061                         idt_vectoring |= INTR_TYPE_SOFT_EXCEPTION;
11062                 } else
11063                         idt_vectoring |= INTR_TYPE_HARD_EXCEPTION;
11064
11065                 if (vcpu->arch.exception.has_error_code) {
11066                         idt_vectoring |= VECTORING_INFO_DELIVER_CODE_MASK;
11067                         vmcs12->idt_vectoring_error_code =
11068                                 vcpu->arch.exception.error_code;
11069                 }
11070
11071                 vmcs12->idt_vectoring_info_field = idt_vectoring;
11072         } else if (vcpu->arch.nmi_injected) {
11073                 vmcs12->idt_vectoring_info_field =
11074                         INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR;
11075         } else if (vcpu->arch.interrupt.pending) {
11076                 nr = vcpu->arch.interrupt.nr;
11077                 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
11078
11079                 if (vcpu->arch.interrupt.soft) {
11080                         idt_vectoring |= INTR_TYPE_SOFT_INTR;
11081                         vmcs12->vm_entry_instruction_len =
11082                                 vcpu->arch.event_exit_inst_len;
11083                 } else
11084                         idt_vectoring |= INTR_TYPE_EXT_INTR;
11085
11086                 vmcs12->idt_vectoring_info_field = idt_vectoring;
11087         }
11088 }
11089
11090 static int vmx_check_nested_events(struct kvm_vcpu *vcpu, bool external_intr)
11091 {
11092         struct vcpu_vmx *vmx = to_vmx(vcpu);
11093         unsigned long exit_qual;
11094
11095         if (kvm_event_needs_reinjection(vcpu))
11096                 return -EBUSY;
11097
11098         if (vcpu->arch.exception.pending &&
11099                 nested_vmx_check_exception(vcpu, &exit_qual)) {
11100                 if (vmx->nested.nested_run_pending)
11101                         return -EBUSY;
11102                 nested_vmx_inject_exception_vmexit(vcpu, exit_qual);
11103                 vcpu->arch.exception.pending = false;
11104                 return 0;
11105         }
11106
11107         if (nested_cpu_has_preemption_timer(get_vmcs12(vcpu)) &&
11108             vmx->nested.preemption_timer_expired) {
11109                 if (vmx->nested.nested_run_pending)
11110                         return -EBUSY;
11111                 nested_vmx_vmexit(vcpu, EXIT_REASON_PREEMPTION_TIMER, 0, 0);
11112                 return 0;
11113         }
11114
11115         if (vcpu->arch.nmi_pending && nested_exit_on_nmi(vcpu)) {
11116                 if (vmx->nested.nested_run_pending)
11117                         return -EBUSY;
11118                 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
11119                                   NMI_VECTOR | INTR_TYPE_NMI_INTR |
11120                                   INTR_INFO_VALID_MASK, 0);
11121                 /*
11122                  * The NMI-triggered VM exit counts as injection:
11123                  * clear this one and block further NMIs.
11124                  */
11125                 vcpu->arch.nmi_pending = 0;
11126                 vmx_set_nmi_mask(vcpu, true);
11127                 return 0;
11128         }
11129
11130         if ((kvm_cpu_has_interrupt(vcpu) || external_intr) &&
11131             nested_exit_on_intr(vcpu)) {
11132                 if (vmx->nested.nested_run_pending)
11133                         return -EBUSY;
11134                 nested_vmx_vmexit(vcpu, EXIT_REASON_EXTERNAL_INTERRUPT, 0, 0);
11135                 return 0;
11136         }
11137
11138         vmx_complete_nested_posted_interrupt(vcpu);
11139         return 0;
11140 }
11141
11142 static u32 vmx_get_preemption_timer_value(struct kvm_vcpu *vcpu)
11143 {
11144         ktime_t remaining =
11145                 hrtimer_get_remaining(&to_vmx(vcpu)->nested.preemption_timer);
11146         u64 value;
11147
11148         if (ktime_to_ns(remaining) <= 0)
11149                 return 0;
11150
11151         value = ktime_to_ns(remaining) * vcpu->arch.virtual_tsc_khz;
11152         do_div(value, 1000000);
11153         return value >> VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
11154 }
11155
11156 /*
11157  * Update the guest state fields of vmcs12 to reflect changes that
11158  * occurred while L2 was running. (The "IA-32e mode guest" bit of the
11159  * VM-entry controls is also updated, since this is really a guest
11160  * state bit.)
11161  */
11162 static void sync_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
11163 {
11164         vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12);
11165         vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12);
11166
11167         vmcs12->guest_rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
11168         vmcs12->guest_rip = kvm_register_read(vcpu, VCPU_REGS_RIP);
11169         vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS);
11170
11171         vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR);
11172         vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR);
11173         vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR);
11174         vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR);
11175         vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR);
11176         vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR);
11177         vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR);
11178         vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR);
11179         vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT);
11180         vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT);
11181         vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT);
11182         vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT);
11183         vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT);
11184         vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT);
11185         vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT);
11186         vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT);
11187         vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT);
11188         vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT);
11189         vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES);
11190         vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES);
11191         vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES);
11192         vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES);
11193         vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES);
11194         vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES);
11195         vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES);
11196         vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES);
11197         vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE);
11198         vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE);
11199         vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE);
11200         vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE);
11201         vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE);
11202         vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE);
11203         vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE);
11204         vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE);
11205         vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE);
11206         vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE);
11207
11208         vmcs12->guest_interruptibility_info =
11209                 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
11210         vmcs12->guest_pending_dbg_exceptions =
11211                 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);
11212         if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
11213                 vmcs12->guest_activity_state = GUEST_ACTIVITY_HLT;
11214         else
11215                 vmcs12->guest_activity_state = GUEST_ACTIVITY_ACTIVE;
11216
11217         if (nested_cpu_has_preemption_timer(vmcs12)) {
11218                 if (vmcs12->vm_exit_controls &
11219                     VM_EXIT_SAVE_VMX_PREEMPTION_TIMER)
11220                         vmcs12->vmx_preemption_timer_value =
11221                                 vmx_get_preemption_timer_value(vcpu);
11222                 hrtimer_cancel(&to_vmx(vcpu)->nested.preemption_timer);
11223         }
11224
11225         /*
11226          * In some cases (usually, nested EPT), L2 is allowed to change its
11227          * own CR3 without exiting. If it has changed it, we must keep it.
11228          * Of course, if L0 is using shadow page tables, GUEST_CR3 was defined
11229          * by L0, not L1 or L2, so we mustn't unconditionally copy it to vmcs12.
11230          *
11231          * Additionally, restore L2's PDPTR to vmcs12.
11232          */
11233         if (enable_ept) {
11234                 vmcs12->guest_cr3 = vmcs_readl(GUEST_CR3);
11235                 vmcs12->guest_pdptr0 = vmcs_read64(GUEST_PDPTR0);
11236                 vmcs12->guest_pdptr1 = vmcs_read64(GUEST_PDPTR1);
11237                 vmcs12->guest_pdptr2 = vmcs_read64(GUEST_PDPTR2);
11238                 vmcs12->guest_pdptr3 = vmcs_read64(GUEST_PDPTR3);
11239         }
11240
11241         vmcs12->guest_linear_address = vmcs_readl(GUEST_LINEAR_ADDRESS);
11242
11243         if (nested_cpu_has_vid(vmcs12))
11244                 vmcs12->guest_intr_status = vmcs_read16(GUEST_INTR_STATUS);
11245
11246         vmcs12->vm_entry_controls =
11247                 (vmcs12->vm_entry_controls & ~VM_ENTRY_IA32E_MODE) |
11248                 (vm_entry_controls_get(to_vmx(vcpu)) & VM_ENTRY_IA32E_MODE);
11249
11250         if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_DEBUG_CONTROLS) {
11251                 kvm_get_dr(vcpu, 7, (unsigned long *)&vmcs12->guest_dr7);
11252                 vmcs12->guest_ia32_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
11253         }
11254
11255         /* TODO: These cannot have changed unless we have MSR bitmaps and
11256          * the relevant bit asks not to trap the change */
11257         if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
11258                 vmcs12->guest_ia32_pat = vmcs_read64(GUEST_IA32_PAT);
11259         if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_EFER)
11260                 vmcs12->guest_ia32_efer = vcpu->arch.efer;
11261         vmcs12->guest_sysenter_cs = vmcs_read32(GUEST_SYSENTER_CS);
11262         vmcs12->guest_sysenter_esp = vmcs_readl(GUEST_SYSENTER_ESP);
11263         vmcs12->guest_sysenter_eip = vmcs_readl(GUEST_SYSENTER_EIP);
11264         if (kvm_mpx_supported())
11265                 vmcs12->guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
11266 }
11267
11268 /*
11269  * prepare_vmcs12 is part of what we need to do when the nested L2 guest exits
11270  * and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12),
11271  * and this function updates it to reflect the changes to the guest state while
11272  * L2 was running (and perhaps made some exits which were handled directly by L0
11273  * without going back to L1), and to reflect the exit reason.
11274  * Note that we do not have to copy here all VMCS fields, just those that
11275  * could have changed by the L2 guest or the exit - i.e., the guest-state and
11276  * exit-information fields only. Other fields are modified by L1 with VMWRITE,
11277  * which already writes to vmcs12 directly.
11278  */
11279 static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
11280                            u32 exit_reason, u32 exit_intr_info,
11281                            unsigned long exit_qualification)
11282 {
11283         /* update guest state fields: */
11284         sync_vmcs12(vcpu, vmcs12);
11285
11286         /* update exit information fields: */
11287
11288         vmcs12->vm_exit_reason = exit_reason;
11289         vmcs12->exit_qualification = exit_qualification;
11290         vmcs12->vm_exit_intr_info = exit_intr_info;
11291
11292         vmcs12->idt_vectoring_info_field = 0;
11293         vmcs12->vm_exit_instruction_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
11294         vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
11295
11296         if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY)) {
11297                 vmcs12->launch_state = 1;
11298
11299                 /* vm_entry_intr_info_field is cleared on exit. Emulate this
11300                  * instead of reading the real value. */
11301                 vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK;
11302
11303                 /*
11304                  * Transfer the event that L0 or L1 may wanted to inject into
11305                  * L2 to IDT_VECTORING_INFO_FIELD.
11306                  */
11307                 vmcs12_save_pending_event(vcpu, vmcs12);
11308         }
11309
11310         /*
11311          * Drop what we picked up for L2 via vmx_complete_interrupts. It is
11312          * preserved above and would only end up incorrectly in L1.
11313          */
11314         vcpu->arch.nmi_injected = false;
11315         kvm_clear_exception_queue(vcpu);
11316         kvm_clear_interrupt_queue(vcpu);
11317 }
11318
11319 /*
11320  * A part of what we need to when the nested L2 guest exits and we want to
11321  * run its L1 parent, is to reset L1's guest state to the host state specified
11322  * in vmcs12.
11323  * This function is to be called not only on normal nested exit, but also on
11324  * a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry
11325  * Failures During or After Loading Guest State").
11326  * This function should be called when the active VMCS is L1's (vmcs01).
11327  */
11328 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
11329                                    struct vmcs12 *vmcs12)
11330 {
11331         struct kvm_segment seg;
11332         u32 entry_failure_code;
11333
11334         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
11335                 vcpu->arch.efer = vmcs12->host_ia32_efer;
11336         else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
11337                 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
11338         else
11339                 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
11340         vmx_set_efer(vcpu, vcpu->arch.efer);
11341
11342         kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp);
11343         kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip);
11344         vmx_set_rflags(vcpu, X86_EFLAGS_FIXED);
11345         /*
11346          * Note that calling vmx_set_cr0 is important, even if cr0 hasn't
11347          * actually changed, because vmx_set_cr0 refers to efer set above.
11348          *
11349          * CR0_GUEST_HOST_MASK is already set in the original vmcs01
11350          * (KVM doesn't change it);
11351          */
11352         vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
11353         vmx_set_cr0(vcpu, vmcs12->host_cr0);
11354
11355         /* Same as above - no reason to call set_cr4_guest_host_mask().  */
11356         vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
11357         vmx_set_cr4(vcpu, vmcs12->host_cr4);
11358
11359         nested_ept_uninit_mmu_context(vcpu);
11360
11361         /*
11362          * Only PDPTE load can fail as the value of cr3 was checked on entry and
11363          * couldn't have changed.
11364          */
11365         if (nested_vmx_load_cr3(vcpu, vmcs12->host_cr3, false, &entry_failure_code))
11366                 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_PDPTE_FAIL);
11367
11368         if (!enable_ept)
11369                 vcpu->arch.walk_mmu->inject_page_fault = kvm_inject_page_fault;
11370
11371         if (enable_vpid) {
11372                 /*
11373                  * Trivially support vpid by letting L2s share their parent
11374                  * L1's vpid. TODO: move to a more elaborate solution, giving
11375                  * each L2 its own vpid and exposing the vpid feature to L1.
11376                  */
11377                 vmx_flush_tlb(vcpu);
11378         }
11379         /* Restore posted intr vector. */
11380         if (nested_cpu_has_posted_intr(vmcs12))
11381                 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
11382
11383         vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
11384         vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp);
11385         vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip);
11386         vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base);
11387         vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base);
11388         vmcs_write32(GUEST_IDTR_LIMIT, 0xFFFF);
11389         vmcs_write32(GUEST_GDTR_LIMIT, 0xFFFF);
11390
11391         /* If not VM_EXIT_CLEAR_BNDCFGS, the L2 value propagates to L1.  */
11392         if (vmcs12->vm_exit_controls & VM_EXIT_CLEAR_BNDCFGS)
11393                 vmcs_write64(GUEST_BNDCFGS, 0);
11394
11395         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) {
11396                 vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat);
11397                 vcpu->arch.pat = vmcs12->host_ia32_pat;
11398         }
11399         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
11400                 vmcs_write64(GUEST_IA32_PERF_GLOBAL_CTRL,
11401                         vmcs12->host_ia32_perf_global_ctrl);
11402
11403         /* Set L1 segment info according to Intel SDM
11404             27.5.2 Loading Host Segment and Descriptor-Table Registers */
11405         seg = (struct kvm_segment) {
11406                 .base = 0,
11407                 .limit = 0xFFFFFFFF,
11408                 .selector = vmcs12->host_cs_selector,
11409                 .type = 11,
11410                 .present = 1,
11411                 .s = 1,
11412                 .g = 1
11413         };
11414         if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
11415                 seg.l = 1;
11416         else
11417                 seg.db = 1;
11418         vmx_set_segment(vcpu, &seg, VCPU_SREG_CS);
11419         seg = (struct kvm_segment) {
11420                 .base = 0,
11421                 .limit = 0xFFFFFFFF,
11422                 .type = 3,
11423                 .present = 1,
11424                 .s = 1,
11425                 .db = 1,
11426                 .g = 1
11427         };
11428         seg.selector = vmcs12->host_ds_selector;
11429         vmx_set_segment(vcpu, &seg, VCPU_SREG_DS);
11430         seg.selector = vmcs12->host_es_selector;
11431         vmx_set_segment(vcpu, &seg, VCPU_SREG_ES);
11432         seg.selector = vmcs12->host_ss_selector;
11433         vmx_set_segment(vcpu, &seg, VCPU_SREG_SS);
11434         seg.selector = vmcs12->host_fs_selector;
11435         seg.base = vmcs12->host_fs_base;
11436         vmx_set_segment(vcpu, &seg, VCPU_SREG_FS);
11437         seg.selector = vmcs12->host_gs_selector;
11438         seg.base = vmcs12->host_gs_base;
11439         vmx_set_segment(vcpu, &seg, VCPU_SREG_GS);
11440         seg = (struct kvm_segment) {
11441                 .base = vmcs12->host_tr_base,
11442                 .limit = 0x67,
11443                 .selector = vmcs12->host_tr_selector,
11444                 .type = 11,
11445                 .present = 1
11446         };
11447         vmx_set_segment(vcpu, &seg, VCPU_SREG_TR);
11448
11449         kvm_set_dr(vcpu, 7, 0x400);
11450         vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
11451
11452         if (cpu_has_vmx_msr_bitmap())
11453                 vmx_set_msr_bitmap(vcpu);
11454
11455         if (nested_vmx_load_msr(vcpu, vmcs12->vm_exit_msr_load_addr,
11456                                 vmcs12->vm_exit_msr_load_count))
11457                 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
11458 }
11459
11460 /*
11461  * Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
11462  * and modify vmcs12 to make it see what it would expect to see there if
11463  * L2 was its real guest. Must only be called when in L2 (is_guest_mode())
11464  */
11465 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
11466                               u32 exit_intr_info,
11467                               unsigned long exit_qualification)
11468 {
11469         struct vcpu_vmx *vmx = to_vmx(vcpu);
11470         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11471
11472         /* trying to cancel vmlaunch/vmresume is a bug */
11473         WARN_ON_ONCE(vmx->nested.nested_run_pending);
11474
11475         /*
11476          * The only expected VM-instruction error is "VM entry with
11477          * invalid control field(s)." Anything else indicates a
11478          * problem with L0.
11479          */
11480         WARN_ON_ONCE(vmx->fail && (vmcs_read32(VM_INSTRUCTION_ERROR) !=
11481                                    VMXERR_ENTRY_INVALID_CONTROL_FIELD));
11482
11483         leave_guest_mode(vcpu);
11484
11485         if (likely(!vmx->fail)) {
11486                 prepare_vmcs12(vcpu, vmcs12, exit_reason, exit_intr_info,
11487                                exit_qualification);
11488
11489                 if (nested_vmx_store_msr(vcpu, vmcs12->vm_exit_msr_store_addr,
11490                                          vmcs12->vm_exit_msr_store_count))
11491                         nested_vmx_abort(vcpu, VMX_ABORT_SAVE_GUEST_MSR_FAIL);
11492         }
11493
11494         vmx_switch_vmcs(vcpu, &vmx->vmcs01);
11495         vm_entry_controls_reset_shadow(vmx);
11496         vm_exit_controls_reset_shadow(vmx);
11497         vmx_segment_cache_clear(vmx);
11498
11499         /* if no vmcs02 cache requested, remove the one we used */
11500         if (VMCS02_POOL_SIZE == 0)
11501                 nested_free_vmcs02(vmx, vmx->nested.current_vmptr);
11502
11503         /* Update any VMCS fields that might have changed while L2 ran */
11504         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
11505         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
11506         vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
11507         if (vmx->hv_deadline_tsc == -1)
11508                 vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
11509                                 PIN_BASED_VMX_PREEMPTION_TIMER);
11510         else
11511                 vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
11512                               PIN_BASED_VMX_PREEMPTION_TIMER);
11513         if (kvm_has_tsc_control)
11514                 decache_tsc_multiplier(vmx);
11515
11516         if (vmx->nested.change_vmcs01_virtual_x2apic_mode) {
11517                 vmx->nested.change_vmcs01_virtual_x2apic_mode = false;
11518                 vmx_set_virtual_x2apic_mode(vcpu,
11519                                 vcpu->arch.apic_base & X2APIC_ENABLE);
11520         } else if (!nested_cpu_has_ept(vmcs12) &&
11521                    nested_cpu_has2(vmcs12,
11522                                    SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
11523                 vmx_flush_tlb_ept_only(vcpu);
11524         }
11525
11526         /* This is needed for same reason as it was needed in prepare_vmcs02 */
11527         vmx->host_rsp = 0;
11528
11529         /* Unpin physical memory we referred to in vmcs02 */
11530         if (vmx->nested.apic_access_page) {
11531                 kvm_release_page_dirty(vmx->nested.apic_access_page);
11532                 vmx->nested.apic_access_page = NULL;
11533         }
11534         if (vmx->nested.virtual_apic_page) {
11535                 kvm_release_page_dirty(vmx->nested.virtual_apic_page);
11536                 vmx->nested.virtual_apic_page = NULL;
11537         }
11538         if (vmx->nested.pi_desc_page) {
11539                 kunmap(vmx->nested.pi_desc_page);
11540                 kvm_release_page_dirty(vmx->nested.pi_desc_page);
11541                 vmx->nested.pi_desc_page = NULL;
11542                 vmx->nested.pi_desc = NULL;
11543         }
11544
11545         /*
11546          * We are now running in L2, mmu_notifier will force to reload the
11547          * page's hpa for L2 vmcs. Need to reload it for L1 before entering L1.
11548          */
11549         kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
11550
11551         if (enable_shadow_vmcs)
11552                 vmx->nested.sync_shadow_vmcs = true;
11553
11554         /* in case we halted in L2 */
11555         vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
11556
11557         if (likely(!vmx->fail)) {
11558                 /*
11559                  * TODO: SDM says that with acknowledge interrupt on
11560                  * exit, bit 31 of the VM-exit interrupt information
11561                  * (valid interrupt) is always set to 1 on
11562                  * EXIT_REASON_EXTERNAL_INTERRUPT, so we shouldn't
11563                  * need kvm_cpu_has_interrupt().  See the commit
11564                  * message for details.
11565                  */
11566                 if (nested_exit_intr_ack_set(vcpu) &&
11567                     exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT &&
11568                     kvm_cpu_has_interrupt(vcpu)) {
11569                         int irq = kvm_cpu_get_interrupt(vcpu);
11570                         WARN_ON(irq < 0);
11571                         vmcs12->vm_exit_intr_info = irq |
11572                                 INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR;
11573                 }
11574
11575                 trace_kvm_nested_vmexit_inject(vmcs12->vm_exit_reason,
11576                                                vmcs12->exit_qualification,
11577                                                vmcs12->idt_vectoring_info_field,
11578                                                vmcs12->vm_exit_intr_info,
11579                                                vmcs12->vm_exit_intr_error_code,
11580                                                KVM_ISA_VMX);
11581
11582                 load_vmcs12_host_state(vcpu, vmcs12);
11583
11584                 return;
11585         }
11586         
11587         /*
11588          * After an early L2 VM-entry failure, we're now back
11589          * in L1 which thinks it just finished a VMLAUNCH or
11590          * VMRESUME instruction, so we need to set the failure
11591          * flag and the VM-instruction error field of the VMCS
11592          * accordingly.
11593          */
11594         nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
11595         /*
11596          * The emulated instruction was already skipped in
11597          * nested_vmx_run, but the updated RIP was never
11598          * written back to the vmcs01.
11599          */
11600         skip_emulated_instruction(vcpu);
11601         vmx->fail = 0;
11602 }
11603
11604 /*
11605  * Forcibly leave nested mode in order to be able to reset the VCPU later on.
11606  */
11607 static void vmx_leave_nested(struct kvm_vcpu *vcpu)
11608 {
11609         if (is_guest_mode(vcpu)) {
11610                 to_vmx(vcpu)->nested.nested_run_pending = 0;
11611                 nested_vmx_vmexit(vcpu, -1, 0, 0);
11612         }
11613         free_nested(to_vmx(vcpu));
11614 }
11615
11616 /*
11617  * L1's failure to enter L2 is a subset of a normal exit, as explained in
11618  * 23.7 "VM-entry failures during or after loading guest state" (this also
11619  * lists the acceptable exit-reason and exit-qualification parameters).
11620  * It should only be called before L2 actually succeeded to run, and when
11621  * vmcs01 is current (it doesn't leave_guest_mode() or switch vmcss).
11622  */
11623 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
11624                         struct vmcs12 *vmcs12,
11625                         u32 reason, unsigned long qualification)
11626 {
11627         load_vmcs12_host_state(vcpu, vmcs12);
11628         vmcs12->vm_exit_reason = reason | VMX_EXIT_REASONS_FAILED_VMENTRY;
11629         vmcs12->exit_qualification = qualification;
11630         nested_vmx_succeed(vcpu);
11631         if (enable_shadow_vmcs)
11632                 to_vmx(vcpu)->nested.sync_shadow_vmcs = true;
11633 }
11634
11635 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
11636                                struct x86_instruction_info *info,
11637                                enum x86_intercept_stage stage)
11638 {
11639         return X86EMUL_CONTINUE;
11640 }
11641
11642 #ifdef CONFIG_X86_64
11643 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
11644 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
11645                                   u64 divisor, u64 *result)
11646 {
11647         u64 low = a << shift, high = a >> (64 - shift);
11648
11649         /* To avoid the overflow on divq */
11650         if (high >= divisor)
11651                 return 1;
11652
11653         /* Low hold the result, high hold rem which is discarded */
11654         asm("divq %2\n\t" : "=a" (low), "=d" (high) :
11655             "rm" (divisor), "0" (low), "1" (high));
11656         *result = low;
11657
11658         return 0;
11659 }
11660
11661 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc)
11662 {
11663         struct vcpu_vmx *vmx = to_vmx(vcpu);
11664         u64 tscl = rdtsc();
11665         u64 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
11666         u64 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
11667
11668         /* Convert to host delta tsc if tsc scaling is enabled */
11669         if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
11670                         u64_shl_div_u64(delta_tsc,
11671                                 kvm_tsc_scaling_ratio_frac_bits,
11672                                 vcpu->arch.tsc_scaling_ratio,
11673                                 &delta_tsc))
11674                 return -ERANGE;
11675
11676         /*
11677          * If the delta tsc can't fit in the 32 bit after the multi shift,
11678          * we can't use the preemption timer.
11679          * It's possible that it fits on later vmentries, but checking
11680          * on every vmentry is costly so we just use an hrtimer.
11681          */
11682         if (delta_tsc >> (cpu_preemption_timer_multi + 32))
11683                 return -ERANGE;
11684
11685         vmx->hv_deadline_tsc = tscl + delta_tsc;
11686         vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
11687                         PIN_BASED_VMX_PREEMPTION_TIMER);
11688
11689         return delta_tsc == 0;
11690 }
11691
11692 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
11693 {
11694         struct vcpu_vmx *vmx = to_vmx(vcpu);
11695         vmx->hv_deadline_tsc = -1;
11696         vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
11697                         PIN_BASED_VMX_PREEMPTION_TIMER);
11698 }
11699 #endif
11700
11701 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
11702 {
11703         if (ple_gap)
11704                 shrink_ple_window(vcpu);
11705 }
11706
11707 static void vmx_slot_enable_log_dirty(struct kvm *kvm,
11708                                      struct kvm_memory_slot *slot)
11709 {
11710         kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
11711         kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
11712 }
11713
11714 static void vmx_slot_disable_log_dirty(struct kvm *kvm,
11715                                        struct kvm_memory_slot *slot)
11716 {
11717         kvm_mmu_slot_set_dirty(kvm, slot);
11718 }
11719
11720 static void vmx_flush_log_dirty(struct kvm *kvm)
11721 {
11722         kvm_flush_pml_buffers(kvm);
11723 }
11724
11725 static int vmx_write_pml_buffer(struct kvm_vcpu *vcpu)
11726 {
11727         struct vmcs12 *vmcs12;
11728         struct vcpu_vmx *vmx = to_vmx(vcpu);
11729         gpa_t gpa;
11730         struct page *page = NULL;
11731         u64 *pml_address;
11732
11733         if (is_guest_mode(vcpu)) {
11734                 WARN_ON_ONCE(vmx->nested.pml_full);
11735
11736                 /*
11737                  * Check if PML is enabled for the nested guest.
11738                  * Whether eptp bit 6 is set is already checked
11739                  * as part of A/D emulation.
11740                  */
11741                 vmcs12 = get_vmcs12(vcpu);
11742                 if (!nested_cpu_has_pml(vmcs12))
11743                         return 0;
11744
11745                 if (vmcs12->guest_pml_index >= PML_ENTITY_NUM) {
11746                         vmx->nested.pml_full = true;
11747                         return 1;
11748                 }
11749
11750                 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS) & ~0xFFFull;
11751
11752                 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->pml_address);
11753                 if (is_error_page(page))
11754                         return 0;
11755
11756                 pml_address = kmap(page);
11757                 pml_address[vmcs12->guest_pml_index--] = gpa;
11758                 kunmap(page);
11759                 kvm_release_page_clean(page);
11760         }
11761
11762         return 0;
11763 }
11764
11765 static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
11766                                            struct kvm_memory_slot *memslot,
11767                                            gfn_t offset, unsigned long mask)
11768 {
11769         kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
11770 }
11771
11772 static void __pi_post_block(struct kvm_vcpu *vcpu)
11773 {
11774         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
11775         struct pi_desc old, new;
11776         unsigned int dest;
11777
11778         do {
11779                 old.control = new.control = pi_desc->control;
11780                 WARN(old.nv != POSTED_INTR_WAKEUP_VECTOR,
11781                      "Wakeup handler not enabled while the VCPU is blocked\n");
11782
11783                 dest = cpu_physical_id(vcpu->cpu);
11784
11785                 if (x2apic_enabled())
11786                         new.ndst = dest;
11787                 else
11788                         new.ndst = (dest << 8) & 0xFF00;
11789
11790                 /* set 'NV' to 'notification vector' */
11791                 new.nv = POSTED_INTR_VECTOR;
11792         } while (cmpxchg64(&pi_desc->control, old.control,
11793                            new.control) != old.control);
11794
11795         if (!WARN_ON_ONCE(vcpu->pre_pcpu == -1)) {
11796                 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
11797                 list_del(&vcpu->blocked_vcpu_list);
11798                 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
11799                 vcpu->pre_pcpu = -1;
11800         }
11801 }
11802
11803 /*
11804  * This routine does the following things for vCPU which is going
11805  * to be blocked if VT-d PI is enabled.
11806  * - Store the vCPU to the wakeup list, so when interrupts happen
11807  *   we can find the right vCPU to wake up.
11808  * - Change the Posted-interrupt descriptor as below:
11809  *      'NDST' <-- vcpu->pre_pcpu
11810  *      'NV' <-- POSTED_INTR_WAKEUP_VECTOR
11811  * - If 'ON' is set during this process, which means at least one
11812  *   interrupt is posted for this vCPU, we cannot block it, in
11813  *   this case, return 1, otherwise, return 0.
11814  *
11815  */
11816 static int pi_pre_block(struct kvm_vcpu *vcpu)
11817 {
11818         unsigned int dest;
11819         struct pi_desc old, new;
11820         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
11821
11822         if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
11823                 !irq_remapping_cap(IRQ_POSTING_CAP)  ||
11824                 !kvm_vcpu_apicv_active(vcpu))
11825                 return 0;
11826
11827         WARN_ON(irqs_disabled());
11828         local_irq_disable();
11829         if (!WARN_ON_ONCE(vcpu->pre_pcpu != -1)) {
11830                 vcpu->pre_pcpu = vcpu->cpu;
11831                 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
11832                 list_add_tail(&vcpu->blocked_vcpu_list,
11833                               &per_cpu(blocked_vcpu_on_cpu,
11834                                        vcpu->pre_pcpu));
11835                 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
11836         }
11837
11838         do {
11839                 old.control = new.control = pi_desc->control;
11840
11841                 WARN((pi_desc->sn == 1),
11842                      "Warning: SN field of posted-interrupts "
11843                      "is set before blocking\n");
11844
11845                 /*
11846                  * Since vCPU can be preempted during this process,
11847                  * vcpu->cpu could be different with pre_pcpu, we
11848                  * need to set pre_pcpu as the destination of wakeup
11849                  * notification event, then we can find the right vCPU
11850                  * to wakeup in wakeup handler if interrupts happen
11851                  * when the vCPU is in blocked state.
11852                  */
11853                 dest = cpu_physical_id(vcpu->pre_pcpu);
11854
11855                 if (x2apic_enabled())
11856                         new.ndst = dest;
11857                 else
11858                         new.ndst = (dest << 8) & 0xFF00;
11859
11860                 /* set 'NV' to 'wakeup vector' */
11861                 new.nv = POSTED_INTR_WAKEUP_VECTOR;
11862         } while (cmpxchg64(&pi_desc->control, old.control,
11863                            new.control) != old.control);
11864
11865         /* We should not block the vCPU if an interrupt is posted for it.  */
11866         if (pi_test_on(pi_desc) == 1)
11867                 __pi_post_block(vcpu);
11868
11869         local_irq_enable();
11870         return (vcpu->pre_pcpu == -1);
11871 }
11872
11873 static int vmx_pre_block(struct kvm_vcpu *vcpu)
11874 {
11875         if (pi_pre_block(vcpu))
11876                 return 1;
11877
11878         if (kvm_lapic_hv_timer_in_use(vcpu))
11879                 kvm_lapic_switch_to_sw_timer(vcpu);
11880
11881         return 0;
11882 }
11883
11884 static void pi_post_block(struct kvm_vcpu *vcpu)
11885 {
11886         if (vcpu->pre_pcpu == -1)
11887                 return;
11888
11889         WARN_ON(irqs_disabled());
11890         local_irq_disable();
11891         __pi_post_block(vcpu);
11892         local_irq_enable();
11893 }
11894
11895 static void vmx_post_block(struct kvm_vcpu *vcpu)
11896 {
11897         if (kvm_x86_ops->set_hv_timer)
11898                 kvm_lapic_switch_to_hv_timer(vcpu);
11899
11900         pi_post_block(vcpu);
11901 }
11902
11903 /*
11904  * vmx_update_pi_irte - set IRTE for Posted-Interrupts
11905  *
11906  * @kvm: kvm
11907  * @host_irq: host irq of the interrupt
11908  * @guest_irq: gsi of the interrupt
11909  * @set: set or unset PI
11910  * returns 0 on success, < 0 on failure
11911  */
11912 static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
11913                               uint32_t guest_irq, bool set)
11914 {
11915         struct kvm_kernel_irq_routing_entry *e;
11916         struct kvm_irq_routing_table *irq_rt;
11917         struct kvm_lapic_irq irq;
11918         struct kvm_vcpu *vcpu;
11919         struct vcpu_data vcpu_info;
11920         int idx, ret = 0;
11921
11922         if (!kvm_arch_has_assigned_device(kvm) ||
11923                 !irq_remapping_cap(IRQ_POSTING_CAP) ||
11924                 !kvm_vcpu_apicv_active(kvm->vcpus[0]))
11925                 return 0;
11926
11927         idx = srcu_read_lock(&kvm->irq_srcu);
11928         irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
11929         if (guest_irq >= irq_rt->nr_rt_entries ||
11930             hlist_empty(&irq_rt->map[guest_irq])) {
11931                 pr_warn_once("no route for guest_irq %u/%u (broken user space?)\n",
11932                              guest_irq, irq_rt->nr_rt_entries);
11933                 goto out;
11934         }
11935
11936         hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
11937                 if (e->type != KVM_IRQ_ROUTING_MSI)
11938                         continue;
11939                 /*
11940                  * VT-d PI cannot support posting multicast/broadcast
11941                  * interrupts to a vCPU, we still use interrupt remapping
11942                  * for these kind of interrupts.
11943                  *
11944                  * For lowest-priority interrupts, we only support
11945                  * those with single CPU as the destination, e.g. user
11946                  * configures the interrupts via /proc/irq or uses
11947                  * irqbalance to make the interrupts single-CPU.
11948                  *
11949                  * We will support full lowest-priority interrupt later.
11950                  */
11951
11952                 kvm_set_msi_irq(kvm, e, &irq);
11953                 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
11954                         /*
11955                          * Make sure the IRTE is in remapped mode if
11956                          * we don't handle it in posted mode.
11957                          */
11958                         ret = irq_set_vcpu_affinity(host_irq, NULL);
11959                         if (ret < 0) {
11960                                 printk(KERN_INFO
11961                                    "failed to back to remapped mode, irq: %u\n",
11962                                    host_irq);
11963                                 goto out;
11964                         }
11965
11966                         continue;
11967                 }
11968
11969                 vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
11970                 vcpu_info.vector = irq.vector;
11971
11972                 trace_kvm_pi_irte_update(vcpu->vcpu_id, host_irq, e->gsi,
11973                                 vcpu_info.vector, vcpu_info.pi_desc_addr, set);
11974
11975                 if (set)
11976                         ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
11977                 else
11978                         ret = irq_set_vcpu_affinity(host_irq, NULL);
11979
11980                 if (ret < 0) {
11981                         printk(KERN_INFO "%s: failed to update PI IRTE\n",
11982                                         __func__);
11983                         goto out;
11984                 }
11985         }
11986
11987         ret = 0;
11988 out:
11989         srcu_read_unlock(&kvm->irq_srcu, idx);
11990         return ret;
11991 }
11992
11993 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
11994 {
11995         if (vcpu->arch.mcg_cap & MCG_LMCE_P)
11996                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
11997                         FEATURE_CONTROL_LMCE;
11998         else
11999                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
12000                         ~FEATURE_CONTROL_LMCE;
12001 }
12002
12003 static struct kvm_x86_ops vmx_x86_ops __ro_after_init = {
12004         .cpu_has_kvm_support = cpu_has_kvm_support,
12005         .disabled_by_bios = vmx_disabled_by_bios,
12006         .hardware_setup = hardware_setup,
12007         .hardware_unsetup = hardware_unsetup,
12008         .check_processor_compatibility = vmx_check_processor_compat,
12009         .hardware_enable = hardware_enable,
12010         .hardware_disable = hardware_disable,
12011         .cpu_has_accelerated_tpr = report_flexpriority,
12012         .cpu_has_high_real_mode_segbase = vmx_has_high_real_mode_segbase,
12013
12014         .vcpu_create = vmx_create_vcpu,
12015         .vcpu_free = vmx_free_vcpu,
12016         .vcpu_reset = vmx_vcpu_reset,
12017
12018         .prepare_guest_switch = vmx_save_host_state,
12019         .vcpu_load = vmx_vcpu_load,
12020         .vcpu_put = vmx_vcpu_put,
12021
12022         .update_bp_intercept = update_exception_bitmap,
12023         .get_msr = vmx_get_msr,
12024         .set_msr = vmx_set_msr,
12025         .get_segment_base = vmx_get_segment_base,
12026         .get_segment = vmx_get_segment,
12027         .set_segment = vmx_set_segment,
12028         .get_cpl = vmx_get_cpl,
12029         .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
12030         .decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
12031         .decache_cr3 = vmx_decache_cr3,
12032         .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
12033         .set_cr0 = vmx_set_cr0,
12034         .set_cr3 = vmx_set_cr3,
12035         .set_cr4 = vmx_set_cr4,
12036         .set_efer = vmx_set_efer,
12037         .get_idt = vmx_get_idt,
12038         .set_idt = vmx_set_idt,
12039         .get_gdt = vmx_get_gdt,
12040         .set_gdt = vmx_set_gdt,
12041         .get_dr6 = vmx_get_dr6,
12042         .set_dr6 = vmx_set_dr6,
12043         .set_dr7 = vmx_set_dr7,
12044         .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
12045         .cache_reg = vmx_cache_reg,
12046         .get_rflags = vmx_get_rflags,
12047         .set_rflags = vmx_set_rflags,
12048
12049         .tlb_flush = vmx_flush_tlb,
12050
12051         .run = vmx_vcpu_run,
12052         .handle_exit = vmx_handle_exit,
12053         .skip_emulated_instruction = skip_emulated_instruction,
12054         .set_interrupt_shadow = vmx_set_interrupt_shadow,
12055         .get_interrupt_shadow = vmx_get_interrupt_shadow,
12056         .patch_hypercall = vmx_patch_hypercall,
12057         .set_irq = vmx_inject_irq,
12058         .set_nmi = vmx_inject_nmi,
12059         .queue_exception = vmx_queue_exception,
12060         .cancel_injection = vmx_cancel_injection,
12061         .interrupt_allowed = vmx_interrupt_allowed,
12062         .nmi_allowed = vmx_nmi_allowed,
12063         .get_nmi_mask = vmx_get_nmi_mask,
12064         .set_nmi_mask = vmx_set_nmi_mask,
12065         .enable_nmi_window = enable_nmi_window,
12066         .enable_irq_window = enable_irq_window,
12067         .update_cr8_intercept = update_cr8_intercept,
12068         .set_virtual_x2apic_mode = vmx_set_virtual_x2apic_mode,
12069         .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
12070         .get_enable_apicv = vmx_get_enable_apicv,
12071         .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
12072         .load_eoi_exitmap = vmx_load_eoi_exitmap,
12073         .apicv_post_state_restore = vmx_apicv_post_state_restore,
12074         .hwapic_irr_update = vmx_hwapic_irr_update,
12075         .hwapic_isr_update = vmx_hwapic_isr_update,
12076         .sync_pir_to_irr = vmx_sync_pir_to_irr,
12077         .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
12078
12079         .set_tss_addr = vmx_set_tss_addr,
12080         .get_tdp_level = get_ept_level,
12081         .get_mt_mask = vmx_get_mt_mask,
12082
12083         .get_exit_info = vmx_get_exit_info,
12084
12085         .get_lpage_level = vmx_get_lpage_level,
12086
12087         .cpuid_update = vmx_cpuid_update,
12088
12089         .rdtscp_supported = vmx_rdtscp_supported,
12090         .invpcid_supported = vmx_invpcid_supported,
12091
12092         .set_supported_cpuid = vmx_set_supported_cpuid,
12093
12094         .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
12095
12096         .write_tsc_offset = vmx_write_tsc_offset,
12097
12098         .set_tdp_cr3 = vmx_set_cr3,
12099
12100         .check_intercept = vmx_check_intercept,
12101         .handle_external_intr = vmx_handle_external_intr,
12102         .mpx_supported = vmx_mpx_supported,
12103         .xsaves_supported = vmx_xsaves_supported,
12104
12105         .check_nested_events = vmx_check_nested_events,
12106
12107         .sched_in = vmx_sched_in,
12108
12109         .slot_enable_log_dirty = vmx_slot_enable_log_dirty,
12110         .slot_disable_log_dirty = vmx_slot_disable_log_dirty,
12111         .flush_log_dirty = vmx_flush_log_dirty,
12112         .enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
12113         .write_log_dirty = vmx_write_pml_buffer,
12114
12115         .pre_block = vmx_pre_block,
12116         .post_block = vmx_post_block,
12117
12118         .pmu_ops = &intel_pmu_ops,
12119
12120         .update_pi_irte = vmx_update_pi_irte,
12121
12122 #ifdef CONFIG_X86_64
12123         .set_hv_timer = vmx_set_hv_timer,
12124         .cancel_hv_timer = vmx_cancel_hv_timer,
12125 #endif
12126
12127         .setup_mce = vmx_setup_mce,
12128 };
12129
12130 static int __init vmx_init(void)
12131 {
12132         int r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
12133                      __alignof__(struct vcpu_vmx), THIS_MODULE);
12134         if (r)
12135                 return r;
12136
12137 #ifdef CONFIG_KEXEC_CORE
12138         rcu_assign_pointer(crash_vmclear_loaded_vmcss,
12139                            crash_vmclear_local_loaded_vmcss);
12140 #endif
12141
12142         return 0;
12143 }
12144
12145 static void __exit vmx_exit(void)
12146 {
12147 #ifdef CONFIG_KEXEC_CORE
12148         RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
12149         synchronize_rcu();
12150 #endif
12151
12152         kvm_exit();
12153 }
12154
12155 module_init(vmx_init)
12156 module_exit(vmx_exit)