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