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