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