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