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