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