Merge branch 'linux-3.10.y' of git://git.kernel.org/pub/scm/linux/kernel/git/stable...
[firefly-linux-kernel-4.4.55.git] / arch / x86 / kvm / vmx.c
1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * This module enables machines with Intel VT-x extensions to run virtual
5  * machines without emulation or binary translation.
6  *
7  * Copyright (C) 2006 Qumranet, Inc.
8  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
9  *
10  * Authors:
11  *   Avi Kivity   <avi@qumranet.com>
12  *   Yaniv Kamay  <yaniv@qumranet.com>
13  *
14  * This work is licensed under the terms of the GNU GPL, version 2.  See
15  * the COPYING file in the top-level directory.
16  *
17  */
18
19 #include "irq.h"
20 #include "mmu.h"
21 #include "cpuid.h"
22
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/ftrace_event.h>
32 #include <linux/slab.h>
33 #include <linux/tboot.h>
34 #include "kvm_cache_regs.h"
35 #include "x86.h"
36
37 #include <asm/io.h>
38 #include <asm/desc.h>
39 #include <asm/vmx.h>
40 #include <asm/virtext.h>
41 #include <asm/mce.h>
42 #include <asm/i387.h>
43 #include <asm/xcr.h>
44 #include <asm/perf_event.h>
45 #include <asm/kexec.h>
46
47 #include "trace.h"
48
49 #define __ex(x) __kvm_handle_fault_on_reboot(x)
50 #define __ex_clear(x, reg) \
51         ____kvm_handle_fault_on_reboot(x, "xor " reg " , " reg)
52
53 MODULE_AUTHOR("Qumranet");
54 MODULE_LICENSE("GPL");
55
56 static const struct x86_cpu_id vmx_cpu_id[] = {
57         X86_FEATURE_MATCH(X86_FEATURE_VMX),
58         {}
59 };
60 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
61
62 static bool __read_mostly enable_vpid = 1;
63 module_param_named(vpid, enable_vpid, bool, 0444);
64
65 static bool __read_mostly flexpriority_enabled = 1;
66 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
67
68 static bool __read_mostly enable_ept = 1;
69 module_param_named(ept, enable_ept, bool, S_IRUGO);
70
71 static bool __read_mostly enable_unrestricted_guest = 1;
72 module_param_named(unrestricted_guest,
73                         enable_unrestricted_guest, bool, S_IRUGO);
74
75 static bool __read_mostly enable_ept_ad_bits = 1;
76 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
77
78 static bool __read_mostly emulate_invalid_guest_state = true;
79 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
80
81 static bool __read_mostly vmm_exclusive = 1;
82 module_param(vmm_exclusive, bool, S_IRUGO);
83
84 static bool __read_mostly fasteoi = 1;
85 module_param(fasteoi, bool, S_IRUGO);
86
87 static bool __read_mostly enable_apicv = 1;
88 module_param(enable_apicv, bool, S_IRUGO);
89
90 static bool __read_mostly enable_shadow_vmcs = 1;
91 module_param_named(enable_shadow_vmcs, enable_shadow_vmcs, bool, S_IRUGO);
92 /*
93  * If nested=1, nested virtualization is supported, i.e., guests may use
94  * VMX and be a hypervisor for its own guests. If nested=0, guests may not
95  * use VMX instructions.
96  */
97 static bool __read_mostly nested = 0;
98 module_param(nested, bool, S_IRUGO);
99
100 #define KVM_GUEST_CR0_MASK (X86_CR0_NW | X86_CR0_CD)
101 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST (X86_CR0_WP | X86_CR0_NE)
102 #define KVM_VM_CR0_ALWAYS_ON                                            \
103         (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE)
104 #define KVM_CR4_GUEST_OWNED_BITS                                      \
105         (X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR      \
106          | X86_CR4_OSXMMEXCPT)
107
108 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
109 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
110
111 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
112
113 /*
114  * These 2 parameters are used to config the controls for Pause-Loop Exiting:
115  * ple_gap:    upper bound on the amount of time between two successive
116  *             executions of PAUSE in a loop. Also indicate if ple enabled.
117  *             According to test, this time is usually smaller than 128 cycles.
118  * ple_window: upper bound on the amount of time a guest is allowed to execute
119  *             in a PAUSE loop. Tests indicate that most spinlocks are held for
120  *             less than 2^12 cycles
121  * Time is measured based on a counter that runs at the same rate as the TSC,
122  * refer SDM volume 3b section 21.6.13 & 22.1.3.
123  */
124 #define KVM_VMX_DEFAULT_PLE_GAP    128
125 #define KVM_VMX_DEFAULT_PLE_WINDOW 4096
126 static int ple_gap = KVM_VMX_DEFAULT_PLE_GAP;
127 module_param(ple_gap, int, S_IRUGO);
128
129 static int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
130 module_param(ple_window, int, S_IRUGO);
131
132 extern const ulong vmx_return;
133
134 #define NR_AUTOLOAD_MSRS 8
135 #define VMCS02_POOL_SIZE 1
136
137 struct vmcs {
138         u32 revision_id;
139         u32 abort;
140         char data[0];
141 };
142
143 /*
144  * Track a VMCS that may be loaded on a certain CPU. If it is (cpu!=-1), also
145  * remember whether it was VMLAUNCHed, and maintain a linked list of all VMCSs
146  * loaded on this CPU (so we can clear them if the CPU goes down).
147  */
148 struct loaded_vmcs {
149         struct vmcs *vmcs;
150         int cpu;
151         int launched;
152         struct list_head loaded_vmcss_on_cpu_link;
153 };
154
155 struct shared_msr_entry {
156         unsigned index;
157         u64 data;
158         u64 mask;
159 };
160
161 /*
162  * struct vmcs12 describes the state that our guest hypervisor (L1) keeps for a
163  * single nested guest (L2), hence the name vmcs12. Any VMX implementation has
164  * a VMCS structure, and vmcs12 is our emulated VMX's VMCS. This structure is
165  * stored in guest memory specified by VMPTRLD, but is opaque to the guest,
166  * which must access it using VMREAD/VMWRITE/VMCLEAR instructions.
167  * More than one of these structures may exist, if L1 runs multiple L2 guests.
168  * nested_vmx_run() will use the data here to build a vmcs02: a VMCS for the
169  * underlying hardware which will be used to run L2.
170  * This structure is packed to ensure that its layout is identical across
171  * machines (necessary for live migration).
172  * If there are changes in this struct, VMCS12_REVISION must be changed.
173  */
174 typedef u64 natural_width;
175 struct __packed vmcs12 {
176         /* According to the Intel spec, a VMCS region must start with the
177          * following two fields. Then follow implementation-specific data.
178          */
179         u32 revision_id;
180         u32 abort;
181
182         u32 launch_state; /* set to 0 by VMCLEAR, to 1 by VMLAUNCH */
183         u32 padding[7]; /* room for future expansion */
184
185         u64 io_bitmap_a;
186         u64 io_bitmap_b;
187         u64 msr_bitmap;
188         u64 vm_exit_msr_store_addr;
189         u64 vm_exit_msr_load_addr;
190         u64 vm_entry_msr_load_addr;
191         u64 tsc_offset;
192         u64 virtual_apic_page_addr;
193         u64 apic_access_addr;
194         u64 ept_pointer;
195         u64 guest_physical_address;
196         u64 vmcs_link_pointer;
197         u64 guest_ia32_debugctl;
198         u64 guest_ia32_pat;
199         u64 guest_ia32_efer;
200         u64 guest_ia32_perf_global_ctrl;
201         u64 guest_pdptr0;
202         u64 guest_pdptr1;
203         u64 guest_pdptr2;
204         u64 guest_pdptr3;
205         u64 host_ia32_pat;
206         u64 host_ia32_efer;
207         u64 host_ia32_perf_global_ctrl;
208         u64 padding64[8]; /* room for future expansion */
209         /*
210          * To allow migration of L1 (complete with its L2 guests) between
211          * machines of different natural widths (32 or 64 bit), we cannot have
212          * unsigned long fields with no explict size. We use u64 (aliased
213          * natural_width) instead. Luckily, x86 is little-endian.
214          */
215         natural_width cr0_guest_host_mask;
216         natural_width cr4_guest_host_mask;
217         natural_width cr0_read_shadow;
218         natural_width cr4_read_shadow;
219         natural_width cr3_target_value0;
220         natural_width cr3_target_value1;
221         natural_width cr3_target_value2;
222         natural_width cr3_target_value3;
223         natural_width exit_qualification;
224         natural_width guest_linear_address;
225         natural_width guest_cr0;
226         natural_width guest_cr3;
227         natural_width guest_cr4;
228         natural_width guest_es_base;
229         natural_width guest_cs_base;
230         natural_width guest_ss_base;
231         natural_width guest_ds_base;
232         natural_width guest_fs_base;
233         natural_width guest_gs_base;
234         natural_width guest_ldtr_base;
235         natural_width guest_tr_base;
236         natural_width guest_gdtr_base;
237         natural_width guest_idtr_base;
238         natural_width guest_dr7;
239         natural_width guest_rsp;
240         natural_width guest_rip;
241         natural_width guest_rflags;
242         natural_width guest_pending_dbg_exceptions;
243         natural_width guest_sysenter_esp;
244         natural_width guest_sysenter_eip;
245         natural_width host_cr0;
246         natural_width host_cr3;
247         natural_width host_cr4;
248         natural_width host_fs_base;
249         natural_width host_gs_base;
250         natural_width host_tr_base;
251         natural_width host_gdtr_base;
252         natural_width host_idtr_base;
253         natural_width host_ia32_sysenter_esp;
254         natural_width host_ia32_sysenter_eip;
255         natural_width host_rsp;
256         natural_width host_rip;
257         natural_width paddingl[8]; /* room for future expansion */
258         u32 pin_based_vm_exec_control;
259         u32 cpu_based_vm_exec_control;
260         u32 exception_bitmap;
261         u32 page_fault_error_code_mask;
262         u32 page_fault_error_code_match;
263         u32 cr3_target_count;
264         u32 vm_exit_controls;
265         u32 vm_exit_msr_store_count;
266         u32 vm_exit_msr_load_count;
267         u32 vm_entry_controls;
268         u32 vm_entry_msr_load_count;
269         u32 vm_entry_intr_info_field;
270         u32 vm_entry_exception_error_code;
271         u32 vm_entry_instruction_len;
272         u32 tpr_threshold;
273         u32 secondary_vm_exec_control;
274         u32 vm_instruction_error;
275         u32 vm_exit_reason;
276         u32 vm_exit_intr_info;
277         u32 vm_exit_intr_error_code;
278         u32 idt_vectoring_info_field;
279         u32 idt_vectoring_error_code;
280         u32 vm_exit_instruction_len;
281         u32 vmx_instruction_info;
282         u32 guest_es_limit;
283         u32 guest_cs_limit;
284         u32 guest_ss_limit;
285         u32 guest_ds_limit;
286         u32 guest_fs_limit;
287         u32 guest_gs_limit;
288         u32 guest_ldtr_limit;
289         u32 guest_tr_limit;
290         u32 guest_gdtr_limit;
291         u32 guest_idtr_limit;
292         u32 guest_es_ar_bytes;
293         u32 guest_cs_ar_bytes;
294         u32 guest_ss_ar_bytes;
295         u32 guest_ds_ar_bytes;
296         u32 guest_fs_ar_bytes;
297         u32 guest_gs_ar_bytes;
298         u32 guest_ldtr_ar_bytes;
299         u32 guest_tr_ar_bytes;
300         u32 guest_interruptibility_info;
301         u32 guest_activity_state;
302         u32 guest_sysenter_cs;
303         u32 host_ia32_sysenter_cs;
304         u32 vmx_preemption_timer_value;
305         u32 padding32[7]; /* room for future expansion */
306         u16 virtual_processor_id;
307         u16 guest_es_selector;
308         u16 guest_cs_selector;
309         u16 guest_ss_selector;
310         u16 guest_ds_selector;
311         u16 guest_fs_selector;
312         u16 guest_gs_selector;
313         u16 guest_ldtr_selector;
314         u16 guest_tr_selector;
315         u16 host_es_selector;
316         u16 host_cs_selector;
317         u16 host_ss_selector;
318         u16 host_ds_selector;
319         u16 host_fs_selector;
320         u16 host_gs_selector;
321         u16 host_tr_selector;
322 };
323
324 /*
325  * VMCS12_REVISION is an arbitrary id that should be changed if the content or
326  * layout of struct vmcs12 is changed. MSR_IA32_VMX_BASIC returns this id, and
327  * VMPTRLD verifies that the VMCS region that L1 is loading contains this id.
328  */
329 #define VMCS12_REVISION 0x11e57ed0
330
331 /*
332  * VMCS12_SIZE is the number of bytes L1 should allocate for the VMXON region
333  * and any VMCS region. Although only sizeof(struct vmcs12) are used by the
334  * current implementation, 4K are reserved to avoid future complications.
335  */
336 #define VMCS12_SIZE 0x1000
337
338 /* Used to remember the last vmcs02 used for some recently used vmcs12s */
339 struct vmcs02_list {
340         struct list_head list;
341         gpa_t vmptr;
342         struct loaded_vmcs vmcs02;
343 };
344
345 /*
346  * The nested_vmx structure is part of vcpu_vmx, and holds information we need
347  * for correct emulation of VMX (i.e., nested VMX) on this vcpu.
348  */
349 struct nested_vmx {
350         /* Has the level1 guest done vmxon? */
351         bool vmxon;
352
353         /* The guest-physical address of the current VMCS L1 keeps for L2 */
354         gpa_t current_vmptr;
355         /* The host-usable pointer to the above */
356         struct page *current_vmcs12_page;
357         struct vmcs12 *current_vmcs12;
358         struct vmcs *current_shadow_vmcs;
359         /*
360          * Indicates if the shadow vmcs must be updated with the
361          * data hold by vmcs12
362          */
363         bool sync_shadow_vmcs;
364
365         /* vmcs02_list cache of VMCSs recently used to run L2 guests */
366         struct list_head vmcs02_pool;
367         int vmcs02_num;
368         u64 vmcs01_tsc_offset;
369         /* L2 must run next, and mustn't decide to exit to L1. */
370         bool nested_run_pending;
371         /*
372          * Guest pages referred to in vmcs02 with host-physical pointers, so
373          * we must keep them pinned while L2 runs.
374          */
375         struct page *apic_access_page;
376 };
377
378 #define POSTED_INTR_ON  0
379 /* Posted-Interrupt Descriptor */
380 struct pi_desc {
381         u32 pir[8];     /* Posted interrupt requested */
382         u32 control;    /* bit 0 of control is outstanding notification bit */
383         u32 rsvd[7];
384 } __aligned(64);
385
386 static bool pi_test_and_set_on(struct pi_desc *pi_desc)
387 {
388         return test_and_set_bit(POSTED_INTR_ON,
389                         (unsigned long *)&pi_desc->control);
390 }
391
392 static bool pi_test_and_clear_on(struct pi_desc *pi_desc)
393 {
394         return test_and_clear_bit(POSTED_INTR_ON,
395                         (unsigned long *)&pi_desc->control);
396 }
397
398 static int pi_test_and_set_pir(int vector, struct pi_desc *pi_desc)
399 {
400         return test_and_set_bit(vector, (unsigned long *)pi_desc->pir);
401 }
402
403 struct vcpu_vmx {
404         struct kvm_vcpu       vcpu;
405         unsigned long         host_rsp;
406         u8                    fail;
407         u8                    cpl;
408         bool                  nmi_known_unmasked;
409         u32                   exit_intr_info;
410         u32                   idt_vectoring_info;
411         ulong                 rflags;
412         struct shared_msr_entry *guest_msrs;
413         int                   nmsrs;
414         int                   save_nmsrs;
415         unsigned long         host_idt_base;
416 #ifdef CONFIG_X86_64
417         u64                   msr_host_kernel_gs_base;
418         u64                   msr_guest_kernel_gs_base;
419 #endif
420         /*
421          * loaded_vmcs points to the VMCS currently used in this vcpu. For a
422          * non-nested (L1) guest, it always points to vmcs01. For a nested
423          * guest (L2), it points to a different VMCS.
424          */
425         struct loaded_vmcs    vmcs01;
426         struct loaded_vmcs   *loaded_vmcs;
427         bool                  __launched; /* temporary, used in vmx_vcpu_run */
428         struct msr_autoload {
429                 unsigned nr;
430                 struct vmx_msr_entry guest[NR_AUTOLOAD_MSRS];
431                 struct vmx_msr_entry host[NR_AUTOLOAD_MSRS];
432         } msr_autoload;
433         struct {
434                 int           loaded;
435                 u16           fs_sel, gs_sel, ldt_sel;
436 #ifdef CONFIG_X86_64
437                 u16           ds_sel, es_sel;
438 #endif
439                 int           gs_ldt_reload_needed;
440                 int           fs_reload_needed;
441                 unsigned long vmcs_host_cr4;    /* May not match real cr4 */
442         } host_state;
443         struct {
444                 int vm86_active;
445                 ulong save_rflags;
446                 struct kvm_segment segs[8];
447         } rmode;
448         struct {
449                 u32 bitmask; /* 4 bits per segment (1 bit per field) */
450                 struct kvm_save_segment {
451                         u16 selector;
452                         unsigned long base;
453                         u32 limit;
454                         u32 ar;
455                 } seg[8];
456         } segment_cache;
457         int vpid;
458         bool emulation_required;
459
460         /* Support for vnmi-less CPUs */
461         int soft_vnmi_blocked;
462         ktime_t entry_time;
463         s64 vnmi_blocked_time;
464         u32 exit_reason;
465
466         bool rdtscp_enabled;
467
468         /* Posted interrupt descriptor */
469         struct pi_desc pi_desc;
470
471         /* Support for a guest hypervisor (nested VMX) */
472         struct nested_vmx nested;
473 };
474
475 enum segment_cache_field {
476         SEG_FIELD_SEL = 0,
477         SEG_FIELD_BASE = 1,
478         SEG_FIELD_LIMIT = 2,
479         SEG_FIELD_AR = 3,
480
481         SEG_FIELD_NR = 4
482 };
483
484 static inline struct vcpu_vmx *to_vmx(struct kvm_vcpu *vcpu)
485 {
486         return container_of(vcpu, struct vcpu_vmx, vcpu);
487 }
488
489 #define VMCS12_OFFSET(x) offsetof(struct vmcs12, x)
490 #define FIELD(number, name)     [number] = VMCS12_OFFSET(name)
491 #define FIELD64(number, name)   [number] = VMCS12_OFFSET(name), \
492                                 [number##_HIGH] = VMCS12_OFFSET(name)+4
493
494
495 static const unsigned long shadow_read_only_fields[] = {
496         /*
497          * We do NOT shadow fields that are modified when L0
498          * traps and emulates any vmx instruction (e.g. VMPTRLD,
499          * VMXON...) executed by L1.
500          * For example, VM_INSTRUCTION_ERROR is read
501          * by L1 if a vmx instruction fails (part of the error path).
502          * Note the code assumes this logic. If for some reason
503          * we start shadowing these fields then we need to
504          * force a shadow sync when L0 emulates vmx instructions
505          * (e.g. force a sync if VM_INSTRUCTION_ERROR is modified
506          * by nested_vmx_failValid)
507          */
508         VM_EXIT_REASON,
509         VM_EXIT_INTR_INFO,
510         VM_EXIT_INSTRUCTION_LEN,
511         IDT_VECTORING_INFO_FIELD,
512         IDT_VECTORING_ERROR_CODE,
513         VM_EXIT_INTR_ERROR_CODE,
514         EXIT_QUALIFICATION,
515         GUEST_LINEAR_ADDRESS,
516         GUEST_PHYSICAL_ADDRESS
517 };
518 static const int max_shadow_read_only_fields =
519         ARRAY_SIZE(shadow_read_only_fields);
520
521 static const unsigned long shadow_read_write_fields[] = {
522         GUEST_RIP,
523         GUEST_RSP,
524         GUEST_CR0,
525         GUEST_CR3,
526         GUEST_CR4,
527         GUEST_INTERRUPTIBILITY_INFO,
528         GUEST_RFLAGS,
529         GUEST_CS_SELECTOR,
530         GUEST_CS_AR_BYTES,
531         GUEST_CS_LIMIT,
532         GUEST_CS_BASE,
533         GUEST_ES_BASE,
534         CR0_GUEST_HOST_MASK,
535         CR0_READ_SHADOW,
536         CR4_READ_SHADOW,
537         TSC_OFFSET,
538         EXCEPTION_BITMAP,
539         CPU_BASED_VM_EXEC_CONTROL,
540         VM_ENTRY_EXCEPTION_ERROR_CODE,
541         VM_ENTRY_INTR_INFO_FIELD,
542         VM_ENTRY_INSTRUCTION_LEN,
543         VM_ENTRY_EXCEPTION_ERROR_CODE,
544         HOST_FS_BASE,
545         HOST_GS_BASE,
546         HOST_FS_SELECTOR,
547         HOST_GS_SELECTOR
548 };
549 static const int max_shadow_read_write_fields =
550         ARRAY_SIZE(shadow_read_write_fields);
551
552 static const unsigned short vmcs_field_to_offset_table[] = {
553         FIELD(VIRTUAL_PROCESSOR_ID, virtual_processor_id),
554         FIELD(GUEST_ES_SELECTOR, guest_es_selector),
555         FIELD(GUEST_CS_SELECTOR, guest_cs_selector),
556         FIELD(GUEST_SS_SELECTOR, guest_ss_selector),
557         FIELD(GUEST_DS_SELECTOR, guest_ds_selector),
558         FIELD(GUEST_FS_SELECTOR, guest_fs_selector),
559         FIELD(GUEST_GS_SELECTOR, guest_gs_selector),
560         FIELD(GUEST_LDTR_SELECTOR, guest_ldtr_selector),
561         FIELD(GUEST_TR_SELECTOR, guest_tr_selector),
562         FIELD(HOST_ES_SELECTOR, host_es_selector),
563         FIELD(HOST_CS_SELECTOR, host_cs_selector),
564         FIELD(HOST_SS_SELECTOR, host_ss_selector),
565         FIELD(HOST_DS_SELECTOR, host_ds_selector),
566         FIELD(HOST_FS_SELECTOR, host_fs_selector),
567         FIELD(HOST_GS_SELECTOR, host_gs_selector),
568         FIELD(HOST_TR_SELECTOR, host_tr_selector),
569         FIELD64(IO_BITMAP_A, io_bitmap_a),
570         FIELD64(IO_BITMAP_B, io_bitmap_b),
571         FIELD64(MSR_BITMAP, msr_bitmap),
572         FIELD64(VM_EXIT_MSR_STORE_ADDR, vm_exit_msr_store_addr),
573         FIELD64(VM_EXIT_MSR_LOAD_ADDR, vm_exit_msr_load_addr),
574         FIELD64(VM_ENTRY_MSR_LOAD_ADDR, vm_entry_msr_load_addr),
575         FIELD64(TSC_OFFSET, tsc_offset),
576         FIELD64(VIRTUAL_APIC_PAGE_ADDR, virtual_apic_page_addr),
577         FIELD64(APIC_ACCESS_ADDR, apic_access_addr),
578         FIELD64(EPT_POINTER, ept_pointer),
579         FIELD64(GUEST_PHYSICAL_ADDRESS, guest_physical_address),
580         FIELD64(VMCS_LINK_POINTER, vmcs_link_pointer),
581         FIELD64(GUEST_IA32_DEBUGCTL, guest_ia32_debugctl),
582         FIELD64(GUEST_IA32_PAT, guest_ia32_pat),
583         FIELD64(GUEST_IA32_EFER, guest_ia32_efer),
584         FIELD64(GUEST_IA32_PERF_GLOBAL_CTRL, guest_ia32_perf_global_ctrl),
585         FIELD64(GUEST_PDPTR0, guest_pdptr0),
586         FIELD64(GUEST_PDPTR1, guest_pdptr1),
587         FIELD64(GUEST_PDPTR2, guest_pdptr2),
588         FIELD64(GUEST_PDPTR3, guest_pdptr3),
589         FIELD64(HOST_IA32_PAT, host_ia32_pat),
590         FIELD64(HOST_IA32_EFER, host_ia32_efer),
591         FIELD64(HOST_IA32_PERF_GLOBAL_CTRL, host_ia32_perf_global_ctrl),
592         FIELD(PIN_BASED_VM_EXEC_CONTROL, pin_based_vm_exec_control),
593         FIELD(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control),
594         FIELD(EXCEPTION_BITMAP, exception_bitmap),
595         FIELD(PAGE_FAULT_ERROR_CODE_MASK, page_fault_error_code_mask),
596         FIELD(PAGE_FAULT_ERROR_CODE_MATCH, page_fault_error_code_match),
597         FIELD(CR3_TARGET_COUNT, cr3_target_count),
598         FIELD(VM_EXIT_CONTROLS, vm_exit_controls),
599         FIELD(VM_EXIT_MSR_STORE_COUNT, vm_exit_msr_store_count),
600         FIELD(VM_EXIT_MSR_LOAD_COUNT, vm_exit_msr_load_count),
601         FIELD(VM_ENTRY_CONTROLS, vm_entry_controls),
602         FIELD(VM_ENTRY_MSR_LOAD_COUNT, vm_entry_msr_load_count),
603         FIELD(VM_ENTRY_INTR_INFO_FIELD, vm_entry_intr_info_field),
604         FIELD(VM_ENTRY_EXCEPTION_ERROR_CODE, vm_entry_exception_error_code),
605         FIELD(VM_ENTRY_INSTRUCTION_LEN, vm_entry_instruction_len),
606         FIELD(TPR_THRESHOLD, tpr_threshold),
607         FIELD(SECONDARY_VM_EXEC_CONTROL, secondary_vm_exec_control),
608         FIELD(VM_INSTRUCTION_ERROR, vm_instruction_error),
609         FIELD(VM_EXIT_REASON, vm_exit_reason),
610         FIELD(VM_EXIT_INTR_INFO, vm_exit_intr_info),
611         FIELD(VM_EXIT_INTR_ERROR_CODE, vm_exit_intr_error_code),
612         FIELD(IDT_VECTORING_INFO_FIELD, idt_vectoring_info_field),
613         FIELD(IDT_VECTORING_ERROR_CODE, idt_vectoring_error_code),
614         FIELD(VM_EXIT_INSTRUCTION_LEN, vm_exit_instruction_len),
615         FIELD(VMX_INSTRUCTION_INFO, vmx_instruction_info),
616         FIELD(GUEST_ES_LIMIT, guest_es_limit),
617         FIELD(GUEST_CS_LIMIT, guest_cs_limit),
618         FIELD(GUEST_SS_LIMIT, guest_ss_limit),
619         FIELD(GUEST_DS_LIMIT, guest_ds_limit),
620         FIELD(GUEST_FS_LIMIT, guest_fs_limit),
621         FIELD(GUEST_GS_LIMIT, guest_gs_limit),
622         FIELD(GUEST_LDTR_LIMIT, guest_ldtr_limit),
623         FIELD(GUEST_TR_LIMIT, guest_tr_limit),
624         FIELD(GUEST_GDTR_LIMIT, guest_gdtr_limit),
625         FIELD(GUEST_IDTR_LIMIT, guest_idtr_limit),
626         FIELD(GUEST_ES_AR_BYTES, guest_es_ar_bytes),
627         FIELD(GUEST_CS_AR_BYTES, guest_cs_ar_bytes),
628         FIELD(GUEST_SS_AR_BYTES, guest_ss_ar_bytes),
629         FIELD(GUEST_DS_AR_BYTES, guest_ds_ar_bytes),
630         FIELD(GUEST_FS_AR_BYTES, guest_fs_ar_bytes),
631         FIELD(GUEST_GS_AR_BYTES, guest_gs_ar_bytes),
632         FIELD(GUEST_LDTR_AR_BYTES, guest_ldtr_ar_bytes),
633         FIELD(GUEST_TR_AR_BYTES, guest_tr_ar_bytes),
634         FIELD(GUEST_INTERRUPTIBILITY_INFO, guest_interruptibility_info),
635         FIELD(GUEST_ACTIVITY_STATE, guest_activity_state),
636         FIELD(GUEST_SYSENTER_CS, guest_sysenter_cs),
637         FIELD(HOST_IA32_SYSENTER_CS, host_ia32_sysenter_cs),
638         FIELD(VMX_PREEMPTION_TIMER_VALUE, vmx_preemption_timer_value),
639         FIELD(CR0_GUEST_HOST_MASK, cr0_guest_host_mask),
640         FIELD(CR4_GUEST_HOST_MASK, cr4_guest_host_mask),
641         FIELD(CR0_READ_SHADOW, cr0_read_shadow),
642         FIELD(CR4_READ_SHADOW, cr4_read_shadow),
643         FIELD(CR3_TARGET_VALUE0, cr3_target_value0),
644         FIELD(CR3_TARGET_VALUE1, cr3_target_value1),
645         FIELD(CR3_TARGET_VALUE2, cr3_target_value2),
646         FIELD(CR3_TARGET_VALUE3, cr3_target_value3),
647         FIELD(EXIT_QUALIFICATION, exit_qualification),
648         FIELD(GUEST_LINEAR_ADDRESS, guest_linear_address),
649         FIELD(GUEST_CR0, guest_cr0),
650         FIELD(GUEST_CR3, guest_cr3),
651         FIELD(GUEST_CR4, guest_cr4),
652         FIELD(GUEST_ES_BASE, guest_es_base),
653         FIELD(GUEST_CS_BASE, guest_cs_base),
654         FIELD(GUEST_SS_BASE, guest_ss_base),
655         FIELD(GUEST_DS_BASE, guest_ds_base),
656         FIELD(GUEST_FS_BASE, guest_fs_base),
657         FIELD(GUEST_GS_BASE, guest_gs_base),
658         FIELD(GUEST_LDTR_BASE, guest_ldtr_base),
659         FIELD(GUEST_TR_BASE, guest_tr_base),
660         FIELD(GUEST_GDTR_BASE, guest_gdtr_base),
661         FIELD(GUEST_IDTR_BASE, guest_idtr_base),
662         FIELD(GUEST_DR7, guest_dr7),
663         FIELD(GUEST_RSP, guest_rsp),
664         FIELD(GUEST_RIP, guest_rip),
665         FIELD(GUEST_RFLAGS, guest_rflags),
666         FIELD(GUEST_PENDING_DBG_EXCEPTIONS, guest_pending_dbg_exceptions),
667         FIELD(GUEST_SYSENTER_ESP, guest_sysenter_esp),
668         FIELD(GUEST_SYSENTER_EIP, guest_sysenter_eip),
669         FIELD(HOST_CR0, host_cr0),
670         FIELD(HOST_CR3, host_cr3),
671         FIELD(HOST_CR4, host_cr4),
672         FIELD(HOST_FS_BASE, host_fs_base),
673         FIELD(HOST_GS_BASE, host_gs_base),
674         FIELD(HOST_TR_BASE, host_tr_base),
675         FIELD(HOST_GDTR_BASE, host_gdtr_base),
676         FIELD(HOST_IDTR_BASE, host_idtr_base),
677         FIELD(HOST_IA32_SYSENTER_ESP, host_ia32_sysenter_esp),
678         FIELD(HOST_IA32_SYSENTER_EIP, host_ia32_sysenter_eip),
679         FIELD(HOST_RSP, host_rsp),
680         FIELD(HOST_RIP, host_rip),
681 };
682 static const int max_vmcs_field = ARRAY_SIZE(vmcs_field_to_offset_table);
683
684 static inline short vmcs_field_to_offset(unsigned long field)
685 {
686         if (field >= max_vmcs_field || vmcs_field_to_offset_table[field] == 0)
687                 return -1;
688         return vmcs_field_to_offset_table[field];
689 }
690
691 static inline struct vmcs12 *get_vmcs12(struct kvm_vcpu *vcpu)
692 {
693         return to_vmx(vcpu)->nested.current_vmcs12;
694 }
695
696 static struct page *nested_get_page(struct kvm_vcpu *vcpu, gpa_t addr)
697 {
698         struct page *page = gfn_to_page(vcpu->kvm, addr >> PAGE_SHIFT);
699         if (is_error_page(page))
700                 return NULL;
701
702         return page;
703 }
704
705 static void nested_release_page(struct page *page)
706 {
707         kvm_release_page_dirty(page);
708 }
709
710 static void nested_release_page_clean(struct page *page)
711 {
712         kvm_release_page_clean(page);
713 }
714
715 static u64 construct_eptp(unsigned long root_hpa);
716 static void kvm_cpu_vmxon(u64 addr);
717 static void kvm_cpu_vmxoff(void);
718 static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3);
719 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr);
720 static void vmx_set_segment(struct kvm_vcpu *vcpu,
721                             struct kvm_segment *var, int seg);
722 static void vmx_get_segment(struct kvm_vcpu *vcpu,
723                             struct kvm_segment *var, int seg);
724 static bool guest_state_valid(struct kvm_vcpu *vcpu);
725 static u32 vmx_segment_access_rights(struct kvm_segment *var);
726 static void vmx_sync_pir_to_irr_dummy(struct kvm_vcpu *vcpu);
727 static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx);
728 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx);
729
730 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
731 static DEFINE_PER_CPU(struct vmcs *, current_vmcs);
732 /*
733  * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
734  * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
735  */
736 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
737 static DEFINE_PER_CPU(struct desc_ptr, host_gdt);
738
739 static unsigned long *vmx_io_bitmap_a;
740 static unsigned long *vmx_io_bitmap_b;
741 static unsigned long *vmx_msr_bitmap_legacy;
742 static unsigned long *vmx_msr_bitmap_longmode;
743 static unsigned long *vmx_msr_bitmap_legacy_x2apic;
744 static unsigned long *vmx_msr_bitmap_longmode_x2apic;
745 static unsigned long *vmx_vmread_bitmap;
746 static unsigned long *vmx_vmwrite_bitmap;
747
748 static bool cpu_has_load_ia32_efer;
749 static bool cpu_has_load_perf_global_ctrl;
750
751 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
752 static DEFINE_SPINLOCK(vmx_vpid_lock);
753
754 static struct vmcs_config {
755         int size;
756         int order;
757         u32 revision_id;
758         u32 pin_based_exec_ctrl;
759         u32 cpu_based_exec_ctrl;
760         u32 cpu_based_2nd_exec_ctrl;
761         u32 vmexit_ctrl;
762         u32 vmentry_ctrl;
763 } vmcs_config;
764
765 static struct vmx_capability {
766         u32 ept;
767         u32 vpid;
768 } vmx_capability;
769
770 #define VMX_SEGMENT_FIELD(seg)                                  \
771         [VCPU_SREG_##seg] = {                                   \
772                 .selector = GUEST_##seg##_SELECTOR,             \
773                 .base = GUEST_##seg##_BASE,                     \
774                 .limit = GUEST_##seg##_LIMIT,                   \
775                 .ar_bytes = GUEST_##seg##_AR_BYTES,             \
776         }
777
778 static const struct kvm_vmx_segment_field {
779         unsigned selector;
780         unsigned base;
781         unsigned limit;
782         unsigned ar_bytes;
783 } kvm_vmx_segment_fields[] = {
784         VMX_SEGMENT_FIELD(CS),
785         VMX_SEGMENT_FIELD(DS),
786         VMX_SEGMENT_FIELD(ES),
787         VMX_SEGMENT_FIELD(FS),
788         VMX_SEGMENT_FIELD(GS),
789         VMX_SEGMENT_FIELD(SS),
790         VMX_SEGMENT_FIELD(TR),
791         VMX_SEGMENT_FIELD(LDTR),
792 };
793
794 static u64 host_efer;
795
796 static void ept_save_pdptrs(struct kvm_vcpu *vcpu);
797
798 /*
799  * Keep MSR_STAR at the end, as setup_msrs() will try to optimize it
800  * away by decrementing the array size.
801  */
802 static const u32 vmx_msr_index[] = {
803 #ifdef CONFIG_X86_64
804         MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
805 #endif
806         MSR_EFER, MSR_TSC_AUX, MSR_STAR,
807 };
808 #define NR_VMX_MSR ARRAY_SIZE(vmx_msr_index)
809
810 static inline bool is_page_fault(u32 intr_info)
811 {
812         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
813                              INTR_INFO_VALID_MASK)) ==
814                 (INTR_TYPE_HARD_EXCEPTION | PF_VECTOR | INTR_INFO_VALID_MASK);
815 }
816
817 static inline bool is_no_device(u32 intr_info)
818 {
819         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
820                              INTR_INFO_VALID_MASK)) ==
821                 (INTR_TYPE_HARD_EXCEPTION | NM_VECTOR | INTR_INFO_VALID_MASK);
822 }
823
824 static inline bool is_invalid_opcode(u32 intr_info)
825 {
826         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
827                              INTR_INFO_VALID_MASK)) ==
828                 (INTR_TYPE_HARD_EXCEPTION | UD_VECTOR | INTR_INFO_VALID_MASK);
829 }
830
831 static inline bool is_external_interrupt(u32 intr_info)
832 {
833         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
834                 == (INTR_TYPE_EXT_INTR | INTR_INFO_VALID_MASK);
835 }
836
837 static inline bool is_machine_check(u32 intr_info)
838 {
839         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
840                              INTR_INFO_VALID_MASK)) ==
841                 (INTR_TYPE_HARD_EXCEPTION | MC_VECTOR | INTR_INFO_VALID_MASK);
842 }
843
844 static inline bool cpu_has_vmx_msr_bitmap(void)
845 {
846         return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_USE_MSR_BITMAPS;
847 }
848
849 static inline bool cpu_has_vmx_tpr_shadow(void)
850 {
851         return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW;
852 }
853
854 static inline bool vm_need_tpr_shadow(struct kvm *kvm)
855 {
856         return (cpu_has_vmx_tpr_shadow()) && (irqchip_in_kernel(kvm));
857 }
858
859 static inline bool cpu_has_secondary_exec_ctrls(void)
860 {
861         return vmcs_config.cpu_based_exec_ctrl &
862                 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
863 }
864
865 static inline bool cpu_has_vmx_virtualize_apic_accesses(void)
866 {
867         return vmcs_config.cpu_based_2nd_exec_ctrl &
868                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
869 }
870
871 static inline bool cpu_has_vmx_virtualize_x2apic_mode(void)
872 {
873         return vmcs_config.cpu_based_2nd_exec_ctrl &
874                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
875 }
876
877 static inline bool cpu_has_vmx_apic_register_virt(void)
878 {
879         return vmcs_config.cpu_based_2nd_exec_ctrl &
880                 SECONDARY_EXEC_APIC_REGISTER_VIRT;
881 }
882
883 static inline bool cpu_has_vmx_virtual_intr_delivery(void)
884 {
885         return vmcs_config.cpu_based_2nd_exec_ctrl &
886                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY;
887 }
888
889 static inline bool cpu_has_vmx_posted_intr(void)
890 {
891         return vmcs_config.pin_based_exec_ctrl & PIN_BASED_POSTED_INTR;
892 }
893
894 static inline bool cpu_has_vmx_apicv(void)
895 {
896         return cpu_has_vmx_apic_register_virt() &&
897                 cpu_has_vmx_virtual_intr_delivery() &&
898                 cpu_has_vmx_posted_intr();
899 }
900
901 static inline bool cpu_has_vmx_flexpriority(void)
902 {
903         return cpu_has_vmx_tpr_shadow() &&
904                 cpu_has_vmx_virtualize_apic_accesses();
905 }
906
907 static inline bool cpu_has_vmx_ept_execute_only(void)
908 {
909         return vmx_capability.ept & VMX_EPT_EXECUTE_ONLY_BIT;
910 }
911
912 static inline bool cpu_has_vmx_eptp_uncacheable(void)
913 {
914         return vmx_capability.ept & VMX_EPTP_UC_BIT;
915 }
916
917 static inline bool cpu_has_vmx_eptp_writeback(void)
918 {
919         return vmx_capability.ept & VMX_EPTP_WB_BIT;
920 }
921
922 static inline bool cpu_has_vmx_ept_2m_page(void)
923 {
924         return vmx_capability.ept & VMX_EPT_2MB_PAGE_BIT;
925 }
926
927 static inline bool cpu_has_vmx_ept_1g_page(void)
928 {
929         return vmx_capability.ept & VMX_EPT_1GB_PAGE_BIT;
930 }
931
932 static inline bool cpu_has_vmx_ept_4levels(void)
933 {
934         return vmx_capability.ept & VMX_EPT_PAGE_WALK_4_BIT;
935 }
936
937 static inline bool cpu_has_vmx_ept_ad_bits(void)
938 {
939         return vmx_capability.ept & VMX_EPT_AD_BIT;
940 }
941
942 static inline bool cpu_has_vmx_invept_context(void)
943 {
944         return vmx_capability.ept & VMX_EPT_EXTENT_CONTEXT_BIT;
945 }
946
947 static inline bool cpu_has_vmx_invept_global(void)
948 {
949         return vmx_capability.ept & VMX_EPT_EXTENT_GLOBAL_BIT;
950 }
951
952 static inline bool cpu_has_vmx_invvpid_single(void)
953 {
954         return vmx_capability.vpid & VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT;
955 }
956
957 static inline bool cpu_has_vmx_invvpid_global(void)
958 {
959         return vmx_capability.vpid & VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT;
960 }
961
962 static inline bool cpu_has_vmx_ept(void)
963 {
964         return vmcs_config.cpu_based_2nd_exec_ctrl &
965                 SECONDARY_EXEC_ENABLE_EPT;
966 }
967
968 static inline bool cpu_has_vmx_unrestricted_guest(void)
969 {
970         return vmcs_config.cpu_based_2nd_exec_ctrl &
971                 SECONDARY_EXEC_UNRESTRICTED_GUEST;
972 }
973
974 static inline bool cpu_has_vmx_ple(void)
975 {
976         return vmcs_config.cpu_based_2nd_exec_ctrl &
977                 SECONDARY_EXEC_PAUSE_LOOP_EXITING;
978 }
979
980 static inline bool vm_need_virtualize_apic_accesses(struct kvm *kvm)
981 {
982         return flexpriority_enabled && irqchip_in_kernel(kvm);
983 }
984
985 static inline bool cpu_has_vmx_vpid(void)
986 {
987         return vmcs_config.cpu_based_2nd_exec_ctrl &
988                 SECONDARY_EXEC_ENABLE_VPID;
989 }
990
991 static inline bool cpu_has_vmx_rdtscp(void)
992 {
993         return vmcs_config.cpu_based_2nd_exec_ctrl &
994                 SECONDARY_EXEC_RDTSCP;
995 }
996
997 static inline bool cpu_has_vmx_invpcid(void)
998 {
999         return vmcs_config.cpu_based_2nd_exec_ctrl &
1000                 SECONDARY_EXEC_ENABLE_INVPCID;
1001 }
1002
1003 static inline bool cpu_has_virtual_nmis(void)
1004 {
1005         return vmcs_config.pin_based_exec_ctrl & PIN_BASED_VIRTUAL_NMIS;
1006 }
1007
1008 static inline bool cpu_has_vmx_wbinvd_exit(void)
1009 {
1010         return vmcs_config.cpu_based_2nd_exec_ctrl &
1011                 SECONDARY_EXEC_WBINVD_EXITING;
1012 }
1013
1014 static inline bool cpu_has_vmx_shadow_vmcs(void)
1015 {
1016         u64 vmx_msr;
1017         rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
1018         /* check if the cpu supports writing r/o exit information fields */
1019         if (!(vmx_msr & MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS))
1020                 return false;
1021
1022         return vmcs_config.cpu_based_2nd_exec_ctrl &
1023                 SECONDARY_EXEC_SHADOW_VMCS;
1024 }
1025
1026 static inline bool report_flexpriority(void)
1027 {
1028         return flexpriority_enabled;
1029 }
1030
1031 static inline bool nested_cpu_has(struct vmcs12 *vmcs12, u32 bit)
1032 {
1033         return vmcs12->cpu_based_vm_exec_control & bit;
1034 }
1035
1036 static inline bool nested_cpu_has2(struct vmcs12 *vmcs12, u32 bit)
1037 {
1038         return (vmcs12->cpu_based_vm_exec_control &
1039                         CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
1040                 (vmcs12->secondary_vm_exec_control & bit);
1041 }
1042
1043 static inline bool nested_cpu_has_virtual_nmis(struct vmcs12 *vmcs12,
1044         struct kvm_vcpu *vcpu)
1045 {
1046         return vmcs12->pin_based_vm_exec_control & PIN_BASED_VIRTUAL_NMIS;
1047 }
1048
1049 static inline bool is_exception(u32 intr_info)
1050 {
1051         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1052                 == (INTR_TYPE_HARD_EXCEPTION | INTR_INFO_VALID_MASK);
1053 }
1054
1055 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu);
1056 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
1057                         struct vmcs12 *vmcs12,
1058                         u32 reason, unsigned long qualification);
1059
1060 static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
1061 {
1062         int i;
1063
1064         for (i = 0; i < vmx->nmsrs; ++i)
1065                 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
1066                         return i;
1067         return -1;
1068 }
1069
1070 static inline void __invvpid(int ext, u16 vpid, gva_t gva)
1071 {
1072     struct {
1073         u64 vpid : 16;
1074         u64 rsvd : 48;
1075         u64 gva;
1076     } operand = { vpid, 0, gva };
1077
1078     asm volatile (__ex(ASM_VMX_INVVPID)
1079                   /* CF==1 or ZF==1 --> rc = -1 */
1080                   "; ja 1f ; ud2 ; 1:"
1081                   : : "a"(&operand), "c"(ext) : "cc", "memory");
1082 }
1083
1084 static inline void __invept(int ext, u64 eptp, gpa_t gpa)
1085 {
1086         struct {
1087                 u64 eptp, gpa;
1088         } operand = {eptp, gpa};
1089
1090         asm volatile (__ex(ASM_VMX_INVEPT)
1091                         /* CF==1 or ZF==1 --> rc = -1 */
1092                         "; ja 1f ; ud2 ; 1:\n"
1093                         : : "a" (&operand), "c" (ext) : "cc", "memory");
1094 }
1095
1096 static struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
1097 {
1098         int i;
1099
1100         i = __find_msr_index(vmx, msr);
1101         if (i >= 0)
1102                 return &vmx->guest_msrs[i];
1103         return NULL;
1104 }
1105
1106 static void vmcs_clear(struct vmcs *vmcs)
1107 {
1108         u64 phys_addr = __pa(vmcs);
1109         u8 error;
1110
1111         asm volatile (__ex(ASM_VMX_VMCLEAR_RAX) "; setna %0"
1112                       : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
1113                       : "cc", "memory");
1114         if (error)
1115                 printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n",
1116                        vmcs, phys_addr);
1117 }
1118
1119 static inline void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
1120 {
1121         vmcs_clear(loaded_vmcs->vmcs);
1122         loaded_vmcs->cpu = -1;
1123         loaded_vmcs->launched = 0;
1124 }
1125
1126 static void vmcs_load(struct vmcs *vmcs)
1127 {
1128         u64 phys_addr = __pa(vmcs);
1129         u8 error;
1130
1131         asm volatile (__ex(ASM_VMX_VMPTRLD_RAX) "; setna %0"
1132                         : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
1133                         : "cc", "memory");
1134         if (error)
1135                 printk(KERN_ERR "kvm: vmptrld %p/%llx failed\n",
1136                        vmcs, phys_addr);
1137 }
1138
1139 #ifdef CONFIG_KEXEC
1140 /*
1141  * This bitmap is used to indicate whether the vmclear
1142  * operation is enabled on all cpus. All disabled by
1143  * default.
1144  */
1145 static cpumask_t crash_vmclear_enabled_bitmap = CPU_MASK_NONE;
1146
1147 static inline void crash_enable_local_vmclear(int cpu)
1148 {
1149         cpumask_set_cpu(cpu, &crash_vmclear_enabled_bitmap);
1150 }
1151
1152 static inline void crash_disable_local_vmclear(int cpu)
1153 {
1154         cpumask_clear_cpu(cpu, &crash_vmclear_enabled_bitmap);
1155 }
1156
1157 static inline int crash_local_vmclear_enabled(int cpu)
1158 {
1159         return cpumask_test_cpu(cpu, &crash_vmclear_enabled_bitmap);
1160 }
1161
1162 static void crash_vmclear_local_loaded_vmcss(void)
1163 {
1164         int cpu = raw_smp_processor_id();
1165         struct loaded_vmcs *v;
1166
1167         if (!crash_local_vmclear_enabled(cpu))
1168                 return;
1169
1170         list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
1171                             loaded_vmcss_on_cpu_link)
1172                 vmcs_clear(v->vmcs);
1173 }
1174 #else
1175 static inline void crash_enable_local_vmclear(int cpu) { }
1176 static inline void crash_disable_local_vmclear(int cpu) { }
1177 #endif /* CONFIG_KEXEC */
1178
1179 static void __loaded_vmcs_clear(void *arg)
1180 {
1181         struct loaded_vmcs *loaded_vmcs = arg;
1182         int cpu = raw_smp_processor_id();
1183
1184         if (loaded_vmcs->cpu != cpu)
1185                 return; /* vcpu migration can race with cpu offline */
1186         if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
1187                 per_cpu(current_vmcs, cpu) = NULL;
1188         crash_disable_local_vmclear(cpu);
1189         list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
1190
1191         /*
1192          * we should ensure updating loaded_vmcs->loaded_vmcss_on_cpu_link
1193          * is before setting loaded_vmcs->vcpu to -1 which is done in
1194          * loaded_vmcs_init. Otherwise, other cpu can see vcpu = -1 fist
1195          * then adds the vmcs into percpu list before it is deleted.
1196          */
1197         smp_wmb();
1198
1199         loaded_vmcs_init(loaded_vmcs);
1200         crash_enable_local_vmclear(cpu);
1201 }
1202
1203 static void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
1204 {
1205         int cpu = loaded_vmcs->cpu;
1206
1207         if (cpu != -1)
1208                 smp_call_function_single(cpu,
1209                          __loaded_vmcs_clear, loaded_vmcs, 1);
1210 }
1211
1212 static inline void vpid_sync_vcpu_single(struct vcpu_vmx *vmx)
1213 {
1214         if (vmx->vpid == 0)
1215                 return;
1216
1217         if (cpu_has_vmx_invvpid_single())
1218                 __invvpid(VMX_VPID_EXTENT_SINGLE_CONTEXT, vmx->vpid, 0);
1219 }
1220
1221 static inline void vpid_sync_vcpu_global(void)
1222 {
1223         if (cpu_has_vmx_invvpid_global())
1224                 __invvpid(VMX_VPID_EXTENT_ALL_CONTEXT, 0, 0);
1225 }
1226
1227 static inline void vpid_sync_context(struct vcpu_vmx *vmx)
1228 {
1229         if (cpu_has_vmx_invvpid_single())
1230                 vpid_sync_vcpu_single(vmx);
1231         else
1232                 vpid_sync_vcpu_global();
1233 }
1234
1235 static inline void ept_sync_global(void)
1236 {
1237         if (cpu_has_vmx_invept_global())
1238                 __invept(VMX_EPT_EXTENT_GLOBAL, 0, 0);
1239 }
1240
1241 static inline void ept_sync_context(u64 eptp)
1242 {
1243         if (enable_ept) {
1244                 if (cpu_has_vmx_invept_context())
1245                         __invept(VMX_EPT_EXTENT_CONTEXT, eptp, 0);
1246                 else
1247                         ept_sync_global();
1248         }
1249 }
1250
1251 static __always_inline unsigned long vmcs_readl(unsigned long field)
1252 {
1253         unsigned long value;
1254
1255         asm volatile (__ex_clear(ASM_VMX_VMREAD_RDX_RAX, "%0")
1256                       : "=a"(value) : "d"(field) : "cc");
1257         return value;
1258 }
1259
1260 static __always_inline u16 vmcs_read16(unsigned long field)
1261 {
1262         return vmcs_readl(field);
1263 }
1264
1265 static __always_inline u32 vmcs_read32(unsigned long field)
1266 {
1267         return vmcs_readl(field);
1268 }
1269
1270 static __always_inline u64 vmcs_read64(unsigned long field)
1271 {
1272 #ifdef CONFIG_X86_64
1273         return vmcs_readl(field);
1274 #else
1275         return vmcs_readl(field) | ((u64)vmcs_readl(field+1) << 32);
1276 #endif
1277 }
1278
1279 static noinline void vmwrite_error(unsigned long field, unsigned long value)
1280 {
1281         printk(KERN_ERR "vmwrite error: reg %lx value %lx (err %d)\n",
1282                field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
1283         dump_stack();
1284 }
1285
1286 static void vmcs_writel(unsigned long field, unsigned long value)
1287 {
1288         u8 error;
1289
1290         asm volatile (__ex(ASM_VMX_VMWRITE_RAX_RDX) "; setna %0"
1291                        : "=q"(error) : "a"(value), "d"(field) : "cc");
1292         if (unlikely(error))
1293                 vmwrite_error(field, value);
1294 }
1295
1296 static void vmcs_write16(unsigned long field, u16 value)
1297 {
1298         vmcs_writel(field, value);
1299 }
1300
1301 static void vmcs_write32(unsigned long field, u32 value)
1302 {
1303         vmcs_writel(field, value);
1304 }
1305
1306 static void vmcs_write64(unsigned long field, u64 value)
1307 {
1308         vmcs_writel(field, value);
1309 #ifndef CONFIG_X86_64
1310         asm volatile ("");
1311         vmcs_writel(field+1, value >> 32);
1312 #endif
1313 }
1314
1315 static void vmcs_clear_bits(unsigned long field, u32 mask)
1316 {
1317         vmcs_writel(field, vmcs_readl(field) & ~mask);
1318 }
1319
1320 static void vmcs_set_bits(unsigned long field, u32 mask)
1321 {
1322         vmcs_writel(field, vmcs_readl(field) | mask);
1323 }
1324
1325 static void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
1326 {
1327         vmx->segment_cache.bitmask = 0;
1328 }
1329
1330 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
1331                                        unsigned field)
1332 {
1333         bool ret;
1334         u32 mask = 1 << (seg * SEG_FIELD_NR + field);
1335
1336         if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
1337                 vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
1338                 vmx->segment_cache.bitmask = 0;
1339         }
1340         ret = vmx->segment_cache.bitmask & mask;
1341         vmx->segment_cache.bitmask |= mask;
1342         return ret;
1343 }
1344
1345 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
1346 {
1347         u16 *p = &vmx->segment_cache.seg[seg].selector;
1348
1349         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
1350                 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
1351         return *p;
1352 }
1353
1354 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
1355 {
1356         ulong *p = &vmx->segment_cache.seg[seg].base;
1357
1358         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
1359                 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
1360         return *p;
1361 }
1362
1363 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
1364 {
1365         u32 *p = &vmx->segment_cache.seg[seg].limit;
1366
1367         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
1368                 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
1369         return *p;
1370 }
1371
1372 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
1373 {
1374         u32 *p = &vmx->segment_cache.seg[seg].ar;
1375
1376         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
1377                 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
1378         return *p;
1379 }
1380
1381 static void update_exception_bitmap(struct kvm_vcpu *vcpu)
1382 {
1383         u32 eb;
1384
1385         eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
1386              (1u << NM_VECTOR) | (1u << DB_VECTOR);
1387         if ((vcpu->guest_debug &
1388              (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
1389             (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
1390                 eb |= 1u << BP_VECTOR;
1391         if (to_vmx(vcpu)->rmode.vm86_active)
1392                 eb = ~0;
1393         if (enable_ept)
1394                 eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
1395         if (vcpu->fpu_active)
1396                 eb &= ~(1u << NM_VECTOR);
1397
1398         /* When we are running a nested L2 guest and L1 specified for it a
1399          * certain exception bitmap, we must trap the same exceptions and pass
1400          * them to L1. When running L2, we will only handle the exceptions
1401          * specified above if L1 did not want them.
1402          */
1403         if (is_guest_mode(vcpu))
1404                 eb |= get_vmcs12(vcpu)->exception_bitmap;
1405
1406         vmcs_write32(EXCEPTION_BITMAP, eb);
1407 }
1408
1409 static void clear_atomic_switch_msr_special(unsigned long entry,
1410                 unsigned long exit)
1411 {
1412         vmcs_clear_bits(VM_ENTRY_CONTROLS, entry);
1413         vmcs_clear_bits(VM_EXIT_CONTROLS, exit);
1414 }
1415
1416 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
1417 {
1418         unsigned i;
1419         struct msr_autoload *m = &vmx->msr_autoload;
1420
1421         switch (msr) {
1422         case MSR_EFER:
1423                 if (cpu_has_load_ia32_efer) {
1424                         clear_atomic_switch_msr_special(VM_ENTRY_LOAD_IA32_EFER,
1425                                         VM_EXIT_LOAD_IA32_EFER);
1426                         return;
1427                 }
1428                 break;
1429         case MSR_CORE_PERF_GLOBAL_CTRL:
1430                 if (cpu_has_load_perf_global_ctrl) {
1431                         clear_atomic_switch_msr_special(
1432                                         VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
1433                                         VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
1434                         return;
1435                 }
1436                 break;
1437         }
1438
1439         for (i = 0; i < m->nr; ++i)
1440                 if (m->guest[i].index == msr)
1441                         break;
1442
1443         if (i == m->nr)
1444                 return;
1445         --m->nr;
1446         m->guest[i] = m->guest[m->nr];
1447         m->host[i] = m->host[m->nr];
1448         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
1449         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
1450 }
1451
1452 static void add_atomic_switch_msr_special(unsigned long entry,
1453                 unsigned long exit, unsigned long guest_val_vmcs,
1454                 unsigned long host_val_vmcs, u64 guest_val, u64 host_val)
1455 {
1456         vmcs_write64(guest_val_vmcs, guest_val);
1457         vmcs_write64(host_val_vmcs, host_val);
1458         vmcs_set_bits(VM_ENTRY_CONTROLS, entry);
1459         vmcs_set_bits(VM_EXIT_CONTROLS, exit);
1460 }
1461
1462 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
1463                                   u64 guest_val, u64 host_val)
1464 {
1465         unsigned i;
1466         struct msr_autoload *m = &vmx->msr_autoload;
1467
1468         switch (msr) {
1469         case MSR_EFER:
1470                 if (cpu_has_load_ia32_efer) {
1471                         add_atomic_switch_msr_special(VM_ENTRY_LOAD_IA32_EFER,
1472                                         VM_EXIT_LOAD_IA32_EFER,
1473                                         GUEST_IA32_EFER,
1474                                         HOST_IA32_EFER,
1475                                         guest_val, host_val);
1476                         return;
1477                 }
1478                 break;
1479         case MSR_CORE_PERF_GLOBAL_CTRL:
1480                 if (cpu_has_load_perf_global_ctrl) {
1481                         add_atomic_switch_msr_special(
1482                                         VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
1483                                         VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
1484                                         GUEST_IA32_PERF_GLOBAL_CTRL,
1485                                         HOST_IA32_PERF_GLOBAL_CTRL,
1486                                         guest_val, host_val);
1487                         return;
1488                 }
1489                 break;
1490         }
1491
1492         for (i = 0; i < m->nr; ++i)
1493                 if (m->guest[i].index == msr)
1494                         break;
1495
1496         if (i == NR_AUTOLOAD_MSRS) {
1497                 printk_once(KERN_WARNING"Not enough mst switch entries. "
1498                                 "Can't add msr %x\n", msr);
1499                 return;
1500         } else if (i == m->nr) {
1501                 ++m->nr;
1502                 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
1503                 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
1504         }
1505
1506         m->guest[i].index = msr;
1507         m->guest[i].value = guest_val;
1508         m->host[i].index = msr;
1509         m->host[i].value = host_val;
1510 }
1511
1512 static void reload_tss(void)
1513 {
1514         /*
1515          * VT restores TR but not its size.  Useless.
1516          */
1517         struct desc_ptr *gdt = &__get_cpu_var(host_gdt);
1518         struct desc_struct *descs;
1519
1520         descs = (void *)gdt->address;
1521         descs[GDT_ENTRY_TSS].type = 9; /* available TSS */
1522         load_TR_desc();
1523 }
1524
1525 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
1526 {
1527         u64 guest_efer;
1528         u64 ignore_bits;
1529
1530         guest_efer = vmx->vcpu.arch.efer;
1531
1532         /*
1533          * NX is emulated; LMA and LME handled by hardware; SCE meaningless
1534          * outside long mode
1535          */
1536         ignore_bits = EFER_NX | EFER_SCE;
1537 #ifdef CONFIG_X86_64
1538         ignore_bits |= EFER_LMA | EFER_LME;
1539         /* SCE is meaningful only in long mode on Intel */
1540         if (guest_efer & EFER_LMA)
1541                 ignore_bits &= ~(u64)EFER_SCE;
1542 #endif
1543         guest_efer &= ~ignore_bits;
1544         guest_efer |= host_efer & ignore_bits;
1545         vmx->guest_msrs[efer_offset].data = guest_efer;
1546         vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
1547
1548         clear_atomic_switch_msr(vmx, MSR_EFER);
1549         /* On ept, can't emulate nx, and must switch nx atomically */
1550         if (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX)) {
1551                 guest_efer = vmx->vcpu.arch.efer;
1552                 if (!(guest_efer & EFER_LMA))
1553                         guest_efer &= ~EFER_LME;
1554                 add_atomic_switch_msr(vmx, MSR_EFER, guest_efer, host_efer);
1555                 return false;
1556         }
1557
1558         return true;
1559 }
1560
1561 static unsigned long segment_base(u16 selector)
1562 {
1563         struct desc_ptr *gdt = &__get_cpu_var(host_gdt);
1564         struct desc_struct *d;
1565         unsigned long table_base;
1566         unsigned long v;
1567
1568         if (!(selector & ~3))
1569                 return 0;
1570
1571         table_base = gdt->address;
1572
1573         if (selector & 4) {           /* from ldt */
1574                 u16 ldt_selector = kvm_read_ldt();
1575
1576                 if (!(ldt_selector & ~3))
1577                         return 0;
1578
1579                 table_base = segment_base(ldt_selector);
1580         }
1581         d = (struct desc_struct *)(table_base + (selector & ~7));
1582         v = get_desc_base(d);
1583 #ifdef CONFIG_X86_64
1584        if (d->s == 0 && (d->type == 2 || d->type == 9 || d->type == 11))
1585                v |= ((unsigned long)((struct ldttss_desc64 *)d)->base3) << 32;
1586 #endif
1587         return v;
1588 }
1589
1590 static inline unsigned long kvm_read_tr_base(void)
1591 {
1592         u16 tr;
1593         asm("str %0" : "=g"(tr));
1594         return segment_base(tr);
1595 }
1596
1597 static void vmx_save_host_state(struct kvm_vcpu *vcpu)
1598 {
1599         struct vcpu_vmx *vmx = to_vmx(vcpu);
1600         int i;
1601
1602         if (vmx->host_state.loaded)
1603                 return;
1604
1605         vmx->host_state.loaded = 1;
1606         /*
1607          * Set host fs and gs selectors.  Unfortunately, 22.2.3 does not
1608          * allow segment selectors with cpl > 0 or ti == 1.
1609          */
1610         vmx->host_state.ldt_sel = kvm_read_ldt();
1611         vmx->host_state.gs_ldt_reload_needed = vmx->host_state.ldt_sel;
1612         savesegment(fs, vmx->host_state.fs_sel);
1613         if (!(vmx->host_state.fs_sel & 7)) {
1614                 vmcs_write16(HOST_FS_SELECTOR, vmx->host_state.fs_sel);
1615                 vmx->host_state.fs_reload_needed = 0;
1616         } else {
1617                 vmcs_write16(HOST_FS_SELECTOR, 0);
1618                 vmx->host_state.fs_reload_needed = 1;
1619         }
1620         savesegment(gs, vmx->host_state.gs_sel);
1621         if (!(vmx->host_state.gs_sel & 7))
1622                 vmcs_write16(HOST_GS_SELECTOR, vmx->host_state.gs_sel);
1623         else {
1624                 vmcs_write16(HOST_GS_SELECTOR, 0);
1625                 vmx->host_state.gs_ldt_reload_needed = 1;
1626         }
1627
1628 #ifdef CONFIG_X86_64
1629         savesegment(ds, vmx->host_state.ds_sel);
1630         savesegment(es, vmx->host_state.es_sel);
1631 #endif
1632
1633 #ifdef CONFIG_X86_64
1634         vmcs_writel(HOST_FS_BASE, read_msr(MSR_FS_BASE));
1635         vmcs_writel(HOST_GS_BASE, read_msr(MSR_GS_BASE));
1636 #else
1637         vmcs_writel(HOST_FS_BASE, segment_base(vmx->host_state.fs_sel));
1638         vmcs_writel(HOST_GS_BASE, segment_base(vmx->host_state.gs_sel));
1639 #endif
1640
1641 #ifdef CONFIG_X86_64
1642         rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1643         if (is_long_mode(&vmx->vcpu))
1644                 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1645 #endif
1646         for (i = 0; i < vmx->save_nmsrs; ++i)
1647                 kvm_set_shared_msr(vmx->guest_msrs[i].index,
1648                                    vmx->guest_msrs[i].data,
1649                                    vmx->guest_msrs[i].mask);
1650 }
1651
1652 static void __vmx_load_host_state(struct vcpu_vmx *vmx)
1653 {
1654         if (!vmx->host_state.loaded)
1655                 return;
1656
1657         ++vmx->vcpu.stat.host_state_reload;
1658         vmx->host_state.loaded = 0;
1659 #ifdef CONFIG_X86_64
1660         if (is_long_mode(&vmx->vcpu))
1661                 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1662 #endif
1663         if (vmx->host_state.gs_ldt_reload_needed) {
1664                 kvm_load_ldt(vmx->host_state.ldt_sel);
1665 #ifdef CONFIG_X86_64
1666                 load_gs_index(vmx->host_state.gs_sel);
1667 #else
1668                 loadsegment(gs, vmx->host_state.gs_sel);
1669 #endif
1670         }
1671         if (vmx->host_state.fs_reload_needed)
1672                 loadsegment(fs, vmx->host_state.fs_sel);
1673 #ifdef CONFIG_X86_64
1674         if (unlikely(vmx->host_state.ds_sel | vmx->host_state.es_sel)) {
1675                 loadsegment(ds, vmx->host_state.ds_sel);
1676                 loadsegment(es, vmx->host_state.es_sel);
1677         }
1678 #endif
1679         reload_tss();
1680 #ifdef CONFIG_X86_64
1681         wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1682 #endif
1683         /*
1684          * If the FPU is not active (through the host task or
1685          * the guest vcpu), then restore the cr0.TS bit.
1686          */
1687         if (!user_has_fpu() && !vmx->vcpu.guest_fpu_loaded)
1688                 stts();
1689         load_gdt(&__get_cpu_var(host_gdt));
1690 }
1691
1692 static void vmx_load_host_state(struct vcpu_vmx *vmx)
1693 {
1694         preempt_disable();
1695         __vmx_load_host_state(vmx);
1696         preempt_enable();
1697 }
1698
1699 /*
1700  * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1701  * vcpu mutex is already taken.
1702  */
1703 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1704 {
1705         struct vcpu_vmx *vmx = to_vmx(vcpu);
1706         u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
1707
1708         if (!vmm_exclusive)
1709                 kvm_cpu_vmxon(phys_addr);
1710         else if (vmx->loaded_vmcs->cpu != cpu)
1711                 loaded_vmcs_clear(vmx->loaded_vmcs);
1712
1713         if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
1714                 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1715                 vmcs_load(vmx->loaded_vmcs->vmcs);
1716         }
1717
1718         if (vmx->loaded_vmcs->cpu != cpu) {
1719                 struct desc_ptr *gdt = &__get_cpu_var(host_gdt);
1720                 unsigned long sysenter_esp;
1721
1722                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1723                 local_irq_disable();
1724                 crash_disable_local_vmclear(cpu);
1725
1726                 /*
1727                  * Read loaded_vmcs->cpu should be before fetching
1728                  * loaded_vmcs->loaded_vmcss_on_cpu_link.
1729                  * See the comments in __loaded_vmcs_clear().
1730                  */
1731                 smp_rmb();
1732
1733                 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1734                          &per_cpu(loaded_vmcss_on_cpu, cpu));
1735                 crash_enable_local_vmclear(cpu);
1736                 local_irq_enable();
1737
1738                 /*
1739                  * Linux uses per-cpu TSS and GDT, so set these when switching
1740                  * processors.
1741                  */
1742                 vmcs_writel(HOST_TR_BASE, kvm_read_tr_base()); /* 22.2.4 */
1743                 vmcs_writel(HOST_GDTR_BASE, gdt->address);   /* 22.2.4 */
1744
1745                 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
1746                 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
1747                 vmx->loaded_vmcs->cpu = cpu;
1748         }
1749 }
1750
1751 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1752 {
1753         __vmx_load_host_state(to_vmx(vcpu));
1754         if (!vmm_exclusive) {
1755                 __loaded_vmcs_clear(to_vmx(vcpu)->loaded_vmcs);
1756                 vcpu->cpu = -1;
1757                 kvm_cpu_vmxoff();
1758         }
1759 }
1760
1761 static void vmx_fpu_activate(struct kvm_vcpu *vcpu)
1762 {
1763         ulong cr0;
1764
1765         if (vcpu->fpu_active)
1766                 return;
1767         vcpu->fpu_active = 1;
1768         cr0 = vmcs_readl(GUEST_CR0);
1769         cr0 &= ~(X86_CR0_TS | X86_CR0_MP);
1770         cr0 |= kvm_read_cr0_bits(vcpu, X86_CR0_TS | X86_CR0_MP);
1771         vmcs_writel(GUEST_CR0, cr0);
1772         update_exception_bitmap(vcpu);
1773         vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
1774         if (is_guest_mode(vcpu))
1775                 vcpu->arch.cr0_guest_owned_bits &=
1776                         ~get_vmcs12(vcpu)->cr0_guest_host_mask;
1777         vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
1778 }
1779
1780 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
1781
1782 /*
1783  * Return the cr0 value that a nested guest would read. This is a combination
1784  * of the real cr0 used to run the guest (guest_cr0), and the bits shadowed by
1785  * its hypervisor (cr0_read_shadow).
1786  */
1787 static inline unsigned long nested_read_cr0(struct vmcs12 *fields)
1788 {
1789         return (fields->guest_cr0 & ~fields->cr0_guest_host_mask) |
1790                 (fields->cr0_read_shadow & fields->cr0_guest_host_mask);
1791 }
1792 static inline unsigned long nested_read_cr4(struct vmcs12 *fields)
1793 {
1794         return (fields->guest_cr4 & ~fields->cr4_guest_host_mask) |
1795                 (fields->cr4_read_shadow & fields->cr4_guest_host_mask);
1796 }
1797
1798 static void vmx_fpu_deactivate(struct kvm_vcpu *vcpu)
1799 {
1800         /* Note that there is no vcpu->fpu_active = 0 here. The caller must
1801          * set this *before* calling this function.
1802          */
1803         vmx_decache_cr0_guest_bits(vcpu);
1804         vmcs_set_bits(GUEST_CR0, X86_CR0_TS | X86_CR0_MP);
1805         update_exception_bitmap(vcpu);
1806         vcpu->arch.cr0_guest_owned_bits = 0;
1807         vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
1808         if (is_guest_mode(vcpu)) {
1809                 /*
1810                  * L1's specified read shadow might not contain the TS bit,
1811                  * so now that we turned on shadowing of this bit, we need to
1812                  * set this bit of the shadow. Like in nested_vmx_run we need
1813                  * nested_read_cr0(vmcs12), but vmcs12->guest_cr0 is not yet
1814                  * up-to-date here because we just decached cr0.TS (and we'll
1815                  * only update vmcs12->guest_cr0 on nested exit).
1816                  */
1817                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1818                 vmcs12->guest_cr0 = (vmcs12->guest_cr0 & ~X86_CR0_TS) |
1819                         (vcpu->arch.cr0 & X86_CR0_TS);
1820                 vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
1821         } else
1822                 vmcs_writel(CR0_READ_SHADOW, vcpu->arch.cr0);
1823 }
1824
1825 static unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
1826 {
1827         unsigned long rflags, save_rflags;
1828
1829         if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
1830                 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
1831                 rflags = vmcs_readl(GUEST_RFLAGS);
1832                 if (to_vmx(vcpu)->rmode.vm86_active) {
1833                         rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1834                         save_rflags = to_vmx(vcpu)->rmode.save_rflags;
1835                         rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1836                 }
1837                 to_vmx(vcpu)->rflags = rflags;
1838         }
1839         return to_vmx(vcpu)->rflags;
1840 }
1841
1842 static void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1843 {
1844         __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
1845         to_vmx(vcpu)->rflags = rflags;
1846         if (to_vmx(vcpu)->rmode.vm86_active) {
1847                 to_vmx(vcpu)->rmode.save_rflags = rflags;
1848                 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1849         }
1850         vmcs_writel(GUEST_RFLAGS, rflags);
1851 }
1852
1853 static u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1854 {
1855         u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1856         int ret = 0;
1857
1858         if (interruptibility & GUEST_INTR_STATE_STI)
1859                 ret |= KVM_X86_SHADOW_INT_STI;
1860         if (interruptibility & GUEST_INTR_STATE_MOV_SS)
1861                 ret |= KVM_X86_SHADOW_INT_MOV_SS;
1862
1863         return ret & mask;
1864 }
1865
1866 static void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1867 {
1868         u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1869         u32 interruptibility = interruptibility_old;
1870
1871         interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1872
1873         if (mask & KVM_X86_SHADOW_INT_MOV_SS)
1874                 interruptibility |= GUEST_INTR_STATE_MOV_SS;
1875         else if (mask & KVM_X86_SHADOW_INT_STI)
1876                 interruptibility |= GUEST_INTR_STATE_STI;
1877
1878         if ((interruptibility != interruptibility_old))
1879                 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1880 }
1881
1882 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
1883 {
1884         unsigned long rip;
1885
1886         rip = kvm_rip_read(vcpu);
1887         rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1888         kvm_rip_write(vcpu, rip);
1889
1890         /* skipping an emulated instruction also counts */
1891         vmx_set_interrupt_shadow(vcpu, 0);
1892 }
1893
1894 /*
1895  * KVM wants to inject page-faults which it got to the guest. This function
1896  * checks whether in a nested guest, we need to inject them to L1 or L2.
1897  * This function assumes it is called with the exit reason in vmcs02 being
1898  * a #PF exception (this is the only case in which KVM injects a #PF when L2
1899  * is running).
1900  */
1901 static int nested_pf_handled(struct kvm_vcpu *vcpu)
1902 {
1903         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1904
1905         /* TODO: also check PFEC_MATCH/MASK, not just EB.PF. */
1906         if (!(vmcs12->exception_bitmap & (1u << PF_VECTOR)))
1907                 return 0;
1908
1909         nested_vmx_vmexit(vcpu);
1910         return 1;
1911 }
1912
1913 static void vmx_queue_exception(struct kvm_vcpu *vcpu, unsigned nr,
1914                                 bool has_error_code, u32 error_code,
1915                                 bool reinject)
1916 {
1917         struct vcpu_vmx *vmx = to_vmx(vcpu);
1918         u32 intr_info = nr | INTR_INFO_VALID_MASK;
1919
1920         if (nr == PF_VECTOR && is_guest_mode(vcpu) &&
1921             !vmx->nested.nested_run_pending && nested_pf_handled(vcpu))
1922                 return;
1923
1924         if (has_error_code) {
1925                 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
1926                 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
1927         }
1928
1929         if (vmx->rmode.vm86_active) {
1930                 int inc_eip = 0;
1931                 if (kvm_exception_is_soft(nr))
1932                         inc_eip = vcpu->arch.event_exit_inst_len;
1933                 if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
1934                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
1935                 return;
1936         }
1937
1938         if (kvm_exception_is_soft(nr)) {
1939                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
1940                              vmx->vcpu.arch.event_exit_inst_len);
1941                 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
1942         } else
1943                 intr_info |= INTR_TYPE_HARD_EXCEPTION;
1944
1945         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
1946 }
1947
1948 static bool vmx_rdtscp_supported(void)
1949 {
1950         return cpu_has_vmx_rdtscp();
1951 }
1952
1953 static bool vmx_invpcid_supported(void)
1954 {
1955         return cpu_has_vmx_invpcid() && enable_ept;
1956 }
1957
1958 /*
1959  * Swap MSR entry in host/guest MSR entry array.
1960  */
1961 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
1962 {
1963         struct shared_msr_entry tmp;
1964
1965         tmp = vmx->guest_msrs[to];
1966         vmx->guest_msrs[to] = vmx->guest_msrs[from];
1967         vmx->guest_msrs[from] = tmp;
1968 }
1969
1970 static void vmx_set_msr_bitmap(struct kvm_vcpu *vcpu)
1971 {
1972         unsigned long *msr_bitmap;
1973
1974         if (irqchip_in_kernel(vcpu->kvm) && apic_x2apic_mode(vcpu->arch.apic)) {
1975                 if (is_long_mode(vcpu))
1976                         msr_bitmap = vmx_msr_bitmap_longmode_x2apic;
1977                 else
1978                         msr_bitmap = vmx_msr_bitmap_legacy_x2apic;
1979         } else {
1980                 if (is_long_mode(vcpu))
1981                         msr_bitmap = vmx_msr_bitmap_longmode;
1982                 else
1983                         msr_bitmap = vmx_msr_bitmap_legacy;
1984         }
1985
1986         vmcs_write64(MSR_BITMAP, __pa(msr_bitmap));
1987 }
1988
1989 /*
1990  * Set up the vmcs to automatically save and restore system
1991  * msrs.  Don't touch the 64-bit msrs if the guest is in legacy
1992  * mode, as fiddling with msrs is very expensive.
1993  */
1994 static void setup_msrs(struct vcpu_vmx *vmx)
1995 {
1996         int save_nmsrs, index;
1997
1998         save_nmsrs = 0;
1999 #ifdef CONFIG_X86_64
2000         if (is_long_mode(&vmx->vcpu)) {
2001                 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
2002                 if (index >= 0)
2003                         move_msr_up(vmx, index, save_nmsrs++);
2004                 index = __find_msr_index(vmx, MSR_LSTAR);
2005                 if (index >= 0)
2006                         move_msr_up(vmx, index, save_nmsrs++);
2007                 index = __find_msr_index(vmx, MSR_CSTAR);
2008                 if (index >= 0)
2009                         move_msr_up(vmx, index, save_nmsrs++);
2010                 index = __find_msr_index(vmx, MSR_TSC_AUX);
2011                 if (index >= 0 && vmx->rdtscp_enabled)
2012                         move_msr_up(vmx, index, save_nmsrs++);
2013                 /*
2014                  * MSR_STAR is only needed on long mode guests, and only
2015                  * if efer.sce is enabled.
2016                  */
2017                 index = __find_msr_index(vmx, MSR_STAR);
2018                 if ((index >= 0) && (vmx->vcpu.arch.efer & EFER_SCE))
2019                         move_msr_up(vmx, index, save_nmsrs++);
2020         }
2021 #endif
2022         index = __find_msr_index(vmx, MSR_EFER);
2023         if (index >= 0 && update_transition_efer(vmx, index))
2024                 move_msr_up(vmx, index, save_nmsrs++);
2025
2026         vmx->save_nmsrs = save_nmsrs;
2027
2028         if (cpu_has_vmx_msr_bitmap())
2029                 vmx_set_msr_bitmap(&vmx->vcpu);
2030 }
2031
2032 /*
2033  * reads and returns guest's timestamp counter "register"
2034  * guest_tsc = host_tsc + tsc_offset    -- 21.3
2035  */
2036 static u64 guest_read_tsc(void)
2037 {
2038         u64 host_tsc, tsc_offset;
2039
2040         rdtscll(host_tsc);
2041         tsc_offset = vmcs_read64(TSC_OFFSET);
2042         return host_tsc + tsc_offset;
2043 }
2044
2045 /*
2046  * Like guest_read_tsc, but always returns L1's notion of the timestamp
2047  * counter, even if a nested guest (L2) is currently running.
2048  */
2049 u64 vmx_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
2050 {
2051         u64 tsc_offset;
2052
2053         tsc_offset = is_guest_mode(vcpu) ?
2054                 to_vmx(vcpu)->nested.vmcs01_tsc_offset :
2055                 vmcs_read64(TSC_OFFSET);
2056         return host_tsc + tsc_offset;
2057 }
2058
2059 /*
2060  * Engage any workarounds for mis-matched TSC rates.  Currently limited to
2061  * software catchup for faster rates on slower CPUs.
2062  */
2063 static void vmx_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
2064 {
2065         if (!scale)
2066                 return;
2067
2068         if (user_tsc_khz > tsc_khz) {
2069                 vcpu->arch.tsc_catchup = 1;
2070                 vcpu->arch.tsc_always_catchup = 1;
2071         } else
2072                 WARN(1, "user requested TSC rate below hardware speed\n");
2073 }
2074
2075 static u64 vmx_read_tsc_offset(struct kvm_vcpu *vcpu)
2076 {
2077         return vmcs_read64(TSC_OFFSET);
2078 }
2079
2080 /*
2081  * writes 'offset' into guest's timestamp counter offset register
2082  */
2083 static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
2084 {
2085         if (is_guest_mode(vcpu)) {
2086                 /*
2087                  * We're here if L1 chose not to trap WRMSR to TSC. According
2088                  * to the spec, this should set L1's TSC; The offset that L1
2089                  * set for L2 remains unchanged, and still needs to be added
2090                  * to the newly set TSC to get L2's TSC.
2091                  */
2092                 struct vmcs12 *vmcs12;
2093                 to_vmx(vcpu)->nested.vmcs01_tsc_offset = offset;
2094                 /* recalculate vmcs02.TSC_OFFSET: */
2095                 vmcs12 = get_vmcs12(vcpu);
2096                 vmcs_write64(TSC_OFFSET, offset +
2097                         (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETING) ?
2098                          vmcs12->tsc_offset : 0));
2099         } else {
2100                 vmcs_write64(TSC_OFFSET, offset);
2101         }
2102 }
2103
2104 static void vmx_adjust_tsc_offset(struct kvm_vcpu *vcpu, s64 adjustment, bool host)
2105 {
2106         u64 offset = vmcs_read64(TSC_OFFSET);
2107         vmcs_write64(TSC_OFFSET, offset + adjustment);
2108         if (is_guest_mode(vcpu)) {
2109                 /* Even when running L2, the adjustment needs to apply to L1 */
2110                 to_vmx(vcpu)->nested.vmcs01_tsc_offset += adjustment;
2111         }
2112 }
2113
2114 static u64 vmx_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
2115 {
2116         return target_tsc - native_read_tsc();
2117 }
2118
2119 static bool guest_cpuid_has_vmx(struct kvm_vcpu *vcpu)
2120 {
2121         struct kvm_cpuid_entry2 *best = kvm_find_cpuid_entry(vcpu, 1, 0);
2122         return best && (best->ecx & (1 << (X86_FEATURE_VMX & 31)));
2123 }
2124
2125 /*
2126  * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
2127  * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
2128  * all guests if the "nested" module option is off, and can also be disabled
2129  * for a single guest by disabling its VMX cpuid bit.
2130  */
2131 static inline bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
2132 {
2133         return nested && guest_cpuid_has_vmx(vcpu);
2134 }
2135
2136 /*
2137  * nested_vmx_setup_ctls_msrs() sets up variables containing the values to be
2138  * returned for the various VMX controls MSRs when nested VMX is enabled.
2139  * The same values should also be used to verify that vmcs12 control fields are
2140  * valid during nested entry from L1 to L2.
2141  * Each of these control msrs has a low and high 32-bit half: A low bit is on
2142  * if the corresponding bit in the (32-bit) control field *must* be on, and a
2143  * bit in the high half is on if the corresponding bit in the control field
2144  * may be on. See also vmx_control_verify().
2145  * TODO: allow these variables to be modified (downgraded) by module options
2146  * or other means.
2147  */
2148 static u32 nested_vmx_procbased_ctls_low, nested_vmx_procbased_ctls_high;
2149 static u32 nested_vmx_secondary_ctls_low, nested_vmx_secondary_ctls_high;
2150 static u32 nested_vmx_pinbased_ctls_low, nested_vmx_pinbased_ctls_high;
2151 static u32 nested_vmx_exit_ctls_low, nested_vmx_exit_ctls_high;
2152 static u32 nested_vmx_entry_ctls_low, nested_vmx_entry_ctls_high;
2153 static u32 nested_vmx_misc_low, nested_vmx_misc_high;
2154 static __init void nested_vmx_setup_ctls_msrs(void)
2155 {
2156         /*
2157          * Note that as a general rule, the high half of the MSRs (bits in
2158          * the control fields which may be 1) should be initialized by the
2159          * intersection of the underlying hardware's MSR (i.e., features which
2160          * can be supported) and the list of features we want to expose -
2161          * because they are known to be properly supported in our code.
2162          * Also, usually, the low half of the MSRs (bits which must be 1) can
2163          * be set to 0, meaning that L1 may turn off any of these bits. The
2164          * reason is that if one of these bits is necessary, it will appear
2165          * in vmcs01 and prepare_vmcs02, when it bitwise-or's the control
2166          * fields of vmcs01 and vmcs02, will turn these bits off - and
2167          * nested_vmx_exit_handled() will not pass related exits to L1.
2168          * These rules have exceptions below.
2169          */
2170
2171         /* pin-based controls */
2172         rdmsr(MSR_IA32_VMX_PINBASED_CTLS,
2173               nested_vmx_pinbased_ctls_low, nested_vmx_pinbased_ctls_high);
2174         /*
2175          * According to the Intel spec, if bit 55 of VMX_BASIC is off (as it is
2176          * in our case), bits 1, 2 and 4 (i.e., 0x16) must be 1 in this MSR.
2177          */
2178         nested_vmx_pinbased_ctls_low |= PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
2179         nested_vmx_pinbased_ctls_high &= PIN_BASED_EXT_INTR_MASK |
2180                 PIN_BASED_NMI_EXITING | PIN_BASED_VIRTUAL_NMIS |
2181                 PIN_BASED_VMX_PREEMPTION_TIMER;
2182         nested_vmx_pinbased_ctls_high |= PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
2183
2184         /*
2185          * Exit controls
2186          * If bit 55 of VMX_BASIC is off, bits 0-8 and 10, 11, 13, 14, 16 and
2187          * 17 must be 1.
2188          */
2189         nested_vmx_exit_ctls_low = VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
2190         /* Note that guest use of VM_EXIT_ACK_INTR_ON_EXIT is not supported. */
2191 #ifdef CONFIG_X86_64
2192         nested_vmx_exit_ctls_high = VM_EXIT_HOST_ADDR_SPACE_SIZE;
2193 #else
2194         nested_vmx_exit_ctls_high = 0;
2195 #endif
2196         nested_vmx_exit_ctls_high |= VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
2197
2198         /* entry controls */
2199         rdmsr(MSR_IA32_VMX_ENTRY_CTLS,
2200                 nested_vmx_entry_ctls_low, nested_vmx_entry_ctls_high);
2201         /* If bit 55 of VMX_BASIC is off, bits 0-8 and 12 must be 1. */
2202         nested_vmx_entry_ctls_low = VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
2203         nested_vmx_entry_ctls_high &=
2204                 VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_IA32E_MODE;
2205         nested_vmx_entry_ctls_high |= VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
2206
2207         /* cpu-based controls */
2208         rdmsr(MSR_IA32_VMX_PROCBASED_CTLS,
2209                 nested_vmx_procbased_ctls_low, nested_vmx_procbased_ctls_high);
2210         nested_vmx_procbased_ctls_low = 0;
2211         nested_vmx_procbased_ctls_high &=
2212                 CPU_BASED_VIRTUAL_INTR_PENDING | CPU_BASED_USE_TSC_OFFSETING |
2213                 CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING |
2214                 CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING |
2215                 CPU_BASED_CR3_STORE_EXITING |
2216 #ifdef CONFIG_X86_64
2217                 CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING |
2218 #endif
2219                 CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING |
2220                 CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_EXITING |
2221                 CPU_BASED_RDPMC_EXITING | CPU_BASED_RDTSC_EXITING |
2222                 CPU_BASED_PAUSE_EXITING |
2223                 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2224         /*
2225          * We can allow some features even when not supported by the
2226          * hardware. For example, L1 can specify an MSR bitmap - and we
2227          * can use it to avoid exits to L1 - even when L0 runs L2
2228          * without MSR bitmaps.
2229          */
2230         nested_vmx_procbased_ctls_high |= CPU_BASED_USE_MSR_BITMAPS;
2231
2232         /* secondary cpu-based controls */
2233         rdmsr(MSR_IA32_VMX_PROCBASED_CTLS2,
2234                 nested_vmx_secondary_ctls_low, nested_vmx_secondary_ctls_high);
2235         nested_vmx_secondary_ctls_low = 0;
2236         nested_vmx_secondary_ctls_high &=
2237                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2238                 SECONDARY_EXEC_WBINVD_EXITING;
2239
2240         /* miscellaneous data */
2241         rdmsr(MSR_IA32_VMX_MISC, nested_vmx_misc_low, nested_vmx_misc_high);
2242         nested_vmx_misc_low &= VMX_MISC_PREEMPTION_TIMER_RATE_MASK |
2243                 VMX_MISC_SAVE_EFER_LMA;
2244         nested_vmx_misc_high = 0;
2245 }
2246
2247 static inline bool vmx_control_verify(u32 control, u32 low, u32 high)
2248 {
2249         /*
2250          * Bits 0 in high must be 0, and bits 1 in low must be 1.
2251          */
2252         return ((control & high) | low) == control;
2253 }
2254
2255 static inline u64 vmx_control_msr(u32 low, u32 high)
2256 {
2257         return low | ((u64)high << 32);
2258 }
2259
2260 /*
2261  * If we allow our guest to use VMX instructions (i.e., nested VMX), we should
2262  * also let it use VMX-specific MSRs.
2263  * vmx_get_vmx_msr() and vmx_set_vmx_msr() return 1 when we handled a
2264  * VMX-specific MSR, or 0 when we haven't (and the caller should handle it
2265  * like all other MSRs).
2266  */
2267 static int vmx_get_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
2268 {
2269         if (!nested_vmx_allowed(vcpu) && msr_index >= MSR_IA32_VMX_BASIC &&
2270                      msr_index <= MSR_IA32_VMX_TRUE_ENTRY_CTLS) {
2271                 /*
2272                  * According to the spec, processors which do not support VMX
2273                  * should throw a #GP(0) when VMX capability MSRs are read.
2274                  */
2275                 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
2276                 return 1;
2277         }
2278
2279         switch (msr_index) {
2280         case MSR_IA32_FEATURE_CONTROL:
2281                 *pdata = 0;
2282                 break;
2283         case MSR_IA32_VMX_BASIC:
2284                 /*
2285                  * This MSR reports some information about VMX support. We
2286                  * should return information about the VMX we emulate for the
2287                  * guest, and the VMCS structure we give it - not about the
2288                  * VMX support of the underlying hardware.
2289                  */
2290                 *pdata = VMCS12_REVISION |
2291                            ((u64)VMCS12_SIZE << VMX_BASIC_VMCS_SIZE_SHIFT) |
2292                            (VMX_BASIC_MEM_TYPE_WB << VMX_BASIC_MEM_TYPE_SHIFT);
2293                 break;
2294         case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
2295         case MSR_IA32_VMX_PINBASED_CTLS:
2296                 *pdata = vmx_control_msr(nested_vmx_pinbased_ctls_low,
2297                                         nested_vmx_pinbased_ctls_high);
2298                 break;
2299         case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
2300         case MSR_IA32_VMX_PROCBASED_CTLS:
2301                 *pdata = vmx_control_msr(nested_vmx_procbased_ctls_low,
2302                                         nested_vmx_procbased_ctls_high);
2303                 break;
2304         case MSR_IA32_VMX_TRUE_EXIT_CTLS:
2305         case MSR_IA32_VMX_EXIT_CTLS:
2306                 *pdata = vmx_control_msr(nested_vmx_exit_ctls_low,
2307                                         nested_vmx_exit_ctls_high);
2308                 break;
2309         case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
2310         case MSR_IA32_VMX_ENTRY_CTLS:
2311                 *pdata = vmx_control_msr(nested_vmx_entry_ctls_low,
2312                                         nested_vmx_entry_ctls_high);
2313                 break;
2314         case MSR_IA32_VMX_MISC:
2315                 *pdata = vmx_control_msr(nested_vmx_misc_low,
2316                                          nested_vmx_misc_high);
2317                 break;
2318         /*
2319          * These MSRs specify bits which the guest must keep fixed (on or off)
2320          * while L1 is in VMXON mode (in L1's root mode, or running an L2).
2321          * We picked the standard core2 setting.
2322          */
2323 #define VMXON_CR0_ALWAYSON      (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE)
2324 #define VMXON_CR4_ALWAYSON      X86_CR4_VMXE
2325         case MSR_IA32_VMX_CR0_FIXED0:
2326                 *pdata = VMXON_CR0_ALWAYSON;
2327                 break;
2328         case MSR_IA32_VMX_CR0_FIXED1:
2329                 *pdata = -1ULL;
2330                 break;
2331         case MSR_IA32_VMX_CR4_FIXED0:
2332                 *pdata = VMXON_CR4_ALWAYSON;
2333                 break;
2334         case MSR_IA32_VMX_CR4_FIXED1:
2335                 *pdata = -1ULL;
2336                 break;
2337         case MSR_IA32_VMX_VMCS_ENUM:
2338                 *pdata = 0x1f;
2339                 break;
2340         case MSR_IA32_VMX_PROCBASED_CTLS2:
2341                 *pdata = vmx_control_msr(nested_vmx_secondary_ctls_low,
2342                                         nested_vmx_secondary_ctls_high);
2343                 break;
2344         case MSR_IA32_VMX_EPT_VPID_CAP:
2345                 /* Currently, no nested ept or nested vpid */
2346                 *pdata = 0;
2347                 break;
2348         default:
2349                 return 0;
2350         }
2351
2352         return 1;
2353 }
2354
2355 static int vmx_set_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
2356 {
2357         if (!nested_vmx_allowed(vcpu))
2358                 return 0;
2359
2360         if (msr_index == MSR_IA32_FEATURE_CONTROL)
2361                 /* TODO: the right thing. */
2362                 return 1;
2363         /*
2364          * No need to treat VMX capability MSRs specially: If we don't handle
2365          * them, handle_wrmsr will #GP(0), which is correct (they are readonly)
2366          */
2367         return 0;
2368 }
2369
2370 /*
2371  * Reads an msr value (of 'msr_index') into 'pdata'.
2372  * Returns 0 on success, non-0 otherwise.
2373  * Assumes vcpu_load() was already called.
2374  */
2375 static int vmx_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
2376 {
2377         u64 data;
2378         struct shared_msr_entry *msr;
2379
2380         if (!pdata) {
2381                 printk(KERN_ERR "BUG: get_msr called with NULL pdata\n");
2382                 return -EINVAL;
2383         }
2384
2385         switch (msr_index) {
2386 #ifdef CONFIG_X86_64
2387         case MSR_FS_BASE:
2388                 data = vmcs_readl(GUEST_FS_BASE);
2389                 break;
2390         case MSR_GS_BASE:
2391                 data = vmcs_readl(GUEST_GS_BASE);
2392                 break;
2393         case MSR_KERNEL_GS_BASE:
2394                 vmx_load_host_state(to_vmx(vcpu));
2395                 data = to_vmx(vcpu)->msr_guest_kernel_gs_base;
2396                 break;
2397 #endif
2398         case MSR_EFER:
2399                 return kvm_get_msr_common(vcpu, msr_index, pdata);
2400         case MSR_IA32_TSC:
2401                 data = guest_read_tsc();
2402                 break;
2403         case MSR_IA32_SYSENTER_CS:
2404                 data = vmcs_read32(GUEST_SYSENTER_CS);
2405                 break;
2406         case MSR_IA32_SYSENTER_EIP:
2407                 data = vmcs_readl(GUEST_SYSENTER_EIP);
2408                 break;
2409         case MSR_IA32_SYSENTER_ESP:
2410                 data = vmcs_readl(GUEST_SYSENTER_ESP);
2411                 break;
2412         case MSR_TSC_AUX:
2413                 if (!to_vmx(vcpu)->rdtscp_enabled)
2414                         return 1;
2415                 /* Otherwise falls through */
2416         default:
2417                 if (vmx_get_vmx_msr(vcpu, msr_index, pdata))
2418                         return 0;
2419                 msr = find_msr_entry(to_vmx(vcpu), msr_index);
2420                 if (msr) {
2421                         data = msr->data;
2422                         break;
2423                 }
2424                 return kvm_get_msr_common(vcpu, msr_index, pdata);
2425         }
2426
2427         *pdata = data;
2428         return 0;
2429 }
2430
2431 /*
2432  * Writes msr value into into the appropriate "register".
2433  * Returns 0 on success, non-0 otherwise.
2434  * Assumes vcpu_load() was already called.
2435  */
2436 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2437 {
2438         struct vcpu_vmx *vmx = to_vmx(vcpu);
2439         struct shared_msr_entry *msr;
2440         int ret = 0;
2441         u32 msr_index = msr_info->index;
2442         u64 data = msr_info->data;
2443
2444         switch (msr_index) {
2445         case MSR_EFER:
2446                 ret = kvm_set_msr_common(vcpu, msr_info);
2447                 break;
2448 #ifdef CONFIG_X86_64
2449         case MSR_FS_BASE:
2450                 vmx_segment_cache_clear(vmx);
2451                 vmcs_writel(GUEST_FS_BASE, data);
2452                 break;
2453         case MSR_GS_BASE:
2454                 vmx_segment_cache_clear(vmx);
2455                 vmcs_writel(GUEST_GS_BASE, data);
2456                 break;
2457         case MSR_KERNEL_GS_BASE:
2458                 vmx_load_host_state(vmx);
2459                 vmx->msr_guest_kernel_gs_base = data;
2460                 break;
2461 #endif
2462         case MSR_IA32_SYSENTER_CS:
2463                 vmcs_write32(GUEST_SYSENTER_CS, data);
2464                 break;
2465         case MSR_IA32_SYSENTER_EIP:
2466                 vmcs_writel(GUEST_SYSENTER_EIP, data);
2467                 break;
2468         case MSR_IA32_SYSENTER_ESP:
2469                 vmcs_writel(GUEST_SYSENTER_ESP, data);
2470                 break;
2471         case MSR_IA32_TSC:
2472                 kvm_write_tsc(vcpu, msr_info);
2473                 break;
2474         case MSR_IA32_CR_PAT:
2475                 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
2476                         vmcs_write64(GUEST_IA32_PAT, data);
2477                         vcpu->arch.pat = data;
2478                         break;
2479                 }
2480                 ret = kvm_set_msr_common(vcpu, msr_info);
2481                 break;
2482         case MSR_IA32_TSC_ADJUST:
2483                 ret = kvm_set_msr_common(vcpu, msr_info);
2484                 break;
2485         case MSR_TSC_AUX:
2486                 if (!vmx->rdtscp_enabled)
2487                         return 1;
2488                 /* Check reserved bit, higher 32 bits should be zero */
2489                 if ((data >> 32) != 0)
2490                         return 1;
2491                 /* Otherwise falls through */
2492         default:
2493                 if (vmx_set_vmx_msr(vcpu, msr_index, data))
2494                         break;
2495                 msr = find_msr_entry(vmx, msr_index);
2496                 if (msr) {
2497                         u64 old_msr_data = msr->data;
2498                         msr->data = data;
2499                         if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
2500                                 preempt_disable();
2501                                 ret = kvm_set_shared_msr(msr->index, msr->data,
2502                                                          msr->mask);
2503                                 preempt_enable();
2504                                 if (ret)
2505                                         msr->data = old_msr_data;
2506                         }
2507                         break;
2508                 }
2509                 ret = kvm_set_msr_common(vcpu, msr_info);
2510         }
2511
2512         return ret;
2513 }
2514
2515 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2516 {
2517         __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
2518         switch (reg) {
2519         case VCPU_REGS_RSP:
2520                 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
2521                 break;
2522         case VCPU_REGS_RIP:
2523                 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
2524                 break;
2525         case VCPU_EXREG_PDPTR:
2526                 if (enable_ept)
2527                         ept_save_pdptrs(vcpu);
2528                 break;
2529         default:
2530                 break;
2531         }
2532 }
2533
2534 static __init int cpu_has_kvm_support(void)
2535 {
2536         return cpu_has_vmx();
2537 }
2538
2539 static __init int vmx_disabled_by_bios(void)
2540 {
2541         u64 msr;
2542
2543         rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
2544         if (msr & FEATURE_CONTROL_LOCKED) {
2545                 /* launched w/ TXT and VMX disabled */
2546                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
2547                         && tboot_enabled())
2548                         return 1;
2549                 /* launched w/o TXT and VMX only enabled w/ TXT */
2550                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
2551                         && (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
2552                         && !tboot_enabled()) {
2553                         printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
2554                                 "activate TXT before enabling KVM\n");
2555                         return 1;
2556                 }
2557                 /* launched w/o TXT and VMX disabled */
2558                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
2559                         && !tboot_enabled())
2560                         return 1;
2561         }
2562
2563         return 0;
2564 }
2565
2566 static void kvm_cpu_vmxon(u64 addr)
2567 {
2568         asm volatile (ASM_VMX_VMXON_RAX
2569                         : : "a"(&addr), "m"(addr)
2570                         : "memory", "cc");
2571 }
2572
2573 static int hardware_enable(void)
2574 {
2575         int cpu = raw_smp_processor_id();
2576         u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2577         u64 old, test_bits;
2578
2579         if (read_cr4() & X86_CR4_VMXE)
2580                 return -EBUSY;
2581
2582         INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
2583
2584         /*
2585          * Now we can enable the vmclear operation in kdump
2586          * since the loaded_vmcss_on_cpu list on this cpu
2587          * has been initialized.
2588          *
2589          * Though the cpu is not in VMX operation now, there
2590          * is no problem to enable the vmclear operation
2591          * for the loaded_vmcss_on_cpu list is empty!
2592          */
2593         crash_enable_local_vmclear(cpu);
2594
2595         rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
2596
2597         test_bits = FEATURE_CONTROL_LOCKED;
2598         test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
2599         if (tboot_enabled())
2600                 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
2601
2602         if ((old & test_bits) != test_bits) {
2603                 /* enable and lock */
2604                 wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
2605         }
2606         write_cr4(read_cr4() | X86_CR4_VMXE); /* FIXME: not cpu hotplug safe */
2607
2608         if (vmm_exclusive) {
2609                 kvm_cpu_vmxon(phys_addr);
2610                 ept_sync_global();
2611         }
2612
2613         native_store_gdt(&__get_cpu_var(host_gdt));
2614
2615         return 0;
2616 }
2617
2618 static void vmclear_local_loaded_vmcss(void)
2619 {
2620         int cpu = raw_smp_processor_id();
2621         struct loaded_vmcs *v, *n;
2622
2623         list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
2624                                  loaded_vmcss_on_cpu_link)
2625                 __loaded_vmcs_clear(v);
2626 }
2627
2628
2629 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
2630  * tricks.
2631  */
2632 static void kvm_cpu_vmxoff(void)
2633 {
2634         asm volatile (__ex(ASM_VMX_VMXOFF) : : : "cc");
2635 }
2636
2637 static void hardware_disable(void)
2638 {
2639         if (vmm_exclusive) {
2640                 vmclear_local_loaded_vmcss();
2641                 kvm_cpu_vmxoff();
2642         }
2643         write_cr4(read_cr4() & ~X86_CR4_VMXE);
2644 }
2645
2646 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
2647                                       u32 msr, u32 *result)
2648 {
2649         u32 vmx_msr_low, vmx_msr_high;
2650         u32 ctl = ctl_min | ctl_opt;
2651
2652         rdmsr(msr, vmx_msr_low, vmx_msr_high);
2653
2654         ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
2655         ctl |= vmx_msr_low;  /* bit == 1 in low word  ==> must be one  */
2656
2657         /* Ensure minimum (required) set of control bits are supported. */
2658         if (ctl_min & ~ctl)
2659                 return -EIO;
2660
2661         *result = ctl;
2662         return 0;
2663 }
2664
2665 static __init bool allow_1_setting(u32 msr, u32 ctl)
2666 {
2667         u32 vmx_msr_low, vmx_msr_high;
2668
2669         rdmsr(msr, vmx_msr_low, vmx_msr_high);
2670         return vmx_msr_high & ctl;
2671 }
2672
2673 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
2674 {
2675         u32 vmx_msr_low, vmx_msr_high;
2676         u32 min, opt, min2, opt2;
2677         u32 _pin_based_exec_control = 0;
2678         u32 _cpu_based_exec_control = 0;
2679         u32 _cpu_based_2nd_exec_control = 0;
2680         u32 _vmexit_control = 0;
2681         u32 _vmentry_control = 0;
2682
2683         min = CPU_BASED_HLT_EXITING |
2684 #ifdef CONFIG_X86_64
2685               CPU_BASED_CR8_LOAD_EXITING |
2686               CPU_BASED_CR8_STORE_EXITING |
2687 #endif
2688               CPU_BASED_CR3_LOAD_EXITING |
2689               CPU_BASED_CR3_STORE_EXITING |
2690               CPU_BASED_USE_IO_BITMAPS |
2691               CPU_BASED_MOV_DR_EXITING |
2692               CPU_BASED_USE_TSC_OFFSETING |
2693               CPU_BASED_MWAIT_EXITING |
2694               CPU_BASED_MONITOR_EXITING |
2695               CPU_BASED_INVLPG_EXITING |
2696               CPU_BASED_RDPMC_EXITING;
2697
2698         opt = CPU_BASED_TPR_SHADOW |
2699               CPU_BASED_USE_MSR_BITMAPS |
2700               CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2701         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
2702                                 &_cpu_based_exec_control) < 0)
2703                 return -EIO;
2704 #ifdef CONFIG_X86_64
2705         if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2706                 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
2707                                            ~CPU_BASED_CR8_STORE_EXITING;
2708 #endif
2709         if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
2710                 min2 = 0;
2711                 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2712                         SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2713                         SECONDARY_EXEC_WBINVD_EXITING |
2714                         SECONDARY_EXEC_ENABLE_VPID |
2715                         SECONDARY_EXEC_ENABLE_EPT |
2716                         SECONDARY_EXEC_UNRESTRICTED_GUEST |
2717                         SECONDARY_EXEC_PAUSE_LOOP_EXITING |
2718                         SECONDARY_EXEC_RDTSCP |
2719                         SECONDARY_EXEC_ENABLE_INVPCID |
2720                         SECONDARY_EXEC_APIC_REGISTER_VIRT |
2721                         SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2722                         SECONDARY_EXEC_SHADOW_VMCS;
2723                 if (adjust_vmx_controls(min2, opt2,
2724                                         MSR_IA32_VMX_PROCBASED_CTLS2,
2725                                         &_cpu_based_2nd_exec_control) < 0)
2726                         return -EIO;
2727         }
2728 #ifndef CONFIG_X86_64
2729         if (!(_cpu_based_2nd_exec_control &
2730                                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
2731                 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
2732 #endif
2733
2734         if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2735                 _cpu_based_2nd_exec_control &= ~(
2736                                 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2737                                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2738                                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2739
2740         if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
2741                 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
2742                    enabled */
2743                 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
2744                                              CPU_BASED_CR3_STORE_EXITING |
2745                                              CPU_BASED_INVLPG_EXITING);
2746                 rdmsr(MSR_IA32_VMX_EPT_VPID_CAP,
2747                       vmx_capability.ept, vmx_capability.vpid);
2748         }
2749
2750         min = 0;
2751 #ifdef CONFIG_X86_64
2752         min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
2753 #endif
2754         opt = VM_EXIT_SAVE_IA32_PAT | VM_EXIT_LOAD_IA32_PAT |
2755                 VM_EXIT_ACK_INTR_ON_EXIT;
2756         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
2757                                 &_vmexit_control) < 0)
2758                 return -EIO;
2759
2760         min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
2761         opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR;
2762         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
2763                                 &_pin_based_exec_control) < 0)
2764                 return -EIO;
2765
2766         if (!(_cpu_based_2nd_exec_control &
2767                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) ||
2768                 !(_vmexit_control & VM_EXIT_ACK_INTR_ON_EXIT))
2769                 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
2770
2771         min = 0;
2772         opt = VM_ENTRY_LOAD_IA32_PAT;
2773         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
2774                                 &_vmentry_control) < 0)
2775                 return -EIO;
2776
2777         rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
2778
2779         /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
2780         if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
2781                 return -EIO;
2782
2783 #ifdef CONFIG_X86_64
2784         /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
2785         if (vmx_msr_high & (1u<<16))
2786                 return -EIO;
2787 #endif
2788
2789         /* Require Write-Back (WB) memory type for VMCS accesses. */
2790         if (((vmx_msr_high >> 18) & 15) != 6)
2791                 return -EIO;
2792
2793         vmcs_conf->size = vmx_msr_high & 0x1fff;
2794         vmcs_conf->order = get_order(vmcs_config.size);
2795         vmcs_conf->revision_id = vmx_msr_low;
2796
2797         vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
2798         vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
2799         vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
2800         vmcs_conf->vmexit_ctrl         = _vmexit_control;
2801         vmcs_conf->vmentry_ctrl        = _vmentry_control;
2802
2803         cpu_has_load_ia32_efer =
2804                 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
2805                                 VM_ENTRY_LOAD_IA32_EFER)
2806                 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
2807                                    VM_EXIT_LOAD_IA32_EFER);
2808
2809         cpu_has_load_perf_global_ctrl =
2810                 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
2811                                 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
2812                 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
2813                                    VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
2814
2815         /*
2816          * Some cpus support VM_ENTRY_(LOAD|SAVE)_IA32_PERF_GLOBAL_CTRL
2817          * but due to arrata below it can't be used. Workaround is to use
2818          * msr load mechanism to switch IA32_PERF_GLOBAL_CTRL.
2819          *
2820          * VM Exit May Incorrectly Clear IA32_PERF_GLOBAL_CTRL [34:32]
2821          *
2822          * AAK155             (model 26)
2823          * AAP115             (model 30)
2824          * AAT100             (model 37)
2825          * BC86,AAY89,BD102   (model 44)
2826          * BA97               (model 46)
2827          *
2828          */
2829         if (cpu_has_load_perf_global_ctrl && boot_cpu_data.x86 == 0x6) {
2830                 switch (boot_cpu_data.x86_model) {
2831                 case 26:
2832                 case 30:
2833                 case 37:
2834                 case 44:
2835                 case 46:
2836                         cpu_has_load_perf_global_ctrl = false;
2837                         printk_once(KERN_WARNING"kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
2838                                         "does not work properly. Using workaround\n");
2839                         break;
2840                 default:
2841                         break;
2842                 }
2843         }
2844
2845         return 0;
2846 }
2847
2848 static struct vmcs *alloc_vmcs_cpu(int cpu)
2849 {
2850         int node = cpu_to_node(cpu);
2851         struct page *pages;
2852         struct vmcs *vmcs;
2853
2854         pages = alloc_pages_exact_node(node, GFP_KERNEL, vmcs_config.order);
2855         if (!pages)
2856                 return NULL;
2857         vmcs = page_address(pages);
2858         memset(vmcs, 0, vmcs_config.size);
2859         vmcs->revision_id = vmcs_config.revision_id; /* vmcs revision id */
2860         return vmcs;
2861 }
2862
2863 static struct vmcs *alloc_vmcs(void)
2864 {
2865         return alloc_vmcs_cpu(raw_smp_processor_id());
2866 }
2867
2868 static void free_vmcs(struct vmcs *vmcs)
2869 {
2870         free_pages((unsigned long)vmcs, vmcs_config.order);
2871 }
2872
2873 /*
2874  * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
2875  */
2876 static void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2877 {
2878         if (!loaded_vmcs->vmcs)
2879                 return;
2880         loaded_vmcs_clear(loaded_vmcs);
2881         free_vmcs(loaded_vmcs->vmcs);
2882         loaded_vmcs->vmcs = NULL;
2883 }
2884
2885 static void free_kvm_area(void)
2886 {
2887         int cpu;
2888
2889         for_each_possible_cpu(cpu) {
2890                 free_vmcs(per_cpu(vmxarea, cpu));
2891                 per_cpu(vmxarea, cpu) = NULL;
2892         }
2893 }
2894
2895 static __init int alloc_kvm_area(void)
2896 {
2897         int cpu;
2898
2899         for_each_possible_cpu(cpu) {
2900                 struct vmcs *vmcs;
2901
2902                 vmcs = alloc_vmcs_cpu(cpu);
2903                 if (!vmcs) {
2904                         free_kvm_area();
2905                         return -ENOMEM;
2906                 }
2907
2908                 per_cpu(vmxarea, cpu) = vmcs;
2909         }
2910         return 0;
2911 }
2912
2913 static __init int hardware_setup(void)
2914 {
2915         if (setup_vmcs_config(&vmcs_config) < 0)
2916                 return -EIO;
2917
2918         if (boot_cpu_has(X86_FEATURE_NX))
2919                 kvm_enable_efer_bits(EFER_NX);
2920
2921         if (!cpu_has_vmx_vpid())
2922                 enable_vpid = 0;
2923         if (!cpu_has_vmx_shadow_vmcs())
2924                 enable_shadow_vmcs = 0;
2925
2926         if (!cpu_has_vmx_ept() ||
2927             !cpu_has_vmx_ept_4levels()) {
2928                 enable_ept = 0;
2929                 enable_unrestricted_guest = 0;
2930                 enable_ept_ad_bits = 0;
2931         }
2932
2933         if (!cpu_has_vmx_ept_ad_bits())
2934                 enable_ept_ad_bits = 0;
2935
2936         if (!cpu_has_vmx_unrestricted_guest())
2937                 enable_unrestricted_guest = 0;
2938
2939         if (!cpu_has_vmx_flexpriority())
2940                 flexpriority_enabled = 0;
2941
2942         if (!cpu_has_vmx_tpr_shadow())
2943                 kvm_x86_ops->update_cr8_intercept = NULL;
2944
2945         if (enable_ept && !cpu_has_vmx_ept_2m_page())
2946                 kvm_disable_largepages();
2947
2948         if (!cpu_has_vmx_ple())
2949                 ple_gap = 0;
2950
2951         if (!cpu_has_vmx_apicv())
2952                 enable_apicv = 0;
2953
2954         if (enable_apicv)
2955                 kvm_x86_ops->update_cr8_intercept = NULL;
2956         else {
2957                 kvm_x86_ops->hwapic_irr_update = NULL;
2958                 kvm_x86_ops->deliver_posted_interrupt = NULL;
2959                 kvm_x86_ops->sync_pir_to_irr = vmx_sync_pir_to_irr_dummy;
2960         }
2961
2962         if (nested)
2963                 nested_vmx_setup_ctls_msrs();
2964
2965         return alloc_kvm_area();
2966 }
2967
2968 static __exit void hardware_unsetup(void)
2969 {
2970         free_kvm_area();
2971 }
2972
2973 static bool emulation_required(struct kvm_vcpu *vcpu)
2974 {
2975         return emulate_invalid_guest_state && !guest_state_valid(vcpu);
2976 }
2977
2978 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
2979                 struct kvm_segment *save)
2980 {
2981         if (!emulate_invalid_guest_state) {
2982                 /*
2983                  * CS and SS RPL should be equal during guest entry according
2984                  * to VMX spec, but in reality it is not always so. Since vcpu
2985                  * is in the middle of the transition from real mode to
2986                  * protected mode it is safe to assume that RPL 0 is a good
2987                  * default value.
2988                  */
2989                 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
2990                         save->selector &= ~SELECTOR_RPL_MASK;
2991                 save->dpl = save->selector & SELECTOR_RPL_MASK;
2992                 save->s = 1;
2993         }
2994         vmx_set_segment(vcpu, save, seg);
2995 }
2996
2997 static void enter_pmode(struct kvm_vcpu *vcpu)
2998 {
2999         unsigned long flags;
3000         struct vcpu_vmx *vmx = to_vmx(vcpu);
3001
3002         /*
3003          * Update real mode segment cache. It may be not up-to-date if sement
3004          * register was written while vcpu was in a guest mode.
3005          */
3006         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
3007         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
3008         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
3009         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
3010         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
3011         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
3012
3013         vmx->rmode.vm86_active = 0;
3014
3015         vmx_segment_cache_clear(vmx);
3016
3017         vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
3018
3019         flags = vmcs_readl(GUEST_RFLAGS);
3020         flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
3021         flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
3022         vmcs_writel(GUEST_RFLAGS, flags);
3023
3024         vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
3025                         (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
3026
3027         update_exception_bitmap(vcpu);
3028
3029         fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
3030         fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
3031         fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
3032         fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
3033         fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
3034         fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
3035
3036         /* CPL is always 0 when CPU enters protected mode */
3037         __set_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail);
3038         vmx->cpl = 0;
3039 }
3040
3041 static void fix_rmode_seg(int seg, struct kvm_segment *save)
3042 {
3043         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3044         struct kvm_segment var = *save;
3045
3046         var.dpl = 0x3;
3047         if (seg == VCPU_SREG_CS)
3048                 var.type = 0x3;
3049
3050         if (!emulate_invalid_guest_state) {
3051                 var.selector = var.base >> 4;
3052                 var.base = var.base & 0xffff0;
3053                 var.limit = 0xffff;
3054                 var.g = 0;
3055                 var.db = 0;
3056                 var.present = 1;
3057                 var.s = 1;
3058                 var.l = 0;
3059                 var.unusable = 0;
3060                 var.type = 0x3;
3061                 var.avl = 0;
3062                 if (save->base & 0xf)
3063                         printk_once(KERN_WARNING "kvm: segment base is not "
3064                                         "paragraph aligned when entering "
3065                                         "protected mode (seg=%d)", seg);
3066         }
3067
3068         vmcs_write16(sf->selector, var.selector);
3069         vmcs_write32(sf->base, var.base);
3070         vmcs_write32(sf->limit, var.limit);
3071         vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
3072 }
3073
3074 static void enter_rmode(struct kvm_vcpu *vcpu)
3075 {
3076         unsigned long flags;
3077         struct vcpu_vmx *vmx = to_vmx(vcpu);
3078
3079         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
3080         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
3081         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
3082         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
3083         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
3084         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
3085         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
3086
3087         vmx->rmode.vm86_active = 1;
3088
3089         /*
3090          * Very old userspace does not call KVM_SET_TSS_ADDR before entering
3091          * vcpu. Warn the user that an update is overdue.
3092          */
3093         if (!vcpu->kvm->arch.tss_addr)
3094                 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
3095                              "called before entering vcpu\n");
3096
3097         vmx_segment_cache_clear(vmx);
3098
3099         vmcs_writel(GUEST_TR_BASE, vcpu->kvm->arch.tss_addr);
3100         vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
3101         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
3102
3103         flags = vmcs_readl(GUEST_RFLAGS);
3104         vmx->rmode.save_rflags = flags;
3105
3106         flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
3107
3108         vmcs_writel(GUEST_RFLAGS, flags);
3109         vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
3110         update_exception_bitmap(vcpu);
3111
3112         fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
3113         fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
3114         fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
3115         fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
3116         fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
3117         fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
3118
3119         kvm_mmu_reset_context(vcpu);
3120 }
3121
3122 static void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
3123 {
3124         struct vcpu_vmx *vmx = to_vmx(vcpu);
3125         struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
3126
3127         if (!msr)
3128                 return;
3129
3130         /*
3131          * Force kernel_gs_base reloading before EFER changes, as control
3132          * of this msr depends on is_long_mode().
3133          */
3134         vmx_load_host_state(to_vmx(vcpu));
3135         vcpu->arch.efer = efer;
3136         if (efer & EFER_LMA) {
3137                 vmcs_write32(VM_ENTRY_CONTROLS,
3138                              vmcs_read32(VM_ENTRY_CONTROLS) |
3139                              VM_ENTRY_IA32E_MODE);
3140                 msr->data = efer;
3141         } else {
3142                 vmcs_write32(VM_ENTRY_CONTROLS,
3143                              vmcs_read32(VM_ENTRY_CONTROLS) &
3144                              ~VM_ENTRY_IA32E_MODE);
3145
3146                 msr->data = efer & ~EFER_LME;
3147         }
3148         setup_msrs(vmx);
3149 }
3150
3151 #ifdef CONFIG_X86_64
3152
3153 static void enter_lmode(struct kvm_vcpu *vcpu)
3154 {
3155         u32 guest_tr_ar;
3156
3157         vmx_segment_cache_clear(to_vmx(vcpu));
3158
3159         guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
3160         if ((guest_tr_ar & AR_TYPE_MASK) != AR_TYPE_BUSY_64_TSS) {
3161                 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
3162                                      __func__);
3163                 vmcs_write32(GUEST_TR_AR_BYTES,
3164                              (guest_tr_ar & ~AR_TYPE_MASK)
3165                              | AR_TYPE_BUSY_64_TSS);
3166         }
3167         vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
3168 }
3169
3170 static void exit_lmode(struct kvm_vcpu *vcpu)
3171 {
3172         vmcs_write32(VM_ENTRY_CONTROLS,
3173                      vmcs_read32(VM_ENTRY_CONTROLS)
3174                      & ~VM_ENTRY_IA32E_MODE);
3175         vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
3176 }
3177
3178 #endif
3179
3180 static void vmx_flush_tlb(struct kvm_vcpu *vcpu)
3181 {
3182         vpid_sync_context(to_vmx(vcpu));
3183         if (enable_ept) {
3184                 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3185                         return;
3186                 ept_sync_context(construct_eptp(vcpu->arch.mmu.root_hpa));
3187         }
3188 }
3189
3190 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
3191 {
3192         ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
3193
3194         vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
3195         vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
3196 }
3197
3198 static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
3199 {
3200         if (enable_ept && is_paging(vcpu))
3201                 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
3202         __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
3203 }
3204
3205 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
3206 {
3207         ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
3208
3209         vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
3210         vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
3211 }
3212
3213 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
3214 {
3215         if (!test_bit(VCPU_EXREG_PDPTR,
3216                       (unsigned long *)&vcpu->arch.regs_dirty))
3217                 return;
3218
3219         if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
3220                 vmcs_write64(GUEST_PDPTR0, vcpu->arch.mmu.pdptrs[0]);
3221                 vmcs_write64(GUEST_PDPTR1, vcpu->arch.mmu.pdptrs[1]);
3222                 vmcs_write64(GUEST_PDPTR2, vcpu->arch.mmu.pdptrs[2]);
3223                 vmcs_write64(GUEST_PDPTR3, vcpu->arch.mmu.pdptrs[3]);
3224         }
3225 }
3226
3227 static void ept_save_pdptrs(struct kvm_vcpu *vcpu)
3228 {
3229         if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
3230                 vcpu->arch.mmu.pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
3231                 vcpu->arch.mmu.pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
3232                 vcpu->arch.mmu.pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
3233                 vcpu->arch.mmu.pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
3234         }
3235
3236         __set_bit(VCPU_EXREG_PDPTR,
3237                   (unsigned long *)&vcpu->arch.regs_avail);
3238         __set_bit(VCPU_EXREG_PDPTR,
3239                   (unsigned long *)&vcpu->arch.regs_dirty);
3240 }
3241
3242 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
3243
3244 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
3245                                         unsigned long cr0,
3246                                         struct kvm_vcpu *vcpu)
3247 {
3248         if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
3249                 vmx_decache_cr3(vcpu);
3250         if (!(cr0 & X86_CR0_PG)) {
3251                 /* From paging/starting to nonpaging */
3252                 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
3253                              vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
3254                              (CPU_BASED_CR3_LOAD_EXITING |
3255                               CPU_BASED_CR3_STORE_EXITING));
3256                 vcpu->arch.cr0 = cr0;
3257                 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3258         } else if (!is_paging(vcpu)) {
3259                 /* From nonpaging to paging */
3260                 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
3261                              vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
3262                              ~(CPU_BASED_CR3_LOAD_EXITING |
3263                                CPU_BASED_CR3_STORE_EXITING));
3264                 vcpu->arch.cr0 = cr0;
3265                 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3266         }
3267
3268         if (!(cr0 & X86_CR0_WP))
3269                 *hw_cr0 &= ~X86_CR0_WP;
3270 }
3271
3272 static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
3273 {
3274         struct vcpu_vmx *vmx = to_vmx(vcpu);
3275         unsigned long hw_cr0;
3276
3277         hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK);
3278         if (enable_unrestricted_guest)
3279                 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
3280         else {
3281                 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
3282
3283                 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
3284                         enter_pmode(vcpu);
3285
3286                 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
3287                         enter_rmode(vcpu);
3288         }
3289
3290 #ifdef CONFIG_X86_64
3291         if (vcpu->arch.efer & EFER_LME) {
3292                 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
3293                         enter_lmode(vcpu);
3294                 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
3295                         exit_lmode(vcpu);
3296         }
3297 #endif
3298
3299         if (enable_ept)
3300                 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
3301
3302         if (!vcpu->fpu_active)
3303                 hw_cr0 |= X86_CR0_TS | X86_CR0_MP;
3304
3305         vmcs_writel(CR0_READ_SHADOW, cr0);
3306         vmcs_writel(GUEST_CR0, hw_cr0);
3307         vcpu->arch.cr0 = cr0;
3308
3309         /* depends on vcpu->arch.cr0 to be set to a new value */
3310         vmx->emulation_required = emulation_required(vcpu);
3311 }
3312
3313 static u64 construct_eptp(unsigned long root_hpa)
3314 {
3315         u64 eptp;
3316
3317         /* TODO write the value reading from MSR */
3318         eptp = VMX_EPT_DEFAULT_MT |
3319                 VMX_EPT_DEFAULT_GAW << VMX_EPT_GAW_EPTP_SHIFT;
3320         if (enable_ept_ad_bits)
3321                 eptp |= VMX_EPT_AD_ENABLE_BIT;
3322         eptp |= (root_hpa & PAGE_MASK);
3323
3324         return eptp;
3325 }
3326
3327 static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
3328 {
3329         unsigned long guest_cr3;
3330         u64 eptp;
3331
3332         guest_cr3 = cr3;
3333         if (enable_ept) {
3334                 eptp = construct_eptp(cr3);
3335                 vmcs_write64(EPT_POINTER, eptp);
3336                 guest_cr3 = is_paging(vcpu) ? kvm_read_cr3(vcpu) :
3337                         vcpu->kvm->arch.ept_identity_map_addr;
3338                 ept_load_pdptrs(vcpu);
3339         }
3340
3341         vmx_flush_tlb(vcpu);
3342         vmcs_writel(GUEST_CR3, guest_cr3);
3343 }
3344
3345 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3346 {
3347         unsigned long hw_cr4 = cr4 | (to_vmx(vcpu)->rmode.vm86_active ?
3348                     KVM_RMODE_VM_CR4_ALWAYS_ON : KVM_PMODE_VM_CR4_ALWAYS_ON);
3349
3350         if (cr4 & X86_CR4_VMXE) {
3351                 /*
3352                  * To use VMXON (and later other VMX instructions), a guest
3353                  * must first be able to turn on cr4.VMXE (see handle_vmon()).
3354                  * So basically the check on whether to allow nested VMX
3355                  * is here.
3356                  */
3357                 if (!nested_vmx_allowed(vcpu))
3358                         return 1;
3359         }
3360         if (to_vmx(vcpu)->nested.vmxon &&
3361             ((cr4 & VMXON_CR4_ALWAYSON) != VMXON_CR4_ALWAYSON))
3362                 return 1;
3363
3364         vcpu->arch.cr4 = cr4;
3365         if (enable_ept) {
3366                 if (!is_paging(vcpu)) {
3367                         hw_cr4 &= ~X86_CR4_PAE;
3368                         hw_cr4 |= X86_CR4_PSE;
3369                         /*
3370                          * SMEP is disabled if CPU is in non-paging mode in
3371                          * hardware. However KVM always uses paging mode to
3372                          * emulate guest non-paging mode with TDP.
3373                          * To emulate this behavior, SMEP needs to be manually
3374                          * disabled when guest switches to non-paging mode.
3375                          */
3376                         hw_cr4 &= ~X86_CR4_SMEP;
3377                 } else if (!(cr4 & X86_CR4_PAE)) {
3378                         hw_cr4 &= ~X86_CR4_PAE;
3379                 }
3380         }
3381
3382         vmcs_writel(CR4_READ_SHADOW, cr4);
3383         vmcs_writel(GUEST_CR4, hw_cr4);
3384         return 0;
3385 }
3386
3387 static void vmx_get_segment(struct kvm_vcpu *vcpu,
3388                             struct kvm_segment *var, int seg)
3389 {
3390         struct vcpu_vmx *vmx = to_vmx(vcpu);
3391         u32 ar;
3392
3393         if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3394                 *var = vmx->rmode.segs[seg];
3395                 if (seg == VCPU_SREG_TR
3396                     || var->selector == vmx_read_guest_seg_selector(vmx, seg))
3397                         return;
3398                 var->base = vmx_read_guest_seg_base(vmx, seg);
3399                 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3400                 return;
3401         }
3402         var->base = vmx_read_guest_seg_base(vmx, seg);
3403         var->limit = vmx_read_guest_seg_limit(vmx, seg);
3404         var->selector = vmx_read_guest_seg_selector(vmx, seg);
3405         ar = vmx_read_guest_seg_ar(vmx, seg);
3406         var->unusable = (ar >> 16) & 1;
3407         var->type = ar & 15;
3408         var->s = (ar >> 4) & 1;
3409         var->dpl = (ar >> 5) & 3;
3410         /*
3411          * Some userspaces do not preserve unusable property. Since usable
3412          * segment has to be present according to VMX spec we can use present
3413          * property to amend userspace bug by making unusable segment always
3414          * nonpresent. vmx_segment_access_rights() already marks nonpresent
3415          * segment as unusable.
3416          */
3417         var->present = !var->unusable;
3418         var->avl = (ar >> 12) & 1;
3419         var->l = (ar >> 13) & 1;
3420         var->db = (ar >> 14) & 1;
3421         var->g = (ar >> 15) & 1;
3422 }
3423
3424 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
3425 {
3426         struct kvm_segment s;
3427
3428         if (to_vmx(vcpu)->rmode.vm86_active) {
3429                 vmx_get_segment(vcpu, &s, seg);
3430                 return s.base;
3431         }
3432         return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
3433 }
3434
3435 static int vmx_get_cpl(struct kvm_vcpu *vcpu)
3436 {
3437         struct vcpu_vmx *vmx = to_vmx(vcpu);
3438
3439         if (!is_protmode(vcpu))
3440                 return 0;
3441
3442         if (!is_long_mode(vcpu)
3443             && (kvm_get_rflags(vcpu) & X86_EFLAGS_VM)) /* if virtual 8086 */
3444                 return 3;
3445
3446         if (!test_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail)) {
3447                 __set_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail);
3448                 vmx->cpl = vmx_read_guest_seg_selector(vmx, VCPU_SREG_CS) & 3;
3449         }
3450
3451         return vmx->cpl;
3452 }
3453
3454
3455 static u32 vmx_segment_access_rights(struct kvm_segment *var)
3456 {
3457         u32 ar;
3458
3459         if (var->unusable || !var->present)
3460                 ar = 1 << 16;
3461         else {
3462                 ar = var->type & 15;
3463                 ar |= (var->s & 1) << 4;
3464                 ar |= (var->dpl & 3) << 5;
3465                 ar |= (var->present & 1) << 7;
3466                 ar |= (var->avl & 1) << 12;
3467                 ar |= (var->l & 1) << 13;
3468                 ar |= (var->db & 1) << 14;
3469                 ar |= (var->g & 1) << 15;
3470         }
3471
3472         return ar;
3473 }
3474
3475 static void vmx_set_segment(struct kvm_vcpu *vcpu,
3476                             struct kvm_segment *var, int seg)
3477 {
3478         struct vcpu_vmx *vmx = to_vmx(vcpu);
3479         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3480
3481         vmx_segment_cache_clear(vmx);
3482         if (seg == VCPU_SREG_CS)
3483                 __clear_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail);
3484
3485         if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3486                 vmx->rmode.segs[seg] = *var;
3487                 if (seg == VCPU_SREG_TR)
3488                         vmcs_write16(sf->selector, var->selector);
3489                 else if (var->s)
3490                         fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
3491                 goto out;
3492         }
3493
3494         vmcs_writel(sf->base, var->base);
3495         vmcs_write32(sf->limit, var->limit);
3496         vmcs_write16(sf->selector, var->selector);
3497
3498         /*
3499          *   Fix the "Accessed" bit in AR field of segment registers for older
3500          * qemu binaries.
3501          *   IA32 arch specifies that at the time of processor reset the
3502          * "Accessed" bit in the AR field of segment registers is 1. And qemu
3503          * is setting it to 0 in the userland code. This causes invalid guest
3504          * state vmexit when "unrestricted guest" mode is turned on.
3505          *    Fix for this setup issue in cpu_reset is being pushed in the qemu
3506          * tree. Newer qemu binaries with that qemu fix would not need this
3507          * kvm hack.
3508          */
3509         if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
3510                 var->type |= 0x1; /* Accessed */
3511
3512         vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
3513
3514 out:
3515         vmx->emulation_required |= emulation_required(vcpu);
3516 }
3517
3518 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3519 {
3520         u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
3521
3522         *db = (ar >> 14) & 1;
3523         *l = (ar >> 13) & 1;
3524 }
3525
3526 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3527 {
3528         dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
3529         dt->address = vmcs_readl(GUEST_IDTR_BASE);
3530 }
3531
3532 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3533 {
3534         vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
3535         vmcs_writel(GUEST_IDTR_BASE, dt->address);
3536 }
3537
3538 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3539 {
3540         dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
3541         dt->address = vmcs_readl(GUEST_GDTR_BASE);
3542 }
3543
3544 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3545 {
3546         vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
3547         vmcs_writel(GUEST_GDTR_BASE, dt->address);
3548 }
3549
3550 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
3551 {
3552         struct kvm_segment var;
3553         u32 ar;
3554
3555         vmx_get_segment(vcpu, &var, seg);
3556         var.dpl = 0x3;
3557         if (seg == VCPU_SREG_CS)
3558                 var.type = 0x3;
3559         ar = vmx_segment_access_rights(&var);
3560
3561         if (var.base != (var.selector << 4))
3562                 return false;
3563         if (var.limit != 0xffff)
3564                 return false;
3565         if (ar != 0xf3)
3566                 return false;
3567
3568         return true;
3569 }
3570
3571 static bool code_segment_valid(struct kvm_vcpu *vcpu)
3572 {
3573         struct kvm_segment cs;
3574         unsigned int cs_rpl;
3575
3576         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3577         cs_rpl = cs.selector & SELECTOR_RPL_MASK;
3578
3579         if (cs.unusable)
3580                 return false;
3581         if (~cs.type & (AR_TYPE_CODE_MASK|AR_TYPE_ACCESSES_MASK))
3582                 return false;
3583         if (!cs.s)
3584                 return false;
3585         if (cs.type & AR_TYPE_WRITEABLE_MASK) {
3586                 if (cs.dpl > cs_rpl)
3587                         return false;
3588         } else {
3589                 if (cs.dpl != cs_rpl)
3590                         return false;
3591         }
3592         if (!cs.present)
3593                 return false;
3594
3595         /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
3596         return true;
3597 }
3598
3599 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
3600 {
3601         struct kvm_segment ss;
3602         unsigned int ss_rpl;
3603
3604         vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3605         ss_rpl = ss.selector & SELECTOR_RPL_MASK;
3606
3607         if (ss.unusable)
3608                 return true;
3609         if (ss.type != 3 && ss.type != 7)
3610                 return false;
3611         if (!ss.s)
3612                 return false;
3613         if (ss.dpl != ss_rpl) /* DPL != RPL */
3614                 return false;
3615         if (!ss.present)
3616                 return false;
3617
3618         return true;
3619 }
3620
3621 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
3622 {
3623         struct kvm_segment var;
3624         unsigned int rpl;
3625
3626         vmx_get_segment(vcpu, &var, seg);
3627         rpl = var.selector & SELECTOR_RPL_MASK;
3628
3629         if (var.unusable)
3630                 return true;
3631         if (!var.s)
3632                 return false;
3633         if (!var.present)
3634                 return false;
3635         if (~var.type & (AR_TYPE_CODE_MASK|AR_TYPE_WRITEABLE_MASK)) {
3636                 if (var.dpl < rpl) /* DPL < RPL */
3637                         return false;
3638         }
3639
3640         /* TODO: Add other members to kvm_segment_field to allow checking for other access
3641          * rights flags
3642          */
3643         return true;
3644 }
3645
3646 static bool tr_valid(struct kvm_vcpu *vcpu)
3647 {
3648         struct kvm_segment tr;
3649
3650         vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
3651
3652         if (tr.unusable)
3653                 return false;
3654         if (tr.selector & SELECTOR_TI_MASK)     /* TI = 1 */
3655                 return false;
3656         if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
3657                 return false;
3658         if (!tr.present)
3659                 return false;
3660
3661         return true;
3662 }
3663
3664 static bool ldtr_valid(struct kvm_vcpu *vcpu)
3665 {
3666         struct kvm_segment ldtr;
3667
3668         vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
3669
3670         if (ldtr.unusable)
3671                 return true;
3672         if (ldtr.selector & SELECTOR_TI_MASK)   /* TI = 1 */
3673                 return false;
3674         if (ldtr.type != 2)
3675                 return false;
3676         if (!ldtr.present)
3677                 return false;
3678
3679         return true;
3680 }
3681
3682 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
3683 {
3684         struct kvm_segment cs, ss;
3685
3686         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3687         vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3688
3689         return ((cs.selector & SELECTOR_RPL_MASK) ==
3690                  (ss.selector & SELECTOR_RPL_MASK));
3691 }
3692
3693 /*
3694  * Check if guest state is valid. Returns true if valid, false if
3695  * not.
3696  * We assume that registers are always usable
3697  */
3698 static bool guest_state_valid(struct kvm_vcpu *vcpu)
3699 {
3700         if (enable_unrestricted_guest)
3701                 return true;
3702
3703         /* real mode guest state checks */
3704         if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
3705                 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
3706                         return false;
3707                 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
3708                         return false;
3709                 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
3710                         return false;
3711                 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
3712                         return false;
3713                 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
3714                         return false;
3715                 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
3716                         return false;
3717         } else {
3718         /* protected mode guest state checks */
3719                 if (!cs_ss_rpl_check(vcpu))
3720                         return false;
3721                 if (!code_segment_valid(vcpu))
3722                         return false;
3723                 if (!stack_segment_valid(vcpu))
3724                         return false;
3725                 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
3726                         return false;
3727                 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
3728                         return false;
3729                 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
3730                         return false;
3731                 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
3732                         return false;
3733                 if (!tr_valid(vcpu))
3734                         return false;
3735                 if (!ldtr_valid(vcpu))
3736                         return false;
3737         }
3738         /* TODO:
3739          * - Add checks on RIP
3740          * - Add checks on RFLAGS
3741          */
3742
3743         return true;
3744 }
3745
3746 static int init_rmode_tss(struct kvm *kvm)
3747 {
3748         gfn_t fn;
3749         u16 data = 0;
3750         int r, idx, ret = 0;
3751
3752         idx = srcu_read_lock(&kvm->srcu);
3753         fn = kvm->arch.tss_addr >> PAGE_SHIFT;
3754         r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3755         if (r < 0)
3756                 goto out;
3757         data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
3758         r = kvm_write_guest_page(kvm, fn++, &data,
3759                         TSS_IOPB_BASE_OFFSET, sizeof(u16));
3760         if (r < 0)
3761                 goto out;
3762         r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
3763         if (r < 0)
3764                 goto out;
3765         r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3766         if (r < 0)
3767                 goto out;
3768         data = ~0;
3769         r = kvm_write_guest_page(kvm, fn, &data,
3770                                  RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
3771                                  sizeof(u8));
3772         if (r < 0)
3773                 goto out;
3774
3775         ret = 1;
3776 out:
3777         srcu_read_unlock(&kvm->srcu, idx);
3778         return ret;
3779 }
3780
3781 static int init_rmode_identity_map(struct kvm *kvm)
3782 {
3783         int i, idx, r, ret;
3784         pfn_t identity_map_pfn;
3785         u32 tmp;
3786
3787         if (!enable_ept)
3788                 return 1;
3789         if (unlikely(!kvm->arch.ept_identity_pagetable)) {
3790                 printk(KERN_ERR "EPT: identity-mapping pagetable "
3791                         "haven't been allocated!\n");
3792                 return 0;
3793         }
3794         if (likely(kvm->arch.ept_identity_pagetable_done))
3795                 return 1;
3796         ret = 0;
3797         identity_map_pfn = kvm->arch.ept_identity_map_addr >> PAGE_SHIFT;
3798         idx = srcu_read_lock(&kvm->srcu);
3799         r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
3800         if (r < 0)
3801                 goto out;
3802         /* Set up identity-mapping pagetable for EPT in real mode */
3803         for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
3804                 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
3805                         _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
3806                 r = kvm_write_guest_page(kvm, identity_map_pfn,
3807                                 &tmp, i * sizeof(tmp), sizeof(tmp));
3808                 if (r < 0)
3809                         goto out;
3810         }
3811         kvm->arch.ept_identity_pagetable_done = true;
3812         ret = 1;
3813 out:
3814         srcu_read_unlock(&kvm->srcu, idx);
3815         return ret;
3816 }
3817
3818 static void seg_setup(int seg)
3819 {
3820         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3821         unsigned int ar;
3822
3823         vmcs_write16(sf->selector, 0);
3824         vmcs_writel(sf->base, 0);
3825         vmcs_write32(sf->limit, 0xffff);
3826         ar = 0x93;
3827         if (seg == VCPU_SREG_CS)
3828                 ar |= 0x08; /* code segment */
3829
3830         vmcs_write32(sf->ar_bytes, ar);
3831 }
3832
3833 static int alloc_apic_access_page(struct kvm *kvm)
3834 {
3835         struct page *page;
3836         struct kvm_userspace_memory_region kvm_userspace_mem;
3837         int r = 0;
3838
3839         mutex_lock(&kvm->slots_lock);
3840         if (kvm->arch.apic_access_page)
3841                 goto out;
3842         kvm_userspace_mem.slot = APIC_ACCESS_PAGE_PRIVATE_MEMSLOT;
3843         kvm_userspace_mem.flags = 0;
3844         kvm_userspace_mem.guest_phys_addr = 0xfee00000ULL;
3845         kvm_userspace_mem.memory_size = PAGE_SIZE;
3846         r = __kvm_set_memory_region(kvm, &kvm_userspace_mem);
3847         if (r)
3848                 goto out;
3849
3850         page = gfn_to_page(kvm, 0xfee00);
3851         if (is_error_page(page)) {
3852                 r = -EFAULT;
3853                 goto out;
3854         }
3855
3856         kvm->arch.apic_access_page = page;
3857 out:
3858         mutex_unlock(&kvm->slots_lock);
3859         return r;
3860 }
3861
3862 static int alloc_identity_pagetable(struct kvm *kvm)
3863 {
3864         struct page *page;
3865         struct kvm_userspace_memory_region kvm_userspace_mem;
3866         int r = 0;
3867
3868         mutex_lock(&kvm->slots_lock);
3869         if (kvm->arch.ept_identity_pagetable)
3870                 goto out;
3871         kvm_userspace_mem.slot = IDENTITY_PAGETABLE_PRIVATE_MEMSLOT;
3872         kvm_userspace_mem.flags = 0;
3873         kvm_userspace_mem.guest_phys_addr =
3874                 kvm->arch.ept_identity_map_addr;
3875         kvm_userspace_mem.memory_size = PAGE_SIZE;
3876         r = __kvm_set_memory_region(kvm, &kvm_userspace_mem);
3877         if (r)
3878                 goto out;
3879
3880         page = gfn_to_page(kvm, kvm->arch.ept_identity_map_addr >> PAGE_SHIFT);
3881         if (is_error_page(page)) {
3882                 r = -EFAULT;
3883                 goto out;
3884         }
3885
3886         kvm->arch.ept_identity_pagetable = page;
3887 out:
3888         mutex_unlock(&kvm->slots_lock);
3889         return r;
3890 }
3891
3892 static void allocate_vpid(struct vcpu_vmx *vmx)
3893 {
3894         int vpid;
3895
3896         vmx->vpid = 0;
3897         if (!enable_vpid)
3898                 return;
3899         spin_lock(&vmx_vpid_lock);
3900         vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
3901         if (vpid < VMX_NR_VPIDS) {
3902                 vmx->vpid = vpid;
3903                 __set_bit(vpid, vmx_vpid_bitmap);
3904         }
3905         spin_unlock(&vmx_vpid_lock);
3906 }
3907
3908 static void free_vpid(struct vcpu_vmx *vmx)
3909 {
3910         if (!enable_vpid)
3911                 return;
3912         spin_lock(&vmx_vpid_lock);
3913         if (vmx->vpid != 0)
3914                 __clear_bit(vmx->vpid, vmx_vpid_bitmap);
3915         spin_unlock(&vmx_vpid_lock);
3916 }
3917
3918 #define MSR_TYPE_R      1
3919 #define MSR_TYPE_W      2
3920 static void __vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
3921                                                 u32 msr, int type)
3922 {
3923         int f = sizeof(unsigned long);
3924
3925         if (!cpu_has_vmx_msr_bitmap())
3926                 return;
3927
3928         /*
3929          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
3930          * have the write-low and read-high bitmap offsets the wrong way round.
3931          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
3932          */
3933         if (msr <= 0x1fff) {
3934                 if (type & MSR_TYPE_R)
3935                         /* read-low */
3936                         __clear_bit(msr, msr_bitmap + 0x000 / f);
3937
3938                 if (type & MSR_TYPE_W)
3939                         /* write-low */
3940                         __clear_bit(msr, msr_bitmap + 0x800 / f);
3941
3942         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
3943                 msr &= 0x1fff;
3944                 if (type & MSR_TYPE_R)
3945                         /* read-high */
3946                         __clear_bit(msr, msr_bitmap + 0x400 / f);
3947
3948                 if (type & MSR_TYPE_W)
3949                         /* write-high */
3950                         __clear_bit(msr, msr_bitmap + 0xc00 / f);
3951
3952         }
3953 }
3954
3955 static void __vmx_enable_intercept_for_msr(unsigned long *msr_bitmap,
3956                                                 u32 msr, int type)
3957 {
3958         int f = sizeof(unsigned long);
3959
3960         if (!cpu_has_vmx_msr_bitmap())
3961                 return;
3962
3963         /*
3964          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
3965          * have the write-low and read-high bitmap offsets the wrong way round.
3966          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
3967          */
3968         if (msr <= 0x1fff) {
3969                 if (type & MSR_TYPE_R)
3970                         /* read-low */
3971                         __set_bit(msr, msr_bitmap + 0x000 / f);
3972
3973                 if (type & MSR_TYPE_W)
3974                         /* write-low */
3975                         __set_bit(msr, msr_bitmap + 0x800 / f);
3976
3977         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
3978                 msr &= 0x1fff;
3979                 if (type & MSR_TYPE_R)
3980                         /* read-high */
3981                         __set_bit(msr, msr_bitmap + 0x400 / f);
3982
3983                 if (type & MSR_TYPE_W)
3984                         /* write-high */
3985                         __set_bit(msr, msr_bitmap + 0xc00 / f);
3986
3987         }
3988 }
3989
3990 static void vmx_disable_intercept_for_msr(u32 msr, bool longmode_only)
3991 {
3992         if (!longmode_only)
3993                 __vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy,
3994                                                 msr, MSR_TYPE_R | MSR_TYPE_W);
3995         __vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode,
3996                                                 msr, MSR_TYPE_R | MSR_TYPE_W);
3997 }
3998
3999 static void vmx_enable_intercept_msr_read_x2apic(u32 msr)
4000 {
4001         __vmx_enable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic,
4002                         msr, MSR_TYPE_R);
4003         __vmx_enable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic,
4004                         msr, MSR_TYPE_R);
4005 }
4006
4007 static void vmx_disable_intercept_msr_read_x2apic(u32 msr)
4008 {
4009         __vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic,
4010                         msr, MSR_TYPE_R);
4011         __vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic,
4012                         msr, MSR_TYPE_R);
4013 }
4014
4015 static void vmx_disable_intercept_msr_write_x2apic(u32 msr)
4016 {
4017         __vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic,
4018                         msr, MSR_TYPE_W);
4019         __vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic,
4020                         msr, MSR_TYPE_W);
4021 }
4022
4023 static int vmx_vm_has_apicv(struct kvm *kvm)
4024 {
4025         return enable_apicv && irqchip_in_kernel(kvm);
4026 }
4027
4028 /*
4029  * Send interrupt to vcpu via posted interrupt way.
4030  * 1. If target vcpu is running(non-root mode), send posted interrupt
4031  * notification to vcpu and hardware will sync PIR to vIRR atomically.
4032  * 2. If target vcpu isn't running(root mode), kick it to pick up the
4033  * interrupt from PIR in next vmentry.
4034  */
4035 static void vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
4036 {
4037         struct vcpu_vmx *vmx = to_vmx(vcpu);
4038         int r;
4039
4040         if (pi_test_and_set_pir(vector, &vmx->pi_desc))
4041                 return;
4042
4043         r = pi_test_and_set_on(&vmx->pi_desc);
4044         kvm_make_request(KVM_REQ_EVENT, vcpu);
4045 #ifdef CONFIG_SMP
4046         if (!r && (vcpu->mode == IN_GUEST_MODE))
4047                 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu),
4048                                 POSTED_INTR_VECTOR);
4049         else
4050 #endif
4051                 kvm_vcpu_kick(vcpu);
4052 }
4053
4054 static void vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
4055 {
4056         struct vcpu_vmx *vmx = to_vmx(vcpu);
4057
4058         if (!pi_test_and_clear_on(&vmx->pi_desc))
4059                 return;
4060
4061         kvm_apic_update_irr(vcpu, vmx->pi_desc.pir);
4062 }
4063
4064 static void vmx_sync_pir_to_irr_dummy(struct kvm_vcpu *vcpu)
4065 {
4066         return;
4067 }
4068
4069 /*
4070  * Set up the vmcs's constant host-state fields, i.e., host-state fields that
4071  * will not change in the lifetime of the guest.
4072  * Note that host-state that does change is set elsewhere. E.g., host-state
4073  * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
4074  */
4075 static void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
4076 {
4077         u32 low32, high32;
4078         unsigned long tmpl;
4079         struct desc_ptr dt;
4080         unsigned long cr4;
4081
4082         vmcs_writel(HOST_CR0, read_cr0() & ~X86_CR0_TS);  /* 22.2.3 */
4083         vmcs_writel(HOST_CR3, read_cr3());  /* 22.2.3  FIXME: shadow tables */
4084
4085         /* Save the most likely value for this task's CR4 in the VMCS. */
4086         cr4 = read_cr4();
4087         vmcs_writel(HOST_CR4, cr4);                     /* 22.2.3, 22.2.5 */
4088         vmx->host_state.vmcs_host_cr4 = cr4;
4089
4090         vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS);  /* 22.2.4 */
4091 #ifdef CONFIG_X86_64
4092         /*
4093          * Load null selectors, so we can avoid reloading them in
4094          * __vmx_load_host_state(), in case userspace uses the null selectors
4095          * too (the expected case).
4096          */
4097         vmcs_write16(HOST_DS_SELECTOR, 0);
4098         vmcs_write16(HOST_ES_SELECTOR, 0);
4099 #else
4100         vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
4101         vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
4102 #endif
4103         vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
4104         vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8);  /* 22.2.4 */
4105
4106         native_store_idt(&dt);
4107         vmcs_writel(HOST_IDTR_BASE, dt.address);   /* 22.2.4 */
4108         vmx->host_idt_base = dt.address;
4109
4110         vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */
4111
4112         rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
4113         vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
4114         rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
4115         vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl);   /* 22.2.3 */
4116
4117         if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
4118                 rdmsr(MSR_IA32_CR_PAT, low32, high32);
4119                 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
4120         }
4121 }
4122
4123 static void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
4124 {
4125         vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
4126         if (enable_ept)
4127                 vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
4128         if (is_guest_mode(&vmx->vcpu))
4129                 vmx->vcpu.arch.cr4_guest_owned_bits &=
4130                         ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
4131         vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
4132 }
4133
4134 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
4135 {
4136         u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
4137
4138         if (!vmx_vm_has_apicv(vmx->vcpu.kvm))
4139                 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
4140         return pin_based_exec_ctrl;
4141 }
4142
4143 static u32 vmx_exec_control(struct vcpu_vmx *vmx)
4144 {
4145         u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
4146         if (!vm_need_tpr_shadow(vmx->vcpu.kvm)) {
4147                 exec_control &= ~CPU_BASED_TPR_SHADOW;
4148 #ifdef CONFIG_X86_64
4149                 exec_control |= CPU_BASED_CR8_STORE_EXITING |
4150                                 CPU_BASED_CR8_LOAD_EXITING;
4151 #endif
4152         }
4153         if (!enable_ept)
4154                 exec_control |= CPU_BASED_CR3_STORE_EXITING |
4155                                 CPU_BASED_CR3_LOAD_EXITING  |
4156                                 CPU_BASED_INVLPG_EXITING;
4157         return exec_control;
4158 }
4159
4160 static u32 vmx_secondary_exec_control(struct vcpu_vmx *vmx)
4161 {
4162         u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
4163         if (!vm_need_virtualize_apic_accesses(vmx->vcpu.kvm))
4164                 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
4165         if (vmx->vpid == 0)
4166                 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
4167         if (!enable_ept) {
4168                 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
4169                 enable_unrestricted_guest = 0;
4170                 /* Enable INVPCID for non-ept guests may cause performance regression. */
4171                 exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
4172         }
4173         if (!enable_unrestricted_guest)
4174                 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
4175         if (!ple_gap)
4176                 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
4177         if (!vmx_vm_has_apicv(vmx->vcpu.kvm))
4178                 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
4179                                   SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4180         exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
4181         /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
4182            (handle_vmptrld).
4183            We can NOT enable shadow_vmcs here because we don't have yet
4184            a current VMCS12
4185         */
4186         exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
4187         return exec_control;
4188 }
4189
4190 static void ept_set_mmio_spte_mask(void)
4191 {
4192         /*
4193          * EPT Misconfigurations can be generated if the value of bits 2:0
4194          * of an EPT paging-structure entry is 110b (write/execute).
4195          * Also, magic bits (0xffull << 49) is set to quickly identify mmio
4196          * spte.
4197          */
4198         kvm_mmu_set_mmio_spte_mask(0xffull << 49 | 0x6ull);
4199 }
4200
4201 /*
4202  * Sets up the vmcs for emulated real mode.
4203  */
4204 static int vmx_vcpu_setup(struct vcpu_vmx *vmx)
4205 {
4206 #ifdef CONFIG_X86_64
4207         unsigned long a;
4208 #endif
4209         int i;
4210
4211         /* I/O */
4212         vmcs_write64(IO_BITMAP_A, __pa(vmx_io_bitmap_a));
4213         vmcs_write64(IO_BITMAP_B, __pa(vmx_io_bitmap_b));
4214
4215         if (enable_shadow_vmcs) {
4216                 vmcs_write64(VMREAD_BITMAP, __pa(vmx_vmread_bitmap));
4217                 vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmwrite_bitmap));
4218         }
4219         if (cpu_has_vmx_msr_bitmap())
4220                 vmcs_write64(MSR_BITMAP, __pa(vmx_msr_bitmap_legacy));
4221
4222         vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
4223
4224         /* Control */
4225         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
4226
4227         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
4228
4229         if (cpu_has_secondary_exec_ctrls()) {
4230                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
4231                                 vmx_secondary_exec_control(vmx));
4232         }
4233
4234         if (vmx_vm_has_apicv(vmx->vcpu.kvm)) {
4235                 vmcs_write64(EOI_EXIT_BITMAP0, 0);
4236                 vmcs_write64(EOI_EXIT_BITMAP1, 0);
4237                 vmcs_write64(EOI_EXIT_BITMAP2, 0);
4238                 vmcs_write64(EOI_EXIT_BITMAP3, 0);
4239
4240                 vmcs_write16(GUEST_INTR_STATUS, 0);
4241
4242                 vmcs_write64(POSTED_INTR_NV, POSTED_INTR_VECTOR);
4243                 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
4244         }
4245
4246         if (ple_gap) {
4247                 vmcs_write32(PLE_GAP, ple_gap);
4248                 vmcs_write32(PLE_WINDOW, ple_window);
4249         }
4250
4251         vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
4252         vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
4253         vmcs_write32(CR3_TARGET_COUNT, 0);           /* 22.2.1 */
4254
4255         vmcs_write16(HOST_FS_SELECTOR, 0);            /* 22.2.4 */
4256         vmcs_write16(HOST_GS_SELECTOR, 0);            /* 22.2.4 */
4257         vmx_set_constant_host_state(vmx);
4258 #ifdef CONFIG_X86_64
4259         rdmsrl(MSR_FS_BASE, a);
4260         vmcs_writel(HOST_FS_BASE, a); /* 22.2.4 */
4261         rdmsrl(MSR_GS_BASE, a);
4262         vmcs_writel(HOST_GS_BASE, a); /* 22.2.4 */
4263 #else
4264         vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
4265         vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
4266 #endif
4267
4268         vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
4269         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
4270         vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host));
4271         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
4272         vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest));
4273
4274         if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
4275                 u32 msr_low, msr_high;
4276                 u64 host_pat;
4277                 rdmsr(MSR_IA32_CR_PAT, msr_low, msr_high);
4278                 host_pat = msr_low | ((u64) msr_high << 32);
4279                 /* Write the default value follow host pat */
4280                 vmcs_write64(GUEST_IA32_PAT, host_pat);
4281                 /* Keep arch.pat sync with GUEST_IA32_PAT */
4282                 vmx->vcpu.arch.pat = host_pat;
4283         }
4284
4285         for (i = 0; i < NR_VMX_MSR; ++i) {
4286                 u32 index = vmx_msr_index[i];
4287                 u32 data_low, data_high;
4288                 int j = vmx->nmsrs;
4289
4290                 if (rdmsr_safe(index, &data_low, &data_high) < 0)
4291                         continue;
4292                 if (wrmsr_safe(index, data_low, data_high) < 0)
4293                         continue;
4294                 vmx->guest_msrs[j].index = i;
4295                 vmx->guest_msrs[j].data = 0;
4296                 vmx->guest_msrs[j].mask = -1ull;
4297                 ++vmx->nmsrs;
4298         }
4299
4300         vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);
4301
4302         /* 22.2.1, 20.8.1 */
4303         vmcs_write32(VM_ENTRY_CONTROLS, vmcs_config.vmentry_ctrl);
4304
4305         vmcs_writel(CR0_GUEST_HOST_MASK, ~0UL);
4306         set_cr4_guest_host_mask(vmx);
4307
4308         return 0;
4309 }
4310
4311 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu)
4312 {
4313         struct vcpu_vmx *vmx = to_vmx(vcpu);
4314         u64 msr;
4315
4316         vmx->rmode.vm86_active = 0;
4317
4318         vmx->soft_vnmi_blocked = 0;
4319
4320         vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
4321         kvm_set_cr8(&vmx->vcpu, 0);
4322         msr = 0xfee00000 | MSR_IA32_APICBASE_ENABLE;
4323         if (kvm_vcpu_is_bsp(&vmx->vcpu))
4324                 msr |= MSR_IA32_APICBASE_BSP;
4325         kvm_set_apic_base(&vmx->vcpu, msr);
4326
4327         vmx_segment_cache_clear(vmx);
4328
4329         seg_setup(VCPU_SREG_CS);
4330         vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
4331         vmcs_write32(GUEST_CS_BASE, 0xffff0000);
4332
4333         seg_setup(VCPU_SREG_DS);
4334         seg_setup(VCPU_SREG_ES);
4335         seg_setup(VCPU_SREG_FS);
4336         seg_setup(VCPU_SREG_GS);
4337         seg_setup(VCPU_SREG_SS);
4338
4339         vmcs_write16(GUEST_TR_SELECTOR, 0);
4340         vmcs_writel(GUEST_TR_BASE, 0);
4341         vmcs_write32(GUEST_TR_LIMIT, 0xffff);
4342         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4343
4344         vmcs_write16(GUEST_LDTR_SELECTOR, 0);
4345         vmcs_writel(GUEST_LDTR_BASE, 0);
4346         vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
4347         vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
4348
4349         vmcs_write32(GUEST_SYSENTER_CS, 0);
4350         vmcs_writel(GUEST_SYSENTER_ESP, 0);
4351         vmcs_writel(GUEST_SYSENTER_EIP, 0);
4352
4353         vmcs_writel(GUEST_RFLAGS, 0x02);
4354         kvm_rip_write(vcpu, 0xfff0);
4355
4356         vmcs_writel(GUEST_GDTR_BASE, 0);
4357         vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
4358
4359         vmcs_writel(GUEST_IDTR_BASE, 0);
4360         vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
4361
4362         vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
4363         vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
4364         vmcs_write32(GUEST_PENDING_DBG_EXCEPTIONS, 0);
4365
4366         /* Special registers */
4367         vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
4368
4369         setup_msrs(vmx);
4370
4371         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);  /* 22.2.1 */
4372
4373         if (cpu_has_vmx_tpr_shadow()) {
4374                 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
4375                 if (vm_need_tpr_shadow(vmx->vcpu.kvm))
4376                         vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
4377                                      __pa(vmx->vcpu.arch.apic->regs));
4378                 vmcs_write32(TPR_THRESHOLD, 0);
4379         }
4380
4381         if (vm_need_virtualize_apic_accesses(vmx->vcpu.kvm))
4382                 vmcs_write64(APIC_ACCESS_ADDR,
4383                              page_to_phys(vmx->vcpu.kvm->arch.apic_access_page));
4384
4385         if (vmx_vm_has_apicv(vcpu->kvm))
4386                 memset(&vmx->pi_desc, 0, sizeof(struct pi_desc));
4387
4388         if (vmx->vpid != 0)
4389                 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
4390
4391         vmx->vcpu.arch.cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
4392         vmx_set_cr0(&vmx->vcpu, kvm_read_cr0(vcpu)); /* enter rmode */
4393         vmx_set_cr4(&vmx->vcpu, 0);
4394         vmx_set_efer(&vmx->vcpu, 0);
4395         vmx_fpu_activate(&vmx->vcpu);
4396         update_exception_bitmap(&vmx->vcpu);
4397
4398         vpid_sync_context(vmx);
4399 }
4400
4401 /*
4402  * In nested virtualization, check if L1 asked to exit on external interrupts.
4403  * For most existing hypervisors, this will always return true.
4404  */
4405 static bool nested_exit_on_intr(struct kvm_vcpu *vcpu)
4406 {
4407         return get_vmcs12(vcpu)->pin_based_vm_exec_control &
4408                 PIN_BASED_EXT_INTR_MASK;
4409 }
4410
4411 static bool nested_exit_on_nmi(struct kvm_vcpu *vcpu)
4412 {
4413         return get_vmcs12(vcpu)->pin_based_vm_exec_control &
4414                 PIN_BASED_NMI_EXITING;
4415 }
4416
4417 static int enable_irq_window(struct kvm_vcpu *vcpu)
4418 {
4419         u32 cpu_based_vm_exec_control;
4420
4421         if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
4422                 /*
4423                  * We get here if vmx_interrupt_allowed() said we can't
4424                  * inject to L1 now because L2 must run. The caller will have
4425                  * to make L2 exit right after entry, so we can inject to L1
4426                  * more promptly.
4427                  */
4428                 return -EBUSY;
4429
4430         cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
4431         cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_INTR_PENDING;
4432         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
4433         return 0;
4434 }
4435
4436 static int enable_nmi_window(struct kvm_vcpu *vcpu)
4437 {
4438         u32 cpu_based_vm_exec_control;
4439
4440         if (!cpu_has_virtual_nmis())
4441                 return enable_irq_window(vcpu);
4442
4443         if (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI)
4444                 return enable_irq_window(vcpu);
4445
4446         cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
4447         cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_NMI_PENDING;
4448         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
4449         return 0;
4450 }
4451
4452 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
4453 {
4454         struct vcpu_vmx *vmx = to_vmx(vcpu);
4455         uint32_t intr;
4456         int irq = vcpu->arch.interrupt.nr;
4457
4458         trace_kvm_inj_virq(irq);
4459
4460         ++vcpu->stat.irq_injections;
4461         if (vmx->rmode.vm86_active) {
4462                 int inc_eip = 0;
4463                 if (vcpu->arch.interrupt.soft)
4464                         inc_eip = vcpu->arch.event_exit_inst_len;
4465                 if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE)
4466                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
4467                 return;
4468         }
4469         intr = irq | INTR_INFO_VALID_MASK;
4470         if (vcpu->arch.interrupt.soft) {
4471                 intr |= INTR_TYPE_SOFT_INTR;
4472                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
4473                              vmx->vcpu.arch.event_exit_inst_len);
4474         } else
4475                 intr |= INTR_TYPE_EXT_INTR;
4476         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
4477 }
4478
4479 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
4480 {
4481         struct vcpu_vmx *vmx = to_vmx(vcpu);
4482
4483         if (is_guest_mode(vcpu))
4484                 return;
4485
4486         if (!cpu_has_virtual_nmis()) {
4487                 /*
4488                  * Tracking the NMI-blocked state in software is built upon
4489                  * finding the next open IRQ window. This, in turn, depends on
4490                  * well-behaving guests: They have to keep IRQs disabled at
4491                  * least as long as the NMI handler runs. Otherwise we may
4492                  * cause NMI nesting, maybe breaking the guest. But as this is
4493                  * highly unlikely, we can live with the residual risk.
4494                  */
4495                 vmx->soft_vnmi_blocked = 1;
4496                 vmx->vnmi_blocked_time = 0;
4497         }
4498
4499         ++vcpu->stat.nmi_injections;
4500         vmx->nmi_known_unmasked = false;
4501         if (vmx->rmode.vm86_active) {
4502                 if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE)
4503                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
4504                 return;
4505         }
4506         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
4507                         INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
4508 }
4509
4510 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
4511 {
4512         if (!cpu_has_virtual_nmis())
4513                 return to_vmx(vcpu)->soft_vnmi_blocked;
4514         if (to_vmx(vcpu)->nmi_known_unmasked)
4515                 return false;
4516         return vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
4517 }
4518
4519 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
4520 {
4521         struct vcpu_vmx *vmx = to_vmx(vcpu);
4522
4523         if (!cpu_has_virtual_nmis()) {
4524                 if (vmx->soft_vnmi_blocked != masked) {
4525                         vmx->soft_vnmi_blocked = masked;
4526                         vmx->vnmi_blocked_time = 0;
4527                 }
4528         } else {
4529                 vmx->nmi_known_unmasked = !masked;
4530                 if (masked)
4531                         vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
4532                                       GUEST_INTR_STATE_NMI);
4533                 else
4534                         vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
4535                                         GUEST_INTR_STATE_NMI);
4536         }
4537 }
4538
4539 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
4540 {
4541         if (is_guest_mode(vcpu)) {
4542                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4543
4544                 if (to_vmx(vcpu)->nested.nested_run_pending)
4545                         return 0;
4546                 if (nested_exit_on_nmi(vcpu)) {
4547                         nested_vmx_vmexit(vcpu);
4548                         vmcs12->vm_exit_reason = EXIT_REASON_EXCEPTION_NMI;
4549                         vmcs12->vm_exit_intr_info = NMI_VECTOR |
4550                                 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK;
4551                         /*
4552                          * The NMI-triggered VM exit counts as injection:
4553                          * clear this one and block further NMIs.
4554                          */
4555                         vcpu->arch.nmi_pending = 0;
4556                         vmx_set_nmi_mask(vcpu, true);
4557                         return 0;
4558                 }
4559         }
4560
4561         if (!cpu_has_virtual_nmis() && to_vmx(vcpu)->soft_vnmi_blocked)
4562                 return 0;
4563
4564         return  !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4565                   (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
4566                    | GUEST_INTR_STATE_NMI));
4567 }
4568
4569 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
4570 {
4571         if (is_guest_mode(vcpu)) {
4572                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4573
4574                 if (to_vmx(vcpu)->nested.nested_run_pending)
4575                         return 0;
4576                 if (nested_exit_on_intr(vcpu)) {
4577                         nested_vmx_vmexit(vcpu);
4578                         vmcs12->vm_exit_reason =
4579                                 EXIT_REASON_EXTERNAL_INTERRUPT;
4580                         vmcs12->vm_exit_intr_info = 0;
4581                         /*
4582                          * fall through to normal code, but now in L1, not L2
4583                          */
4584                 }
4585         }
4586
4587         return (vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
4588                 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4589                         (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
4590 }
4591
4592 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
4593 {
4594         int ret;
4595         struct kvm_userspace_memory_region tss_mem = {
4596                 .slot = TSS_PRIVATE_MEMSLOT,
4597                 .guest_phys_addr = addr,
4598                 .memory_size = PAGE_SIZE * 3,
4599                 .flags = 0,
4600         };
4601
4602         ret = kvm_set_memory_region(kvm, &tss_mem);
4603         if (ret)
4604                 return ret;
4605         kvm->arch.tss_addr = addr;
4606         if (!init_rmode_tss(kvm))
4607                 return  -ENOMEM;
4608
4609         return 0;
4610 }
4611
4612 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
4613 {
4614         switch (vec) {
4615         case BP_VECTOR:
4616                 /*
4617                  * Update instruction length as we may reinject the exception
4618                  * from user space while in guest debugging mode.
4619                  */
4620                 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
4621                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4622                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
4623                         return false;
4624                 /* fall through */
4625         case DB_VECTOR:
4626                 if (vcpu->guest_debug &
4627                         (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
4628                         return false;
4629                 /* fall through */
4630         case DE_VECTOR:
4631         case OF_VECTOR:
4632         case BR_VECTOR:
4633         case UD_VECTOR:
4634         case DF_VECTOR:
4635         case SS_VECTOR:
4636         case GP_VECTOR:
4637         case MF_VECTOR:
4638                 return true;
4639         break;
4640         }
4641         return false;
4642 }
4643
4644 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
4645                                   int vec, u32 err_code)
4646 {
4647         /*
4648          * Instruction with address size override prefix opcode 0x67
4649          * Cause the #SS fault with 0 error code in VM86 mode.
4650          */
4651         if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
4652                 if (emulate_instruction(vcpu, 0) == EMULATE_DONE) {
4653                         if (vcpu->arch.halt_request) {
4654                                 vcpu->arch.halt_request = 0;
4655                                 return kvm_emulate_halt(vcpu);
4656                         }
4657                         return 1;
4658                 }
4659                 return 0;
4660         }
4661
4662         /*
4663          * Forward all other exceptions that are valid in real mode.
4664          * FIXME: Breaks guest debugging in real mode, needs to be fixed with
4665          *        the required debugging infrastructure rework.
4666          */
4667         kvm_queue_exception(vcpu, vec);
4668         return 1;
4669 }
4670
4671 /*
4672  * Trigger machine check on the host. We assume all the MSRs are already set up
4673  * by the CPU and that we still run on the same CPU as the MCE occurred on.
4674  * We pass a fake environment to the machine check handler because we want
4675  * the guest to be always treated like user space, no matter what context
4676  * it used internally.
4677  */
4678 static void kvm_machine_check(void)
4679 {
4680 #if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
4681         struct pt_regs regs = {
4682                 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
4683                 .flags = X86_EFLAGS_IF,
4684         };
4685
4686         do_machine_check(&regs, 0);
4687 #endif
4688 }
4689
4690 static int handle_machine_check(struct kvm_vcpu *vcpu)
4691 {
4692         /* already handled by vcpu_run */
4693         return 1;
4694 }
4695
4696 static int handle_exception(struct kvm_vcpu *vcpu)
4697 {
4698         struct vcpu_vmx *vmx = to_vmx(vcpu);
4699         struct kvm_run *kvm_run = vcpu->run;
4700         u32 intr_info, ex_no, error_code;
4701         unsigned long cr2, rip, dr6;
4702         u32 vect_info;
4703         enum emulation_result er;
4704
4705         vect_info = vmx->idt_vectoring_info;
4706         intr_info = vmx->exit_intr_info;
4707
4708         if (is_machine_check(intr_info))
4709                 return handle_machine_check(vcpu);
4710
4711         if ((intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR)
4712                 return 1;  /* already handled by vmx_vcpu_run() */
4713
4714         if (is_no_device(intr_info)) {
4715                 vmx_fpu_activate(vcpu);
4716                 return 1;
4717         }
4718
4719         if (is_invalid_opcode(intr_info)) {
4720                 er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD);
4721                 if (er != EMULATE_DONE)
4722                         kvm_queue_exception(vcpu, UD_VECTOR);
4723                 return 1;
4724         }
4725
4726         error_code = 0;
4727         if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
4728                 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
4729
4730         /*
4731          * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
4732          * MMIO, it is better to report an internal error.
4733          * See the comments in vmx_handle_exit.
4734          */
4735         if ((vect_info & VECTORING_INFO_VALID_MASK) &&
4736             !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
4737                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4738                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
4739                 vcpu->run->internal.ndata = 2;
4740                 vcpu->run->internal.data[0] = vect_info;
4741                 vcpu->run->internal.data[1] = intr_info;
4742                 return 0;
4743         }
4744
4745         if (is_page_fault(intr_info)) {
4746                 /* EPT won't cause page fault directly */
4747                 BUG_ON(enable_ept);
4748                 cr2 = vmcs_readl(EXIT_QUALIFICATION);
4749                 trace_kvm_page_fault(cr2, error_code);
4750
4751                 if (kvm_event_needs_reinjection(vcpu))
4752                         kvm_mmu_unprotect_page_virt(vcpu, cr2);
4753                 return kvm_mmu_page_fault(vcpu, cr2, error_code, NULL, 0);
4754         }
4755
4756         ex_no = intr_info & INTR_INFO_VECTOR_MASK;
4757
4758         if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
4759                 return handle_rmode_exception(vcpu, ex_no, error_code);
4760
4761         switch (ex_no) {
4762         case DB_VECTOR:
4763                 dr6 = vmcs_readl(EXIT_QUALIFICATION);
4764                 if (!(vcpu->guest_debug &
4765                       (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
4766                         vcpu->arch.dr6 = dr6 | DR6_FIXED_1;
4767                         kvm_queue_exception(vcpu, DB_VECTOR);
4768                         return 1;
4769                 }
4770                 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
4771                 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
4772                 /* fall through */
4773         case BP_VECTOR:
4774                 /*
4775                  * Update instruction length as we may reinject #BP from
4776                  * user space while in guest debugging mode. Reading it for
4777                  * #DB as well causes no harm, it is not used in that case.
4778                  */
4779                 vmx->vcpu.arch.event_exit_inst_len =
4780                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4781                 kvm_run->exit_reason = KVM_EXIT_DEBUG;
4782                 rip = kvm_rip_read(vcpu);
4783                 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
4784                 kvm_run->debug.arch.exception = ex_no;
4785                 break;
4786         default:
4787                 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
4788                 kvm_run->ex.exception = ex_no;
4789                 kvm_run->ex.error_code = error_code;
4790                 break;
4791         }
4792         return 0;
4793 }
4794
4795 static int handle_external_interrupt(struct kvm_vcpu *vcpu)
4796 {
4797         ++vcpu->stat.irq_exits;
4798         return 1;
4799 }
4800
4801 static int handle_triple_fault(struct kvm_vcpu *vcpu)
4802 {
4803         vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
4804         return 0;
4805 }
4806
4807 static int handle_io(struct kvm_vcpu *vcpu)
4808 {
4809         unsigned long exit_qualification;
4810         int size, in, string;
4811         unsigned port;
4812
4813         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4814         string = (exit_qualification & 16) != 0;
4815         in = (exit_qualification & 8) != 0;
4816
4817         ++vcpu->stat.io_exits;
4818
4819         if (string || in)
4820                 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
4821
4822         port = exit_qualification >> 16;
4823         size = (exit_qualification & 7) + 1;
4824         skip_emulated_instruction(vcpu);
4825
4826         return kvm_fast_pio_out(vcpu, size, port);
4827 }
4828
4829 static void
4830 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
4831 {
4832         /*
4833          * Patch in the VMCALL instruction:
4834          */
4835         hypercall[0] = 0x0f;
4836         hypercall[1] = 0x01;
4837         hypercall[2] = 0xc1;
4838 }
4839
4840 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
4841 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
4842 {
4843         if (is_guest_mode(vcpu)) {
4844                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4845                 unsigned long orig_val = val;
4846
4847                 /*
4848                  * We get here when L2 changed cr0 in a way that did not change
4849                  * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
4850                  * but did change L0 shadowed bits. So we first calculate the
4851                  * effective cr0 value that L1 would like to write into the
4852                  * hardware. It consists of the L2-owned bits from the new
4853                  * value combined with the L1-owned bits from L1's guest_cr0.
4854                  */
4855                 val = (val & ~vmcs12->cr0_guest_host_mask) |
4856                         (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
4857
4858                 /* TODO: will have to take unrestricted guest mode into
4859                  * account */
4860                 if ((val & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON)
4861                         return 1;
4862
4863                 if (kvm_set_cr0(vcpu, val))
4864                         return 1;
4865                 vmcs_writel(CR0_READ_SHADOW, orig_val);
4866                 return 0;
4867         } else {
4868                 if (to_vmx(vcpu)->nested.vmxon &&
4869                     ((val & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON))
4870                         return 1;
4871                 return kvm_set_cr0(vcpu, val);
4872         }
4873 }
4874
4875 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
4876 {
4877         if (is_guest_mode(vcpu)) {
4878                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4879                 unsigned long orig_val = val;
4880
4881                 /* analogously to handle_set_cr0 */
4882                 val = (val & ~vmcs12->cr4_guest_host_mask) |
4883                         (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
4884                 if (kvm_set_cr4(vcpu, val))
4885                         return 1;
4886                 vmcs_writel(CR4_READ_SHADOW, orig_val);
4887                 return 0;
4888         } else
4889                 return kvm_set_cr4(vcpu, val);
4890 }
4891
4892 /* called to set cr0 as approriate for clts instruction exit. */
4893 static void handle_clts(struct kvm_vcpu *vcpu)
4894 {
4895         if (is_guest_mode(vcpu)) {
4896                 /*
4897                  * We get here when L2 did CLTS, and L1 didn't shadow CR0.TS
4898                  * but we did (!fpu_active). We need to keep GUEST_CR0.TS on,
4899                  * just pretend it's off (also in arch.cr0 for fpu_activate).
4900                  */
4901                 vmcs_writel(CR0_READ_SHADOW,
4902                         vmcs_readl(CR0_READ_SHADOW) & ~X86_CR0_TS);
4903                 vcpu->arch.cr0 &= ~X86_CR0_TS;
4904         } else
4905                 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
4906 }
4907
4908 static int handle_cr(struct kvm_vcpu *vcpu)
4909 {
4910         unsigned long exit_qualification, val;
4911         int cr;
4912         int reg;
4913         int err;
4914
4915         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4916         cr = exit_qualification & 15;
4917         reg = (exit_qualification >> 8) & 15;
4918         switch ((exit_qualification >> 4) & 3) {
4919         case 0: /* mov to cr */
4920                 val = kvm_register_read(vcpu, reg);
4921                 trace_kvm_cr_write(cr, val);
4922                 switch (cr) {
4923                 case 0:
4924                         err = handle_set_cr0(vcpu, val);
4925                         kvm_complete_insn_gp(vcpu, err);
4926                         return 1;
4927                 case 3:
4928                         err = kvm_set_cr3(vcpu, val);
4929                         kvm_complete_insn_gp(vcpu, err);
4930                         return 1;
4931                 case 4:
4932                         err = handle_set_cr4(vcpu, val);
4933                         kvm_complete_insn_gp(vcpu, err);
4934                         return 1;
4935                 case 8: {
4936                                 u8 cr8_prev = kvm_get_cr8(vcpu);
4937                                 u8 cr8 = kvm_register_read(vcpu, reg);
4938                                 err = kvm_set_cr8(vcpu, cr8);
4939                                 kvm_complete_insn_gp(vcpu, err);
4940                                 if (irqchip_in_kernel(vcpu->kvm))
4941                                         return 1;
4942                                 if (cr8_prev <= cr8)
4943                                         return 1;
4944                                 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
4945                                 return 0;
4946                         }
4947                 }
4948                 break;
4949         case 2: /* clts */
4950                 handle_clts(vcpu);
4951                 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
4952                 skip_emulated_instruction(vcpu);
4953                 vmx_fpu_activate(vcpu);
4954                 return 1;
4955         case 1: /*mov from cr*/
4956                 switch (cr) {
4957                 case 3:
4958                         val = kvm_read_cr3(vcpu);
4959                         kvm_register_write(vcpu, reg, val);
4960                         trace_kvm_cr_read(cr, val);
4961                         skip_emulated_instruction(vcpu);
4962                         return 1;
4963                 case 8:
4964                         val = kvm_get_cr8(vcpu);
4965                         kvm_register_write(vcpu, reg, val);
4966                         trace_kvm_cr_read(cr, val);
4967                         skip_emulated_instruction(vcpu);
4968                         return 1;
4969                 }
4970                 break;
4971         case 3: /* lmsw */
4972                 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
4973                 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
4974                 kvm_lmsw(vcpu, val);
4975
4976                 skip_emulated_instruction(vcpu);
4977                 return 1;
4978         default:
4979                 break;
4980         }
4981         vcpu->run->exit_reason = 0;
4982         vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
4983                (int)(exit_qualification >> 4) & 3, cr);
4984         return 0;
4985 }
4986
4987 static int handle_dr(struct kvm_vcpu *vcpu)
4988 {
4989         unsigned long exit_qualification;
4990         int dr, reg;
4991
4992         /* Do not handle if the CPL > 0, will trigger GP on re-entry */
4993         if (!kvm_require_cpl(vcpu, 0))
4994                 return 1;
4995         dr = vmcs_readl(GUEST_DR7);
4996         if (dr & DR7_GD) {
4997                 /*
4998                  * As the vm-exit takes precedence over the debug trap, we
4999                  * need to emulate the latter, either for the host or the
5000                  * guest debugging itself.
5001                  */
5002                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
5003                         vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
5004                         vcpu->run->debug.arch.dr7 = dr;
5005                         vcpu->run->debug.arch.pc =
5006                                 vmcs_readl(GUEST_CS_BASE) +
5007                                 vmcs_readl(GUEST_RIP);
5008                         vcpu->run->debug.arch.exception = DB_VECTOR;
5009                         vcpu->run->exit_reason = KVM_EXIT_DEBUG;
5010                         return 0;
5011                 } else {
5012                         vcpu->arch.dr7 &= ~DR7_GD;
5013                         vcpu->arch.dr6 |= DR6_BD;
5014                         vmcs_writel(GUEST_DR7, vcpu->arch.dr7);
5015                         kvm_queue_exception(vcpu, DB_VECTOR);
5016                         return 1;
5017                 }
5018         }
5019
5020         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5021         dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
5022         reg = DEBUG_REG_ACCESS_REG(exit_qualification);
5023         if (exit_qualification & TYPE_MOV_FROM_DR) {
5024                 unsigned long val;
5025                 if (!kvm_get_dr(vcpu, dr, &val))
5026                         kvm_register_write(vcpu, reg, val);
5027         } else
5028                 kvm_set_dr(vcpu, dr, vcpu->arch.regs[reg]);
5029         skip_emulated_instruction(vcpu);
5030         return 1;
5031 }
5032
5033 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
5034 {
5035         vmcs_writel(GUEST_DR7, val);
5036 }
5037
5038 static int handle_cpuid(struct kvm_vcpu *vcpu)
5039 {
5040         kvm_emulate_cpuid(vcpu);
5041         return 1;
5042 }
5043
5044 static int handle_rdmsr(struct kvm_vcpu *vcpu)
5045 {
5046         u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
5047         u64 data;
5048
5049         if (vmx_get_msr(vcpu, ecx, &data)) {
5050                 trace_kvm_msr_read_ex(ecx);
5051                 kvm_inject_gp(vcpu, 0);
5052                 return 1;
5053         }
5054
5055         trace_kvm_msr_read(ecx, data);
5056
5057         /* FIXME: handling of bits 32:63 of rax, rdx */
5058         vcpu->arch.regs[VCPU_REGS_RAX] = data & -1u;
5059         vcpu->arch.regs[VCPU_REGS_RDX] = (data >> 32) & -1u;
5060         skip_emulated_instruction(vcpu);
5061         return 1;
5062 }
5063
5064 static int handle_wrmsr(struct kvm_vcpu *vcpu)
5065 {
5066         struct msr_data msr;
5067         u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
5068         u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
5069                 | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
5070
5071         msr.data = data;
5072         msr.index = ecx;
5073         msr.host_initiated = false;
5074         if (kvm_set_msr(vcpu, &msr) != 0) {
5075                 trace_kvm_msr_write_ex(ecx, data);
5076                 kvm_inject_gp(vcpu, 0);
5077                 return 1;
5078         }
5079
5080         trace_kvm_msr_write(ecx, data);
5081         skip_emulated_instruction(vcpu);
5082         return 1;
5083 }
5084
5085 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
5086 {
5087         kvm_make_request(KVM_REQ_EVENT, vcpu);
5088         return 1;
5089 }
5090
5091 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
5092 {
5093         u32 cpu_based_vm_exec_control;
5094
5095         /* clear pending irq */
5096         cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5097         cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
5098         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
5099
5100         kvm_make_request(KVM_REQ_EVENT, vcpu);
5101
5102         ++vcpu->stat.irq_window_exits;
5103
5104         /*
5105          * If the user space waits to inject interrupts, exit as soon as
5106          * possible
5107          */
5108         if (!irqchip_in_kernel(vcpu->kvm) &&
5109             vcpu->run->request_interrupt_window &&
5110             !kvm_cpu_has_interrupt(vcpu)) {
5111                 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
5112                 return 0;
5113         }
5114         return 1;
5115 }
5116
5117 static int handle_halt(struct kvm_vcpu *vcpu)
5118 {
5119         skip_emulated_instruction(vcpu);
5120         return kvm_emulate_halt(vcpu);
5121 }
5122
5123 static int handle_vmcall(struct kvm_vcpu *vcpu)
5124 {
5125         skip_emulated_instruction(vcpu);
5126         kvm_emulate_hypercall(vcpu);
5127         return 1;
5128 }
5129
5130 static int handle_invd(struct kvm_vcpu *vcpu)
5131 {
5132         return emulate_instruction(vcpu, 0) == EMULATE_DONE;
5133 }
5134
5135 static int handle_invlpg(struct kvm_vcpu *vcpu)
5136 {
5137         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5138
5139         kvm_mmu_invlpg(vcpu, exit_qualification);
5140         skip_emulated_instruction(vcpu);
5141         return 1;
5142 }
5143
5144 static int handle_rdpmc(struct kvm_vcpu *vcpu)
5145 {
5146         int err;
5147
5148         err = kvm_rdpmc(vcpu);
5149         kvm_complete_insn_gp(vcpu, err);
5150
5151         return 1;
5152 }
5153
5154 static int handle_wbinvd(struct kvm_vcpu *vcpu)
5155 {
5156         skip_emulated_instruction(vcpu);
5157         kvm_emulate_wbinvd(vcpu);
5158         return 1;
5159 }
5160
5161 static int handle_xsetbv(struct kvm_vcpu *vcpu)
5162 {
5163         u64 new_bv = kvm_read_edx_eax(vcpu);
5164         u32 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
5165
5166         if (kvm_set_xcr(vcpu, index, new_bv) == 0)
5167                 skip_emulated_instruction(vcpu);
5168         return 1;
5169 }
5170
5171 static int handle_apic_access(struct kvm_vcpu *vcpu)
5172 {
5173         if (likely(fasteoi)) {
5174                 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5175                 int access_type, offset;
5176
5177                 access_type = exit_qualification & APIC_ACCESS_TYPE;
5178                 offset = exit_qualification & APIC_ACCESS_OFFSET;
5179                 /*
5180                  * Sane guest uses MOV to write EOI, with written value
5181                  * not cared. So make a short-circuit here by avoiding
5182                  * heavy instruction emulation.
5183                  */
5184                 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
5185                     (offset == APIC_EOI)) {
5186                         kvm_lapic_set_eoi(vcpu);
5187                         skip_emulated_instruction(vcpu);
5188                         return 1;
5189                 }
5190         }
5191         return emulate_instruction(vcpu, 0) == EMULATE_DONE;
5192 }
5193
5194 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
5195 {
5196         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5197         int vector = exit_qualification & 0xff;
5198
5199         /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
5200         kvm_apic_set_eoi_accelerated(vcpu, vector);
5201         return 1;
5202 }
5203
5204 static int handle_apic_write(struct kvm_vcpu *vcpu)
5205 {
5206         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5207         u32 offset = exit_qualification & 0xfff;
5208
5209         /* APIC-write VM exit is trap-like and thus no need to adjust IP */
5210         kvm_apic_write_nodecode(vcpu, offset);
5211         return 1;
5212 }
5213
5214 static int handle_task_switch(struct kvm_vcpu *vcpu)
5215 {
5216         struct vcpu_vmx *vmx = to_vmx(vcpu);
5217         unsigned long exit_qualification;
5218         bool has_error_code = false;
5219         u32 error_code = 0;
5220         u16 tss_selector;
5221         int reason, type, idt_v, idt_index;
5222
5223         idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
5224         idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
5225         type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
5226
5227         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5228
5229         reason = (u32)exit_qualification >> 30;
5230         if (reason == TASK_SWITCH_GATE && idt_v) {
5231                 switch (type) {
5232                 case INTR_TYPE_NMI_INTR:
5233                         vcpu->arch.nmi_injected = false;
5234                         vmx_set_nmi_mask(vcpu, true);
5235                         break;
5236                 case INTR_TYPE_EXT_INTR:
5237                 case INTR_TYPE_SOFT_INTR:
5238                         kvm_clear_interrupt_queue(vcpu);
5239                         break;
5240                 case INTR_TYPE_HARD_EXCEPTION:
5241                         if (vmx->idt_vectoring_info &
5242                             VECTORING_INFO_DELIVER_CODE_MASK) {
5243                                 has_error_code = true;
5244                                 error_code =
5245                                         vmcs_read32(IDT_VECTORING_ERROR_CODE);
5246                         }
5247                         /* fall through */
5248                 case INTR_TYPE_SOFT_EXCEPTION:
5249                         kvm_clear_exception_queue(vcpu);
5250                         break;
5251                 default:
5252                         break;
5253                 }
5254         }
5255         tss_selector = exit_qualification;
5256
5257         if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
5258                        type != INTR_TYPE_EXT_INTR &&
5259                        type != INTR_TYPE_NMI_INTR))
5260                 skip_emulated_instruction(vcpu);
5261
5262         if (kvm_task_switch(vcpu, tss_selector,
5263                             type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason,
5264                             has_error_code, error_code) == EMULATE_FAIL) {
5265                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5266                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5267                 vcpu->run->internal.ndata = 0;
5268                 return 0;
5269         }
5270
5271         /* clear all local breakpoint enable flags */
5272         vmcs_writel(GUEST_DR7, vmcs_readl(GUEST_DR7) & ~55);
5273
5274         /*
5275          * TODO: What about debug traps on tss switch?
5276          *       Are we supposed to inject them and update dr6?
5277          */
5278
5279         return 1;
5280 }
5281
5282 static int handle_ept_violation(struct kvm_vcpu *vcpu)
5283 {
5284         unsigned long exit_qualification;
5285         gpa_t gpa;
5286         u32 error_code;
5287         int gla_validity;
5288
5289         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5290
5291         gla_validity = (exit_qualification >> 7) & 0x3;
5292         if (gla_validity != 0x3 && gla_validity != 0x1 && gla_validity != 0) {
5293                 printk(KERN_ERR "EPT: Handling EPT violation failed!\n");
5294                 printk(KERN_ERR "EPT: GPA: 0x%lx, GVA: 0x%lx\n",
5295                         (long unsigned int)vmcs_read64(GUEST_PHYSICAL_ADDRESS),
5296                         vmcs_readl(GUEST_LINEAR_ADDRESS));
5297                 printk(KERN_ERR "EPT: Exit qualification is 0x%lx\n",
5298                         (long unsigned int)exit_qualification);
5299                 vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
5300                 vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_VIOLATION;
5301                 return 0;
5302         }
5303
5304         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5305         trace_kvm_page_fault(gpa, exit_qualification);
5306
5307         /* It is a write fault? */
5308         error_code = exit_qualification & (1U << 1);
5309         /* ept page table is present? */
5310         error_code |= (exit_qualification >> 3) & 0x1;
5311
5312         return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
5313 }
5314
5315 static u64 ept_rsvd_mask(u64 spte, int level)
5316 {
5317         int i;
5318         u64 mask = 0;
5319
5320         for (i = 51; i > boot_cpu_data.x86_phys_bits; i--)
5321                 mask |= (1ULL << i);
5322
5323         if (level > 2)
5324                 /* bits 7:3 reserved */
5325                 mask |= 0xf8;
5326         else if (level == 2) {
5327                 if (spte & (1ULL << 7))
5328                         /* 2MB ref, bits 20:12 reserved */
5329                         mask |= 0x1ff000;
5330                 else
5331                         /* bits 6:3 reserved */
5332                         mask |= 0x78;
5333         }
5334
5335         return mask;
5336 }
5337
5338 static void ept_misconfig_inspect_spte(struct kvm_vcpu *vcpu, u64 spte,
5339                                        int level)
5340 {
5341         printk(KERN_ERR "%s: spte 0x%llx level %d\n", __func__, spte, level);
5342
5343         /* 010b (write-only) */
5344         WARN_ON((spte & 0x7) == 0x2);
5345
5346         /* 110b (write/execute) */
5347         WARN_ON((spte & 0x7) == 0x6);
5348
5349         /* 100b (execute-only) and value not supported by logical processor */
5350         if (!cpu_has_vmx_ept_execute_only())
5351                 WARN_ON((spte & 0x7) == 0x4);
5352
5353         /* not 000b */
5354         if ((spte & 0x7)) {
5355                 u64 rsvd_bits = spte & ept_rsvd_mask(spte, level);
5356
5357                 if (rsvd_bits != 0) {
5358                         printk(KERN_ERR "%s: rsvd_bits = 0x%llx\n",
5359                                          __func__, rsvd_bits);
5360                         WARN_ON(1);
5361                 }
5362
5363                 if (level == 1 || (level == 2 && (spte & (1ULL << 7)))) {
5364                         u64 ept_mem_type = (spte & 0x38) >> 3;
5365
5366                         if (ept_mem_type == 2 || ept_mem_type == 3 ||
5367                             ept_mem_type == 7) {
5368                                 printk(KERN_ERR "%s: ept_mem_type=0x%llx\n",
5369                                                 __func__, ept_mem_type);
5370                                 WARN_ON(1);
5371                         }
5372                 }
5373         }
5374 }
5375
5376 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
5377 {
5378         u64 sptes[4];
5379         int nr_sptes, i, ret;
5380         gpa_t gpa;
5381
5382         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5383
5384         ret = handle_mmio_page_fault_common(vcpu, gpa, true);
5385         if (likely(ret == 1))
5386                 return x86_emulate_instruction(vcpu, gpa, 0, NULL, 0) ==
5387                                               EMULATE_DONE;
5388         if (unlikely(!ret))
5389                 return 1;
5390
5391         /* It is the real ept misconfig */
5392         printk(KERN_ERR "EPT: Misconfiguration.\n");
5393         printk(KERN_ERR "EPT: GPA: 0x%llx\n", gpa);
5394
5395         nr_sptes = kvm_mmu_get_spte_hierarchy(vcpu, gpa, sptes);
5396
5397         for (i = PT64_ROOT_LEVEL; i > PT64_ROOT_LEVEL - nr_sptes; --i)
5398                 ept_misconfig_inspect_spte(vcpu, sptes[i-1], i);
5399
5400         vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
5401         vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_MISCONFIG;
5402
5403         return 0;
5404 }
5405
5406 static int handle_nmi_window(struct kvm_vcpu *vcpu)
5407 {
5408         u32 cpu_based_vm_exec_control;
5409
5410         /* clear pending NMI */
5411         cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5412         cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
5413         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
5414         ++vcpu->stat.nmi_window_exits;
5415         kvm_make_request(KVM_REQ_EVENT, vcpu);
5416
5417         return 1;
5418 }
5419
5420 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
5421 {
5422         struct vcpu_vmx *vmx = to_vmx(vcpu);
5423         enum emulation_result err = EMULATE_DONE;
5424         int ret = 1;
5425         u32 cpu_exec_ctrl;
5426         bool intr_window_requested;
5427         unsigned count = 130;
5428
5429         cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5430         intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
5431
5432         while (!guest_state_valid(vcpu) && count-- != 0) {
5433                 if (intr_window_requested && vmx_interrupt_allowed(vcpu))
5434                         return handle_interrupt_window(&vmx->vcpu);
5435
5436                 if (test_bit(KVM_REQ_EVENT, &vcpu->requests))
5437                         return 1;
5438
5439                 err = emulate_instruction(vcpu, EMULTYPE_NO_REEXECUTE);
5440
5441                 if (err == EMULATE_DO_MMIO) {
5442                         ret = 0;
5443                         goto out;
5444                 }
5445
5446                 if (err != EMULATE_DONE) {
5447                         vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5448                         vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5449                         vcpu->run->internal.ndata = 0;
5450                         return 0;
5451                 }
5452
5453                 if (vcpu->arch.halt_request) {
5454                         vcpu->arch.halt_request = 0;
5455                         ret = kvm_emulate_halt(vcpu);
5456                         goto out;
5457                 }
5458
5459                 if (signal_pending(current))
5460                         goto out;
5461                 if (need_resched())
5462                         schedule();
5463         }
5464
5465         vmx->emulation_required = emulation_required(vcpu);
5466 out:
5467         return ret;
5468 }
5469
5470 /*
5471  * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
5472  * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
5473  */
5474 static int handle_pause(struct kvm_vcpu *vcpu)
5475 {
5476         skip_emulated_instruction(vcpu);
5477         kvm_vcpu_on_spin(vcpu);
5478
5479         return 1;
5480 }
5481
5482 static int handle_invalid_op(struct kvm_vcpu *vcpu)
5483 {
5484         kvm_queue_exception(vcpu, UD_VECTOR);
5485         return 1;
5486 }
5487
5488 /*
5489  * To run an L2 guest, we need a vmcs02 based on the L1-specified vmcs12.
5490  * We could reuse a single VMCS for all the L2 guests, but we also want the
5491  * option to allocate a separate vmcs02 for each separate loaded vmcs12 - this
5492  * allows keeping them loaded on the processor, and in the future will allow
5493  * optimizations where prepare_vmcs02 doesn't need to set all the fields on
5494  * every entry if they never change.
5495  * So we keep, in vmx->nested.vmcs02_pool, a cache of size VMCS02_POOL_SIZE
5496  * (>=0) with a vmcs02 for each recently loaded vmcs12s, most recent first.
5497  *
5498  * The following functions allocate and free a vmcs02 in this pool.
5499  */
5500
5501 /* Get a VMCS from the pool to use as vmcs02 for the current vmcs12. */
5502 static struct loaded_vmcs *nested_get_current_vmcs02(struct vcpu_vmx *vmx)
5503 {
5504         struct vmcs02_list *item;
5505         list_for_each_entry(item, &vmx->nested.vmcs02_pool, list)
5506                 if (item->vmptr == vmx->nested.current_vmptr) {
5507                         list_move(&item->list, &vmx->nested.vmcs02_pool);
5508                         return &item->vmcs02;
5509                 }
5510
5511         if (vmx->nested.vmcs02_num >= max(VMCS02_POOL_SIZE, 1)) {
5512                 /* Recycle the least recently used VMCS. */
5513                 item = list_entry(vmx->nested.vmcs02_pool.prev,
5514                         struct vmcs02_list, list);
5515                 item->vmptr = vmx->nested.current_vmptr;
5516                 list_move(&item->list, &vmx->nested.vmcs02_pool);
5517                 return &item->vmcs02;
5518         }
5519
5520         /* Create a new VMCS */
5521         item = kmalloc(sizeof(struct vmcs02_list), GFP_KERNEL);
5522         if (!item)
5523                 return NULL;
5524         item->vmcs02.vmcs = alloc_vmcs();
5525         if (!item->vmcs02.vmcs) {
5526                 kfree(item);
5527                 return NULL;
5528         }
5529         loaded_vmcs_init(&item->vmcs02);
5530         item->vmptr = vmx->nested.current_vmptr;
5531         list_add(&(item->list), &(vmx->nested.vmcs02_pool));
5532         vmx->nested.vmcs02_num++;
5533         return &item->vmcs02;
5534 }
5535
5536 /* Free and remove from pool a vmcs02 saved for a vmcs12 (if there is one) */
5537 static void nested_free_vmcs02(struct vcpu_vmx *vmx, gpa_t vmptr)
5538 {
5539         struct vmcs02_list *item;
5540         list_for_each_entry(item, &vmx->nested.vmcs02_pool, list)
5541                 if (item->vmptr == vmptr) {
5542                         free_loaded_vmcs(&item->vmcs02);
5543                         list_del(&item->list);
5544                         kfree(item);
5545                         vmx->nested.vmcs02_num--;
5546                         return;
5547                 }
5548 }
5549
5550 /*
5551  * Free all VMCSs saved for this vcpu, except the one pointed by
5552  * vmx->loaded_vmcs. These include the VMCSs in vmcs02_pool (except the one
5553  * currently used, if running L2), and vmcs01 when running L2.
5554  */
5555 static void nested_free_all_saved_vmcss(struct vcpu_vmx *vmx)
5556 {
5557         struct vmcs02_list *item, *n;
5558         list_for_each_entry_safe(item, n, &vmx->nested.vmcs02_pool, list) {
5559                 if (vmx->loaded_vmcs != &item->vmcs02)
5560                         free_loaded_vmcs(&item->vmcs02);
5561                 list_del(&item->list);
5562                 kfree(item);
5563         }
5564         vmx->nested.vmcs02_num = 0;
5565
5566         if (vmx->loaded_vmcs != &vmx->vmcs01)
5567                 free_loaded_vmcs(&vmx->vmcs01);
5568 }
5569
5570 static void nested_vmx_failValid(struct kvm_vcpu *vcpu,
5571                                  u32 vm_instruction_error);
5572
5573 /*
5574  * Emulate the VMXON instruction.
5575  * Currently, we just remember that VMX is active, and do not save or even
5576  * inspect the argument to VMXON (the so-called "VMXON pointer") because we
5577  * do not currently need to store anything in that guest-allocated memory
5578  * region. Consequently, VMCLEAR and VMPTRLD also do not verify that the their
5579  * argument is different from the VMXON pointer (which the spec says they do).
5580  */
5581 static int handle_vmon(struct kvm_vcpu *vcpu)
5582 {
5583         struct kvm_segment cs;
5584         struct vcpu_vmx *vmx = to_vmx(vcpu);
5585         struct vmcs *shadow_vmcs;
5586
5587         /* The Intel VMX Instruction Reference lists a bunch of bits that
5588          * are prerequisite to running VMXON, most notably cr4.VMXE must be
5589          * set to 1 (see vmx_set_cr4() for when we allow the guest to set this).
5590          * Otherwise, we should fail with #UD. We test these now:
5591          */
5592         if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE) ||
5593             !kvm_read_cr0_bits(vcpu, X86_CR0_PE) ||
5594             (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
5595                 kvm_queue_exception(vcpu, UD_VECTOR);
5596                 return 1;
5597         }
5598
5599         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
5600         if (is_long_mode(vcpu) && !cs.l) {
5601                 kvm_queue_exception(vcpu, UD_VECTOR);
5602                 return 1;
5603         }
5604
5605         if (vmx_get_cpl(vcpu)) {
5606                 kvm_inject_gp(vcpu, 0);
5607                 return 1;
5608         }
5609         if (vmx->nested.vmxon) {
5610                 nested_vmx_failValid(vcpu, VMXERR_VMXON_IN_VMX_ROOT_OPERATION);
5611                 skip_emulated_instruction(vcpu);
5612                 return 1;
5613         }
5614         if (enable_shadow_vmcs) {
5615                 shadow_vmcs = alloc_vmcs();
5616                 if (!shadow_vmcs)
5617                         return -ENOMEM;
5618                 /* mark vmcs as shadow */
5619                 shadow_vmcs->revision_id |= (1u << 31);
5620                 /* init shadow vmcs */
5621                 vmcs_clear(shadow_vmcs);
5622                 vmx->nested.current_shadow_vmcs = shadow_vmcs;
5623         }
5624
5625         INIT_LIST_HEAD(&(vmx->nested.vmcs02_pool));
5626         vmx->nested.vmcs02_num = 0;
5627
5628         vmx->nested.vmxon = true;
5629
5630         skip_emulated_instruction(vcpu);
5631         return 1;
5632 }
5633
5634 /*
5635  * Intel's VMX Instruction Reference specifies a common set of prerequisites
5636  * for running VMX instructions (except VMXON, whose prerequisites are
5637  * slightly different). It also specifies what exception to inject otherwise.
5638  */
5639 static int nested_vmx_check_permission(struct kvm_vcpu *vcpu)
5640 {
5641         struct kvm_segment cs;
5642         struct vcpu_vmx *vmx = to_vmx(vcpu);
5643
5644         if (!vmx->nested.vmxon) {
5645                 kvm_queue_exception(vcpu, UD_VECTOR);
5646                 return 0;
5647         }
5648
5649         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
5650         if ((vmx_get_rflags(vcpu) & X86_EFLAGS_VM) ||
5651             (is_long_mode(vcpu) && !cs.l)) {
5652                 kvm_queue_exception(vcpu, UD_VECTOR);
5653                 return 0;
5654         }
5655
5656         if (vmx_get_cpl(vcpu)) {
5657                 kvm_inject_gp(vcpu, 0);
5658                 return 0;
5659         }
5660
5661         return 1;
5662 }
5663
5664 static inline void nested_release_vmcs12(struct vcpu_vmx *vmx)
5665 {
5666         u32 exec_control;
5667         if (enable_shadow_vmcs) {
5668                 if (vmx->nested.current_vmcs12 != NULL) {
5669                         /* copy to memory all shadowed fields in case
5670                            they were modified */
5671                         copy_shadow_to_vmcs12(vmx);
5672                         vmx->nested.sync_shadow_vmcs = false;
5673                         exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
5674                         exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
5675                         vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
5676                         vmcs_write64(VMCS_LINK_POINTER, -1ull);
5677                 }
5678         }
5679         kunmap(vmx->nested.current_vmcs12_page);
5680         nested_release_page(vmx->nested.current_vmcs12_page);
5681 }
5682
5683 /*
5684  * Free whatever needs to be freed from vmx->nested when L1 goes down, or
5685  * just stops using VMX.
5686  */
5687 static void free_nested(struct vcpu_vmx *vmx)
5688 {
5689         if (!vmx->nested.vmxon)
5690                 return;
5691         vmx->nested.vmxon = false;
5692         if (vmx->nested.current_vmptr != -1ull) {
5693                 nested_release_vmcs12(vmx);
5694                 vmx->nested.current_vmptr = -1ull;
5695                 vmx->nested.current_vmcs12 = NULL;
5696         }
5697         if (enable_shadow_vmcs)
5698                 free_vmcs(vmx->nested.current_shadow_vmcs);
5699         /* Unpin physical memory we referred to in current vmcs02 */
5700         if (vmx->nested.apic_access_page) {
5701                 nested_release_page(vmx->nested.apic_access_page);
5702                 vmx->nested.apic_access_page = 0;
5703         }
5704
5705         nested_free_all_saved_vmcss(vmx);
5706 }
5707
5708 /* Emulate the VMXOFF instruction */
5709 static int handle_vmoff(struct kvm_vcpu *vcpu)
5710 {
5711         if (!nested_vmx_check_permission(vcpu))
5712                 return 1;
5713         free_nested(to_vmx(vcpu));
5714         skip_emulated_instruction(vcpu);
5715         return 1;
5716 }
5717
5718 /*
5719  * Decode the memory-address operand of a vmx instruction, as recorded on an
5720  * exit caused by such an instruction (run by a guest hypervisor).
5721  * On success, returns 0. When the operand is invalid, returns 1 and throws
5722  * #UD or #GP.
5723  */
5724 static int get_vmx_mem_address(struct kvm_vcpu *vcpu,
5725                                  unsigned long exit_qualification,
5726                                  u32 vmx_instruction_info, gva_t *ret)
5727 {
5728         /*
5729          * According to Vol. 3B, "Information for VM Exits Due to Instruction
5730          * Execution", on an exit, vmx_instruction_info holds most of the
5731          * addressing components of the operand. Only the displacement part
5732          * is put in exit_qualification (see 3B, "Basic VM-Exit Information").
5733          * For how an actual address is calculated from all these components,
5734          * refer to Vol. 1, "Operand Addressing".
5735          */
5736         int  scaling = vmx_instruction_info & 3;
5737         int  addr_size = (vmx_instruction_info >> 7) & 7;
5738         bool is_reg = vmx_instruction_info & (1u << 10);
5739         int  seg_reg = (vmx_instruction_info >> 15) & 7;
5740         int  index_reg = (vmx_instruction_info >> 18) & 0xf;
5741         bool index_is_valid = !(vmx_instruction_info & (1u << 22));
5742         int  base_reg       = (vmx_instruction_info >> 23) & 0xf;
5743         bool base_is_valid  = !(vmx_instruction_info & (1u << 27));
5744
5745         if (is_reg) {
5746                 kvm_queue_exception(vcpu, UD_VECTOR);
5747                 return 1;
5748         }
5749
5750         /* Addr = segment_base + offset */
5751         /* offset = base + [index * scale] + displacement */
5752         *ret = vmx_get_segment_base(vcpu, seg_reg);
5753         if (base_is_valid)
5754                 *ret += kvm_register_read(vcpu, base_reg);
5755         if (index_is_valid)
5756                 *ret += kvm_register_read(vcpu, index_reg)<<scaling;
5757         *ret += exit_qualification; /* holds the displacement */
5758
5759         if (addr_size == 1) /* 32 bit */
5760                 *ret &= 0xffffffff;
5761
5762         /*
5763          * TODO: throw #GP (and return 1) in various cases that the VM*
5764          * instructions require it - e.g., offset beyond segment limit,
5765          * unusable or unreadable/unwritable segment, non-canonical 64-bit
5766          * address, and so on. Currently these are not checked.
5767          */
5768         return 0;
5769 }
5770
5771 /*
5772  * The following 3 functions, nested_vmx_succeed()/failValid()/failInvalid(),
5773  * set the success or error code of an emulated VMX instruction, as specified
5774  * by Vol 2B, VMX Instruction Reference, "Conventions".
5775  */
5776 static void nested_vmx_succeed(struct kvm_vcpu *vcpu)
5777 {
5778         vmx_set_rflags(vcpu, vmx_get_rflags(vcpu)
5779                         & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
5780                             X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF));
5781 }
5782
5783 static void nested_vmx_failInvalid(struct kvm_vcpu *vcpu)
5784 {
5785         vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
5786                         & ~(X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
5787                             X86_EFLAGS_SF | X86_EFLAGS_OF))
5788                         | X86_EFLAGS_CF);
5789 }
5790
5791 static void nested_vmx_failValid(struct kvm_vcpu *vcpu,
5792                                         u32 vm_instruction_error)
5793 {
5794         if (to_vmx(vcpu)->nested.current_vmptr == -1ull) {
5795                 /*
5796                  * failValid writes the error number to the current VMCS, which
5797                  * can't be done there isn't a current VMCS.
5798                  */
5799                 nested_vmx_failInvalid(vcpu);
5800                 return;
5801         }
5802         vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
5803                         & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
5804                             X86_EFLAGS_SF | X86_EFLAGS_OF))
5805                         | X86_EFLAGS_ZF);
5806         get_vmcs12(vcpu)->vm_instruction_error = vm_instruction_error;
5807         /*
5808          * We don't need to force a shadow sync because
5809          * VM_INSTRUCTION_ERROR is not shadowed
5810          */
5811 }
5812
5813 /* Emulate the VMCLEAR instruction */
5814 static int handle_vmclear(struct kvm_vcpu *vcpu)
5815 {
5816         struct vcpu_vmx *vmx = to_vmx(vcpu);
5817         gva_t gva;
5818         gpa_t vmptr;
5819         struct vmcs12 *vmcs12;
5820         struct page *page;
5821         struct x86_exception e;
5822
5823         if (!nested_vmx_check_permission(vcpu))
5824                 return 1;
5825
5826         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
5827                         vmcs_read32(VMX_INSTRUCTION_INFO), &gva))
5828                 return 1;
5829
5830         if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &vmptr,
5831                                 sizeof(vmptr), &e)) {
5832                 kvm_inject_page_fault(vcpu, &e);
5833                 return 1;
5834         }
5835
5836         if (!IS_ALIGNED(vmptr, PAGE_SIZE)) {
5837                 nested_vmx_failValid(vcpu, VMXERR_VMCLEAR_INVALID_ADDRESS);
5838                 skip_emulated_instruction(vcpu);
5839                 return 1;
5840         }
5841
5842         if (vmptr == vmx->nested.current_vmptr) {
5843                 nested_release_vmcs12(vmx);
5844                 vmx->nested.current_vmptr = -1ull;
5845                 vmx->nested.current_vmcs12 = NULL;
5846         }
5847
5848         page = nested_get_page(vcpu, vmptr);
5849         if (page == NULL) {
5850                 /*
5851                  * For accurate processor emulation, VMCLEAR beyond available
5852                  * physical memory should do nothing at all. However, it is
5853                  * possible that a nested vmx bug, not a guest hypervisor bug,
5854                  * resulted in this case, so let's shut down before doing any
5855                  * more damage:
5856                  */
5857                 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5858                 return 1;
5859         }
5860         vmcs12 = kmap(page);
5861         vmcs12->launch_state = 0;
5862         kunmap(page);
5863         nested_release_page(page);
5864
5865         nested_free_vmcs02(vmx, vmptr);
5866
5867         skip_emulated_instruction(vcpu);
5868         nested_vmx_succeed(vcpu);
5869         return 1;
5870 }
5871
5872 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch);
5873
5874 /* Emulate the VMLAUNCH instruction */
5875 static int handle_vmlaunch(struct kvm_vcpu *vcpu)
5876 {
5877         return nested_vmx_run(vcpu, true);
5878 }
5879
5880 /* Emulate the VMRESUME instruction */
5881 static int handle_vmresume(struct kvm_vcpu *vcpu)
5882 {
5883
5884         return nested_vmx_run(vcpu, false);
5885 }
5886
5887 enum vmcs_field_type {
5888         VMCS_FIELD_TYPE_U16 = 0,
5889         VMCS_FIELD_TYPE_U64 = 1,
5890         VMCS_FIELD_TYPE_U32 = 2,
5891         VMCS_FIELD_TYPE_NATURAL_WIDTH = 3
5892 };
5893
5894 static inline int vmcs_field_type(unsigned long field)
5895 {
5896         if (0x1 & field)        /* the *_HIGH fields are all 32 bit */
5897                 return VMCS_FIELD_TYPE_U32;
5898         return (field >> 13) & 0x3 ;
5899 }
5900
5901 static inline int vmcs_field_readonly(unsigned long field)
5902 {
5903         return (((field >> 10) & 0x3) == 1);
5904 }
5905
5906 /*
5907  * Read a vmcs12 field. Since these can have varying lengths and we return
5908  * one type, we chose the biggest type (u64) and zero-extend the return value
5909  * to that size. Note that the caller, handle_vmread, might need to use only
5910  * some of the bits we return here (e.g., on 32-bit guests, only 32 bits of
5911  * 64-bit fields are to be returned).
5912  */
5913 static inline bool vmcs12_read_any(struct kvm_vcpu *vcpu,
5914                                         unsigned long field, u64 *ret)
5915 {
5916         short offset = vmcs_field_to_offset(field);
5917         char *p;
5918
5919         if (offset < 0)
5920                 return 0;
5921
5922         p = ((char *)(get_vmcs12(vcpu))) + offset;
5923
5924         switch (vmcs_field_type(field)) {
5925         case VMCS_FIELD_TYPE_NATURAL_WIDTH:
5926                 *ret = *((natural_width *)p);
5927                 return 1;
5928         case VMCS_FIELD_TYPE_U16:
5929                 *ret = *((u16 *)p);
5930                 return 1;
5931         case VMCS_FIELD_TYPE_U32:
5932                 *ret = *((u32 *)p);
5933                 return 1;
5934         case VMCS_FIELD_TYPE_U64:
5935                 *ret = *((u64 *)p);
5936                 return 1;
5937         default:
5938                 return 0; /* can never happen. */
5939         }
5940 }
5941
5942
5943 static inline bool vmcs12_write_any(struct kvm_vcpu *vcpu,
5944                                     unsigned long field, u64 field_value){
5945         short offset = vmcs_field_to_offset(field);
5946         char *p = ((char *) get_vmcs12(vcpu)) + offset;
5947         if (offset < 0)
5948                 return false;
5949
5950         switch (vmcs_field_type(field)) {
5951         case VMCS_FIELD_TYPE_U16:
5952                 *(u16 *)p = field_value;
5953                 return true;
5954         case VMCS_FIELD_TYPE_U32:
5955                 *(u32 *)p = field_value;
5956                 return true;
5957         case VMCS_FIELD_TYPE_U64:
5958                 *(u64 *)p = field_value;
5959                 return true;
5960         case VMCS_FIELD_TYPE_NATURAL_WIDTH:
5961                 *(natural_width *)p = field_value;
5962                 return true;
5963         default:
5964                 return false; /* can never happen. */
5965         }
5966
5967 }
5968
5969 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx)
5970 {
5971         int i;
5972         unsigned long field;
5973         u64 field_value;
5974         struct vmcs *shadow_vmcs = vmx->nested.current_shadow_vmcs;
5975         unsigned long *fields = (unsigned long *)shadow_read_write_fields;
5976         int num_fields = max_shadow_read_write_fields;
5977
5978         vmcs_load(shadow_vmcs);
5979
5980         for (i = 0; i < num_fields; i++) {
5981                 field = fields[i];
5982                 switch (vmcs_field_type(field)) {
5983                 case VMCS_FIELD_TYPE_U16:
5984                         field_value = vmcs_read16(field);
5985                         break;
5986                 case VMCS_FIELD_TYPE_U32:
5987                         field_value = vmcs_read32(field);
5988                         break;
5989                 case VMCS_FIELD_TYPE_U64:
5990                         field_value = vmcs_read64(field);
5991                         break;
5992                 case VMCS_FIELD_TYPE_NATURAL_WIDTH:
5993                         field_value = vmcs_readl(field);
5994                         break;
5995                 }
5996                 vmcs12_write_any(&vmx->vcpu, field, field_value);
5997         }
5998
5999         vmcs_clear(shadow_vmcs);
6000         vmcs_load(vmx->loaded_vmcs->vmcs);
6001 }
6002
6003 static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx)
6004 {
6005         unsigned long *fields[] = {
6006                 (unsigned long *)shadow_read_write_fields,
6007                 (unsigned long *)shadow_read_only_fields
6008         };
6009         int num_lists =  ARRAY_SIZE(fields);
6010         int max_fields[] = {
6011                 max_shadow_read_write_fields,
6012                 max_shadow_read_only_fields
6013         };
6014         int i, q;
6015         unsigned long field;
6016         u64 field_value = 0;
6017         struct vmcs *shadow_vmcs = vmx->nested.current_shadow_vmcs;
6018
6019         vmcs_load(shadow_vmcs);
6020
6021         for (q = 0; q < num_lists; q++) {
6022                 for (i = 0; i < max_fields[q]; i++) {
6023                         field = fields[q][i];
6024                         vmcs12_read_any(&vmx->vcpu, field, &field_value);
6025
6026                         switch (vmcs_field_type(field)) {
6027                         case VMCS_FIELD_TYPE_U16:
6028                                 vmcs_write16(field, (u16)field_value);
6029                                 break;
6030                         case VMCS_FIELD_TYPE_U32:
6031                                 vmcs_write32(field, (u32)field_value);
6032                                 break;
6033                         case VMCS_FIELD_TYPE_U64:
6034                                 vmcs_write64(field, (u64)field_value);
6035                                 break;
6036                         case VMCS_FIELD_TYPE_NATURAL_WIDTH:
6037                                 vmcs_writel(field, (long)field_value);
6038                                 break;
6039                         }
6040                 }
6041         }
6042
6043         vmcs_clear(shadow_vmcs);
6044         vmcs_load(vmx->loaded_vmcs->vmcs);
6045 }
6046
6047 /*
6048  * VMX instructions which assume a current vmcs12 (i.e., that VMPTRLD was
6049  * used before) all generate the same failure when it is missing.
6050  */
6051 static int nested_vmx_check_vmcs12(struct kvm_vcpu *vcpu)
6052 {
6053         struct vcpu_vmx *vmx = to_vmx(vcpu);
6054         if (vmx->nested.current_vmptr == -1ull) {
6055                 nested_vmx_failInvalid(vcpu);
6056                 skip_emulated_instruction(vcpu);
6057                 return 0;
6058         }
6059         return 1;
6060 }
6061
6062 static int handle_vmread(struct kvm_vcpu *vcpu)
6063 {
6064         unsigned long field;
6065         u64 field_value;
6066         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6067         u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
6068         gva_t gva = 0;
6069
6070         if (!nested_vmx_check_permission(vcpu) ||
6071             !nested_vmx_check_vmcs12(vcpu))
6072                 return 1;
6073
6074         /* Decode instruction info and find the field to read */
6075         field = kvm_register_read(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
6076         /* Read the field, zero-extended to a u64 field_value */
6077         if (!vmcs12_read_any(vcpu, field, &field_value)) {
6078                 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
6079                 skip_emulated_instruction(vcpu);
6080                 return 1;
6081         }
6082         /*
6083          * Now copy part of this value to register or memory, as requested.
6084          * Note that the number of bits actually copied is 32 or 64 depending
6085          * on the guest's mode (32 or 64 bit), not on the given field's length.
6086          */
6087         if (vmx_instruction_info & (1u << 10)) {
6088                 kvm_register_write(vcpu, (((vmx_instruction_info) >> 3) & 0xf),
6089                         field_value);
6090         } else {
6091                 if (get_vmx_mem_address(vcpu, exit_qualification,
6092                                 vmx_instruction_info, &gva))
6093                         return 1;
6094                 /* _system ok, as nested_vmx_check_permission verified cpl=0 */
6095                 kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, gva,
6096                              &field_value, (is_long_mode(vcpu) ? 8 : 4), NULL);
6097         }
6098
6099         nested_vmx_succeed(vcpu);
6100         skip_emulated_instruction(vcpu);
6101         return 1;
6102 }
6103
6104
6105 static int handle_vmwrite(struct kvm_vcpu *vcpu)
6106 {
6107         unsigned long field;
6108         gva_t gva;
6109         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6110         u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
6111         /* The value to write might be 32 or 64 bits, depending on L1's long
6112          * mode, and eventually we need to write that into a field of several
6113          * possible lengths. The code below first zero-extends the value to 64
6114          * bit (field_value), and then copies only the approriate number of
6115          * bits into the vmcs12 field.
6116          */
6117         u64 field_value = 0;
6118         struct x86_exception e;
6119
6120         if (!nested_vmx_check_permission(vcpu) ||
6121             !nested_vmx_check_vmcs12(vcpu))
6122                 return 1;
6123
6124         if (vmx_instruction_info & (1u << 10))
6125                 field_value = kvm_register_read(vcpu,
6126                         (((vmx_instruction_info) >> 3) & 0xf));
6127         else {
6128                 if (get_vmx_mem_address(vcpu, exit_qualification,
6129                                 vmx_instruction_info, &gva))
6130                         return 1;
6131                 if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva,
6132                            &field_value, (is_long_mode(vcpu) ? 8 : 4), &e)) {
6133                         kvm_inject_page_fault(vcpu, &e);
6134                         return 1;
6135                 }
6136         }
6137
6138
6139         field = kvm_register_read(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
6140         if (vmcs_field_readonly(field)) {
6141                 nested_vmx_failValid(vcpu,
6142                         VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT);
6143                 skip_emulated_instruction(vcpu);
6144                 return 1;
6145         }
6146
6147         if (!vmcs12_write_any(vcpu, field, field_value)) {
6148                 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
6149                 skip_emulated_instruction(vcpu);
6150                 return 1;
6151         }
6152
6153         nested_vmx_succeed(vcpu);
6154         skip_emulated_instruction(vcpu);
6155         return 1;
6156 }
6157
6158 /* Emulate the VMPTRLD instruction */
6159 static int handle_vmptrld(struct kvm_vcpu *vcpu)
6160 {
6161         struct vcpu_vmx *vmx = to_vmx(vcpu);
6162         gva_t gva;
6163         gpa_t vmptr;
6164         struct x86_exception e;
6165         u32 exec_control;
6166
6167         if (!nested_vmx_check_permission(vcpu))
6168                 return 1;
6169
6170         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
6171                         vmcs_read32(VMX_INSTRUCTION_INFO), &gva))
6172                 return 1;
6173
6174         if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &vmptr,
6175                                 sizeof(vmptr), &e)) {
6176                 kvm_inject_page_fault(vcpu, &e);
6177                 return 1;
6178         }
6179
6180         if (!IS_ALIGNED(vmptr, PAGE_SIZE)) {
6181                 nested_vmx_failValid(vcpu, VMXERR_VMPTRLD_INVALID_ADDRESS);
6182                 skip_emulated_instruction(vcpu);
6183                 return 1;
6184         }
6185
6186         if (vmx->nested.current_vmptr != vmptr) {
6187                 struct vmcs12 *new_vmcs12;
6188                 struct page *page;
6189                 page = nested_get_page(vcpu, vmptr);
6190                 if (page == NULL) {
6191                         nested_vmx_failInvalid(vcpu);
6192                         skip_emulated_instruction(vcpu);
6193                         return 1;
6194                 }
6195                 new_vmcs12 = kmap(page);
6196                 if (new_vmcs12->revision_id != VMCS12_REVISION) {
6197                         kunmap(page);
6198                         nested_release_page_clean(page);
6199                         nested_vmx_failValid(vcpu,
6200                                 VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
6201                         skip_emulated_instruction(vcpu);
6202                         return 1;
6203                 }
6204                 if (vmx->nested.current_vmptr != -1ull)
6205                         nested_release_vmcs12(vmx);
6206
6207                 vmx->nested.current_vmptr = vmptr;
6208                 vmx->nested.current_vmcs12 = new_vmcs12;
6209                 vmx->nested.current_vmcs12_page = page;
6210                 if (enable_shadow_vmcs) {
6211                         exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
6212                         exec_control |= SECONDARY_EXEC_SHADOW_VMCS;
6213                         vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
6214                         vmcs_write64(VMCS_LINK_POINTER,
6215                                      __pa(vmx->nested.current_shadow_vmcs));
6216                         vmx->nested.sync_shadow_vmcs = true;
6217                 }
6218         }
6219
6220         nested_vmx_succeed(vcpu);
6221         skip_emulated_instruction(vcpu);
6222         return 1;
6223 }
6224
6225 /* Emulate the VMPTRST instruction */
6226 static int handle_vmptrst(struct kvm_vcpu *vcpu)
6227 {
6228         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6229         u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
6230         gva_t vmcs_gva;
6231         struct x86_exception e;
6232
6233         if (!nested_vmx_check_permission(vcpu))
6234                 return 1;
6235
6236         if (get_vmx_mem_address(vcpu, exit_qualification,
6237                         vmx_instruction_info, &vmcs_gva))
6238                 return 1;
6239         /* ok to use *_system, as nested_vmx_check_permission verified cpl=0 */
6240         if (kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, vmcs_gva,
6241                                  (void *)&to_vmx(vcpu)->nested.current_vmptr,
6242                                  sizeof(u64), &e)) {
6243                 kvm_inject_page_fault(vcpu, &e);
6244                 return 1;
6245         }
6246         nested_vmx_succeed(vcpu);
6247         skip_emulated_instruction(vcpu);
6248         return 1;
6249 }
6250
6251 static int handle_invept(struct kvm_vcpu *vcpu)
6252 {
6253         kvm_queue_exception(vcpu, UD_VECTOR);
6254         return 1;
6255 }
6256
6257 static int handle_invvpid(struct kvm_vcpu *vcpu)
6258 {
6259         kvm_queue_exception(vcpu, UD_VECTOR);
6260         return 1;
6261 }
6262
6263 /*
6264  * The exit handlers return 1 if the exit was handled fully and guest execution
6265  * may resume.  Otherwise they set the kvm_run parameter to indicate what needs
6266  * to be done to userspace and return 0.
6267  */
6268 static int (*const kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
6269         [EXIT_REASON_EXCEPTION_NMI]           = handle_exception,
6270         [EXIT_REASON_EXTERNAL_INTERRUPT]      = handle_external_interrupt,
6271         [EXIT_REASON_TRIPLE_FAULT]            = handle_triple_fault,
6272         [EXIT_REASON_NMI_WINDOW]              = handle_nmi_window,
6273         [EXIT_REASON_IO_INSTRUCTION]          = handle_io,
6274         [EXIT_REASON_CR_ACCESS]               = handle_cr,
6275         [EXIT_REASON_DR_ACCESS]               = handle_dr,
6276         [EXIT_REASON_CPUID]                   = handle_cpuid,
6277         [EXIT_REASON_MSR_READ]                = handle_rdmsr,
6278         [EXIT_REASON_MSR_WRITE]               = handle_wrmsr,
6279         [EXIT_REASON_PENDING_INTERRUPT]       = handle_interrupt_window,
6280         [EXIT_REASON_HLT]                     = handle_halt,
6281         [EXIT_REASON_INVD]                    = handle_invd,
6282         [EXIT_REASON_INVLPG]                  = handle_invlpg,
6283         [EXIT_REASON_RDPMC]                   = handle_rdpmc,
6284         [EXIT_REASON_VMCALL]                  = handle_vmcall,
6285         [EXIT_REASON_VMCLEAR]                 = handle_vmclear,
6286         [EXIT_REASON_VMLAUNCH]                = handle_vmlaunch,
6287         [EXIT_REASON_VMPTRLD]                 = handle_vmptrld,
6288         [EXIT_REASON_VMPTRST]                 = handle_vmptrst,
6289         [EXIT_REASON_VMREAD]                  = handle_vmread,
6290         [EXIT_REASON_VMRESUME]                = handle_vmresume,
6291         [EXIT_REASON_VMWRITE]                 = handle_vmwrite,
6292         [EXIT_REASON_VMOFF]                   = handle_vmoff,
6293         [EXIT_REASON_VMON]                    = handle_vmon,
6294         [EXIT_REASON_TPR_BELOW_THRESHOLD]     = handle_tpr_below_threshold,
6295         [EXIT_REASON_APIC_ACCESS]             = handle_apic_access,
6296         [EXIT_REASON_APIC_WRITE]              = handle_apic_write,
6297         [EXIT_REASON_EOI_INDUCED]             = handle_apic_eoi_induced,
6298         [EXIT_REASON_WBINVD]                  = handle_wbinvd,
6299         [EXIT_REASON_XSETBV]                  = handle_xsetbv,
6300         [EXIT_REASON_TASK_SWITCH]             = handle_task_switch,
6301         [EXIT_REASON_MCE_DURING_VMENTRY]      = handle_machine_check,
6302         [EXIT_REASON_EPT_VIOLATION]           = handle_ept_violation,
6303         [EXIT_REASON_EPT_MISCONFIG]           = handle_ept_misconfig,
6304         [EXIT_REASON_PAUSE_INSTRUCTION]       = handle_pause,
6305         [EXIT_REASON_MWAIT_INSTRUCTION]       = handle_invalid_op,
6306         [EXIT_REASON_MONITOR_INSTRUCTION]     = handle_invalid_op,
6307         [EXIT_REASON_INVEPT]                  = handle_invept,
6308         [EXIT_REASON_INVVPID]                 = handle_invvpid,
6309 };
6310
6311 static const int kvm_vmx_max_exit_handlers =
6312         ARRAY_SIZE(kvm_vmx_exit_handlers);
6313
6314 static bool nested_vmx_exit_handled_io(struct kvm_vcpu *vcpu,
6315                                        struct vmcs12 *vmcs12)
6316 {
6317         unsigned long exit_qualification;
6318         gpa_t bitmap, last_bitmap;
6319         unsigned int port;
6320         int size;
6321         u8 b;
6322
6323         if (nested_cpu_has(vmcs12, CPU_BASED_UNCOND_IO_EXITING))
6324                 return 1;
6325
6326         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
6327                 return 0;
6328
6329         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6330
6331         port = exit_qualification >> 16;
6332         size = (exit_qualification & 7) + 1;
6333
6334         last_bitmap = (gpa_t)-1;
6335         b = -1;
6336
6337         while (size > 0) {
6338                 if (port < 0x8000)
6339                         bitmap = vmcs12->io_bitmap_a;
6340                 else if (port < 0x10000)
6341                         bitmap = vmcs12->io_bitmap_b;
6342                 else
6343                         return 1;
6344                 bitmap += (port & 0x7fff) / 8;
6345
6346                 if (last_bitmap != bitmap)
6347                         if (kvm_read_guest(vcpu->kvm, bitmap, &b, 1))
6348                                 return 1;
6349                 if (b & (1 << (port & 7)))
6350                         return 1;
6351
6352                 port++;
6353                 size--;
6354                 last_bitmap = bitmap;
6355         }
6356
6357         return 0;
6358 }
6359
6360 /*
6361  * Return 1 if we should exit from L2 to L1 to handle an MSR access access,
6362  * rather than handle it ourselves in L0. I.e., check whether L1 expressed
6363  * disinterest in the current event (read or write a specific MSR) by using an
6364  * MSR bitmap. This may be the case even when L0 doesn't use MSR bitmaps.
6365  */
6366 static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu,
6367         struct vmcs12 *vmcs12, u32 exit_reason)
6368 {
6369         u32 msr_index = vcpu->arch.regs[VCPU_REGS_RCX];
6370         gpa_t bitmap;
6371
6372         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
6373                 return 1;
6374
6375         /*
6376          * The MSR_BITMAP page is divided into four 1024-byte bitmaps,
6377          * for the four combinations of read/write and low/high MSR numbers.
6378          * First we need to figure out which of the four to use:
6379          */
6380         bitmap = vmcs12->msr_bitmap;
6381         if (exit_reason == EXIT_REASON_MSR_WRITE)
6382                 bitmap += 2048;
6383         if (msr_index >= 0xc0000000) {
6384                 msr_index -= 0xc0000000;
6385                 bitmap += 1024;
6386         }
6387
6388         /* Then read the msr_index'th bit from this bitmap: */
6389         if (msr_index < 1024*8) {
6390                 unsigned char b;
6391                 if (kvm_read_guest(vcpu->kvm, bitmap + msr_index/8, &b, 1))
6392                         return 1;
6393                 return 1 & (b >> (msr_index & 7));
6394         } else
6395                 return 1; /* let L1 handle the wrong parameter */
6396 }
6397
6398 /*
6399  * Return 1 if we should exit from L2 to L1 to handle a CR access exit,
6400  * rather than handle it ourselves in L0. I.e., check if L1 wanted to
6401  * intercept (via guest_host_mask etc.) the current event.
6402  */
6403 static bool nested_vmx_exit_handled_cr(struct kvm_vcpu *vcpu,
6404         struct vmcs12 *vmcs12)
6405 {
6406         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6407         int cr = exit_qualification & 15;
6408         int reg = (exit_qualification >> 8) & 15;
6409         unsigned long val = kvm_register_read(vcpu, reg);
6410
6411         switch ((exit_qualification >> 4) & 3) {
6412         case 0: /* mov to cr */
6413                 switch (cr) {
6414                 case 0:
6415                         if (vmcs12->cr0_guest_host_mask &
6416                             (val ^ vmcs12->cr0_read_shadow))
6417                                 return 1;
6418                         break;
6419                 case 3:
6420                         if ((vmcs12->cr3_target_count >= 1 &&
6421                                         vmcs12->cr3_target_value0 == val) ||
6422                                 (vmcs12->cr3_target_count >= 2 &&
6423                                         vmcs12->cr3_target_value1 == val) ||
6424                                 (vmcs12->cr3_target_count >= 3 &&
6425                                         vmcs12->cr3_target_value2 == val) ||
6426                                 (vmcs12->cr3_target_count >= 4 &&
6427                                         vmcs12->cr3_target_value3 == val))
6428                                 return 0;
6429                         if (nested_cpu_has(vmcs12, CPU_BASED_CR3_LOAD_EXITING))
6430                                 return 1;
6431                         break;
6432                 case 4:
6433                         if (vmcs12->cr4_guest_host_mask &
6434                             (vmcs12->cr4_read_shadow ^ val))
6435                                 return 1;
6436                         break;
6437                 case 8:
6438                         if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING))
6439                                 return 1;
6440                         break;
6441                 }
6442                 break;
6443         case 2: /* clts */
6444                 if ((vmcs12->cr0_guest_host_mask & X86_CR0_TS) &&
6445                     (vmcs12->cr0_read_shadow & X86_CR0_TS))
6446                         return 1;
6447                 break;
6448         case 1: /* mov from cr */
6449                 switch (cr) {
6450                 case 3:
6451                         if (vmcs12->cpu_based_vm_exec_control &
6452                             CPU_BASED_CR3_STORE_EXITING)
6453                                 return 1;
6454                         break;
6455                 case 8:
6456                         if (vmcs12->cpu_based_vm_exec_control &
6457                             CPU_BASED_CR8_STORE_EXITING)
6458                                 return 1;
6459                         break;
6460                 }
6461                 break;
6462         case 3: /* lmsw */
6463                 /*
6464                  * lmsw can change bits 1..3 of cr0, and only set bit 0 of
6465                  * cr0. Other attempted changes are ignored, with no exit.
6466                  */
6467                 if (vmcs12->cr0_guest_host_mask & 0xe &
6468                     (val ^ vmcs12->cr0_read_shadow))
6469                         return 1;
6470                 if ((vmcs12->cr0_guest_host_mask & 0x1) &&
6471                     !(vmcs12->cr0_read_shadow & 0x1) &&
6472                     (val & 0x1))
6473                         return 1;
6474                 break;
6475         }
6476         return 0;
6477 }
6478
6479 /*
6480  * Return 1 if we should exit from L2 to L1 to handle an exit, or 0 if we
6481  * should handle it ourselves in L0 (and then continue L2). Only call this
6482  * when in is_guest_mode (L2).
6483  */
6484 static bool nested_vmx_exit_handled(struct kvm_vcpu *vcpu)
6485 {
6486         u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
6487         struct vcpu_vmx *vmx = to_vmx(vcpu);
6488         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6489         u32 exit_reason = vmx->exit_reason;
6490
6491         if (vmx->nested.nested_run_pending)
6492                 return 0;
6493
6494         if (unlikely(vmx->fail)) {
6495                 pr_info_ratelimited("%s failed vm entry %x\n", __func__,
6496                                     vmcs_read32(VM_INSTRUCTION_ERROR));
6497                 return 1;
6498         }
6499
6500         switch (exit_reason) {
6501         case EXIT_REASON_EXCEPTION_NMI:
6502                 if (!is_exception(intr_info))
6503                         return 0;
6504                 else if (is_page_fault(intr_info))
6505                         return enable_ept;
6506                 return vmcs12->exception_bitmap &
6507                                 (1u << (intr_info & INTR_INFO_VECTOR_MASK));
6508         case EXIT_REASON_EXTERNAL_INTERRUPT:
6509                 return 0;
6510         case EXIT_REASON_TRIPLE_FAULT:
6511                 return 1;
6512         case EXIT_REASON_PENDING_INTERRUPT:
6513                 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_INTR_PENDING);
6514         case EXIT_REASON_NMI_WINDOW:
6515                 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING);
6516         case EXIT_REASON_TASK_SWITCH:
6517                 return 1;
6518         case EXIT_REASON_CPUID:
6519                 return 1;
6520         case EXIT_REASON_HLT:
6521                 return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
6522         case EXIT_REASON_INVD:
6523                 return 1;
6524         case EXIT_REASON_INVLPG:
6525                 return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
6526         case EXIT_REASON_RDPMC:
6527                 return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
6528         case EXIT_REASON_RDTSC:
6529                 return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
6530         case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
6531         case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
6532         case EXIT_REASON_VMPTRST: case EXIT_REASON_VMREAD:
6533         case EXIT_REASON_VMRESUME: case EXIT_REASON_VMWRITE:
6534         case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
6535         case EXIT_REASON_INVEPT: case EXIT_REASON_INVVPID:
6536                 /*
6537                  * VMX instructions trap unconditionally. This allows L1 to
6538                  * emulate them for its L2 guest, i.e., allows 3-level nesting!
6539                  */
6540                 return 1;
6541         case EXIT_REASON_CR_ACCESS:
6542                 return nested_vmx_exit_handled_cr(vcpu, vmcs12);
6543         case EXIT_REASON_DR_ACCESS:
6544                 return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
6545         case EXIT_REASON_IO_INSTRUCTION:
6546                 return nested_vmx_exit_handled_io(vcpu, vmcs12);
6547         case EXIT_REASON_MSR_READ:
6548         case EXIT_REASON_MSR_WRITE:
6549                 return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
6550         case EXIT_REASON_INVALID_STATE:
6551                 return 1;
6552         case EXIT_REASON_MWAIT_INSTRUCTION:
6553                 return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
6554         case EXIT_REASON_MONITOR_INSTRUCTION:
6555                 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
6556         case EXIT_REASON_PAUSE_INSTRUCTION:
6557                 return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
6558                         nested_cpu_has2(vmcs12,
6559                                 SECONDARY_EXEC_PAUSE_LOOP_EXITING);
6560         case EXIT_REASON_MCE_DURING_VMENTRY:
6561                 return 0;
6562         case EXIT_REASON_TPR_BELOW_THRESHOLD:
6563                 return 1;
6564         case EXIT_REASON_APIC_ACCESS:
6565                 return nested_cpu_has2(vmcs12,
6566                         SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
6567         case EXIT_REASON_EPT_VIOLATION:
6568         case EXIT_REASON_EPT_MISCONFIG:
6569                 return 0;
6570         case EXIT_REASON_PREEMPTION_TIMER:
6571                 return vmcs12->pin_based_vm_exec_control &
6572                         PIN_BASED_VMX_PREEMPTION_TIMER;
6573         case EXIT_REASON_WBINVD:
6574                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
6575         case EXIT_REASON_XSETBV:
6576                 return 1;
6577         default:
6578                 return 1;
6579         }
6580 }
6581
6582 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
6583 {
6584         *info1 = vmcs_readl(EXIT_QUALIFICATION);
6585         *info2 = vmcs_read32(VM_EXIT_INTR_INFO);
6586 }
6587
6588 /*
6589  * The guest has exited.  See if we can fix it or if we need userspace
6590  * assistance.
6591  */
6592 static int vmx_handle_exit(struct kvm_vcpu *vcpu)
6593 {
6594         struct vcpu_vmx *vmx = to_vmx(vcpu);
6595         u32 exit_reason = vmx->exit_reason;
6596         u32 vectoring_info = vmx->idt_vectoring_info;
6597
6598         /* If guest state is invalid, start emulating */
6599         if (vmx->emulation_required)
6600                 return handle_invalid_guest_state(vcpu);
6601
6602         /*
6603          * the KVM_REQ_EVENT optimization bit is only on for one entry, and if
6604          * we did not inject a still-pending event to L1 now because of
6605          * nested_run_pending, we need to re-enable this bit.
6606          */
6607         if (vmx->nested.nested_run_pending)
6608                 kvm_make_request(KVM_REQ_EVENT, vcpu);
6609
6610         if (!is_guest_mode(vcpu) && (exit_reason == EXIT_REASON_VMLAUNCH ||
6611             exit_reason == EXIT_REASON_VMRESUME))
6612                 vmx->nested.nested_run_pending = 1;
6613         else
6614                 vmx->nested.nested_run_pending = 0;
6615
6616         if (is_guest_mode(vcpu) && nested_vmx_exit_handled(vcpu)) {
6617                 nested_vmx_vmexit(vcpu);
6618                 return 1;
6619         }
6620
6621         if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
6622                 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6623                 vcpu->run->fail_entry.hardware_entry_failure_reason
6624                         = exit_reason;
6625                 return 0;
6626         }
6627
6628         if (unlikely(vmx->fail)) {
6629                 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6630                 vcpu->run->fail_entry.hardware_entry_failure_reason
6631                         = vmcs_read32(VM_INSTRUCTION_ERROR);
6632                 return 0;
6633         }
6634
6635         /*
6636          * Note:
6637          * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
6638          * delivery event since it indicates guest is accessing MMIO.
6639          * The vm-exit can be triggered again after return to guest that
6640          * will cause infinite loop.
6641          */
6642         if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
6643                         (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
6644                         exit_reason != EXIT_REASON_EPT_VIOLATION &&
6645                         exit_reason != EXIT_REASON_TASK_SWITCH)) {
6646                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6647                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
6648                 vcpu->run->internal.ndata = 2;
6649                 vcpu->run->internal.data[0] = vectoring_info;
6650                 vcpu->run->internal.data[1] = exit_reason;
6651                 return 0;
6652         }
6653
6654         if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked &&
6655             !(is_guest_mode(vcpu) && nested_cpu_has_virtual_nmis(
6656                                         get_vmcs12(vcpu), vcpu)))) {
6657                 if (vmx_interrupt_allowed(vcpu)) {
6658                         vmx->soft_vnmi_blocked = 0;
6659                 } else if (vmx->vnmi_blocked_time > 1000000000LL &&
6660                            vcpu->arch.nmi_pending) {
6661                         /*
6662                          * This CPU don't support us in finding the end of an
6663                          * NMI-blocked window if the guest runs with IRQs
6664                          * disabled. So we pull the trigger after 1 s of
6665                          * futile waiting, but inform the user about this.
6666                          */
6667                         printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
6668                                "state on VCPU %d after 1 s timeout\n",
6669                                __func__, vcpu->vcpu_id);
6670                         vmx->soft_vnmi_blocked = 0;
6671                 }
6672         }
6673
6674         if (exit_reason < kvm_vmx_max_exit_handlers
6675             && kvm_vmx_exit_handlers[exit_reason])
6676                 return kvm_vmx_exit_handlers[exit_reason](vcpu);
6677         else {
6678                 WARN_ONCE(1, "vmx: unexpected exit reason 0x%x\n", exit_reason);
6679                 kvm_queue_exception(vcpu, UD_VECTOR);
6680                 return 1;
6681         }
6682 }
6683
6684 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
6685 {
6686         if (irr == -1 || tpr < irr) {
6687                 vmcs_write32(TPR_THRESHOLD, 0);
6688                 return;
6689         }
6690
6691         vmcs_write32(TPR_THRESHOLD, irr);
6692 }
6693
6694 static void vmx_set_virtual_x2apic_mode(struct kvm_vcpu *vcpu, bool set)
6695 {
6696         u32 sec_exec_control;
6697
6698         /*
6699          * There is not point to enable virtualize x2apic without enable
6700          * apicv
6701          */
6702         if (!cpu_has_vmx_virtualize_x2apic_mode() ||
6703                                 !vmx_vm_has_apicv(vcpu->kvm))
6704                 return;
6705
6706         if (!vm_need_tpr_shadow(vcpu->kvm))
6707                 return;
6708
6709         sec_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
6710
6711         if (set) {
6712                 sec_exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6713                 sec_exec_control |= SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6714         } else {
6715                 sec_exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6716                 sec_exec_control |= SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6717         }
6718         vmcs_write32(SECONDARY_VM_EXEC_CONTROL, sec_exec_control);
6719
6720         vmx_set_msr_bitmap(vcpu);
6721 }
6722
6723 static void vmx_hwapic_isr_update(struct kvm *kvm, int isr)
6724 {
6725         u16 status;
6726         u8 old;
6727
6728         if (!vmx_vm_has_apicv(kvm))
6729                 return;
6730
6731         if (isr == -1)
6732                 isr = 0;
6733
6734         status = vmcs_read16(GUEST_INTR_STATUS);
6735         old = status >> 8;
6736         if (isr != old) {
6737                 status &= 0xff;
6738                 status |= isr << 8;
6739                 vmcs_write16(GUEST_INTR_STATUS, status);
6740         }
6741 }
6742
6743 static void vmx_set_rvi(int vector)
6744 {
6745         u16 status;
6746         u8 old;
6747
6748         status = vmcs_read16(GUEST_INTR_STATUS);
6749         old = (u8)status & 0xff;
6750         if ((u8)vector != old) {
6751                 status &= ~0xff;
6752                 status |= (u8)vector;
6753                 vmcs_write16(GUEST_INTR_STATUS, status);
6754         }
6755 }
6756
6757 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
6758 {
6759         if (max_irr == -1)
6760                 return;
6761
6762         vmx_set_rvi(max_irr);
6763 }
6764
6765 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
6766 {
6767         if (!vmx_vm_has_apicv(vcpu->kvm))
6768                 return;
6769
6770         vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
6771         vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
6772         vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
6773         vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
6774 }
6775
6776 static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
6777 {
6778         u32 exit_intr_info;
6779
6780         if (!(vmx->exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
6781               || vmx->exit_reason == EXIT_REASON_EXCEPTION_NMI))
6782                 return;
6783
6784         vmx->exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
6785         exit_intr_info = vmx->exit_intr_info;
6786
6787         /* Handle machine checks before interrupts are enabled */
6788         if (is_machine_check(exit_intr_info))
6789                 kvm_machine_check();
6790
6791         /* We need to handle NMIs before interrupts are enabled */
6792         if ((exit_intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR &&
6793             (exit_intr_info & INTR_INFO_VALID_MASK)) {
6794                 kvm_before_handle_nmi(&vmx->vcpu);
6795                 asm("int $2");
6796                 kvm_after_handle_nmi(&vmx->vcpu);
6797         }
6798 }
6799
6800 static void vmx_handle_external_intr(struct kvm_vcpu *vcpu)
6801 {
6802         u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
6803
6804         /*
6805          * If external interrupt exists, IF bit is set in rflags/eflags on the
6806          * interrupt stack frame, and interrupt will be enabled on a return
6807          * from interrupt handler.
6808          */
6809         if ((exit_intr_info & (INTR_INFO_VALID_MASK | INTR_INFO_INTR_TYPE_MASK))
6810                         == (INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR)) {
6811                 unsigned int vector;
6812                 unsigned long entry;
6813                 gate_desc *desc;
6814                 struct vcpu_vmx *vmx = to_vmx(vcpu);
6815 #ifdef CONFIG_X86_64
6816                 unsigned long tmp;
6817 #endif
6818
6819                 vector =  exit_intr_info & INTR_INFO_VECTOR_MASK;
6820                 desc = (gate_desc *)vmx->host_idt_base + vector;
6821                 entry = gate_offset(*desc);
6822                 asm volatile(
6823 #ifdef CONFIG_X86_64
6824                         "mov %%" _ASM_SP ", %[sp]\n\t"
6825                         "and $0xfffffffffffffff0, %%" _ASM_SP "\n\t"
6826                         "push $%c[ss]\n\t"
6827                         "push %[sp]\n\t"
6828 #endif
6829                         "pushf\n\t"
6830                         "orl $0x200, (%%" _ASM_SP ")\n\t"
6831                         __ASM_SIZE(push) " $%c[cs]\n\t"
6832                         "call *%[entry]\n\t"
6833                         :
6834 #ifdef CONFIG_X86_64
6835                         [sp]"=&r"(tmp)
6836 #endif
6837                         :
6838                         [entry]"r"(entry),
6839                         [ss]"i"(__KERNEL_DS),
6840                         [cs]"i"(__KERNEL_CS)
6841                         );
6842         } else
6843                 local_irq_enable();
6844 }
6845
6846 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
6847 {
6848         u32 exit_intr_info;
6849         bool unblock_nmi;
6850         u8 vector;
6851         bool idtv_info_valid;
6852
6853         idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6854
6855         if (cpu_has_virtual_nmis()) {
6856                 if (vmx->nmi_known_unmasked)
6857                         return;
6858                 /*
6859                  * Can't use vmx->exit_intr_info since we're not sure what
6860                  * the exit reason is.
6861                  */
6862                 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
6863                 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
6864                 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
6865                 /*
6866                  * SDM 3: 27.7.1.2 (September 2008)
6867                  * Re-set bit "block by NMI" before VM entry if vmexit caused by
6868                  * a guest IRET fault.
6869                  * SDM 3: 23.2.2 (September 2008)
6870                  * Bit 12 is undefined in any of the following cases:
6871                  *  If the VM exit sets the valid bit in the IDT-vectoring
6872                  *   information field.
6873                  *  If the VM exit is due to a double fault.
6874                  */
6875                 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
6876                     vector != DF_VECTOR && !idtv_info_valid)
6877                         vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6878                                       GUEST_INTR_STATE_NMI);
6879                 else
6880                         vmx->nmi_known_unmasked =
6881                                 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
6882                                   & GUEST_INTR_STATE_NMI);
6883         } else if (unlikely(vmx->soft_vnmi_blocked))
6884                 vmx->vnmi_blocked_time +=
6885                         ktime_to_ns(ktime_sub(ktime_get(), vmx->entry_time));
6886 }
6887
6888 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
6889                                       u32 idt_vectoring_info,
6890                                       int instr_len_field,
6891                                       int error_code_field)
6892 {
6893         u8 vector;
6894         int type;
6895         bool idtv_info_valid;
6896
6897         idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6898
6899         vcpu->arch.nmi_injected = false;
6900         kvm_clear_exception_queue(vcpu);
6901         kvm_clear_interrupt_queue(vcpu);
6902
6903         if (!idtv_info_valid)
6904                 return;
6905
6906         kvm_make_request(KVM_REQ_EVENT, vcpu);
6907
6908         vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
6909         type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
6910
6911         switch (type) {
6912         case INTR_TYPE_NMI_INTR:
6913                 vcpu->arch.nmi_injected = true;
6914                 /*
6915                  * SDM 3: 27.7.1.2 (September 2008)
6916                  * Clear bit "block by NMI" before VM entry if a NMI
6917                  * delivery faulted.
6918                  */
6919                 vmx_set_nmi_mask(vcpu, false);
6920                 break;
6921         case INTR_TYPE_SOFT_EXCEPTION:
6922                 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6923                 /* fall through */
6924         case INTR_TYPE_HARD_EXCEPTION:
6925                 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
6926                         u32 err = vmcs_read32(error_code_field);
6927                         kvm_queue_exception_e(vcpu, vector, err);
6928                 } else
6929                         kvm_queue_exception(vcpu, vector);
6930                 break;
6931         case INTR_TYPE_SOFT_INTR:
6932                 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6933                 /* fall through */
6934         case INTR_TYPE_EXT_INTR:
6935                 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
6936                 break;
6937         default:
6938                 break;
6939         }
6940 }
6941
6942 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
6943 {
6944         __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
6945                                   VM_EXIT_INSTRUCTION_LEN,
6946                                   IDT_VECTORING_ERROR_CODE);
6947 }
6948
6949 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
6950 {
6951         __vmx_complete_interrupts(vcpu,
6952                                   vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
6953                                   VM_ENTRY_INSTRUCTION_LEN,
6954                                   VM_ENTRY_EXCEPTION_ERROR_CODE);
6955
6956         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
6957 }
6958
6959 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
6960 {
6961         int i, nr_msrs;
6962         struct perf_guest_switch_msr *msrs;
6963
6964         msrs = perf_guest_get_msrs(&nr_msrs);
6965
6966         if (!msrs)
6967                 return;
6968
6969         for (i = 0; i < nr_msrs; i++)
6970                 if (msrs[i].host == msrs[i].guest)
6971                         clear_atomic_switch_msr(vmx, msrs[i].msr);
6972                 else
6973                         add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
6974                                         msrs[i].host);
6975 }
6976
6977 static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
6978 {
6979         struct vcpu_vmx *vmx = to_vmx(vcpu);
6980         unsigned long debugctlmsr, cr4;
6981
6982         /* Record the guest's net vcpu time for enforced NMI injections. */
6983         if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked))
6984                 vmx->entry_time = ktime_get();
6985
6986         /* Don't enter VMX if guest state is invalid, let the exit handler
6987            start emulation until we arrive back to a valid state */
6988         if (vmx->emulation_required)
6989                 return;
6990
6991         if (vmx->nested.sync_shadow_vmcs) {
6992                 copy_vmcs12_to_shadow(vmx);
6993                 vmx->nested.sync_shadow_vmcs = false;
6994         }
6995
6996         if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
6997                 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
6998         if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
6999                 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
7000
7001         cr4 = read_cr4();
7002         if (unlikely(cr4 != vmx->host_state.vmcs_host_cr4)) {
7003                 vmcs_writel(HOST_CR4, cr4);
7004                 vmx->host_state.vmcs_host_cr4 = cr4;
7005         }
7006
7007         /* When single-stepping over STI and MOV SS, we must clear the
7008          * corresponding interruptibility bits in the guest state. Otherwise
7009          * vmentry fails as it then expects bit 14 (BS) in pending debug
7010          * exceptions being set, but that's not correct for the guest debugging
7011          * case. */
7012         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
7013                 vmx_set_interrupt_shadow(vcpu, 0);
7014
7015         atomic_switch_perf_msrs(vmx);
7016         debugctlmsr = get_debugctlmsr();
7017
7018         vmx->__launched = vmx->loaded_vmcs->launched;
7019         asm(
7020                 /* Store host registers */
7021                 "push %%" _ASM_DX "; push %%" _ASM_BP ";"
7022                 "push %%" _ASM_CX " \n\t" /* placeholder for guest rcx */
7023                 "push %%" _ASM_CX " \n\t"
7024                 "cmp %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
7025                 "je 1f \n\t"
7026                 "mov %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
7027                 __ex(ASM_VMX_VMWRITE_RSP_RDX) "\n\t"
7028                 "1: \n\t"
7029                 /* Reload cr2 if changed */
7030                 "mov %c[cr2](%0), %%" _ASM_AX " \n\t"
7031                 "mov %%cr2, %%" _ASM_DX " \n\t"
7032                 "cmp %%" _ASM_AX ", %%" _ASM_DX " \n\t"
7033                 "je 2f \n\t"
7034                 "mov %%" _ASM_AX", %%cr2 \n\t"
7035                 "2: \n\t"
7036                 /* Check if vmlaunch of vmresume is needed */
7037                 "cmpl $0, %c[launched](%0) \n\t"
7038                 /* Load guest registers.  Don't clobber flags. */
7039                 "mov %c[rax](%0), %%" _ASM_AX " \n\t"
7040                 "mov %c[rbx](%0), %%" _ASM_BX " \n\t"
7041                 "mov %c[rdx](%0), %%" _ASM_DX " \n\t"
7042                 "mov %c[rsi](%0), %%" _ASM_SI " \n\t"
7043                 "mov %c[rdi](%0), %%" _ASM_DI " \n\t"
7044                 "mov %c[rbp](%0), %%" _ASM_BP " \n\t"
7045 #ifdef CONFIG_X86_64
7046                 "mov %c[r8](%0),  %%r8  \n\t"
7047                 "mov %c[r9](%0),  %%r9  \n\t"
7048                 "mov %c[r10](%0), %%r10 \n\t"
7049                 "mov %c[r11](%0), %%r11 \n\t"
7050                 "mov %c[r12](%0), %%r12 \n\t"
7051                 "mov %c[r13](%0), %%r13 \n\t"
7052                 "mov %c[r14](%0), %%r14 \n\t"
7053                 "mov %c[r15](%0), %%r15 \n\t"
7054 #endif
7055                 "mov %c[rcx](%0), %%" _ASM_CX " \n\t" /* kills %0 (ecx) */
7056
7057                 /* Enter guest mode */
7058                 "jne 1f \n\t"
7059                 __ex(ASM_VMX_VMLAUNCH) "\n\t"
7060                 "jmp 2f \n\t"
7061                 "1: " __ex(ASM_VMX_VMRESUME) "\n\t"
7062                 "2: "
7063                 /* Save guest registers, load host registers, keep flags */
7064                 "mov %0, %c[wordsize](%%" _ASM_SP ") \n\t"
7065                 "pop %0 \n\t"
7066                 "mov %%" _ASM_AX ", %c[rax](%0) \n\t"
7067                 "mov %%" _ASM_BX ", %c[rbx](%0) \n\t"
7068                 __ASM_SIZE(pop) " %c[rcx](%0) \n\t"
7069                 "mov %%" _ASM_DX ", %c[rdx](%0) \n\t"
7070                 "mov %%" _ASM_SI ", %c[rsi](%0) \n\t"
7071                 "mov %%" _ASM_DI ", %c[rdi](%0) \n\t"
7072                 "mov %%" _ASM_BP ", %c[rbp](%0) \n\t"
7073 #ifdef CONFIG_X86_64
7074                 "mov %%r8,  %c[r8](%0) \n\t"
7075                 "mov %%r9,  %c[r9](%0) \n\t"
7076                 "mov %%r10, %c[r10](%0) \n\t"
7077                 "mov %%r11, %c[r11](%0) \n\t"
7078                 "mov %%r12, %c[r12](%0) \n\t"
7079                 "mov %%r13, %c[r13](%0) \n\t"
7080                 "mov %%r14, %c[r14](%0) \n\t"
7081                 "mov %%r15, %c[r15](%0) \n\t"
7082 #endif
7083                 "mov %%cr2, %%" _ASM_AX "   \n\t"
7084                 "mov %%" _ASM_AX ", %c[cr2](%0) \n\t"
7085
7086                 "pop  %%" _ASM_BP "; pop  %%" _ASM_DX " \n\t"
7087                 "setbe %c[fail](%0) \n\t"
7088                 ".pushsection .rodata \n\t"
7089                 ".global vmx_return \n\t"
7090                 "vmx_return: " _ASM_PTR " 2b \n\t"
7091                 ".popsection"
7092               : : "c"(vmx), "d"((unsigned long)HOST_RSP),
7093                 [launched]"i"(offsetof(struct vcpu_vmx, __launched)),
7094                 [fail]"i"(offsetof(struct vcpu_vmx, fail)),
7095                 [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)),
7096                 [rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])),
7097                 [rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])),
7098                 [rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])),
7099                 [rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])),
7100                 [rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])),
7101                 [rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])),
7102                 [rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])),
7103 #ifdef CONFIG_X86_64
7104                 [r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])),
7105                 [r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])),
7106                 [r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])),
7107                 [r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])),
7108                 [r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])),
7109                 [r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])),
7110                 [r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])),
7111                 [r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])),
7112 #endif
7113                 [cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2)),
7114                 [wordsize]"i"(sizeof(ulong))
7115               : "cc", "memory"
7116 #ifdef CONFIG_X86_64
7117                 , "rax", "rbx", "rdi", "rsi"
7118                 , "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
7119 #else
7120                 , "eax", "ebx", "edi", "esi"
7121 #endif
7122               );
7123
7124         /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
7125         if (debugctlmsr)
7126                 update_debugctlmsr(debugctlmsr);
7127
7128 #ifndef CONFIG_X86_64
7129         /*
7130          * The sysexit path does not restore ds/es, so we must set them to
7131          * a reasonable value ourselves.
7132          *
7133          * We can't defer this to vmx_load_host_state() since that function
7134          * may be executed in interrupt context, which saves and restore segments
7135          * around it, nullifying its effect.
7136          */
7137         loadsegment(ds, __USER_DS);
7138         loadsegment(es, __USER_DS);
7139 #endif
7140
7141         vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
7142                                   | (1 << VCPU_EXREG_RFLAGS)
7143                                   | (1 << VCPU_EXREG_CPL)
7144                                   | (1 << VCPU_EXREG_PDPTR)
7145                                   | (1 << VCPU_EXREG_SEGMENTS)
7146                                   | (1 << VCPU_EXREG_CR3));
7147         vcpu->arch.regs_dirty = 0;
7148
7149         vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
7150
7151         vmx->loaded_vmcs->launched = 1;
7152
7153         vmx->exit_reason = vmcs_read32(VM_EXIT_REASON);
7154         trace_kvm_exit(vmx->exit_reason, vcpu, KVM_ISA_VMX);
7155
7156         vmx_complete_atomic_exit(vmx);
7157         vmx_recover_nmi_blocking(vmx);
7158         vmx_complete_interrupts(vmx);
7159 }
7160
7161 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
7162 {
7163         struct vcpu_vmx *vmx = to_vmx(vcpu);
7164
7165         free_vpid(vmx);
7166         free_loaded_vmcs(vmx->loaded_vmcs);
7167         free_nested(vmx);
7168         kfree(vmx->guest_msrs);
7169         kvm_vcpu_uninit(vcpu);
7170         kmem_cache_free(kvm_vcpu_cache, vmx);
7171 }
7172
7173 static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
7174 {
7175         int err;
7176         struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
7177         int cpu;
7178
7179         if (!vmx)
7180                 return ERR_PTR(-ENOMEM);
7181
7182         allocate_vpid(vmx);
7183
7184         err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
7185         if (err)
7186                 goto free_vcpu;
7187
7188         vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
7189         err = -ENOMEM;
7190         if (!vmx->guest_msrs) {
7191                 goto uninit_vcpu;
7192         }
7193
7194         vmx->loaded_vmcs = &vmx->vmcs01;
7195         vmx->loaded_vmcs->vmcs = alloc_vmcs();
7196         if (!vmx->loaded_vmcs->vmcs)
7197                 goto free_msrs;
7198         if (!vmm_exclusive)
7199                 kvm_cpu_vmxon(__pa(per_cpu(vmxarea, raw_smp_processor_id())));
7200         loaded_vmcs_init(vmx->loaded_vmcs);
7201         if (!vmm_exclusive)
7202                 kvm_cpu_vmxoff();
7203
7204         cpu = get_cpu();
7205         vmx_vcpu_load(&vmx->vcpu, cpu);
7206         vmx->vcpu.cpu = cpu;
7207         err = vmx_vcpu_setup(vmx);
7208         vmx_vcpu_put(&vmx->vcpu);
7209         put_cpu();
7210         if (err)
7211                 goto free_vmcs;
7212         if (vm_need_virtualize_apic_accesses(kvm)) {
7213                 err = alloc_apic_access_page(kvm);
7214                 if (err)
7215                         goto free_vmcs;
7216         }
7217
7218         if (enable_ept) {
7219                 if (!kvm->arch.ept_identity_map_addr)
7220                         kvm->arch.ept_identity_map_addr =
7221                                 VMX_EPT_IDENTITY_PAGETABLE_ADDR;
7222                 err = -ENOMEM;
7223                 if (alloc_identity_pagetable(kvm) != 0)
7224                         goto free_vmcs;
7225                 if (!init_rmode_identity_map(kvm))
7226                         goto free_vmcs;
7227         }
7228
7229         vmx->nested.current_vmptr = -1ull;
7230         vmx->nested.current_vmcs12 = NULL;
7231
7232         return &vmx->vcpu;
7233
7234 free_vmcs:
7235         free_loaded_vmcs(vmx->loaded_vmcs);
7236 free_msrs:
7237         kfree(vmx->guest_msrs);
7238 uninit_vcpu:
7239         kvm_vcpu_uninit(&vmx->vcpu);
7240 free_vcpu:
7241         free_vpid(vmx);
7242         kmem_cache_free(kvm_vcpu_cache, vmx);
7243         return ERR_PTR(err);
7244 }
7245
7246 static void __init vmx_check_processor_compat(void *rtn)
7247 {
7248         struct vmcs_config vmcs_conf;
7249
7250         *(int *)rtn = 0;
7251         if (setup_vmcs_config(&vmcs_conf) < 0)
7252                 *(int *)rtn = -EIO;
7253         if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
7254                 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
7255                                 smp_processor_id());
7256                 *(int *)rtn = -EIO;
7257         }
7258 }
7259
7260 static int get_ept_level(void)
7261 {
7262         return VMX_EPT_DEFAULT_GAW + 1;
7263 }
7264
7265 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
7266 {
7267         u64 ret;
7268
7269         /* For VT-d and EPT combination
7270          * 1. MMIO: always map as UC
7271          * 2. EPT with VT-d:
7272          *   a. VT-d without snooping control feature: can't guarantee the
7273          *      result, try to trust guest.
7274          *   b. VT-d with snooping control feature: snooping control feature of
7275          *      VT-d engine can guarantee the cache correctness. Just set it
7276          *      to WB to keep consistent with host. So the same as item 3.
7277          * 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
7278          *    consistent with host MTRR
7279          */
7280         if (is_mmio)
7281                 ret = MTRR_TYPE_UNCACHABLE << VMX_EPT_MT_EPTE_SHIFT;
7282         else if (vcpu->kvm->arch.iommu_domain &&
7283                 !(vcpu->kvm->arch.iommu_flags & KVM_IOMMU_CACHE_COHERENCY))
7284                 ret = kvm_get_guest_memory_type(vcpu, gfn) <<
7285                       VMX_EPT_MT_EPTE_SHIFT;
7286         else
7287                 ret = (MTRR_TYPE_WRBACK << VMX_EPT_MT_EPTE_SHIFT)
7288                         | VMX_EPT_IPAT_BIT;
7289
7290         return ret;
7291 }
7292
7293 static int vmx_get_lpage_level(void)
7294 {
7295         if (enable_ept && !cpu_has_vmx_ept_1g_page())
7296                 return PT_DIRECTORY_LEVEL;
7297         else
7298                 /* For shadow and EPT supported 1GB page */
7299                 return PT_PDPE_LEVEL;
7300 }
7301
7302 static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
7303 {
7304         struct kvm_cpuid_entry2 *best;
7305         struct vcpu_vmx *vmx = to_vmx(vcpu);
7306         u32 exec_control;
7307
7308         vmx->rdtscp_enabled = false;
7309         if (vmx_rdtscp_supported()) {
7310                 exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
7311                 if (exec_control & SECONDARY_EXEC_RDTSCP) {
7312                         best = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
7313                         if (best && (best->edx & bit(X86_FEATURE_RDTSCP)))
7314                                 vmx->rdtscp_enabled = true;
7315                         else {
7316                                 exec_control &= ~SECONDARY_EXEC_RDTSCP;
7317                                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
7318                                                 exec_control);
7319                         }
7320                 }
7321         }
7322
7323         /* Exposing INVPCID only when PCID is exposed */
7324         best = kvm_find_cpuid_entry(vcpu, 0x7, 0);
7325         if (vmx_invpcid_supported() &&
7326             best && (best->ebx & bit(X86_FEATURE_INVPCID)) &&
7327             guest_cpuid_has_pcid(vcpu)) {
7328                 exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
7329                 exec_control |= SECONDARY_EXEC_ENABLE_INVPCID;
7330                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
7331                              exec_control);
7332         } else {
7333                 if (cpu_has_secondary_exec_ctrls()) {
7334                         exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
7335                         exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
7336                         vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
7337                                      exec_control);
7338                 }
7339                 if (best)
7340                         best->ebx &= ~bit(X86_FEATURE_INVPCID);
7341         }
7342 }
7343
7344 static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
7345 {
7346         if (func == 1 && nested)
7347                 entry->ecx |= bit(X86_FEATURE_VMX);
7348 }
7349
7350 /*
7351  * prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
7352  * L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
7353  * with L0's requirements for its guest (a.k.a. vmsc01), so we can run the L2
7354  * guest in a way that will both be appropriate to L1's requests, and our
7355  * needs. In addition to modifying the active vmcs (which is vmcs02), this
7356  * function also has additional necessary side-effects, like setting various
7357  * vcpu->arch fields.
7358  */
7359 static void prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
7360 {
7361         struct vcpu_vmx *vmx = to_vmx(vcpu);
7362         u32 exec_control;
7363
7364         vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
7365         vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
7366         vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
7367         vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
7368         vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
7369         vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
7370         vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
7371         vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
7372         vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
7373         vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
7374         vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
7375         vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
7376         vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
7377         vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
7378         vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
7379         vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
7380         vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
7381         vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
7382         vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
7383         vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
7384         vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
7385         vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
7386         vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
7387         vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
7388         vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
7389         vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
7390         vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
7391         vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
7392         vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
7393         vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
7394         vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
7395         vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
7396         vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
7397         vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
7398         vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
7399         vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
7400
7401         vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
7402         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
7403                 vmcs12->vm_entry_intr_info_field);
7404         vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
7405                 vmcs12->vm_entry_exception_error_code);
7406         vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
7407                 vmcs12->vm_entry_instruction_len);
7408         vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
7409                 vmcs12->guest_interruptibility_info);
7410         vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
7411         kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
7412         vmcs_writel(GUEST_RFLAGS, vmcs12->guest_rflags);
7413         vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
7414                 vmcs12->guest_pending_dbg_exceptions);
7415         vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
7416         vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
7417
7418         vmcs_write64(VMCS_LINK_POINTER, -1ull);
7419
7420         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL,
7421                 (vmcs_config.pin_based_exec_ctrl |
7422                  vmcs12->pin_based_vm_exec_control));
7423
7424         if (vmcs12->pin_based_vm_exec_control & PIN_BASED_VMX_PREEMPTION_TIMER)
7425                 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE,
7426                              vmcs12->vmx_preemption_timer_value);
7427
7428         /*
7429          * Whether page-faults are trapped is determined by a combination of
7430          * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.
7431          * If enable_ept, L0 doesn't care about page faults and we should
7432          * set all of these to L1's desires. However, if !enable_ept, L0 does
7433          * care about (at least some) page faults, and because it is not easy
7434          * (if at all possible?) to merge L0 and L1's desires, we simply ask
7435          * to exit on each and every L2 page fault. This is done by setting
7436          * MASK=MATCH=0 and (see below) EB.PF=1.
7437          * Note that below we don't need special code to set EB.PF beyond the
7438          * "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
7439          * vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
7440          * !enable_ept, EB.PF is 1, so the "or" will always be 1.
7441          *
7442          * A problem with this approach (when !enable_ept) is that L1 may be
7443          * injected with more page faults than it asked for. This could have
7444          * caused problems, but in practice existing hypervisors don't care.
7445          * To fix this, we will need to emulate the PFEC checking (on the L1
7446          * page tables), using walk_addr(), when injecting PFs to L1.
7447          */
7448         vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK,
7449                 enable_ept ? vmcs12->page_fault_error_code_mask : 0);
7450         vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
7451                 enable_ept ? vmcs12->page_fault_error_code_match : 0);
7452
7453         if (cpu_has_secondary_exec_ctrls()) {
7454                 u32 exec_control = vmx_secondary_exec_control(vmx);
7455                 if (!vmx->rdtscp_enabled)
7456                         exec_control &= ~SECONDARY_EXEC_RDTSCP;
7457                 /* Take the following fields only from vmcs12 */
7458                 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
7459                 if (nested_cpu_has(vmcs12,
7460                                 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS))
7461                         exec_control |= vmcs12->secondary_vm_exec_control;
7462
7463                 if (exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) {
7464                         /*
7465                          * Translate L1 physical address to host physical
7466                          * address for vmcs02. Keep the page pinned, so this
7467                          * physical address remains valid. We keep a reference
7468                          * to it so we can release it later.
7469                          */
7470                         if (vmx->nested.apic_access_page) /* shouldn't happen */
7471                                 nested_release_page(vmx->nested.apic_access_page);
7472                         vmx->nested.apic_access_page =
7473                                 nested_get_page(vcpu, vmcs12->apic_access_addr);
7474                         /*
7475                          * If translation failed, no matter: This feature asks
7476                          * to exit when accessing the given address, and if it
7477                          * can never be accessed, this feature won't do
7478                          * anything anyway.
7479                          */
7480                         if (!vmx->nested.apic_access_page)
7481                                 exec_control &=
7482                                   ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
7483                         else
7484                                 vmcs_write64(APIC_ACCESS_ADDR,
7485                                   page_to_phys(vmx->nested.apic_access_page));
7486                 }
7487
7488                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
7489         }
7490
7491
7492         /*
7493          * Set host-state according to L0's settings (vmcs12 is irrelevant here)
7494          * Some constant fields are set here by vmx_set_constant_host_state().
7495          * Other fields are different per CPU, and will be set later when
7496          * vmx_vcpu_load() is called, and when vmx_save_host_state() is called.
7497          */
7498         vmx_set_constant_host_state(vmx);
7499
7500         /*
7501          * HOST_RSP is normally set correctly in vmx_vcpu_run() just before
7502          * entry, but only if the current (host) sp changed from the value
7503          * we wrote last (vmx->host_rsp). This cache is no longer relevant
7504          * if we switch vmcs, and rather than hold a separate cache per vmcs,
7505          * here we just force the write to happen on entry.
7506          */
7507         vmx->host_rsp = 0;
7508
7509         exec_control = vmx_exec_control(vmx); /* L0's desires */
7510         exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
7511         exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
7512         exec_control &= ~CPU_BASED_TPR_SHADOW;
7513         exec_control |= vmcs12->cpu_based_vm_exec_control;
7514         /*
7515          * Merging of IO and MSR bitmaps not currently supported.
7516          * Rather, exit every time.
7517          */
7518         exec_control &= ~CPU_BASED_USE_MSR_BITMAPS;
7519         exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
7520         exec_control |= CPU_BASED_UNCOND_IO_EXITING;
7521
7522         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
7523
7524         /* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
7525          * bitwise-or of what L1 wants to trap for L2, and what we want to
7526          * trap. Note that CR0.TS also needs updating - we do this later.
7527          */
7528         update_exception_bitmap(vcpu);
7529         vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
7530         vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
7531
7532         /* Note: IA32_MODE, LOAD_IA32_EFER are modified by vmx_set_efer below */
7533         vmcs_write32(VM_EXIT_CONTROLS,
7534                 vmcs12->vm_exit_controls | vmcs_config.vmexit_ctrl);
7535         vmcs_write32(VM_ENTRY_CONTROLS, vmcs12->vm_entry_controls |
7536                 (vmcs_config.vmentry_ctrl & ~VM_ENTRY_IA32E_MODE));
7537
7538         if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT)
7539                 vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
7540         else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
7541                 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
7542
7543
7544         set_cr4_guest_host_mask(vmx);
7545
7546         if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
7547                 vmcs_write64(TSC_OFFSET,
7548                         vmx->nested.vmcs01_tsc_offset + vmcs12->tsc_offset);
7549         else
7550                 vmcs_write64(TSC_OFFSET, vmx->nested.vmcs01_tsc_offset);
7551
7552         if (enable_vpid) {
7553                 /*
7554                  * Trivially support vpid by letting L2s share their parent
7555                  * L1's vpid. TODO: move to a more elaborate solution, giving
7556                  * each L2 its own vpid and exposing the vpid feature to L1.
7557                  */
7558                 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
7559                 vmx_flush_tlb(vcpu);
7560         }
7561
7562         if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)
7563                 vcpu->arch.efer = vmcs12->guest_ia32_efer;
7564         else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
7565                 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
7566         else
7567                 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
7568         /* Note: modifies VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
7569         vmx_set_efer(vcpu, vcpu->arch.efer);
7570
7571         /*
7572          * This sets GUEST_CR0 to vmcs12->guest_cr0, with possibly a modified
7573          * TS bit (for lazy fpu) and bits which we consider mandatory enabled.
7574          * The CR0_READ_SHADOW is what L2 should have expected to read given
7575          * the specifications by L1; It's not enough to take
7576          * vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we
7577          * have more bits than L1 expected.
7578          */
7579         vmx_set_cr0(vcpu, vmcs12->guest_cr0);
7580         vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
7581
7582         vmx_set_cr4(vcpu, vmcs12->guest_cr4);
7583         vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
7584
7585         /* shadow page tables on either EPT or shadow page tables */
7586         kvm_set_cr3(vcpu, vmcs12->guest_cr3);
7587         kvm_mmu_reset_context(vcpu);
7588
7589         kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->guest_rsp);
7590         kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->guest_rip);
7591 }
7592
7593 /*
7594  * nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1
7595  * for running an L2 nested guest.
7596  */
7597 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
7598 {
7599         struct vmcs12 *vmcs12;
7600         struct vcpu_vmx *vmx = to_vmx(vcpu);
7601         int cpu;
7602         struct loaded_vmcs *vmcs02;
7603         bool ia32e;
7604
7605         if (!nested_vmx_check_permission(vcpu) ||
7606             !nested_vmx_check_vmcs12(vcpu))
7607                 return 1;
7608
7609         skip_emulated_instruction(vcpu);
7610         vmcs12 = get_vmcs12(vcpu);
7611
7612         if (enable_shadow_vmcs)
7613                 copy_shadow_to_vmcs12(vmx);
7614
7615         /*
7616          * The nested entry process starts with enforcing various prerequisites
7617          * on vmcs12 as required by the Intel SDM, and act appropriately when
7618          * they fail: As the SDM explains, some conditions should cause the
7619          * instruction to fail, while others will cause the instruction to seem
7620          * to succeed, but return an EXIT_REASON_INVALID_STATE.
7621          * To speed up the normal (success) code path, we should avoid checking
7622          * for misconfigurations which will anyway be caught by the processor
7623          * when using the merged vmcs02.
7624          */
7625         if (vmcs12->launch_state == launch) {
7626                 nested_vmx_failValid(vcpu,
7627                         launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
7628                                : VMXERR_VMRESUME_NONLAUNCHED_VMCS);
7629                 return 1;
7630         }
7631
7632         if (vmcs12->guest_activity_state != GUEST_ACTIVITY_ACTIVE) {
7633                 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
7634                 return 1;
7635         }
7636
7637         if ((vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_MSR_BITMAPS) &&
7638                         !IS_ALIGNED(vmcs12->msr_bitmap, PAGE_SIZE)) {
7639                 /*TODO: Also verify bits beyond physical address width are 0*/
7640                 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
7641                 return 1;
7642         }
7643
7644         if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) &&
7645                         !IS_ALIGNED(vmcs12->apic_access_addr, PAGE_SIZE)) {
7646                 /*TODO: Also verify bits beyond physical address width are 0*/
7647                 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
7648                 return 1;
7649         }
7650
7651         if (vmcs12->vm_entry_msr_load_count > 0 ||
7652             vmcs12->vm_exit_msr_load_count > 0 ||
7653             vmcs12->vm_exit_msr_store_count > 0) {
7654                 pr_warn_ratelimited("%s: VMCS MSR_{LOAD,STORE} unsupported\n",
7655                                     __func__);
7656                 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
7657                 return 1;
7658         }
7659
7660         if (!vmx_control_verify(vmcs12->cpu_based_vm_exec_control,
7661               nested_vmx_procbased_ctls_low, nested_vmx_procbased_ctls_high) ||
7662             !vmx_control_verify(vmcs12->secondary_vm_exec_control,
7663               nested_vmx_secondary_ctls_low, nested_vmx_secondary_ctls_high) ||
7664             !vmx_control_verify(vmcs12->pin_based_vm_exec_control,
7665               nested_vmx_pinbased_ctls_low, nested_vmx_pinbased_ctls_high) ||
7666             !vmx_control_verify(vmcs12->vm_exit_controls,
7667               nested_vmx_exit_ctls_low, nested_vmx_exit_ctls_high) ||
7668             !vmx_control_verify(vmcs12->vm_entry_controls,
7669               nested_vmx_entry_ctls_low, nested_vmx_entry_ctls_high))
7670         {
7671                 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
7672                 return 1;
7673         }
7674
7675         if (((vmcs12->host_cr0 & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON) ||
7676             ((vmcs12->host_cr4 & VMXON_CR4_ALWAYSON) != VMXON_CR4_ALWAYSON)) {
7677                 nested_vmx_failValid(vcpu,
7678                         VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
7679                 return 1;
7680         }
7681
7682         if (((vmcs12->guest_cr0 & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON) ||
7683             ((vmcs12->guest_cr4 & VMXON_CR4_ALWAYSON) != VMXON_CR4_ALWAYSON)) {
7684                 nested_vmx_entry_failure(vcpu, vmcs12,
7685                         EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT);
7686                 return 1;
7687         }
7688         if (vmcs12->vmcs_link_pointer != -1ull) {
7689                 nested_vmx_entry_failure(vcpu, vmcs12,
7690                         EXIT_REASON_INVALID_STATE, ENTRY_FAIL_VMCS_LINK_PTR);
7691                 return 1;
7692         }
7693
7694         /*
7695          * If the load IA32_EFER VM-entry control is 1, the following checks
7696          * are performed on the field for the IA32_EFER MSR:
7697          * - Bits reserved in the IA32_EFER MSR must be 0.
7698          * - Bit 10 (corresponding to IA32_EFER.LMA) must equal the value of
7699          *   the IA-32e mode guest VM-exit control. It must also be identical
7700          *   to bit 8 (LME) if bit 31 in the CR0 field (corresponding to
7701          *   CR0.PG) is 1.
7702          */
7703         if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER) {
7704                 ia32e = (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) != 0;
7705                 if (!kvm_valid_efer(vcpu, vmcs12->guest_ia32_efer) ||
7706                     ia32e != !!(vmcs12->guest_ia32_efer & EFER_LMA) ||
7707                     ((vmcs12->guest_cr0 & X86_CR0_PG) &&
7708                      ia32e != !!(vmcs12->guest_ia32_efer & EFER_LME))) {
7709                         nested_vmx_entry_failure(vcpu, vmcs12,
7710                                 EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT);
7711                         return 1;
7712                 }
7713         }
7714
7715         /*
7716          * If the load IA32_EFER VM-exit control is 1, bits reserved in the
7717          * IA32_EFER MSR must be 0 in the field for that register. In addition,
7718          * the values of the LMA and LME bits in the field must each be that of
7719          * the host address-space size VM-exit control.
7720          */
7721         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) {
7722                 ia32e = (vmcs12->vm_exit_controls &
7723                          VM_EXIT_HOST_ADDR_SPACE_SIZE) != 0;
7724                 if (!kvm_valid_efer(vcpu, vmcs12->host_ia32_efer) ||
7725                     ia32e != !!(vmcs12->host_ia32_efer & EFER_LMA) ||
7726                     ia32e != !!(vmcs12->host_ia32_efer & EFER_LME)) {
7727                         nested_vmx_entry_failure(vcpu, vmcs12,
7728                                 EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT);
7729                         return 1;
7730                 }
7731         }
7732
7733         /*
7734          * We're finally done with prerequisite checking, and can start with
7735          * the nested entry.
7736          */
7737
7738         vmcs02 = nested_get_current_vmcs02(vmx);
7739         if (!vmcs02)
7740                 return -ENOMEM;
7741
7742         enter_guest_mode(vcpu);
7743
7744         vmx->nested.vmcs01_tsc_offset = vmcs_read64(TSC_OFFSET);
7745
7746         cpu = get_cpu();
7747         vmx->loaded_vmcs = vmcs02;
7748         vmx_vcpu_put(vcpu);
7749         vmx_vcpu_load(vcpu, cpu);
7750         vcpu->cpu = cpu;
7751         put_cpu();
7752
7753         vmx_segment_cache_clear(vmx);
7754
7755         vmcs12->launch_state = 1;
7756
7757         prepare_vmcs02(vcpu, vmcs12);
7758
7759         /*
7760          * Note no nested_vmx_succeed or nested_vmx_fail here. At this point
7761          * we are no longer running L1, and VMLAUNCH/VMRESUME has not yet
7762          * returned as far as L1 is concerned. It will only return (and set
7763          * the success flag) when L2 exits (see nested_vmx_vmexit()).
7764          */
7765         return 1;
7766 }
7767
7768 /*
7769  * On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
7770  * because L2 may have changed some cr0 bits directly (CRO_GUEST_HOST_MASK).
7771  * This function returns the new value we should put in vmcs12.guest_cr0.
7772  * It's not enough to just return the vmcs02 GUEST_CR0. Rather,
7773  *  1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
7774  *     available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0
7775  *     didn't trap the bit, because if L1 did, so would L0).
7776  *  2. Bits that L1 asked to trap (and therefore L0 also did) could not have
7777  *     been modified by L2, and L1 knows it. So just leave the old value of
7778  *     the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0
7779  *     isn't relevant, because if L0 traps this bit it can set it to anything.
7780  *  3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have
7781  *     changed these bits, and therefore they need to be updated, but L0
7782  *     didn't necessarily allow them to be changed in GUEST_CR0 - and rather
7783  *     put them in vmcs02 CR0_READ_SHADOW. So take these bits from there.
7784  */
7785 static inline unsigned long
7786 vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
7787 {
7788         return
7789         /*1*/   (vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) |
7790         /*2*/   (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) |
7791         /*3*/   (vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask |
7792                         vcpu->arch.cr0_guest_owned_bits));
7793 }
7794
7795 static inline unsigned long
7796 vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
7797 {
7798         return
7799         /*1*/   (vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) |
7800         /*2*/   (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) |
7801         /*3*/   (vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask |
7802                         vcpu->arch.cr4_guest_owned_bits));
7803 }
7804
7805 static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
7806                                        struct vmcs12 *vmcs12)
7807 {
7808         u32 idt_vectoring;
7809         unsigned int nr;
7810
7811         if (vcpu->arch.exception.pending) {
7812                 nr = vcpu->arch.exception.nr;
7813                 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
7814
7815                 if (kvm_exception_is_soft(nr)) {
7816                         vmcs12->vm_exit_instruction_len =
7817                                 vcpu->arch.event_exit_inst_len;
7818                         idt_vectoring |= INTR_TYPE_SOFT_EXCEPTION;
7819                 } else
7820                         idt_vectoring |= INTR_TYPE_HARD_EXCEPTION;
7821
7822                 if (vcpu->arch.exception.has_error_code) {
7823                         idt_vectoring |= VECTORING_INFO_DELIVER_CODE_MASK;
7824                         vmcs12->idt_vectoring_error_code =
7825                                 vcpu->arch.exception.error_code;
7826                 }
7827
7828                 vmcs12->idt_vectoring_info_field = idt_vectoring;
7829         } else if (vcpu->arch.nmi_pending) {
7830                 vmcs12->idt_vectoring_info_field =
7831                         INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR;
7832         } else if (vcpu->arch.interrupt.pending) {
7833                 nr = vcpu->arch.interrupt.nr;
7834                 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
7835
7836                 if (vcpu->arch.interrupt.soft) {
7837                         idt_vectoring |= INTR_TYPE_SOFT_INTR;
7838                         vmcs12->vm_entry_instruction_len =
7839                                 vcpu->arch.event_exit_inst_len;
7840                 } else
7841                         idt_vectoring |= INTR_TYPE_EXT_INTR;
7842
7843                 vmcs12->idt_vectoring_info_field = idt_vectoring;
7844         }
7845 }
7846
7847 /*
7848  * prepare_vmcs12 is part of what we need to do when the nested L2 guest exits
7849  * and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12),
7850  * and this function updates it to reflect the changes to the guest state while
7851  * L2 was running (and perhaps made some exits which were handled directly by L0
7852  * without going back to L1), and to reflect the exit reason.
7853  * Note that we do not have to copy here all VMCS fields, just those that
7854  * could have changed by the L2 guest or the exit - i.e., the guest-state and
7855  * exit-information fields only. Other fields are modified by L1 with VMWRITE,
7856  * which already writes to vmcs12 directly.
7857  */
7858 static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
7859 {
7860         /* update guest state fields: */
7861         vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12);
7862         vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12);
7863
7864         kvm_get_dr(vcpu, 7, (unsigned long *)&vmcs12->guest_dr7);
7865         vmcs12->guest_rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
7866         vmcs12->guest_rip = kvm_register_read(vcpu, VCPU_REGS_RIP);
7867         vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS);
7868
7869         vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR);
7870         vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR);
7871         vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR);
7872         vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR);
7873         vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR);
7874         vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR);
7875         vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR);
7876         vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR);
7877         vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT);
7878         vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT);
7879         vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT);
7880         vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT);
7881         vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT);
7882         vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT);
7883         vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT);
7884         vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT);
7885         vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT);
7886         vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT);
7887         vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES);
7888         vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES);
7889         vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES);
7890         vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES);
7891         vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES);
7892         vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES);
7893         vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES);
7894         vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES);
7895         vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE);
7896         vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE);
7897         vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE);
7898         vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE);
7899         vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE);
7900         vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE);
7901         vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE);
7902         vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE);
7903         vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE);
7904         vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE);
7905
7906         vmcs12->guest_interruptibility_info =
7907                 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
7908         vmcs12->guest_pending_dbg_exceptions =
7909                 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);
7910
7911         vmcs12->vm_entry_controls =
7912                 (vmcs12->vm_entry_controls & ~VM_ENTRY_IA32E_MODE) |
7913                 (vmcs_read32(VM_ENTRY_CONTROLS) & VM_ENTRY_IA32E_MODE);
7914
7915         /* TODO: These cannot have changed unless we have MSR bitmaps and
7916          * the relevant bit asks not to trap the change */
7917         vmcs12->guest_ia32_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
7918         if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
7919                 vmcs12->guest_ia32_pat = vmcs_read64(GUEST_IA32_PAT);
7920         vmcs12->guest_sysenter_cs = vmcs_read32(GUEST_SYSENTER_CS);
7921         vmcs12->guest_sysenter_esp = vmcs_readl(GUEST_SYSENTER_ESP);
7922         vmcs12->guest_sysenter_eip = vmcs_readl(GUEST_SYSENTER_EIP);
7923
7924         /* update exit information fields: */
7925
7926         vmcs12->vm_exit_reason  = to_vmx(vcpu)->exit_reason;
7927         vmcs12->exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7928
7929         vmcs12->vm_exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
7930         if ((vmcs12->vm_exit_intr_info &
7931              (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) ==
7932             (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK))
7933                 vmcs12->vm_exit_intr_error_code =
7934                         vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
7935         vmcs12->idt_vectoring_info_field = 0;
7936         vmcs12->vm_exit_instruction_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
7937         vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7938
7939         if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY)) {
7940                 /* vm_entry_intr_info_field is cleared on exit. Emulate this
7941                  * instead of reading the real value. */
7942                 vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK;
7943
7944                 /*
7945                  * Transfer the event that L0 or L1 may wanted to inject into
7946                  * L2 to IDT_VECTORING_INFO_FIELD.
7947                  */
7948                 vmcs12_save_pending_event(vcpu, vmcs12);
7949         }
7950
7951         /*
7952          * Drop what we picked up for L2 via vmx_complete_interrupts. It is
7953          * preserved above and would only end up incorrectly in L1.
7954          */
7955         vcpu->arch.nmi_injected = false;
7956         kvm_clear_exception_queue(vcpu);
7957         kvm_clear_interrupt_queue(vcpu);
7958 }
7959
7960 /*
7961  * A part of what we need to when the nested L2 guest exits and we want to
7962  * run its L1 parent, is to reset L1's guest state to the host state specified
7963  * in vmcs12.
7964  * This function is to be called not only on normal nested exit, but also on
7965  * a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry
7966  * Failures During or After Loading Guest State").
7967  * This function should be called when the active VMCS is L1's (vmcs01).
7968  */
7969 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
7970                                    struct vmcs12 *vmcs12)
7971 {
7972         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
7973                 vcpu->arch.efer = vmcs12->host_ia32_efer;
7974         else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
7975                 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
7976         else
7977                 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
7978         vmx_set_efer(vcpu, vcpu->arch.efer);
7979
7980         kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp);
7981         kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip);
7982         vmx_set_rflags(vcpu, X86_EFLAGS_FIXED);
7983         /*
7984          * Note that calling vmx_set_cr0 is important, even if cr0 hasn't
7985          * actually changed, because it depends on the current state of
7986          * fpu_active (which may have changed).
7987          * Note that vmx_set_cr0 refers to efer set above.
7988          */
7989         kvm_set_cr0(vcpu, vmcs12->host_cr0);
7990         /*
7991          * If we did fpu_activate()/fpu_deactivate() during L2's run, we need
7992          * to apply the same changes to L1's vmcs. We just set cr0 correctly,
7993          * but we also need to update cr0_guest_host_mask and exception_bitmap.
7994          */
7995         update_exception_bitmap(vcpu);
7996         vcpu->arch.cr0_guest_owned_bits = (vcpu->fpu_active ? X86_CR0_TS : 0);
7997         vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
7998
7999         /*
8000          * Note that CR4_GUEST_HOST_MASK is already set in the original vmcs01
8001          * (KVM doesn't change it)- no reason to call set_cr4_guest_host_mask();
8002          */
8003         vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
8004         kvm_set_cr4(vcpu, vmcs12->host_cr4);
8005
8006         /* shadow page tables on either EPT or shadow page tables */
8007         kvm_set_cr3(vcpu, vmcs12->host_cr3);
8008         kvm_mmu_reset_context(vcpu);
8009
8010         if (enable_vpid) {
8011                 /*
8012                  * Trivially support vpid by letting L2s share their parent
8013                  * L1's vpid. TODO: move to a more elaborate solution, giving
8014                  * each L2 its own vpid and exposing the vpid feature to L1.
8015                  */
8016                 vmx_flush_tlb(vcpu);
8017         }
8018
8019
8020         vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
8021         vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp);
8022         vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip);
8023         vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base);
8024         vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base);
8025         vmcs_writel(GUEST_TR_BASE, vmcs12->host_tr_base);
8026         vmcs_writel(GUEST_GS_BASE, vmcs12->host_gs_base);
8027         vmcs_writel(GUEST_FS_BASE, vmcs12->host_fs_base);
8028         vmcs_write16(GUEST_ES_SELECTOR, vmcs12->host_es_selector);
8029         vmcs_write16(GUEST_CS_SELECTOR, vmcs12->host_cs_selector);
8030         vmcs_write16(GUEST_SS_SELECTOR, vmcs12->host_ss_selector);
8031         vmcs_write16(GUEST_DS_SELECTOR, vmcs12->host_ds_selector);
8032         vmcs_write16(GUEST_FS_SELECTOR, vmcs12->host_fs_selector);
8033         vmcs_write16(GUEST_GS_SELECTOR, vmcs12->host_gs_selector);
8034         vmcs_write16(GUEST_TR_SELECTOR, vmcs12->host_tr_selector);
8035
8036         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT)
8037                 vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat);
8038         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
8039                 vmcs_write64(GUEST_IA32_PERF_GLOBAL_CTRL,
8040                         vmcs12->host_ia32_perf_global_ctrl);
8041
8042         kvm_set_dr(vcpu, 7, 0x400);
8043         vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
8044 }
8045
8046 /*
8047  * Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
8048  * and modify vmcs12 to make it see what it would expect to see there if
8049  * L2 was its real guest. Must only be called when in L2 (is_guest_mode())
8050  */
8051 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu)
8052 {
8053         struct vcpu_vmx *vmx = to_vmx(vcpu);
8054         int cpu;
8055         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
8056
8057         /* trying to cancel vmlaunch/vmresume is a bug */
8058         WARN_ON_ONCE(vmx->nested.nested_run_pending);
8059
8060         leave_guest_mode(vcpu);
8061         prepare_vmcs12(vcpu, vmcs12);
8062
8063         cpu = get_cpu();
8064         vmx->loaded_vmcs = &vmx->vmcs01;
8065         vmx_vcpu_put(vcpu);
8066         vmx_vcpu_load(vcpu, cpu);
8067         vcpu->cpu = cpu;
8068         put_cpu();
8069
8070         vmx_segment_cache_clear(vmx);
8071
8072         /* if no vmcs02 cache requested, remove the one we used */
8073         if (VMCS02_POOL_SIZE == 0)
8074                 nested_free_vmcs02(vmx, vmx->nested.current_vmptr);
8075
8076         load_vmcs12_host_state(vcpu, vmcs12);
8077
8078         /* Update TSC_OFFSET if TSC was changed while L2 ran */
8079         vmcs_write64(TSC_OFFSET, vmx->nested.vmcs01_tsc_offset);
8080
8081         /* This is needed for same reason as it was needed in prepare_vmcs02 */
8082         vmx->host_rsp = 0;
8083
8084         /* Unpin physical memory we referred to in vmcs02 */
8085         if (vmx->nested.apic_access_page) {
8086                 nested_release_page(vmx->nested.apic_access_page);
8087                 vmx->nested.apic_access_page = 0;
8088         }
8089
8090         /*
8091          * Exiting from L2 to L1, we're now back to L1 which thinks it just
8092          * finished a VMLAUNCH or VMRESUME instruction, so we need to set the
8093          * success or failure flag accordingly.
8094          */
8095         if (unlikely(vmx->fail)) {
8096                 vmx->fail = 0;
8097                 nested_vmx_failValid(vcpu, vmcs_read32(VM_INSTRUCTION_ERROR));
8098         } else
8099                 nested_vmx_succeed(vcpu);
8100         if (enable_shadow_vmcs)
8101                 vmx->nested.sync_shadow_vmcs = true;
8102 }
8103
8104 /*
8105  * L1's failure to enter L2 is a subset of a normal exit, as explained in
8106  * 23.7 "VM-entry failures during or after loading guest state" (this also
8107  * lists the acceptable exit-reason and exit-qualification parameters).
8108  * It should only be called before L2 actually succeeded to run, and when
8109  * vmcs01 is current (it doesn't leave_guest_mode() or switch vmcss).
8110  */
8111 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
8112                         struct vmcs12 *vmcs12,
8113                         u32 reason, unsigned long qualification)
8114 {
8115         load_vmcs12_host_state(vcpu, vmcs12);
8116         vmcs12->vm_exit_reason = reason | VMX_EXIT_REASONS_FAILED_VMENTRY;
8117         vmcs12->exit_qualification = qualification;
8118         nested_vmx_succeed(vcpu);
8119         if (enable_shadow_vmcs)
8120                 to_vmx(vcpu)->nested.sync_shadow_vmcs = true;
8121 }
8122
8123 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
8124                                struct x86_instruction_info *info,
8125                                enum x86_intercept_stage stage)
8126 {
8127         return X86EMUL_CONTINUE;
8128 }
8129
8130 static struct kvm_x86_ops vmx_x86_ops = {
8131         .cpu_has_kvm_support = cpu_has_kvm_support,
8132         .disabled_by_bios = vmx_disabled_by_bios,
8133         .hardware_setup = hardware_setup,
8134         .hardware_unsetup = hardware_unsetup,
8135         .check_processor_compatibility = vmx_check_processor_compat,
8136         .hardware_enable = hardware_enable,
8137         .hardware_disable = hardware_disable,
8138         .cpu_has_accelerated_tpr = report_flexpriority,
8139
8140         .vcpu_create = vmx_create_vcpu,
8141         .vcpu_free = vmx_free_vcpu,
8142         .vcpu_reset = vmx_vcpu_reset,
8143
8144         .prepare_guest_switch = vmx_save_host_state,
8145         .vcpu_load = vmx_vcpu_load,
8146         .vcpu_put = vmx_vcpu_put,
8147
8148         .update_db_bp_intercept = update_exception_bitmap,
8149         .get_msr = vmx_get_msr,
8150         .set_msr = vmx_set_msr,
8151         .get_segment_base = vmx_get_segment_base,
8152         .get_segment = vmx_get_segment,
8153         .set_segment = vmx_set_segment,
8154         .get_cpl = vmx_get_cpl,
8155         .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
8156         .decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
8157         .decache_cr3 = vmx_decache_cr3,
8158         .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
8159         .set_cr0 = vmx_set_cr0,
8160         .set_cr3 = vmx_set_cr3,
8161         .set_cr4 = vmx_set_cr4,
8162         .set_efer = vmx_set_efer,
8163         .get_idt = vmx_get_idt,
8164         .set_idt = vmx_set_idt,
8165         .get_gdt = vmx_get_gdt,
8166         .set_gdt = vmx_set_gdt,
8167         .set_dr7 = vmx_set_dr7,
8168         .cache_reg = vmx_cache_reg,
8169         .get_rflags = vmx_get_rflags,
8170         .set_rflags = vmx_set_rflags,
8171         .fpu_activate = vmx_fpu_activate,
8172         .fpu_deactivate = vmx_fpu_deactivate,
8173
8174         .tlb_flush = vmx_flush_tlb,
8175
8176         .run = vmx_vcpu_run,
8177         .handle_exit = vmx_handle_exit,
8178         .skip_emulated_instruction = skip_emulated_instruction,
8179         .set_interrupt_shadow = vmx_set_interrupt_shadow,
8180         .get_interrupt_shadow = vmx_get_interrupt_shadow,
8181         .patch_hypercall = vmx_patch_hypercall,
8182         .set_irq = vmx_inject_irq,
8183         .set_nmi = vmx_inject_nmi,
8184         .queue_exception = vmx_queue_exception,
8185         .cancel_injection = vmx_cancel_injection,
8186         .interrupt_allowed = vmx_interrupt_allowed,
8187         .nmi_allowed = vmx_nmi_allowed,
8188         .get_nmi_mask = vmx_get_nmi_mask,
8189         .set_nmi_mask = vmx_set_nmi_mask,
8190         .enable_nmi_window = enable_nmi_window,
8191         .enable_irq_window = enable_irq_window,
8192         .update_cr8_intercept = update_cr8_intercept,
8193         .set_virtual_x2apic_mode = vmx_set_virtual_x2apic_mode,
8194         .vm_has_apicv = vmx_vm_has_apicv,
8195         .load_eoi_exitmap = vmx_load_eoi_exitmap,
8196         .hwapic_irr_update = vmx_hwapic_irr_update,
8197         .hwapic_isr_update = vmx_hwapic_isr_update,
8198         .sync_pir_to_irr = vmx_sync_pir_to_irr,
8199         .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
8200
8201         .set_tss_addr = vmx_set_tss_addr,
8202         .get_tdp_level = get_ept_level,
8203         .get_mt_mask = vmx_get_mt_mask,
8204
8205         .get_exit_info = vmx_get_exit_info,
8206
8207         .get_lpage_level = vmx_get_lpage_level,
8208
8209         .cpuid_update = vmx_cpuid_update,
8210
8211         .rdtscp_supported = vmx_rdtscp_supported,
8212         .invpcid_supported = vmx_invpcid_supported,
8213
8214         .set_supported_cpuid = vmx_set_supported_cpuid,
8215
8216         .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
8217
8218         .set_tsc_khz = vmx_set_tsc_khz,
8219         .read_tsc_offset = vmx_read_tsc_offset,
8220         .write_tsc_offset = vmx_write_tsc_offset,
8221         .adjust_tsc_offset = vmx_adjust_tsc_offset,
8222         .compute_tsc_offset = vmx_compute_tsc_offset,
8223         .read_l1_tsc = vmx_read_l1_tsc,
8224
8225         .set_tdp_cr3 = vmx_set_cr3,
8226
8227         .check_intercept = vmx_check_intercept,
8228         .handle_external_intr = vmx_handle_external_intr,
8229 };
8230
8231 static int __init vmx_init(void)
8232 {
8233         int r, i, msr;
8234
8235         rdmsrl_safe(MSR_EFER, &host_efer);
8236
8237         for (i = 0; i < NR_VMX_MSR; ++i)
8238                 kvm_define_shared_msr(i, vmx_msr_index[i]);
8239
8240         vmx_io_bitmap_a = (unsigned long *)__get_free_page(GFP_KERNEL);
8241         if (!vmx_io_bitmap_a)
8242                 return -ENOMEM;
8243
8244         r = -ENOMEM;
8245
8246         vmx_io_bitmap_b = (unsigned long *)__get_free_page(GFP_KERNEL);
8247         if (!vmx_io_bitmap_b)
8248                 goto out;
8249
8250         vmx_msr_bitmap_legacy = (unsigned long *)__get_free_page(GFP_KERNEL);
8251         if (!vmx_msr_bitmap_legacy)
8252                 goto out1;
8253
8254         vmx_msr_bitmap_legacy_x2apic =
8255                                 (unsigned long *)__get_free_page(GFP_KERNEL);
8256         if (!vmx_msr_bitmap_legacy_x2apic)
8257                 goto out2;
8258
8259         vmx_msr_bitmap_longmode = (unsigned long *)__get_free_page(GFP_KERNEL);
8260         if (!vmx_msr_bitmap_longmode)
8261                 goto out3;
8262
8263         vmx_msr_bitmap_longmode_x2apic =
8264                                 (unsigned long *)__get_free_page(GFP_KERNEL);
8265         if (!vmx_msr_bitmap_longmode_x2apic)
8266                 goto out4;
8267         vmx_vmread_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);
8268         if (!vmx_vmread_bitmap)
8269                 goto out5;
8270
8271         vmx_vmwrite_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);
8272         if (!vmx_vmwrite_bitmap)
8273                 goto out6;
8274
8275         memset(vmx_vmread_bitmap, 0xff, PAGE_SIZE);
8276         memset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE);
8277         /* shadowed read/write fields */
8278         for (i = 0; i < max_shadow_read_write_fields; i++) {
8279                 clear_bit(shadow_read_write_fields[i], vmx_vmwrite_bitmap);
8280                 clear_bit(shadow_read_write_fields[i], vmx_vmread_bitmap);
8281         }
8282         /* shadowed read only fields */
8283         for (i = 0; i < max_shadow_read_only_fields; i++)
8284                 clear_bit(shadow_read_only_fields[i], vmx_vmread_bitmap);
8285
8286         /*
8287          * Allow direct access to the PC debug port (it is often used for I/O
8288          * delays, but the vmexits simply slow things down).
8289          */
8290         memset(vmx_io_bitmap_a, 0xff, PAGE_SIZE);
8291         clear_bit(0x80, vmx_io_bitmap_a);
8292
8293         memset(vmx_io_bitmap_b, 0xff, PAGE_SIZE);
8294
8295         memset(vmx_msr_bitmap_legacy, 0xff, PAGE_SIZE);
8296         memset(vmx_msr_bitmap_longmode, 0xff, PAGE_SIZE);
8297
8298         set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
8299
8300         r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
8301                      __alignof__(struct vcpu_vmx), THIS_MODULE);
8302         if (r)
8303                 goto out7;
8304
8305 #ifdef CONFIG_KEXEC
8306         rcu_assign_pointer(crash_vmclear_loaded_vmcss,
8307                            crash_vmclear_local_loaded_vmcss);
8308 #endif
8309
8310         vmx_disable_intercept_for_msr(MSR_FS_BASE, false);
8311         vmx_disable_intercept_for_msr(MSR_GS_BASE, false);
8312         vmx_disable_intercept_for_msr(MSR_KERNEL_GS_BASE, true);
8313         vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_CS, false);
8314         vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_ESP, false);
8315         vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_EIP, false);
8316         memcpy(vmx_msr_bitmap_legacy_x2apic,
8317                         vmx_msr_bitmap_legacy, PAGE_SIZE);
8318         memcpy(vmx_msr_bitmap_longmode_x2apic,
8319                         vmx_msr_bitmap_longmode, PAGE_SIZE);
8320
8321         if (enable_apicv) {
8322                 for (msr = 0x800; msr <= 0x8ff; msr++)
8323                         vmx_disable_intercept_msr_read_x2apic(msr);
8324
8325                 /* According SDM, in x2apic mode, the whole id reg is used.
8326                  * But in KVM, it only use the highest eight bits. Need to
8327                  * intercept it */
8328                 vmx_enable_intercept_msr_read_x2apic(0x802);
8329                 /* TMCCT */
8330                 vmx_enable_intercept_msr_read_x2apic(0x839);
8331                 /* TPR */
8332                 vmx_disable_intercept_msr_write_x2apic(0x808);
8333                 /* EOI */
8334                 vmx_disable_intercept_msr_write_x2apic(0x80b);
8335                 /* SELF-IPI */
8336                 vmx_disable_intercept_msr_write_x2apic(0x83f);
8337         }
8338
8339         if (enable_ept) {
8340                 kvm_mmu_set_mask_ptes(0ull,
8341                         (enable_ept_ad_bits) ? VMX_EPT_ACCESS_BIT : 0ull,
8342                         (enable_ept_ad_bits) ? VMX_EPT_DIRTY_BIT : 0ull,
8343                         0ull, VMX_EPT_EXECUTABLE_MASK);
8344                 ept_set_mmio_spte_mask();
8345                 kvm_enable_tdp();
8346         } else
8347                 kvm_disable_tdp();
8348
8349         return 0;
8350
8351 out7:
8352         free_page((unsigned long)vmx_vmwrite_bitmap);
8353 out6:
8354         free_page((unsigned long)vmx_vmread_bitmap);
8355 out5:
8356         free_page((unsigned long)vmx_msr_bitmap_longmode_x2apic);
8357 out4:
8358         free_page((unsigned long)vmx_msr_bitmap_longmode);
8359 out3:
8360         free_page((unsigned long)vmx_msr_bitmap_legacy_x2apic);
8361 out2:
8362         free_page((unsigned long)vmx_msr_bitmap_legacy);
8363 out1:
8364         free_page((unsigned long)vmx_io_bitmap_b);
8365 out:
8366         free_page((unsigned long)vmx_io_bitmap_a);
8367         return r;
8368 }
8369
8370 static void __exit vmx_exit(void)
8371 {
8372         free_page((unsigned long)vmx_msr_bitmap_legacy_x2apic);
8373         free_page((unsigned long)vmx_msr_bitmap_longmode_x2apic);
8374         free_page((unsigned long)vmx_msr_bitmap_legacy);
8375         free_page((unsigned long)vmx_msr_bitmap_longmode);
8376         free_page((unsigned long)vmx_io_bitmap_b);
8377         free_page((unsigned long)vmx_io_bitmap_a);
8378         free_page((unsigned long)vmx_vmwrite_bitmap);
8379         free_page((unsigned long)vmx_vmread_bitmap);
8380
8381 #ifdef CONFIG_KEXEC
8382         rcu_assign_pointer(crash_vmclear_loaded_vmcss, NULL);
8383         synchronize_rcu();
8384 #endif
8385
8386         kvm_exit();
8387 }
8388
8389 module_init(vmx_init)
8390 module_exit(vmx_exit)