OSDN Git Service

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