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