~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/arch/x86/kvm/vmx.c

Version: ~ [ linux-5.11-rc3 ] ~ [ linux-5.10.7 ] ~ [ linux-5.9.16 ] ~ [ linux-5.8.18 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.89 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.167 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.215 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.251 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.251 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.140 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.85 ] ~ [ linux-3.15.10 ] ~ [ linux-3.14.79 ] ~ [ linux-3.13.11 ] ~ [ linux-3.12.74 ] ~ [ linux-3.11.10 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

  1 /*
  2  * Kernel-based Virtual Machine driver for Linux
  3  *
  4  * This module enables machines with Intel VT-x extensions to run virtual
  5  * machines without emulation or binary translation.
  6  *
  7  * Copyright (C) 2006 Qumranet, Inc.
  8  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
  9  *
 10  * Authors:
 11  *   Avi Kivity   <avi@qumranet.com>
 12  *   Yaniv Kamay  <yaniv@qumranet.com>
 13  *
 14  * This work is licensed under the terms of the GNU GPL, version 2.  See
 15  * the COPYING file in the top-level directory.
 16  *
 17  */
 18 
 19 #include "irq.h"
 20 #include "mmu.h"
 21 #include "cpuid.h"
 22 #include "lapic.h"
 23 
 24 #include <linux/kvm_host.h>
 25 #include <linux/module.h>
 26 #include <linux/kernel.h>
 27 #include <linux/mm.h>
 28 #include <linux/highmem.h>
 29 #include <linux/sched.h>
 30 #include <linux/moduleparam.h>
 31 #include <linux/mod_devicetable.h>
 32 #include <linux/trace_events.h>
 33 #include <linux/slab.h>
 34 #include <linux/tboot.h>
 35 #include <linux/hrtimer.h>
 36 #include "kvm_cache_regs.h"
 37 #include "x86.h"
 38 
 39 #include <asm/cpu.h>
 40 #include <asm/io.h>
 41 #include <asm/desc.h>
 42 #include <asm/vmx.h>
 43 #include <asm/virtext.h>
 44 #include <asm/mce.h>
 45 #include <asm/fpu/internal.h>
 46 #include <asm/perf_event.h>
 47 #include <asm/debugreg.h>
 48 #include <asm/kexec.h>
 49 #include <asm/apic.h>
 50 #include <asm/irq_remapping.h>
 51 
 52 #include "trace.h"
 53 #include "pmu.h"
 54 
 55 #define __ex(x) __kvm_handle_fault_on_reboot(x)
 56 #define __ex_clear(x, reg) \
 57         ____kvm_handle_fault_on_reboot(x, "xor " reg " , " reg)
 58 
 59 MODULE_AUTHOR("Qumranet");
 60 MODULE_LICENSE("GPL");
 61 
 62 static const struct x86_cpu_id vmx_cpu_id[] = {
 63         X86_FEATURE_MATCH(X86_FEATURE_VMX),
 64         {}
 65 };
 66 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
 67 
 68 static bool __read_mostly enable_vpid = 1;
 69 module_param_named(vpid, enable_vpid, bool, 0444);
 70 
 71 static bool __read_mostly flexpriority_enabled = 1;
 72 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
 73 
 74 static bool __read_mostly enable_ept = 1;
 75 module_param_named(ept, enable_ept, bool, S_IRUGO);
 76 
 77 static bool __read_mostly enable_unrestricted_guest = 1;
 78 module_param_named(unrestricted_guest,
 79                         enable_unrestricted_guest, bool, S_IRUGO);
 80 
 81 static bool __read_mostly enable_ept_ad_bits = 1;
 82 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
 83 
 84 static bool __read_mostly emulate_invalid_guest_state = true;
 85 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
 86 
 87 static bool __read_mostly vmm_exclusive = 1;
 88 module_param(vmm_exclusive, bool, S_IRUGO);
 89 
 90 static bool __read_mostly fasteoi = 1;
 91 module_param(fasteoi, bool, S_IRUGO);
 92 
 93 static bool __read_mostly enable_apicv = 1;
 94 module_param(enable_apicv, bool, S_IRUGO);
 95 
 96 static bool __read_mostly enable_shadow_vmcs = 1;
 97 module_param_named(enable_shadow_vmcs, enable_shadow_vmcs, bool, S_IRUGO);
 98 /*
 99  * If nested=1, nested virtualization is supported, i.e., guests may use
100  * VMX and be a hypervisor for its own guests. If nested=0, guests may not
101  * use VMX instructions.
102  */
103 static bool __read_mostly nested = 0;
104 module_param(nested, bool, S_IRUGO);
105 
106 static u64 __read_mostly host_xss;
107 
108 static bool __read_mostly enable_pml = 1;
109 module_param_named(pml, enable_pml, bool, S_IRUGO);
110 
111 #define KVM_VMX_TSC_MULTIPLIER_MAX     0xffffffffffffffffULL
112 
113 /* Guest_tsc -> host_tsc conversion requires 64-bit division.  */
114 static int __read_mostly cpu_preemption_timer_multi;
115 static bool __read_mostly enable_preemption_timer = 1;
116 #ifdef CONFIG_X86_64
117 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
118 #endif
119 
120 #define KVM_GUEST_CR0_MASK (X86_CR0_NW | X86_CR0_CD)
121 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST (X86_CR0_WP | X86_CR0_NE)
122 #define KVM_VM_CR0_ALWAYS_ON                                            \
123         (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE)
124 #define KVM_CR4_GUEST_OWNED_BITS                                      \
125         (X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR      \
126          | X86_CR4_OSXMMEXCPT | X86_CR4_TSD)
127 
128 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
129 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
130 
131 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
132 
133 #define VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE 5
134 
135 /*
136  * These 2 parameters are used to config the controls for Pause-Loop Exiting:
137  * ple_gap:    upper bound on the amount of time between two successive
138  *             executions of PAUSE in a loop. Also indicate if ple enabled.
139  *             According to test, this time is usually smaller than 128 cycles.
140  * ple_window: upper bound on the amount of time a guest is allowed to execute
141  *             in a PAUSE loop. Tests indicate that most spinlocks are held for
142  *             less than 2^12 cycles
143  * Time is measured based on a counter that runs at the same rate as the TSC,
144  * refer SDM volume 3b section 21.6.13 & 22.1.3.
145  */
146 #define KVM_VMX_DEFAULT_PLE_GAP           128
147 #define KVM_VMX_DEFAULT_PLE_WINDOW        4096
148 #define KVM_VMX_DEFAULT_PLE_WINDOW_GROW   2
149 #define KVM_VMX_DEFAULT_PLE_WINDOW_SHRINK 0
150 #define KVM_VMX_DEFAULT_PLE_WINDOW_MAX    \
151                 INT_MAX / KVM_VMX_DEFAULT_PLE_WINDOW_GROW
152 
153 static int ple_gap = KVM_VMX_DEFAULT_PLE_GAP;
154 module_param(ple_gap, int, S_IRUGO);
155 
156 static int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
157 module_param(ple_window, int, S_IRUGO);
158 
159 /* Default doubles per-vcpu window every exit. */
160 static int ple_window_grow = KVM_VMX_DEFAULT_PLE_WINDOW_GROW;
161 module_param(ple_window_grow, int, S_IRUGO);
162 
163 /* Default resets per-vcpu window every exit to ple_window. */
164 static int ple_window_shrink = KVM_VMX_DEFAULT_PLE_WINDOW_SHRINK;
165 module_param(ple_window_shrink, int, S_IRUGO);
166 
167 /* Default is to compute the maximum so we can never overflow. */
168 static int ple_window_actual_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
169 static int ple_window_max        = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
170 module_param(ple_window_max, int, S_IRUGO);
171 
172 extern const ulong vmx_return;
173 
174 #define NR_AUTOLOAD_MSRS 8
175 #define VMCS02_POOL_SIZE 1
176 
177 struct vmcs {
178         u32 revision_id;
179         u32 abort;
180         char data[0];
181 };
182 
183 /*
184  * Track a VMCS that may be loaded on a certain CPU. If it is (cpu!=-1), also
185  * remember whether it was VMLAUNCHed, and maintain a linked list of all VMCSs
186  * loaded on this CPU (so we can clear them if the CPU goes down).
187  */
188 struct loaded_vmcs {
189         struct vmcs *vmcs;
190         int cpu;
191         int launched;
192         struct list_head loaded_vmcss_on_cpu_link;
193 };
194 
195 struct shared_msr_entry {
196         unsigned index;
197         u64 data;
198         u64 mask;
199 };
200 
201 /*
202  * struct vmcs12 describes the state that our guest hypervisor (L1) keeps for a
203  * single nested guest (L2), hence the name vmcs12. Any VMX implementation has
204  * a VMCS structure, and vmcs12 is our emulated VMX's VMCS. This structure is
205  * stored in guest memory specified by VMPTRLD, but is opaque to the guest,
206  * which must access it using VMREAD/VMWRITE/VMCLEAR instructions.
207  * More than one of these structures may exist, if L1 runs multiple L2 guests.
208  * nested_vmx_run() will use the data here to build a vmcs02: a VMCS for the
209  * underlying hardware which will be used to run L2.
210  * This structure is packed to ensure that its layout is identical across
211  * machines (necessary for live migration).
212  * If there are changes in this struct, VMCS12_REVISION must be changed.
213  */
214 typedef u64 natural_width;
215 struct __packed vmcs12 {
216         /* According to the Intel spec, a VMCS region must start with the
217          * following two fields. Then follow implementation-specific data.
218          */
219         u32 revision_id;
220         u32 abort;
221 
222         u32 launch_state; /* set to 0 by VMCLEAR, to 1 by VMLAUNCH */
223         u32 padding[7]; /* room for future expansion */
224 
225         u64 io_bitmap_a;
226         u64 io_bitmap_b;
227         u64 msr_bitmap;
228         u64 vm_exit_msr_store_addr;
229         u64 vm_exit_msr_load_addr;
230         u64 vm_entry_msr_load_addr;
231         u64 tsc_offset;
232         u64 virtual_apic_page_addr;
233         u64 apic_access_addr;
234         u64 posted_intr_desc_addr;
235         u64 ept_pointer;
236         u64 eoi_exit_bitmap0;
237         u64 eoi_exit_bitmap1;
238         u64 eoi_exit_bitmap2;
239         u64 eoi_exit_bitmap3;
240         u64 xss_exit_bitmap;
241         u64 guest_physical_address;
242         u64 vmcs_link_pointer;
243         u64 guest_ia32_debugctl;
244         u64 guest_ia32_pat;
245         u64 guest_ia32_efer;
246         u64 guest_ia32_perf_global_ctrl;
247         u64 guest_pdptr0;
248         u64 guest_pdptr1;
249         u64 guest_pdptr2;
250         u64 guest_pdptr3;
251         u64 guest_bndcfgs;
252         u64 host_ia32_pat;
253         u64 host_ia32_efer;
254         u64 host_ia32_perf_global_ctrl;
255         u64 padding64[8]; /* room for future expansion */
256         /*
257          * To allow migration of L1 (complete with its L2 guests) between
258          * machines of different natural widths (32 or 64 bit), we cannot have
259          * unsigned long fields with no explict size. We use u64 (aliased
260          * natural_width) instead. Luckily, x86 is little-endian.
261          */
262         natural_width cr0_guest_host_mask;
263         natural_width cr4_guest_host_mask;
264         natural_width cr0_read_shadow;
265         natural_width cr4_read_shadow;
266         natural_width cr3_target_value0;
267         natural_width cr3_target_value1;
268         natural_width cr3_target_value2;
269         natural_width cr3_target_value3;
270         natural_width exit_qualification;
271         natural_width guest_linear_address;
272         natural_width guest_cr0;
273         natural_width guest_cr3;
274         natural_width guest_cr4;
275         natural_width guest_es_base;
276         natural_width guest_cs_base;
277         natural_width guest_ss_base;
278         natural_width guest_ds_base;
279         natural_width guest_fs_base;
280         natural_width guest_gs_base;
281         natural_width guest_ldtr_base;
282         natural_width guest_tr_base;
283         natural_width guest_gdtr_base;
284         natural_width guest_idtr_base;
285         natural_width guest_dr7;
286         natural_width guest_rsp;
287         natural_width guest_rip;
288         natural_width guest_rflags;
289         natural_width guest_pending_dbg_exceptions;
290         natural_width guest_sysenter_esp;
291         natural_width guest_sysenter_eip;
292         natural_width host_cr0;
293         natural_width host_cr3;
294         natural_width host_cr4;
295         natural_width host_fs_base;
296         natural_width host_gs_base;
297         natural_width host_tr_base;
298         natural_width host_gdtr_base;
299         natural_width host_idtr_base;
300         natural_width host_ia32_sysenter_esp;
301         natural_width host_ia32_sysenter_eip;
302         natural_width host_rsp;
303         natural_width host_rip;
304         natural_width paddingl[8]; /* room for future expansion */
305         u32 pin_based_vm_exec_control;
306         u32 cpu_based_vm_exec_control;
307         u32 exception_bitmap;
308         u32 page_fault_error_code_mask;
309         u32 page_fault_error_code_match;
310         u32 cr3_target_count;
311         u32 vm_exit_controls;
312         u32 vm_exit_msr_store_count;
313         u32 vm_exit_msr_load_count;
314         u32 vm_entry_controls;
315         u32 vm_entry_msr_load_count;
316         u32 vm_entry_intr_info_field;
317         u32 vm_entry_exception_error_code;
318         u32 vm_entry_instruction_len;
319         u32 tpr_threshold;
320         u32 secondary_vm_exec_control;
321         u32 vm_instruction_error;
322         u32 vm_exit_reason;
323         u32 vm_exit_intr_info;
324         u32 vm_exit_intr_error_code;
325         u32 idt_vectoring_info_field;
326         u32 idt_vectoring_error_code;
327         u32 vm_exit_instruction_len;
328         u32 vmx_instruction_info;
329         u32 guest_es_limit;
330         u32 guest_cs_limit;
331         u32 guest_ss_limit;
332         u32 guest_ds_limit;
333         u32 guest_fs_limit;
334         u32 guest_gs_limit;
335         u32 guest_ldtr_limit;
336         u32 guest_tr_limit;
337         u32 guest_gdtr_limit;
338         u32 guest_idtr_limit;
339         u32 guest_es_ar_bytes;
340         u32 guest_cs_ar_bytes;
341         u32 guest_ss_ar_bytes;
342         u32 guest_ds_ar_bytes;
343         u32 guest_fs_ar_bytes;
344         u32 guest_gs_ar_bytes;
345         u32 guest_ldtr_ar_bytes;
346         u32 guest_tr_ar_bytes;
347         u32 guest_interruptibility_info;
348         u32 guest_activity_state;
349         u32 guest_sysenter_cs;
350         u32 host_ia32_sysenter_cs;
351         u32 vmx_preemption_timer_value;
352         u32 padding32[7]; /* room for future expansion */
353         u16 virtual_processor_id;
354         u16 posted_intr_nv;
355         u16 guest_es_selector;
356         u16 guest_cs_selector;
357         u16 guest_ss_selector;
358         u16 guest_ds_selector;
359         u16 guest_fs_selector;
360         u16 guest_gs_selector;
361         u16 guest_ldtr_selector;
362         u16 guest_tr_selector;
363         u16 guest_intr_status;
364         u16 host_es_selector;
365         u16 host_cs_selector;
366         u16 host_ss_selector;
367         u16 host_ds_selector;
368         u16 host_fs_selector;
369         u16 host_gs_selector;
370         u16 host_tr_selector;
371 };
372 
373 /*
374  * VMCS12_REVISION is an arbitrary id that should be changed if the content or
375  * layout of struct vmcs12 is changed. MSR_IA32_VMX_BASIC returns this id, and
376  * VMPTRLD verifies that the VMCS region that L1 is loading contains this id.
377  */
378 #define VMCS12_REVISION 0x11e57ed0
379 
380 /*
381  * VMCS12_SIZE is the number of bytes L1 should allocate for the VMXON region
382  * and any VMCS region. Although only sizeof(struct vmcs12) are used by the
383  * current implementation, 4K are reserved to avoid future complications.
384  */
385 #define VMCS12_SIZE 0x1000
386 
387 /* Used to remember the last vmcs02 used for some recently used vmcs12s */
388 struct vmcs02_list {
389         struct list_head list;
390         gpa_t vmptr;
391         struct loaded_vmcs vmcs02;
392 };
393 
394 /*
395  * The nested_vmx structure is part of vcpu_vmx, and holds information we need
396  * for correct emulation of VMX (i.e., nested VMX) on this vcpu.
397  */
398 struct nested_vmx {
399         /* Has the level1 guest done vmxon? */
400         bool vmxon;
401         gpa_t vmxon_ptr;
402 
403         /* The guest-physical address of the current VMCS L1 keeps for L2 */
404         gpa_t current_vmptr;
405         /* The host-usable pointer to the above */
406         struct page *current_vmcs12_page;
407         struct vmcs12 *current_vmcs12;
408         /*
409          * Cache of the guest's VMCS, existing outside of guest memory.
410          * Loaded from guest memory during VMPTRLD. Flushed to guest
411          * memory during VMXOFF, VMCLEAR, VMPTRLD.
412          */
413         struct vmcs12 *cached_vmcs12;
414         struct vmcs *current_shadow_vmcs;
415         /*
416          * Indicates if the shadow vmcs must be updated with the
417          * data hold by vmcs12
418          */
419         bool sync_shadow_vmcs;
420 
421         /* vmcs02_list cache of VMCSs recently used to run L2 guests */
422         struct list_head vmcs02_pool;
423         int vmcs02_num;
424         u64 vmcs01_tsc_offset;
425         bool change_vmcs01_virtual_x2apic_mode;
426         /* L2 must run next, and mustn't decide to exit to L1. */
427         bool nested_run_pending;
428         /*
429          * Guest pages referred to in vmcs02 with host-physical pointers, so
430          * we must keep them pinned while L2 runs.
431          */
432         struct page *apic_access_page;
433         struct page *virtual_apic_page;
434         struct page *pi_desc_page;
435         struct pi_desc *pi_desc;
436         bool pi_pending;
437         u16 posted_intr_nv;
438 
439         unsigned long *msr_bitmap;
440 
441         struct hrtimer preemption_timer;
442         bool preemption_timer_expired;
443 
444         /* to migrate it to L2 if VM_ENTRY_LOAD_DEBUG_CONTROLS is off */
445         u64 vmcs01_debugctl;
446 
447         u16 vpid02;
448         u16 last_vpid;
449 
450         u32 nested_vmx_procbased_ctls_low;
451         u32 nested_vmx_procbased_ctls_high;
452         u32 nested_vmx_true_procbased_ctls_low;
453         u32 nested_vmx_secondary_ctls_low;
454         u32 nested_vmx_secondary_ctls_high;
455         u32 nested_vmx_pinbased_ctls_low;
456         u32 nested_vmx_pinbased_ctls_high;
457         u32 nested_vmx_exit_ctls_low;
458         u32 nested_vmx_exit_ctls_high;
459         u32 nested_vmx_true_exit_ctls_low;
460         u32 nested_vmx_entry_ctls_low;
461         u32 nested_vmx_entry_ctls_high;
462         u32 nested_vmx_true_entry_ctls_low;
463         u32 nested_vmx_misc_low;
464         u32 nested_vmx_misc_high;
465         u32 nested_vmx_ept_caps;
466         u32 nested_vmx_vpid_caps;
467 };
468 
469 #define POSTED_INTR_ON  0
470 #define POSTED_INTR_SN  1
471 
472 /* Posted-Interrupt Descriptor */
473 struct pi_desc {
474         u32 pir[8];     /* Posted interrupt requested */
475         union {
476                 struct {
477                                 /* bit 256 - Outstanding Notification */
478                         u16     on      : 1,
479                                 /* bit 257 - Suppress Notification */
480                                 sn      : 1,
481                                 /* bit 271:258 - Reserved */
482                                 rsvd_1  : 14;
483                                 /* bit 279:272 - Notification Vector */
484                         u8      nv;
485                                 /* bit 287:280 - Reserved */
486                         u8      rsvd_2;
487                                 /* bit 319:288 - Notification Destination */
488                         u32     ndst;
489                 };
490                 u64 control;
491         };
492         u32 rsvd[6];
493 } __aligned(64);
494 
495 static bool pi_test_and_set_on(struct pi_desc *pi_desc)
496 {
497         return test_and_set_bit(POSTED_INTR_ON,
498                         (unsigned long *)&pi_desc->control);
499 }
500 
501 static bool pi_test_and_clear_on(struct pi_desc *pi_desc)
502 {
503         return test_and_clear_bit(POSTED_INTR_ON,
504                         (unsigned long *)&pi_desc->control);
505 }
506 
507 static int pi_test_and_set_pir(int vector, struct pi_desc *pi_desc)
508 {
509         return test_and_set_bit(vector, (unsigned long *)pi_desc->pir);
510 }
511 
512 static inline void pi_clear_sn(struct pi_desc *pi_desc)
513 {
514         return clear_bit(POSTED_INTR_SN,
515                         (unsigned long *)&pi_desc->control);
516 }
517 
518 static inline void pi_set_sn(struct pi_desc *pi_desc)
519 {
520         return set_bit(POSTED_INTR_SN,
521                         (unsigned long *)&pi_desc->control);
522 }
523 
524 static inline int pi_test_on(struct pi_desc *pi_desc)
525 {
526         return test_bit(POSTED_INTR_ON,
527                         (unsigned long *)&pi_desc->control);
528 }
529 
530 static inline int pi_test_sn(struct pi_desc *pi_desc)
531 {
532         return test_bit(POSTED_INTR_SN,
533                         (unsigned long *)&pi_desc->control);
534 }
535 
536 struct vcpu_vmx {
537         struct kvm_vcpu       vcpu;
538         unsigned long         host_rsp;
539         u8                    fail;
540         bool                  nmi_known_unmasked;
541         u32                   exit_intr_info;
542         u32                   idt_vectoring_info;
543         ulong                 rflags;
544         struct shared_msr_entry *guest_msrs;
545         int                   nmsrs;
546         int                   save_nmsrs;
547         unsigned long         host_idt_base;
548 #ifdef CONFIG_X86_64
549         u64                   msr_host_kernel_gs_base;
550         u64                   msr_guest_kernel_gs_base;
551 #endif
552         u32 vm_entry_controls_shadow;
553         u32 vm_exit_controls_shadow;
554         /*
555          * loaded_vmcs points to the VMCS currently used in this vcpu. For a
556          * non-nested (L1) guest, it always points to vmcs01. For a nested
557          * guest (L2), it points to a different VMCS.
558          */
559         struct loaded_vmcs    vmcs01;
560         struct loaded_vmcs   *loaded_vmcs;
561         bool                  __launched; /* temporary, used in vmx_vcpu_run */
562         struct msr_autoload {
563                 unsigned nr;
564                 struct vmx_msr_entry guest[NR_AUTOLOAD_MSRS];
565                 struct vmx_msr_entry host[NR_AUTOLOAD_MSRS];
566         } msr_autoload;
567         struct {
568                 int           loaded;
569                 u16           fs_sel, gs_sel, ldt_sel;
570 #ifdef CONFIG_X86_64
571                 u16           ds_sel, es_sel;
572 #endif
573                 int           gs_ldt_reload_needed;
574                 int           fs_reload_needed;
575                 u64           msr_host_bndcfgs;
576                 unsigned long vmcs_host_cr4;    /* May not match real cr4 */
577         } host_state;
578         struct {
579                 int vm86_active;
580                 ulong save_rflags;
581                 struct kvm_segment segs[8];
582         } rmode;
583         struct {
584                 u32 bitmask; /* 4 bits per segment (1 bit per field) */
585                 struct kvm_save_segment {
586                         u16 selector;
587                         unsigned long base;
588                         u32 limit;
589                         u32 ar;
590                 } seg[8];
591         } segment_cache;
592         int vpid;
593         bool emulation_required;
594 
595         /* Support for vnmi-less CPUs */
596         int soft_vnmi_blocked;
597         ktime_t entry_time;
598         s64 vnmi_blocked_time;
599         u32 exit_reason;
600 
601         /* Posted interrupt descriptor */
602         struct pi_desc pi_desc;
603 
604         /* Support for a guest hypervisor (nested VMX) */
605         struct nested_vmx nested;
606 
607         /* Dynamic PLE window. */
608         int ple_window;
609         bool ple_window_dirty;
610 
611         /* Support for PML */
612 #define PML_ENTITY_NUM          512
613         struct page *pml_pg;
614 
615         /* apic deadline value in host tsc */
616         u64 hv_deadline_tsc;
617 
618         u64 current_tsc_ratio;
619 
620         bool guest_pkru_valid;
621         u32 guest_pkru;
622         u32 host_pkru;
623 
624         /*
625          * Only bits masked by msr_ia32_feature_control_valid_bits can be set in
626          * msr_ia32_feature_control. FEATURE_CONTROL_LOCKED is always included
627          * in msr_ia32_feature_control_valid_bits.
628          */
629         u64 msr_ia32_feature_control;
630         u64 msr_ia32_feature_control_valid_bits;
631 };
632 
633 enum segment_cache_field {
634         SEG_FIELD_SEL = 0,
635         SEG_FIELD_BASE = 1,
636         SEG_FIELD_LIMIT = 2,
637         SEG_FIELD_AR = 3,
638 
639         SEG_FIELD_NR = 4
640 };
641 
642 static inline struct vcpu_vmx *to_vmx(struct kvm_vcpu *vcpu)
643 {
644         return container_of(vcpu, struct vcpu_vmx, vcpu);
645 }
646 
647 static struct pi_desc *vcpu_to_pi_desc(struct kvm_vcpu *vcpu)
648 {
649         return &(to_vmx(vcpu)->pi_desc);
650 }
651 
652 #define VMCS12_OFFSET(x) offsetof(struct vmcs12, x)
653 #define FIELD(number, name)     [number] = VMCS12_OFFSET(name)
654 #define FIELD64(number, name)   [number] = VMCS12_OFFSET(name), \
655                                 [number##_HIGH] = VMCS12_OFFSET(name)+4
656 
657 
658 static unsigned long shadow_read_only_fields[] = {
659         /*
660          * We do NOT shadow fields that are modified when L0
661          * traps and emulates any vmx instruction (e.g. VMPTRLD,
662          * VMXON...) executed by L1.
663          * For example, VM_INSTRUCTION_ERROR is read
664          * by L1 if a vmx instruction fails (part of the error path).
665          * Note the code assumes this logic. If for some reason
666          * we start shadowing these fields then we need to
667          * force a shadow sync when L0 emulates vmx instructions
668          * (e.g. force a sync if VM_INSTRUCTION_ERROR is modified
669          * by nested_vmx_failValid)
670          */
671         VM_EXIT_REASON,
672         VM_EXIT_INTR_INFO,
673         VM_EXIT_INSTRUCTION_LEN,
674         IDT_VECTORING_INFO_FIELD,
675         IDT_VECTORING_ERROR_CODE,
676         VM_EXIT_INTR_ERROR_CODE,
677         EXIT_QUALIFICATION,
678         GUEST_LINEAR_ADDRESS,
679         GUEST_PHYSICAL_ADDRESS
680 };
681 static int max_shadow_read_only_fields =
682         ARRAY_SIZE(shadow_read_only_fields);
683 
684 static unsigned long shadow_read_write_fields[] = {
685         TPR_THRESHOLD,
686         GUEST_RIP,
687         GUEST_RSP,
688         GUEST_CR0,
689         GUEST_CR3,
690         GUEST_CR4,
691         GUEST_INTERRUPTIBILITY_INFO,
692         GUEST_RFLAGS,
693         GUEST_CS_SELECTOR,
694         GUEST_CS_AR_BYTES,
695         GUEST_CS_LIMIT,
696         GUEST_CS_BASE,
697         GUEST_ES_BASE,
698         GUEST_BNDCFGS,
699         CR0_GUEST_HOST_MASK,
700         CR0_READ_SHADOW,
701         CR4_READ_SHADOW,
702         TSC_OFFSET,
703         EXCEPTION_BITMAP,
704         CPU_BASED_VM_EXEC_CONTROL,
705         VM_ENTRY_EXCEPTION_ERROR_CODE,
706         VM_ENTRY_INTR_INFO_FIELD,
707         VM_ENTRY_INSTRUCTION_LEN,
708         VM_ENTRY_EXCEPTION_ERROR_CODE,
709         HOST_FS_BASE,
710         HOST_GS_BASE,
711         HOST_FS_SELECTOR,
712         HOST_GS_SELECTOR
713 };
714 static int max_shadow_read_write_fields =
715         ARRAY_SIZE(shadow_read_write_fields);
716 
717 static const unsigned short vmcs_field_to_offset_table[] = {
718         FIELD(VIRTUAL_PROCESSOR_ID, virtual_processor_id),
719         FIELD(POSTED_INTR_NV, posted_intr_nv),
720         FIELD(GUEST_ES_SELECTOR, guest_es_selector),
721         FIELD(GUEST_CS_SELECTOR, guest_cs_selector),
722         FIELD(GUEST_SS_SELECTOR, guest_ss_selector),
723         FIELD(GUEST_DS_SELECTOR, guest_ds_selector),
724         FIELD(GUEST_FS_SELECTOR, guest_fs_selector),
725         FIELD(GUEST_GS_SELECTOR, guest_gs_selector),
726         FIELD(GUEST_LDTR_SELECTOR, guest_ldtr_selector),
727         FIELD(GUEST_TR_SELECTOR, guest_tr_selector),
728         FIELD(GUEST_INTR_STATUS, guest_intr_status),
729         FIELD(HOST_ES_SELECTOR, host_es_selector),
730         FIELD(HOST_CS_SELECTOR, host_cs_selector),
731         FIELD(HOST_SS_SELECTOR, host_ss_selector),
732         FIELD(HOST_DS_SELECTOR, host_ds_selector),
733         FIELD(HOST_FS_SELECTOR, host_fs_selector),
734         FIELD(HOST_GS_SELECTOR, host_gs_selector),
735         FIELD(HOST_TR_SELECTOR, host_tr_selector),
736         FIELD64(IO_BITMAP_A, io_bitmap_a),
737         FIELD64(IO_BITMAP_B, io_bitmap_b),
738         FIELD64(MSR_BITMAP, msr_bitmap),
739         FIELD64(VM_EXIT_MSR_STORE_ADDR, vm_exit_msr_store_addr),
740         FIELD64(VM_EXIT_MSR_LOAD_ADDR, vm_exit_msr_load_addr),
741         FIELD64(VM_ENTRY_MSR_LOAD_ADDR, vm_entry_msr_load_addr),
742         FIELD64(TSC_OFFSET, tsc_offset),
743         FIELD64(VIRTUAL_APIC_PAGE_ADDR, virtual_apic_page_addr),
744         FIELD64(APIC_ACCESS_ADDR, apic_access_addr),
745         FIELD64(POSTED_INTR_DESC_ADDR, posted_intr_desc_addr),
746         FIELD64(EPT_POINTER, ept_pointer),
747         FIELD64(EOI_EXIT_BITMAP0, eoi_exit_bitmap0),
748         FIELD64(EOI_EXIT_BITMAP1, eoi_exit_bitmap1),
749         FIELD64(EOI_EXIT_BITMAP2, eoi_exit_bitmap2),
750         FIELD64(EOI_EXIT_BITMAP3, eoi_exit_bitmap3),
751         FIELD64(XSS_EXIT_BITMAP, xss_exit_bitmap),
752         FIELD64(GUEST_PHYSICAL_ADDRESS, guest_physical_address),
753         FIELD64(VMCS_LINK_POINTER, vmcs_link_pointer),
754         FIELD64(GUEST_IA32_DEBUGCTL, guest_ia32_debugctl),
755         FIELD64(GUEST_IA32_PAT, guest_ia32_pat),
756         FIELD64(GUEST_IA32_EFER, guest_ia32_efer),
757         FIELD64(GUEST_IA32_PERF_GLOBAL_CTRL, guest_ia32_perf_global_ctrl),
758         FIELD64(GUEST_PDPTR0, guest_pdptr0),
759         FIELD64(GUEST_PDPTR1, guest_pdptr1),
760         FIELD64(GUEST_PDPTR2, guest_pdptr2),
761         FIELD64(GUEST_PDPTR3, guest_pdptr3),
762         FIELD64(GUEST_BNDCFGS, guest_bndcfgs),
763         FIELD64(HOST_IA32_PAT, host_ia32_pat),
764         FIELD64(HOST_IA32_EFER, host_ia32_efer),
765         FIELD64(HOST_IA32_PERF_GLOBAL_CTRL, host_ia32_perf_global_ctrl),
766         FIELD(PIN_BASED_VM_EXEC_CONTROL, pin_based_vm_exec_control),
767         FIELD(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control),
768         FIELD(EXCEPTION_BITMAP, exception_bitmap),
769         FIELD(PAGE_FAULT_ERROR_CODE_MASK, page_fault_error_code_mask),
770         FIELD(PAGE_FAULT_ERROR_CODE_MATCH, page_fault_error_code_match),
771         FIELD(CR3_TARGET_COUNT, cr3_target_count),
772         FIELD(VM_EXIT_CONTROLS, vm_exit_controls),
773         FIELD(VM_EXIT_MSR_STORE_COUNT, vm_exit_msr_store_count),
774         FIELD(VM_EXIT_MSR_LOAD_COUNT, vm_exit_msr_load_count),
775         FIELD(VM_ENTRY_CONTROLS, vm_entry_controls),
776         FIELD(VM_ENTRY_MSR_LOAD_COUNT, vm_entry_msr_load_count),
777         FIELD(VM_ENTRY_INTR_INFO_FIELD, vm_entry_intr_info_field),
778         FIELD(VM_ENTRY_EXCEPTION_ERROR_CODE, vm_entry_exception_error_code),
779         FIELD(VM_ENTRY_INSTRUCTION_LEN, vm_entry_instruction_len),
780         FIELD(TPR_THRESHOLD, tpr_threshold),
781         FIELD(SECONDARY_VM_EXEC_CONTROL, secondary_vm_exec_control),
782         FIELD(VM_INSTRUCTION_ERROR, vm_instruction_error),
783         FIELD(VM_EXIT_REASON, vm_exit_reason),
784         FIELD(VM_EXIT_INTR_INFO, vm_exit_intr_info),
785         FIELD(VM_EXIT_INTR_ERROR_CODE, vm_exit_intr_error_code),
786         FIELD(IDT_VECTORING_INFO_FIELD, idt_vectoring_info_field),
787         FIELD(IDT_VECTORING_ERROR_CODE, idt_vectoring_error_code),
788         FIELD(VM_EXIT_INSTRUCTION_LEN, vm_exit_instruction_len),
789         FIELD(VMX_INSTRUCTION_INFO, vmx_instruction_info),
790         FIELD(GUEST_ES_LIMIT, guest_es_limit),
791         FIELD(GUEST_CS_LIMIT, guest_cs_limit),
792         FIELD(GUEST_SS_LIMIT, guest_ss_limit),
793         FIELD(GUEST_DS_LIMIT, guest_ds_limit),
794         FIELD(GUEST_FS_LIMIT, guest_fs_limit),
795         FIELD(GUEST_GS_LIMIT, guest_gs_limit),
796         FIELD(GUEST_LDTR_LIMIT, guest_ldtr_limit),
797         FIELD(GUEST_TR_LIMIT, guest_tr_limit),
798         FIELD(GUEST_GDTR_LIMIT, guest_gdtr_limit),
799         FIELD(GUEST_IDTR_LIMIT, guest_idtr_limit),
800         FIELD(GUEST_ES_AR_BYTES, guest_es_ar_bytes),
801         FIELD(GUEST_CS_AR_BYTES, guest_cs_ar_bytes),
802         FIELD(GUEST_SS_AR_BYTES, guest_ss_ar_bytes),
803         FIELD(GUEST_DS_AR_BYTES, guest_ds_ar_bytes),
804         FIELD(GUEST_FS_AR_BYTES, guest_fs_ar_bytes),
805         FIELD(GUEST_GS_AR_BYTES, guest_gs_ar_bytes),
806         FIELD(GUEST_LDTR_AR_BYTES, guest_ldtr_ar_bytes),
807         FIELD(GUEST_TR_AR_BYTES, guest_tr_ar_bytes),
808         FIELD(GUEST_INTERRUPTIBILITY_INFO, guest_interruptibility_info),
809         FIELD(GUEST_ACTIVITY_STATE, guest_activity_state),
810         FIELD(GUEST_SYSENTER_CS, guest_sysenter_cs),
811         FIELD(HOST_IA32_SYSENTER_CS, host_ia32_sysenter_cs),
812         FIELD(VMX_PREEMPTION_TIMER_VALUE, vmx_preemption_timer_value),
813         FIELD(CR0_GUEST_HOST_MASK, cr0_guest_host_mask),
814         FIELD(CR4_GUEST_HOST_MASK, cr4_guest_host_mask),
815         FIELD(CR0_READ_SHADOW, cr0_read_shadow),
816         FIELD(CR4_READ_SHADOW, cr4_read_shadow),
817         FIELD(CR3_TARGET_VALUE0, cr3_target_value0),
818         FIELD(CR3_TARGET_VALUE1, cr3_target_value1),
819         FIELD(CR3_TARGET_VALUE2, cr3_target_value2),
820         FIELD(CR3_TARGET_VALUE3, cr3_target_value3),
821         FIELD(EXIT_QUALIFICATION, exit_qualification),
822         FIELD(GUEST_LINEAR_ADDRESS, guest_linear_address),
823         FIELD(GUEST_CR0, guest_cr0),
824         FIELD(GUEST_CR3, guest_cr3),
825         FIELD(GUEST_CR4, guest_cr4),
826         FIELD(GUEST_ES_BASE, guest_es_base),
827         FIELD(GUEST_CS_BASE, guest_cs_base),
828         FIELD(GUEST_SS_BASE, guest_ss_base),
829         FIELD(GUEST_DS_BASE, guest_ds_base),
830         FIELD(GUEST_FS_BASE, guest_fs_base),
831         FIELD(GUEST_GS_BASE, guest_gs_base),
832         FIELD(GUEST_LDTR_BASE, guest_ldtr_base),
833         FIELD(GUEST_TR_BASE, guest_tr_base),
834         FIELD(GUEST_GDTR_BASE, guest_gdtr_base),
835         FIELD(GUEST_IDTR_BASE, guest_idtr_base),
836         FIELD(GUEST_DR7, guest_dr7),
837         FIELD(GUEST_RSP, guest_rsp),
838         FIELD(GUEST_RIP, guest_rip),
839         FIELD(GUEST_RFLAGS, guest_rflags),
840         FIELD(GUEST_PENDING_DBG_EXCEPTIONS, guest_pending_dbg_exceptions),
841         FIELD(GUEST_SYSENTER_ESP, guest_sysenter_esp),
842         FIELD(GUEST_SYSENTER_EIP, guest_sysenter_eip),
843         FIELD(HOST_CR0, host_cr0),
844         FIELD(HOST_CR3, host_cr3),
845         FIELD(HOST_CR4, host_cr4),
846         FIELD(HOST_FS_BASE, host_fs_base),
847         FIELD(HOST_GS_BASE, host_gs_base),
848         FIELD(HOST_TR_BASE, host_tr_base),
849         FIELD(HOST_GDTR_BASE, host_gdtr_base),
850         FIELD(HOST_IDTR_BASE, host_idtr_base),
851         FIELD(HOST_IA32_SYSENTER_ESP, host_ia32_sysenter_esp),
852         FIELD(HOST_IA32_SYSENTER_EIP, host_ia32_sysenter_eip),
853         FIELD(HOST_RSP, host_rsp),
854         FIELD(HOST_RIP, host_rip),
855 };
856 
857 static inline short vmcs_field_to_offset(unsigned long field)
858 {
859         BUILD_BUG_ON(ARRAY_SIZE(vmcs_field_to_offset_table) > SHRT_MAX);
860 
861         if (field >= ARRAY_SIZE(vmcs_field_to_offset_table) ||
862             vmcs_field_to_offset_table[field] == 0)
863                 return -ENOENT;
864 
865         return vmcs_field_to_offset_table[field];
866 }
867 
868 static inline struct vmcs12 *get_vmcs12(struct kvm_vcpu *vcpu)
869 {
870         return to_vmx(vcpu)->nested.cached_vmcs12;
871 }
872 
873 static struct page *nested_get_page(struct kvm_vcpu *vcpu, gpa_t addr)
874 {
875         struct page *page = kvm_vcpu_gfn_to_page(vcpu, addr >> PAGE_SHIFT);
876         if (is_error_page(page))
877                 return NULL;
878 
879         return page;
880 }
881 
882 static void nested_release_page(struct page *page)
883 {
884         kvm_release_page_dirty(page);
885 }
886 
887 static void nested_release_page_clean(struct page *page)
888 {
889         kvm_release_page_clean(page);
890 }
891 
892 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu);
893 static u64 construct_eptp(unsigned long root_hpa);
894 static void kvm_cpu_vmxon(u64 addr);
895 static void kvm_cpu_vmxoff(void);
896 static bool vmx_xsaves_supported(void);
897 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr);
898 static void vmx_set_segment(struct kvm_vcpu *vcpu,
899                             struct kvm_segment *var, int seg);
900 static void vmx_get_segment(struct kvm_vcpu *vcpu,
901                             struct kvm_segment *var, int seg);
902 static bool guest_state_valid(struct kvm_vcpu *vcpu);
903 static u32 vmx_segment_access_rights(struct kvm_segment *var);
904 static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx);
905 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx);
906 static int alloc_identity_pagetable(struct kvm *kvm);
907 
908 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
909 static DEFINE_PER_CPU(struct vmcs *, current_vmcs);
910 /*
911  * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
912  * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
913  */
914 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
915 static DEFINE_PER_CPU(struct desc_ptr, host_gdt);
916 
917 /*
918  * We maintian a per-CPU linked-list of vCPU, so in wakeup_handler() we
919  * can find which vCPU should be waken up.
920  */
921 static DEFINE_PER_CPU(struct list_head, blocked_vcpu_on_cpu);
922 static DEFINE_PER_CPU(spinlock_t, blocked_vcpu_on_cpu_lock);
923 
924 static unsigned long *vmx_io_bitmap_a;
925 static unsigned long *vmx_io_bitmap_b;
926 static unsigned long *vmx_msr_bitmap_legacy;
927 static unsigned long *vmx_msr_bitmap_longmode;
928 static unsigned long *vmx_msr_bitmap_legacy_x2apic;
929 static unsigned long *vmx_msr_bitmap_longmode_x2apic;
930 static unsigned long *vmx_vmread_bitmap;
931 static unsigned long *vmx_vmwrite_bitmap;
932 
933 static bool cpu_has_load_ia32_efer;
934 static bool cpu_has_load_perf_global_ctrl;
935 
936 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
937 static DEFINE_SPINLOCK(vmx_vpid_lock);
938 
939 static struct vmcs_config {
940         int size;
941         int order;
942         u32 revision_id;
943         u32 pin_based_exec_ctrl;
944         u32 cpu_based_exec_ctrl;
945         u32 cpu_based_2nd_exec_ctrl;
946         u32 vmexit_ctrl;
947         u32 vmentry_ctrl;
948 } vmcs_config;
949 
950 static struct vmx_capability {
951         u32 ept;
952         u32 vpid;
953 } vmx_capability;
954 
955 #define VMX_SEGMENT_FIELD(seg)                                  \
956         [VCPU_SREG_##seg] = {                                   \
957                 .selector = GUEST_##seg##_SELECTOR,             \
958                 .base = GUEST_##seg##_BASE,                     \
959                 .limit = GUEST_##seg##_LIMIT,                   \
960                 .ar_bytes = GUEST_##seg##_AR_BYTES,             \
961         }
962 
963 static const struct kvm_vmx_segment_field {
964         unsigned selector;
965         unsigned base;
966         unsigned limit;
967         unsigned ar_bytes;
968 } kvm_vmx_segment_fields[] = {
969         VMX_SEGMENT_FIELD(CS),
970         VMX_SEGMENT_FIELD(DS),
971         VMX_SEGMENT_FIELD(ES),
972         VMX_SEGMENT_FIELD(FS),
973         VMX_SEGMENT_FIELD(GS),
974         VMX_SEGMENT_FIELD(SS),
975         VMX_SEGMENT_FIELD(TR),
976         VMX_SEGMENT_FIELD(LDTR),
977 };
978 
979 static u64 host_efer;
980 
981 static void ept_save_pdptrs(struct kvm_vcpu *vcpu);
982 
983 /*
984  * Keep MSR_STAR at the end, as setup_msrs() will try to optimize it
985  * away by decrementing the array size.
986  */
987 static const u32 vmx_msr_index[] = {
988 #ifdef CONFIG_X86_64
989         MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
990 #endif
991         MSR_EFER, MSR_TSC_AUX, MSR_STAR,
992 };
993 
994 static inline bool is_exception_n(u32 intr_info, u8 vector)
995 {
996         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
997                              INTR_INFO_VALID_MASK)) ==
998                 (INTR_TYPE_HARD_EXCEPTION | vector | INTR_INFO_VALID_MASK);
999 }
1000 
1001 static inline bool is_debug(u32 intr_info)
1002 {
1003         return is_exception_n(intr_info, DB_VECTOR);
1004 }
1005 
1006 static inline bool is_breakpoint(u32 intr_info)
1007 {
1008         return is_exception_n(intr_info, BP_VECTOR);
1009 }
1010 
1011 static inline bool is_page_fault(u32 intr_info)
1012 {
1013         return is_exception_n(intr_info, PF_VECTOR);
1014 }
1015 
1016 static inline bool is_no_device(u32 intr_info)
1017 {
1018         return is_exception_n(intr_info, NM_VECTOR);
1019 }
1020 
1021 static inline bool is_invalid_opcode(u32 intr_info)
1022 {
1023         return is_exception_n(intr_info, UD_VECTOR);
1024 }
1025 
1026 static inline bool is_external_interrupt(u32 intr_info)
1027 {
1028         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1029                 == (INTR_TYPE_EXT_INTR | INTR_INFO_VALID_MASK);
1030 }
1031 
1032 static inline bool is_machine_check(u32 intr_info)
1033 {
1034         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1035                              INTR_INFO_VALID_MASK)) ==
1036                 (INTR_TYPE_HARD_EXCEPTION | MC_VECTOR | INTR_INFO_VALID_MASK);
1037 }
1038 
1039 static inline bool cpu_has_vmx_msr_bitmap(void)
1040 {
1041         return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_USE_MSR_BITMAPS;
1042 }
1043 
1044 static inline bool cpu_has_vmx_tpr_shadow(void)
1045 {
1046         return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW;
1047 }
1048 
1049 static inline bool cpu_need_tpr_shadow(struct kvm_vcpu *vcpu)
1050 {
1051         return cpu_has_vmx_tpr_shadow() && lapic_in_kernel(vcpu);
1052 }
1053 
1054 static inline bool cpu_has_secondary_exec_ctrls(void)
1055 {
1056         return vmcs_config.cpu_based_exec_ctrl &
1057                 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
1058 }
1059 
1060 static inline bool cpu_has_vmx_virtualize_apic_accesses(void)
1061 {
1062         return vmcs_config.cpu_based_2nd_exec_ctrl &
1063                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
1064 }
1065 
1066 static inline bool cpu_has_vmx_virtualize_x2apic_mode(void)
1067 {
1068         return vmcs_config.cpu_based_2nd_exec_ctrl &
1069                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
1070 }
1071 
1072 static inline bool cpu_has_vmx_apic_register_virt(void)
1073 {
1074         return vmcs_config.cpu_based_2nd_exec_ctrl &
1075                 SECONDARY_EXEC_APIC_REGISTER_VIRT;
1076 }
1077 
1078 static inline bool cpu_has_vmx_virtual_intr_delivery(void)
1079 {
1080         return vmcs_config.cpu_based_2nd_exec_ctrl &
1081                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY;
1082 }
1083 
1084 /*
1085  * Comment's format: document - errata name - stepping - processor name.
1086  * Refer from
1087  * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
1088  */
1089 static u32 vmx_preemption_cpu_tfms[] = {
1090 /* 323344.pdf - BA86   - D0 - Xeon 7500 Series */
1091 0x000206E6,
1092 /* 323056.pdf - AAX65  - C2 - Xeon L3406 */
1093 /* 322814.pdf - AAT59  - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
1094 /* 322911.pdf - AAU65  - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
1095 0x00020652,
1096 /* 322911.pdf - AAU65  - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
1097 0x00020655,
1098 /* 322373.pdf - AAO95  - B1 - Xeon 3400 Series */
1099 /* 322166.pdf - AAN92  - B1 - i7-800 and i5-700 Desktop */
1100 /*
1101  * 320767.pdf - AAP86  - B1 -
1102  * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
1103  */
1104 0x000106E5,
1105 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
1106 0x000106A0,
1107 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
1108 0x000106A1,
1109 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
1110 0x000106A4,
1111  /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
1112  /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
1113  /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
1114 0x000106A5,
1115 };
1116 
1117 static inline bool cpu_has_broken_vmx_preemption_timer(void)
1118 {
1119         u32 eax = cpuid_eax(0x00000001), i;
1120 
1121         /* Clear the reserved bits */
1122         eax &= ~(0x3U << 14 | 0xfU << 28);
1123         for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
1124                 if (eax == vmx_preemption_cpu_tfms[i])
1125                         return true;
1126 
1127         return false;
1128 }
1129 
1130 static inline bool cpu_has_vmx_preemption_timer(void)
1131 {
1132         return vmcs_config.pin_based_exec_ctrl &
1133                 PIN_BASED_VMX_PREEMPTION_TIMER;
1134 }
1135 
1136 static inline bool cpu_has_vmx_posted_intr(void)
1137 {
1138         return IS_ENABLED(CONFIG_X86_LOCAL_APIC) &&
1139                 vmcs_config.pin_based_exec_ctrl & PIN_BASED_POSTED_INTR;
1140 }
1141 
1142 static inline bool cpu_has_vmx_apicv(void)
1143 {
1144         return cpu_has_vmx_apic_register_virt() &&
1145                 cpu_has_vmx_virtual_intr_delivery() &&
1146                 cpu_has_vmx_posted_intr();
1147 }
1148 
1149 static inline bool cpu_has_vmx_flexpriority(void)
1150 {
1151         return cpu_has_vmx_tpr_shadow() &&
1152                 cpu_has_vmx_virtualize_apic_accesses();
1153 }
1154 
1155 static inline bool cpu_has_vmx_ept_execute_only(void)
1156 {
1157         return vmx_capability.ept & VMX_EPT_EXECUTE_ONLY_BIT;
1158 }
1159 
1160 static inline bool cpu_has_vmx_ept_2m_page(void)
1161 {
1162         return vmx_capability.ept & VMX_EPT_2MB_PAGE_BIT;
1163 }
1164 
1165 static inline bool cpu_has_vmx_ept_1g_page(void)
1166 {
1167         return vmx_capability.ept & VMX_EPT_1GB_PAGE_BIT;
1168 }
1169 
1170 static inline bool cpu_has_vmx_ept_4levels(void)
1171 {
1172         return vmx_capability.ept & VMX_EPT_PAGE_WALK_4_BIT;
1173 }
1174 
1175 static inline bool cpu_has_vmx_ept_ad_bits(void)
1176 {
1177         return vmx_capability.ept & VMX_EPT_AD_BIT;
1178 }
1179 
1180 static inline bool cpu_has_vmx_invept_context(void)
1181 {
1182         return vmx_capability.ept & VMX_EPT_EXTENT_CONTEXT_BIT;
1183 }
1184 
1185 static inline bool cpu_has_vmx_invept_global(void)
1186 {
1187         return vmx_capability.ept & VMX_EPT_EXTENT_GLOBAL_BIT;
1188 }
1189 
1190 static inline bool cpu_has_vmx_invvpid_single(void)
1191 {
1192         return vmx_capability.vpid & VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT;
1193 }
1194 
1195 static inline bool cpu_has_vmx_invvpid_global(void)
1196 {
1197         return vmx_capability.vpid & VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT;
1198 }
1199 
1200 static inline bool cpu_has_vmx_ept(void)
1201 {
1202         return vmcs_config.cpu_based_2nd_exec_ctrl &
1203                 SECONDARY_EXEC_ENABLE_EPT;
1204 }
1205 
1206 static inline bool cpu_has_vmx_unrestricted_guest(void)
1207 {
1208         return vmcs_config.cpu_based_2nd_exec_ctrl &
1209                 SECONDARY_EXEC_UNRESTRICTED_GUEST;
1210 }
1211 
1212 static inline bool cpu_has_vmx_ple(void)
1213 {
1214         return vmcs_config.cpu_based_2nd_exec_ctrl &
1215                 SECONDARY_EXEC_PAUSE_LOOP_EXITING;
1216 }
1217 
1218 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
1219 {
1220         return flexpriority_enabled && lapic_in_kernel(vcpu);
1221 }
1222 
1223 static inline bool cpu_has_vmx_vpid(void)
1224 {
1225         return vmcs_config.cpu_based_2nd_exec_ctrl &
1226                 SECONDARY_EXEC_ENABLE_VPID;
1227 }
1228 
1229 static inline bool cpu_has_vmx_rdtscp(void)
1230 {
1231         return vmcs_config.cpu_based_2nd_exec_ctrl &
1232                 SECONDARY_EXEC_RDTSCP;
1233 }
1234 
1235 static inline bool cpu_has_vmx_invpcid(void)
1236 {
1237         return vmcs_config.cpu_based_2nd_exec_ctrl &
1238                 SECONDARY_EXEC_ENABLE_INVPCID;
1239 }
1240 
1241 static inline bool cpu_has_virtual_nmis(void)
1242 {
1243         return vmcs_config.pin_based_exec_ctrl & PIN_BASED_VIRTUAL_NMIS;
1244 }
1245 
1246 static inline bool cpu_has_vmx_wbinvd_exit(void)
1247 {
1248         return vmcs_config.cpu_based_2nd_exec_ctrl &
1249                 SECONDARY_EXEC_WBINVD_EXITING;
1250 }
1251 
1252 static inline bool cpu_has_vmx_shadow_vmcs(void)
1253 {
1254         u64 vmx_msr;
1255         rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
1256         /* check if the cpu supports writing r/o exit information fields */
1257         if (!(vmx_msr & MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS))
1258                 return false;
1259 
1260         return vmcs_config.cpu_based_2nd_exec_ctrl &
1261                 SECONDARY_EXEC_SHADOW_VMCS;
1262 }
1263 
1264 static inline bool cpu_has_vmx_pml(void)
1265 {
1266         return vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_ENABLE_PML;
1267 }
1268 
1269 static inline bool cpu_has_vmx_tsc_scaling(void)
1270 {
1271         return vmcs_config.cpu_based_2nd_exec_ctrl &
1272                 SECONDARY_EXEC_TSC_SCALING;
1273 }
1274 
1275 static inline bool report_flexpriority(void)
1276 {
1277         return flexpriority_enabled;
1278 }
1279 
1280 static inline bool nested_cpu_has(struct vmcs12 *vmcs12, u32 bit)
1281 {
1282         return vmcs12->cpu_based_vm_exec_control & bit;
1283 }
1284 
1285 static inline bool nested_cpu_has2(struct vmcs12 *vmcs12, u32 bit)
1286 {
1287         return (vmcs12->cpu_based_vm_exec_control &
1288                         CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
1289                 (vmcs12->secondary_vm_exec_control & bit);
1290 }
1291 
1292 static inline bool nested_cpu_has_virtual_nmis(struct vmcs12 *vmcs12)
1293 {
1294         return vmcs12->pin_based_vm_exec_control & PIN_BASED_VIRTUAL_NMIS;
1295 }
1296 
1297 static inline bool nested_cpu_has_preemption_timer(struct vmcs12 *vmcs12)
1298 {
1299         return vmcs12->pin_based_vm_exec_control &
1300                 PIN_BASED_VMX_PREEMPTION_TIMER;
1301 }
1302 
1303 static inline int nested_cpu_has_ept(struct vmcs12 *vmcs12)
1304 {
1305         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_EPT);
1306 }
1307 
1308 static inline bool nested_cpu_has_xsaves(struct vmcs12 *vmcs12)
1309 {
1310         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES) &&
1311                 vmx_xsaves_supported();
1312 }
1313 
1314 static inline bool nested_cpu_has_virt_x2apic_mode(struct vmcs12 *vmcs12)
1315 {
1316         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
1317 }
1318 
1319 static inline bool nested_cpu_has_vpid(struct vmcs12 *vmcs12)
1320 {
1321         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VPID);
1322 }
1323 
1324 static inline bool nested_cpu_has_apic_reg_virt(struct vmcs12 *vmcs12)
1325 {
1326         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_APIC_REGISTER_VIRT);
1327 }
1328 
1329 static inline bool nested_cpu_has_vid(struct vmcs12 *vmcs12)
1330 {
1331         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
1332 }
1333 
1334 static inline bool nested_cpu_has_posted_intr(struct vmcs12 *vmcs12)
1335 {
1336         return vmcs12->pin_based_vm_exec_control & PIN_BASED_POSTED_INTR;
1337 }
1338 
1339 static inline bool is_nmi(u32 intr_info)
1340 {
1341         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1342                 == (INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK);
1343 }
1344 
1345 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
1346                               u32 exit_intr_info,
1347                               unsigned long exit_qualification);
1348 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
1349                         struct vmcs12 *vmcs12,
1350                         u32 reason, unsigned long qualification);
1351 
1352 static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
1353 {
1354         int i;
1355 
1356         for (i = 0; i < vmx->nmsrs; ++i)
1357                 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
1358                         return i;
1359         return -1;
1360 }
1361 
1362 static inline void __invvpid(int ext, u16 vpid, gva_t gva)
1363 {
1364     struct {
1365         u64 vpid : 16;
1366         u64 rsvd : 48;
1367         u64 gva;
1368     } operand = { vpid, 0, gva };
1369 
1370     asm volatile (__ex(ASM_VMX_INVVPID)
1371                   /* CF==1 or ZF==1 --> rc = -1 */
1372                   "; ja 1f ; ud2 ; 1:"
1373                   : : "a"(&operand), "c"(ext) : "cc", "memory");
1374 }
1375 
1376 static inline void __invept(int ext, u64 eptp, gpa_t gpa)
1377 {
1378         struct {
1379                 u64 eptp, gpa;
1380         } operand = {eptp, gpa};
1381 
1382         asm volatile (__ex(ASM_VMX_INVEPT)
1383                         /* CF==1 or ZF==1 --> rc = -1 */
1384                         "; ja 1f ; ud2 ; 1:\n"
1385                         : : "a" (&operand), "c" (ext) : "cc", "memory");
1386 }
1387 
1388 static struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
1389 {
1390         int i;
1391 
1392         i = __find_msr_index(vmx, msr);
1393         if (i >= 0)
1394                 return &vmx->guest_msrs[i];
1395         return NULL;
1396 }
1397 
1398 static void vmcs_clear(struct vmcs *vmcs)
1399 {
1400         u64 phys_addr = __pa(vmcs);
1401         u8 error;
1402 
1403         asm volatile (__ex(ASM_VMX_VMCLEAR_RAX) "; setna %0"
1404                       : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
1405                       : "cc", "memory");
1406         if (error)
1407                 printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n",
1408                        vmcs, phys_addr);
1409 }
1410 
1411 static inline void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
1412 {
1413         vmcs_clear(loaded_vmcs->vmcs);
1414         loaded_vmcs->cpu = -1;
1415         loaded_vmcs->launched = 0;
1416 }
1417 
1418 static void vmcs_load(struct vmcs *vmcs)
1419 {
1420         u64 phys_addr = __pa(vmcs);
1421         u8 error;
1422 
1423         asm volatile (__ex(ASM_VMX_VMPTRLD_RAX) "; setna %0"
1424                         : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
1425                         : "cc", "memory");
1426         if (error)
1427                 printk(KERN_ERR "kvm: vmptrld %p/%llx failed\n",
1428                        vmcs, phys_addr);
1429 }
1430 
1431 #ifdef CONFIG_KEXEC_CORE
1432 /*
1433  * This bitmap is used to indicate whether the vmclear
1434  * operation is enabled on all cpus. All disabled by
1435  * default.
1436  */
1437 static cpumask_t crash_vmclear_enabled_bitmap = CPU_MASK_NONE;
1438 
1439 static inline void crash_enable_local_vmclear(int cpu)
1440 {
1441         cpumask_set_cpu(cpu, &crash_vmclear_enabled_bitmap);
1442 }
1443 
1444 static inline void crash_disable_local_vmclear(int cpu)
1445 {
1446         cpumask_clear_cpu(cpu, &crash_vmclear_enabled_bitmap);
1447 }
1448 
1449 static inline int crash_local_vmclear_enabled(int cpu)
1450 {
1451         return cpumask_test_cpu(cpu, &crash_vmclear_enabled_bitmap);
1452 }
1453 
1454 static void crash_vmclear_local_loaded_vmcss(void)
1455 {
1456         int cpu = raw_smp_processor_id();
1457         struct loaded_vmcs *v;
1458 
1459         if (!crash_local_vmclear_enabled(cpu))
1460                 return;
1461 
1462         list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
1463                             loaded_vmcss_on_cpu_link)
1464                 vmcs_clear(v->vmcs);
1465 }
1466 #else
1467 static inline void crash_enable_local_vmclear(int cpu) { }
1468 static inline void crash_disable_local_vmclear(int cpu) { }
1469 #endif /* CONFIG_KEXEC_CORE */
1470 
1471 static void __loaded_vmcs_clear(void *arg)
1472 {
1473         struct loaded_vmcs *loaded_vmcs = arg;
1474         int cpu = raw_smp_processor_id();
1475 
1476         if (loaded_vmcs->cpu != cpu)
1477                 return; /* vcpu migration can race with cpu offline */
1478         if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
1479                 per_cpu(current_vmcs, cpu) = NULL;
1480         crash_disable_local_vmclear(cpu);
1481         list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
1482 
1483         /*
1484          * we should ensure updating loaded_vmcs->loaded_vmcss_on_cpu_link
1485          * is before setting loaded_vmcs->vcpu to -1 which is done in
1486          * loaded_vmcs_init. Otherwise, other cpu can see vcpu = -1 fist
1487          * then adds the vmcs into percpu list before it is deleted.
1488          */
1489         smp_wmb();
1490 
1491         loaded_vmcs_init(loaded_vmcs);
1492         crash_enable_local_vmclear(cpu);
1493 }
1494 
1495 static void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
1496 {
1497         int cpu = loaded_vmcs->cpu;
1498 
1499         if (cpu != -1)
1500                 smp_call_function_single(cpu,
1501                          __loaded_vmcs_clear, loaded_vmcs, 1);
1502 }
1503 
1504 static inline void vpid_sync_vcpu_single(int vpid)
1505 {
1506         if (vpid == 0)
1507                 return;
1508 
1509         if (cpu_has_vmx_invvpid_single())
1510                 __invvpid(VMX_VPID_EXTENT_SINGLE_CONTEXT, vpid, 0);
1511 }
1512 
1513 static inline void vpid_sync_vcpu_global(void)
1514 {
1515         if (cpu_has_vmx_invvpid_global())
1516                 __invvpid(VMX_VPID_EXTENT_ALL_CONTEXT, 0, 0);
1517 }
1518 
1519 static inline void vpid_sync_context(int vpid)
1520 {
1521         if (cpu_has_vmx_invvpid_single())
1522                 vpid_sync_vcpu_single(vpid);
1523         else
1524                 vpid_sync_vcpu_global();
1525 }
1526 
1527 static inline void ept_sync_global(void)
1528 {
1529         if (cpu_has_vmx_invept_global())
1530                 __invept(VMX_EPT_EXTENT_GLOBAL, 0, 0);
1531 }
1532 
1533 static inline void ept_sync_context(u64 eptp)
1534 {
1535         if (enable_ept) {
1536                 if (cpu_has_vmx_invept_context())
1537                         __invept(VMX_EPT_EXTENT_CONTEXT, eptp, 0);
1538                 else
1539                         ept_sync_global();
1540         }
1541 }
1542 
1543 static __always_inline void vmcs_check16(unsigned long field)
1544 {
1545         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
1546                          "16-bit accessor invalid for 64-bit field");
1547         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
1548                          "16-bit accessor invalid for 64-bit high field");
1549         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
1550                          "16-bit accessor invalid for 32-bit high field");
1551         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
1552                          "16-bit accessor invalid for natural width field");
1553 }
1554 
1555 static __always_inline void vmcs_check32(unsigned long field)
1556 {
1557         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
1558                          "32-bit accessor invalid for 16-bit field");
1559         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
1560                          "32-bit accessor invalid for natural width field");
1561 }
1562 
1563 static __always_inline void vmcs_check64(unsigned long field)
1564 {
1565         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
1566                          "64-bit accessor invalid for 16-bit field");
1567         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
1568                          "64-bit accessor invalid for 64-bit high field");
1569         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
1570                          "64-bit accessor invalid for 32-bit field");
1571         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
1572                          "64-bit accessor invalid for natural width field");
1573 }
1574 
1575 static __always_inline void vmcs_checkl(unsigned long field)
1576 {
1577         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
1578                          "Natural width accessor invalid for 16-bit field");
1579         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
1580                          "Natural width accessor invalid for 64-bit field");
1581         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
1582                          "Natural width accessor invalid for 64-bit high field");
1583         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
1584                          "Natural width accessor invalid for 32-bit field");
1585 }
1586 
1587 static __always_inline unsigned long __vmcs_readl(unsigned long field)
1588 {
1589         unsigned long value;
1590 
1591         asm volatile (__ex_clear(ASM_VMX_VMREAD_RDX_RAX, "%0")
1592                       : "=a"(value) : "d"(field) : "cc");
1593         return value;
1594 }
1595 
1596 static __always_inline u16 vmcs_read16(unsigned long field)
1597 {
1598         vmcs_check16(field);
1599         return __vmcs_readl(field);
1600 }
1601 
1602 static __always_inline u32 vmcs_read32(unsigned long field)
1603 {
1604         vmcs_check32(field);
1605         return __vmcs_readl(field);
1606 }
1607 
1608 static __always_inline u64 vmcs_read64(unsigned long field)
1609 {
1610         vmcs_check64(field);
1611 #ifdef CONFIG_X86_64
1612         return __vmcs_readl(field);
1613 #else
1614         return __vmcs_readl(field) | ((u64)__vmcs_readl(field+1) << 32);
1615 #endif
1616 }
1617 
1618 static __always_inline unsigned long vmcs_readl(unsigned long field)
1619 {
1620         vmcs_checkl(field);
1621         return __vmcs_readl(field);
1622 }
1623 
1624 static noinline void vmwrite_error(unsigned long field, unsigned long value)
1625 {
1626         printk(KERN_ERR "vmwrite error: reg %lx value %lx (err %d)\n",
1627                field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
1628         dump_stack();
1629 }
1630 
1631 static __always_inline void __vmcs_writel(unsigned long field, unsigned long value)
1632 {
1633         u8 error;
1634 
1635         asm volatile (__ex(ASM_VMX_VMWRITE_RAX_RDX) "; setna %0"
1636                        : "=q"(error) : "a"(value), "d"(field) : "cc");
1637         if (unlikely(error))
1638                 vmwrite_error(field, value);
1639 }
1640 
1641 static __always_inline void vmcs_write16(unsigned long field, u16 value)
1642 {
1643         vmcs_check16(field);
1644         __vmcs_writel(field, value);
1645 }
1646 
1647 static __always_inline void vmcs_write32(unsigned long field, u32 value)
1648 {
1649         vmcs_check32(field);
1650         __vmcs_writel(field, value);
1651 }
1652 
1653 static __always_inline void vmcs_write64(unsigned long field, u64 value)
1654 {
1655         vmcs_check64(field);
1656         __vmcs_writel(field, value);
1657 #ifndef CONFIG_X86_64
1658         asm volatile ("");
1659         __vmcs_writel(field+1, value >> 32);
1660 #endif
1661 }
1662 
1663 static __always_inline void vmcs_writel(unsigned long field, unsigned long value)
1664 {
1665         vmcs_checkl(field);
1666         __vmcs_writel(field, value);
1667 }
1668 
1669 static __always_inline void vmcs_clear_bits(unsigned long field, u32 mask)
1670 {
1671         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
1672                          "vmcs_clear_bits does not support 64-bit fields");
1673         __vmcs_writel(field, __vmcs_readl(field) & ~mask);
1674 }
1675 
1676 static __always_inline void vmcs_set_bits(unsigned long field, u32 mask)
1677 {
1678         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
1679                          "vmcs_set_bits does not support 64-bit fields");
1680         __vmcs_writel(field, __vmcs_readl(field) | mask);
1681 }
1682 
1683 static inline void vm_entry_controls_reset_shadow(struct vcpu_vmx *vmx)
1684 {
1685         vmx->vm_entry_controls_shadow = vmcs_read32(VM_ENTRY_CONTROLS);
1686 }
1687 
1688 static inline void vm_entry_controls_init(struct vcpu_vmx *vmx, u32 val)
1689 {
1690         vmcs_write32(VM_ENTRY_CONTROLS, val);
1691         vmx->vm_entry_controls_shadow = val;
1692 }
1693 
1694 static inline void vm_entry_controls_set(struct vcpu_vmx *vmx, u32 val)
1695 {
1696         if (vmx->vm_entry_controls_shadow != val)
1697                 vm_entry_controls_init(vmx, val);
1698 }
1699 
1700 static inline u32 vm_entry_controls_get(struct vcpu_vmx *vmx)
1701 {
1702         return vmx->vm_entry_controls_shadow;
1703 }
1704 
1705 
1706 static inline void vm_entry_controls_setbit(struct vcpu_vmx *vmx, u32 val)
1707 {
1708         vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) | val);
1709 }
1710 
1711 static inline void vm_entry_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
1712 {
1713         vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) & ~val);
1714 }
1715 
1716 static inline void vm_exit_controls_reset_shadow(struct vcpu_vmx *vmx)
1717 {
1718         vmx->vm_exit_controls_shadow = vmcs_read32(VM_EXIT_CONTROLS);
1719 }
1720 
1721 static inline void vm_exit_controls_init(struct vcpu_vmx *vmx, u32 val)
1722 {
1723         vmcs_write32(VM_EXIT_CONTROLS, val);
1724         vmx->vm_exit_controls_shadow = val;
1725 }
1726 
1727 static inline void vm_exit_controls_set(struct vcpu_vmx *vmx, u32 val)
1728 {
1729         if (vmx->vm_exit_controls_shadow != val)
1730                 vm_exit_controls_init(vmx, val);
1731 }
1732 
1733 static inline u32 vm_exit_controls_get(struct vcpu_vmx *vmx)
1734 {
1735         return vmx->vm_exit_controls_shadow;
1736 }
1737 
1738 
1739 static inline void vm_exit_controls_setbit(struct vcpu_vmx *vmx, u32 val)
1740 {
1741         vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) | val);
1742 }
1743 
1744 static inline void vm_exit_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
1745 {
1746         vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) & ~val);
1747 }
1748 
1749 static void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
1750 {
1751         vmx->segment_cache.bitmask = 0;
1752 }
1753 
1754 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
1755                                        unsigned field)
1756 {
1757         bool ret;
1758         u32 mask = 1 << (seg * SEG_FIELD_NR + field);
1759 
1760         if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
1761                 vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
1762                 vmx->segment_cache.bitmask = 0;
1763         }
1764         ret = vmx->segment_cache.bitmask & mask;
1765         vmx->segment_cache.bitmask |= mask;
1766         return ret;
1767 }
1768 
1769 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
1770 {
1771         u16 *p = &vmx->segment_cache.seg[seg].selector;
1772 
1773         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
1774                 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
1775         return *p;
1776 }
1777 
1778 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
1779 {
1780         ulong *p = &vmx->segment_cache.seg[seg].base;
1781 
1782         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
1783                 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
1784         return *p;
1785 }
1786 
1787 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
1788 {
1789         u32 *p = &vmx->segment_cache.seg[seg].limit;
1790 
1791         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
1792                 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
1793         return *p;
1794 }
1795 
1796 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
1797 {
1798         u32 *p = &vmx->segment_cache.seg[seg].ar;
1799 
1800         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
1801                 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
1802         return *p;
1803 }
1804 
1805 static void update_exception_bitmap(struct kvm_vcpu *vcpu)
1806 {
1807         u32 eb;
1808 
1809         eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
1810              (1u << NM_VECTOR) | (1u << DB_VECTOR) | (1u << AC_VECTOR);
1811         if ((vcpu->guest_debug &
1812              (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
1813             (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
1814                 eb |= 1u << BP_VECTOR;
1815         if (to_vmx(vcpu)->rmode.vm86_active)
1816                 eb = ~0;
1817         if (enable_ept)
1818                 eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
1819         if (vcpu->fpu_active)
1820                 eb &= ~(1u << NM_VECTOR);
1821 
1822         /* When we are running a nested L2 guest and L1 specified for it a
1823          * certain exception bitmap, we must trap the same exceptions and pass
1824          * them to L1. When running L2, we will only handle the exceptions
1825          * specified above if L1 did not want them.
1826          */
1827         if (is_guest_mode(vcpu))
1828                 eb |= get_vmcs12(vcpu)->exception_bitmap;
1829 
1830         vmcs_write32(EXCEPTION_BITMAP, eb);
1831 }
1832 
1833 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
1834                 unsigned long entry, unsigned long exit)
1835 {
1836         vm_entry_controls_clearbit(vmx, entry);
1837         vm_exit_controls_clearbit(vmx, exit);
1838 }
1839 
1840 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
1841 {
1842         unsigned i;
1843         struct msr_autoload *m = &vmx->msr_autoload;
1844 
1845         switch (msr) {
1846         case MSR_EFER:
1847                 if (cpu_has_load_ia32_efer) {
1848                         clear_atomic_switch_msr_special(vmx,
1849                                         VM_ENTRY_LOAD_IA32_EFER,
1850                                         VM_EXIT_LOAD_IA32_EFER);
1851                         return;
1852                 }
1853                 break;
1854         case MSR_CORE_PERF_GLOBAL_CTRL:
1855                 if (cpu_has_load_perf_global_ctrl) {
1856                         clear_atomic_switch_msr_special(vmx,
1857                                         VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
1858                                         VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
1859                         return;
1860                 }
1861                 break;
1862         }
1863 
1864         for (i = 0; i < m->nr; ++i)
1865                 if (m->guest[i].index == msr)
1866                         break;
1867 
1868         if (i == m->nr)
1869                 return;
1870         --m->nr;
1871         m->guest[i] = m->guest[m->nr];
1872         m->host[i] = m->host[m->nr];
1873         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
1874         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
1875 }
1876 
1877 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
1878                 unsigned long entry, unsigned long exit,
1879                 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
1880                 u64 guest_val, u64 host_val)
1881 {
1882         vmcs_write64(guest_val_vmcs, guest_val);
1883         vmcs_write64(host_val_vmcs, host_val);
1884         vm_entry_controls_setbit(vmx, entry);
1885         vm_exit_controls_setbit(vmx, exit);
1886 }
1887 
1888 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
1889                                   u64 guest_val, u64 host_val)
1890 {
1891         unsigned i;
1892         struct msr_autoload *m = &vmx->msr_autoload;
1893 
1894         switch (msr) {
1895         case MSR_EFER:
1896                 if (cpu_has_load_ia32_efer) {
1897                         add_atomic_switch_msr_special(vmx,
1898                                         VM_ENTRY_LOAD_IA32_EFER,
1899                                         VM_EXIT_LOAD_IA32_EFER,
1900                                         GUEST_IA32_EFER,
1901                                         HOST_IA32_EFER,
1902                                         guest_val, host_val);
1903                         return;
1904                 }
1905                 break;
1906         case MSR_CORE_PERF_GLOBAL_CTRL:
1907                 if (cpu_has_load_perf_global_ctrl) {
1908                         add_atomic_switch_msr_special(vmx,
1909                                         VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
1910                                         VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
1911                                         GUEST_IA32_PERF_GLOBAL_CTRL,
1912                                         HOST_IA32_PERF_GLOBAL_CTRL,
1913                                         guest_val, host_val);
1914                         return;
1915                 }
1916                 break;
1917         case MSR_IA32_PEBS_ENABLE:
1918                 /* PEBS needs a quiescent period after being disabled (to write
1919                  * a record).  Disabling PEBS through VMX MSR swapping doesn't
1920                  * provide that period, so a CPU could write host's record into
1921                  * guest's memory.
1922                  */
1923                 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
1924         }
1925 
1926         for (i = 0; i < m->nr; ++i)
1927                 if (m->guest[i].index == msr)
1928                         break;
1929 
1930         if (i == NR_AUTOLOAD_MSRS) {
1931                 printk_once(KERN_WARNING "Not enough msr switch entries. "
1932                                 "Can't add msr %x\n", msr);
1933                 return;
1934         } else if (i == m->nr) {
1935                 ++m->nr;
1936                 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
1937                 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
1938         }
1939 
1940         m->guest[i].index = msr;
1941         m->guest[i].value = guest_val;
1942         m->host[i].index = msr;
1943         m->host[i].value = host_val;
1944 }
1945 
1946 static void reload_tss(void)
1947 {
1948         /*
1949          * VT restores TR but not its size.  Useless.
1950          */
1951         struct desc_ptr *gdt = this_cpu_ptr(&host_gdt);
1952         struct desc_struct *descs;
1953 
1954         descs = (void *)gdt->address;
1955         descs[GDT_ENTRY_TSS].type = 9; /* available TSS */
1956         load_TR_desc();
1957 }
1958 
1959 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
1960 {
1961         u64 guest_efer = vmx->vcpu.arch.efer;
1962         u64 ignore_bits = 0;
1963 
1964         if (!enable_ept) {
1965                 /*
1966                  * NX is needed to handle CR0.WP=1, CR4.SMEP=1.  Testing
1967                  * host CPUID is more efficient than testing guest CPUID
1968                  * or CR4.  Host SMEP is anyway a requirement for guest SMEP.
1969                  */
1970                 if (boot_cpu_has(X86_FEATURE_SMEP))
1971                         guest_efer |= EFER_NX;
1972                 else if (!(guest_efer & EFER_NX))
1973                         ignore_bits |= EFER_NX;
1974         }
1975 
1976         /*
1977          * LMA and LME handled by hardware; SCE meaningless outside long mode.
1978          */
1979         ignore_bits |= EFER_SCE;
1980 #ifdef CONFIG_X86_64
1981         ignore_bits |= EFER_LMA | EFER_LME;
1982         /* SCE is meaningful only in long mode on Intel */
1983         if (guest_efer & EFER_LMA)
1984                 ignore_bits &= ~(u64)EFER_SCE;
1985 #endif
1986 
1987         clear_atomic_switch_msr(vmx, MSR_EFER);
1988 
1989         /*
1990          * On EPT, we can't emulate NX, so we must switch EFER atomically.
1991          * On CPUs that support "load IA32_EFER", always switch EFER
1992          * atomically, since it's faster than switching it manually.
1993          */
1994         if (cpu_has_load_ia32_efer ||
1995             (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
1996                 if (!(guest_efer & EFER_LMA))
1997                         guest_efer &= ~EFER_LME;
1998                 if (guest_efer != host_efer)
1999                         add_atomic_switch_msr(vmx, MSR_EFER,
2000                                               guest_efer, host_efer);
2001                 return false;
2002         } else {
2003                 guest_efer &= ~ignore_bits;
2004                 guest_efer |= host_efer & ignore_bits;
2005 
2006                 vmx->guest_msrs[efer_offset].data = guest_efer;
2007                 vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
2008 
2009                 return true;
2010         }
2011 }
2012 
2013 static unsigned long segment_base(u16 selector)
2014 {
2015         struct desc_ptr *gdt = this_cpu_ptr(&host_gdt);
2016         struct desc_struct *d;
2017         unsigned long table_base;
2018         unsigned long v;
2019 
2020         if (!(selector & ~3))
2021                 return 0;
2022 
2023         table_base = gdt->address;
2024 
2025         if (selector & 4) {           /* from ldt */
2026                 u16 ldt_selector = kvm_read_ldt();
2027 
2028                 if (!(ldt_selector & ~3))
2029                         return 0;
2030 
2031                 table_base = segment_base(ldt_selector);
2032         }
2033         d = (struct desc_struct *)(table_base + (selector & ~7));
2034         v = get_desc_base(d);
2035 #ifdef CONFIG_X86_64
2036        if (d->s == 0 && (d->type == 2 || d->type == 9 || d->type == 11))
2037                v |= ((unsigned long)((struct ldttss_desc64 *)d)->base3) << 32;
2038 #endif
2039         return v;
2040 }
2041 
2042 static inline unsigned long kvm_read_tr_base(void)
2043 {
2044         u16 tr;
2045         asm("str %0" : "=g"(tr));
2046         return segment_base(tr);
2047 }
2048 
2049 static void vmx_save_host_state(struct kvm_vcpu *vcpu)
2050 {
2051         struct vcpu_vmx *vmx = to_vmx(vcpu);
2052         int i;
2053 
2054         if (vmx->host_state.loaded)
2055                 return;
2056 
2057         vmx->host_state.loaded = 1;
2058         /*
2059          * Set host fs and gs selectors.  Unfortunately, 22.2.3 does not
2060          * allow segment selectors with cpl > 0 or ti == 1.
2061          */
2062         vmx->host_state.ldt_sel = kvm_read_ldt();
2063         vmx->host_state.gs_ldt_reload_needed = vmx->host_state.ldt_sel;
2064         savesegment(fs, vmx->host_state.fs_sel);
2065         if (!(vmx->host_state.fs_sel & 7)) {
2066                 vmcs_write16(HOST_FS_SELECTOR, vmx->host_state.fs_sel);
2067                 vmx->host_state.fs_reload_needed = 0;
2068         } else {
2069                 vmcs_write16(HOST_FS_SELECTOR, 0);
2070                 vmx->host_state.fs_reload_needed = 1;
2071         }
2072         savesegment(gs, vmx->host_state.gs_sel);
2073         if (!(vmx->host_state.gs_sel & 7))
2074                 vmcs_write16(HOST_GS_SELECTOR, vmx->host_state.gs_sel);
2075         else {
2076                 vmcs_write16(HOST_GS_SELECTOR, 0);
2077                 vmx->host_state.gs_ldt_reload_needed = 1;
2078         }
2079 
2080 #ifdef CONFIG_X86_64
2081         savesegment(ds, vmx->host_state.ds_sel);
2082         savesegment(es, vmx->host_state.es_sel);
2083 #endif
2084 
2085 #ifdef CONFIG_X86_64
2086         vmcs_writel(HOST_FS_BASE, read_msr(MSR_FS_BASE));
2087         vmcs_writel(HOST_GS_BASE, read_msr(MSR_GS_BASE));
2088 #else
2089         vmcs_writel(HOST_FS_BASE, segment_base(vmx->host_state.fs_sel));
2090         vmcs_writel(HOST_GS_BASE, segment_base(vmx->host_state.gs_sel));
2091 #endif
2092 
2093 #ifdef CONFIG_X86_64
2094         rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
2095         if (is_long_mode(&vmx->vcpu))
2096                 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2097 #endif
2098         if (boot_cpu_has(X86_FEATURE_MPX))
2099                 rdmsrl(MSR_IA32_BNDCFGS, vmx->host_state.msr_host_bndcfgs);
2100         for (i = 0; i < vmx->save_nmsrs; ++i)
2101                 kvm_set_shared_msr(vmx->guest_msrs[i].index,
2102                                    vmx->guest_msrs[i].data,
2103                                    vmx->guest_msrs[i].mask);
2104 }
2105 
2106 static void __vmx_load_host_state(struct vcpu_vmx *vmx)
2107 {
2108         if (!vmx->host_state.loaded)
2109                 return;
2110 
2111         ++vmx->vcpu.stat.host_state_reload;
2112         vmx->host_state.loaded = 0;
2113 #ifdef CONFIG_X86_64
2114         if (is_long_mode(&vmx->vcpu))
2115                 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2116 #endif
2117         if (vmx->host_state.gs_ldt_reload_needed) {
2118                 kvm_load_ldt(vmx->host_state.ldt_sel);
2119 #ifdef CONFIG_X86_64
2120                 load_gs_index(vmx->host_state.gs_sel);
2121 #else
2122                 loadsegment(gs, vmx->host_state.gs_sel);
2123 #endif
2124         }
2125         if (vmx->host_state.fs_reload_needed)
2126                 loadsegment(fs, vmx->host_state.fs_sel);
2127 #ifdef CONFIG_X86_64
2128         if (unlikely(vmx->host_state.ds_sel | vmx->host_state.es_sel)) {
2129                 loadsegment(ds, vmx->host_state.ds_sel);
2130                 loadsegment(es, vmx->host_state.es_sel);
2131         }
2132 #endif
2133         reload_tss();
2134 #ifdef CONFIG_X86_64
2135         wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
2136 #endif
2137         if (vmx->host_state.msr_host_bndcfgs)
2138                 wrmsrl(MSR_IA32_BNDCFGS, vmx->host_state.msr_host_bndcfgs);
2139         /*
2140          * If the FPU is not active (through the host task or
2141          * the guest vcpu), then restore the cr0.TS bit.
2142          */
2143         if (!fpregs_active() && !vmx->vcpu.guest_fpu_loaded)
2144                 stts();
2145         load_gdt(this_cpu_ptr(&host_gdt));
2146 }
2147 
2148 static void vmx_load_host_state(struct vcpu_vmx *vmx)
2149 {
2150         preempt_disable();
2151         __vmx_load_host_state(vmx);
2152         preempt_enable();
2153 }
2154 
2155 static void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
2156 {
2157         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
2158         struct pi_desc old, new;
2159         unsigned int dest;
2160 
2161         if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
2162                 !irq_remapping_cap(IRQ_POSTING_CAP)  ||
2163                 !kvm_vcpu_apicv_active(vcpu))
2164                 return;
2165 
2166         do {
2167                 old.control = new.control = pi_desc->control;
2168 
2169                 /*
2170                  * If 'nv' field is POSTED_INTR_WAKEUP_VECTOR, there
2171                  * are two possible cases:
2172                  * 1. After running 'pre_block', context switch
2173                  *    happened. For this case, 'sn' was set in
2174                  *    vmx_vcpu_put(), so we need to clear it here.
2175                  * 2. After running 'pre_block', we were blocked,
2176                  *    and woken up by some other guy. For this case,
2177                  *    we don't need to do anything, 'pi_post_block'
2178                  *    will do everything for us. However, we cannot
2179                  *    check whether it is case #1 or case #2 here
2180                  *    (maybe, not needed), so we also clear sn here,
2181                  *    I think it is not a big deal.
2182                  */
2183                 if (pi_desc->nv != POSTED_INTR_WAKEUP_VECTOR) {
2184                         if (vcpu->cpu != cpu) {
2185                                 dest = cpu_physical_id(cpu);
2186 
2187                                 if (x2apic_enabled())
2188                                         new.ndst = dest;
2189                                 else
2190                                         new.ndst = (dest << 8) & 0xFF00;
2191                         }
2192 
2193                         /* set 'NV' to 'notification vector' */
2194                         new.nv = POSTED_INTR_VECTOR;
2195                 }
2196 
2197                 /* Allow posting non-urgent interrupts */
2198                 new.sn = 0;
2199         } while (cmpxchg(&pi_desc->control, old.control,
2200                         new.control) != old.control);
2201 }
2202 
2203 static void decache_tsc_multiplier(struct vcpu_vmx *vmx)
2204 {
2205         vmx->current_tsc_ratio = vmx->vcpu.arch.tsc_scaling_ratio;
2206         vmcs_write64(TSC_MULTIPLIER, vmx->current_tsc_ratio);
2207 }
2208 
2209 /*
2210  * Switches to specified vcpu, until a matching vcpu_put(), but assumes
2211  * vcpu mutex is already taken.
2212  */
2213 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2214 {
2215         struct vcpu_vmx *vmx = to_vmx(vcpu);
2216         u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2217         bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
2218 
2219         if (!vmm_exclusive)
2220                 kvm_cpu_vmxon(phys_addr);
2221         else if (!already_loaded)
2222                 loaded_vmcs_clear(vmx->loaded_vmcs);
2223 
2224         if (!already_loaded) {
2225                 local_irq_disable();
2226                 crash_disable_local_vmclear(cpu);
2227 
2228                 /*
2229                  * Read loaded_vmcs->cpu should be before fetching
2230                  * loaded_vmcs->loaded_vmcss_on_cpu_link.
2231                  * See the comments in __loaded_vmcs_clear().
2232                  */
2233                 smp_rmb();
2234 
2235                 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
2236                          &per_cpu(loaded_vmcss_on_cpu, cpu));
2237                 crash_enable_local_vmclear(cpu);
2238                 local_irq_enable();
2239         }
2240 
2241         if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
2242                 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
2243                 vmcs_load(vmx->loaded_vmcs->vmcs);
2244         }
2245 
2246         if (!already_loaded) {
2247                 struct desc_ptr *gdt = this_cpu_ptr(&host_gdt);
2248                 unsigned long sysenter_esp;
2249 
2250                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2251 
2252                 /*
2253                  * Linux uses per-cpu TSS and GDT, so set these when switching
2254                  * processors.
2255                  */
2256                 vmcs_writel(HOST_TR_BASE, kvm_read_tr_base()); /* 22.2.4 */
2257                 vmcs_writel(HOST_GDTR_BASE, gdt->address);   /* 22.2.4 */
2258 
2259                 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
2260                 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
2261 
2262                 vmx->loaded_vmcs->cpu = cpu;
2263         }
2264 
2265         /* Setup TSC multiplier */
2266         if (kvm_has_tsc_control &&
2267             vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
2268                 decache_tsc_multiplier(vmx);
2269 
2270         vmx_vcpu_pi_load(vcpu, cpu);
2271         vmx->host_pkru = read_pkru();
2272 }
2273 
2274 static void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
2275 {
2276         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
2277 
2278         if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
2279                 !irq_remapping_cap(IRQ_POSTING_CAP)  ||
2280                 !kvm_vcpu_apicv_active(vcpu))
2281                 return;
2282 
2283         /* Set SN when the vCPU is preempted */
2284         if (vcpu->preempted)
2285                 pi_set_sn(pi_desc);
2286 }
2287 
2288 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
2289 {
2290         vmx_vcpu_pi_put(vcpu);
2291 
2292         __vmx_load_host_state(to_vmx(vcpu));
2293         if (!vmm_exclusive) {
2294                 __loaded_vmcs_clear(to_vmx(vcpu)->loaded_vmcs);
2295                 vcpu->cpu = -1;
2296                 kvm_cpu_vmxoff();
2297         }
2298 }
2299 
2300 static void vmx_fpu_activate(struct kvm_vcpu *vcpu)
2301 {
2302         ulong cr0;
2303 
2304         if (vcpu->fpu_active)
2305                 return;
2306         vcpu->fpu_active = 1;
2307         cr0 = vmcs_readl(GUEST_CR0);
2308         cr0 &= ~(X86_CR0_TS | X86_CR0_MP);
2309         cr0 |= kvm_read_cr0_bits(vcpu, X86_CR0_TS | X86_CR0_MP);
2310         vmcs_writel(GUEST_CR0, cr0);
2311         update_exception_bitmap(vcpu);
2312         vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
2313         if (is_guest_mode(vcpu))
2314                 vcpu->arch.cr0_guest_owned_bits &=
2315                         ~get_vmcs12(vcpu)->cr0_guest_host_mask;
2316         vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
2317 }
2318 
2319 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
2320 
2321 /*
2322  * Return the cr0 value that a nested guest would read. This is a combination
2323  * of the real cr0 used to run the guest (guest_cr0), and the bits shadowed by
2324  * its hypervisor (cr0_read_shadow).
2325  */
2326 static inline unsigned long nested_read_cr0(struct vmcs12 *fields)
2327 {
2328         return (fields->guest_cr0 & ~fields->cr0_guest_host_mask) |
2329                 (fields->cr0_read_shadow & fields->cr0_guest_host_mask);
2330 }
2331 static inline unsigned long nested_read_cr4(struct vmcs12 *fields)
2332 {
2333         return (fields->guest_cr4 & ~fields->cr4_guest_host_mask) |
2334                 (fields->cr4_read_shadow & fields->cr4_guest_host_mask);
2335 }
2336 
2337 static void vmx_fpu_deactivate(struct kvm_vcpu *vcpu)
2338 {
2339         /* Note that there is no vcpu->fpu_active = 0 here. The caller must
2340          * set this *before* calling this function.
2341          */
2342         vmx_decache_cr0_guest_bits(vcpu);
2343         vmcs_set_bits(GUEST_CR0, X86_CR0_TS | X86_CR0_MP);
2344         update_exception_bitmap(vcpu);
2345         vcpu->arch.cr0_guest_owned_bits = 0;
2346         vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
2347         if (is_guest_mode(vcpu)) {
2348                 /*
2349                  * L1's specified read shadow might not contain the TS bit,
2350                  * so now that we turned on shadowing of this bit, we need to
2351                  * set this bit of the shadow. Like in nested_vmx_run we need
2352                  * nested_read_cr0(vmcs12), but vmcs12->guest_cr0 is not yet
2353                  * up-to-date here because we just decached cr0.TS (and we'll
2354                  * only update vmcs12->guest_cr0 on nested exit).
2355                  */
2356                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
2357                 vmcs12->guest_cr0 = (vmcs12->guest_cr0 & ~X86_CR0_TS) |
2358                         (vcpu->arch.cr0 & X86_CR0_TS);
2359                 vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
2360         } else
2361                 vmcs_writel(CR0_READ_SHADOW, vcpu->arch.cr0);
2362 }
2363 
2364 static unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
2365 {
2366         unsigned long rflags, save_rflags;
2367 
2368         if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
2369                 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
2370                 rflags = vmcs_readl(GUEST_RFLAGS);
2371                 if (to_vmx(vcpu)->rmode.vm86_active) {
2372                         rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2373                         save_rflags = to_vmx(vcpu)->rmode.save_rflags;
2374                         rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2375                 }
2376                 to_vmx(vcpu)->rflags = rflags;
2377         }
2378         return to_vmx(vcpu)->rflags;
2379 }
2380 
2381 static void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
2382 {
2383         __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
2384         to_vmx(vcpu)->rflags = rflags;
2385         if (to_vmx(vcpu)->rmode.vm86_active) {
2386                 to_vmx(vcpu)->rmode.save_rflags = rflags;
2387                 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2388         }
2389         vmcs_writel(GUEST_RFLAGS, rflags);
2390 }
2391 
2392 static u32 vmx_get_pkru(struct kvm_vcpu *vcpu)
2393 {
2394         return to_vmx(vcpu)->guest_pkru;
2395 }
2396 
2397 static u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
2398 {
2399         u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
2400         int ret = 0;
2401 
2402         if (interruptibility & GUEST_INTR_STATE_STI)
2403                 ret |= KVM_X86_SHADOW_INT_STI;
2404         if (interruptibility & GUEST_INTR_STATE_MOV_SS)
2405                 ret |= KVM_X86_SHADOW_INT_MOV_SS;
2406 
2407         return ret;
2408 }
2409 
2410 static void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
2411 {
2412         u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
2413         u32 interruptibility = interruptibility_old;
2414 
2415         interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
2416 
2417         if (mask & KVM_X86_SHADOW_INT_MOV_SS)
2418                 interruptibility |= GUEST_INTR_STATE_MOV_SS;
2419         else if (mask & KVM_X86_SHADOW_INT_STI)
2420                 interruptibility |= GUEST_INTR_STATE_STI;
2421 
2422         if ((interruptibility != interruptibility_old))
2423                 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
2424 }
2425 
2426 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
2427 {
2428         unsigned long rip;
2429 
2430         rip = kvm_rip_read(vcpu);
2431         rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
2432         kvm_rip_write(vcpu, rip);
2433 
2434         /* skipping an emulated instruction also counts */
2435         vmx_set_interrupt_shadow(vcpu, 0);
2436 }
2437 
2438 /*
2439  * KVM wants to inject page-faults which it got to the guest. This function
2440  * checks whether in a nested guest, we need to inject them to L1 or L2.
2441  */
2442 static int nested_vmx_check_exception(struct kvm_vcpu *vcpu, unsigned nr)
2443 {
2444         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
2445 
2446         if (!(vmcs12->exception_bitmap & (1u << nr)))
2447                 return 0;
2448 
2449         nested_vmx_vmexit(vcpu, to_vmx(vcpu)->exit_reason,
2450                           vmcs_read32(VM_EXIT_INTR_INFO),
2451                           vmcs_readl(EXIT_QUALIFICATION));
2452         return 1;
2453 }
2454 
2455 static void vmx_queue_exception(struct kvm_vcpu *vcpu, unsigned nr,
2456                                 bool has_error_code, u32 error_code,
2457                                 bool reinject)
2458 {
2459         struct vcpu_vmx *vmx = to_vmx(vcpu);
2460         u32 intr_info = nr | INTR_INFO_VALID_MASK;
2461 
2462         if (!reinject && is_guest_mode(vcpu) &&
2463             nested_vmx_check_exception(vcpu, nr))
2464                 return;
2465 
2466         if (has_error_code) {
2467                 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
2468                 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
2469         }
2470 
2471         if (vmx->rmode.vm86_active) {
2472                 int inc_eip = 0;
2473                 if (kvm_exception_is_soft(nr))
2474                         inc_eip = vcpu->arch.event_exit_inst_len;
2475                 if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
2476                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2477                 return;
2478         }
2479 
2480         if (kvm_exception_is_soft(nr)) {
2481                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
2482                              vmx->vcpu.arch.event_exit_inst_len);
2483                 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
2484         } else
2485                 intr_info |= INTR_TYPE_HARD_EXCEPTION;
2486 
2487         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
2488 }
2489 
2490 static bool vmx_rdtscp_supported(void)
2491 {
2492         return cpu_has_vmx_rdtscp();
2493 }
2494 
2495 static bool vmx_invpcid_supported(void)
2496 {
2497         return cpu_has_vmx_invpcid() && enable_ept;
2498 }
2499 
2500 /*
2501  * Swap MSR entry in host/guest MSR entry array.
2502  */
2503 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
2504 {
2505         struct shared_msr_entry tmp;
2506 
2507         tmp = vmx->guest_msrs[to];
2508         vmx->guest_msrs[to] = vmx->guest_msrs[from];
2509         vmx->guest_msrs[from] = tmp;
2510 }
2511 
2512 static void vmx_set_msr_bitmap(struct kvm_vcpu *vcpu)
2513 {
2514         unsigned long *msr_bitmap;
2515 
2516         if (is_guest_mode(vcpu))
2517                 msr_bitmap = to_vmx(vcpu)->nested.msr_bitmap;
2518         else if (cpu_has_secondary_exec_ctrls() &&
2519                  (vmcs_read32(SECONDARY_VM_EXEC_CONTROL) &
2520                   SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
2521                 if (is_long_mode(vcpu))
2522                         msr_bitmap = vmx_msr_bitmap_longmode_x2apic;
2523                 else
2524                         msr_bitmap = vmx_msr_bitmap_legacy_x2apic;
2525         } else {
2526                 if (is_long_mode(vcpu))
2527                         msr_bitmap = vmx_msr_bitmap_longmode;
2528                 else
2529                         msr_bitmap = vmx_msr_bitmap_legacy;
2530         }
2531 
2532         vmcs_write64(MSR_BITMAP, __pa(msr_bitmap));
2533 }
2534 
2535 /*
2536  * Set up the vmcs to automatically save and restore system
2537  * msrs.  Don't touch the 64-bit msrs if the guest is in legacy
2538  * mode, as fiddling with msrs is very expensive.
2539  */
2540 static void setup_msrs(struct vcpu_vmx *vmx)
2541 {
2542         int save_nmsrs, index;
2543 
2544         save_nmsrs = 0;
2545 #ifdef CONFIG_X86_64
2546         if (is_long_mode(&vmx->vcpu)) {
2547                 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
2548                 if (index >= 0)
2549                         move_msr_up(vmx, index, save_nmsrs++);
2550                 index = __find_msr_index(vmx, MSR_LSTAR);
2551                 if (index >= 0)
2552                         move_msr_up(vmx, index, save_nmsrs++);
2553                 index = __find_msr_index(vmx, MSR_CSTAR);
2554                 if (index >= 0)
2555                         move_msr_up(vmx, index, save_nmsrs++);
2556                 index = __find_msr_index(vmx, MSR_TSC_AUX);
2557                 if (index >= 0 && guest_cpuid_has_rdtscp(&vmx->vcpu))
2558                         move_msr_up(vmx, index, save_nmsrs++);
2559                 /*
2560                  * MSR_STAR is only needed on long mode guests, and only
2561                  * if efer.sce is enabled.
2562                  */
2563                 index = __find_msr_index(vmx, MSR_STAR);
2564                 if ((index >= 0) && (vmx->vcpu.arch.efer & EFER_SCE))
2565                         move_msr_up(vmx, index, save_nmsrs++);
2566         }
2567 #endif
2568         index = __find_msr_index(vmx, MSR_EFER);
2569         if (index >= 0 && update_transition_efer(vmx, index))
2570                 move_msr_up(vmx, index, save_nmsrs++);
2571 
2572         vmx->save_nmsrs = save_nmsrs;
2573 
2574         if (cpu_has_vmx_msr_bitmap())
2575                 vmx_set_msr_bitmap(&vmx->vcpu);
2576 }
2577 
2578 /*
2579  * reads and returns guest's timestamp counter "register"
2580  * guest_tsc = (host_tsc * tsc multiplier) >> 48 + tsc_offset
2581  * -- Intel TSC Scaling for Virtualization White Paper, sec 1.3
2582  */
2583 static u64 guest_read_tsc(struct kvm_vcpu *vcpu)
2584 {
2585         u64 host_tsc, tsc_offset;
2586 
2587         host_tsc = rdtsc();
2588         tsc_offset = vmcs_read64(TSC_OFFSET);
2589         return kvm_scale_tsc(vcpu, host_tsc) + tsc_offset;
2590 }
2591 
2592 /*
2593  * Like guest_read_tsc, but always returns L1's notion of the timestamp
2594  * counter, even if a nested guest (L2) is currently running.
2595  */
2596 static u64 vmx_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
2597 {
2598         u64 tsc_offset;
2599 
2600         tsc_offset = is_guest_mode(vcpu) ?
2601                 to_vmx(vcpu)->nested.vmcs01_tsc_offset :
2602                 vmcs_read64(TSC_OFFSET);
2603         return host_tsc + tsc_offset;
2604 }
2605 
2606 static u64 vmx_read_tsc_offset(struct kvm_vcpu *vcpu)
2607 {
2608         return vmcs_read64(TSC_OFFSET);
2609 }
2610 
2611 /*
2612  * writes 'offset' into guest's timestamp counter offset register
2613  */
2614 static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
2615 {
2616         if (is_guest_mode(vcpu)) {
2617                 /*
2618                  * We're here if L1 chose not to trap WRMSR to TSC. According
2619                  * to the spec, this should set L1's TSC; The offset that L1
2620                  * set for L2 remains unchanged, and still needs to be added
2621                  * to the newly set TSC to get L2's TSC.
2622                  */
2623                 struct vmcs12 *vmcs12;
2624                 to_vmx(vcpu)->nested.vmcs01_tsc_offset = offset;
2625                 /* recalculate vmcs02.TSC_OFFSET: */
2626                 vmcs12 = get_vmcs12(vcpu);
2627                 vmcs_write64(TSC_OFFSET, offset +
2628                         (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETING) ?
2629                          vmcs12->tsc_offset : 0));
2630         } else {
2631                 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
2632                                            vmcs_read64(TSC_OFFSET), offset);
2633                 vmcs_write64(TSC_OFFSET, offset);
2634         }
2635 }
2636 
2637 static void vmx_adjust_tsc_offset_guest(struct kvm_vcpu *vcpu, s64 adjustment)
2638 {
2639         u64 offset = vmcs_read64(TSC_OFFSET);
2640 
2641         vmcs_write64(TSC_OFFSET, offset + adjustment);
2642         if (is_guest_mode(vcpu)) {
2643                 /* Even when running L2, the adjustment needs to apply to L1 */
2644                 to_vmx(vcpu)->nested.vmcs01_tsc_offset += adjustment;
2645         } else
2646                 trace_kvm_write_tsc_offset(vcpu->vcpu_id, offset,
2647                                            offset + adjustment);
2648 }
2649 
2650 static bool guest_cpuid_has_vmx(struct kvm_vcpu *vcpu)
2651 {
2652         struct kvm_cpuid_entry2 *best = kvm_find_cpuid_entry(vcpu, 1, 0);
2653         return best && (best->ecx & (1 << (X86_FEATURE_VMX & 31)));
2654 }
2655 
2656 /*
2657  * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
2658  * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
2659  * all guests if the "nested" module option is off, and can also be disabled
2660  * for a single guest by disabling its VMX cpuid bit.
2661  */
2662 static inline bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
2663 {
2664         return nested && guest_cpuid_has_vmx(vcpu);
2665 }
2666 
2667 /*
2668  * nested_vmx_setup_ctls_msrs() sets up variables containing the values to be
2669  * returned for the various VMX controls MSRs when nested VMX is enabled.
2670  * The same values should also be used to verify that vmcs12 control fields are
2671  * valid during nested entry from L1 to L2.
2672  * Each of these control msrs has a low and high 32-bit half: A low bit is on
2673  * if the corresponding bit in the (32-bit) control field *must* be on, and a
2674  * bit in the high half is on if the corresponding bit in the control field
2675  * may be on. See also vmx_control_verify().
2676  */
2677 static void nested_vmx_setup_ctls_msrs(struct vcpu_vmx *vmx)
2678 {
2679         /*
2680          * Note that as a general rule, the high half of the MSRs (bits in
2681          * the control fields which may be 1) should be initialized by the
2682          * intersection of the underlying hardware's MSR (i.e., features which
2683          * can be supported) and the list of features we want to expose -
2684          * because they are known to be properly supported in our code.
2685          * Also, usually, the low half of the MSRs (bits which must be 1) can
2686          * be set to 0, meaning that L1 may turn off any of these bits. The
2687          * reason is that if one of these bits is necessary, it will appear
2688          * in vmcs01 and prepare_vmcs02, when it bitwise-or's the control
2689          * fields of vmcs01 and vmcs02, will turn these bits off - and
2690          * nested_vmx_exit_handled() will not pass related exits to L1.
2691          * These rules have exceptions below.
2692          */
2693 
2694         /* pin-based controls */
2695         rdmsr(MSR_IA32_VMX_PINBASED_CTLS,
2696                 vmx->nested.nested_vmx_pinbased_ctls_low,
2697                 vmx->nested.nested_vmx_pinbased_ctls_high);
2698         vmx->nested.nested_vmx_pinbased_ctls_low |=
2699                 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
2700         vmx->nested.nested_vmx_pinbased_ctls_high &=
2701                 PIN_BASED_EXT_INTR_MASK |
2702                 PIN_BASED_NMI_EXITING |
2703                 PIN_BASED_VIRTUAL_NMIS;
2704         vmx->nested.nested_vmx_pinbased_ctls_high |=
2705                 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
2706                 PIN_BASED_VMX_PREEMPTION_TIMER;
2707         if (kvm_vcpu_apicv_active(&vmx->vcpu))
2708                 vmx->nested.nested_vmx_pinbased_ctls_high |=
2709                         PIN_BASED_POSTED_INTR;
2710 
2711         /* exit controls */
2712         rdmsr(MSR_IA32_VMX_EXIT_CTLS,
2713                 vmx->nested.nested_vmx_exit_ctls_low,
2714                 vmx->nested.nested_vmx_exit_ctls_high);
2715         vmx->nested.nested_vmx_exit_ctls_low =
2716                 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
2717 
2718         vmx->nested.nested_vmx_exit_ctls_high &=
2719 #ifdef CONFIG_X86_64
2720                 VM_EXIT_HOST_ADDR_SPACE_SIZE |
2721 #endif
2722                 VM_EXIT_LOAD_IA32_PAT | VM_EXIT_SAVE_IA32_PAT;
2723         vmx->nested.nested_vmx_exit_ctls_high |=
2724                 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR |
2725                 VM_EXIT_LOAD_IA32_EFER | VM_EXIT_SAVE_IA32_EFER |
2726                 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER | VM_EXIT_ACK_INTR_ON_EXIT;
2727 
2728         if (kvm_mpx_supported())
2729                 vmx->nested.nested_vmx_exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
2730 
2731         /* We support free control of debug control saving. */
2732         vmx->nested.nested_vmx_true_exit_ctls_low =
2733                 vmx->nested.nested_vmx_exit_ctls_low &
2734                 ~VM_EXIT_SAVE_DEBUG_CONTROLS;
2735 
2736         /* entry controls */
2737         rdmsr(MSR_IA32_VMX_ENTRY_CTLS,
2738                 vmx->nested.nested_vmx_entry_ctls_low,
2739                 vmx->nested.nested_vmx_entry_ctls_high);
2740         vmx->nested.nested_vmx_entry_ctls_low =
2741                 VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
2742         vmx->nested.nested_vmx_entry_ctls_high &=
2743 #ifdef CONFIG_X86_64
2744                 VM_ENTRY_IA32E_MODE |
2745 #endif
2746                 VM_ENTRY_LOAD_IA32_PAT;
2747         vmx->nested.nested_vmx_entry_ctls_high |=
2748                 (VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR | VM_ENTRY_LOAD_IA32_EFER);
2749         if (kvm_mpx_supported())
2750                 vmx->nested.nested_vmx_entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
2751 
2752         /* We support free control of debug control loading. */
2753         vmx->nested.nested_vmx_true_entry_ctls_low =
2754                 vmx->nested.nested_vmx_entry_ctls_low &
2755                 ~VM_ENTRY_LOAD_DEBUG_CONTROLS;
2756 
2757         /* cpu-based controls */
2758         rdmsr(MSR_IA32_VMX_PROCBASED_CTLS,
2759                 vmx->nested.nested_vmx_procbased_ctls_low,
2760                 vmx->nested.nested_vmx_procbased_ctls_high);
2761         vmx->nested.nested_vmx_procbased_ctls_low =
2762                 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
2763         vmx->nested.nested_vmx_procbased_ctls_high &=
2764                 CPU_BASED_VIRTUAL_INTR_PENDING |
2765                 CPU_BASED_VIRTUAL_NMI_PENDING | CPU_BASED_USE_TSC_OFFSETING |
2766                 CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING |
2767                 CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING |
2768                 CPU_BASED_CR3_STORE_EXITING |
2769 #ifdef CONFIG_X86_64
2770                 CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING |
2771 #endif
2772                 CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING |
2773                 CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_TRAP_FLAG |
2774                 CPU_BASED_MONITOR_EXITING | CPU_BASED_RDPMC_EXITING |
2775                 CPU_BASED_RDTSC_EXITING | CPU_BASED_PAUSE_EXITING |
2776                 CPU_BASED_TPR_SHADOW | CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2777         /*
2778          * We can allow some features even when not supported by the
2779          * hardware. For example, L1 can specify an MSR bitmap - and we
2780          * can use it to avoid exits to L1 - even when L0 runs L2
2781          * without MSR bitmaps.
2782          */
2783         vmx->nested.nested_vmx_procbased_ctls_high |=
2784                 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
2785                 CPU_BASED_USE_MSR_BITMAPS;
2786 
2787         /* We support free control of CR3 access interception. */
2788         vmx->nested.nested_vmx_true_procbased_ctls_low =
2789                 vmx->nested.nested_vmx_procbased_ctls_low &
2790                 ~(CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_CR3_STORE_EXITING);
2791 
2792         /* secondary cpu-based controls */
2793         rdmsr(MSR_IA32_VMX_PROCBASED_CTLS2,
2794                 vmx->nested.nested_vmx_secondary_ctls_low,
2795                 vmx->nested.nested_vmx_secondary_ctls_high);
2796         vmx->nested.nested_vmx_secondary_ctls_low = 0;
2797         vmx->nested.nested_vmx_secondary_ctls_high &=
2798                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2799                 SECONDARY_EXEC_RDTSCP |
2800                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2801                 SECONDARY_EXEC_ENABLE_VPID |
2802                 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2803                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2804                 SECONDARY_EXEC_WBINVD_EXITING |
2805                 SECONDARY_EXEC_XSAVES;
2806 
2807         if (enable_ept) {
2808                 /* nested EPT: emulate EPT also to L1 */
2809                 vmx->nested.nested_vmx_secondary_ctls_high |=
2810                         SECONDARY_EXEC_ENABLE_EPT;
2811                 vmx->nested.nested_vmx_ept_caps = VMX_EPT_PAGE_WALK_4_BIT |
2812                          VMX_EPTP_WB_BIT | VMX_EPT_2MB_PAGE_BIT |
2813                          VMX_EPT_INVEPT_BIT;
2814                 if (cpu_has_vmx_ept_execute_only())
2815                         vmx->nested.nested_vmx_ept_caps |=
2816                                 VMX_EPT_EXECUTE_ONLY_BIT;
2817                 vmx->nested.nested_vmx_ept_caps &= vmx_capability.ept;
2818                 vmx->nested.nested_vmx_ept_caps |= VMX_EPT_EXTENT_GLOBAL_BIT |
2819                         VMX_EPT_EXTENT_CONTEXT_BIT;
2820         } else
2821                 vmx->nested.nested_vmx_ept_caps = 0;
2822 
2823         /*
2824          * Old versions of KVM use the single-context version without
2825          * checking for support, so declare that it is supported even
2826          * though it is treated as global context.  The alternative is
2827          * not failing the single-context invvpid, and it is worse.
2828          */
2829         if (enable_vpid)
2830                 vmx->nested.nested_vmx_vpid_caps = VMX_VPID_INVVPID_BIT |
2831                                 VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT |
2832                                 VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT;
2833         else
2834                 vmx->nested.nested_vmx_vpid_caps = 0;
2835 
2836         if (enable_unrestricted_guest)
2837                 vmx->nested.nested_vmx_secondary_ctls_high |=
2838                         SECONDARY_EXEC_UNRESTRICTED_GUEST;
2839 
2840         /* miscellaneous data */
2841         rdmsr(MSR_IA32_VMX_MISC,
2842                 vmx->nested.nested_vmx_misc_low,
2843                 vmx->nested.nested_vmx_misc_high);
2844         vmx->nested.nested_vmx_misc_low &= VMX_MISC_SAVE_EFER_LMA;
2845         vmx->nested.nested_vmx_misc_low |=
2846                 VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE |
2847                 VMX_MISC_ACTIVITY_HLT;
2848         vmx->nested.nested_vmx_misc_high = 0;
2849 }
2850 
2851 static inline bool vmx_control_verify(u32 control, u32 low, u32 high)
2852 {
2853         /*
2854          * Bits 0 in high must be 0, and bits 1 in low must be 1.
2855          */
2856         return ((control & high) | low) == control;
2857 }
2858 
2859 static inline u64 vmx_control_msr(u32 low, u32 high)
2860 {
2861         return low | ((u64)high << 32);
2862 }
2863 
2864 /* Returns 0 on success, non-0 otherwise. */
2865 static int vmx_get_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
2866 {
2867         struct vcpu_vmx *vmx = to_vmx(vcpu);
2868 
2869         switch (msr_index) {
2870         case MSR_IA32_VMX_BASIC:
2871                 /*
2872                  * This MSR reports some information about VMX support. We
2873                  * should return information about the VMX we emulate for the
2874                  * guest, and the VMCS structure we give it - not about the
2875                  * VMX support of the underlying hardware.
2876                  */
2877                 *pdata = VMCS12_REVISION | VMX_BASIC_TRUE_CTLS |
2878                            ((u64)VMCS12_SIZE << VMX_BASIC_VMCS_SIZE_SHIFT) |
2879                            (VMX_BASIC_MEM_TYPE_WB << VMX_BASIC_MEM_TYPE_SHIFT);
2880                 break;
2881         case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
2882         case MSR_IA32_VMX_PINBASED_CTLS:
2883                 *pdata = vmx_control_msr(
2884                         vmx->nested.nested_vmx_pinbased_ctls_low,
2885                         vmx->nested.nested_vmx_pinbased_ctls_high);
2886                 break;
2887         case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
2888                 *pdata = vmx_control_msr(
2889                         vmx->nested.nested_vmx_true_procbased_ctls_low,
2890                         vmx->nested.nested_vmx_procbased_ctls_high);
2891                 break;
2892         case MSR_IA32_VMX_PROCBASED_CTLS:
2893                 *pdata = vmx_control_msr(
2894                         vmx->nested.nested_vmx_procbased_ctls_low,
2895                         vmx->nested.nested_vmx_procbased_ctls_high);
2896                 break;
2897         case MSR_IA32_VMX_TRUE_EXIT_CTLS:
2898                 *pdata = vmx_control_msr(
2899                         vmx->nested.nested_vmx_true_exit_ctls_low,
2900                         vmx->nested.nested_vmx_exit_ctls_high);
2901                 break;
2902         case MSR_IA32_VMX_EXIT_CTLS:
2903                 *pdata = vmx_control_msr(
2904                         vmx->nested.nested_vmx_exit_ctls_low,
2905                         vmx->nested.nested_vmx_exit_ctls_high);
2906                 break;
2907         case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
2908                 *pdata = vmx_control_msr(
2909                         vmx->nested.nested_vmx_true_entry_ctls_low,
2910                         vmx->nested.nested_vmx_entry_ctls_high);
2911                 break;
2912         case MSR_IA32_VMX_ENTRY_CTLS:
2913                 *pdata = vmx_control_msr(
2914                         vmx->nested.nested_vmx_entry_ctls_low,
2915                         vmx->nested.nested_vmx_entry_ctls_high);
2916                 break;
2917         case MSR_IA32_VMX_MISC:
2918                 *pdata = vmx_control_msr(
2919                         vmx->nested.nested_vmx_misc_low,
2920                         vmx->nested.nested_vmx_misc_high);
2921                 break;
2922         /*
2923          * These MSRs specify bits which the guest must keep fixed (on or off)
2924          * while L1 is in VMXON mode (in L1's root mode, or running an L2).
2925          * We picked the standard core2 setting.
2926          */
2927 #define VMXON_CR0_ALWAYSON      (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE)
2928 #define VMXON_CR4_ALWAYSON      X86_CR4_VMXE
2929         case MSR_IA32_VMX_CR0_FIXED0:
2930                 *pdata = VMXON_CR0_ALWAYSON;
2931                 break;
2932         case MSR_IA32_VMX_CR0_FIXED1:
2933                 *pdata = -1ULL;
2934                 break;
2935         case MSR_IA32_VMX_CR4_FIXED0:
2936                 *pdata = VMXON_CR4_ALWAYSON;
2937                 break;
2938         case MSR_IA32_VMX_CR4_FIXED1:
2939                 *pdata = -1ULL;
2940                 break;
2941         case MSR_IA32_VMX_VMCS_ENUM:
2942                 *pdata = 0x2e; /* highest index: VMX_PREEMPTION_TIMER_VALUE */
2943                 break;
2944         case MSR_IA32_VMX_PROCBASED_CTLS2:
2945                 *pdata = vmx_control_msr(
2946                         vmx->nested.nested_vmx_secondary_ctls_low,
2947                         vmx->nested.nested_vmx_secondary_ctls_high);
2948                 break;
2949         case MSR_IA32_VMX_EPT_VPID_CAP:
2950                 *pdata = vmx->nested.nested_vmx_ept_caps |
2951                         ((u64)vmx->nested.nested_vmx_vpid_caps << 32);
2952                 break;
2953         default:
2954                 return 1;
2955         }
2956 
2957         return 0;
2958 }
2959 
2960 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
2961                                                  uint64_t val)
2962 {
2963         uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
2964 
2965         return !(val & ~valid_bits);
2966 }
2967 
2968 /*
2969  * Reads an msr value (of 'msr_index') into 'pdata'.
2970  * Returns 0 on success, non-0 otherwise.
2971  * Assumes vcpu_load() was already called.
2972  */
2973 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2974 {
2975         struct shared_msr_entry *msr;
2976 
2977         switch (msr_info->index) {
2978 #ifdef CONFIG_X86_64
2979         case MSR_FS_BASE:
2980                 msr_info->data = vmcs_readl(GUEST_FS_BASE);
2981                 break;
2982         case MSR_GS_BASE:
2983                 msr_info->data = vmcs_readl(GUEST_GS_BASE);
2984                 break;
2985         case MSR_KERNEL_GS_BASE:
2986                 vmx_load_host_state(to_vmx(vcpu));
2987                 msr_info->data = to_vmx(vcpu)->msr_guest_kernel_gs_base;
2988                 break;
2989 #endif
2990         case MSR_EFER:
2991                 return kvm_get_msr_common(vcpu, msr_info);
2992         case MSR_IA32_TSC:
2993                 msr_info->data = guest_read_tsc(vcpu);
2994                 break;
2995         case MSR_IA32_SYSENTER_CS:
2996                 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
2997                 break;
2998         case MSR_IA32_SYSENTER_EIP:
2999                 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
3000                 break;
3001         case MSR_IA32_SYSENTER_ESP:
3002                 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
3003                 break;
3004         case MSR_IA32_BNDCFGS:
3005                 if (!kvm_mpx_supported())
3006                         return 1;
3007                 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
3008                 break;
3009         case MSR_IA32_MCG_EXT_CTL:
3010                 if (!msr_info->host_initiated &&
3011                     !(to_vmx(vcpu)->msr_ia32_feature_control &
3012                       FEATURE_CONTROL_LMCE))
3013                         return 1;
3014                 msr_info->data = vcpu->arch.mcg_ext_ctl;
3015                 break;
3016         case MSR_IA32_FEATURE_CONTROL:
3017                 msr_info->data = to_vmx(vcpu)->msr_ia32_feature_control;
3018                 break;
3019         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
3020                 if (!nested_vmx_allowed(vcpu))
3021                         return 1;
3022                 return vmx_get_vmx_msr(vcpu, msr_info->index, &msr_info->data);
3023         case MSR_IA32_XSS:
3024                 if (!vmx_xsaves_supported())
3025                         return 1;
3026                 msr_info->data = vcpu->arch.ia32_xss;
3027                 break;
3028         case MSR_TSC_AUX:
3029                 if (!guest_cpuid_has_rdtscp(vcpu) && !msr_info->host_initiated)
3030                         return 1;
3031                 /* Otherwise falls through */
3032         default:
3033                 msr = find_msr_entry(to_vmx(vcpu), msr_info->index);
3034                 if (msr) {
3035                         msr_info->data = msr->data;
3036                         break;
3037                 }
3038                 return kvm_get_msr_common(vcpu, msr_info);
3039         }
3040 
3041         return 0;
3042 }
3043 
3044 static void vmx_leave_nested(struct kvm_vcpu *vcpu);
3045 
3046 /*
3047  * Writes msr value into into the appropriate "register".
3048  * Returns 0 on success, non-0 otherwise.
3049  * Assumes vcpu_load() was already called.
3050  */
3051 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3052 {
3053         struct vcpu_vmx *vmx = to_vmx(vcpu);
3054         struct shared_msr_entry *msr;
3055         int ret = 0;
3056         u32 msr_index = msr_info->index;
3057         u64 data = msr_info->data;
3058 
3059         switch (msr_index) {
3060         case MSR_EFER:
3061                 ret = kvm_set_msr_common(vcpu, msr_info);
3062                 break;
3063 #ifdef CONFIG_X86_64
3064         case MSR_FS_BASE:
3065                 vmx_segment_cache_clear(vmx);
3066                 vmcs_writel(GUEST_FS_BASE, data);
3067                 break;
3068         case MSR_GS_BASE:
3069                 vmx_segment_cache_clear(vmx);
3070                 vmcs_writel(GUEST_GS_BASE, data);
3071                 break;
3072         case MSR_KERNEL_GS_BASE:
3073                 vmx_load_host_state(vmx);
3074                 vmx->msr_guest_kernel_gs_base = data;
3075                 break;
3076 #endif
3077         case MSR_IA32_SYSENTER_CS:
3078                 vmcs_write32(GUEST_SYSENTER_CS, data);
3079                 break;
3080         case MSR_IA32_SYSENTER_EIP:
3081                 vmcs_writel(GUEST_SYSENTER_EIP, data);
3082                 break;
3083         case MSR_IA32_SYSENTER_ESP:
3084                 vmcs_writel(GUEST_SYSENTER_ESP, data);
3085                 break;
3086         case MSR_IA32_BNDCFGS:
3087                 if (!kvm_mpx_supported())
3088                         return 1;
3089                 vmcs_write64(GUEST_BNDCFGS, data);
3090                 break;
3091         case MSR_IA32_TSC:
3092                 kvm_write_tsc(vcpu, msr_info);
3093                 break;
3094         case MSR_IA32_CR_PAT:
3095                 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
3096                         if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
3097                                 return 1;
3098                         vmcs_write64(GUEST_IA32_PAT, data);
3099                         vcpu->arch.pat = data;
3100                         break;
3101                 }
3102                 ret = kvm_set_msr_common(vcpu, msr_info);
3103                 break;
3104         case MSR_IA32_TSC_ADJUST:
3105                 ret = kvm_set_msr_common(vcpu, msr_info);
3106                 break;
3107         case MSR_IA32_MCG_EXT_CTL:
3108                 if ((!msr_info->host_initiated &&
3109                      !(to_vmx(vcpu)->msr_ia32_feature_control &
3110                        FEATURE_CONTROL_LMCE)) ||
3111                     (data & ~MCG_EXT_CTL_LMCE_EN))
3112                         return 1;
3113                 vcpu->arch.mcg_ext_ctl = data;
3114                 break;
3115         case MSR_IA32_FEATURE_CONTROL:
3116                 if (!vmx_feature_control_msr_valid(vcpu, data) ||
3117                     (to_vmx(vcpu)->msr_ia32_feature_control &
3118                      FEATURE_CONTROL_LOCKED && !msr_info->host_initiated))
3119                         return 1;
3120                 vmx->msr_ia32_feature_control = data;
3121                 if (msr_info->host_initiated && data == 0)
3122                         vmx_leave_nested(vcpu);
3123                 break;
3124         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
3125                 return 1; /* they are read-only */
3126         case MSR_IA32_XSS:
3127                 if (!vmx_xsaves_supported())
3128                         return 1;
3129                 /*
3130                  * The only supported bit as of Skylake is bit 8, but
3131                  * it is not supported on KVM.
3132                  */
3133                 if (data != 0)
3134                         return 1;
3135                 vcpu->arch.ia32_xss = data;
3136                 if (vcpu->arch.ia32_xss != host_xss)
3137                         add_atomic_switch_msr(vmx, MSR_IA32_XSS,
3138                                 vcpu->arch.ia32_xss, host_xss);
3139                 else
3140                         clear_atomic_switch_msr(vmx, MSR_IA32_XSS);
3141                 break;
3142         case MSR_TSC_AUX:
3143                 if (!guest_cpuid_has_rdtscp(vcpu) && !msr_info->host_initiated)
3144                         return 1;
3145                 /* Check reserved bit, higher 32 bits should be zero */
3146                 if ((data >> 32) != 0)
3147                         return 1;
3148                 /* Otherwise falls through */
3149         default:
3150                 msr = find_msr_entry(vmx, msr_index);
3151                 if (msr) {
3152                         u64 old_msr_data = msr->data;
3153                         msr->data = data;
3154                         if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
3155                                 preempt_disable();
3156                                 ret = kvm_set_shared_msr(msr->index, msr->data,
3157                                                          msr->mask);
3158                                 preempt_enable();
3159                                 if (ret)
3160                                         msr->data = old_msr_data;
3161                         }
3162                         break;
3163                 }
3164                 ret = kvm_set_msr_common(vcpu, msr_info);
3165         }
3166 
3167         return ret;
3168 }
3169 
3170 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
3171 {
3172         __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
3173         switch (reg) {
3174         case VCPU_REGS_RSP:
3175                 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
3176                 break;
3177         case VCPU_REGS_RIP:
3178                 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
3179                 break;
3180         case VCPU_EXREG_PDPTR:
3181                 if (enable_ept)
3182                         ept_save_pdptrs(vcpu);
3183                 break;
3184         default:
3185                 break;
3186         }
3187 }
3188 
3189 static __init int cpu_has_kvm_support(void)
3190 {
3191         return cpu_has_vmx();
3192 }
3193 
3194 static __init int vmx_disabled_by_bios(void)
3195 {
3196         u64 msr;
3197 
3198         rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
3199         if (msr & FEATURE_CONTROL_LOCKED) {
3200                 /* launched w/ TXT and VMX disabled */
3201                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
3202                         && tboot_enabled())
3203                         return 1;
3204                 /* launched w/o TXT and VMX only enabled w/ TXT */
3205                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
3206                         && (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
3207                         && !tboot_enabled()) {
3208                         printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
3209                                 "activate TXT before enabling KVM\n");
3210                         return 1;
3211                 }
3212                 /* launched w/o TXT and VMX disabled */
3213                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
3214                         && !tboot_enabled())
3215                         return 1;
3216         }
3217 
3218         return 0;
3219 }
3220 
3221 static void kvm_cpu_vmxon(u64 addr)
3222 {
3223         intel_pt_handle_vmx(1);
3224 
3225         asm volatile (ASM_VMX_VMXON_RAX
3226                         : : "a"(&addr), "m"(addr)
3227                         : "memory", "cc");
3228 }
3229 
3230 static int hardware_enable(void)
3231 {
3232         int cpu = raw_smp_processor_id();
3233         u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
3234         u64 old, test_bits;
3235 
3236         if (cr4_read_shadow() & X86_CR4_VMXE)
3237                 return -EBUSY;
3238 
3239         INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
3240         INIT_LIST_HEAD(&per_cpu(blocked_vcpu_on_cpu, cpu));
3241         spin_lock_init(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
3242 
3243         /*
3244          * Now we can enable the vmclear operation in kdump
3245          * since the loaded_vmcss_on_cpu list on this cpu
3246          * has been initialized.
3247          *
3248          * Though the cpu is not in VMX operation now, there
3249          * is no problem to enable the vmclear operation
3250          * for the loaded_vmcss_on_cpu list is empty!
3251          */
3252         crash_enable_local_vmclear(cpu);
3253 
3254         rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
3255 
3256         test_bits = FEATURE_CONTROL_LOCKED;
3257         test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
3258         if (tboot_enabled())
3259                 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
3260 
3261         if ((old & test_bits) != test_bits) {
3262                 /* enable and lock */
3263                 wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
3264         }
3265         cr4_set_bits(X86_CR4_VMXE);
3266 
3267         if (vmm_exclusive) {
3268                 kvm_cpu_vmxon(phys_addr);
3269                 ept_sync_global();
3270         }
3271 
3272         native_store_gdt(this_cpu_ptr(&host_gdt));
3273 
3274         return 0;
3275 }
3276 
3277 static void vmclear_local_loaded_vmcss(void)
3278 {
3279         int cpu = raw_smp_processor_id();
3280         struct loaded_vmcs *v, *n;
3281 
3282         list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
3283                                  loaded_vmcss_on_cpu_link)
3284                 __loaded_vmcs_clear(v);
3285 }
3286 
3287 
3288 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
3289  * tricks.
3290  */
3291 static void kvm_cpu_vmxoff(void)
3292 {
3293         asm volatile (__ex(ASM_VMX_VMXOFF) : : : "cc");
3294 
3295         intel_pt_handle_vmx(0);
3296 }
3297 
3298 static void hardware_disable(void)
3299 {
3300         if (vmm_exclusive) {
3301                 vmclear_local_loaded_vmcss();
3302                 kvm_cpu_vmxoff();
3303         }
3304         cr4_clear_bits(X86_CR4_VMXE);
3305 }
3306 
3307 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
3308                                       u32 msr, u32 *result)
3309 {
3310         u32 vmx_msr_low, vmx_msr_high;
3311         u32 ctl = ctl_min | ctl_opt;
3312 
3313         rdmsr(msr, vmx_msr_low, vmx_msr_high);
3314 
3315         ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
3316         ctl |= vmx_msr_low;  /* bit == 1 in low word  ==> must be one  */
3317 
3318         /* Ensure minimum (required) set of control bits are supported. */
3319         if (ctl_min & ~ctl)
3320                 return -EIO;
3321 
3322         *result = ctl;
3323         return 0;
3324 }
3325 
3326 static __init bool allow_1_setting(u32 msr, u32 ctl)
3327 {
3328         u32 vmx_msr_low, vmx_msr_high;
3329 
3330         rdmsr(msr, vmx_msr_low, vmx_msr_high);
3331         return vmx_msr_high & ctl;
3332 }
3333 
3334 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
3335 {
3336         u32 vmx_msr_low, vmx_msr_high;
3337         u32 min, opt, min2, opt2;
3338         u32 _pin_based_exec_control = 0;
3339         u32 _cpu_based_exec_control = 0;
3340         u32 _cpu_based_2nd_exec_control = 0;
3341         u32 _vmexit_control = 0;
3342         u32 _vmentry_control = 0;
3343 
3344         min = CPU_BASED_HLT_EXITING |
3345 #ifdef CONFIG_X86_64
3346               CPU_BASED_CR8_LOAD_EXITING |
3347               CPU_BASED_CR8_STORE_EXITING |
3348 #endif
3349               CPU_BASED_CR3_LOAD_EXITING |
3350               CPU_BASED_CR3_STORE_EXITING |
3351               CPU_BASED_USE_IO_BITMAPS |
3352               CPU_BASED_MOV_DR_EXITING |
3353               CPU_BASED_USE_TSC_OFFSETING |
3354               CPU_BASED_MWAIT_EXITING |
3355               CPU_BASED_MONITOR_EXITING |
3356               CPU_BASED_INVLPG_EXITING |
3357               CPU_BASED_RDPMC_EXITING;
3358 
3359         opt = CPU_BASED_TPR_SHADOW |
3360               CPU_BASED_USE_MSR_BITMAPS |
3361               CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
3362         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
3363                                 &_cpu_based_exec_control) < 0)
3364                 return -EIO;
3365 #ifdef CONFIG_X86_64
3366         if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
3367                 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
3368                                            ~CPU_BASED_CR8_STORE_EXITING;
3369 #endif
3370         if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
3371                 min2 = 0;
3372                 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
3373                         SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
3374                         SECONDARY_EXEC_WBINVD_EXITING |
3375                         SECONDARY_EXEC_ENABLE_VPID |
3376                         SECONDARY_EXEC_ENABLE_EPT |
3377                         SECONDARY_EXEC_UNRESTRICTED_GUEST |
3378                         SECONDARY_EXEC_PAUSE_LOOP_EXITING |
3379                         SECONDARY_EXEC_RDTSCP |
3380                         SECONDARY_EXEC_ENABLE_INVPCID |
3381                         SECONDARY_EXEC_APIC_REGISTER_VIRT |
3382                         SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
3383                         SECONDARY_EXEC_SHADOW_VMCS |
3384                         SECONDARY_EXEC_XSAVES |
3385                         SECONDARY_EXEC_ENABLE_PML |
3386                         SECONDARY_EXEC_TSC_SCALING;
3387                 if (adjust_vmx_controls(min2, opt2,
3388                                         MSR_IA32_VMX_PROCBASED_CTLS2,
3389                                         &_cpu_based_2nd_exec_control) < 0)
3390                         return -EIO;
3391         }
3392 #ifndef CONFIG_X86_64
3393         if (!(_cpu_based_2nd_exec_control &
3394                                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
3395                 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
3396 #endif
3397 
3398         if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
3399                 _cpu_based_2nd_exec_control &= ~(
3400                                 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3401                                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
3402                                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
3403 
3404         if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
3405                 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
3406                    enabled */
3407                 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
3408                                              CPU_BASED_CR3_STORE_EXITING |
3409                                              CPU_BASED_INVLPG_EXITING);
3410                 rdmsr(MSR_IA32_VMX_EPT_VPID_CAP,
3411                       vmx_capability.ept, vmx_capability.vpid);
3412         }
3413 
3414         min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
3415 #ifdef CONFIG_X86_64
3416         min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
3417 #endif
3418         opt = VM_EXIT_SAVE_IA32_PAT | VM_EXIT_LOAD_IA32_PAT |
3419                 VM_EXIT_CLEAR_BNDCFGS;
3420         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
3421                                 &_vmexit_control) < 0)
3422                 return -EIO;
3423 
3424         min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
3425         opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
3426                  PIN_BASED_VMX_PREEMPTION_TIMER;
3427         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
3428                                 &_pin_based_exec_control) < 0)
3429                 return -EIO;
3430 
3431         if (cpu_has_broken_vmx_preemption_timer())
3432                 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
3433         if (!(_cpu_based_2nd_exec_control &
3434                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
3435                 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
3436 
3437         min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
3438         opt = VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_BNDCFGS;
3439         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
3440                                 &_vmentry_control) < 0)
3441                 return -EIO;
3442 
3443         rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
3444 
3445         /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
3446         if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
3447                 return -EIO;
3448 
3449 #ifdef CONFIG_X86_64
3450         /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
3451         if (vmx_msr_high & (1u<<16))
3452                 return -EIO;
3453 #endif
3454 
3455         /* Require Write-Back (WB) memory type for VMCS accesses. */
3456         if (((vmx_msr_high >> 18) & 15) != 6)
3457                 return -EIO;
3458 
3459         vmcs_conf->size = vmx_msr_high & 0x1fff;
3460         vmcs_conf->order = get_order(vmcs_config.size);
3461         vmcs_conf->revision_id = vmx_msr_low;
3462 
3463         vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
3464         vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
3465         vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
3466         vmcs_conf->vmexit_ctrl         = _vmexit_control;
3467         vmcs_conf->vmentry_ctrl        = _vmentry_control;
3468 
3469         cpu_has_load_ia32_efer =
3470                 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
3471                                 VM_ENTRY_LOAD_IA32_EFER)
3472                 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
3473                                    VM_EXIT_LOAD_IA32_EFER);
3474 
3475         cpu_has_load_perf_global_ctrl =
3476                 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
3477                                 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
3478                 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
3479                                    VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
3480 
3481         /*
3482          * Some cpus support VM_ENTRY_(LOAD|SAVE)_IA32_PERF_GLOBAL_CTRL
3483          * but due to errata below it can't be used. Workaround is to use
3484          * msr load mechanism to switch IA32_PERF_GLOBAL_CTRL.
3485          *
3486          * VM Exit May Incorrectly Clear IA32_PERF_GLOBAL_CTRL [34:32]
3487          *
3488          * AAK155             (model 26)
3489          * AAP115             (model 30)
3490          * AAT100             (model 37)
3491          * BC86,AAY89,BD102   (model 44)
3492          * BA97               (model 46)
3493          *
3494          */
3495         if (cpu_has_load_perf_global_ctrl && boot_cpu_data.x86 == 0x6) {
3496                 switch (boot_cpu_data.x86_model) {
3497                 case 26:
3498                 case 30:
3499                 case 37:
3500                 case 44:
3501                 case 46:
3502                         cpu_has_load_perf_global_ctrl = false;
3503                         printk_once(KERN_WARNING"kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
3504                                         "does not work properly. Using workaround\n");
3505                         break;
3506                 default:
3507                         break;
3508                 }
3509         }
3510 
3511         if (boot_cpu_has(X86_FEATURE_XSAVES))
3512                 rdmsrl(MSR_IA32_XSS, host_xss);
3513 
3514         return 0;
3515 }
3516 
3517 static struct vmcs *alloc_vmcs_cpu(int cpu)
3518 {
3519         int node = cpu_to_node(cpu);
3520         struct page *pages;
3521         struct vmcs *vmcs;
3522 
3523         pages = __alloc_pages_node(node, GFP_KERNEL, vmcs_config.order);
3524         if (!pages)
3525                 return NULL;
3526         vmcs = page_address(pages);
3527         memset(vmcs, 0, vmcs_config.size);
3528         vmcs->revision_id = vmcs_config.revision_id; /* vmcs revision id */
3529         return vmcs;
3530 }
3531 
3532 static struct vmcs *alloc_vmcs(void)
3533 {
3534         return alloc_vmcs_cpu(raw_smp_processor_id());
3535 }
3536 
3537 static void free_vmcs(struct vmcs *vmcs)
3538 {
3539         free_pages((unsigned long)vmcs, vmcs_config.order);
3540 }
3541 
3542 /*
3543  * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
3544  */
3545 static void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
3546 {
3547         if (!loaded_vmcs->vmcs)
3548                 return;
3549         loaded_vmcs_clear(loaded_vmcs);
3550         free_vmcs(loaded_vmcs->vmcs);
3551         loaded_vmcs->vmcs = NULL;
3552 }
3553 
3554 static void free_kvm_area(void)
3555 {
3556         int cpu;
3557 
3558         for_each_possible_cpu(cpu) {
3559                 free_vmcs(per_cpu(vmxarea, cpu));
3560                 per_cpu(vmxarea, cpu) = NULL;
3561         }
3562 }
3563 
3564 static void init_vmcs_shadow_fields(void)
3565 {
3566         int i, j;
3567 
3568         /* No checks for read only fields yet */
3569 
3570         for (i = j = 0; i < max_shadow_read_write_fields; i++) {
3571                 switch (shadow_read_write_fields[i]) {
3572                 case GUEST_BNDCFGS:
3573                         if (!kvm_mpx_supported())
3574                                 continue;
3575                         break;
3576                 default:
3577                         break;
3578                 }
3579 
3580                 if (j < i)
3581                         shadow_read_write_fields[j] =
3582                                 shadow_read_write_fields[i];
3583                 j++;
3584         }
3585         max_shadow_read_write_fields = j;
3586 
3587         /* shadowed fields guest access without vmexit */
3588         for (i = 0; i < max_shadow_read_write_fields; i++) {
3589                 clear_bit(shadow_read_write_fields[i],
3590                           vmx_vmwrite_bitmap);
3591                 clear_bit(shadow_read_write_fields[i],
3592                           vmx_vmread_bitmap);
3593         }
3594         for (i = 0; i < max_shadow_read_only_fields; i++)
3595                 clear_bit(shadow_read_only_fields[i],
3596                           vmx_vmread_bitmap);
3597 }
3598 
3599 static __init int alloc_kvm_area(void)
3600 {
3601         int cpu;
3602 
3603         for_each_possible_cpu(cpu) {
3604                 struct vmcs *vmcs;
3605 
3606                 vmcs = alloc_vmcs_cpu(cpu);
3607                 if (!vmcs) {
3608                         free_kvm_area();
3609                         return -ENOMEM;
3610                 }
3611 
3612                 per_cpu(vmxarea, cpu) = vmcs;
3613         }
3614         return 0;
3615 }
3616 
3617 static bool emulation_required(struct kvm_vcpu *vcpu)
3618 {
3619         return emulate_invalid_guest_state && !guest_state_valid(vcpu);
3620 }
3621 
3622 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
3623                 struct kvm_segment *save)
3624 {
3625         if (!emulate_invalid_guest_state) {
3626                 /*
3627                  * CS and SS RPL should be equal during guest entry according
3628                  * to VMX spec, but in reality it is not always so. Since vcpu
3629                  * is in the middle of the transition from real mode to
3630                  * protected mode it is safe to assume that RPL 0 is a good
3631                  * default value.
3632                  */
3633                 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
3634                         save->selector &= ~SEGMENT_RPL_MASK;
3635                 save->dpl = save->selector & SEGMENT_RPL_MASK;
3636                 save->s = 1;
3637         }
3638         vmx_set_segment(vcpu, save, seg);
3639 }
3640 
3641 static void enter_pmode(struct kvm_vcpu *vcpu)
3642 {
3643         unsigned long flags;
3644         struct vcpu_vmx *vmx = to_vmx(vcpu);
3645 
3646         /*
3647          * Update real mode segment cache. It may be not up-to-date if sement
3648          * register was written while vcpu was in a guest mode.
3649          */
3650         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
3651         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
3652         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
3653         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
3654         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
3655         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
3656 
3657         vmx->rmode.vm86_active = 0;
3658 
3659         vmx_segment_cache_clear(vmx);
3660 
3661         vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
3662 
3663         flags = vmcs_readl(GUEST_RFLAGS);
3664         flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
3665         flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
3666         vmcs_writel(GUEST_RFLAGS, flags);
3667 
3668         vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
3669                         (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
3670 
3671         update_exception_bitmap(vcpu);
3672 
3673         fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
3674         fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
3675         fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
3676         fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
3677         fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
3678         fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
3679 }
3680 
3681 static void fix_rmode_seg(int seg, struct kvm_segment *save)
3682 {
3683         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3684         struct kvm_segment var = *save;
3685 
3686         var.dpl = 0x3;
3687         if (seg == VCPU_SREG_CS)
3688                 var.type = 0x3;
3689 
3690         if (!emulate_invalid_guest_state) {
3691                 var.selector = var.base >> 4;
3692                 var.base = var.base & 0xffff0;
3693                 var.limit = 0xffff;
3694                 var.g = 0;
3695                 var.db = 0;
3696                 var.present = 1;
3697                 var.s = 1;
3698                 var.l = 0;
3699                 var.unusable = 0;
3700                 var.type = 0x3;
3701                 var.avl = 0;
3702                 if (save->base & 0xf)
3703                         printk_once(KERN_WARNING "kvm: segment base is not "
3704                                         "paragraph aligned when entering "
3705                                         "protected mode (seg=%d)", seg);
3706         }
3707 
3708         vmcs_write16(sf->selector, var.selector);
3709         vmcs_write32(sf->base, var.base);
3710         vmcs_write32(sf->limit, var.limit);
3711         vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
3712 }
3713 
3714 static void enter_rmode(struct kvm_vcpu *vcpu)
3715 {
3716         unsigned long flags;
3717         struct vcpu_vmx *vmx = to_vmx(vcpu);
3718 
3719         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
3720         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
3721         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
3722         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
3723         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
3724         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
3725         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
3726 
3727         vmx->rmode.vm86_active = 1;
3728 
3729         /*
3730          * Very old userspace does not call KVM_SET_TSS_ADDR before entering
3731          * vcpu. Warn the user that an update is overdue.
3732          */
3733         if (!vcpu->kvm->arch.tss_addr)
3734                 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
3735                              "called before entering vcpu\n");
3736 
3737         vmx_segment_cache_clear(vmx);
3738 
3739         vmcs_writel(GUEST_TR_BASE, vcpu->kvm->arch.tss_addr);
3740         vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
3741         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
3742 
3743         flags = vmcs_readl(GUEST_RFLAGS);
3744         vmx->rmode.save_rflags = flags;
3745 
3746         flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
3747 
3748         vmcs_writel(GUEST_RFLAGS, flags);
3749         vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
3750         update_exception_bitmap(vcpu);
3751 
3752         fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
3753         fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
3754         fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
3755         fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
3756         fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
3757         fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
3758 
3759         kvm_mmu_reset_context(vcpu);
3760 }
3761 
3762 static void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
3763 {
3764         struct vcpu_vmx *vmx = to_vmx(vcpu);
3765         struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
3766 
3767         if (!msr)
3768                 return;
3769 
3770         /*
3771          * Force kernel_gs_base reloading before EFER changes, as control
3772          * of this msr depends on is_long_mode().
3773          */
3774         vmx_load_host_state(to_vmx(vcpu));
3775         vcpu->arch.efer = efer;
3776         if (efer & EFER_LMA) {
3777                 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
3778                 msr->data = efer;
3779         } else {
3780                 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
3781 
3782                 msr->data = efer & ~EFER_LME;
3783         }
3784         setup_msrs(vmx);
3785 }
3786 
3787 #ifdef CONFIG_X86_64
3788 
3789 static void enter_lmode(struct kvm_vcpu *vcpu)
3790 {
3791         u32 guest_tr_ar;
3792 
3793         vmx_segment_cache_clear(to_vmx(vcpu));
3794 
3795         guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
3796         if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
3797                 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
3798                                      __func__);
3799                 vmcs_write32(GUEST_TR_AR_BYTES,
3800                              (guest_tr_ar & ~VMX_AR_TYPE_MASK)
3801                              | VMX_AR_TYPE_BUSY_64_TSS);
3802         }
3803         vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
3804 }
3805 
3806 static void exit_lmode(struct kvm_vcpu *vcpu)
3807 {
3808         vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
3809         vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
3810 }
3811 
3812 #endif
3813 
3814 static inline void __vmx_flush_tlb(struct kvm_vcpu *vcpu, int vpid)
3815 {
3816         vpid_sync_context(vpid);
3817         if (enable_ept) {
3818                 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3819                         return;
3820                 ept_sync_context(construct_eptp(vcpu->arch.mmu.root_hpa));
3821         }
3822 }
3823 
3824 static void vmx_flush_tlb(struct kvm_vcpu *vcpu)
3825 {
3826         __vmx_flush_tlb(vcpu, to_vmx(vcpu)->vpid);
3827 }
3828 
3829 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
3830 {
3831         ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
3832 
3833         vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
3834         vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
3835 }
3836 
3837 static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
3838 {
3839         if (enable_ept && is_paging(vcpu))
3840                 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
3841         __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
3842 }
3843 
3844 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
3845 {
3846         ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
3847 
3848         vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
3849         vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
3850 }
3851 
3852 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
3853 {
3854         struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
3855 
3856         if (!test_bit(VCPU_EXREG_PDPTR,
3857                       (unsigned long *)&vcpu->arch.regs_dirty))
3858                 return;
3859 
3860         if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
3861                 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
3862                 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
3863                 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
3864                 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
3865         }
3866 }
3867 
3868 static void ept_save_pdptrs(struct kvm_vcpu *vcpu)
3869 {
3870         struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
3871 
3872         if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
3873                 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
3874                 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
3875                 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
3876                 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
3877         }
3878 
3879         __set_bit(VCPU_EXREG_PDPTR,
3880                   (unsigned long *)&vcpu->arch.regs_avail);
3881         __set_bit(VCPU_EXREG_PDPTR,
3882                   (unsigned long *)&vcpu->arch.regs_dirty);
3883 }
3884 
3885 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
3886 
3887 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
3888                                         unsigned long cr0,
3889                                         struct kvm_vcpu *vcpu)
3890 {
3891         if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
3892                 vmx_decache_cr3(vcpu);
3893         if (!(cr0 & X86_CR0_PG)) {
3894                 /* From paging/starting to nonpaging */
3895                 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
3896                              vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
3897                              (CPU_BASED_CR3_LOAD_EXITING |
3898                               CPU_BASED_CR3_STORE_EXITING));
3899                 vcpu->arch.cr0 = cr0;
3900                 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3901         } else if (!is_paging(vcpu)) {
3902                 /* From nonpaging to paging */
3903                 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
3904                              vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
3905                              ~(CPU_BASED_CR3_LOAD_EXITING |
3906                                CPU_BASED_CR3_STORE_EXITING));
3907                 vcpu->arch.cr0 = cr0;
3908                 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3909         }
3910 
3911         if (!(cr0 & X86_CR0_WP))
3912                 *hw_cr0 &= ~X86_CR0_WP;
3913 }
3914 
3915 static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
3916 {
3917         struct vcpu_vmx *vmx = to_vmx(vcpu);
3918         unsigned long hw_cr0;
3919 
3920         hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK);
3921         if (enable_unrestricted_guest)
3922                 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
3923         else {
3924                 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
3925 
3926                 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
3927                         enter_pmode(vcpu);
3928 
3929                 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
3930                         enter_rmode(vcpu);
3931         }
3932 
3933 #ifdef CONFIG_X86_64
3934         if (vcpu->arch.efer & EFER_LME) {
3935                 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
3936                         enter_lmode(vcpu);
3937                 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
3938                         exit_lmode(vcpu);
3939         }
3940 #endif
3941 
3942         if (enable_ept)
3943                 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
3944 
3945         if (!vcpu->fpu_active)
3946                 hw_cr0 |= X86_CR0_TS | X86_CR0_MP;
3947 
3948         vmcs_writel(CR0_READ_SHADOW, cr0);
3949         vmcs_writel(GUEST_CR0, hw_cr0);
3950         vcpu->arch.cr0 = cr0;
3951 
3952         /* depends on vcpu->arch.cr0 to be set to a new value */
3953         vmx->emulation_required = emulation_required(vcpu);
3954 }
3955 
3956 static u64 construct_eptp(unsigned long root_hpa)
3957 {
3958         u64 eptp;
3959 
3960         /* TODO write the value reading from MSR */
3961         eptp = VMX_EPT_DEFAULT_MT |
3962                 VMX_EPT_DEFAULT_GAW << VMX_EPT_GAW_EPTP_SHIFT;
3963         if (enable_ept_ad_bits)
3964                 eptp |= VMX_EPT_AD_ENABLE_BIT;
3965         eptp |= (root_hpa & PAGE_MASK);
3966 
3967         return eptp;
3968 }
3969 
3970 static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
3971 {
3972         unsigned long guest_cr3;
3973         u64 eptp;
3974 
3975         guest_cr3 = cr3;
3976         if (enable_ept) {
3977                 eptp = construct_eptp(cr3);
3978                 vmcs_write64(EPT_POINTER, eptp);
3979                 if (is_paging(vcpu) || is_guest_mode(vcpu))
3980                         guest_cr3 = kvm_read_cr3(vcpu);
3981                 else
3982                         guest_cr3 = vcpu->kvm->arch.ept_identity_map_addr;
3983                 ept_load_pdptrs(vcpu);
3984         }
3985 
3986         vmx_flush_tlb(vcpu);
3987         vmcs_writel(GUEST_CR3, guest_cr3);
3988 }
3989 
3990 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3991 {
3992         /*
3993          * Pass through host's Machine Check Enable value to hw_cr4, which
3994          * is in force while we are in guest mode.  Do not let guests control
3995          * this bit, even if host CR4.MCE == 0.
3996          */
3997         unsigned long hw_cr4 =
3998                 (cr4_read_shadow() & X86_CR4_MCE) |
3999                 (cr4 & ~X86_CR4_MCE) |
4000                 (to_vmx(vcpu)->rmode.vm86_active ?
4001                  KVM_RMODE_VM_CR4_ALWAYS_ON : KVM_PMODE_VM_CR4_ALWAYS_ON);
4002 
4003         if (cr4 & X86_CR4_VMXE) {
4004                 /*
4005                  * To use VMXON (and later other VMX instructions), a guest
4006                  * must first be able to turn on cr4.VMXE (see handle_vmon()).
4007                  * So basically the check on whether to allow nested VMX
4008                  * is here.
4009                  */
4010                 if (!nested_vmx_allowed(vcpu))
4011                         return 1;
4012         }
4013         if (to_vmx(vcpu)->nested.vmxon &&
4014             ((cr4 & VMXON_CR4_ALWAYSON) != VMXON_CR4_ALWAYSON))
4015                 return 1;
4016 
4017         vcpu->arch.cr4 = cr4;
4018         if (enable_ept) {
4019                 if (!is_paging(vcpu)) {
4020                         hw_cr4 &= ~X86_CR4_PAE;
4021                         hw_cr4 |= X86_CR4_PSE;
4022                 } else if (!(cr4 & X86_CR4_PAE)) {
4023                         hw_cr4 &= ~X86_CR4_PAE;
4024                 }
4025         }
4026 
4027         if (!enable_unrestricted_guest && !is_paging(vcpu))
4028                 /*
4029                  * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
4030                  * hardware.  To emulate this behavior, SMEP/SMAP/PKU needs
4031                  * to be manually disabled when guest switches to non-paging
4032                  * mode.
4033                  *
4034                  * If !enable_unrestricted_guest, the CPU is always running
4035                  * with CR0.PG=1 and CR4 needs to be modified.
4036                  * If enable_unrestricted_guest, the CPU automatically
4037                  * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
4038                  */
4039                 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
4040 
4041         vmcs_writel(CR4_READ_SHADOW, cr4);
4042         vmcs_writel(GUEST_CR4, hw_cr4);
4043         return 0;
4044 }
4045 
4046 static void vmx_get_segment(struct kvm_vcpu *vcpu,
4047                             struct kvm_segment *var, int seg)
4048 {
4049         struct vcpu_vmx *vmx = to_vmx(vcpu);
4050         u32 ar;
4051 
4052         if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
4053                 *var = vmx->rmode.segs[seg];
4054                 if (seg == VCPU_SREG_TR
4055                     || var->selector == vmx_read_guest_seg_selector(vmx, seg))
4056                         return;
4057                 var->base = vmx_read_guest_seg_base(vmx, seg);
4058                 var->selector = vmx_read_guest_seg_selector(vmx, seg);
4059                 return;
4060         }
4061         var->base = vmx_read_guest_seg_base(vmx, seg);
4062         var->limit = vmx_read_guest_seg_limit(vmx, seg);
4063         var->selector = vmx_read_guest_seg_selector(vmx, seg);
4064         ar = vmx_read_guest_seg_ar(vmx, seg);
4065         var->unusable = (ar >> 16) & 1;
4066         var->type = ar & 15;
4067         var->s = (ar >> 4) & 1;
4068         var->dpl = (ar >> 5) & 3;
4069         /*
4070          * Some userspaces do not preserve unusable property. Since usable
4071          * segment has to be present according to VMX spec we can use present
4072          * property to amend userspace bug by making unusable segment always
4073          * nonpresent. vmx_segment_access_rights() already marks nonpresent
4074          * segment as unusable.
4075          */
4076         var->present = !var->unusable;
4077         var->avl = (ar >> 12) & 1;
4078         var->l = (ar >> 13) & 1;
4079         var->db = (ar >> 14) & 1;
4080         var->g = (ar >> 15) & 1;
4081 }
4082 
4083 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
4084 {
4085         struct kvm_segment s;
4086 
4087         if (to_vmx(vcpu)->rmode.vm86_active) {
4088                 vmx_get_segment(vcpu, &s, seg);
4089                 return s.base;
4090         }
4091         return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
4092 }
4093 
4094 static int vmx_get_cpl(struct kvm_vcpu *vcpu)
4095 {
4096         struct vcpu_vmx *vmx = to_vmx(vcpu);
4097 
4098         if (unlikely(vmx->rmode.vm86_active))
4099                 return 0;
4100         else {
4101                 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
4102                 return VMX_AR_DPL(ar);
4103         }
4104 }
4105 
4106 static u32 vmx_segment_access_rights(struct kvm_segment *var)
4107 {
4108         u32 ar;
4109 
4110         if (var->unusable || !var->present)
4111                 ar = 1 << 16;
4112         else {
4113                 ar = var->type & 15;
4114                 ar |= (var->s & 1) << 4;
4115                 ar |= (var->dpl & 3) << 5;
4116                 ar |= (var->present & 1) << 7;
4117                 ar |= (var->avl & 1) << 12;
4118                 ar |= (var->l & 1) << 13;
4119                 ar |= (var->db & 1) << 14;
4120                 ar |= (var->g & 1) << 15;
4121         }
4122 
4123         return ar;
4124 }
4125 
4126 static void vmx_set_segment(struct kvm_vcpu *vcpu,
4127                             struct kvm_segment *var, int seg)
4128 {
4129         struct vcpu_vmx *vmx = to_vmx(vcpu);
4130         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
4131 
4132         vmx_segment_cache_clear(vmx);
4133 
4134         if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
4135                 vmx->rmode.segs[seg] = *var;
4136                 if (seg == VCPU_SREG_TR)
4137                         vmcs_write16(sf->selector, var->selector);
4138                 else if (var->s)
4139                         fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
4140                 goto out;
4141         }
4142 
4143         vmcs_writel(sf->base, var->base);
4144         vmcs_write32(sf->limit, var->limit);
4145         vmcs_write16(sf->selector, var->selector);
4146 
4147         /*
4148          *   Fix the "Accessed" bit in AR field of segment registers for older
4149          * qemu binaries.
4150          *   IA32 arch specifies that at the time of processor reset the
4151          * "Accessed" bit in the AR field of segment registers is 1. And qemu
4152          * is setting it to 0 in the userland code. This causes invalid guest
4153          * state vmexit when "unrestricted guest" mode is turned on.
4154          *    Fix for this setup issue in cpu_reset is being pushed in the qemu
4155          * tree. Newer qemu binaries with that qemu fix would not need this
4156          * kvm hack.
4157          */
4158         if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
4159                 var->type |= 0x1; /* Accessed */
4160 
4161         vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
4162 
4163 out:
4164         vmx->emulation_required = emulation_required(vcpu);
4165 }
4166 
4167 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
4168 {
4169         u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
4170 
4171         *db = (ar >> 14) & 1;
4172         *l = (ar >> 13) & 1;
4173 }
4174 
4175 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4176 {
4177         dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
4178         dt->address = vmcs_readl(GUEST_IDTR_BASE);
4179 }
4180 
4181 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4182 {
4183         vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
4184         vmcs_writel(GUEST_IDTR_BASE, dt->address);
4185 }
4186 
4187 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4188 {
4189         dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
4190         dt->address = vmcs_readl(GUEST_GDTR_BASE);
4191 }
4192 
4193 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4194 {
4195         vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
4196         vmcs_writel(GUEST_GDTR_BASE, dt->address);
4197 }
4198 
4199 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
4200 {
4201         struct kvm_segment var;
4202         u32 ar;
4203 
4204         vmx_get_segment(vcpu, &var, seg);
4205         var.dpl = 0x3;
4206         if (seg == VCPU_SREG_CS)
4207                 var.type = 0x3;
4208         ar = vmx_segment_access_rights(&var);
4209 
4210         if (var.base != (var.selector << 4))
4211                 return false;
4212         if (var.limit != 0xffff)
4213                 return false;
4214         if (ar != 0xf3)
4215                 return false;
4216 
4217         return true;
4218 }
4219 
4220 static bool code_segment_valid(struct kvm_vcpu *vcpu)
4221 {
4222         struct kvm_segment cs;
4223         unsigned int cs_rpl;
4224 
4225         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
4226         cs_rpl = cs.selector & SEGMENT_RPL_MASK;
4227 
4228         if (cs.unusable)
4229                 return false;
4230         if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
4231                 return false;
4232         if (!cs.s)
4233                 return false;
4234         if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
4235                 if (cs.dpl > cs_rpl)
4236                         return false;
4237         } else {
4238                 if (cs.dpl != cs_rpl)
4239                         return false;
4240         }
4241         if (!cs.present)
4242                 return false;
4243 
4244         /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
4245         return true;
4246 }
4247 
4248 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
4249 {
4250         struct kvm_segment ss;
4251         unsigned int ss_rpl;
4252 
4253         vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
4254         ss_rpl = ss.selector & SEGMENT_RPL_MASK;
4255 
4256         if (ss.unusable)
4257                 return true;
4258         if (ss.type != 3 && ss.type != 7)
4259                 return false;
4260         if (!ss.s)
4261                 return false;
4262         if (ss.dpl != ss_rpl) /* DPL != RPL */
4263                 return false;
4264         if (!ss.present)
4265                 return false;
4266 
4267         return true;
4268 }
4269 
4270 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
4271 {
4272         struct kvm_segment var;
4273         unsigned int rpl;
4274 
4275         vmx_get_segment(vcpu, &var, seg);
4276         rpl = var.selector & SEGMENT_RPL_MASK;
4277 
4278         if (var.unusable)
4279                 return true;
4280         if (!var.s)
4281                 return false;
4282         if (!var.present)
4283                 return false;
4284         if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
4285                 if (var.dpl < rpl) /* DPL < RPL */
4286                         return false;
4287         }
4288 
4289         /* TODO: Add other members to kvm_segment_field to allow checking for other access
4290          * rights flags
4291          */
4292         return true;
4293 }
4294 
4295 static bool tr_valid(struct kvm_vcpu *vcpu)
4296 {
4297         struct kvm_segment tr;
4298 
4299         vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
4300 
4301         if (tr.unusable)
4302                 return false;
4303         if (tr.selector & SEGMENT_TI_MASK)      /* TI = 1 */
4304                 return false;
4305         if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
4306                 return false;
4307         if (!tr.present)
4308                 return false;
4309 
4310         return true;
4311 }
4312 
4313 static bool ldtr_valid(struct kvm_vcpu *vcpu)
4314 {
4315         struct kvm_segment ldtr;
4316 
4317         vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
4318 
4319         if (ldtr.unusable)
4320                 return true;
4321         if (ldtr.selector & SEGMENT_TI_MASK)    /* TI = 1 */
4322                 return false;
4323         if (ldtr.type != 2)
4324                 return false;
4325         if (!ldtr.present)
4326                 return false;
4327 
4328         return true;
4329 }
4330 
4331 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
4332 {
4333         struct kvm_segment cs, ss;
4334 
4335         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
4336         vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
4337 
4338         return ((cs.selector & SEGMENT_RPL_MASK) ==
4339                  (ss.selector & SEGMENT_RPL_MASK));
4340 }
4341 
4342 /*
4343  * Check if guest state is valid. Returns true if valid, false if
4344  * not.
4345  * We assume that registers are always usable
4346  */
4347 static bool guest_state_valid(struct kvm_vcpu *vcpu)
4348 {
4349         if (enable_unrestricted_guest)
4350                 return true;
4351 
4352         /* real mode guest state checks */
4353         if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
4354                 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
4355                         return false;
4356                 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
4357                         return false;
4358                 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
4359                         return false;
4360                 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
4361                         return false;
4362                 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
4363                         return false;
4364                 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
4365                         return false;
4366         } else {
4367         /* protected mode guest state checks */
4368                 if (!cs_ss_rpl_check(vcpu))
4369                         return false;
4370                 if (!code_segment_valid(vcpu))
4371                         return false;
4372                 if (!stack_segment_valid(vcpu))
4373                         return false;
4374                 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
4375                         return false;
4376                 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
4377                         return false;
4378                 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
4379                         return false;
4380                 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
4381                         return false;
4382                 if (!tr_valid(vcpu))
4383                         return false;
4384                 if (!ldtr_valid(vcpu))
4385                         return false;
4386         }
4387         /* TODO:
4388          * - Add checks on RIP
4389          * - Add checks on RFLAGS
4390          */
4391 
4392         return true;
4393 }
4394 
4395 static int init_rmode_tss(struct kvm *kvm)
4396 {
4397         gfn_t fn;
4398         u16 data = 0;
4399         int idx, r;
4400 
4401         idx = srcu_read_lock(&kvm->srcu);
4402         fn = kvm->arch.tss_addr >> PAGE_SHIFT;
4403         r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
4404         if (r < 0)
4405                 goto out;
4406         data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
4407         r = kvm_write_guest_page(kvm, fn++, &data,
4408                         TSS_IOPB_BASE_OFFSET, sizeof(u16));
4409         if (r < 0)
4410                 goto out;
4411         r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
4412         if (r < 0)
4413                 goto out;
4414         r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
4415         if (r < 0)
4416                 goto out;
4417         data = ~0;
4418         r = kvm_write_guest_page(kvm, fn, &data,
4419                                  RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
4420                                  sizeof(u8));
4421 out:
4422         srcu_read_unlock(&kvm->srcu, idx);
4423         return r;
4424 }
4425 
4426 static int init_rmode_identity_map(struct kvm *kvm)
4427 {
4428         int i, idx, r = 0;
4429         kvm_pfn_t identity_map_pfn;
4430         u32 tmp;
4431 
4432         if (!enable_ept)
4433                 return 0;
4434 
4435         /* Protect kvm->arch.ept_identity_pagetable_done. */
4436         mutex_lock(&kvm->slots_lock);
4437 
4438         if (likely(kvm->arch.ept_identity_pagetable_done))
4439                 goto out2;
4440 
4441         identity_map_pfn = kvm->arch.ept_identity_map_addr >> PAGE_SHIFT;
4442 
4443         r = alloc_identity_pagetable(kvm);
4444         if (r < 0)
4445                 goto out2;
4446 
4447         idx = srcu_read_lock(&kvm->srcu);
4448         r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
4449         if (r < 0)
4450                 goto out;
4451         /* Set up identity-mapping pagetable for EPT in real mode */
4452         for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
4453                 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
4454                         _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
4455                 r = kvm_write_guest_page(kvm, identity_map_pfn,
4456                                 &tmp, i * sizeof(tmp), sizeof(tmp));
4457                 if (r < 0)
4458                         goto out;
4459         }
4460         kvm->arch.ept_identity_pagetable_done = true;
4461 
4462 out:
4463         srcu_read_unlock(&kvm->srcu, idx);
4464 
4465 out2:
4466         mutex_unlock(&kvm->slots_lock);
4467         return r;
4468 }
4469 
4470 static void seg_setup(int seg)
4471 {
4472         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
4473         unsigned int ar;
4474 
4475         vmcs_write16(sf->selector, 0);
4476         vmcs_writel(sf->base, 0);
4477         vmcs_write32(sf->limit, 0xffff);
4478         ar = 0x93;
4479         if (seg == VCPU_SREG_CS)
4480                 ar |= 0x08; /* code segment */
4481 
4482         vmcs_write32(sf->ar_bytes, ar);
4483 }
4484 
4485 static int alloc_apic_access_page(struct kvm *kvm)
4486 {
4487         struct page *page;
4488         int r = 0;
4489 
4490         mutex_lock(&kvm->slots_lock);
4491         if (kvm->arch.apic_access_page_done)
4492                 goto out;
4493         r = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
4494                                     APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
4495         if (r)
4496                 goto out;
4497 
4498         page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
4499         if (is_error_page(page)) {
4500                 r = -EFAULT;
4501                 goto out;
4502         }
4503 
4504         /*
4505          * Do not pin the page in memory, so that memory hot-unplug
4506          * is able to migrate it.
4507          */
4508         put_page(page);
4509         kvm->arch.apic_access_page_done = true;
4510 out:
4511         mutex_unlock(&kvm->slots_lock);
4512         return r;
4513 }
4514 
4515 static int alloc_identity_pagetable(struct kvm *kvm)
4516 {
4517         /* Called with kvm->slots_lock held. */
4518 
4519         int r = 0;
4520 
4521         BUG_ON(kvm->arch.ept_identity_pagetable_done);
4522 
4523         r = __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
4524                                     kvm->arch.ept_identity_map_addr, PAGE_SIZE);
4525 
4526         return r;
4527 }
4528 
4529 static int allocate_vpid(void)
4530 {
4531         int vpid;
4532 
4533         if (!enable_vpid)
4534                 return 0;
4535         spin_lock(&vmx_vpid_lock);
4536         vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
4537         if (vpid < VMX_NR_VPIDS)
4538                 __set_bit(vpid, vmx_vpid_bitmap);
4539         else
4540                 vpid = 0;
4541         spin_unlock(&vmx_vpid_lock);
4542         return vpid;
4543 }
4544 
4545 static void free_vpid(int vpid)
4546 {
4547         if (!enable_vpid || vpid == 0)
4548                 return;
4549         spin_lock(&vmx_vpid_lock);
4550         __clear_bit(vpid, vmx_vpid_bitmap);
4551         spin_unlock(&vmx_vpid_lock);
4552 }
4553 
4554 #define MSR_TYPE_R      1
4555 #define MSR_TYPE_W      2
4556 static void __vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
4557                                                 u32 msr, int type)
4558 {
4559         int f = sizeof(unsigned long);
4560 
4561         if (!cpu_has_vmx_msr_bitmap())
4562                 return;
4563 
4564         /*
4565          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
4566          * have the write-low and read-high bitmap offsets the wrong way round.
4567          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
4568          */
4569         if (msr <= 0x1fff) {
4570                 if (type & MSR_TYPE_R)
4571                         /* read-low */
4572                         __clear_bit(msr, msr_bitmap + 0x000 / f);
4573 
4574                 if (type & MSR_TYPE_W)
4575                         /* write-low */
4576                         __clear_bit(msr, msr_bitmap + 0x800 / f);
4577 
4578         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
4579                 msr &= 0x1fff;
4580                 if (type & MSR_TYPE_R)
4581                         /* read-high */
4582                         __clear_bit(msr, msr_bitmap + 0x400 / f);
4583 
4584                 if (type & MSR_TYPE_W)
4585                         /* write-high */
4586                         __clear_bit(msr, msr_bitmap + 0xc00 / f);
4587 
4588         }
4589 }
4590 
4591 static void __vmx_enable_intercept_for_msr(unsigned long *msr_bitmap,
4592                                                 u32 msr, int type)
4593 {
4594         int f = sizeof(unsigned long);
4595 
4596         if (!cpu_has_vmx_msr_bitmap())
4597                 return;
4598 
4599         /*
4600          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
4601          * have the write-low and read-high bitmap offsets the wrong way round.
4602          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
4603          */
4604         if (msr <= 0x1fff) {
4605                 if (type & MSR_TYPE_R)
4606                         /* read-low */
4607                         __set_bit(msr, msr_bitmap + 0x000 / f);
4608 
4609                 if (type & MSR_TYPE_W)
4610                         /* write-low */
4611                         __set_bit(msr, msr_bitmap + 0x800 / f);
4612 
4613         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
4614                 msr &= 0x1fff;
4615                 if (type & MSR_TYPE_R)
4616                         /* read-high */
4617                         __set_bit(msr, msr_bitmap + 0x400 / f);
4618 
4619                 if (type & MSR_TYPE_W)
4620                         /* write-high */
4621                         __set_bit(msr, msr_bitmap + 0xc00 / f);
4622 
4623         }
4624 }
4625 
4626 /*
4627  * If a msr is allowed by L0, we should check whether it is allowed by L1.
4628  * The corresponding bit will be cleared unless both of L0 and L1 allow it.
4629  */
4630 static void nested_vmx_disable_intercept_for_msr(unsigned long *msr_bitmap_l1,
4631                                                unsigned long *msr_bitmap_nested,
4632                                                u32 msr, int type)
4633 {
4634         int f = sizeof(unsigned long);
4635 
4636         if (!cpu_has_vmx_msr_bitmap()) {
4637                 WARN_ON(1);
4638                 return;
4639         }
4640 
4641         /*
4642          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
4643          * have the write-low and read-high bitmap offsets the wrong way round.
4644          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
4645          */
4646         if (msr <= 0x1fff) {
4647                 if (type & MSR_TYPE_R &&
4648                    !test_bit(msr, msr_bitmap_l1 + 0x000 / f))
4649                         /* read-low */
4650                         __clear_bit(msr, msr_bitmap_nested + 0x000 / f);
4651 
4652                 if (type & MSR_TYPE_W &&
4653                    !test_bit(msr, msr_bitmap_l1 + 0x800 / f))
4654                         /* write-low */
4655                         __clear_bit(msr, msr_bitmap_nested + 0x800 / f);
4656 
4657         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
4658                 msr &= 0x1fff;
4659                 if (type & MSR_TYPE_R &&
4660                    !test_bit(msr, msr_bitmap_l1 + 0x400 / f))
4661                         /* read-high */
4662                         __clear_bit(msr, msr_bitmap_nested + 0x400 / f);
4663 
4664                 if (type & MSR_TYPE_W &&
4665                    !test_bit(msr, msr_bitmap_l1 + 0xc00 / f))
4666                         /* write-high */
4667                         __clear_bit(msr, msr_bitmap_nested + 0xc00 / f);
4668 
4669         }
4670 }
4671 
4672 static void vmx_disable_intercept_for_msr(u32 msr, bool longmode_only)
4673 {
4674         if (!longmode_only)
4675                 __vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy,
4676                                                 msr, MSR_TYPE_R | MSR_TYPE_W);
4677         __vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode,
4678                                                 msr, MSR_TYPE_R | MSR_TYPE_W);
4679 }
4680 
4681 static void vmx_enable_intercept_msr_read_x2apic(u32 msr)
4682 {
4683         __vmx_enable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic,
4684                         msr, MSR_TYPE_R);
4685         __vmx_enable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic,
4686                         msr, MSR_TYPE_R);
4687 }
4688 
4689 static void vmx_disable_intercept_msr_read_x2apic(u32 msr)
4690 {
4691         __vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic,
4692                         msr, MSR_TYPE_R);
4693         __vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic,
4694                         msr, MSR_TYPE_R);
4695 }
4696 
4697 static void vmx_disable_intercept_msr_write_x2apic(u32 msr)
4698 {
4699         __vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic,
4700                         msr, MSR_TYPE_W);
4701         __vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic,
4702                         msr, MSR_TYPE_W);
4703 }
4704 
4705 static bool vmx_get_enable_apicv(void)
4706 {
4707         return enable_apicv;
4708 }
4709 
4710 static int vmx_complete_nested_posted_interrupt(struct kvm_vcpu *vcpu)
4711 {
4712         struct vcpu_vmx *vmx = to_vmx(vcpu);
4713         int max_irr;
4714         void *vapic_page;
4715         u16 status;
4716 
4717         if (vmx->nested.pi_desc &&
4718             vmx->nested.pi_pending) {
4719                 vmx->nested.pi_pending = false;
4720                 if (!pi_test_and_clear_on(vmx->nested.pi_desc))
4721                         return 0;
4722 
4723                 max_irr = find_last_bit(
4724                         (unsigned long *)vmx->nested.pi_desc->pir, 256);
4725 
4726                 if (max_irr == 256)
4727                         return 0;
4728 
4729                 vapic_page = kmap(vmx->nested.virtual_apic_page);
4730                 if (!vapic_page) {
4731                         WARN_ON(1);
4732                         return -ENOMEM;
4733                 }
4734                 __kvm_apic_update_irr(vmx->nested.pi_desc->pir, vapic_page);
4735                 kunmap(vmx->nested.virtual_apic_page);
4736 
4737                 status = vmcs_read16(GUEST_INTR_STATUS);
4738                 if ((u8)max_irr > ((u8)status & 0xff)) {
4739                         status &= ~0xff;
4740                         status |= (u8)max_irr;
4741                         vmcs_write16(GUEST_INTR_STATUS, status);
4742                 }
4743         }
4744         return 0;
4745 }
4746 
4747 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu)
4748 {
4749 #ifdef CONFIG_SMP
4750         if (vcpu->mode == IN_GUEST_MODE) {
4751                 struct vcpu_vmx *vmx = to_vmx(vcpu);
4752 
4753                 /*
4754                  * Currently, we don't support urgent interrupt,
4755                  * all interrupts are recognized as non-urgent
4756                  * interrupt, so we cannot post interrupts when
4757                  * 'SN' is set.
4758                  *
4759                  * If the vcpu is in guest mode, it means it is
4760                  * running instead of being scheduled out and
4761                  * waiting in the run queue, and that's the only
4762                  * case when 'SN' is set currently, warning if
4763                  * 'SN' is set.
4764                  */
4765                 WARN_ON_ONCE(pi_test_sn(&vmx->pi_desc));
4766 
4767                 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu),
4768                                 POSTED_INTR_VECTOR);
4769                 return true;
4770         }
4771 #endif
4772         return false;
4773 }
4774 
4775 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
4776                                                 int vector)
4777 {
4778         struct vcpu_vmx *vmx = to_vmx(vcpu);
4779 
4780         if (is_guest_mode(vcpu) &&
4781             vector == vmx->nested.posted_intr_nv) {
4782                 /* the PIR and ON have been set by L1. */
4783                 kvm_vcpu_trigger_posted_interrupt(vcpu);
4784                 /*
4785                  * If a posted intr is not recognized by hardware,
4786                  * we will accomplish it in the next vmentry.
4787                  */
4788                 vmx->nested.pi_pending = true;
4789                 kvm_make_request(KVM_REQ_EVENT, vcpu);
4790                 return 0;
4791         }
4792         return -1;
4793 }
4794 /*
4795  * Send interrupt to vcpu via posted interrupt way.
4796  * 1. If target vcpu is running(non-root mode), send posted interrupt
4797  * notification to vcpu and hardware will sync PIR to vIRR atomically.
4798  * 2. If target vcpu isn't running(root mode), kick it to pick up the
4799  * interrupt from PIR in next vmentry.
4800  */
4801 static void vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
4802 {
4803         struct vcpu_vmx *vmx = to_vmx(vcpu);
4804         int r;
4805 
4806         r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
4807         if (!r)
4808                 return;
4809 
4810         if (pi_test_and_set_pir(vector, &vmx->pi_desc))
4811                 return;
4812 
4813         r = pi_test_and_set_on(&vmx->pi_desc);
4814         kvm_make_request(KVM_REQ_EVENT, vcpu);
4815         if (r || !kvm_vcpu_trigger_posted_interrupt(vcpu))
4816                 kvm_vcpu_kick(vcpu);
4817 }
4818 
4819 static void vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
4820 {
4821         struct vcpu_vmx *vmx = to_vmx(vcpu);
4822 
4823         if (!pi_test_and_clear_on(&vmx->pi_desc))
4824                 return;
4825 
4826         kvm_apic_update_irr(vcpu, vmx->pi_desc.pir);
4827 }
4828 
4829 /*
4830  * Set up the vmcs's constant host-state fields, i.e., host-state fields that
4831  * will not change in the lifetime of the guest.
4832  * Note that host-state that does change is set elsewhere. E.g., host-state
4833  * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
4834  */
4835 static void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
4836 {
4837         u32 low32, high32;
4838         unsigned long tmpl;
4839         struct desc_ptr dt;
4840         unsigned long cr4;
4841 
4842         vmcs_writel(HOST_CR0, read_cr0() & ~X86_CR0_TS);  /* 22.2.3 */
4843         vmcs_writel(HOST_CR3, read_cr3());  /* 22.2.3  FIXME: shadow tables */
4844 
4845         /* Save the most likely value for this task's CR4 in the VMCS. */
4846         cr4 = cr4_read_shadow();
4847         vmcs_writel(HOST_CR4, cr4);                     /* 22.2.3, 22.2.5 */
4848         vmx->host_state.vmcs_host_cr4 = cr4;
4849 
4850         vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS);  /* 22.2.4 */
4851 #ifdef CONFIG_X86_64
4852         /*
4853          * Load null selectors, so we can avoid reloading them in
4854          * __vmx_load_host_state(), in case userspace uses the null selectors
4855          * too (the expected case).
4856          */
4857         vmcs_write16(HOST_DS_SELECTOR, 0);
4858         vmcs_write16(HOST_ES_SELECTOR, 0);
4859 #else
4860         vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
4861         vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
4862 #endif
4863         vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
4864         vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8);  /* 22.2.4 */
4865 
4866         native_store_idt(&dt);
4867         vmcs_writel(HOST_IDTR_BASE, dt.address);   /* 22.2.4 */
4868         vmx->host_idt_base = dt.address;
4869 
4870         vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */
4871 
4872         rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
4873         vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
4874         rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
4875         vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl);   /* 22.2.3 */
4876 
4877         if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
4878                 rdmsr(MSR_IA32_CR_PAT, low32, high32);
4879                 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
4880         }
4881 }
4882 
4883 static void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
4884 {
4885         vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
4886         if (enable_ept)
4887                 vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
4888         if (is_guest_mode(&vmx->vcpu))
4889                 vmx->vcpu.arch.cr4_guest_owned_bits &=
4890                         ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
4891         vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
4892 }
4893 
4894 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
4895 {
4896         u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
4897 
4898         if (!kvm_vcpu_apicv_active(&vmx->vcpu))
4899                 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
4900         /* Enable the preemption timer dynamically */
4901         pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
4902         return pin_based_exec_ctrl;
4903 }
4904 
4905 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
4906 {
4907         struct vcpu_vmx *vmx = to_vmx(vcpu);
4908 
4909         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
4910         if (cpu_has_secondary_exec_ctrls()) {
4911                 if (kvm_vcpu_apicv_active(vcpu))
4912                         vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
4913                                       SECONDARY_EXEC_APIC_REGISTER_VIRT |
4914                                       SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4915                 else
4916                         vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
4917                                         SECONDARY_EXEC_APIC_REGISTER_VIRT |
4918                                         SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4919         }
4920 
4921         if (cpu_has_vmx_msr_bitmap())
4922                 vmx_set_msr_bitmap(vcpu);
4923 }
4924 
4925 static u32 vmx_exec_control(struct vcpu_vmx *vmx)
4926 {
4927         u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
4928 
4929         if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
4930                 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
4931 
4932         if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
4933                 exec_control &= ~CPU_BASED_TPR_SHADOW;
4934 #ifdef CONFIG_X86_64
4935                 exec_control |= CPU_BASED_CR8_STORE_EXITING |
4936                                 CPU_BASED_CR8_LOAD_EXITING;
4937 #endif
4938         }
4939         if (!enable_ept)
4940                 exec_control |= CPU_BASED_CR3_STORE_EXITING |
4941                                 CPU_BASED_CR3_LOAD_EXITING  |
4942                                 CPU_BASED_INVLPG_EXITING;
4943         return exec_control;
4944 }
4945 
4946 static u32 vmx_secondary_exec_control(struct vcpu_vmx *vmx)
4947 {
4948         u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
4949         if (!cpu_need_virtualize_apic_accesses(&vmx->vcpu))
4950                 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
4951         if (vmx->vpid == 0)
4952                 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
4953         if (!enable_ept) {
4954                 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
4955                 enable_unrestricted_guest = 0;
4956                 /* Enable INVPCID for non-ept guests may cause performance regression. */
4957                 exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
4958         }
4959         if (!enable_unrestricted_guest)
4960                 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
4961         if (!ple_gap)
4962                 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
4963         if (!kvm_vcpu_apicv_active(&vmx->vcpu))
4964                 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
4965                                   SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4966         exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
4967         /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
4968            (handle_vmptrld).
4969            We can NOT enable shadow_vmcs here because we don't have yet
4970            a current VMCS12
4971         */
4972         exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
4973 
4974         if (!enable_pml)
4975                 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
4976 
4977         return exec_control;
4978 }
4979 
4980 static void ept_set_mmio_spte_mask(void)
4981 {
4982         /*
4983          * EPT Misconfigurations can be generated if the value of bits 2:0
4984          * of an EPT paging-structure entry is 110b (write/execute).
4985          * Also, magic bits (0x3ull << 62) is set to quickly identify mmio
4986          * spte.
4987          */
4988         kvm_mmu_set_mmio_spte_mask((0x3ull << 62) | 0x6ull);
4989 }
4990 
4991 #define VMX_XSS_EXIT_BITMAP 0
4992 /*
4993  * Sets up the vmcs for emulated real mode.
4994  */
4995 static int vmx_vcpu_setup(struct vcpu_vmx *vmx)
4996 {
4997 #ifdef CONFIG_X86_64
4998         unsigned long a;
4999 #endif
5000         int i;
5001 
5002         /* I/O */
5003         vmcs_write64(IO_BITMAP_A, __pa(vmx_io_bitmap_a));
5004         vmcs_write64(IO_BITMAP_B, __pa(vmx_io_bitmap_b));
5005 
5006         if (enable_shadow_vmcs) {
5007                 vmcs_write64(VMREAD_BITMAP, __pa(vmx_vmread_bitmap));
5008                 vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmwrite_bitmap));
5009         }
5010         if (cpu_has_vmx_msr_bitmap())
5011                 vmcs_write64(MSR_BITMAP, __pa(vmx_msr_bitmap_legacy));
5012 
5013         vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
5014 
5015         /* Control */
5016         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
5017         vmx->hv_deadline_tsc = -1;
5018 
5019         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
5020 
5021         if (cpu_has_secondary_exec_ctrls()) {
5022                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
5023                                 vmx_secondary_exec_control(vmx));
5024         }
5025 
5026         if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
5027                 vmcs_write64(EOI_EXIT_BITMAP0, 0);
5028                 vmcs_write64(EOI_EXIT_BITMAP1, 0);
5029                 vmcs_write64(EOI_EXIT_BITMAP2, 0);
5030                 vmcs_write64(EOI_EXIT_BITMAP3, 0);
5031 
5032                 vmcs_write16(GUEST_INTR_STATUS, 0);
5033 
5034                 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
5035                 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
5036         }
5037 
5038         if (ple_gap) {
5039                 vmcs_write32(PLE_GAP, ple_gap);
5040                 vmx->ple_window = ple_window;
5041                 vmx->ple_window_dirty = true;
5042         }
5043 
5044         vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
5045         vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
5046         vmcs_write32(CR3_TARGET_COUNT, 0);           /* 22.2.1 */
5047 
5048         vmcs_write16(HOST_FS_SELECTOR, 0);            /* 22.2.4 */
5049         vmcs_write16(HOST_GS_SELECTOR, 0);            /* 22.2.4 */
5050         vmx_set_constant_host_state(vmx);
5051 #ifdef CONFIG_X86_64
5052         rdmsrl(MSR_FS_BASE, a);
5053         vmcs_writel(HOST_FS_BASE, a); /* 22.2.4 */
5054         rdmsrl(MSR_GS_BASE, a);
5055         vmcs_writel(HOST_GS_BASE, a); /* 22.2.4 */
5056 #else
5057         vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
5058         vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
5059 #endif
5060 
5061         vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
5062         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
5063         vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host));
5064         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
5065         vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest));
5066 
5067         if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
5068                 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
5069 
5070         for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
5071                 u32 index = vmx_msr_index[i];
5072                 u32 data_low, data_high;
5073                 int j = vmx->nmsrs;
5074 
5075                 if (rdmsr_safe(index, &data_low, &data_high) < 0)
5076                         continue;
5077                 if (wrmsr_safe(index, data_low, data_high) < 0)
5078                         continue;
5079                 vmx->guest_msrs[j].index = i;
5080                 vmx->guest_msrs[j].data = 0;
5081                 vmx->guest_msrs[j].mask = -1ull;
5082                 ++vmx->nmsrs;
5083         }
5084 
5085 
5086         vm_exit_controls_init(vmx, vmcs_config.vmexit_ctrl);
5087 
5088         /* 22.2.1, 20.8.1 */
5089         vm_entry_controls_init(vmx, vmcs_config.vmentry_ctrl);
5090 
5091         vmcs_writel(CR0_GUEST_HOST_MASK, ~0UL);
5092         set_cr4_guest_host_mask(vmx);
5093 
5094         if (vmx_xsaves_supported())
5095                 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
5096 
5097         if (enable_pml) {
5098                 ASSERT(vmx->pml_pg);
5099                 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
5100                 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
5101         }
5102 
5103         return 0;
5104 }
5105 
5106 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
5107 {
5108         struct vcpu_vmx *vmx = to_vmx(vcpu);
5109         struct msr_data apic_base_msr;
5110         u64 cr0;
5111 
5112         vmx->rmode.vm86_active = 0;
5113 
5114         vmx->soft_vnmi_blocked = 0;
5115 
5116         vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
5117         kvm_set_cr8(vcpu, 0);
5118 
5119         if (!init_event) {
5120                 apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
5121                                      MSR_IA32_APICBASE_ENABLE;
5122                 if (kvm_vcpu_is_reset_bsp(vcpu))
5123                         apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
5124                 apic_base_msr.host_initiated = true;
5125                 kvm_set_apic_base(vcpu, &apic_base_msr);
5126         }
5127 
5128         vmx_segment_cache_clear(vmx);
5129 
5130         seg_setup(VCPU_SREG_CS);
5131         vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
5132         vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
5133 
5134         seg_setup(VCPU_SREG_DS);
5135         seg_setup(VCPU_SREG_ES);
5136         seg_setup(VCPU_SREG_FS);
5137         seg_setup(VCPU_SREG_GS);
5138         seg_setup(VCPU_SREG_SS);
5139 
5140         vmcs_write16(GUEST_TR_SELECTOR, 0);
5141         vmcs_writel(GUEST_TR_BASE, 0);
5142         vmcs_write32(GUEST_TR_LIMIT, 0xffff);
5143         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
5144 
5145         vmcs_write16(GUEST_LDTR_SELECTOR, 0);
5146         vmcs_writel(GUEST_LDTR_BASE, 0);
5147         vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
5148         vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
5149 
5150         if (!init_event) {
5151                 vmcs_write32(GUEST_SYSENTER_CS, 0);
5152                 vmcs_writel(GUEST_SYSENTER_ESP, 0);
5153                 vmcs_writel(GUEST_SYSENTER_EIP, 0);
5154                 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
5155         }
5156 
5157         vmcs_writel(GUEST_RFLAGS, 0x02);
5158         kvm_rip_write(vcpu, 0xfff0);
5159 
5160         vmcs_writel(GUEST_GDTR_BASE, 0);
5161         vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
5162 
5163         vmcs_writel(GUEST_IDTR_BASE, 0);
5164         vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
5165 
5166         vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
5167         vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
5168         vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
5169 
5170         setup_msrs(vmx);
5171 
5172         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);  /* 22.2.1 */
5173 
5174         if (cpu_has_vmx_tpr_shadow() && !init_event) {
5175                 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
5176                 if (cpu_need_tpr_shadow(vcpu))
5177                         vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
5178                                      __pa(vcpu->arch.apic->regs));
5179                 vmcs_write32(TPR_THRESHOLD, 0);
5180         }
5181 
5182         kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
5183 
5184         if (kvm_vcpu_apicv_active(vcpu))
5185                 memset(&vmx->pi_desc, 0, sizeof(struct pi_desc));
5186 
5187         if (vmx->vpid != 0)
5188                 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
5189 
5190         cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
5191         vmx->vcpu.arch.cr0 = cr0;
5192         vmx_set_cr0(vcpu, cr0); /* enter rmode */
5193         vmx_set_cr4(vcpu, 0);
5194         vmx_set_efer(vcpu, 0);
5195         vmx_fpu_activate(vcpu);
5196         update_exception_bitmap(vcpu);
5197 
5198         vpid_sync_context(vmx->vpid);
5199 }
5200 
5201 /*
5202  * In nested virtualization, check if L1 asked to exit on external interrupts.
5203  * For most existing hypervisors, this will always return true.
5204  */
5205 static bool nested_exit_on_intr(struct kvm_vcpu *vcpu)
5206 {
5207         return get_vmcs12(vcpu)->pin_based_vm_exec_control &
5208                 PIN_BASED_EXT_INTR_MASK;
5209 }
5210 
5211 /*
5212  * In nested virtualization, check if L1 has set
5213  * VM_EXIT_ACK_INTR_ON_EXIT
5214  */
5215 static bool nested_exit_intr_ack_set(struct kvm_vcpu *vcpu)
5216 {
5217         return get_vmcs12(vcpu)->vm_exit_controls &
5218                 VM_EXIT_ACK_INTR_ON_EXIT;
5219 }
5220 
5221 static bool nested_exit_on_nmi(struct kvm_vcpu *vcpu)
5222 {
5223         return get_vmcs12(vcpu)->pin_based_vm_exec_control &
5224                 PIN_BASED_NMI_EXITING;
5225 }
5226 
5227 static void enable_irq_window(struct kvm_vcpu *vcpu)
5228 {
5229         u32 cpu_based_vm_exec_control;
5230 
5231         cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5232         cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_INTR_PENDING;
5233         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
5234 }
5235 
5236 static void enable_nmi_window(struct kvm_vcpu *vcpu)
5237 {
5238         u32 cpu_based_vm_exec_control;
5239 
5240         if (!cpu_has_virtual_nmis() ||
5241             vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
5242                 enable_irq_window(vcpu);
5243                 return;
5244         }
5245 
5246         cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5247         cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_NMI_PENDING;
5248         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
5249 }
5250 
5251 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
5252 {
5253         struct vcpu_vmx *vmx = to_vmx(vcpu);
5254         uint32_t intr;
5255         int irq = vcpu->arch.interrupt.nr;
5256 
5257         trace_kvm_inj_virq(irq);
5258 
5259         ++vcpu->stat.irq_injections;
5260         if (vmx->rmode.vm86_active) {
5261                 int inc_eip = 0;
5262                 if (vcpu->arch.interrupt.soft)
5263                         inc_eip = vcpu->arch.event_exit_inst_len;
5264                 if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE)
5265                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5266                 return;
5267         }
5268         intr = irq | INTR_INFO_VALID_MASK;
5269         if (vcpu->arch.interrupt.soft) {
5270                 intr |= INTR_TYPE_SOFT_INTR;
5271                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
5272                              vmx->vcpu.arch.event_exit_inst_len);
5273         } else
5274                 intr |= INTR_TYPE_EXT_INTR;
5275         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
5276 }
5277 
5278 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
5279 {
5280         struct vcpu_vmx *vmx = to_vmx(vcpu);
5281 
5282         if (is_guest_mode(vcpu))
5283                 return;
5284 
5285         if (!cpu_has_virtual_nmis()) {
5286                 /*
5287                  * Tracking the NMI-blocked state in software is built upon
5288                  * finding the next open IRQ window. This, in turn, depends on
5289                  * well-behaving guests: They have to keep IRQs disabled at
5290                  * least as long as the NMI handler runs. Otherwise we may
5291                  * cause NMI nesting, maybe breaking the guest. But as this is
5292                  * highly unlikely, we can live with the residual risk.
5293                  */
5294                 vmx->soft_vnmi_blocked = 1;
5295                 vmx->vnmi_blocked_time = 0;
5296         }
5297 
5298         ++vcpu->stat.nmi_injections;
5299         vmx->nmi_known_unmasked = false;
5300         if (vmx->rmode.vm86_active) {
5301                 if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE)
5302                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5303                 return;
5304         }
5305         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
5306                         INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
5307 }
5308 
5309 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
5310 {
5311         if (!cpu_has_virtual_nmis())
5312                 return to_vmx(vcpu)->soft_vnmi_blocked;
5313         if (to_vmx(vcpu)->nmi_known_unmasked)
5314                 return false;
5315         return vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
5316 }
5317 
5318 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
5319 {
5320         struct vcpu_vmx *vmx = to_vmx(vcpu);
5321 
5322         if (!cpu_has_virtual_nmis()) {
5323                 if (vmx->soft_vnmi_blocked != masked) {
5324                         vmx->soft_vnmi_blocked = masked;
5325                         vmx->vnmi_blocked_time = 0;
5326                 }
5327         } else {
5328                 vmx->nmi_known_unmasked = !masked;
5329                 if (masked)
5330                         vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5331                                       GUEST_INTR_STATE_NMI);
5332                 else
5333                         vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
5334                                         GUEST_INTR_STATE_NMI);
5335         }
5336 }
5337 
5338 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
5339 {
5340         if (to_vmx(vcpu)->nested.nested_run_pending)
5341                 return 0;
5342 
5343         if (!cpu_has_virtual_nmis() && to_vmx(vcpu)->soft_vnmi_blocked)
5344                 return 0;
5345 
5346         return  !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
5347                   (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
5348                    | GUEST_INTR_STATE_NMI));
5349 }
5350 
5351 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
5352 {
5353         return (!to_vmx(vcpu)->nested.nested_run_pending &&
5354                 vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
5355                 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
5356                         (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
5357 }
5358 
5359 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
5360 {
5361         int ret;
5362 
5363         ret = x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
5364                                     PAGE_SIZE * 3);
5365         if (ret)
5366                 return ret;
5367         kvm->arch.tss_addr = addr;
5368         return init_rmode_tss(kvm);
5369 }
5370 
5371 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
5372 {
5373         switch (vec) {
5374         case BP_VECTOR:
5375                 /*
5376                  * Update instruction length as we may reinject the exception
5377                  * from user space while in guest debugging mode.
5378                  */
5379                 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
5380                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
5381                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
5382                         return false;
5383                 /* fall through */
5384         case DB_VECTOR:
5385                 if (vcpu->guest_debug &
5386                         (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
5387                         return false;
5388                 /* fall through */
5389         case DE_VECTOR:
5390         case OF_VECTOR:
5391         case BR_VECTOR:
5392         case UD_VECTOR:
5393         case DF_VECTOR:
5394         case SS_VECTOR:
5395         case GP_VECTOR:
5396         case MF_VECTOR:
5397                 return true;
5398         break;
5399         }
5400         return false;
5401 }
5402 
5403 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
5404                                   int vec, u32 err_code)
5405 {
5406         /*
5407          * Instruction with address size override prefix opcode 0x67
5408          * Cause the #SS fault with 0 error code in VM86 mode.
5409          */
5410         if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
5411                 if (emulate_instruction(vcpu, 0) == EMULATE_DONE) {
5412                         if (vcpu->arch.halt_request) {
5413                                 vcpu->arch.halt_request = 0;
5414                                 return kvm_vcpu_halt(vcpu);
5415                         }
5416                         return 1;
5417                 }
5418                 return 0;
5419         }
5420 
5421         /*
5422          * Forward all other exceptions that are valid in real mode.
5423          * FIXME: Breaks guest debugging in real mode, needs to be fixed with
5424          *        the required debugging infrastructure rework.
5425          */
5426         kvm_queue_exception(vcpu, vec);
5427         return 1;
5428 }
5429 
5430 /*
5431  * Trigger machine check on the host. We assume all the MSRs are already set up
5432  * by the CPU and that we still run on the same CPU as the MCE occurred on.
5433  * We pass a fake environment to the machine check handler because we want
5434  * the guest to be always treated like user space, no matter what context
5435  * it used internally.
5436  */
5437 static void kvm_machine_check(void)
5438 {
5439 #if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
5440         struct pt_regs regs = {
5441                 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
5442                 .flags = X86_EFLAGS_IF,
5443         };
5444 
5445         do_machine_check(&regs, 0);
5446 #endif
5447 }
5448 
5449 static int handle_machine_check(struct kvm_vcpu *vcpu)
5450 {
5451         /* already handled by vcpu_run */
5452         return 1;
5453 }
5454 
5455 static int handle_exception(struct kvm_vcpu *vcpu)
5456 {
5457         struct vcpu_vmx *vmx = to_vmx(vcpu);
5458         struct kvm_run *kvm_run = vcpu->run;
5459         u32 intr_info, ex_no, error_code;
5460         unsigned long cr2, rip, dr6;
5461         u32 vect_info;
5462         enum emulation_result er;
5463 
5464         vect_info = vmx->idt_vectoring_info;
5465         intr_info = vmx->exit_intr_info;
5466 
5467         if (is_machine_check(intr_info))
5468                 return handle_machine_check(vcpu);
5469 
5470         if (is_nmi(intr_info))
5471                 return 1;  /* already handled by vmx_vcpu_run() */
5472 
5473         if (is_no_device(intr_info)) {
5474                 vmx_fpu_activate(vcpu);
5475                 return 1;
5476         }
5477 
5478         if (is_invalid_opcode(intr_info)) {
5479                 if (is_guest_mode(vcpu)) {
5480                         kvm_queue_exception(vcpu, UD_VECTOR);
5481                         return 1;
5482                 }
5483                 er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD);
5484                 if (er != EMULATE_DONE)
5485                         kvm_queue_exception(vcpu, UD_VECTOR);
5486                 return 1;
5487         }
5488 
5489         error_code = 0;
5490         if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
5491                 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
5492 
5493         /*
5494          * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
5495          * MMIO, it is better to report an internal error.
5496          * See the comments in vmx_handle_exit.
5497          */
5498         if ((vect_info & VECTORING_INFO_VALID_MASK) &&
5499             !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
5500                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5501                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
5502                 vcpu->run->internal.ndata = 3;
5503                 vcpu->run->internal.data[0] = vect_info;
5504                 vcpu->run->internal.data[1] = intr_info;
5505                 vcpu->run->internal.data[2] = error_code;
5506                 return 0;
5507         }
5508 
5509         if (is_page_fault(intr_info)) {
5510                 /* EPT won't cause page fault directly */
5511                 BUG_ON(enable_ept);
5512                 cr2 = vmcs_readl(EXIT_QUALIFICATION);
5513                 trace_kvm_page_fault(cr2, error_code);
5514 
5515                 if (kvm_event_needs_reinjection(vcpu))
5516                         kvm_mmu_unprotect_page_virt(vcpu, cr2);
5517                 return kvm_mmu_page_fault(vcpu, cr2, error_code, NULL, 0);
5518         }
5519 
5520         ex_no = intr_info & INTR_INFO_VECTOR_MASK;
5521 
5522         if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
5523                 return handle_rmode_exception(vcpu, ex_no, error_code);
5524 
5525         switch (ex_no) {
5526         case AC_VECTOR:
5527                 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
5528                 return 1;
5529         case DB_VECTOR:
5530                 dr6 = vmcs_readl(EXIT_QUALIFICATION);
5531                 if (!(vcpu->guest_debug &
5532                       (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
5533                         vcpu->arch.dr6 &= ~15;
5534                         vcpu->arch.dr6 |= dr6 | DR6_RTM;
5535                         if (!(dr6 & ~DR6_RESERVED)) /* icebp */
5536                                 skip_emulated_instruction(vcpu);
5537 
5538                         kvm_queue_exception(vcpu, DB_VECTOR);
5539                         return 1;
5540                 }
5541                 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
5542                 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
5543                 /* fall through */
5544         case BP_VECTOR:
5545                 /*
5546                  * Update instruction length as we may reinject #BP from
5547                  * user space while in guest debugging mode. Reading it for
5548                  * #DB as well causes no harm, it is not used in that case.
5549                  */
5550                 vmx->vcpu.arch.event_exit_inst_len =
5551                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
5552                 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5553                 rip = kvm_rip_read(vcpu);
5554                 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
5555                 kvm_run->debug.arch.exception = ex_no;
5556                 break;
5557         default:
5558                 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
5559                 kvm_run->ex.exception = ex_no;
5560                 kvm_run->ex.error_code = error_code;
5561                 break;
5562         }
5563         return 0;
5564 }
5565 
5566 static int handle_external_interrupt(struct kvm_vcpu *vcpu)
5567 {
5568         ++vcpu->stat.irq_exits;
5569         return 1;
5570 }
5571 
5572 static int handle_triple_fault(struct kvm_vcpu *vcpu)
5573 {
5574         vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
5575         return 0;
5576 }
5577 
5578 static int handle_io(struct kvm_vcpu *vcpu)
5579 {
5580         unsigned long exit_qualification;
5581         int size, in, string;
5582         unsigned port;
5583 
5584         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5585         string = (exit_qualification & 16) != 0;
5586         in = (exit_qualification & 8) != 0;
5587 
5588         ++vcpu->stat.io_exits;
5589 
5590         if (string || in)
5591                 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
5592 
5593         port = exit_qualification >> 16;
5594         size = (exit_qualification & 7) + 1;
5595         skip_emulated_instruction(vcpu);
5596 
5597         return kvm_fast_pio_out(vcpu, size, port);
5598 }
5599 
5600 static void
5601 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
5602 {
5603         /*
5604          * Patch in the VMCALL instruction:
5605          */
5606         hypercall[0] = 0x0f;
5607         hypercall[1] = 0x01;
5608         hypercall[2] = 0xc1;
5609 }
5610 
5611 static bool nested_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
5612 {
5613         unsigned long always_on = VMXON_CR0_ALWAYSON;
5614         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5615 
5616         if (to_vmx(vcpu)->nested.nested_vmx_secondary_ctls_high &
5617                 SECONDARY_EXEC_UNRESTRICTED_GUEST &&
5618             nested_cpu_has2(vmcs12, SECONDARY_EXEC_UNRESTRICTED_GUEST))
5619                 always_on &= ~(X86_CR0_PE | X86_CR0_PG);
5620         return (val & always_on) == always_on;
5621 }
5622 
5623 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
5624 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
5625 {
5626         if (is_guest_mode(vcpu)) {
5627                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5628                 unsigned long orig_val = val;
5629 
5630                 /*
5631                  * We get here when L2 changed cr0 in a way that did not change
5632                  * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
5633                  * but did change L0 shadowed bits. So we first calculate the
5634                  * effective cr0 value that L1 would like to write into the
5635                  * hardware. It consists of the L2-owned bits from the new
5636                  * value combined with the L1-owned bits from L1's guest_cr0.
5637                  */
5638                 val = (val & ~vmcs12->cr0_guest_host_mask) |
5639                         (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
5640 
5641                 if (!nested_cr0_valid(vcpu, val))
5642                         return 1;
5643 
5644                 if (kvm_set_cr0(vcpu, val))
5645                         return 1;
5646                 vmcs_writel(CR0_READ_SHADOW, orig_val);
5647                 return 0;
5648         } else {
5649                 if (to_vmx(vcpu)->nested.vmxon &&
5650                     ((val & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON))
5651                         return 1;
5652                 return kvm_set_cr0(vcpu, val);
5653         }
5654 }
5655 
5656 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
5657 {
5658         if (is_guest_mode(vcpu)) {
5659                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5660                 unsigned long orig_val = val;
5661 
5662                 /* analogously to handle_set_cr0 */
5663                 val = (val & ~vmcs12->cr4_guest_host_mask) |
5664                         (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
5665                 if (kvm_set_cr4(vcpu, val))
5666                         return 1;
5667                 vmcs_writel(CR4_READ_SHADOW, orig_val);
5668                 return 0;
5669         } else
5670                 return kvm_set_cr4(vcpu, val);
5671 }
5672 
5673 /* called to set cr0 as appropriate for clts instruction exit. */
5674 static void handle_clts(struct kvm_vcpu *vcpu)
5675 {
5676         if (is_guest_mode(vcpu)) {
5677                 /*
5678                  * We get here when L2 did CLTS, and L1 didn't shadow CR0.TS
5679                  * but we did (!fpu_active). We need to keep GUEST_CR0.TS on,
5680                  * just pretend it's off (also in arch.cr0 for fpu_activate).
5681                  */
5682                 vmcs_writel(CR0_READ_SHADOW,
5683                         vmcs_readl(CR0_READ_SHADOW) & ~X86_CR0_TS);
5684                 vcpu->arch.cr0 &= ~X86_CR0_TS;
5685         } else
5686                 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
5687 }
5688 
5689 static int handle_cr(struct kvm_vcpu *vcpu)
5690 {
5691         unsigned long exit_qualification, val;
5692         int cr;
5693         int reg;
5694         int err;
5695 
5696         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5697         cr = exit_qualification & 15;
5698         reg = (exit_qualification >> 8) & 15;
5699         switch ((exit_qualification >> 4) & 3) {
5700         case 0: /* mov to cr */
5701                 val = kvm_register_readl(vcpu, reg);
5702                 trace_kvm_cr_write(cr, val);
5703                 switch (cr) {
5704                 case 0:
5705                         err = handle_set_cr0(vcpu, val);
5706                         kvm_complete_insn_gp(vcpu, err);
5707                         return 1;
5708                 case 3:
5709                         err = kvm_set_cr3(vcpu, val);
5710                         kvm_complete_insn_gp(vcpu, err);
5711                         return 1;
5712                 case 4:
5713                         err = handle_set_cr4(vcpu, val);
5714                         kvm_complete_insn_gp(vcpu, err);
5715                         return 1;
5716                 case 8: {
5717                                 u8 cr8_prev = kvm_get_cr8(vcpu);
5718                                 u8 cr8 = (u8)val;
5719                                 err = kvm_set_cr8(vcpu, cr8);
5720                                 kvm_complete_insn_gp(vcpu, err);
5721                                 if (lapic_in_kernel(vcpu))
5722                                         return 1;
5723                                 if (cr8_prev <= cr8)
5724                                         return 1;
5725                                 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
5726                                 return 0;
5727                         }
5728                 }
5729                 break;
5730         case 2: /* clts */
5731                 handle_clts(vcpu);
5732                 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
5733                 skip_emulated_instruction(vcpu);
5734                 vmx_fpu_activate(vcpu);
5735                 return 1;
5736         case 1: /*mov from cr*/
5737                 switch (cr) {
5738                 case 3:
5739                         val = kvm_read_cr3(vcpu);
5740                         kvm_register_write(vcpu, reg, val);
5741                         trace_kvm_cr_read(cr, val);
5742                         skip_emulated_instruction(vcpu);
5743                         return 1;
5744                 case 8:
5745                         val = kvm_get_cr8(vcpu);
5746                         kvm_register_write(vcpu, reg, val);
5747                         trace_kvm_cr_read(cr, val);
5748                         skip_emulated_instruction(vcpu);
5749                         return 1;
5750                 }
5751                 break;
5752         case 3: /* lmsw */
5753                 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
5754                 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
5755                 kvm_lmsw(vcpu, val);
5756 
5757                 skip_emulated_instruction(vcpu);
5758                 return 1;
5759         default:
5760                 break;
5761         }
5762         vcpu->run->exit_reason = 0;
5763         vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
5764                (int)(exit_qualification >> 4) & 3, cr);
5765         return 0;
5766 }
5767 
5768 static int handle_dr(struct kvm_vcpu *vcpu)
5769 {
5770         unsigned long exit_qualification;
5771         int dr, dr7, reg;
5772 
5773         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5774         dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
5775 
5776         /* First, if DR does not exist, trigger UD */
5777         if (!kvm_require_dr(vcpu, dr))
5778                 return 1;
5779 
5780         /* Do not handle if the CPL > 0, will trigger GP on re-entry */
5781         if (!kvm_require_cpl(vcpu, 0))
5782                 return 1;
5783         dr7 = vmcs_readl(GUEST_DR7);
5784         if (dr7 & DR7_GD) {
5785                 /*
5786                  * As the vm-exit takes precedence over the debug trap, we
5787                  * need to emulate the latter, either for the host or the
5788                  * guest debugging itself.
5789                  */
5790                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
5791                         vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
5792                         vcpu->run->debug.arch.dr7 = dr7;
5793                         vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
5794                         vcpu->run->debug.arch.exception = DB_VECTOR;
5795                         vcpu->run->exit_reason = KVM_EXIT_DEBUG;
5796                         return 0;
5797                 } else {
5798                         vcpu->arch.dr6 &= ~15;
5799                         vcpu->arch.dr6 |= DR6_BD | DR6_RTM;
5800                         kvm_queue_exception(vcpu, DB_VECTOR);
5801                         return 1;
5802                 }
5803         }
5804 
5805         if (vcpu->guest_debug == 0) {
5806                 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
5807                                 CPU_BASED_MOV_DR_EXITING);
5808 
5809                 /*
5810                  * No more DR vmexits; force a reload of the debug registers
5811                  * and reenter on this instruction.  The next vmexit will
5812                  * retrieve the full state of the debug registers.
5813                  */
5814                 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
5815                 return 1;
5816         }
5817 
5818         reg = DEBUG_REG_ACCESS_REG(exit_qualification);
5819         if (exit_qualification & TYPE_MOV_FROM_DR) {
5820                 unsigned long val;
5821 
5822                 if (kvm_get_dr(vcpu, dr, &val))
5823                         return 1;
5824                 kvm_register_write(vcpu, reg, val);
5825         } else
5826                 if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
5827                         return 1;
5828 
5829         skip_emulated_instruction(vcpu);
5830         return 1;
5831 }
5832 
5833 static u64 vmx_get_dr6(struct kvm_vcpu *vcpu)
5834 {
5835         return vcpu->arch.dr6;
5836 }
5837 
5838 static void vmx_set_dr6(struct kvm_vcpu *vcpu, unsigned long val)
5839 {
5840 }
5841 
5842 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
5843 {
5844         get_debugreg(vcpu->arch.db[0], 0);
5845         get_debugreg(vcpu->arch.db[1], 1);
5846         get_debugreg(vcpu->arch.db[2], 2);
5847         get_debugreg(vcpu->arch.db[3], 3);
5848         get_debugreg(vcpu->arch.dr6, 6);
5849         vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
5850 
5851         vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
5852         vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL, CPU_BASED_MOV_DR_EXITING);
5853 }
5854 
5855 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
5856 {
5857         vmcs_writel(GUEST_DR7, val);
5858 }
5859 
5860 static int handle_cpuid(struct kvm_vcpu *vcpu)
5861 {
5862         kvm_emulate_cpuid(vcpu);
5863         return 1;
5864 }
5865 
5866 static int handle_rdmsr(struct kvm_vcpu *vcpu)
5867 {
5868         u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
5869         struct msr_data msr_info;
5870 
5871         msr_info.index = ecx;
5872         msr_info.host_initiated = false;
5873         if (vmx_get_msr(vcpu, &msr_info)) {
5874                 trace_kvm_msr_read_ex(ecx);
5875                 kvm_inject_gp(vcpu, 0);
5876                 return 1;
5877         }
5878 
5879         trace_kvm_msr_read(ecx, msr_info.data);
5880 
5881         /* FIXME: handling of bits 32:63 of rax, rdx */
5882         vcpu->arch.regs[VCPU_REGS_RAX] = msr_info.data & -1u;
5883         vcpu->arch.regs[VCPU_REGS_RDX] = (msr_info.data >> 32) & -1u;
5884         skip_emulated_instruction(vcpu);
5885         return 1;
5886 }
5887 
5888 static int handle_wrmsr(struct kvm_vcpu *vcpu)
5889 {
5890         struct msr_data msr;
5891         u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
5892         u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
5893                 | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
5894 
5895         msr.data = data;
5896         msr.index = ecx;
5897         msr.host_initiated = false;
5898         if (kvm_set_msr(vcpu, &msr) != 0) {
5899                 trace_kvm_msr_write_ex(ecx, data);
5900                 kvm_inject_gp(vcpu, 0);
5901                 return 1;
5902         }
5903 
5904         trace_kvm_msr_write(ecx, data);
5905         skip_emulated_instruction(vcpu);
5906         return 1;
5907 }
5908 
5909 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
5910 {
5911         kvm_make_request(KVM_REQ_EVENT, vcpu);
5912         return 1;
5913 }
5914 
5915 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
5916 {
5917         u32 cpu_based_vm_exec_control;
5918 
5919         /* clear pending irq */
5920         cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5921         cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
5922         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
5923 
5924         kvm_make_request(KVM_REQ_EVENT, vcpu);