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