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