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