Blame view

arch/x86/kvm/x86.c 156 KB
043405e10   Carsten Otte   KVM: Move x86 msr...
1
2
3
4
5
6
  /*
   * Kernel-based Virtual Machine driver for Linux
   *
   * derived from drivers/kvm/kvm_main.c
   *
   * Copyright (C) 2006 Qumranet, Inc.
4d5c5d0fe   Ben-Ami Yassour   KVM: pci device a...
7
8
   * Copyright (C) 2008 Qumranet, Inc.
   * Copyright IBM Corporation, 2008
9611c1877   Nicolas Kaiser   KVM: fix typo in ...
9
   * Copyright 2010 Red Hat, Inc. and/or its affiliates.
043405e10   Carsten Otte   KVM: Move x86 msr...
10
11
12
13
   *
   * Authors:
   *   Avi Kivity   <avi@qumranet.com>
   *   Yaniv Kamay  <yaniv@qumranet.com>
4d5c5d0fe   Ben-Ami Yassour   KVM: pci device a...
14
15
   *   Amit Shah    <amit.shah@qumranet.com>
   *   Ben-Ami Yassour <benami@il.ibm.com>
043405e10   Carsten Otte   KVM: Move x86 msr...
16
17
18
19
20
   *
   * This work is licensed under the terms of the GNU GPL, version 2.  See
   * the COPYING file in the top-level directory.
   *
   */
edf884172   Avi Kivity   KVM: Move arch de...
21
  #include <linux/kvm_host.h>
313a3dc75   Carsten Otte   KVM: Portability:...
22
  #include "irq.h"
1d737c8a6   Zhang Xiantao   KVM: Portability:...
23
  #include "mmu.h"
7837699fa   Sheng Yang   KVM: In kernel PI...
24
  #include "i8254.h"
37817f298   Izik Eidus   KVM: x86: hardwar...
25
  #include "tss.h"
5fdbf9765   Marcelo Tosatti   KVM: x86: accesso...
26
  #include "kvm_cache_regs.h"
26eef70c3   Avi Kivity   KVM: Clear except...
27
  #include "x86.h"
00b27a3ef   Avi Kivity   KVM: Move cpuid c...
28
  #include "cpuid.h"
313a3dc75   Carsten Otte   KVM: Portability:...
29

18068523d   Glauber de Oliveira Costa   KVM: paravirtuali...
30
  #include <linux/clocksource.h>
4d5c5d0fe   Ben-Ami Yassour   KVM: pci device a...
31
  #include <linux/interrupt.h>
313a3dc75   Carsten Otte   KVM: Portability:...
32
33
34
  #include <linux/kvm.h>
  #include <linux/fs.h>
  #include <linux/vmalloc.h>
5fb76f9be   Carsten Otte   KVM: Portability:...
35
  #include <linux/module.h>
0de10343b   Zhang Xiantao   KVM: Portability:...
36
  #include <linux/mman.h>
2bacc55c7   Marcelo Tosatti   KVM: MMU: emulate...
37
  #include <linux/highmem.h>
19de40a84   Joerg Roedel   KVM: change KVM t...
38
  #include <linux/iommu.h>
62c476c7c   Ben-Ami Yassour   KVM: Device Assig...
39
  #include <linux/intel-iommu.h>
c80766040   Gerd Hoffmann   KVM: Fix kvmclock...
40
  #include <linux/cpufreq.h>
18863bdd6   Avi Kivity   KVM: x86 shared m...
41
  #include <linux/user-return-notifier.h>
a983fb238   Marcelo Tosatti   KVM: x86: switch ...
42
  #include <linux/srcu.h>
5a0e3ad6a   Tejun Heo   include cleanup: ...
43
  #include <linux/slab.h>
ff9d07a0e   Zhang, Yanmin   KVM: Implement pe...
44
  #include <linux/perf_event.h>
7bee342a9   Lai Jiangshan   KVM: x86: use lin...
45
  #include <linux/uaccess.h>
af585b921   Gleb Natapov   KVM: Halt vcpu if...
46
  #include <linux/hash.h>
a1b60c1cd   Joerg Roedel   iommu/core: Conve...
47
  #include <linux/pci.h>
aec51dc4f   Avi Kivity   KVM: Trace mmio
48
  #include <trace/events/kvm.h>
2ed152afc   Xiao Guangrong   KVM: cleanup kvm ...
49

229456fc3   Marcelo Tosatti   KVM: convert cust...
50
51
  #define CREATE_TRACE_POINTS
  #include "trace.h"
043405e10   Carsten Otte   KVM: Move x86 msr...
52

24f1e32c6   Frederic Weisbecker   hw-breakpoints: R...
53
  #include <asm/debugreg.h>
d825ed0a9   Zhang Xiantao   KVM: Portability:...
54
  #include <asm/msr.h>
a5f61300c   Avi Kivity   KVM: Use x86's se...
55
  #include <asm/desc.h>
0bed3b568   Sheng Yang   KVM: Improve MTRR...
56
  #include <asm/mtrr.h>
890ca9aef   Huang Ying   KVM: Add MCE support
57
  #include <asm/mce.h>
7cf30855e   Sheng Yang   KVM: x86: Use unl...
58
  #include <asm/i387.h>
98918833a   Sheng Yang   KVM: x86: Use FPU...
59
  #include <asm/xcr.h>
1d5f066e0   Zachary Amsden   KVM: x86: Fix a p...
60
  #include <asm/pvclock.h>
217fc9cfc   Avi Kivity   KVM: Fix build er...
61
  #include <asm/div64.h>
043405e10   Carsten Otte   KVM: Move x86 msr...
62

313a3dc75   Carsten Otte   KVM: Portability:...
63
  #define MAX_IO_MSRS 256
890ca9aef   Huang Ying   KVM: Add MCE support
64
  #define KVM_MAX_MCE_BANKS 32
5854dbca9   Huang Ying   KVM: MCE: Add MCG...
65
  #define KVM_MCE_CAP_SUPPORTED (MCG_CTL_P | MCG_SER_P)
890ca9aef   Huang Ying   KVM: Add MCE support
66

0f65dd70a   Avi Kivity   KVM: x86 emulator...
67
68
  #define emul_to_vcpu(ctxt) \
  	container_of(ctxt, struct kvm_vcpu, arch.emulate_ctxt)
50a37eb4e   Joerg Roedel   KVM: align valid ...
69
70
71
72
73
  /* EFER defaults:
   * - enable syscall per default because its emulated by KVM
   * - enable LME and LMA per default on 64 bit KVM
   */
  #ifdef CONFIG_X86_64
1260edbe7   Lai Jiangshan   KVM: better reada...
74
75
  static
  u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
50a37eb4e   Joerg Roedel   KVM: align valid ...
76
  #else
1260edbe7   Lai Jiangshan   KVM: better reada...
77
  static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
50a37eb4e   Joerg Roedel   KVM: align valid ...
78
  #endif
313a3dc75   Carsten Otte   KVM: Portability:...
79

ba1389b7a   Avi Kivity   KVM: Extend stats...
80
81
  #define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
  #define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
417bc3041   Hollis Blanchard   KVM: Portability:...
82

cb142eb74   Gleb Natapov   KVM: Update cr8 i...
83
  static void update_cr8_intercept(struct kvm_vcpu *vcpu);
7460fb4a3   Avi Kivity   KVM: Fix simultan...
84
  static void process_nmi(struct kvm_vcpu *vcpu);
674eea0fc   Avi Kivity   KVM: Make the sup...
85

97896d04a   Zhang Xiantao   KVM: Portability:...
86
  struct kvm_x86_ops *kvm_x86_ops;
5fdbf9765   Marcelo Tosatti   KVM: x86: accesso...
87
  EXPORT_SYMBOL_GPL(kvm_x86_ops);
97896d04a   Zhang Xiantao   KVM: Portability:...
88

476bc0015   Rusty Russell   module_param: mak...
89
90
  static bool ignore_msrs = 0;
  module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
ed85c0685   Andre Przywara   KVM: introduce mo...
91

92a1f12d2   Joerg Roedel   KVM: X86: Impleme...
92
93
94
95
  bool kvm_has_tsc_control;
  EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
  u32  kvm_max_guest_tsc_khz;
  EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
18863bdd6   Avi Kivity   KVM: x86 shared m...
96
97
98
99
  #define KVM_NR_SHARED_MSRS 16
  
  struct kvm_shared_msrs_global {
  	int nr;
2bf78fa7b   Sheng Yang   KVM: Extended sha...
100
  	u32 msrs[KVM_NR_SHARED_MSRS];
18863bdd6   Avi Kivity   KVM: x86 shared m...
101
102
103
104
105
  };
  
  struct kvm_shared_msrs {
  	struct user_return_notifier urn;
  	bool registered;
2bf78fa7b   Sheng Yang   KVM: Extended sha...
106
107
108
109
  	struct kvm_shared_msr_values {
  		u64 host;
  		u64 curr;
  	} values[KVM_NR_SHARED_MSRS];
18863bdd6   Avi Kivity   KVM: x86 shared m...
110
111
112
113
  };
  
  static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
  static DEFINE_PER_CPU(struct kvm_shared_msrs, shared_msrs);
417bc3041   Hollis Blanchard   KVM: Portability:...
114
  struct kvm_stats_debugfs_item debugfs_entries[] = {
ba1389b7a   Avi Kivity   KVM: Extend stats...
115
116
117
118
119
120
121
122
123
  	{ "pf_fixed", VCPU_STAT(pf_fixed) },
  	{ "pf_guest", VCPU_STAT(pf_guest) },
  	{ "tlb_flush", VCPU_STAT(tlb_flush) },
  	{ "invlpg", VCPU_STAT(invlpg) },
  	{ "exits", VCPU_STAT(exits) },
  	{ "io_exits", VCPU_STAT(io_exits) },
  	{ "mmio_exits", VCPU_STAT(mmio_exits) },
  	{ "signal_exits", VCPU_STAT(signal_exits) },
  	{ "irq_window", VCPU_STAT(irq_window_exits) },
f08864b42   Sheng Yang   KVM: VMX: Enable ...
124
  	{ "nmi_window", VCPU_STAT(nmi_window_exits) },
ba1389b7a   Avi Kivity   KVM: Extend stats...
125
126
  	{ "halt_exits", VCPU_STAT(halt_exits) },
  	{ "halt_wakeup", VCPU_STAT(halt_wakeup) },
f11c3a8d8   Amit Shah   KVM: Add stat cou...
127
  	{ "hypercalls", VCPU_STAT(hypercalls) },
ba1389b7a   Avi Kivity   KVM: Extend stats...
128
129
130
131
132
133
134
  	{ "request_irq", VCPU_STAT(request_irq_exits) },
  	{ "irq_exits", VCPU_STAT(irq_exits) },
  	{ "host_state_reload", VCPU_STAT(host_state_reload) },
  	{ "efer_reload", VCPU_STAT(efer_reload) },
  	{ "fpu_reload", VCPU_STAT(fpu_reload) },
  	{ "insn_emulation", VCPU_STAT(insn_emulation) },
  	{ "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
fa89a8176   Avi Kivity   KVM: Add statisti...
135
  	{ "irq_injections", VCPU_STAT(irq_injections) },
c4abb7c9c   Jan Kiszka   KVM: x86: Support...
136
  	{ "nmi_injections", VCPU_STAT(nmi_injections) },
4cee57649   Avi Kivity   KVM: MMU: Add som...
137
138
139
140
141
142
  	{ "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
  	{ "mmu_pte_write", VM_STAT(mmu_pte_write) },
  	{ "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
  	{ "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
  	{ "mmu_flooded", VM_STAT(mmu_flooded) },
  	{ "mmu_recycled", VM_STAT(mmu_recycled) },
dfc5aa00c   Avi Kivity   KVM: MMU: Add cac...
143
  	{ "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
4731d4c7a   Marcelo Tosatti   KVM: MMU: out of ...
144
  	{ "mmu_unsync", VM_STAT(mmu_unsync) },
0f74a24c5   Avi Kivity   KVM: Add statisti...
145
  	{ "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
05da45583   Marcelo Tosatti   KVM: MMU: large p...
146
  	{ "largepages", VM_STAT(lpages) },
417bc3041   Hollis Blanchard   KVM: Portability:...
147
148
  	{ NULL }
  };
2acf923e3   Dexuan Cui   KVM: VMX: Enable ...
149
  u64 __read_mostly host_xcr0;
d6aa10003   Avi Kivity   KVM: x86 emulator...
150
  int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
af585b921   Gleb Natapov   KVM: Halt vcpu if...
151
152
153
154
155
156
  static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
  {
  	int i;
  	for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
  		vcpu->arch.apf.gfns[i] = ~0;
  }
18863bdd6   Avi Kivity   KVM: x86 shared m...
157
158
159
  static void kvm_on_user_return(struct user_return_notifier *urn)
  {
  	unsigned slot;
18863bdd6   Avi Kivity   KVM: x86 shared m...
160
161
  	struct kvm_shared_msrs *locals
  		= container_of(urn, struct kvm_shared_msrs, urn);
2bf78fa7b   Sheng Yang   KVM: Extended sha...
162
  	struct kvm_shared_msr_values *values;
18863bdd6   Avi Kivity   KVM: x86 shared m...
163
164
  
  	for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
2bf78fa7b   Sheng Yang   KVM: Extended sha...
165
166
167
168
  		values = &locals->values[slot];
  		if (values->host != values->curr) {
  			wrmsrl(shared_msrs_global.msrs[slot], values->host);
  			values->curr = values->host;
18863bdd6   Avi Kivity   KVM: x86 shared m...
169
170
171
172
173
  		}
  	}
  	locals->registered = false;
  	user_return_notifier_unregister(urn);
  }
2bf78fa7b   Sheng Yang   KVM: Extended sha...
174
  static void shared_msr_update(unsigned slot, u32 msr)
18863bdd6   Avi Kivity   KVM: x86 shared m...
175
  {
2bf78fa7b   Sheng Yang   KVM: Extended sha...
176
  	struct kvm_shared_msrs *smsr;
18863bdd6   Avi Kivity   KVM: x86 shared m...
177
  	u64 value;
2bf78fa7b   Sheng Yang   KVM: Extended sha...
178
179
180
181
182
183
184
185
186
187
188
189
190
191
  	smsr = &__get_cpu_var(shared_msrs);
  	/* only read, and nobody should modify it at this time,
  	 * so don't need lock */
  	if (slot >= shared_msrs_global.nr) {
  		printk(KERN_ERR "kvm: invalid MSR slot!");
  		return;
  	}
  	rdmsrl_safe(msr, &value);
  	smsr->values[slot].host = value;
  	smsr->values[slot].curr = value;
  }
  
  void kvm_define_shared_msr(unsigned slot, u32 msr)
  {
18863bdd6   Avi Kivity   KVM: x86 shared m...
192
193
  	if (slot >= shared_msrs_global.nr)
  		shared_msrs_global.nr = slot + 1;
2bf78fa7b   Sheng Yang   KVM: Extended sha...
194
195
196
  	shared_msrs_global.msrs[slot] = msr;
  	/* we need ensured the shared_msr_global have been updated */
  	smp_wmb();
18863bdd6   Avi Kivity   KVM: x86 shared m...
197
198
199
200
201
202
  }
  EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
  
  static void kvm_shared_msr_cpu_online(void)
  {
  	unsigned i;
18863bdd6   Avi Kivity   KVM: x86 shared m...
203
204
  
  	for (i = 0; i < shared_msrs_global.nr; ++i)
2bf78fa7b   Sheng Yang   KVM: Extended sha...
205
  		shared_msr_update(i, shared_msrs_global.msrs[i]);
18863bdd6   Avi Kivity   KVM: x86 shared m...
206
  }
d5696725b   Avi Kivity   KVM: VMX: Fix com...
207
  void kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
18863bdd6   Avi Kivity   KVM: x86 shared m...
208
209
  {
  	struct kvm_shared_msrs *smsr = &__get_cpu_var(shared_msrs);
2bf78fa7b   Sheng Yang   KVM: Extended sha...
210
  	if (((value ^ smsr->values[slot].curr) & mask) == 0)
18863bdd6   Avi Kivity   KVM: x86 shared m...
211
  		return;
2bf78fa7b   Sheng Yang   KVM: Extended sha...
212
213
  	smsr->values[slot].curr = value;
  	wrmsrl(shared_msrs_global.msrs[slot], value);
18863bdd6   Avi Kivity   KVM: x86 shared m...
214
215
216
217
218
219
220
  	if (!smsr->registered) {
  		smsr->urn.on_user_return = kvm_on_user_return;
  		user_return_notifier_register(&smsr->urn);
  		smsr->registered = true;
  	}
  }
  EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
3548bab50   Avi Kivity   KVM: Drop user re...
221
222
223
224
225
226
227
  static void drop_user_return_notifiers(void *ignore)
  {
  	struct kvm_shared_msrs *smsr = &__get_cpu_var(shared_msrs);
  
  	if (smsr->registered)
  		kvm_on_user_return(&smsr->urn);
  }
6866b83ed   Carsten Otte   KVM: Portability:...
228
229
230
  u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
  {
  	if (irqchip_in_kernel(vcpu->kvm))
ad312c7c7   Zhang Xiantao   KVM: Portability:...
231
  		return vcpu->arch.apic_base;
6866b83ed   Carsten Otte   KVM: Portability:...
232
  	else
ad312c7c7   Zhang Xiantao   KVM: Portability:...
233
  		return vcpu->arch.apic_base;
6866b83ed   Carsten Otte   KVM: Portability:...
234
235
236
237
238
239
240
241
242
  }
  EXPORT_SYMBOL_GPL(kvm_get_apic_base);
  
  void kvm_set_apic_base(struct kvm_vcpu *vcpu, u64 data)
  {
  	/* TODO: reserve bits check */
  	if (irqchip_in_kernel(vcpu->kvm))
  		kvm_lapic_set_base(vcpu, data);
  	else
ad312c7c7   Zhang Xiantao   KVM: Portability:...
243
  		vcpu->arch.apic_base = data;
6866b83ed   Carsten Otte   KVM: Portability:...
244
245
  }
  EXPORT_SYMBOL_GPL(kvm_set_apic_base);
3fd28fce7   Eddie Dong   KVM: x86: make do...
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
  #define EXCPT_BENIGN		0
  #define EXCPT_CONTRIBUTORY	1
  #define EXCPT_PF		2
  
  static int exception_class(int vector)
  {
  	switch (vector) {
  	case PF_VECTOR:
  		return EXCPT_PF;
  	case DE_VECTOR:
  	case TS_VECTOR:
  	case NP_VECTOR:
  	case SS_VECTOR:
  	case GP_VECTOR:
  		return EXCPT_CONTRIBUTORY;
  	default:
  		break;
  	}
  	return EXCPT_BENIGN;
  }
  
  static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
ce7ddec4b   Joerg Roedel   KVM: x86: Allow m...
268
269
  		unsigned nr, bool has_error, u32 error_code,
  		bool reinject)
3fd28fce7   Eddie Dong   KVM: x86: make do...
270
271
272
  {
  	u32 prev_nr;
  	int class1, class2;
3842d135f   Avi Kivity   KVM: Check for pe...
273
  	kvm_make_request(KVM_REQ_EVENT, vcpu);
3fd28fce7   Eddie Dong   KVM: x86: make do...
274
275
276
277
278
279
  	if (!vcpu->arch.exception.pending) {
  	queue:
  		vcpu->arch.exception.pending = true;
  		vcpu->arch.exception.has_error_code = has_error;
  		vcpu->arch.exception.nr = nr;
  		vcpu->arch.exception.error_code = error_code;
3f0fd2927   Joerg Roedel   KVM: x86: Fix exc...
280
  		vcpu->arch.exception.reinject = reinject;
3fd28fce7   Eddie Dong   KVM: x86: make do...
281
282
283
284
285
286
287
  		return;
  	}
  
  	/* to check exception */
  	prev_nr = vcpu->arch.exception.nr;
  	if (prev_nr == DF_VECTOR) {
  		/* triple fault -> shutdown */
a8eeb04a4   Avi Kivity   KVM: Add mini-API...
288
  		kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3fd28fce7   Eddie Dong   KVM: x86: make do...
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
  		return;
  	}
  	class1 = exception_class(prev_nr);
  	class2 = exception_class(nr);
  	if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
  		|| (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
  		/* generate double fault per SDM Table 5-5 */
  		vcpu->arch.exception.pending = true;
  		vcpu->arch.exception.has_error_code = true;
  		vcpu->arch.exception.nr = DF_VECTOR;
  		vcpu->arch.exception.error_code = 0;
  	} else
  		/* replace previous exception with a new one in a hope
  		   that instruction re-execution will regenerate lost
  		   exception */
  		goto queue;
  }
298101da2   Avi Kivity   KVM: Generalize e...
306
307
  void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
  {
ce7ddec4b   Joerg Roedel   KVM: x86: Allow m...
308
  	kvm_multiple_exception(vcpu, nr, false, 0, false);
298101da2   Avi Kivity   KVM: Generalize e...
309
310
  }
  EXPORT_SYMBOL_GPL(kvm_queue_exception);
ce7ddec4b   Joerg Roedel   KVM: x86: Allow m...
311
312
313
314
315
  void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
  {
  	kvm_multiple_exception(vcpu, nr, false, 0, true);
  }
  EXPORT_SYMBOL_GPL(kvm_requeue_exception);
db8fcefaa   Andre Przywara   KVM: move complet...
316
  void kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
c3c91fee5   Avi Kivity   KVM: Replace page...
317
  {
db8fcefaa   Andre Przywara   KVM: move complet...
318
319
320
321
322
323
  	if (err)
  		kvm_inject_gp(vcpu, 0);
  	else
  		kvm_x86_ops->skip_emulated_instruction(vcpu);
  }
  EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
8df25a328   Joerg Roedel   KVM: MMU: Track p...
324

6389ee946   Avi Kivity   KVM: Pull extra p...
325
  void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
c3c91fee5   Avi Kivity   KVM: Replace page...
326
327
  {
  	++vcpu->stat.pf_guest;
6389ee946   Avi Kivity   KVM: Pull extra p...
328
329
  	vcpu->arch.cr2 = fault->address;
  	kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
c3c91fee5   Avi Kivity   KVM: Replace page...
330
  }
27d6c8652   Nadav Har'El   KVM: nVMX: Implem...
331
  EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
c3c91fee5   Avi Kivity   KVM: Replace page...
332

6389ee946   Avi Kivity   KVM: Pull extra p...
333
  void kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
d4f8cf664   Joerg Roedel   KVM: MMU: Propaga...
334
  {
6389ee946   Avi Kivity   KVM: Pull extra p...
335
336
  	if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
  		vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
d4f8cf664   Joerg Roedel   KVM: MMU: Propaga...
337
  	else
6389ee946   Avi Kivity   KVM: Pull extra p...
338
  		vcpu->arch.mmu.inject_page_fault(vcpu, fault);
d4f8cf664   Joerg Roedel   KVM: MMU: Propaga...
339
  }
3419ffc8e   Sheng Yang   KVM: IOAPIC/LAPIC...
340
341
  void kvm_inject_nmi(struct kvm_vcpu *vcpu)
  {
7460fb4a3   Avi Kivity   KVM: Fix simultan...
342
343
  	atomic_inc(&vcpu->arch.nmi_queued);
  	kvm_make_request(KVM_REQ_NMI, vcpu);
3419ffc8e   Sheng Yang   KVM: IOAPIC/LAPIC...
344
345
  }
  EXPORT_SYMBOL_GPL(kvm_inject_nmi);
298101da2   Avi Kivity   KVM: Generalize e...
346
347
  void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
  {
ce7ddec4b   Joerg Roedel   KVM: x86: Allow m...
348
  	kvm_multiple_exception(vcpu, nr, true, error_code, false);
298101da2   Avi Kivity   KVM: Generalize e...
349
350
  }
  EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
ce7ddec4b   Joerg Roedel   KVM: x86: Allow m...
351
352
353
354
355
  void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
  {
  	kvm_multiple_exception(vcpu, nr, true, error_code, true);
  }
  EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
a03490ed2   Carsten Otte   KVM: Portability:...
356
  /*
0a79b0095   Avi Kivity   KVM: VMX: Check c...
357
358
359
360
   * Checks if cpl <= required_cpl; if true, return true.  Otherwise queue
   * a #GP and return false.
   */
  bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
298101da2   Avi Kivity   KVM: Generalize e...
361
  {
0a79b0095   Avi Kivity   KVM: VMX: Check c...
362
363
364
365
  	if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
  		return true;
  	kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
  	return false;
298101da2   Avi Kivity   KVM: Generalize e...
366
  }
0a79b0095   Avi Kivity   KVM: VMX: Check c...
367
  EXPORT_SYMBOL_GPL(kvm_require_cpl);
298101da2   Avi Kivity   KVM: Generalize e...
368

a03490ed2   Carsten Otte   KVM: Portability:...
369
  /*
ec92fe44e   Joerg Roedel   KVM: X86: Add kvm...
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
   * This function will be used to read from the physical memory of the currently
   * running guest. The difference to kvm_read_guest_page is that this function
   * can read from guest physical or from the guest's guest physical memory.
   */
  int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
  			    gfn_t ngfn, void *data, int offset, int len,
  			    u32 access)
  {
  	gfn_t real_gfn;
  	gpa_t ngpa;
  
  	ngpa     = gfn_to_gpa(ngfn);
  	real_gfn = mmu->translate_gpa(vcpu, ngpa, access);
  	if (real_gfn == UNMAPPED_GVA)
  		return -EFAULT;
  
  	real_gfn = gpa_to_gfn(real_gfn);
  
  	return kvm_read_guest_page(vcpu->kvm, real_gfn, data, offset, len);
  }
  EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
3d06b8bfd   Joerg Roedel   KVM: MMU: Introdu...
391
392
393
394
395
396
  int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
  			       void *data, int offset, int len, u32 access)
  {
  	return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
  				       data, offset, len, access);
  }
ec92fe44e   Joerg Roedel   KVM: X86: Add kvm...
397
  /*
a03490ed2   Carsten Otte   KVM: Portability:...
398
399
   * Load the pae pdptrs.  Return true is they are all valid.
   */
ff03a073e   Joerg Roedel   KVM: MMU: Add kvm...
400
  int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
a03490ed2   Carsten Otte   KVM: Portability:...
401
402
403
404
405
  {
  	gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
  	unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
  	int i;
  	int ret;
ff03a073e   Joerg Roedel   KVM: MMU: Add kvm...
406
  	u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
a03490ed2   Carsten Otte   KVM: Portability:...
407

ff03a073e   Joerg Roedel   KVM: MMU: Add kvm...
408
409
410
  	ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
  				      offset * sizeof(u64), sizeof(pdpte),
  				      PFERR_USER_MASK|PFERR_WRITE_MASK);
a03490ed2   Carsten Otte   KVM: Portability:...
411
412
413
414
415
  	if (ret < 0) {
  		ret = 0;
  		goto out;
  	}
  	for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
43a3795a3   Avi Kivity   KVM: MMU: Adjust ...
416
  		if (is_present_gpte(pdpte[i]) &&
20c466b56   Dong, Eddie   KVM: Use rsvd_bit...
417
  		    (pdpte[i] & vcpu->arch.mmu.rsvd_bits_mask[0][2])) {
a03490ed2   Carsten Otte   KVM: Portability:...
418
419
420
421
422
  			ret = 0;
  			goto out;
  		}
  	}
  	ret = 1;
ff03a073e   Joerg Roedel   KVM: MMU: Add kvm...
423
  	memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
6de4f3ada   Avi Kivity   KVM: Cache pdptrs
424
425
426
427
  	__set_bit(VCPU_EXREG_PDPTR,
  		  (unsigned long *)&vcpu->arch.regs_avail);
  	__set_bit(VCPU_EXREG_PDPTR,
  		  (unsigned long *)&vcpu->arch.regs_dirty);
a03490ed2   Carsten Otte   KVM: Portability:...
428
  out:
a03490ed2   Carsten Otte   KVM: Portability:...
429
430
431
  
  	return ret;
  }
cc4b6871e   Joerg Roedel   KVM: export the l...
432
  EXPORT_SYMBOL_GPL(load_pdptrs);
a03490ed2   Carsten Otte   KVM: Portability:...
433

d835dfecd   Avi Kivity   KVM: Don't bother...
434
435
  static bool pdptrs_changed(struct kvm_vcpu *vcpu)
  {
ff03a073e   Joerg Roedel   KVM: MMU: Add kvm...
436
  	u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
d835dfecd   Avi Kivity   KVM: Don't bother...
437
  	bool changed = true;
3d06b8bfd   Joerg Roedel   KVM: MMU: Introdu...
438
439
  	int offset;
  	gfn_t gfn;
d835dfecd   Avi Kivity   KVM: Don't bother...
440
441
442
443
  	int r;
  
  	if (is_long_mode(vcpu) || !is_pae(vcpu))
  		return false;
6de4f3ada   Avi Kivity   KVM: Cache pdptrs
444
445
446
  	if (!test_bit(VCPU_EXREG_PDPTR,
  		      (unsigned long *)&vcpu->arch.regs_avail))
  		return true;
9f8fe5043   Avi Kivity   KVM: Replace read...
447
448
  	gfn = (kvm_read_cr3(vcpu) & ~31u) >> PAGE_SHIFT;
  	offset = (kvm_read_cr3(vcpu) & ~31u) & (PAGE_SIZE - 1);
3d06b8bfd   Joerg Roedel   KVM: MMU: Introdu...
449
450
  	r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
  				       PFERR_USER_MASK | PFERR_WRITE_MASK);
d835dfecd   Avi Kivity   KVM: Don't bother...
451
452
  	if (r < 0)
  		goto out;
ff03a073e   Joerg Roedel   KVM: MMU: Add kvm...
453
  	changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
d835dfecd   Avi Kivity   KVM: Don't bother...
454
  out:
d835dfecd   Avi Kivity   KVM: Don't bother...
455
456
457
  
  	return changed;
  }
49a9b07ed   Avi Kivity   KVM: Fix mov cr0 ...
458
  int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
a03490ed2   Carsten Otte   KVM: Portability:...
459
  {
aad827034   Sheng Yang   KVM: VMX: Only re...
460
461
462
  	unsigned long old_cr0 = kvm_read_cr0(vcpu);
  	unsigned long update_bits = X86_CR0_PG | X86_CR0_WP |
  				    X86_CR0_CD | X86_CR0_NW;
f9a48e6a1   Avi Kivity   KVM: Set cr0.et w...
463
  	cr0 |= X86_CR0_ET;
ab344828e   Gleb Natapov   KVM: x86: fix che...
464
  #ifdef CONFIG_X86_64
0f12244fe   Gleb Natapov   KVM: x86 emulator...
465
466
  	if (cr0 & 0xffffffff00000000UL)
  		return 1;
ab344828e   Gleb Natapov   KVM: x86: fix che...
467
468
469
  #endif
  
  	cr0 &= ~CR0_RESERVED_BITS;
a03490ed2   Carsten Otte   KVM: Portability:...
470

0f12244fe   Gleb Natapov   KVM: x86 emulator...
471
472
  	if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
  		return 1;
a03490ed2   Carsten Otte   KVM: Portability:...
473

0f12244fe   Gleb Natapov   KVM: x86 emulator...
474
475
  	if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
  		return 1;
a03490ed2   Carsten Otte   KVM: Portability:...
476
477
478
  
  	if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
  #ifdef CONFIG_X86_64
f6801dff2   Avi Kivity   KVM: Rename vcpu-...
479
  		if ((vcpu->arch.efer & EFER_LME)) {
a03490ed2   Carsten Otte   KVM: Portability:...
480
  			int cs_db, cs_l;
0f12244fe   Gleb Natapov   KVM: x86 emulator...
481
482
  			if (!is_pae(vcpu))
  				return 1;
a03490ed2   Carsten Otte   KVM: Portability:...
483
  			kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
0f12244fe   Gleb Natapov   KVM: x86 emulator...
484
485
  			if (cs_l)
  				return 1;
a03490ed2   Carsten Otte   KVM: Portability:...
486
487
  		} else
  #endif
ff03a073e   Joerg Roedel   KVM: MMU: Add kvm...
488
  		if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
9f8fe5043   Avi Kivity   KVM: Replace read...
489
  						 kvm_read_cr3(vcpu)))
0f12244fe   Gleb Natapov   KVM: x86 emulator...
490
  			return 1;
a03490ed2   Carsten Otte   KVM: Portability:...
491
492
493
  	}
  
  	kvm_x86_ops->set_cr0(vcpu, cr0);
a03490ed2   Carsten Otte   KVM: Portability:...
494

d170c4190   Lai Jiangshan   KVM: Clear async ...
495
  	if ((cr0 ^ old_cr0) & X86_CR0_PG) {
e5f3f0279   Xiao Guangrong   KVM: MMU: clear a...
496
  		kvm_clear_async_pf_completion_queue(vcpu);
d170c4190   Lai Jiangshan   KVM: Clear async ...
497
498
  		kvm_async_pf_hash_reset(vcpu);
  	}
e5f3f0279   Xiao Guangrong   KVM: MMU: clear a...
499

aad827034   Sheng Yang   KVM: VMX: Only re...
500
501
  	if ((cr0 ^ old_cr0) & update_bits)
  		kvm_mmu_reset_context(vcpu);
0f12244fe   Gleb Natapov   KVM: x86 emulator...
502
503
  	return 0;
  }
2d3ad1f40   Avi Kivity   KVM: Prefix contr...
504
  EXPORT_SYMBOL_GPL(kvm_set_cr0);
a03490ed2   Carsten Otte   KVM: Portability:...
505

2d3ad1f40   Avi Kivity   KVM: Prefix contr...
506
  void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
a03490ed2   Carsten Otte   KVM: Portability:...
507
  {
49a9b07ed   Avi Kivity   KVM: Fix mov cr0 ...
508
  	(void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
a03490ed2   Carsten Otte   KVM: Portability:...
509
  }
2d3ad1f40   Avi Kivity   KVM: Prefix contr...
510
  EXPORT_SYMBOL_GPL(kvm_lmsw);
a03490ed2   Carsten Otte   KVM: Portability:...
511

2acf923e3   Dexuan Cui   KVM: VMX: Enable ...
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
  int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
  {
  	u64 xcr0;
  
  	/* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now  */
  	if (index != XCR_XFEATURE_ENABLED_MASK)
  		return 1;
  	xcr0 = xcr;
  	if (kvm_x86_ops->get_cpl(vcpu) != 0)
  		return 1;
  	if (!(xcr0 & XSTATE_FP))
  		return 1;
  	if ((xcr0 & XSTATE_YMM) && !(xcr0 & XSTATE_SSE))
  		return 1;
  	if (xcr0 & ~host_xcr0)
  		return 1;
  	vcpu->arch.xcr0 = xcr0;
  	vcpu->guest_xcr0_loaded = 0;
  	return 0;
  }
  
  int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
  {
  	if (__kvm_set_xcr(vcpu, index, xcr)) {
  		kvm_inject_gp(vcpu, 0);
  		return 1;
  	}
  	return 0;
  }
  EXPORT_SYMBOL_GPL(kvm_set_xcr);
a83b29c6a   Avi Kivity   KVM: Fix mov cr4 ...
542
  int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
a03490ed2   Carsten Otte   KVM: Portability:...
543
  {
fc78f5193   Avi Kivity   KVM: Add accessor...
544
  	unsigned long old_cr4 = kvm_read_cr4(vcpu);
c68b734fb   Yang, Wei Y   KVM: Add SMEP sup...
545
546
  	unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE |
  				   X86_CR4_PAE | X86_CR4_SMEP;
0f12244fe   Gleb Natapov   KVM: x86 emulator...
547
548
  	if (cr4 & CR4_RESERVED_BITS)
  		return 1;
a03490ed2   Carsten Otte   KVM: Portability:...
549

2acf923e3   Dexuan Cui   KVM: VMX: Enable ...
550
551
  	if (!guest_cpuid_has_xsave(vcpu) && (cr4 & X86_CR4_OSXSAVE))
  		return 1;
c68b734fb   Yang, Wei Y   KVM: Add SMEP sup...
552
553
  	if (!guest_cpuid_has_smep(vcpu) && (cr4 & X86_CR4_SMEP))
  		return 1;
74dc2b4ff   Yang, Wei   KVM: Add RDWRGSFS...
554
555
  	if (!guest_cpuid_has_fsgsbase(vcpu) && (cr4 & X86_CR4_RDWRGSFS))
  		return 1;
a03490ed2   Carsten Otte   KVM: Portability:...
556
  	if (is_long_mode(vcpu)) {
0f12244fe   Gleb Natapov   KVM: x86 emulator...
557
558
  		if (!(cr4 & X86_CR4_PAE))
  			return 1;
a2edf57f5   Avi Kivity   KVM: Fix PDPTR re...
559
560
  	} else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
  		   && ((cr4 ^ old_cr4) & pdptr_bits)
9f8fe5043   Avi Kivity   KVM: Replace read...
561
562
  		   && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
  				   kvm_read_cr3(vcpu)))
0f12244fe   Gleb Natapov   KVM: x86 emulator...
563
  		return 1;
5e1746d62   Nadav Har'El   KVM: nVMX: Allow ...
564
  	if (kvm_x86_ops->set_cr4(vcpu, cr4))
0f12244fe   Gleb Natapov   KVM: x86 emulator...
565
  		return 1;
a03490ed2   Carsten Otte   KVM: Portability:...
566

aad827034   Sheng Yang   KVM: VMX: Only re...
567
568
  	if ((cr4 ^ old_cr4) & pdptr_bits)
  		kvm_mmu_reset_context(vcpu);
0f12244fe   Gleb Natapov   KVM: x86 emulator...
569

2acf923e3   Dexuan Cui   KVM: VMX: Enable ...
570
  	if ((cr4 ^ old_cr4) & X86_CR4_OSXSAVE)
00b27a3ef   Avi Kivity   KVM: Move cpuid c...
571
  		kvm_update_cpuid(vcpu);
2acf923e3   Dexuan Cui   KVM: VMX: Enable ...
572

0f12244fe   Gleb Natapov   KVM: x86 emulator...
573
574
  	return 0;
  }
2d3ad1f40   Avi Kivity   KVM: Prefix contr...
575
  EXPORT_SYMBOL_GPL(kvm_set_cr4);
a03490ed2   Carsten Otte   KVM: Portability:...
576

2390218b6   Avi Kivity   KVM: Fix mov cr3 ...
577
  int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
a03490ed2   Carsten Otte   KVM: Portability:...
578
  {
9f8fe5043   Avi Kivity   KVM: Replace read...
579
  	if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
0ba73cdad   Marcelo Tosatti   KVM: MMU: sync ro...
580
  		kvm_mmu_sync_roots(vcpu);
d835dfecd   Avi Kivity   KVM: Don't bother...
581
  		kvm_mmu_flush_tlb(vcpu);
0f12244fe   Gleb Natapov   KVM: x86 emulator...
582
  		return 0;
d835dfecd   Avi Kivity   KVM: Don't bother...
583
  	}
a03490ed2   Carsten Otte   KVM: Portability:...
584
  	if (is_long_mode(vcpu)) {
0f12244fe   Gleb Natapov   KVM: x86 emulator...
585
586
  		if (cr3 & CR3_L_MODE_RESERVED_BITS)
  			return 1;
a03490ed2   Carsten Otte   KVM: Portability:...
587
588
  	} else {
  		if (is_pae(vcpu)) {
0f12244fe   Gleb Natapov   KVM: x86 emulator...
589
590
  			if (cr3 & CR3_PAE_RESERVED_BITS)
  				return 1;
ff03a073e   Joerg Roedel   KVM: MMU: Add kvm...
591
592
  			if (is_paging(vcpu) &&
  			    !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
0f12244fe   Gleb Natapov   KVM: x86 emulator...
593
  				return 1;
a03490ed2   Carsten Otte   KVM: Portability:...
594
595
596
597
598
599
  		}
  		/*
  		 * We don't check reserved bits in nonpae mode, because
  		 * this isn't enforced, and VMware depends on this.
  		 */
  	}
a03490ed2   Carsten Otte   KVM: Portability:...
600
601
602
603
604
605
606
607
608
609
  	/*
  	 * Does the new cr3 value map to physical memory? (Note, we
  	 * catch an invalid cr3 even in real-mode, because it would
  	 * cause trouble later on when we turn on paging anyway.)
  	 *
  	 * A real CPU would silently accept an invalid cr3 and would
  	 * attempt to use it - with largely undefined (and often hard
  	 * to debug) behavior on the guest side.
  	 */
  	if (unlikely(!gfn_to_memslot(vcpu->kvm, cr3 >> PAGE_SHIFT)))
0f12244fe   Gleb Natapov   KVM: x86 emulator...
610
611
  		return 1;
  	vcpu->arch.cr3 = cr3;
aff48baa3   Avi Kivity   KVM: Fetch guest ...
612
  	__set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
0f12244fe   Gleb Natapov   KVM: x86 emulator...
613
614
615
  	vcpu->arch.mmu.new_cr3(vcpu);
  	return 0;
  }
2d3ad1f40   Avi Kivity   KVM: Prefix contr...
616
  EXPORT_SYMBOL_GPL(kvm_set_cr3);
a03490ed2   Carsten Otte   KVM: Portability:...
617

eea1cff9a   Andre Przywara   KVM: x86: fix CR8...
618
  int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
a03490ed2   Carsten Otte   KVM: Portability:...
619
  {
0f12244fe   Gleb Natapov   KVM: x86 emulator...
620
621
  	if (cr8 & CR8_RESERVED_BITS)
  		return 1;
a03490ed2   Carsten Otte   KVM: Portability:...
622
623
624
  	if (irqchip_in_kernel(vcpu->kvm))
  		kvm_lapic_set_tpr(vcpu, cr8);
  	else
ad312c7c7   Zhang Xiantao   KVM: Portability:...
625
  		vcpu->arch.cr8 = cr8;
0f12244fe   Gleb Natapov   KVM: x86 emulator...
626
627
  	return 0;
  }
2d3ad1f40   Avi Kivity   KVM: Prefix contr...
628
  EXPORT_SYMBOL_GPL(kvm_set_cr8);
a03490ed2   Carsten Otte   KVM: Portability:...
629

2d3ad1f40   Avi Kivity   KVM: Prefix contr...
630
  unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
a03490ed2   Carsten Otte   KVM: Portability:...
631
632
633
634
  {
  	if (irqchip_in_kernel(vcpu->kvm))
  		return kvm_lapic_get_cr8(vcpu);
  	else
ad312c7c7   Zhang Xiantao   KVM: Portability:...
635
  		return vcpu->arch.cr8;
a03490ed2   Carsten Otte   KVM: Portability:...
636
  }
2d3ad1f40   Avi Kivity   KVM: Prefix contr...
637
  EXPORT_SYMBOL_GPL(kvm_get_cr8);
a03490ed2   Carsten Otte   KVM: Portability:...
638

338dbc978   Gleb Natapov   KVM: x86 emulator...
639
  static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
020df0794   Gleb Natapov   KVM: move DR regi...
640
641
642
643
644
645
646
647
  {
  	switch (dr) {
  	case 0 ... 3:
  		vcpu->arch.db[dr] = val;
  		if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
  			vcpu->arch.eff_db[dr] = val;
  		break;
  	case 4:
338dbc978   Gleb Natapov   KVM: x86 emulator...
648
649
  		if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
  			return 1; /* #UD */
020df0794   Gleb Natapov   KVM: move DR regi...
650
651
  		/* fall through */
  	case 6:
338dbc978   Gleb Natapov   KVM: x86 emulator...
652
653
  		if (val & 0xffffffff00000000ULL)
  			return -1; /* #GP */
020df0794   Gleb Natapov   KVM: move DR regi...
654
655
656
  		vcpu->arch.dr6 = (val & DR6_VOLATILE) | DR6_FIXED_1;
  		break;
  	case 5:
338dbc978   Gleb Natapov   KVM: x86 emulator...
657
658
  		if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
  			return 1; /* #UD */
020df0794   Gleb Natapov   KVM: move DR regi...
659
660
  		/* fall through */
  	default: /* 7 */
338dbc978   Gleb Natapov   KVM: x86 emulator...
661
662
  		if (val & 0xffffffff00000000ULL)
  			return -1; /* #GP */
020df0794   Gleb Natapov   KVM: move DR regi...
663
664
665
666
667
668
669
670
671
672
  		vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
  		if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
  			kvm_x86_ops->set_dr7(vcpu, vcpu->arch.dr7);
  			vcpu->arch.switch_db_regs = (val & DR7_BP_EN_MASK);
  		}
  		break;
  	}
  
  	return 0;
  }
338dbc978   Gleb Natapov   KVM: x86 emulator...
673
674
675
676
677
678
679
680
681
682
683
684
685
  
  int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
  {
  	int res;
  
  	res = __kvm_set_dr(vcpu, dr, val);
  	if (res > 0)
  		kvm_queue_exception(vcpu, UD_VECTOR);
  	else if (res < 0)
  		kvm_inject_gp(vcpu, 0);
  
  	return res;
  }
020df0794   Gleb Natapov   KVM: move DR regi...
686
  EXPORT_SYMBOL_GPL(kvm_set_dr);
338dbc978   Gleb Natapov   KVM: x86 emulator...
687
  static int _kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
020df0794   Gleb Natapov   KVM: move DR regi...
688
689
690
691
692
693
  {
  	switch (dr) {
  	case 0 ... 3:
  		*val = vcpu->arch.db[dr];
  		break;
  	case 4:
338dbc978   Gleb Natapov   KVM: x86 emulator...
694
  		if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
020df0794   Gleb Natapov   KVM: move DR regi...
695
  			return 1;
020df0794   Gleb Natapov   KVM: move DR regi...
696
697
698
699
700
  		/* fall through */
  	case 6:
  		*val = vcpu->arch.dr6;
  		break;
  	case 5:
338dbc978   Gleb Natapov   KVM: x86 emulator...
701
  		if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
020df0794   Gleb Natapov   KVM: move DR regi...
702
  			return 1;
020df0794   Gleb Natapov   KVM: move DR regi...
703
704
705
706
707
708
709
710
  		/* fall through */
  	default: /* 7 */
  		*val = vcpu->arch.dr7;
  		break;
  	}
  
  	return 0;
  }
338dbc978   Gleb Natapov   KVM: x86 emulator...
711
712
713
714
715
716
717
718
719
  
  int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
  {
  	if (_kvm_get_dr(vcpu, dr, val)) {
  		kvm_queue_exception(vcpu, UD_VECTOR);
  		return 1;
  	}
  	return 0;
  }
020df0794   Gleb Natapov   KVM: move DR regi...
720
  EXPORT_SYMBOL_GPL(kvm_get_dr);
022cd0e84   Avi Kivity   KVM: Add generic ...
721
722
723
724
725
726
727
728
729
730
731
732
733
734
  bool kvm_rdpmc(struct kvm_vcpu *vcpu)
  {
  	u32 ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
  	u64 data;
  	int err;
  
  	err = kvm_pmu_read_pmc(vcpu, ecx, &data);
  	if (err)
  		return err;
  	kvm_register_write(vcpu, VCPU_REGS_RAX, (u32)data);
  	kvm_register_write(vcpu, VCPU_REGS_RDX, data >> 32);
  	return err;
  }
  EXPORT_SYMBOL_GPL(kvm_rdpmc);
043405e10   Carsten Otte   KVM: Move x86 msr...
735
736
737
738
739
  /*
   * List of msr numbers which we expose to userspace through KVM_GET_MSRS
   * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
   *
   * This list is modified at module load time to reflect the
e3267cbbb   Glauber Costa   KVM: x86: include...
740
741
   * capabilities of the host cpu. This capabilities test skips MSRs that are
   * kvm-specific. Those are put in the beginning of the list.
043405e10   Carsten Otte   KVM: Move x86 msr...
742
   */
e3267cbbb   Glauber Costa   KVM: x86: include...
743

c9aaa8957   Glauber Costa   KVM: Steal time i...
744
  #define KVM_SAVE_MSRS_BEGIN	9
043405e10   Carsten Otte   KVM: Move x86 msr...
745
  static u32 msrs_to_save[] = {
e3267cbbb   Glauber Costa   KVM: x86: include...
746
  	MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
11c6bffa4   Glauber Costa   KVM: x86: change ...
747
  	MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
55cd8e5a4   Gleb Natapov   KVM: Implement ba...
748
  	HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
c9aaa8957   Glauber Costa   KVM: Steal time i...
749
  	HV_X64_MSR_APIC_ASSIST_PAGE, MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
043405e10   Carsten Otte   KVM: Move x86 msr...
750
  	MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
8c06585d6   Brian Gerst   x86: Remove redun...
751
  	MSR_STAR,
043405e10   Carsten Otte   KVM: Move x86 msr...
752
753
754
  #ifdef CONFIG_X86_64
  	MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
  #endif
e90aa41e6   Avi Kivity   KVM: Don't save/r...
755
  	MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA
043405e10   Carsten Otte   KVM: Move x86 msr...
756
757
758
759
760
  };
  
  static unsigned num_msrs_to_save;
  
  static u32 emulated_msrs[] = {
a3e06bbe8   Liu, Jinsong   KVM: emulate lapi...
761
  	MSR_IA32_TSCDEADLINE,
043405e10   Carsten Otte   KVM: Move x86 msr...
762
  	MSR_IA32_MISC_ENABLE,
908e75f3e   Avi Kivity   KVM: Expose MCE c...
763
764
  	MSR_IA32_MCG_STATUS,
  	MSR_IA32_MCG_CTL,
043405e10   Carsten Otte   KVM: Move x86 msr...
765
  };
b69e8caef   Roedel, Joerg   KVM: x86: Inject ...
766
  static int set_efer(struct kvm_vcpu *vcpu, u64 efer)
15c4a6406   Carsten Otte   KVM: Portability:...
767
  {
aad827034   Sheng Yang   KVM: VMX: Only re...
768
  	u64 old_efer = vcpu->arch.efer;
b69e8caef   Roedel, Joerg   KVM: x86: Inject ...
769
770
  	if (efer & efer_reserved_bits)
  		return 1;
15c4a6406   Carsten Otte   KVM: Portability:...
771
772
  
  	if (is_paging(vcpu)
b69e8caef   Roedel, Joerg   KVM: x86: Inject ...
773
774
  	    && (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
  		return 1;
15c4a6406   Carsten Otte   KVM: Portability:...
775

1b2fd70c4   Alexander Graf   KVM: Add FFXSR su...
776
777
778
779
  	if (efer & EFER_FFXSR) {
  		struct kvm_cpuid_entry2 *feat;
  
  		feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
b69e8caef   Roedel, Joerg   KVM: x86: Inject ...
780
781
  		if (!feat || !(feat->edx & bit(X86_FEATURE_FXSR_OPT)))
  			return 1;
1b2fd70c4   Alexander Graf   KVM: Add FFXSR su...
782
  	}
d80174745   Alexander Graf   KVM: SVM: Only al...
783
784
785
786
  	if (efer & EFER_SVME) {
  		struct kvm_cpuid_entry2 *feat;
  
  		feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
b69e8caef   Roedel, Joerg   KVM: x86: Inject ...
787
788
  		if (!feat || !(feat->ecx & bit(X86_FEATURE_SVM)))
  			return 1;
d80174745   Alexander Graf   KVM: SVM: Only al...
789
  	}
15c4a6406   Carsten Otte   KVM: Portability:...
790
  	efer &= ~EFER_LMA;
f6801dff2   Avi Kivity   KVM: Rename vcpu-...
791
  	efer |= vcpu->arch.efer & EFER_LMA;
15c4a6406   Carsten Otte   KVM: Portability:...
792

a3d204e28   Sheng Yang   KVM: x86: Check L...
793
  	kvm_x86_ops->set_efer(vcpu, efer);
9645bb56b   Avi Kivity   KVM: MMU: Use dif...
794
  	vcpu->arch.mmu.base_role.nxe = (efer & EFER_NX) && !tdp_enabled;
b69e8caef   Roedel, Joerg   KVM: x86: Inject ...
795

aad827034   Sheng Yang   KVM: VMX: Only re...
796
797
798
  	/* Update reserved bits */
  	if ((efer ^ old_efer) & EFER_NX)
  		kvm_mmu_reset_context(vcpu);
b69e8caef   Roedel, Joerg   KVM: x86: Inject ...
799
  	return 0;
15c4a6406   Carsten Otte   KVM: Portability:...
800
  }
f2b4b7ddf   Joerg Roedel   KVM: make EFER_RE...
801
802
803
804
805
  void kvm_enable_efer_bits(u64 mask)
  {
         efer_reserved_bits &= ~mask;
  }
  EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
15c4a6406   Carsten Otte   KVM: Portability:...
806
807
808
809
810
811
812
813
814
  /*
   * Writes msr value into into the appropriate "register".
   * Returns 0 on success, non-0 otherwise.
   * Assumes vcpu_load() was already called.
   */
  int kvm_set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
  {
  	return kvm_x86_ops->set_msr(vcpu, msr_index, data);
  }
313a3dc75   Carsten Otte   KVM: Portability:...
815
816
817
818
819
820
821
  /*
   * Adapt set_msr() to msr_io()'s calling convention
   */
  static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
  {
  	return kvm_set_msr(vcpu, index, *data);
  }
18068523d   Glauber de Oliveira Costa   KVM: paravirtuali...
822
823
  static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
  {
9ed3c444a   Avi Kivity   KVM: Fix wallcloc...
824
825
  	int version;
  	int r;
50d0a0f98   Gerd Hoffmann   KVM: Make kvm hos...
826
  	struct pvclock_wall_clock wc;
923de3cf5   Jason Wang   kvmclock: count t...
827
  	struct timespec boot;
18068523d   Glauber de Oliveira Costa   KVM: paravirtuali...
828
829
830
  
  	if (!wall_clock)
  		return;
9ed3c444a   Avi Kivity   KVM: Fix wallcloc...
831
832
833
834
835
836
837
838
  	r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
  	if (r)
  		return;
  
  	if (version & 1)
  		++version;  /* first time write, random junk */
  
  	++version;
18068523d   Glauber de Oliveira Costa   KVM: paravirtuali...
839

18068523d   Glauber de Oliveira Costa   KVM: paravirtuali...
840
  	kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
50d0a0f98   Gerd Hoffmann   KVM: Make kvm hos...
841
842
  	/*
  	 * The guest calculates current wall clock time by adding
34c238a1d   Zachary Amsden   KVM: x86: Rename ...
843
  	 * system time (updated by kvm_guest_time_update below) to the
50d0a0f98   Gerd Hoffmann   KVM: Make kvm hos...
844
845
846
  	 * wall clock specified here.  guest system time equals host
  	 * system time for us, thus we must fill in host boot time here.
  	 */
923de3cf5   Jason Wang   kvmclock: count t...
847
  	getboottime(&boot);
50d0a0f98   Gerd Hoffmann   KVM: Make kvm hos...
848
849
850
851
  
  	wc.sec = boot.tv_sec;
  	wc.nsec = boot.tv_nsec;
  	wc.version = version;
18068523d   Glauber de Oliveira Costa   KVM: paravirtuali...
852
853
854
855
856
  
  	kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
  
  	version++;
  	kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
18068523d   Glauber de Oliveira Costa   KVM: paravirtuali...
857
  }
50d0a0f98   Gerd Hoffmann   KVM: Make kvm hos...
858
859
860
861
862
863
864
865
866
867
868
  static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
  {
  	uint32_t quotient, remainder;
  
  	/* Don't try to replace with do_div(), this one calculates
  	 * "(dividend << 32) / divisor" */
  	__asm__ ( "divl %4"
  		  : "=a" (quotient), "=d" (remainder)
  		  : "0" (0), "1" (dividend), "r" (divisor) );
  	return quotient;
  }
5f4e3f882   Zachary Amsden   KVM: x86: Make ma...
869
870
  static void kvm_get_time_scale(uint32_t scaled_khz, uint32_t base_khz,
  			       s8 *pshift, u32 *pmultiplier)
50d0a0f98   Gerd Hoffmann   KVM: Make kvm hos...
871
  {
5f4e3f882   Zachary Amsden   KVM: x86: Make ma...
872
  	uint64_t scaled64;
50d0a0f98   Gerd Hoffmann   KVM: Make kvm hos...
873
874
875
  	int32_t  shift = 0;
  	uint64_t tps64;
  	uint32_t tps32;
5f4e3f882   Zachary Amsden   KVM: x86: Make ma...
876
877
  	tps64 = base_khz * 1000LL;
  	scaled64 = scaled_khz * 1000LL;
50933623e   Jan Kiszka   KVM: x86: Fix con...
878
  	while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
50d0a0f98   Gerd Hoffmann   KVM: Make kvm hos...
879
880
881
882
883
  		tps64 >>= 1;
  		shift--;
  	}
  
  	tps32 = (uint32_t)tps64;
50933623e   Jan Kiszka   KVM: x86: Fix con...
884
885
  	while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
  		if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
5f4e3f882   Zachary Amsden   KVM: x86: Make ma...
886
887
888
  			scaled64 >>= 1;
  		else
  			tps32 <<= 1;
50d0a0f98   Gerd Hoffmann   KVM: Make kvm hos...
889
890
  		shift++;
  	}
5f4e3f882   Zachary Amsden   KVM: x86: Make ma...
891
892
  	*pshift = shift;
  	*pmultiplier = div_frac(scaled64, tps32);
50d0a0f98   Gerd Hoffmann   KVM: Make kvm hos...
893

5f4e3f882   Zachary Amsden   KVM: x86: Make ma...
894
895
896
  	pr_debug("%s: base_khz %u => %u, shift %d, mul %u
  ",
  		 __func__, base_khz, scaled_khz, shift, *pmultiplier);
50d0a0f98   Gerd Hoffmann   KVM: Make kvm hos...
897
  }
759379dd6   Zachary Amsden   KVM: x86: Add hel...
898
899
900
901
902
903
904
905
  static inline u64 get_kernel_ns(void)
  {
  	struct timespec ts;
  
  	WARN_ON(preemptible());
  	ktime_get_ts(&ts);
  	monotonic_to_bootbased(&ts);
  	return timespec_to_ns(&ts);
50d0a0f98   Gerd Hoffmann   KVM: Make kvm hos...
906
  }
c80766040   Gerd Hoffmann   KVM: Fix kvmclock...
907
  static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
c285545f8   Zachary Amsden   KVM: x86: TSC cat...
908
  unsigned long max_tsc_khz;
c80766040   Gerd Hoffmann   KVM: Fix kvmclock...
909

8cfdc0008   Zachary Amsden   KVM: x86: Make cp...
910
911
912
913
914
915
916
917
  static inline int kvm_tsc_changes_freq(void)
  {
  	int cpu = get_cpu();
  	int ret = !boot_cpu_has(X86_FEATURE_CONSTANT_TSC) &&
  		  cpufreq_quick_get(cpu) != 0;
  	put_cpu();
  	return ret;
  }
a3e06bbe8   Liu, Jinsong   KVM: emulate lapi...
918
  u64 vcpu_tsc_khz(struct kvm_vcpu *vcpu)
1e993611d   Joerg Roedel   KVM: X86: Let kvm...
919
920
921
922
923
924
  {
  	if (vcpu->arch.virtual_tsc_khz)
  		return vcpu->arch.virtual_tsc_khz;
  	else
  		return __this_cpu_read(cpu_tsc_khz);
  }
857e40999   Joerg Roedel   KVM: X86: Delegat...
925
  static inline u64 nsec_to_cycles(struct kvm_vcpu *vcpu, u64 nsec)
759379dd6   Zachary Amsden   KVM: x86: Add hel...
926
  {
217fc9cfc   Avi Kivity   KVM: Fix build er...
927
  	u64 ret;
759379dd6   Zachary Amsden   KVM: x86: Add hel...
928
929
930
931
932
  	WARN_ON(preemptible());
  	if (kvm_tsc_changes_freq())
  		printk_once(KERN_WARNING
  		 "kvm: unreliable cycle conversion on adjustable rate TSC
  ");
857e40999   Joerg Roedel   KVM: X86: Delegat...
933
  	ret = nsec * vcpu_tsc_khz(vcpu);
217fc9cfc   Avi Kivity   KVM: Fix build er...
934
935
  	do_div(ret, USEC_PER_SEC);
  	return ret;
759379dd6   Zachary Amsden   KVM: x86: Add hel...
936
  }
1e993611d   Joerg Roedel   KVM: X86: Let kvm...
937
  static void kvm_init_tsc_catchup(struct kvm_vcpu *vcpu, u32 this_tsc_khz)
c285545f8   Zachary Amsden   KVM: x86: TSC cat...
938
939
940
  {
  	/* Compute a scale to convert nanoseconds in TSC cycles */
  	kvm_get_time_scale(this_tsc_khz, NSEC_PER_SEC / 1000,
1e993611d   Joerg Roedel   KVM: X86: Let kvm...
941
942
  			   &vcpu->arch.tsc_catchup_shift,
  			   &vcpu->arch.tsc_catchup_mult);
c285545f8   Zachary Amsden   KVM: x86: TSC cat...
943
944
945
946
947
  }
  
  static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
  {
  	u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.last_tsc_nsec,
1e993611d   Joerg Roedel   KVM: X86: Let kvm...
948
949
  				      vcpu->arch.tsc_catchup_mult,
  				      vcpu->arch.tsc_catchup_shift);
c285545f8   Zachary Amsden   KVM: x86: TSC cat...
950
951
952
  	tsc += vcpu->arch.last_tsc_write;
  	return tsc;
  }
99e3e30ae   Zachary Amsden   KVM: x86: Move TS...
953
954
955
  void kvm_write_tsc(struct kvm_vcpu *vcpu, u64 data)
  {
  	struct kvm *kvm = vcpu->kvm;
f38e098ff   Zachary Amsden   KVM: x86: TSC res...
956
  	u64 offset, ns, elapsed;
99e3e30ae   Zachary Amsden   KVM: x86: Move TS...
957
  	unsigned long flags;
46543ba45   Zachary Amsden   KVM: x86: Robust ...
958
  	s64 sdiff;
99e3e30ae   Zachary Amsden   KVM: x86: Move TS...
959

038f8c110   Jan Kiszka   KVM: x86: Convert...
960
  	raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
857e40999   Joerg Roedel   KVM: X86: Delegat...
961
  	offset = kvm_x86_ops->compute_tsc_offset(vcpu, data);
759379dd6   Zachary Amsden   KVM: x86: Add hel...
962
  	ns = get_kernel_ns();
f38e098ff   Zachary Amsden   KVM: x86: TSC res...
963
  	elapsed = ns - kvm->arch.last_tsc_nsec;
46543ba45   Zachary Amsden   KVM: x86: Robust ...
964
965
966
  	sdiff = data - kvm->arch.last_tsc_write;
  	if (sdiff < 0)
  		sdiff = -sdiff;
f38e098ff   Zachary Amsden   KVM: x86: TSC res...
967
968
  
  	/*
46543ba45   Zachary Amsden   KVM: x86: Robust ...
969
  	 * Special case: close write to TSC within 5 seconds of
f38e098ff   Zachary Amsden   KVM: x86: TSC res...
970
  	 * another CPU is interpreted as an attempt to synchronize
0d2eb44f6   Lucas De Marchi   x86: Fix common m...
971
  	 * The 5 seconds is to accommodate host load / swapping as
46543ba45   Zachary Amsden   KVM: x86: Robust ...
972
  	 * well as any reset of TSC during the boot process.
f38e098ff   Zachary Amsden   KVM: x86: TSC res...
973
974
  	 *
  	 * In that case, for a reliable TSC, we can match TSC offsets,
46543ba45   Zachary Amsden   KVM: x86: Robust ...
975
  	 * or make a best guest using elapsed value.
f38e098ff   Zachary Amsden   KVM: x86: TSC res...
976
  	 */
857e40999   Joerg Roedel   KVM: X86: Delegat...
977
  	if (sdiff < nsec_to_cycles(vcpu, 5ULL * NSEC_PER_SEC) &&
46543ba45   Zachary Amsden   KVM: x86: Robust ...
978
  	    elapsed < 5ULL * NSEC_PER_SEC) {
f38e098ff   Zachary Amsden   KVM: x86: TSC res...
979
980
981
982
983
  		if (!check_tsc_unstable()) {
  			offset = kvm->arch.last_tsc_offset;
  			pr_debug("kvm: matched tsc offset for %llu
  ", data);
  		} else {
857e40999   Joerg Roedel   KVM: X86: Delegat...
984
  			u64 delta = nsec_to_cycles(vcpu, elapsed);
759379dd6   Zachary Amsden   KVM: x86: Add hel...
985
986
987
  			offset += delta;
  			pr_debug("kvm: adjusted tsc offset by %llu
  ", delta);
f38e098ff   Zachary Amsden   KVM: x86: TSC res...
988
989
990
991
992
993
  		}
  		ns = kvm->arch.last_tsc_nsec;
  	}
  	kvm->arch.last_tsc_nsec = ns;
  	kvm->arch.last_tsc_write = data;
  	kvm->arch.last_tsc_offset = offset;
99e3e30ae   Zachary Amsden   KVM: x86: Move TS...
994
  	kvm_x86_ops->write_tsc_offset(vcpu, offset);
038f8c110   Jan Kiszka   KVM: x86: Convert...
995
  	raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
99e3e30ae   Zachary Amsden   KVM: x86: Move TS...
996
997
998
  
  	/* Reset of TSC must disable overshoot protection below */
  	vcpu->arch.hv_clock.tsc_timestamp = 0;
c285545f8   Zachary Amsden   KVM: x86: TSC cat...
999
1000
  	vcpu->arch.last_tsc_write = data;
  	vcpu->arch.last_tsc_nsec = ns;
99e3e30ae   Zachary Amsden   KVM: x86: Move TS...
1001
1002
  }
  EXPORT_SYMBOL_GPL(kvm_write_tsc);
34c238a1d   Zachary Amsden   KVM: x86: Rename ...
1003
  static int kvm_guest_time_update(struct kvm_vcpu *v)
18068523d   Glauber de Oliveira Costa   KVM: paravirtuali...
1004
  {
18068523d   Glauber de Oliveira Costa   KVM: paravirtuali...
1005
1006
1007
  	unsigned long flags;
  	struct kvm_vcpu_arch *vcpu = &v->arch;
  	void *shared_kaddr;
463656c00   Avi Kivity   KVM: Replace kvmc...
1008
  	unsigned long this_tsc_khz;
1d5f066e0   Zachary Amsden   KVM: x86: Fix a p...
1009
1010
  	s64 kernel_ns, max_kernel_ns;
  	u64 tsc_timestamp;
18068523d   Glauber de Oliveira Costa   KVM: paravirtuali...
1011

18068523d   Glauber de Oliveira Costa   KVM: paravirtuali...
1012
1013
  	/* Keep irq disabled to prevent changes to the clock */
  	local_irq_save(flags);
d5c1785d2   Nadav Har'El   KVM: L1 TSC handling
1014
  	tsc_timestamp = kvm_x86_ops->read_l1_tsc(v);
759379dd6   Zachary Amsden   KVM: x86: Add hel...
1015
  	kernel_ns = get_kernel_ns();
1e993611d   Joerg Roedel   KVM: X86: Let kvm...
1016
  	this_tsc_khz = vcpu_tsc_khz(v);
8cfdc0008   Zachary Amsden   KVM: x86: Make cp...
1017
  	if (unlikely(this_tsc_khz == 0)) {
c285545f8   Zachary Amsden   KVM: x86: TSC cat...
1018
  		local_irq_restore(flags);
34c238a1d   Zachary Amsden   KVM: x86: Rename ...
1019
  		kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
8cfdc0008   Zachary Amsden   KVM: x86: Make cp...
1020
1021
  		return 1;
  	}
18068523d   Glauber de Oliveira Costa   KVM: paravirtuali...
1022

1d5f066e0   Zachary Amsden   KVM: x86: Fix a p...
1023
  	/*
c285545f8   Zachary Amsden   KVM: x86: TSC cat...
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
  	 * We may have to catch up the TSC to match elapsed wall clock
  	 * time for two reasons, even if kvmclock is used.
  	 *   1) CPU could have been running below the maximum TSC rate
  	 *   2) Broken TSC compensation resets the base at each VCPU
  	 *      entry to avoid unknown leaps of TSC even when running
  	 *      again on the same CPU.  This may cause apparent elapsed
  	 *      time to disappear, and the guest to stand still or run
  	 *	very slowly.
  	 */
  	if (vcpu->tsc_catchup) {
  		u64 tsc = compute_guest_tsc(v, kernel_ns);
  		if (tsc > tsc_timestamp) {
  			kvm_x86_ops->adjust_tsc_offset(v, tsc - tsc_timestamp);
  			tsc_timestamp = tsc;
  		}
50d0a0f98   Gerd Hoffmann   KVM: Make kvm hos...
1039
  	}
18068523d   Glauber de Oliveira Costa   KVM: paravirtuali...
1040
  	local_irq_restore(flags);
c285545f8   Zachary Amsden   KVM: x86: TSC cat...
1041
1042
  	if (!vcpu->time_page)
  		return 0;
18068523d   Glauber de Oliveira Costa   KVM: paravirtuali...
1043

c285545f8   Zachary Amsden   KVM: x86: TSC cat...
1044
  	/*
1d5f066e0   Zachary Amsden   KVM: x86: Fix a p...
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
  	 * Time as measured by the TSC may go backwards when resetting the base
  	 * tsc_timestamp.  The reason for this is that the TSC resolution is
  	 * higher than the resolution of the other clock scales.  Thus, many
  	 * possible measurments of the TSC correspond to one measurement of any
  	 * other clock, and so a spread of values is possible.  This is not a
  	 * problem for the computation of the nanosecond clock; with TSC rates
  	 * around 1GHZ, there can only be a few cycles which correspond to one
  	 * nanosecond value, and any path through this code will inevitably
  	 * take longer than that.  However, with the kernel_ns value itself,
  	 * the precision may be much lower, down to HZ granularity.  If the
  	 * first sampling of TSC against kernel_ns ends in the low part of the
  	 * range, and the second in the high end of the range, we can get:
  	 *
  	 * (TSC - offset_low) * S + kns_old > (TSC - offset_high) * S + kns_new
  	 *
  	 * As the sampling errors potentially range in the thousands of cycles,
  	 * it is possible such a time value has already been observed by the
  	 * guest.  To protect against this, we must compute the system time as
  	 * observed by the guest and ensure the new system time is greater.
  	 */
  	max_kernel_ns = 0;
  	if (vcpu->hv_clock.tsc_timestamp && vcpu->last_guest_tsc) {
  		max_kernel_ns = vcpu->last_guest_tsc -
  				vcpu->hv_clock.tsc_timestamp;
  		max_kernel_ns = pvclock_scale_delta(max_kernel_ns,
  				    vcpu->hv_clock.tsc_to_system_mul,
  				    vcpu->hv_clock.tsc_shift);
  		max_kernel_ns += vcpu->last_kernel_ns;
  	}
afbcf7ab8   Glauber Costa   KVM: allow usersp...
1074

e48672fa2   Zachary Amsden   KVM: x86: Unify T...
1075
  	if (unlikely(vcpu->hw_tsc_khz != this_tsc_khz)) {
5f4e3f882   Zachary Amsden   KVM: x86: Make ma...
1076
1077
1078
  		kvm_get_time_scale(NSEC_PER_SEC / 1000, this_tsc_khz,
  				   &vcpu->hv_clock.tsc_shift,
  				   &vcpu->hv_clock.tsc_to_system_mul);
e48672fa2   Zachary Amsden   KVM: x86: Unify T...
1079
  		vcpu->hw_tsc_khz = this_tsc_khz;
8cfdc0008   Zachary Amsden   KVM: x86: Make cp...
1080
  	}
1d5f066e0   Zachary Amsden   KVM: x86: Fix a p...
1081
1082
  	if (max_kernel_ns > kernel_ns)
  		kernel_ns = max_kernel_ns;
8cfdc0008   Zachary Amsden   KVM: x86: Make cp...
1083
  	/* With all the info we got, fill in the values */
1d5f066e0   Zachary Amsden   KVM: x86: Fix a p...
1084
  	vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
759379dd6   Zachary Amsden   KVM: x86: Add hel...
1085
  	vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
1d5f066e0   Zachary Amsden   KVM: x86: Fix a p...
1086
  	vcpu->last_kernel_ns = kernel_ns;
28e4639ad   Zachary Amsden   KVM: x86: Fix kvm...
1087
  	vcpu->last_guest_tsc = tsc_timestamp;
371bcf646   Glauber Costa   KVM: x86: Tell th...
1088
  	vcpu->hv_clock.flags = 0;
18068523d   Glauber de Oliveira Costa   KVM: paravirtuali...
1089
1090
1091
  	/*
  	 * The interface expects us to write an even number signaling that the
  	 * update is finished. Since the guest won't see the intermediate
50d0a0f98   Gerd Hoffmann   KVM: Make kvm hos...
1092
  	 * state, we just increase by 2 at the end.
18068523d   Glauber de Oliveira Costa   KVM: paravirtuali...
1093
  	 */
50d0a0f98   Gerd Hoffmann   KVM: Make kvm hos...
1094
  	vcpu->hv_clock.version += 2;
18068523d   Glauber de Oliveira Costa   KVM: paravirtuali...
1095
1096
1097
1098
  
  	shared_kaddr = kmap_atomic(vcpu->time_page, KM_USER0);
  
  	memcpy(shared_kaddr + vcpu->time_offset, &vcpu->hv_clock,
50d0a0f98   Gerd Hoffmann   KVM: Make kvm hos...
1099
  	       sizeof(vcpu->hv_clock));
18068523d   Glauber de Oliveira Costa   KVM: paravirtuali...
1100
1101
1102
1103
  
  	kunmap_atomic(shared_kaddr, KM_USER0);
  
  	mark_page_dirty(v->kvm, vcpu->time >> PAGE_SHIFT);
8cfdc0008   Zachary Amsden   KVM: x86: Make cp...
1104
  	return 0;
c80766040   Gerd Hoffmann   KVM: Fix kvmclock...
1105
  }
9ba075a66   Avi Kivity   KVM: MTRR support
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
  static bool msr_mtrr_valid(unsigned msr)
  {
  	switch (msr) {
  	case 0x200 ... 0x200 + 2 * KVM_NR_VAR_MTRR - 1:
  	case MSR_MTRRfix64K_00000:
  	case MSR_MTRRfix16K_80000:
  	case MSR_MTRRfix16K_A0000:
  	case MSR_MTRRfix4K_C0000:
  	case MSR_MTRRfix4K_C8000:
  	case MSR_MTRRfix4K_D0000:
  	case MSR_MTRRfix4K_D8000:
  	case MSR_MTRRfix4K_E0000:
  	case MSR_MTRRfix4K_E8000:
  	case MSR_MTRRfix4K_F0000:
  	case MSR_MTRRfix4K_F8000:
  	case MSR_MTRRdefType:
  	case MSR_IA32_CR_PAT:
  		return true;
  	case 0x2f8:
  		return true;
  	}
  	return false;
  }
d6289b936   Marcelo Tosatti   KVM: x86: verify ...
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
  static bool valid_pat_type(unsigned t)
  {
  	return t < 8 && (1 << t) & 0xf3; /* 0, 1, 4, 5, 6, 7 */
  }
  
  static bool valid_mtrr_type(unsigned t)
  {
  	return t < 8 && (1 << t) & 0x73; /* 0, 1, 4, 5, 6 */
  }
  
  static bool mtrr_valid(struct kvm_vcpu *vcpu, u32 msr, u64 data)
  {
  	int i;
  
  	if (!msr_mtrr_valid(msr))
  		return false;
  
  	if (msr == MSR_IA32_CR_PAT) {
  		for (i = 0; i < 8; i++)
  			if (!valid_pat_type((data >> (i * 8)) & 0xff))
  				return false;
  		return true;
  	} else if (msr == MSR_MTRRdefType) {
  		if (data & ~0xcff)
  			return false;
  		return valid_mtrr_type(data & 0xff);
  	} else if (msr >= MSR_MTRRfix64K_00000 && msr <= MSR_MTRRfix4K_F8000) {
  		for (i = 0; i < 8 ; i++)
  			if (!valid_mtrr_type((data >> (i * 8)) & 0xff))
  				return false;
  		return true;
  	}
  
  	/* variable MTRRs */
  	return valid_mtrr_type(data & 0xff);
  }
9ba075a66   Avi Kivity   KVM: MTRR support
1165
1166
  static int set_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
  {
0bed3b568   Sheng Yang   KVM: Improve MTRR...
1167
  	u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
d6289b936   Marcelo Tosatti   KVM: x86: verify ...
1168
  	if (!mtrr_valid(vcpu, msr, data))
9ba075a66   Avi Kivity   KVM: MTRR support
1169
  		return 1;
0bed3b568   Sheng Yang   KVM: Improve MTRR...
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
  	if (msr == MSR_MTRRdefType) {
  		vcpu->arch.mtrr_state.def_type = data;
  		vcpu->arch.mtrr_state.enabled = (data & 0xc00) >> 10;
  	} else if (msr == MSR_MTRRfix64K_00000)
  		p[0] = data;
  	else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
  		p[1 + msr - MSR_MTRRfix16K_80000] = data;
  	else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
  		p[3 + msr - MSR_MTRRfix4K_C0000] = data;
  	else if (msr == MSR_IA32_CR_PAT)
  		vcpu->arch.pat = data;
  	else {	/* Variable MTRRs */
  		int idx, is_mtrr_mask;
  		u64 *pt;
  
  		idx = (msr - 0x200) / 2;
  		is_mtrr_mask = msr - 0x200 - 2 * idx;
  		if (!is_mtrr_mask)
  			pt =
  			  (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
  		else
  			pt =
  			  (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
  		*pt = data;
  	}
  
  	kvm_mmu_reset_context(vcpu);
9ba075a66   Avi Kivity   KVM: MTRR support
1197
1198
  	return 0;
  }
15c4a6406   Carsten Otte   KVM: Portability:...
1199

890ca9aef   Huang Ying   KVM: Add MCE support
1200
  static int set_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 data)
15c4a6406   Carsten Otte   KVM: Portability:...
1201
  {
890ca9aef   Huang Ying   KVM: Add MCE support
1202
1203
  	u64 mcg_cap = vcpu->arch.mcg_cap;
  	unsigned bank_num = mcg_cap & 0xff;
15c4a6406   Carsten Otte   KVM: Portability:...
1204
  	switch (msr) {
15c4a6406   Carsten Otte   KVM: Portability:...
1205
  	case MSR_IA32_MCG_STATUS:
890ca9aef   Huang Ying   KVM: Add MCE support
1206
  		vcpu->arch.mcg_status = data;
15c4a6406   Carsten Otte   KVM: Portability:...
1207
  		break;
c7ac679c1   Joerg Roedel   KVM: emulate acce...
1208
  	case MSR_IA32_MCG_CTL:
890ca9aef   Huang Ying   KVM: Add MCE support
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
  		if (!(mcg_cap & MCG_CTL_P))
  			return 1;
  		if (data != 0 && data != ~(u64)0)
  			return -1;
  		vcpu->arch.mcg_ctl = data;
  		break;
  	default:
  		if (msr >= MSR_IA32_MC0_CTL &&
  		    msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
  			u32 offset = msr - MSR_IA32_MC0_CTL;
114be429c   Andre Przywara   KVM: allow bit 10...
1219
1220
1221
1222
1223
  			/* only 0 or all 1s can be written to IA32_MCi_CTL
  			 * some Linux kernels though clear bit 10 in bank 4 to
  			 * workaround a BIOS/GART TBL issue on AMD K8s, ignore
  			 * this to avoid an uncatched #GP in the guest
  			 */
890ca9aef   Huang Ying   KVM: Add MCE support
1224
  			if ((offset & 0x3) == 0 &&
114be429c   Andre Przywara   KVM: allow bit 10...
1225
  			    data != 0 && (data | (1 << 10)) != ~(u64)0)
890ca9aef   Huang Ying   KVM: Add MCE support
1226
1227
1228
1229
1230
1231
1232
1233
  				return -1;
  			vcpu->arch.mce_banks[offset] = data;
  			break;
  		}
  		return 1;
  	}
  	return 0;
  }
ffde22ac5   Ed Swierk   KVM: Xen PV-on-HV...
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
  static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
  {
  	struct kvm *kvm = vcpu->kvm;
  	int lm = is_long_mode(vcpu);
  	u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
  		: (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
  	u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
  		: kvm->arch.xen_hvm_config.blob_size_32;
  	u32 page_num = data & ~PAGE_MASK;
  	u64 page_addr = data & PAGE_MASK;
  	u8 *page;
  	int r;
  
  	r = -E2BIG;
  	if (page_num >= blob_size)
  		goto out;
  	r = -ENOMEM;
ff5c2c031   Sasha Levin   KVM: Use memdup_u...
1251
1252
1253
  	page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
  	if (IS_ERR(page)) {
  		r = PTR_ERR(page);
ffde22ac5   Ed Swierk   KVM: Xen PV-on-HV...
1254
  		goto out;
ff5c2c031   Sasha Levin   KVM: Use memdup_u...
1255
  	}
ffde22ac5   Ed Swierk   KVM: Xen PV-on-HV...
1256
1257
1258
1259
1260
1261
1262
1263
  	if (kvm_write_guest(kvm, page_addr, page, PAGE_SIZE))
  		goto out_free;
  	r = 0;
  out_free:
  	kfree(page);
  out:
  	return r;
  }
55cd8e5a4   Gleb Natapov   KVM: Implement ba...
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
  static bool kvm_hv_hypercall_enabled(struct kvm *kvm)
  {
  	return kvm->arch.hv_hypercall & HV_X64_MSR_HYPERCALL_ENABLE;
  }
  
  static bool kvm_hv_msr_partition_wide(u32 msr)
  {
  	bool r = false;
  	switch (msr) {
  	case HV_X64_MSR_GUEST_OS_ID:
  	case HV_X64_MSR_HYPERCALL:
  		r = true;
  		break;
  	}
  
  	return r;
  }
  
  static int set_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 data)
  {
  	struct kvm *kvm = vcpu->kvm;
  
  	switch (msr) {
  	case HV_X64_MSR_GUEST_OS_ID:
  		kvm->arch.hv_guest_os_id = data;
  		/* setting guest os id to zero disables hypercall page */
  		if (!kvm->arch.hv_guest_os_id)
  			kvm->arch.hv_hypercall &= ~HV_X64_MSR_HYPERCALL_ENABLE;
  		break;
  	case HV_X64_MSR_HYPERCALL: {
  		u64 gfn;
  		unsigned long addr;
  		u8 instructions[4];
  
  		/* if guest os id is not set hypercall should remain disabled */
  		if (!kvm->arch.hv_guest_os_id)
  			break;
  		if (!(data & HV_X64_MSR_HYPERCALL_ENABLE)) {
  			kvm->arch.hv_hypercall = data;
  			break;
  		}
  		gfn = data >> HV_X64_MSR_HYPERCALL_PAGE_ADDRESS_SHIFT;
  		addr = gfn_to_hva(kvm, gfn);
  		if (kvm_is_error_hva(addr))
  			return 1;
  		kvm_x86_ops->patch_hypercall(vcpu, instructions);
  		((unsigned char *)instructions)[3] = 0xc3; /* ret */
8b0cedff0   Xiao Guangrong   KVM: use __copy_t...
1311
  		if (__copy_to_user((void __user *)addr, instructions, 4))
55cd8e5a4   Gleb Natapov   KVM: Implement ba...
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
  			return 1;
  		kvm->arch.hv_hypercall = data;
  		break;
  	}
  	default:
  		pr_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
  			  "data 0x%llx
  ", msr, data);
  		return 1;
  	}
  	return 0;
  }
  
  static int set_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 data)
  {
10388a071   Gleb Natapov   KVM: Add HYPER-V ...
1327
1328
1329
  	switch (msr) {
  	case HV_X64_MSR_APIC_ASSIST_PAGE: {
  		unsigned long addr;
55cd8e5a4   Gleb Natapov   KVM: Implement ba...
1330

10388a071   Gleb Natapov   KVM: Add HYPER-V ...
1331
1332
1333
1334
1335
1336
1337
1338
  		if (!(data & HV_X64_MSR_APIC_ASSIST_PAGE_ENABLE)) {
  			vcpu->arch.hv_vapic = data;
  			break;
  		}
  		addr = gfn_to_hva(vcpu->kvm, data >>
  				  HV_X64_MSR_APIC_ASSIST_PAGE_ADDRESS_SHIFT);
  		if (kvm_is_error_hva(addr))
  			return 1;
8b0cedff0   Xiao Guangrong   KVM: use __copy_t...
1339
  		if (__clear_user((void __user *)addr, PAGE_SIZE))
10388a071   Gleb Natapov   KVM: Add HYPER-V ...
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
  			return 1;
  		vcpu->arch.hv_vapic = data;
  		break;
  	}
  	case HV_X64_MSR_EOI:
  		return kvm_hv_vapic_msr_write(vcpu, APIC_EOI, data);
  	case HV_X64_MSR_ICR:
  		return kvm_hv_vapic_msr_write(vcpu, APIC_ICR, data);
  	case HV_X64_MSR_TPR:
  		return kvm_hv_vapic_msr_write(vcpu, APIC_TASKPRI, data);
  	default:
  		pr_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
  			  "data 0x%llx
  ", msr, data);
  		return 1;
  	}
  
  	return 0;
55cd8e5a4   Gleb Natapov   KVM: Implement ba...
1358
  }
344d9588a   Gleb Natapov   KVM: Add PV MSR t...
1359
1360
1361
  static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
  {
  	gpa_t gpa = data & ~0x3f;
6adba5274   Gleb Natapov   KVM: Let host kno...
1362
1363
  	/* Bits 2:5 are resrved, Should be zero */
  	if (data & 0x3c)
344d9588a   Gleb Natapov   KVM: Add PV MSR t...
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
  		return 1;
  
  	vcpu->arch.apf.msr_val = data;
  
  	if (!(data & KVM_ASYNC_PF_ENABLED)) {
  		kvm_clear_async_pf_completion_queue(vcpu);
  		kvm_async_pf_hash_reset(vcpu);
  		return 0;
  	}
  
  	if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa))
  		return 1;
6adba5274   Gleb Natapov   KVM: Let host kno...
1376
  	vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
344d9588a   Gleb Natapov   KVM: Add PV MSR t...
1377
1378
1379
  	kvm_async_pf_wakeup_all(vcpu);
  	return 0;
  }
12f9a48f7   Glauber Costa   KVM: x86: release...
1380
1381
1382
1383
1384
1385
1386
  static void kvmclock_reset(struct kvm_vcpu *vcpu)
  {
  	if (vcpu->arch.time_page) {
  		kvm_release_page_dirty(vcpu->arch.time_page);
  		vcpu->arch.time_page = NULL;
  	}
  }
c9aaa8957   Glauber Costa   KVM: Steal time i...
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
  static void accumulate_steal_time(struct kvm_vcpu *vcpu)
  {
  	u64 delta;
  
  	if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
  		return;
  
  	delta = current->sched_info.run_delay - vcpu->arch.st.last_steal;
  	vcpu->arch.st.last_steal = current->sched_info.run_delay;
  	vcpu->arch.st.accum_steal = delta;
  }
  
  static void record_steal_time(struct kvm_vcpu *vcpu)
  {
  	if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
  		return;
  
  	if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
  		&vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
  		return;
  
  	vcpu->arch.st.steal.steal += vcpu->arch.st.accum_steal;
  	vcpu->arch.st.steal.version += 2;
  	vcpu->arch.st.accum_steal = 0;
  
  	kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
  		&vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
  }
15c4a6406   Carsten Otte   KVM: Portability:...
1415
1416
1417
  int kvm_set_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 data)
  {
  	switch (msr) {
15c4a6406   Carsten Otte   KVM: Portability:...
1418
  	case MSR_EFER:
b69e8caef   Roedel, Joerg   KVM: x86: Inject ...
1419
  		return set_efer(vcpu, data);
8f1589d95   Andre Przywara   KVM: ignore AMDs ...
1420
1421
  	case MSR_K7_HWCR:
  		data &= ~(u64)0x40;	/* ignore flush filter disable */
82494028d   Joerg Roedel   KVM: SVM: Ignore ...
1422
  		data &= ~(u64)0x100;	/* ignore ignne emulation enable */
8f1589d95   Andre Przywara   KVM: ignore AMDs ...
1423
1424
1425
1426
1427
1428
  		if (data != 0) {
  			pr_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx
  ",
  				data);
  			return 1;
  		}
15c4a6406   Carsten Otte   KVM: Portability:...
1429
  		break;
f7c6d1400   Andre Przywara   KVM: fix MMIO_CON...
1430
1431
1432
1433
1434
1435
1436
  	case MSR_FAM10H_MMIO_CONF_BASE:
  		if (data != 0) {
  			pr_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
  				"0x%llx
  ", data);
  			return 1;
  		}
15c4a6406   Carsten Otte   KVM: Portability:...
1437
  		break;
c323c0e5f   Andre Przywara   KVM: Ignore PCI E...
1438
  	case MSR_AMD64_NB_CFG:
c7ac679c1   Joerg Roedel   KVM: emulate acce...
1439
  		break;
b5e2fec0e   Alexander Graf   KVM: Ignore DEBUG...
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
  	case MSR_IA32_DEBUGCTLMSR:
  		if (!data) {
  			/* We support the non-activated case already */
  			break;
  		} else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
  			/* Values other than LBR and BTF are vendor-specific,
  			   thus reserved and should throw a #GP */
  			return 1;
  		}
  		pr_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop
  ",
  			__func__, data);
  		break;
15c4a6406   Carsten Otte   KVM: Portability:...
1453
1454
  	case MSR_IA32_UCODE_REV:
  	case MSR_IA32_UCODE_WRITE:
61a6bd672   Avi Kivity   KVM: Fallback sup...
1455
  	case MSR_VM_HSAVE_PA:
6098ca939   Andre Przywara   KVM: handle AMD m...
1456
  	case MSR_AMD64_PATCH_LOADER:
15c4a6406   Carsten Otte   KVM: Portability:...
1457
  		break;
9ba075a66   Avi Kivity   KVM: MTRR support
1458
1459
  	case 0x200 ... 0x2ff:
  		return set_msr_mtrr(vcpu, msr, data);
15c4a6406   Carsten Otte   KVM: Portability:...
1460
1461
1462
  	case MSR_IA32_APICBASE:
  		kvm_set_apic_base(vcpu, data);
  		break;
0105d1a52   Gleb Natapov   KVM: x2apic inter...
1463
1464
  	case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
  		return kvm_x2apic_msr_write(vcpu, msr, data);
a3e06bbe8   Liu, Jinsong   KVM: emulate lapi...
1465
1466
1467
  	case MSR_IA32_TSCDEADLINE:
  		kvm_set_lapic_tscdeadline_msr(vcpu, data);
  		break;
15c4a6406   Carsten Otte   KVM: Portability:...
1468
  	case MSR_IA32_MISC_ENABLE:
ad312c7c7   Zhang Xiantao   KVM: Portability:...
1469
  		vcpu->arch.ia32_misc_enable_msr = data;
15c4a6406   Carsten Otte   KVM: Portability:...
1470
  		break;
11c6bffa4   Glauber Costa   KVM: x86: change ...
1471
  	case MSR_KVM_WALL_CLOCK_NEW:
18068523d   Glauber de Oliveira Costa   KVM: paravirtuali...
1472
1473
1474
1475
  	case MSR_KVM_WALL_CLOCK:
  		vcpu->kvm->arch.wall_clock = data;
  		kvm_write_wall_clock(vcpu->kvm, data);
  		break;
11c6bffa4   Glauber Costa   KVM: x86: change ...
1476
  	case MSR_KVM_SYSTEM_TIME_NEW:
18068523d   Glauber de Oliveira Costa   KVM: paravirtuali...
1477
  	case MSR_KVM_SYSTEM_TIME: {
12f9a48f7   Glauber Costa   KVM: x86: release...
1478
  		kvmclock_reset(vcpu);
18068523d   Glauber de Oliveira Costa   KVM: paravirtuali...
1479
1480
  
  		vcpu->arch.time = data;
c285545f8   Zachary Amsden   KVM: x86: TSC cat...
1481
  		kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
18068523d   Glauber de Oliveira Costa   KVM: paravirtuali...
1482
1483
1484
1485
1486
1487
1488
  
  		/* we verify if the enable bit is set... */
  		if (!(data & 1))
  			break;
  
  		/* ...but clean it before doing the actual write */
  		vcpu->arch.time_offset = data & ~(PAGE_MASK | 1);
18068523d   Glauber de Oliveira Costa   KVM: paravirtuali...
1489
1490
  		vcpu->arch.time_page =
  				gfn_to_page(vcpu->kvm, data >> PAGE_SHIFT);
18068523d   Glauber de Oliveira Costa   KVM: paravirtuali...
1491
1492
1493
1494
1495
  
  		if (is_error_page(vcpu->arch.time_page)) {
  			kvm_release_page_clean(vcpu->arch.time_page);
  			vcpu->arch.time_page = NULL;
  		}
18068523d   Glauber de Oliveira Costa   KVM: paravirtuali...
1496
1497
  		break;
  	}
344d9588a   Gleb Natapov   KVM: Add PV MSR t...
1498
1499
1500
1501
  	case MSR_KVM_ASYNC_PF_EN:
  		if (kvm_pv_enable_async_pf(vcpu, data))
  			return 1;
  		break;
c9aaa8957   Glauber Costa   KVM: Steal time i...
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
  	case MSR_KVM_STEAL_TIME:
  
  		if (unlikely(!sched_info_on()))
  			return 1;
  
  		if (data & KVM_STEAL_RESERVED_MASK)
  			return 1;
  
  		if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
  							data & KVM_STEAL_VALID_BITS))
  			return 1;
  
  		vcpu->arch.st.msr_val = data;
  
  		if (!(data & KVM_MSR_ENABLED))
  			break;
  
  		vcpu->arch.st.last_steal = current->sched_info.run_delay;
  
  		preempt_disable();
  		accumulate_steal_time(vcpu);
  		preempt_enable();
  
  		kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
  
  		break;
890ca9aef   Huang Ying   KVM: Add MCE support
1528
1529
1530
1531
  	case MSR_IA32_MCG_CTL:
  	case MSR_IA32_MCG_STATUS:
  	case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
  		return set_msr_mce(vcpu, msr, data);
71db60232   Andre Przywara   KVM: Move perform...
1532
1533
1534
1535
1536
1537
1538
1539
  
  	/* Performance counters are not protected by a CPUID bit,
  	 * so we should check all of them in the generic path for the sake of
  	 * cross vendor migration.
  	 * Writing a zero into the event select MSRs disables them,
  	 * which we perfectly emulate ;-). Any other value should be at least
  	 * reported, some guests depend on them.
  	 */
71db60232   Andre Przywara   KVM: Move perform...
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
  	case MSR_K7_EVNTSEL0:
  	case MSR_K7_EVNTSEL1:
  	case MSR_K7_EVNTSEL2:
  	case MSR_K7_EVNTSEL3:
  		if (data != 0)
  			pr_unimpl(vcpu, "unimplemented perfctr wrmsr: "
  				"0x%x data 0x%llx
  ", msr, data);
  		break;
  	/* at least RHEL 4 unconditionally writes to the perfctr registers,
  	 * so we ignore writes to make it happy.
  	 */
71db60232   Andre Przywara   KVM: Move perform...
1552
1553
1554
1555
1556
1557
1558
1559
  	case MSR_K7_PERFCTR0:
  	case MSR_K7_PERFCTR1:
  	case MSR_K7_PERFCTR2:
  	case MSR_K7_PERFCTR3:
  		pr_unimpl(vcpu, "unimplemented perfctr wrmsr: "
  			"0x%x data 0x%llx
  ", msr, data);
  		break;
84e0cefa8   Jes Sorensen   KVM: Fix guest ke...
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
  	case MSR_K7_CLK_CTL:
  		/*
  		 * Ignore all writes to this no longer documented MSR.
  		 * Writes are only relevant for old K7 processors,
  		 * all pre-dating SVM, but a recommended workaround from
  		 * AMD for these chips. It is possible to speicify the
  		 * affected processor models on the command line, hence
  		 * the need to ignore the workaround.
  		 */
  		break;
55cd8e5a4   Gleb Natapov   KVM: Implement ba...
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
  	case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
  		if (kvm_hv_msr_partition_wide(msr)) {
  			int r;
  			mutex_lock(&vcpu->kvm->lock);
  			r = set_msr_hyperv_pw(vcpu, msr, data);
  			mutex_unlock(&vcpu->kvm->lock);
  			return r;
  		} else
  			return set_msr_hyperv(vcpu, msr, data);
  		break;
91c9c3eda   john cooper   KVM: x86: handle ...
1580
1581
1582
1583
1584
1585
1586
  	case MSR_IA32_BBL_CR_CTL3:
  		/* Drop writes to this legacy MSR -- see rdmsr
  		 * counterpart for further detail.
  		 */
  		pr_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx
  ", msr, data);
  		break;
15c4a6406   Carsten Otte   KVM: Portability:...
1587
  	default:
ffde22ac5   Ed Swierk   KVM: Xen PV-on-HV...
1588
1589
  		if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
  			return xen_hvm_config(vcpu, data);
f5132b013   Gleb Natapov   KVM: Expose a ver...
1590
1591
  		if (kvm_pmu_msr(vcpu, msr))
  			return kvm_pmu_set_msr(vcpu, msr, data);
ed85c0685   Andre Przywara   KVM: introduce mo...
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
  		if (!ignore_msrs) {
  			pr_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx
  ",
  				msr, data);
  			return 1;
  		} else {
  			pr_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx
  ",
  				msr, data);
  			break;
  		}
15c4a6406   Carsten Otte   KVM: Portability:...
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
  	}
  	return 0;
  }
  EXPORT_SYMBOL_GPL(kvm_set_msr_common);
  
  
  /*
   * Reads an msr value (of 'msr_index') into 'pdata'.
   * Returns 0 on success, non-0 otherwise.
   * Assumes vcpu_load() was already called.
   */
  int kvm_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
  {
  	return kvm_x86_ops->get_msr(vcpu, msr_index, pdata);
  }
9ba075a66   Avi Kivity   KVM: MTRR support
1618
1619
  static int get_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
  {
0bed3b568   Sheng Yang   KVM: Improve MTRR...
1620
  	u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
9ba075a66   Avi Kivity   KVM: MTRR support
1621
1622
  	if (!msr_mtrr_valid(msr))
  		return 1;
0bed3b568   Sheng Yang   KVM: Improve MTRR...
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
  	if (msr == MSR_MTRRdefType)
  		*pdata = vcpu->arch.mtrr_state.def_type +
  			 (vcpu->arch.mtrr_state.enabled << 10);
  	else if (msr == MSR_MTRRfix64K_00000)
  		*pdata = p[0];
  	else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
  		*pdata = p[1 + msr - MSR_MTRRfix16K_80000];
  	else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
  		*pdata = p[3 + msr - MSR_MTRRfix4K_C0000];
  	else if (msr == MSR_IA32_CR_PAT)
  		*pdata = vcpu->arch.pat;
  	else {	/* Variable MTRRs */
  		int idx, is_mtrr_mask;
  		u64 *pt;
  
  		idx = (msr - 0x200) / 2;
  		is_mtrr_mask = msr - 0x200 - 2 * idx;
  		if (!is_mtrr_mask)
  			pt =
  			  (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
  		else
  			pt =
  			  (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
  		*pdata = *pt;
  	}
9ba075a66   Avi Kivity   KVM: MTRR support
1648
1649
  	return 0;
  }
890ca9aef   Huang Ying   KVM: Add MCE support
1650
  static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
15c4a6406   Carsten Otte   KVM: Portability:...
1651
1652
  {
  	u64 data;
890ca9aef   Huang Ying   KVM: Add MCE support
1653
1654
  	u64 mcg_cap = vcpu->arch.mcg_cap;
  	unsigned bank_num = mcg_cap & 0xff;
15c4a6406   Carsten Otte   KVM: Portability:...
1655
1656
  
  	switch (msr) {
15c4a6406   Carsten Otte   KVM: Portability:...
1657
1658
  	case MSR_IA32_P5_MC_ADDR:
  	case MSR_IA32_P5_MC_TYPE:
890ca9aef   Huang Ying   KVM: Add MCE support
1659
1660
  		data = 0;
  		break;
15c4a6406   Carsten Otte   KVM: Portability:...
1661
  	case MSR_IA32_MCG_CAP:
890ca9aef   Huang Ying   KVM: Add MCE support
1662
1663
  		data = vcpu->arch.mcg_cap;
  		break;
c7ac679c1   Joerg Roedel   KVM: emulate acce...
1664
  	case MSR_IA32_MCG_CTL:
890ca9aef   Huang Ying   KVM: Add MCE support
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
  		if (!(mcg_cap & MCG_CTL_P))
  			return 1;
  		data = vcpu->arch.mcg_ctl;
  		break;
  	case MSR_IA32_MCG_STATUS:
  		data = vcpu->arch.mcg_status;
  		break;
  	default:
  		if (msr >= MSR_IA32_MC0_CTL &&
  		    msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
  			u32 offset = msr - MSR_IA32_MC0_CTL;
  			data = vcpu->arch.mce_banks[offset];
  			break;
  		}
  		return 1;
  	}
  	*pdata = data;
  	return 0;
  }
55cd8e5a4   Gleb Natapov   KVM: Implement ba...
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
  static int get_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
  {
  	u64 data = 0;
  	struct kvm *kvm = vcpu->kvm;
  
  	switch (msr) {
  	case HV_X64_MSR_GUEST_OS_ID:
  		data = kvm->arch.hv_guest_os_id;
  		break;
  	case HV_X64_MSR_HYPERCALL:
  		data = kvm->arch.hv_hypercall;
  		break;
  	default:
  		pr_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x
  ", msr);
  		return 1;
  	}
  
  	*pdata = data;
  	return 0;
  }
  
  static int get_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
  {
  	u64 data = 0;
  
  	switch (msr) {
  	case HV_X64_MSR_VP_INDEX: {
  		int r;
  		struct kvm_vcpu *v;
  		kvm_for_each_vcpu(r, v, vcpu->kvm)
  			if (v == vcpu)
  				data = r;
  		break;
  	}
10388a071   Gleb Natapov   KVM: Add HYPER-V ...
1719
1720
1721
1722
1723
1724
  	case HV_X64_MSR_EOI:
  		return kvm_hv_vapic_msr_read(vcpu, APIC_EOI, pdata);
  	case HV_X64_MSR_ICR:
  		return kvm_hv_vapic_msr_read(vcpu, APIC_ICR, pdata);
  	case HV_X64_MSR_TPR:
  		return kvm_hv_vapic_msr_read(vcpu, APIC_TASKPRI, pdata);
14fa67ee9   Mike Waychison   KVM: x86: get_msr...
1725
  	case HV_X64_MSR_APIC_ASSIST_PAGE:
d1613ad5d   Mike Waychison   KVM: Really fix H...
1726
1727
  		data = vcpu->arch.hv_vapic;
  		break;
55cd8e5a4   Gleb Natapov   KVM: Implement ba...
1728
1729
1730
1731
1732
1733
1734
1735
  	default:
  		pr_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x
  ", msr);
  		return 1;
  	}
  	*pdata = data;
  	return 0;
  }
890ca9aef   Huang Ying   KVM: Add MCE support
1736
1737
1738
1739
1740
  int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
  {
  	u64 data;
  
  	switch (msr) {
890ca9aef   Huang Ying   KVM: Add MCE support
1741
  	case MSR_IA32_PLATFORM_ID:
15c4a6406   Carsten Otte   KVM: Portability:...
1742
  	case MSR_IA32_EBL_CR_POWERON:
b5e2fec0e   Alexander Graf   KVM: Ignore DEBUG...
1743
1744
1745
1746
1747
  	case MSR_IA32_DEBUGCTLMSR:
  	case MSR_IA32_LASTBRANCHFROMIP:
  	case MSR_IA32_LASTBRANCHTOIP:
  	case MSR_IA32_LASTINTFROMIP:
  	case MSR_IA32_LASTINTTOIP:
60af2ecdc   Jaswinder Singh Rajput   KVM: Use MSR name...
1748
1749
  	case MSR_K8_SYSCFG:
  	case MSR_K7_HWCR:
61a6bd672   Avi Kivity   KVM: Fallback sup...
1750
  	case MSR_VM_HSAVE_PA:
9e6996240   Amit Shah   KVM: Ignore reads...
1751
  	case MSR_K7_EVNTSEL0:
1f3ee616d   Amit Shah   KVM: ignore reads...
1752
  	case MSR_K7_PERFCTR0:
1fdbd48c2   Andre Przywara   KVM: ignore reads...
1753
  	case MSR_K8_INT_PENDING_MSG:
c323c0e5f   Andre Przywara   KVM: Ignore PCI E...
1754
  	case MSR_AMD64_NB_CFG:
f7c6d1400   Andre Przywara   KVM: fix MMIO_CON...
1755
  	case MSR_FAM10H_MMIO_CONF_BASE:
15c4a6406   Carsten Otte   KVM: Portability:...
1756
1757
  		data = 0;
  		break;
742bc6704   Marcelo Tosatti   KVM: x86: report ...
1758
1759
1760
  	case MSR_IA32_UCODE_REV:
  		data = 0x100000000ULL;
  		break;
9ba075a66   Avi Kivity   KVM: MTRR support
1761
1762
1763
1764
1765
  	case MSR_MTRRcap:
  		data = 0x500 | KVM_NR_VAR_MTRR;
  		break;
  	case 0x200 ... 0x2ff:
  		return get_msr_mtrr(vcpu, msr, pdata);
15c4a6406   Carsten Otte   KVM: Portability:...
1766
1767
1768
  	case 0xcd: /* fsb frequency */
  		data = 3;
  		break;
7b9140982   Jes Sorensen   KVM: x86: Emulate...
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
  		/*
  		 * MSR_EBC_FREQUENCY_ID
  		 * Conservative value valid for even the basic CPU models.
  		 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
  		 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
  		 * and 266MHz for model 3, or 4. Set Core Clock
  		 * Frequency to System Bus Frequency Ratio to 1 (bits
  		 * 31:24) even though these are only valid for CPU
  		 * models > 2, however guests may end up dividing or
  		 * multiplying by zero otherwise.
  		 */
  	case MSR_EBC_FREQUENCY_ID:
  		data = 1 << 24;
  		break;
15c4a6406   Carsten Otte   KVM: Portability:...
1783
1784
1785
  	case MSR_IA32_APICBASE:
  		data = kvm_get_apic_base(vcpu);
  		break;
0105d1a52   Gleb Natapov   KVM: x2apic inter...
1786
1787
1788
  	case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
  		return kvm_x2apic_msr_read(vcpu, msr, pdata);
  		break;
a3e06bbe8   Liu, Jinsong   KVM: emulate lapi...
1789
1790
1791
  	case MSR_IA32_TSCDEADLINE:
  		data = kvm_get_lapic_tscdeadline_msr(vcpu);
  		break;
15c4a6406   Carsten Otte   KVM: Portability:...
1792
  	case MSR_IA32_MISC_ENABLE:
ad312c7c7   Zhang Xiantao   KVM: Portability:...
1793
  		data = vcpu->arch.ia32_misc_enable_msr;
15c4a6406   Carsten Otte   KVM: Portability:...
1794
  		break;
847f0ad8c   Alexander Graf   KVM: Implement du...
1795
1796
1797
1798
1799
1800
  	case MSR_IA32_PERF_STATUS:
  		/* TSC increment by tick */
  		data = 1000ULL;
  		/* CPU multiplier */
  		data |= (((uint64_t)4ULL) << 40);
  		break;
15c4a6406   Carsten Otte   KVM: Portability:...
1801
  	case MSR_EFER:
f6801dff2   Avi Kivity   KVM: Rename vcpu-...
1802
  		data = vcpu->arch.efer;
15c4a6406   Carsten Otte   KVM: Portability:...
1803
  		break;
18068523d   Glauber de Oliveira Costa   KVM: paravirtuali...
1804
  	case MSR_KVM_WALL_CLOCK:
11c6bffa4   Glauber Costa   KVM: x86: change ...
1805
  	case MSR_KVM_WALL_CLOCK_NEW:
18068523d   Glauber de Oliveira Costa   KVM: paravirtuali...
1806
1807
1808
  		data = vcpu->kvm->arch.wall_clock;
  		break;
  	case MSR_KVM_SYSTEM_TIME:
11c6bffa4   Glauber Costa   KVM: x86: change ...
1809
  	case MSR_KVM_SYSTEM_TIME_NEW:
18068523d   Glauber de Oliveira Costa   KVM: paravirtuali...
1810
1811
  		data = vcpu->arch.time;
  		break;
344d9588a   Gleb Natapov   KVM: Add PV MSR t...
1812
1813
1814
  	case MSR_KVM_ASYNC_PF_EN:
  		data = vcpu->arch.apf.msr_val;
  		break;
c9aaa8957   Glauber Costa   KVM: Steal time i...
1815
1816
1817
  	case MSR_KVM_STEAL_TIME:
  		data = vcpu->arch.st.msr_val;
  		break;
890ca9aef   Huang Ying   KVM: Add MCE support
1818
1819
1820
1821
1822
1823
1824
  	case MSR_IA32_P5_MC_ADDR:
  	case MSR_IA32_P5_MC_TYPE:
  	case MSR_IA32_MCG_CAP:
  	case MSR_IA32_MCG_CTL:
  	case MSR_IA32_MCG_STATUS:
  	case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
  		return get_msr_mce(vcpu, msr, pdata);
84e0cefa8   Jes Sorensen   KVM: Fix guest ke...
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
  	case MSR_K7_CLK_CTL:
  		/*
  		 * Provide expected ramp-up count for K7. All other
  		 * are set to zero, indicating minimum divisors for
  		 * every field.
  		 *
  		 * This prevents guest kernels on AMD host with CPU
  		 * type 6, model 8 and higher from exploding due to
  		 * the rdmsr failing.
  		 */
  		data = 0x20000000;
  		break;
55cd8e5a4   Gleb Natapov   KVM: Implement ba...
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
  	case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
  		if (kvm_hv_msr_partition_wide(msr)) {
  			int r;
  			mutex_lock(&vcpu->kvm->lock);
  			r = get_msr_hyperv_pw(vcpu, msr, pdata);
  			mutex_unlock(&vcpu->kvm->lock);
  			return r;
  		} else
  			return get_msr_hyperv(vcpu, msr, pdata);
  		break;
91c9c3eda   john cooper   KVM: x86: handle ...
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
  	case MSR_IA32_BBL_CR_CTL3:
  		/* This legacy MSR exists but isn't fully documented in current
  		 * silicon.  It is however accessed by winxp in very narrow
  		 * scenarios where it sets bit #19, itself documented as
  		 * a "reserved" bit.  Best effort attempt to source coherent
  		 * read data here should the balance of the register be
  		 * interpreted by the guest:
  		 *
  		 * L2 cache control register 3: 64GB range, 256KB size,
  		 * enabled, latency 0x1, configured
  		 */
  		data = 0xbe702111;
  		break;
15c4a6406   Carsten Otte   KVM: Portability:...
1860
  	default:
f5132b013   Gleb Natapov   KVM: Expose a ver...
1861
1862
  		if (kvm_pmu_msr(vcpu, msr))
  			return kvm_pmu_get_msr(vcpu, msr, pdata);
ed85c0685   Andre Przywara   KVM: introduce mo...
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
  		if (!ignore_msrs) {
  			pr_unimpl(vcpu, "unhandled rdmsr: 0x%x
  ", msr);
  			return 1;
  		} else {
  			pr_unimpl(vcpu, "ignored rdmsr: 0x%x
  ", msr);
  			data = 0;
  		}
  		break;
15c4a6406   Carsten Otte   KVM: Portability:...
1873
1874
1875
1876
1877
  	}
  	*pdata = data;
  	return 0;
  }
  EXPORT_SYMBOL_GPL(kvm_get_msr_common);
313a3dc75   Carsten Otte   KVM: Portability:...
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
  /*
   * Read or write a bunch of msrs. All parameters are kernel addresses.
   *
   * @return number of msrs set successfully.
   */
  static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
  		    struct kvm_msr_entry *entries,
  		    int (*do_msr)(struct kvm_vcpu *vcpu,
  				  unsigned index, u64 *data))
  {
f656ce018   Marcelo Tosatti   KVM: switch vcpu ...
1888
  	int i, idx;
313a3dc75   Carsten Otte   KVM: Portability:...
1889

f656ce018   Marcelo Tosatti   KVM: switch vcpu ...
1890
  	idx = srcu_read_lock(&vcpu->kvm->srcu);
313a3dc75   Carsten Otte   KVM: Portability:...
1891
1892
1893
  	for (i = 0; i < msrs->nmsrs; ++i)
  		if (do_msr(vcpu, entries[i].index, &entries[i].data))
  			break;
f656ce018   Marcelo Tosatti   KVM: switch vcpu ...
1894
  	srcu_read_unlock(&vcpu->kvm->srcu, idx);
313a3dc75   Carsten Otte   KVM: Portability:...
1895

313a3dc75   Carsten Otte   KVM: Portability:...
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
  	return i;
  }
  
  /*
   * Read or write a bunch of msrs. Parameters are user addresses.
   *
   * @return number of msrs set successfully.
   */
  static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
  		  int (*do_msr)(struct kvm_vcpu *vcpu,
  				unsigned index, u64 *data),
  		  int writeback)
  {
  	struct kvm_msrs msrs;
  	struct kvm_msr_entry *entries;
  	int r, n;
  	unsigned size;
  
  	r = -EFAULT;
  	if (copy_from_user(&msrs, user_msrs, sizeof msrs))
  		goto out;
  
  	r = -E2BIG;
  	if (msrs.nmsrs >= MAX_IO_MSRS)
  		goto out;
313a3dc75   Carsten Otte   KVM: Portability:...
1921
  	size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
ff5c2c031   Sasha Levin   KVM: Use memdup_u...
1922
1923
1924
  	entries = memdup_user(user_msrs->entries, size);
  	if (IS_ERR(entries)) {
  		r = PTR_ERR(entries);
313a3dc75   Carsten Otte   KVM: Portability:...
1925
  		goto out;
ff5c2c031   Sasha Levin   KVM: Use memdup_u...
1926
  	}
313a3dc75   Carsten Otte   KVM: Portability:...
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
  
  	r = n = __msr_io(vcpu, &msrs, entries, do_msr);
  	if (r < 0)
  		goto out_free;
  
  	r = -EFAULT;
  	if (writeback && copy_to_user(user_msrs->entries, entries, size))
  		goto out_free;
  
  	r = n;
  
  out_free:
7a73c0283   Avi Kivity   KVM: Use kmalloc(...
1939
  	kfree(entries);
313a3dc75   Carsten Otte   KVM: Portability:...
1940
1941
1942
  out:
  	return r;
  }
018d00d2f   Zhang Xiantao   KVM: Portability:...
1943
1944
1945
1946
1947
1948
1949
1950
  int kvm_dev_ioctl_check_extension(long ext)
  {
  	int r;
  
  	switch (ext) {
  	case KVM_CAP_IRQCHIP:
  	case KVM_CAP_HLT:
  	case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
018d00d2f   Zhang Xiantao   KVM: Portability:...
1951
  	case KVM_CAP_SET_TSS_ADDR:
077167174   Dan Kenigsberg   KVM: Enhance gues...
1952
  	case KVM_CAP_EXT_CPUID:
c80766040   Gerd Hoffmann   KVM: Fix kvmclock...
1953
  	case KVM_CAP_CLOCKSOURCE:
7837699fa   Sheng Yang   KVM: In kernel PI...
1954
  	case KVM_CAP_PIT:
a28e4f5a6   Marcelo Tosatti   KVM: add basic pa...
1955
  	case KVM_CAP_NOP_IO_DELAY:
62d9f0dbc   Marcelo Tosatti   KVM: add ioctls t...
1956
  	case KVM_CAP_MP_STATE:
ed8486243   Avi Kivity   KVM: Advertise sy...
1957
  	case KVM_CAP_SYNC_MMU:
a355c85c5   Lai Jiangshan   KVM: return true ...
1958
  	case KVM_CAP_USER_NMI:
52d939a0b   Marcelo Tosatti   KVM: PIT: provide...
1959
  	case KVM_CAP_REINJECT_CONTROL:
4925663a0   Gleb Natapov   KVM: Report IRQ i...
1960
  	case KVM_CAP_IRQ_INJECT_STATUS:
e56d532f2   Sheng Yang   KVM: Device assig...
1961
  	case KVM_CAP_ASSIGN_DEV_IRQ:
721eecbf4   Gregory Haskins   KVM: irqfd
1962
  	case KVM_CAP_IRQFD:
d34e6b175   Gregory Haskins   KVM: add ioeventf...
1963
  	case KVM_CAP_IOEVENTFD:
c5ff41ce6   Jan Kiszka   KVM: Allow PIT em...
1964
  	case KVM_CAP_PIT2:
e9f427573   Beth Kon   KVM: PIT support ...
1965
  	case KVM_CAP_PIT_STATE2:
b927a3cec   Sheng Yang   KVM: VMX: Introdu...
1966
  	case KVM_CAP_SET_IDENTITY_MAP_ADDR:
ffde22ac5   Ed Swierk   KVM: Xen PV-on-HV...
1967
  	case KVM_CAP_XEN_HVM:
afbcf7ab8   Glauber Costa   KVM: allow usersp...
1968
  	case KVM_CAP_ADJUST_CLOCK:
3cfc3092f   Jan Kiszka   KVM: x86: Add KVM...
1969
  	case KVM_CAP_VCPU_EVENTS:
55cd8e5a4   Gleb Natapov   KVM: Implement ba...
1970
  	case KVM_CAP_HYPERV:
10388a071   Gleb Natapov   KVM: Add HYPER-V ...
1971
  	case KVM_CAP_HYPERV_VAPIC:
c25bc1638   Gleb Natapov   KVM: Implement No...
1972
  	case KVM_CAP_HYPERV_SPIN:
ab9f4ecbb   Zhai, Edwin   KVM: enable PCI m...
1973
  	case KVM_CAP_PCI_SEGMENT:
a1efbe77c   Jan Kiszka   KVM: x86: Add sup...
1974
  	case KVM_CAP_DEBUGREGS:
d2be1651b   Jan Kiszka   KVM: x86: Add KVM...
1975
  	case KVM_CAP_X86_ROBUST_SINGLESTEP:
2d5b5a665   Sheng Yang   KVM: x86: XSAVE/X...
1976
  	case KVM_CAP_XSAVE:
344d9588a   Gleb Natapov   KVM: Add PV MSR t...
1977
  	case KVM_CAP_ASYNC_PF:
92a1f12d2   Joerg Roedel   KVM: X86: Impleme...
1978
  	case KVM_CAP_GET_TSC_KHZ:
018d00d2f   Zhang Xiantao   KVM: Portability:...
1979
1980
  		r = 1;
  		break;
542472b53   Laurent Vivier   KVM: Add coalesce...
1981
1982
1983
  	case KVM_CAP_COALESCED_MMIO:
  		r = KVM_COALESCED_MMIO_PAGE_OFFSET;
  		break;
774ead3ad   Avi Kivity   KVM: Disable vapi...
1984
1985
1986
  	case KVM_CAP_VAPIC:
  		r = !kvm_x86_ops->cpu_has_accelerated_tpr();
  		break;
f725230af   Avi Kivity   KVM: Add API to r...
1987
  	case KVM_CAP_NR_VCPUS:
8c3ba334f   Sasha Levin   KVM: x86: Raise t...
1988
1989
1990
  		r = KVM_SOFT_MAX_VCPUS;
  		break;
  	case KVM_CAP_MAX_VCPUS:
f725230af   Avi Kivity   KVM: Add API to r...
1991
1992
  		r = KVM_MAX_VCPUS;
  		break;
a988b910e   Avi Kivity   KVM: Add API for ...
1993
1994
1995
  	case KVM_CAP_NR_MEMSLOTS:
  		r = KVM_MEMORY_SLOTS;
  		break;
a68a6a728   Marcelo Tosatti   KVM: x86: disable...
1996
1997
  	case KVM_CAP_PV_MMU:	/* obsolete */
  		r = 0;
2f333bcb4   Marcelo Tosatti   KVM: MMU: hyperca...
1998
  		break;
62c476c7c   Ben-Ami Yassour   KVM: Device Assig...
1999
  	case KVM_CAP_IOMMU:
a1b60c1cd   Joerg Roedel   iommu/core: Conve...
2000
  		r = iommu_present(&pci_bus_type);
62c476c7c   Ben-Ami Yassour   KVM: Device Assig...
2001
  		break;
890ca9aef   Huang Ying   KVM: Add MCE support
2002
2003
2004
  	case KVM_CAP_MCE:
  		r = KVM_MAX_MCE_BANKS;
  		break;
2d5b5a665   Sheng Yang   KVM: x86: XSAVE/X...
2005
2006
2007
  	case KVM_CAP_XCRS:
  		r = cpu_has_xsave;
  		break;
92a1f12d2   Joerg Roedel   KVM: X86: Impleme...
2008
2009
2010
  	case KVM_CAP_TSC_CONTROL:
  		r = kvm_has_tsc_control;
  		break;
4d25a066b   Jan Kiszka   KVM: Don't automa...
2011
2012
2013
  	case KVM_CAP_TSC_DEADLINE_TIMER:
  		r = boot_cpu_has(X86_FEATURE_TSC_DEADLINE_TIMER);
  		break;
018d00d2f   Zhang Xiantao   KVM: Portability:...
2014
2015
2016
2017
2018
2019
2020
  	default:
  		r = 0;
  		break;
  	}
  	return r;
  
  }
043405e10   Carsten Otte   KVM: Move x86 msr...
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
  long kvm_arch_dev_ioctl(struct file *filp,
  			unsigned int ioctl, unsigned long arg)
  {
  	void __user *argp = (void __user *)arg;
  	long r;
  
  	switch (ioctl) {
  	case KVM_GET_MSR_INDEX_LIST: {
  		struct kvm_msr_list __user *user_msr_list = argp;
  		struct kvm_msr_list msr_list;
  		unsigned n;
  
  		r = -EFAULT;
  		if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
  			goto out;
  		n = msr_list.nmsrs;
  		msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
  		if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
  			goto out;
  		r = -E2BIG;
e125e7b69   Jan Kiszka   KVM: Fix KVM_GET_...
2041
  		if (n < msr_list.nmsrs)
043405e10   Carsten Otte   KVM: Move x86 msr...
2042
2043
2044
2045
2046
  			goto out;
  		r = -EFAULT;
  		if (copy_to_user(user_msr_list->indices, &msrs_to_save,
  				 num_msrs_to_save * sizeof(u32)))
  			goto out;
e125e7b69   Jan Kiszka   KVM: Fix KVM_GET_...
2047
  		if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
043405e10   Carsten Otte   KVM: Move x86 msr...
2048
2049
2050
2051
2052
2053
  				 &emulated_msrs,
  				 ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
  			goto out;
  		r = 0;
  		break;
  	}
674eea0fc   Avi Kivity   KVM: Make the sup...
2054
2055
2056
2057
2058
2059
2060
2061
  	case KVM_GET_SUPPORTED_CPUID: {
  		struct kvm_cpuid2 __user *cpuid_arg = argp;
  		struct kvm_cpuid2 cpuid;
  
  		r = -EFAULT;
  		if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
  			goto out;
  		r = kvm_dev_ioctl_get_supported_cpuid(&cpuid,
193554750   Amit Shah   KVM: x86: Fix typ...
2062
  						      cpuid_arg->entries);
674eea0fc   Avi Kivity   KVM: Make the sup...
2063
2064
2065
2066
2067
2068
2069
2070
2071
  		if (r)
  			goto out;
  
  		r = -EFAULT;
  		if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
  			goto out;
  		r = 0;
  		break;
  	}
890ca9aef   Huang Ying   KVM: Add MCE support
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
  	case KVM_X86_GET_MCE_CAP_SUPPORTED: {
  		u64 mce_cap;
  
  		mce_cap = KVM_MCE_CAP_SUPPORTED;
  		r = -EFAULT;
  		if (copy_to_user(argp, &mce_cap, sizeof mce_cap))
  			goto out;
  		r = 0;
  		break;
  	}
043405e10   Carsten Otte   KVM: Move x86 msr...
2082
2083
2084
2085
2086
2087
  	default:
  		r = -EINVAL;
  	}
  out:
  	return r;
  }
f5f48ee15   Sheng Yang   KVM: VMX: Execute...
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
  static void wbinvd_ipi(void *garbage)
  {
  	wbinvd();
  }
  
  static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
  {
  	return vcpu->kvm->arch.iommu_domain &&
  		!(vcpu->kvm->arch.iommu_flags & KVM_IOMMU_CACHE_COHERENCY);
  }
313a3dc75   Carsten Otte   KVM: Portability:...
2098
2099
  void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
  {
f5f48ee15   Sheng Yang   KVM: VMX: Execute...
2100
2101
2102
2103
2104
2105
2106
2107
  	/* Address WBINVD may be executed by guest */
  	if (need_emulate_wbinvd(vcpu)) {
  		if (kvm_x86_ops->has_wbinvd_exit())
  			cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
  		else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
  			smp_call_function_single(vcpu->cpu,
  					wbinvd_ipi, NULL, 1);
  	}
313a3dc75   Carsten Otte   KVM: Portability:...
2108
  	kvm_x86_ops->vcpu_load(vcpu, cpu);
48434c20e   Zachary Amsden   KVM: x86: Fix dee...
2109
  	if (unlikely(vcpu->cpu != cpu) || check_tsc_unstable()) {
e48672fa2   Zachary Amsden   KVM: x86: Unify T...
2110
  		/* Make sure TSC doesn't go backwards */
8f6055cba   Joerg Roedel   KVM: X86: Make ts...
2111
2112
  		s64 tsc_delta;
  		u64 tsc;
d5c1785d2   Nadav Har'El   KVM: L1 TSC handling
2113
  		tsc = kvm_x86_ops->read_l1_tsc(vcpu);
8f6055cba   Joerg Roedel   KVM: X86: Make ts...
2114
2115
  		tsc_delta = !vcpu->arch.last_guest_tsc ? 0 :
  			     tsc - vcpu->arch.last_guest_tsc;
e48672fa2   Zachary Amsden   KVM: x86: Unify T...
2116
2117
  		if (tsc_delta < 0)
  			mark_tsc_unstable("KVM discovered backwards TSC");
c285545f8   Zachary Amsden   KVM: x86: TSC cat...
2118
  		if (check_tsc_unstable()) {
e48672fa2   Zachary Amsden   KVM: x86: Unify T...
2119
  			kvm_x86_ops->adjust_tsc_offset(vcpu, -tsc_delta);
c285545f8   Zachary Amsden   KVM: x86: TSC cat...
2120
  			vcpu->arch.tsc_catchup = 1;
c285545f8   Zachary Amsden   KVM: x86: TSC cat...
2121
  		}
1aa8ceef0   Nikola Ciprich   KVM: fix kvmclock...
2122
  		kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
c285545f8   Zachary Amsden   KVM: x86: TSC cat...
2123
2124
  		if (vcpu->cpu != cpu)
  			kvm_migrate_timers(vcpu);
e48672fa2   Zachary Amsden   KVM: x86: Unify T...
2125
  		vcpu->cpu = cpu;
6b7d7e762   Zachary Amsden   KVM: x86: Harden ...
2126
  	}
c9aaa8957   Glauber Costa   KVM: Steal time i...
2127
2128
2129
  
  	accumulate_steal_time(vcpu);
  	kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
313a3dc75   Carsten Otte   KVM: Portability:...
2130
2131
2132
2133
  }
  
  void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
  {
02daab21d   Avi Kivity   KVM: Lazify fpu a...
2134
  	kvm_x86_ops->vcpu_put(vcpu);
1c11e7135   Avi Kivity   KVM: VMX: Avoid w...
2135
  	kvm_put_guest_fpu(vcpu);
d5c1785d2   Nadav Har'El   KVM: L1 TSC handling
2136
  	vcpu->arch.last_guest_tsc = kvm_x86_ops->read_l1_tsc(vcpu);
313a3dc75   Carsten Otte   KVM: Portability:...
2137
  }
313a3dc75   Carsten Otte   KVM: Portability:...
2138
2139
2140
  static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
  				    struct kvm_lapic_state *s)
  {
ad312c7c7   Zhang Xiantao   KVM: Portability:...
2141
  	memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
313a3dc75   Carsten Otte   KVM: Portability:...
2142
2143
2144
2145
2146
2147
2148
  
  	return 0;
  }
  
  static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
  				    struct kvm_lapic_state *s)
  {
ad312c7c7   Zhang Xiantao   KVM: Portability:...
2149
  	memcpy(vcpu->arch.apic->regs, s->regs, sizeof *s);
313a3dc75   Carsten Otte   KVM: Portability:...
2150
  	kvm_apic_post_state_restore(vcpu);
cb142eb74   Gleb Natapov   KVM: Update cr8 i...
2151
  	update_cr8_intercept(vcpu);
313a3dc75   Carsten Otte   KVM: Portability:...
2152
2153
2154
  
  	return 0;
  }
f77bc6a42   Zhang Xiantao   KVM: Portability:...
2155
2156
2157
2158
2159
2160
2161
  static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
  				    struct kvm_interrupt *irq)
  {
  	if (irq->irq < 0 || irq->irq >= 256)
  		return -EINVAL;
  	if (irqchip_in_kernel(vcpu->kvm))
  		return -ENXIO;
f77bc6a42   Zhang Xiantao   KVM: Portability:...
2162

66fd3f7f9   Gleb Natapov   KVM: Do not re-ex...
2163
  	kvm_queue_interrupt(vcpu, irq->irq, false);
3842d135f   Avi Kivity   KVM: Check for pe...
2164
  	kvm_make_request(KVM_REQ_EVENT, vcpu);
f77bc6a42   Zhang Xiantao   KVM: Portability:...
2165

f77bc6a42   Zhang Xiantao   KVM: Portability:...
2166
2167
  	return 0;
  }
c4abb7c9c   Jan Kiszka   KVM: x86: Support...
2168
2169
  static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
  {
c4abb7c9c   Jan Kiszka   KVM: x86: Support...
2170
  	kvm_inject_nmi(vcpu);
c4abb7c9c   Jan Kiszka   KVM: x86: Support...
2171
2172
2173
  
  	return 0;
  }
b209749f5   Avi Kivity   KVM: local APIC T...
2174
2175
2176
2177
2178
2179
2180
2181
  static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
  					   struct kvm_tpr_access_ctl *tac)
  {
  	if (tac->flags)
  		return -EINVAL;
  	vcpu->arch.tpr_access_reporting = !!tac->enabled;
  	return 0;
  }
890ca9aef   Huang Ying   KVM: Add MCE support
2182
2183
2184
2185
2186
2187
2188
  static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
  					u64 mcg_cap)
  {
  	int r;
  	unsigned bank_num = mcg_cap & 0xff, bank;
  
  	r = -EINVAL;
a9e38c3e0   Jan Kiszka   KVM: x86: Catch p...
2189
  	if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
890ca9aef   Huang Ying   KVM: Add MCE support
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
  		goto out;
  	if (mcg_cap & ~(KVM_MCE_CAP_SUPPORTED | 0xff | 0xff0000))
  		goto out;
  	r = 0;
  	vcpu->arch.mcg_cap = mcg_cap;
  	/* Init IA32_MCG_CTL to all 1s */
  	if (mcg_cap & MCG_CTL_P)
  		vcpu->arch.mcg_ctl = ~(u64)0;
  	/* Init IA32_MCi_CTL to all 1s */
  	for (bank = 0; bank < bank_num; bank++)
  		vcpu->arch.mce_banks[bank*4] = ~(u64)0;
  out:
  	return r;
  }
  
  static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
  				      struct kvm_x86_mce *mce)
  {
  	u64 mcg_cap = vcpu->arch.mcg_cap;
  	unsigned bank_num = mcg_cap & 0xff;
  	u64 *banks = vcpu->arch.mce_banks;
  
  	if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
  		return -EINVAL;
  	/*
  	 * if IA32_MCG_CTL is not all 1s, the uncorrected error
  	 * reporting is disabled
  	 */
  	if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
  	    vcpu->arch.mcg_ctl != ~(u64)0)
  		return 0;
  	banks += 4 * mce->bank;
  	/*
  	 * if IA32_MCi_CTL is not all 1s, the uncorrected error
  	 * reporting is disabled for the bank
  	 */
  	if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
  		return 0;
  	if (mce->status & MCI_STATUS_UC) {
  		if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
fc78f5193   Avi Kivity   KVM: Add accessor...
2230
  		    !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
a8eeb04a4   Avi Kivity   KVM: Add mini-API...
2231
  			kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
890ca9aef   Huang Ying   KVM: Add MCE support
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
  			return 0;
  		}
  		if (banks[1] & MCI_STATUS_VAL)
  			mce->status |= MCI_STATUS_OVER;
  		banks[2] = mce->addr;
  		banks[3] = mce->misc;
  		vcpu->arch.mcg_status = mce->mcg_status;
  		banks[1] = mce->status;
  		kvm_queue_exception(vcpu, MC_VECTOR);
  	} else if (!(banks[1] & MCI_STATUS_VAL)
  		   || !(banks[1] & MCI_STATUS_UC)) {
  		if (banks[1] & MCI_STATUS_VAL)
  			mce->status |= MCI_STATUS_OVER;
  		banks[2] = mce->addr;
  		banks[3] = mce->misc;
  		banks[1] = mce->status;
  	} else
  		banks[1] |= MCI_STATUS_OVER;
  	return 0;
  }
3cfc3092f   Jan Kiszka   KVM: x86: Add KVM...
2252
2253
2254
  static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
  					       struct kvm_vcpu_events *events)
  {
7460fb4a3   Avi Kivity   KVM: Fix simultan...
2255
  	process_nmi(vcpu);
03b82a30e   Jan Kiszka   KVM: x86: Do not ...
2256
2257
2258
  	events->exception.injected =
  		vcpu->arch.exception.pending &&
  		!kvm_exception_is_soft(vcpu->arch.exception.nr);
3cfc3092f   Jan Kiszka   KVM: x86: Add KVM...
2259
2260
  	events->exception.nr = vcpu->arch.exception.nr;
  	events->exception.has_error_code = vcpu->arch.exception.has_error_code;
97e69aa62   Vasiliy Kulikov   KVM: x86: fix inf...
2261
  	events->exception.pad = 0;
3cfc3092f   Jan Kiszka   KVM: x86: Add KVM...
2262
  	events->exception.error_code = vcpu->arch.exception.error_code;
03b82a30e   Jan Kiszka   KVM: x86: Do not ...
2263
2264
  	events->interrupt.injected =
  		vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
3cfc3092f   Jan Kiszka   KVM: x86: Add KVM...
2265
  	events->interrupt.nr = vcpu->arch.interrupt.nr;
03b82a30e   Jan Kiszka   KVM: x86: Do not ...
2266
  	events->interrupt.soft = 0;
48005f64d   Jan Kiszka   KVM: x86: Save&re...
2267
2268
2269
  	events->interrupt.shadow =
  		kvm_x86_ops->get_interrupt_shadow(vcpu,
  			KVM_X86_SHADOW_INT_MOV_SS | KVM_X86_SHADOW_INT_STI);
3cfc3092f   Jan Kiszka   KVM: x86: Add KVM...
2270
2271
  
  	events->nmi.injected = vcpu->arch.nmi_injected;
7460fb4a3   Avi Kivity   KVM: Fix simultan...
2272
  	events->nmi.pending = vcpu->arch.nmi_pending != 0;
3cfc3092f   Jan Kiszka   KVM: x86: Add KVM...
2273
  	events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
97e69aa62   Vasiliy Kulikov   KVM: x86: fix inf...
2274
  	events->nmi.pad = 0;
3cfc3092f   Jan Kiszka   KVM: x86: Add KVM...
2275
2276
  
  	events->sipi_vector = vcpu->arch.sipi_vector;
dab4b911a   Jan Kiszka   KVM: x86: Extend ...
2277
  	events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
48005f64d   Jan Kiszka   KVM: x86: Save&re...
2278
2279
  			 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
  			 | KVM_VCPUEVENT_VALID_SHADOW);
97e69aa62   Vasiliy Kulikov   KVM: x86: fix inf...
2280
  	memset(&events->reserved, 0, sizeof(events->reserved));
3cfc3092f   Jan Kiszka   KVM: x86: Add KVM...
2281
2282
2283
2284
2285
  }
  
  static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
  					      struct kvm_vcpu_events *events)
  {
dab4b911a   Jan Kiszka   KVM: x86: Extend ...
2286
  	if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
48005f64d   Jan Kiszka   KVM: x86: Save&re...
2287
2288
  			      | KVM_VCPUEVENT_VALID_SIPI_VECTOR
  			      | KVM_VCPUEVENT_VALID_SHADOW))
3cfc3092f   Jan Kiszka   KVM: x86: Add KVM...
2289
  		return -EINVAL;
7460fb4a3   Avi Kivity   KVM: Fix simultan...
2290
  	process_nmi(vcpu);
3cfc3092f   Jan Kiszka   KVM: x86: Add KVM...
2291
2292
2293
2294
2295
2296
2297
2298
  	vcpu->arch.exception.pending = events->exception.injected;
  	vcpu->arch.exception.nr = events->exception.nr;
  	vcpu->arch.exception.has_error_code = events->exception.has_error_code;
  	vcpu->arch.exception.error_code = events->exception.error_code;
  
  	vcpu->arch.interrupt.pending = events->interrupt.injected;
  	vcpu->arch.interrupt.nr = events->interrupt.nr;
  	vcpu->arch.interrupt.soft = events->interrupt.soft;
48005f64d   Jan Kiszka   KVM: x86: Save&re...
2299
2300
2301
  	if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
  		kvm_x86_ops->set_interrupt_shadow(vcpu,
  						  events->interrupt.shadow);
3cfc3092f   Jan Kiszka   KVM: x86: Add KVM...
2302
2303
  
  	vcpu->arch.nmi_injected = events->nmi.injected;
dab4b911a   Jan Kiszka   KVM: x86: Extend ...
2304
2305
  	if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
  		vcpu->arch.nmi_pending = events->nmi.pending;
3cfc3092f   Jan Kiszka   KVM: x86: Add KVM...
2306
  	kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
dab4b911a   Jan Kiszka   KVM: x86: Extend ...
2307
2308
  	if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR)
  		vcpu->arch.sipi_vector = events->sipi_vector;
3cfc3092f   Jan Kiszka   KVM: x86: Add KVM...
2309

3842d135f   Avi Kivity   KVM: Check for pe...
2310
  	kvm_make_request(KVM_REQ_EVENT, vcpu);
3cfc3092f   Jan Kiszka   KVM: x86: Add KVM...
2311
2312
  	return 0;
  }
a1efbe77c   Jan Kiszka   KVM: x86: Add sup...
2313
2314
2315
  static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
  					     struct kvm_debugregs *dbgregs)
  {
a1efbe77c   Jan Kiszka   KVM: x86: Add sup...
2316
2317
2318
2319
  	memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
  	dbgregs->dr6 = vcpu->arch.dr6;
  	dbgregs->dr7 = vcpu->arch.dr7;
  	dbgregs->flags = 0;
97e69aa62   Vasiliy Kulikov   KVM: x86: fix inf...
2320
  	memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
a1efbe77c   Jan Kiszka   KVM: x86: Add sup...
2321
2322
2323
2324
2325
2326
2327
  }
  
  static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
  					    struct kvm_debugregs *dbgregs)
  {
  	if (dbgregs->flags)
  		return -EINVAL;
a1efbe77c   Jan Kiszka   KVM: x86: Add sup...
2328
2329
2330
  	memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
  	vcpu->arch.dr6 = dbgregs->dr6;
  	vcpu->arch.dr7 = dbgregs->dr7;
a1efbe77c   Jan Kiszka   KVM: x86: Add sup...
2331
2332
  	return 0;
  }
2d5b5a665   Sheng Yang   KVM: x86: XSAVE/X...
2333
2334
2335
2336
2337
2338
  static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
  					 struct kvm_xsave *guest_xsave)
  {
  	if (cpu_has_xsave)
  		memcpy(guest_xsave->region,
  			&vcpu->arch.guest_fpu.state->xsave,
f45755b83   Xiaotian Feng   KVM: fix poison o...
2339
  			xstate_size);
2d5b5a665   Sheng Yang   KVM: x86: XSAVE/X...
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
  	else {
  		memcpy(guest_xsave->region,
  			&vcpu->arch.guest_fpu.state->fxsave,
  			sizeof(struct i387_fxsave_struct));
  		*(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
  			XSTATE_FPSSE;
  	}
  }
  
  static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
  					struct kvm_xsave *guest_xsave)
  {
  	u64 xstate_bv =
  		*(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
  
  	if (cpu_has_xsave)
  		memcpy(&vcpu->arch.guest_fpu.state->xsave,
f45755b83   Xiaotian Feng   KVM: fix poison o...
2357
  			guest_xsave->region, xstate_size);
2d5b5a665   Sheng Yang   KVM: x86: XSAVE/X...
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
  	else {
  		if (xstate_bv & ~XSTATE_FPSSE)
  			return -EINVAL;
  		memcpy(&vcpu->arch.guest_fpu.state->fxsave,
  			guest_xsave->region, sizeof(struct i387_fxsave_struct));
  	}
  	return 0;
  }
  
  static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
  					struct kvm_xcrs *guest_xcrs)
  {
  	if (!cpu_has_xsave) {
  		guest_xcrs->nr_xcrs = 0;
  		return;
  	}
  
  	guest_xcrs->nr_xcrs = 1;
  	guest_xcrs->flags = 0;
  	guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
  	guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
  }
  
  static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
  				       struct kvm_xcrs *guest_xcrs)
  {
  	int i, r = 0;
  
  	if (!cpu_has_xsave)
  		return -EINVAL;
  
  	if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
  		return -EINVAL;
  
  	for (i = 0; i < guest_xcrs->nr_xcrs; i++)
  		/* Only support XCR0 currently */
  		if (guest_xcrs->xcrs[0].xcr == XCR_XFEATURE_ENABLED_MASK) {
  			r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
  				guest_xcrs->xcrs[0].value);
  			break;
  		}
  	if (r)
  		r = -EINVAL;
  	return r;
  }
313a3dc75   Carsten Otte   KVM: Portability:...
2403
2404
2405
2406
2407
2408
  long kvm_arch_vcpu_ioctl(struct file *filp,
  			 unsigned int ioctl, unsigned long arg)
  {
  	struct kvm_vcpu *vcpu = filp->private_data;
  	void __user *argp = (void __user *)arg;
  	int r;
d1ac91d8a   Avi Kivity   KVM: Consolidate ...
2409
2410
2411
2412
2413
2414
2415
2416
  	union {
  		struct kvm_lapic_state *lapic;
  		struct kvm_xsave *xsave;
  		struct kvm_xcrs *xcrs;
  		void *buffer;
  	} u;
  
  	u.buffer = NULL;
313a3dc75   Carsten Otte   KVM: Portability:...
2417
2418
  	switch (ioctl) {
  	case KVM_GET_LAPIC: {
2204ae3c9   Marcelo Tosatti   KVM: x86: disallo...
2419
2420
2421
  		r = -EINVAL;
  		if (!vcpu->arch.apic)
  			goto out;
d1ac91d8a   Avi Kivity   KVM: Consolidate ...
2422
  		u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
313a3dc75   Carsten Otte   KVM: Portability:...
2423

b772ff362   Dave Hansen   KVM: Reduce stack...
2424
  		r = -ENOMEM;
d1ac91d8a   Avi Kivity   KVM: Consolidate ...
2425
  		if (!u.lapic)
b772ff362   Dave Hansen   KVM: Reduce stack...
2426
  			goto out;
d1ac91d8a   Avi Kivity   KVM: Consolidate ...
2427
  		r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
313a3dc75   Carsten Otte   KVM: Portability:...
2428
2429
2430
  		if (r)
  			goto out;
  		r = -EFAULT;
d1ac91d8a   Avi Kivity   KVM: Consolidate ...
2431
  		if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
313a3dc75   Carsten Otte   KVM: Portability:...
2432
2433
2434
2435
2436
  			goto out;
  		r = 0;
  		break;
  	}
  	case KVM_SET_LAPIC: {
2204ae3c9   Marcelo Tosatti   KVM: x86: disallo...
2437
2438
2439
  		r = -EINVAL;
  		if (!vcpu->arch.apic)
  			goto out;
ff5c2c031   Sasha Levin   KVM: Use memdup_u...
2440
2441
2442
  		u.lapic = memdup_user(argp, sizeof(*u.lapic));
  		if (IS_ERR(u.lapic)) {
  			r = PTR_ERR(u.lapic);
313a3dc75   Carsten Otte   KVM: Portability:...
2443
  			goto out;
ff5c2c031   Sasha Levin   KVM: Use memdup_u...
2444
  		}
d1ac91d8a   Avi Kivity   KVM: Consolidate ...
2445
  		r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
313a3dc75   Carsten Otte   KVM: Portability:...
2446
2447
2448
2449
2450
  		if (r)
  			goto out;
  		r = 0;
  		break;
  	}
f77bc6a42   Zhang Xiantao   KVM: Portability:...
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
  	case KVM_INTERRUPT: {
  		struct kvm_interrupt irq;
  
  		r = -EFAULT;
  		if (copy_from_user(&irq, argp, sizeof irq))
  			goto out;
  		r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
  		if (r)
  			goto out;
  		r = 0;
  		break;
  	}
c4abb7c9c   Jan Kiszka   KVM: x86: Support...
2463
2464
2465
2466
2467
2468
2469
  	case KVM_NMI: {
  		r = kvm_vcpu_ioctl_nmi(vcpu);
  		if (r)
  			goto out;
  		r = 0;
  		break;
  	}
313a3dc75   Carsten Otte   KVM: Portability:...
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
  	case KVM_SET_CPUID: {
  		struct kvm_cpuid __user *cpuid_arg = argp;
  		struct kvm_cpuid cpuid;
  
  		r = -EFAULT;
  		if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
  			goto out;
  		r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
  		if (r)
  			goto out;
  		break;
  	}
077167174   Dan Kenigsberg   KVM: Enhance gues...
2482
2483
2484
2485
2486
2487
2488
2489
  	case KVM_SET_CPUID2: {
  		struct kvm_cpuid2 __user *cpuid_arg = argp;
  		struct kvm_cpuid2 cpuid;
  
  		r = -EFAULT;
  		if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
  			goto out;
  		r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
193554750   Amit Shah   KVM: x86: Fix typ...
2490
  					      cpuid_arg->entries);
077167174   Dan Kenigsberg   KVM: Enhance gues...
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
  		if (r)
  			goto out;
  		break;
  	}
  	case KVM_GET_CPUID2: {
  		struct kvm_cpuid2 __user *cpuid_arg = argp;
  		struct kvm_cpuid2 cpuid;
  
  		r = -EFAULT;
  		if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
  			goto out;
  		r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
193554750   Amit Shah   KVM: x86: Fix typ...
2503
  					      cpuid_arg->entries);
077167174   Dan Kenigsberg   KVM: Enhance gues...
2504
2505
2506
2507
2508
2509
2510
2511
  		if (r)
  			goto out;
  		r = -EFAULT;
  		if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
  			goto out;
  		r = 0;
  		break;
  	}
313a3dc75   Carsten Otte   KVM: Portability:...
2512
2513
2514
2515
2516
2517
  	case KVM_GET_MSRS:
  		r = msr_io(vcpu, argp, kvm_get_msr, 1);
  		break;
  	case KVM_SET_MSRS:
  		r = msr_io(vcpu, argp, do_set_msr, 0);
  		break;
b209749f5   Avi Kivity   KVM: local APIC T...
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
  	case KVM_TPR_ACCESS_REPORTING: {
  		struct kvm_tpr_access_ctl tac;
  
  		r = -EFAULT;
  		if (copy_from_user(&tac, argp, sizeof tac))
  			goto out;
  		r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
  		if (r)
  			goto out;
  		r = -EFAULT;
  		if (copy_to_user(argp, &tac, sizeof tac))
  			goto out;
  		r = 0;
  		break;
  	};
b93463aa5   Avi Kivity   KVM: Accelerated ...
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
  	case KVM_SET_VAPIC_ADDR: {
  		struct kvm_vapic_addr va;
  
  		r = -EINVAL;
  		if (!irqchip_in_kernel(vcpu->kvm))
  			goto out;
  		r = -EFAULT;
  		if (copy_from_user(&va, argp, sizeof va))
  			goto out;
  		r = 0;
  		kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
  		break;
  	}
890ca9aef   Huang Ying   KVM: Add MCE support
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
  	case KVM_X86_SETUP_MCE: {
  		u64 mcg_cap;
  
  		r = -EFAULT;
  		if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
  			goto out;
  		r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
  		break;
  	}
  	case KVM_X86_SET_MCE: {
  		struct kvm_x86_mce mce;
  
  		r = -EFAULT;
  		if (copy_from_user(&mce, argp, sizeof mce))
  			goto out;
  		r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
  		break;
  	}
3cfc3092f   Jan Kiszka   KVM: x86: Add KVM...
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
  	case KVM_GET_VCPU_EVENTS: {
  		struct kvm_vcpu_events events;
  
  		kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
  
  		r = -EFAULT;
  		if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
  			break;
  		r = 0;
  		break;
  	}
  	case KVM_SET_VCPU_EVENTS: {
  		struct kvm_vcpu_events events;
  
  		r = -EFAULT;
  		if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
  			break;
  
  		r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
  		break;
  	}
a1efbe77c   Jan Kiszka   KVM: x86: Add sup...
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
  	case KVM_GET_DEBUGREGS: {
  		struct kvm_debugregs dbgregs;
  
  		kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
  
  		r = -EFAULT;
  		if (copy_to_user(argp, &dbgregs,
  				 sizeof(struct kvm_debugregs)))
  			break;
  		r = 0;
  		break;
  	}
  	case KVM_SET_DEBUGREGS: {
  		struct kvm_debugregs dbgregs;
  
  		r = -EFAULT;
  		if (copy_from_user(&dbgregs, argp,
  				   sizeof(struct kvm_debugregs)))
  			break;
  
  		r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
  		break;
  	}
2d5b5a665   Sheng Yang   KVM: x86: XSAVE/X...
2608
  	case KVM_GET_XSAVE: {
d1ac91d8a   Avi Kivity   KVM: Consolidate ...
2609
  		u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
2d5b5a665   Sheng Yang   KVM: x86: XSAVE/X...
2610
  		r = -ENOMEM;
d1ac91d8a   Avi Kivity   KVM: Consolidate ...
2611
  		if (!u.xsave)
2d5b5a665   Sheng Yang   KVM: x86: XSAVE/X...
2612
  			break;
d1ac91d8a   Avi Kivity   KVM: Consolidate ...
2613
  		kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
2d5b5a665   Sheng Yang   KVM: x86: XSAVE/X...
2614
2615
  
  		r = -EFAULT;
d1ac91d8a   Avi Kivity   KVM: Consolidate ...
2616
  		if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
2d5b5a665   Sheng Yang   KVM: x86: XSAVE/X...
2617
2618
2619
2620
2621
  			break;
  		r = 0;
  		break;
  	}
  	case KVM_SET_XSAVE: {
ff5c2c031   Sasha Levin   KVM: Use memdup_u...
2622
2623
2624
2625
2626
  		u.xsave = memdup_user(argp, sizeof(*u.xsave));
  		if (IS_ERR(u.xsave)) {
  			r = PTR_ERR(u.xsave);
  			goto out;
  		}
2d5b5a665   Sheng Yang   KVM: x86: XSAVE/X...
2627

d1ac91d8a   Avi Kivity   KVM: Consolidate ...
2628
  		r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
2d5b5a665   Sheng Yang   KVM: x86: XSAVE/X...
2629
2630
2631
  		break;
  	}
  	case KVM_GET_XCRS: {
d1ac91d8a   Avi Kivity   KVM: Consolidate ...
2632
  		u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
2d5b5a665   Sheng Yang   KVM: x86: XSAVE/X...
2633
  		r = -ENOMEM;
d1ac91d8a   Avi Kivity   KVM: Consolidate ...
2634
  		if (!u.xcrs)
2d5b5a665   Sheng Yang   KVM: x86: XSAVE/X...
2635
  			break;
d1ac91d8a   Avi Kivity   KVM: Consolidate ...
2636
  		kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
2d5b5a665   Sheng Yang   KVM: x86: XSAVE/X...
2637
2638
  
  		r = -EFAULT;
d1ac91d8a   Avi Kivity   KVM: Consolidate ...
2639
  		if (copy_to_user(argp, u.xcrs,
2d5b5a665   Sheng Yang   KVM: x86: XSAVE/X...
2640
2641
2642
2643
2644
2645
  				 sizeof(struct kvm_xcrs)))
  			break;
  		r = 0;
  		break;
  	}
  	case KVM_SET_XCRS: {
ff5c2c031   Sasha Levin   KVM: Use memdup_u...
2646
2647
2648
2649
2650
  		u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
  		if (IS_ERR(u.xcrs)) {
  			r = PTR_ERR(u.xcrs);
  			goto out;
  		}
2d5b5a665   Sheng Yang   KVM: x86: XSAVE/X...
2651

d1ac91d8a   Avi Kivity   KVM: Consolidate ...
2652
  		r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
2d5b5a665   Sheng Yang   KVM: x86: XSAVE/X...
2653
2654
  		break;
  	}
92a1f12d2   Joerg Roedel   KVM: X86: Impleme...
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
  	case KVM_SET_TSC_KHZ: {
  		u32 user_tsc_khz;
  
  		r = -EINVAL;
  		if (!kvm_has_tsc_control)
  			break;
  
  		user_tsc_khz = (u32)arg;
  
  		if (user_tsc_khz >= kvm_max_guest_tsc_khz)
  			goto out;
  
  		kvm_x86_ops->set_tsc_khz(vcpu, user_tsc_khz);
  
  		r = 0;
  		goto out;
  	}
  	case KVM_GET_TSC_KHZ: {
  		r = -EIO;
  		if (check_tsc_unstable())
  			goto out;
  
  		r = vcpu_tsc_khz(vcpu);
  
  		goto out;
  	}
313a3dc75   Carsten Otte   KVM: Portability:...
2681
2682
2683
2684
  	default:
  		r = -EINVAL;
  	}
  out:
d1ac91d8a   Avi Kivity   KVM: Consolidate ...
2685
  	kfree(u.buffer);
313a3dc75   Carsten Otte   KVM: Portability:...
2686
2687
  	return r;
  }
1fe779f8e   Carsten Otte   KVM: Portability:...
2688
2689
2690
2691
2692
2693
2694
2695
2696
  static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
  {
  	int ret;
  
  	if (addr > (unsigned int)(-3 * PAGE_SIZE))
  		return -1;
  	ret = kvm_x86_ops->set_tss_addr(kvm, addr);
  	return ret;
  }
b927a3cec   Sheng Yang   KVM: VMX: Introdu...
2697
2698
2699
2700
2701
2702
  static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
  					      u64 ident_addr)
  {
  	kvm->arch.ept_identity_map_addr = ident_addr;
  	return 0;
  }
1fe779f8e   Carsten Otte   KVM: Portability:...
2703
2704
2705
2706
2707
  static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
  					  u32 kvm_nr_mmu_pages)
  {
  	if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
  		return -EINVAL;
79fac95ec   Marcelo Tosatti   KVM: convert slot...
2708
  	mutex_lock(&kvm->slots_lock);
7c8a83b75   Marcelo Tosatti   KVM: MMU: protect...
2709
  	spin_lock(&kvm->mmu_lock);
1fe779f8e   Carsten Otte   KVM: Portability:...
2710
2711
  
  	kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
f05e70ac0   Zhang Xiantao   KVM: Portability:...
2712
  	kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
1fe779f8e   Carsten Otte   KVM: Portability:...
2713

7c8a83b75   Marcelo Tosatti   KVM: MMU: protect...
2714
  	spin_unlock(&kvm->mmu_lock);
79fac95ec   Marcelo Tosatti   KVM: convert slot...
2715
  	mutex_unlock(&kvm->slots_lock);
1fe779f8e   Carsten Otte   KVM: Portability:...
2716
2717
2718
2719
2720
  	return 0;
  }
  
  static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
  {
39de71ec5   Dave Hansen   KVM: rename x86 k...
2721
  	return kvm->arch.n_max_mmu_pages;
1fe779f8e   Carsten Otte   KVM: Portability:...
2722
  }
1fe779f8e   Carsten Otte   KVM: Portability:...
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
  static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
  {
  	int r;
  
  	r = 0;
  	switch (chip->chip_id) {
  	case KVM_IRQCHIP_PIC_MASTER:
  		memcpy(&chip->chip.pic,
  			&pic_irqchip(kvm)->pics[0],
  			sizeof(struct kvm_pic_state));
  		break;
  	case KVM_IRQCHIP_PIC_SLAVE:
  		memcpy(&chip->chip.pic,
  			&pic_irqchip(kvm)->pics[1],
  			sizeof(struct kvm_pic_state));
  		break;
  	case KVM_IRQCHIP_IOAPIC:
eba0226bd   Gleb Natapov   KVM: Move IO APIC...
2740
  		r = kvm_get_ioapic(kvm, &chip->chip.ioapic);
1fe779f8e   Carsten Otte   KVM: Portability:...
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
  		break;
  	default:
  		r = -EINVAL;
  		break;
  	}
  	return r;
  }
  
  static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
  {
  	int r;
  
  	r = 0;
  	switch (chip->chip_id) {
  	case KVM_IRQCHIP_PIC_MASTER:
f4f510508   Avi Kivity   KVM: Convert PIC ...
2756
  		spin_lock(&pic_irqchip(kvm)->lock);
1fe779f8e   Carsten Otte   KVM: Portability:...
2757
2758
2759
  		memcpy(&pic_irqchip(kvm)->pics[0],
  			&chip->chip.pic,
  			sizeof(struct kvm_pic_state));
f4f510508   Avi Kivity   KVM: Convert PIC ...
2760
  		spin_unlock(&pic_irqchip(kvm)->lock);
1fe779f8e   Carsten Otte   KVM: Portability:...
2761
2762
  		break;
  	case KVM_IRQCHIP_PIC_SLAVE:
f4f510508   Avi Kivity   KVM: Convert PIC ...
2763
  		spin_lock(&pic_irqchip(kvm)->lock);
1fe779f8e   Carsten Otte   KVM: Portability:...
2764
2765
2766
  		memcpy(&pic_irqchip(kvm)->pics[1],
  			&chip->chip.pic,
  			sizeof(struct kvm_pic_state));
f4f510508   Avi Kivity   KVM: Convert PIC ...
2767
  		spin_unlock(&pic_irqchip(kvm)->lock);
1fe779f8e   Carsten Otte   KVM: Portability:...
2768
2769
  		break;
  	case KVM_IRQCHIP_IOAPIC:
eba0226bd   Gleb Natapov   KVM: Move IO APIC...
2770
  		r = kvm_set_ioapic(kvm, &chip->chip.ioapic);
1fe779f8e   Carsten Otte   KVM: Portability:...
2771
2772
2773
2774
2775
2776
2777
2778
  		break;
  	default:
  		r = -EINVAL;
  		break;
  	}
  	kvm_pic_update_irq(pic_irqchip(kvm));
  	return r;
  }
e0f63cb92   Sheng Yang   KVM: Add save/res...
2779
2780
2781
  static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
  {
  	int r = 0;
894a9c554   Marcelo Tosatti   KVM: x86: missing...
2782
  	mutex_lock(&kvm->arch.vpit->pit_state.lock);
e0f63cb92   Sheng Yang   KVM: Add save/res...
2783
  	memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
894a9c554   Marcelo Tosatti   KVM: x86: missing...
2784
  	mutex_unlock(&kvm->arch.vpit->pit_state.lock);
e0f63cb92   Sheng Yang   KVM: Add save/res...
2785
2786
2787
2788
2789
2790
  	return r;
  }
  
  static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
  {
  	int r = 0;
894a9c554   Marcelo Tosatti   KVM: x86: missing...
2791
  	mutex_lock(&kvm->arch.vpit->pit_state.lock);
e0f63cb92   Sheng Yang   KVM: Add save/res...
2792
  	memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
e9f427573   Beth Kon   KVM: PIT support ...
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
  	kvm_pit_load_count(kvm, 0, ps->channels[0].count, 0);
  	mutex_unlock(&kvm->arch.vpit->pit_state.lock);
  	return r;
  }
  
  static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
  {
  	int r = 0;
  
  	mutex_lock(&kvm->arch.vpit->pit_state.lock);
  	memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
  		sizeof(ps->channels));
  	ps->flags = kvm->arch.vpit->pit_state.flags;
  	mutex_unlock(&kvm->arch.vpit->pit_state.lock);
97e69aa62   Vasiliy Kulikov   KVM: x86: fix inf...
2807
  	memset(&ps->reserved, 0, sizeof(ps->reserved));
e9f427573   Beth Kon   KVM: PIT support ...
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
  	return r;
  }
  
  static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
  {
  	int r = 0, start = 0;
  	u32 prev_legacy, cur_legacy;
  	mutex_lock(&kvm->arch.vpit->pit_state.lock);
  	prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
  	cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
  	if (!prev_legacy && cur_legacy)
  		start = 1;
  	memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
  	       sizeof(kvm->arch.vpit->pit_state.channels));
  	kvm->arch.vpit->pit_state.flags = ps->flags;
  	kvm_pit_load_count(kvm, 0, kvm->arch.vpit->pit_state.channels[0].count, start);
894a9c554   Marcelo Tosatti   KVM: x86: missing...
2824
  	mutex_unlock(&kvm->arch.vpit->pit_state.lock);
e0f63cb92   Sheng Yang   KVM: Add save/res...
2825
2826
  	return r;
  }
52d939a0b   Marcelo Tosatti   KVM: PIT: provide...
2827
2828
2829
2830
2831
  static int kvm_vm_ioctl_reinject(struct kvm *kvm,
  				 struct kvm_reinject_control *control)
  {
  	if (!kvm->arch.vpit)
  		return -ENXIO;
894a9c554   Marcelo Tosatti   KVM: x86: missing...
2832
  	mutex_lock(&kvm->arch.vpit->pit_state.lock);
52d939a0b   Marcelo Tosatti   KVM: PIT: provide...
2833
  	kvm->arch.vpit->pit_state.pit_timer.reinject = control->pit_reinject;
894a9c554   Marcelo Tosatti   KVM: x86: missing...
2834
  	mutex_unlock(&kvm->arch.vpit->pit_state.lock);
52d939a0b   Marcelo Tosatti   KVM: PIT: provide...
2835
2836
  	return 0;
  }
95d4c16ce   Takuya Yoshikawa   KVM: Optimize dir...
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
  /**
   * write_protect_slot - write protect a slot for dirty logging
   * @kvm: the kvm instance
   * @memslot: the slot we protect
   * @dirty_bitmap: the bitmap indicating which pages are dirty
   * @nr_dirty_pages: the number of dirty pages
   *
   * We have two ways to find all sptes to protect:
   * 1. Use kvm_mmu_slot_remove_write_access() which walks all shadow pages and
   *    checks ones that have a spte mapping a page in the slot.
   * 2. Use kvm_mmu_rmap_write_protect() for each gfn found in the bitmap.
   *
   * Generally speaking, if there are not so many dirty pages compared to the
   * number of shadow pages, we should use the latter.
   *
   * Note that letting others write into a page marked dirty in the old bitmap
   * by using the remaining tlb entry is not a problem.  That page will become
   * write protected again when we flush the tlb and then be reported dirty to
   * the user space by copying the old bitmap.
   */
  static void write_protect_slot(struct kvm *kvm,
  			       struct kvm_memory_slot *memslot,
  			       unsigned long *dirty_bitmap,
  			       unsigned long nr_dirty_pages)
  {
  	/* Not many dirty pages compared to # of shadow pages. */
  	if (nr_dirty_pages < kvm->arch.n_used_mmu_pages) {
  		unsigned long gfn_offset;
  
  		for_each_set_bit(gfn_offset, dirty_bitmap, memslot->npages) {
  			unsigned long gfn = memslot->base_gfn + gfn_offset;
  
  			spin_lock(&kvm->mmu_lock);
  			kvm_mmu_rmap_write_protect(kvm, gfn, memslot);
  			spin_unlock(&kvm->mmu_lock);
  		}
  		kvm_flush_remote_tlbs(kvm);
  	} else {
  		spin_lock(&kvm->mmu_lock);
  		kvm_mmu_slot_remove_write_access(kvm, memslot->id);
  		spin_unlock(&kvm->mmu_lock);
  	}
  }
5bb064dcd   Zhang Xiantao   KVM: Portability:...
2880
2881
2882
2883
2884
2885
  /*
   * Get (and clear) the dirty memory log for a memory slot.
   */
  int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
  				      struct kvm_dirty_log *log)
  {
7850ac542   Takuya Yoshikawa   KVM: Count the nu...
2886
  	int r;
5bb064dcd   Zhang Xiantao   KVM: Portability:...
2887
  	struct kvm_memory_slot *memslot;
95d4c16ce   Takuya Yoshikawa   KVM: Optimize dir...
2888
  	unsigned long n, nr_dirty_pages;
5bb064dcd   Zhang Xiantao   KVM: Portability:...
2889

79fac95ec   Marcelo Tosatti   KVM: convert slot...
2890
  	mutex_lock(&kvm->slots_lock);
5bb064dcd   Zhang Xiantao   KVM: Portability:...
2891

b050b015a   Marcelo Tosatti   KVM: use SRCU for...
2892
2893
2894
  	r = -EINVAL;
  	if (log->slot >= KVM_MEMORY_SLOTS)
  		goto out;
28a37544f   Xiao Guangrong   KVM: introduce id...
2895
  	memslot = id_to_memslot(kvm->memslots, log->slot);
b050b015a   Marcelo Tosatti   KVM: use SRCU for...
2896
2897
2898
  	r = -ENOENT;
  	if (!memslot->dirty_bitmap)
  		goto out;
87bf6e7de   Takuya Yoshikawa   KVM: fix the hand...
2899
  	n = kvm_dirty_bitmap_bytes(memslot);
95d4c16ce   Takuya Yoshikawa   KVM: Optimize dir...
2900
  	nr_dirty_pages = memslot->nr_dirty_pages;
b050b015a   Marcelo Tosatti   KVM: use SRCU for...
2901

5bb064dcd   Zhang Xiantao   KVM: Portability:...
2902
  	/* If nothing is dirty, don't bother messing with page tables. */
95d4c16ce   Takuya Yoshikawa   KVM: Optimize dir...
2903
  	if (nr_dirty_pages) {
b050b015a   Marcelo Tosatti   KVM: use SRCU for...
2904
  		struct kvm_memslots *slots, *old_slots;
28a37544f   Xiao Guangrong   KVM: introduce id...
2905
  		unsigned long *dirty_bitmap, *dirty_bitmap_head;
b050b015a   Marcelo Tosatti   KVM: use SRCU for...
2906

28a37544f   Xiao Guangrong   KVM: introduce id...
2907
2908
2909
2910
2911
  		dirty_bitmap = memslot->dirty_bitmap;
  		dirty_bitmap_head = memslot->dirty_bitmap_head;
  		if (dirty_bitmap == dirty_bitmap_head)
  			dirty_bitmap_head += n / sizeof(long);
  		memset(dirty_bitmap_head, 0, n);
b050b015a   Marcelo Tosatti   KVM: use SRCU for...
2912

914ebccd2   Takuya Yoshikawa   KVM: x86: avoid u...
2913
  		r = -ENOMEM;
cdfca7b34   Sasha Levin   KVM: Use kmemdup(...
2914
  		slots = kmemdup(kvm->memslots, sizeof(*kvm->memslots), GFP_KERNEL);
515a01279   Takuya Yoshikawa   KVM: pre-allocate...
2915
  		if (!slots)
914ebccd2   Takuya Yoshikawa   KVM: x86: avoid u...
2916
  			goto out;
cdfca7b34   Sasha Levin   KVM: Use kmemdup(...
2917

28a37544f   Xiao Guangrong   KVM: introduce id...
2918
  		memslot = id_to_memslot(slots, log->slot);
95d4c16ce   Takuya Yoshikawa   KVM: Optimize dir...
2919
  		memslot->nr_dirty_pages = 0;
28a37544f   Xiao Guangrong   KVM: introduce id...
2920
  		memslot->dirty_bitmap = dirty_bitmap_head;
be593d628   Xiao Guangrong   KVM: introduce up...
2921
  		update_memslots(slots, NULL);
b050b015a   Marcelo Tosatti   KVM: use SRCU for...
2922
2923
2924
2925
  
  		old_slots = kvm->memslots;
  		rcu_assign_pointer(kvm->memslots, slots);
  		synchronize_srcu_expedited(&kvm->srcu);
b050b015a   Marcelo Tosatti   KVM: use SRCU for...
2926
  		kfree(old_slots);
914ebccd2   Takuya Yoshikawa   KVM: x86: avoid u...
2927

95d4c16ce   Takuya Yoshikawa   KVM: Optimize dir...
2928
  		write_protect_slot(kvm, memslot, dirty_bitmap, nr_dirty_pages);
edde99ce0   Michael S. Tsirkin   KVM: Write protec...
2929

914ebccd2   Takuya Yoshikawa   KVM: x86: avoid u...
2930
  		r = -EFAULT;
515a01279   Takuya Yoshikawa   KVM: pre-allocate...
2931
  		if (copy_to_user(log->dirty_bitmap, dirty_bitmap, n))
914ebccd2   Takuya Yoshikawa   KVM: x86: avoid u...
2932
  			goto out;
914ebccd2   Takuya Yoshikawa   KVM: x86: avoid u...
2933
2934
2935
2936
  	} else {
  		r = -EFAULT;
  		if (clear_user(log->dirty_bitmap, n))
  			goto out;
5bb064dcd   Zhang Xiantao   KVM: Portability:...
2937
  	}
b050b015a   Marcelo Tosatti   KVM: use SRCU for...
2938

5bb064dcd   Zhang Xiantao   KVM: Portability:...
2939
2940
  	r = 0;
  out:
79fac95ec   Marcelo Tosatti   KVM: convert slot...
2941
  	mutex_unlock(&kvm->slots_lock);
5bb064dcd   Zhang Xiantao   KVM: Portability:...
2942
2943
  	return r;
  }
1fe779f8e   Carsten Otte   KVM: Portability:...
2944
2945
2946
2947
2948
  long kvm_arch_vm_ioctl(struct file *filp,
  		       unsigned int ioctl, unsigned long arg)
  {
  	struct kvm *kvm = filp->private_data;
  	void __user *argp = (void __user *)arg;
367e1319b   Avi Kivity   KVM: Return -ENOT...
2949
  	int r = -ENOTTY;
f0d662759   Dave Hansen   KVM: Reduce kvm s...
2950
2951
2952
2953
2954
2955
2956
  	/*
  	 * This union makes it completely explicit to gcc-3.x
  	 * that these two variables' stack usage should be
  	 * combined, not added together.
  	 */
  	union {
  		struct kvm_pit_state ps;
e9f427573   Beth Kon   KVM: PIT support ...
2957
  		struct kvm_pit_state2 ps2;
c5ff41ce6   Jan Kiszka   KVM: Allow PIT em...
2958
  		struct kvm_pit_config pit_config;
f0d662759   Dave Hansen   KVM: Reduce kvm s...
2959
  	} u;
1fe779f8e   Carsten Otte   KVM: Portability:...
2960
2961
2962
2963
2964
2965
2966
  
  	switch (ioctl) {
  	case KVM_SET_TSS_ADDR:
  		r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
  		if (r < 0)
  			goto out;
  		break;
b927a3cec   Sheng Yang   KVM: VMX: Introdu...
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
  	case KVM_SET_IDENTITY_MAP_ADDR: {
  		u64 ident_addr;
  
  		r = -EFAULT;
  		if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
  			goto out;
  		r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
  		if (r < 0)
  			goto out;
  		break;
  	}
1fe779f8e   Carsten Otte   KVM: Portability:...
2978
2979
2980
2981
2982
2983
2984
2985
  	case KVM_SET_NR_MMU_PAGES:
  		r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
  		if (r)
  			goto out;
  		break;
  	case KVM_GET_NR_MMU_PAGES:
  		r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
  		break;
3ddea128a   Marcelo Tosatti   KVM: x86: disallo...
2986
2987
2988
2989
2990
2991
2992
  	case KVM_CREATE_IRQCHIP: {
  		struct kvm_pic *vpic;
  
  		mutex_lock(&kvm->lock);
  		r = -EEXIST;
  		if (kvm->arch.vpic)
  			goto create_irqchip_unlock;
1fe779f8e   Carsten Otte   KVM: Portability:...
2993
  		r = -ENOMEM;
3ddea128a   Marcelo Tosatti   KVM: x86: disallo...
2994
2995
  		vpic = kvm_create_pic(kvm);
  		if (vpic) {
1fe779f8e   Carsten Otte   KVM: Portability:...
2996
2997
  			r = kvm_ioapic_init(kvm);
  			if (r) {
175504cdb   Takuya Yoshikawa   KVM: Take missing...
2998
  				mutex_lock(&kvm->slots_lock);
72bb2fcd2   Wei Yongjun   KVM: cleanup the ...
2999
  				kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
743eeb0b0   Sasha Levin   KVM: Intelligent ...
3000
3001
3002
3003
3004
  							  &vpic->dev_master);
  				kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
  							  &vpic->dev_slave);
  				kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
  							  &vpic->dev_eclr);
175504cdb   Takuya Yoshikawa   KVM: Take missing...
3005
  				mutex_unlock(&kvm->slots_lock);
3ddea128a   Marcelo Tosatti   KVM: x86: disallo...
3006
3007
  				kfree(vpic);
  				goto create_irqchip_unlock;
1fe779f8e   Carsten Otte   KVM: Portability:...
3008
3009
  			}
  		} else
3ddea128a   Marcelo Tosatti   KVM: x86: disallo...
3010
3011
3012
3013
  			goto create_irqchip_unlock;
  		smp_wmb();
  		kvm->arch.vpic = vpic;
  		smp_wmb();
399ec807d   Avi Kivity   KVM: Userspace co...
3014
3015
  		r = kvm_setup_default_irq_routing(kvm);
  		if (r) {
175504cdb   Takuya Yoshikawa   KVM: Take missing...
3016
  			mutex_lock(&kvm->slots_lock);
3ddea128a   Marcelo Tosatti   KVM: x86: disallo...
3017
  			mutex_lock(&kvm->irq_lock);
72bb2fcd2   Wei Yongjun   KVM: cleanup the ...
3018
3019
  			kvm_ioapic_destroy(kvm);
  			kvm_destroy_pic(kvm);
3ddea128a   Marcelo Tosatti   KVM: x86: disallo...
3020
  			mutex_unlock(&kvm->irq_lock);
175504cdb   Takuya Yoshikawa   KVM: Take missing...
3021
  			mutex_unlock(&kvm->slots_lock);
399ec807d   Avi Kivity   KVM: Userspace co...
3022
  		}
3ddea128a   Marcelo Tosatti   KVM: x86: disallo...
3023
3024
  	create_irqchip_unlock:
  		mutex_unlock(&kvm->lock);
1fe779f8e   Carsten Otte   KVM: Portability:...
3025
  		break;
3ddea128a   Marcelo Tosatti   KVM: x86: disallo...
3026
  	}
7837699fa   Sheng Yang   KVM: In kernel PI...
3027
  	case KVM_CREATE_PIT:
c5ff41ce6   Jan Kiszka   KVM: Allow PIT em...
3028
3029
3030
3031
3032
3033
3034
3035
  		u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
  		goto create_pit;
  	case KVM_CREATE_PIT2:
  		r = -EFAULT;
  		if (copy_from_user(&u.pit_config, argp,
  				   sizeof(struct kvm_pit_config)))
  			goto out;
  	create_pit:
79fac95ec   Marcelo Tosatti   KVM: convert slot...
3036
  		mutex_lock(&kvm->slots_lock);
269e05e48   Avi Kivity   KVM: Properly loc...
3037
3038
3039
  		r = -EEXIST;
  		if (kvm->arch.vpit)
  			goto create_pit_unlock;
7837699fa   Sheng Yang   KVM: In kernel PI...
3040
  		r = -ENOMEM;
c5ff41ce6   Jan Kiszka   KVM: Allow PIT em...
3041
  		kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
7837699fa   Sheng Yang   KVM: In kernel PI...
3042
3043
  		if (kvm->arch.vpit)
  			r = 0;
269e05e48   Avi Kivity   KVM: Properly loc...
3044
  	create_pit_unlock:
79fac95ec   Marcelo Tosatti   KVM: convert slot...
3045
  		mutex_unlock(&kvm->slots_lock);
7837699fa   Sheng Yang   KVM: In kernel PI...
3046
  		break;
4925663a0   Gleb Natapov   KVM: Report IRQ i...
3047
  	case KVM_IRQ_LINE_STATUS:
1fe779f8e   Carsten Otte   KVM: Portability:...
3048
3049
3050
3051
3052
3053
  	case KVM_IRQ_LINE: {
  		struct kvm_irq_level irq_event;
  
  		r = -EFAULT;
  		if (copy_from_user(&irq_event, argp, sizeof irq_event))
  			goto out;
160d2f6c0   Wei Yongjun   KVM: x86: fix the...
3054
  		r = -ENXIO;
1fe779f8e   Carsten Otte   KVM: Portability:...
3055
  		if (irqchip_in_kernel(kvm)) {
4925663a0   Gleb Natapov   KVM: Report IRQ i...
3056
  			__s32 status;
4925663a0   Gleb Natapov   KVM: Report IRQ i...
3057
3058
  			status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
  					irq_event.irq, irq_event.level);
4925663a0   Gleb Natapov   KVM: Report IRQ i...
3059
  			if (ioctl == KVM_IRQ_LINE_STATUS) {
160d2f6c0   Wei Yongjun   KVM: x86: fix the...
3060
  				r = -EFAULT;
4925663a0   Gleb Natapov   KVM: Report IRQ i...
3061
3062
3063
3064
3065
  				irq_event.status = status;
  				if (copy_to_user(argp, &irq_event,
  							sizeof irq_event))
  					goto out;
  			}
1fe779f8e   Carsten Otte   KVM: Portability:...
3066
3067
3068
3069
3070
3071
  			r = 0;
  		}
  		break;
  	}
  	case KVM_GET_IRQCHIP: {
  		/* 0: PIC master, 1: PIC slave, 2: IOAPIC */
ff5c2c031   Sasha Levin   KVM: Use memdup_u...
3072
  		struct kvm_irqchip *chip;
1fe779f8e   Carsten Otte   KVM: Portability:...
3073

ff5c2c031   Sasha Levin   KVM: Use memdup_u...
3074
3075
3076
  		chip = memdup_user(argp, sizeof(*chip));
  		if (IS_ERR(chip)) {
  			r = PTR_ERR(chip);
1fe779f8e   Carsten Otte   KVM: Portability:...
3077
  			goto out;
ff5c2c031   Sasha Levin   KVM: Use memdup_u...
3078
  		}
1fe779f8e   Carsten Otte   KVM: Portability:...
3079
3080
  		r = -ENXIO;
  		if (!irqchip_in_kernel(kvm))
f0d662759   Dave Hansen   KVM: Reduce kvm s...
3081
3082
  			goto get_irqchip_out;
  		r = kvm_vm_ioctl_get_irqchip(kvm, chip);
1fe779f8e   Carsten Otte   KVM: Portability:...
3083
  		if (r)
f0d662759   Dave Hansen   KVM: Reduce kvm s...
3084
  			goto get_irqchip_out;
1fe779f8e   Carsten Otte   KVM: Portability:...
3085
  		r = -EFAULT;
f0d662759   Dave Hansen   KVM: Reduce kvm s...
3086
3087
  		if (copy_to_user(argp, chip, sizeof *chip))
  			goto get_irqchip_out;
1fe779f8e   Carsten Otte   KVM: Portability:...
3088
  		r = 0;
f0d662759   Dave Hansen   KVM: Reduce kvm s...
3089
3090
3091
3092
  	get_irqchip_out:
  		kfree(chip);
  		if (r)
  			goto out;
1fe779f8e   Carsten Otte   KVM: Portability:...
3093
3094
3095
3096
  		break;
  	}
  	case KVM_SET_IRQCHIP: {
  		/* 0: PIC master, 1: PIC slave, 2: IOAPIC */
ff5c2c031   Sasha Levin   KVM: Use memdup_u...
3097
  		struct kvm_irqchip *chip;
1fe779f8e   Carsten Otte   KVM: Portability:...
3098

ff5c2c031   Sasha Levin   KVM: Use memdup_u...
3099
3100
3101
  		chip = memdup_user(argp, sizeof(*chip));
  		if (IS_ERR(chip)) {
  			r = PTR_ERR(chip);
1fe779f8e   Carsten Otte   KVM: Portability:...
3102
  			goto out;
ff5c2c031   Sasha Levin   KVM: Use memdup_u...
3103
  		}
1fe779f8e   Carsten Otte   KVM: Portability:...
3104
3105
  		r = -ENXIO;
  		if (!irqchip_in_kernel(kvm))
f0d662759   Dave Hansen   KVM: Reduce kvm s...
3106
3107
  			goto set_irqchip_out;
  		r = kvm_vm_ioctl_set_irqchip(kvm, chip);
1fe779f8e   Carsten Otte   KVM: Portability:...
3108
  		if (r)
f0d662759   Dave Hansen   KVM: Reduce kvm s...
3109
  			goto set_irqchip_out;
1fe779f8e   Carsten Otte   KVM: Portability:...
3110
  		r = 0;
f0d662759   Dave Hansen   KVM: Reduce kvm s...
3111
3112
3113
3114
  	set_irqchip_out:
  		kfree(chip);
  		if (r)
  			goto out;
1fe779f8e   Carsten Otte   KVM: Portability:...
3115
3116
  		break;
  	}
e0f63cb92   Sheng Yang   KVM: Add save/res...
3117
  	case KVM_GET_PIT: {
e0f63cb92   Sheng Yang   KVM: Add save/res...
3118
  		r = -EFAULT;
f0d662759   Dave Hansen   KVM: Reduce kvm s...
3119
  		if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
e0f63cb92   Sheng Yang   KVM: Add save/res...
3120
3121
3122
3123
  			goto out;
  		r = -ENXIO;
  		if (!kvm->arch.vpit)
  			goto out;
f0d662759   Dave Hansen   KVM: Reduce kvm s...
3124
  		r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
e0f63cb92   Sheng Yang   KVM: Add save/res...
3125
3126
3127
  		if (r)
  			goto out;
  		r = -EFAULT;
f0d662759   Dave Hansen   KVM: Reduce kvm s...
3128
  		if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
e0f63cb92   Sheng Yang   KVM: Add save/res...
3129
3130
3131
3132
3133
  			goto out;
  		r = 0;
  		break;
  	}
  	case KVM_SET_PIT: {
e0f63cb92   Sheng Yang   KVM: Add save/res...
3134
  		r = -EFAULT;
f0d662759   Dave Hansen   KVM: Reduce kvm s...
3135
  		if (copy_from_user(&u.ps, argp, sizeof u.ps))
e0f63cb92   Sheng Yang   KVM: Add save/res...
3136
3137
3138
3139
  			goto out;
  		r = -ENXIO;
  		if (!kvm->arch.vpit)
  			goto out;
f0d662759   Dave Hansen   KVM: Reduce kvm s...
3140
  		r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
e0f63cb92   Sheng Yang   KVM: Add save/res...
3141
3142
3143
3144
3145
  		if (r)
  			goto out;
  		r = 0;
  		break;
  	}
e9f427573   Beth Kon   KVM: PIT support ...
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
  	case KVM_GET_PIT2: {
  		r = -ENXIO;
  		if (!kvm->arch.vpit)
  			goto out;
  		r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
  		if (r)
  			goto out;
  		r = -EFAULT;
  		if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
  			goto out;
  		r = 0;
  		break;
  	}
  	case KVM_SET_PIT2: {
  		r = -EFAULT;
  		if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
  			goto out;
  		r = -ENXIO;
  		if (!kvm->arch.vpit)
  			goto out;
  		r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
  		if (r)
  			goto out;
  		r = 0;
  		break;
  	}
52d939a0b   Marcelo Tosatti   KVM: PIT: provide...
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
  	case KVM_REINJECT_CONTROL: {
  		struct kvm_reinject_control control;
  		r =  -EFAULT;
  		if (copy_from_user(&control, argp, sizeof(control)))
  			goto out;
  		r = kvm_vm_ioctl_reinject(kvm, &control);
  		if (r)
  			goto out;
  		r = 0;
  		break;
  	}
ffde22ac5   Ed Swierk   KVM: Xen PV-on-HV...
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
  	case KVM_XEN_HVM_CONFIG: {
  		r = -EFAULT;
  		if (copy_from_user(&kvm->arch.xen_hvm_config, argp,
  				   sizeof(struct kvm_xen_hvm_config)))
  			goto out;
  		r = -EINVAL;
  		if (kvm->arch.xen_hvm_config.flags)
  			goto out;
  		r = 0;
  		break;
  	}
afbcf7ab8   Glauber Costa   KVM: allow usersp...
3194
  	case KVM_SET_CLOCK: {
afbcf7ab8   Glauber Costa   KVM: allow usersp...
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
  		struct kvm_clock_data user_ns;
  		u64 now_ns;
  		s64 delta;
  
  		r = -EFAULT;
  		if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
  			goto out;
  
  		r = -EINVAL;
  		if (user_ns.flags)
  			goto out;
  
  		r = 0;
395c6b0a9   Avi Kivity   KVM: Disable inte...
3208
  		local_irq_disable();
759379dd6   Zachary Amsden   KVM: x86: Add hel...
3209
  		now_ns = get_kernel_ns();
afbcf7ab8   Glauber Costa   KVM: allow usersp...
3210
  		delta = user_ns.clock - now_ns;
395c6b0a9   Avi Kivity   KVM: Disable inte...
3211
  		local_irq_enable();
afbcf7ab8   Glauber Costa   KVM: allow usersp...
3212
3213
3214
3215
  		kvm->arch.kvmclock_offset = delta;
  		break;
  	}
  	case KVM_GET_CLOCK: {
afbcf7ab8   Glauber Costa   KVM: allow usersp...
3216
3217
  		struct kvm_clock_data user_ns;
  		u64 now_ns;
395c6b0a9   Avi Kivity   KVM: Disable inte...
3218
  		local_irq_disable();
759379dd6   Zachary Amsden   KVM: x86: Add hel...
3219
  		now_ns = get_kernel_ns();
afbcf7ab8   Glauber Costa   KVM: allow usersp...
3220
  		user_ns.clock = kvm->arch.kvmclock_offset + now_ns;
395c6b0a9   Avi Kivity   KVM: Disable inte...
3221
  		local_irq_enable();
afbcf7ab8   Glauber Costa   KVM: allow usersp...
3222
  		user_ns.flags = 0;
97e69aa62   Vasiliy Kulikov   KVM: x86: fix inf...
3223
  		memset(&user_ns.pad, 0, sizeof(user_ns.pad));
afbcf7ab8   Glauber Costa   KVM: allow usersp...
3224
3225
3226
3227
3228
3229
3230
  
  		r = -EFAULT;
  		if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
  			goto out;
  		r = 0;
  		break;
  	}
1fe779f8e   Carsten Otte   KVM: Portability:...
3231
3232
3233
3234
3235
3236
  	default:
  		;
  	}
  out:
  	return r;
  }
a16b043cc   Zhang Xiantao   KVM: Remove __ini...
3237
  static void kvm_init_msr_list(void)
043405e10   Carsten Otte   KVM: Move x86 msr...
3238
3239
3240
  {
  	u32 dummy[2];
  	unsigned i, j;
e3267cbbb   Glauber Costa   KVM: x86: include...
3241
3242
  	/* skip the first msrs in the list. KVM-specific */
  	for (i = j = KVM_SAVE_MSRS_BEGIN; i < ARRAY_SIZE(msrs_to_save); i++) {
043405e10   Carsten Otte   KVM: Move x86 msr...
3243
3244
3245
3246
3247
3248
3249
3250
  		if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
  			continue;
  		if (j < i)
  			msrs_to_save[j] = msrs_to_save[i];
  		j++;
  	}
  	num_msrs_to_save = j;
  }
bda9020e2   Michael S. Tsirkin   KVM: remove in_ra...
3251
3252
  static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
  			   const void *v)
bbd9b64e3   Carsten Otte   KVM: Portability:...
3253
  {
70252a105   Avi Kivity   KVM: extend in-ke...
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
  	int handled = 0;
  	int n;
  
  	do {
  		n = min(len, 8);
  		if (!(vcpu->arch.apic &&
  		      !kvm_iodevice_write(&vcpu->arch.apic->dev, addr, n, v))
  		    && kvm_io_bus_write(vcpu->kvm, KVM_MMIO_BUS, addr, n, v))
  			break;
  		handled += n;
  		addr += n;
  		len -= n;
  		v += n;
  	} while (len);
bbd9b64e3   Carsten Otte   KVM: Portability:...
3268

70252a105   Avi Kivity   KVM: extend in-ke...
3269
  	return handled;
bbd9b64e3   Carsten Otte   KVM: Portability:...
3270
  }
bda9020e2   Michael S. Tsirkin   KVM: remove in_ra...
3271
  static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
bbd9b64e3   Carsten Otte   KVM: Portability:...
3272
  {
70252a105   Avi Kivity   KVM: extend in-ke...
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
  	int handled = 0;
  	int n;
  
  	do {
  		n = min(len, 8);
  		if (!(vcpu->arch.apic &&
  		      !kvm_iodevice_read(&vcpu->arch.apic->dev, addr, n, v))
  		    && kvm_io_bus_read(vcpu->kvm, KVM_MMIO_BUS, addr, n, v))
  			break;
  		trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, *(u64 *)v);
  		handled += n;
  		addr += n;
  		len -= n;
  		v += n;
  	} while (len);
bbd9b64e3   Carsten Otte   KVM: Portability:...
3288

70252a105   Avi Kivity   KVM: extend in-ke...
3289
  	return handled;
bbd9b64e3   Carsten Otte   KVM: Portability:...
3290
  }
2dafc6c23   Gleb Natapov   KVM: x86 emulator...
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
  static void kvm_set_segment(struct kvm_vcpu *vcpu,
  			struct kvm_segment *var, int seg)
  {
  	kvm_x86_ops->set_segment(vcpu, var, seg);
  }
  
  void kvm_get_segment(struct kvm_vcpu *vcpu,
  		     struct kvm_segment *var, int seg)
  {
  	kvm_x86_ops->get_segment(vcpu, var, seg);
  }
e459e3228   Xiao Guangrong   KVM: MMU: move th...
3302
  gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access)
02f59dc9f   Joerg Roedel   KVM: MMU: Introdu...
3303
3304
  {
  	gpa_t t_gpa;
ab9ae3138   Avi Kivity   KVM: Push struct ...
3305
  	struct x86_exception exception;
02f59dc9f   Joerg Roedel   KVM: MMU: Introdu...
3306
3307
3308
3309
3310
  
  	BUG_ON(!mmu_is_nested(vcpu));
  
  	/* NPT walks are always user-walks */
  	access |= PFERR_USER_MASK;
ab9ae3138   Avi Kivity   KVM: Push struct ...
3311
  	t_gpa  = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, &exception);
02f59dc9f   Joerg Roedel   KVM: MMU: Introdu...
3312
3313
3314
  
  	return t_gpa;
  }
ab9ae3138   Avi Kivity   KVM: Push struct ...
3315
3316
  gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
  			      struct x86_exception *exception)
1871c6020   Gleb Natapov   KVM: x86 emulator...
3317
3318
  {
  	u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
ab9ae3138   Avi Kivity   KVM: Push struct ...
3319
  	return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
1871c6020   Gleb Natapov   KVM: x86 emulator...
3320
  }
ab9ae3138   Avi Kivity   KVM: Push struct ...
3321
3322
   gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
  				struct x86_exception *exception)
1871c6020   Gleb Natapov   KVM: x86 emulator...
3323
3324
3325
  {
  	u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
  	access |= PFERR_FETCH_MASK;
ab9ae3138   Avi Kivity   KVM: Push struct ...
3326
  	return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
1871c6020   Gleb Natapov   KVM: x86 emulator...
3327
  }
ab9ae3138   Avi Kivity   KVM: Push struct ...
3328
3329
  gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
  			       struct x86_exception *exception)
1871c6020   Gleb Natapov   KVM: x86 emulator...
3330
3331
3332
  {
  	u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
  	access |= PFERR_WRITE_MASK;
ab9ae3138   Avi Kivity   KVM: Push struct ...
3333
  	return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
1871c6020   Gleb Natapov   KVM: x86 emulator...
3334
3335
3336
  }
  
  /* uses this to access any guest's mapped memory without checking CPL */
ab9ae3138   Avi Kivity   KVM: Push struct ...
3337
3338
  gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
  				struct x86_exception *exception)
1871c6020   Gleb Natapov   KVM: x86 emulator...
3339
  {
ab9ae3138   Avi Kivity   KVM: Push struct ...
3340
  	return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
1871c6020   Gleb Natapov   KVM: x86 emulator...
3341
3342
3343
3344
  }
  
  static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
  				      struct kvm_vcpu *vcpu, u32 access,
bcc55cba9   Avi Kivity   KVM: x86 emulator...
3345
  				      struct x86_exception *exception)
bbd9b64e3   Carsten Otte   KVM: Portability:...
3346
3347
  {
  	void *data = val;
10589a469   Marcelo Tosatti   KVM: MMU: Concurr...
3348
  	int r = X86EMUL_CONTINUE;
bbd9b64e3   Carsten Otte   KVM: Portability:...
3349
3350
  
  	while (bytes) {
14dfe855f   Joerg Roedel   KVM: X86: Introdu...
3351
  		gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
ab9ae3138   Avi Kivity   KVM: Push struct ...
3352
  							    exception);
bbd9b64e3   Carsten Otte   KVM: Portability:...
3353
  		unsigned offset = addr & (PAGE_SIZE-1);
77c2002e7   Izik Eidus   KVM: introduce kv...
3354
  		unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
bbd9b64e3   Carsten Otte   KVM: Portability:...
3355
  		int ret;
bcc55cba9   Avi Kivity   KVM: x86 emulator...
3356
  		if (gpa == UNMAPPED_GVA)
ab9ae3138   Avi Kivity   KVM: Push struct ...
3357
  			return X86EMUL_PROPAGATE_FAULT;
77c2002e7   Izik Eidus   KVM: introduce kv...
3358
  		ret = kvm_read_guest(vcpu->kvm, gpa, data, toread);
10589a469   Marcelo Tosatti   KVM: MMU: Concurr...
3359
  		if (ret < 0) {
c3cd7ffaf   Gleb Natapov   KVM: x86 emulator...
3360
  			r = X86EMUL_IO_NEEDED;
10589a469   Marcelo Tosatti   KVM: MMU: Concurr...
3361
3362
  			goto out;
  		}
bbd9b64e3   Carsten Otte   KVM: Portability:...
3363

77c2002e7   Izik Eidus   KVM: introduce kv...
3364
3365
3366
  		bytes -= toread;
  		data += toread;
  		addr += toread;
bbd9b64e3   Carsten Otte   KVM: Portability:...
3367
  	}
10589a469   Marcelo Tosatti   KVM: MMU: Concurr...
3368
  out:
10589a469   Marcelo Tosatti   KVM: MMU: Concurr...
3369
  	return r;
bbd9b64e3   Carsten Otte   KVM: Portability:...
3370
  }
77c2002e7   Izik Eidus   KVM: introduce kv...
3371

1871c6020   Gleb Natapov   KVM: x86 emulator...
3372
  /* used for instruction fetching */
0f65dd70a   Avi Kivity   KVM: x86 emulator...
3373
3374
  static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
  				gva_t addr, void *val, unsigned int bytes,
bcc55cba9   Avi Kivity   KVM: x86 emulator...
3375
  				struct x86_exception *exception)
1871c6020   Gleb Natapov   KVM: x86 emulator...
3376
  {
0f65dd70a   Avi Kivity   KVM: x86 emulator...
3377
  	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
1871c6020   Gleb Natapov   KVM: x86 emulator...
3378
  	u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
0f65dd70a   Avi Kivity   KVM: x86 emulator...
3379

1871c6020   Gleb Natapov   KVM: x86 emulator...
3380
  	return kvm_read_guest_virt_helper(addr, val, bytes, vcpu,
bcc55cba9   Avi Kivity   KVM: x86 emulator...
3381
3382
  					  access | PFERR_FETCH_MASK,
  					  exception);
1871c6020   Gleb Natapov   KVM: x86 emulator...
3383
  }
064aea774   Nadav Har'El   KVM: nVMX: Decodi...
3384
  int kvm_read_guest_virt(struct x86_emulate_ctxt *ctxt,
0f65dd70a   Avi Kivity   KVM: x86 emulator...
3385
  			       gva_t addr, void *val, unsigned int bytes,
bcc55cba9   Avi Kivity   KVM: x86 emulator...
3386
  			       struct x86_exception *exception)
1871c6020   Gleb Natapov   KVM: x86 emulator...
3387
  {
0f65dd70a   Avi Kivity   KVM: x86 emulator...
3388
  	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
1871c6020   Gleb Natapov   KVM: x86 emulator...
3389
  	u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
0f65dd70a   Avi Kivity   KVM: x86 emulator...
3390

1871c6020   Gleb Natapov   KVM: x86 emulator...
3391
  	return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
bcc55cba9   Avi Kivity   KVM: x86 emulator...
3392
  					  exception);
1871c6020   Gleb Natapov   KVM: x86 emulator...
3393
  }
064aea774   Nadav Har'El   KVM: nVMX: Decodi...
3394
  EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
1871c6020   Gleb Natapov   KVM: x86 emulator...
3395

0f65dd70a   Avi Kivity   KVM: x86 emulator...
3396
3397
  static int kvm_read_guest_virt_system(struct x86_emulate_ctxt *ctxt,
  				      gva_t addr, void *val, unsigned int bytes,
bcc55cba9   Avi Kivity   KVM: x86 emulator...
3398
  				      struct x86_exception *exception)
1871c6020   Gleb Natapov   KVM: x86 emulator...
3399
  {
0f65dd70a   Avi Kivity   KVM: x86 emulator...
3400
  	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
bcc55cba9   Avi Kivity   KVM: x86 emulator...
3401
  	return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, 0, exception);
1871c6020   Gleb Natapov   KVM: x86 emulator...
3402
  }
6a4d75506   Nadav Har'El   KVM: nVMX: Implem...
3403
  int kvm_write_guest_virt_system(struct x86_emulate_ctxt *ctxt,
0f65dd70a   Avi Kivity   KVM: x86 emulator...
3404
  				       gva_t addr, void *val,
2dafc6c23   Gleb Natapov   KVM: x86 emulator...
3405
  				       unsigned int bytes,
bcc55cba9   Avi Kivity   KVM: x86 emulator...
3406
  				       struct x86_exception *exception)
77c2002e7   Izik Eidus   KVM: introduce kv...
3407
  {
0f65dd70a   Avi Kivity   KVM: x86 emulator...
3408
  	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
77c2002e7   Izik Eidus   KVM: introduce kv...
3409
3410
3411
3412
  	void *data = val;
  	int r = X86EMUL_CONTINUE;
  
  	while (bytes) {
14dfe855f   Joerg Roedel   KVM: X86: Introdu...
3413
3414
  		gpa_t gpa =  vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
  							     PFERR_WRITE_MASK,
ab9ae3138   Avi Kivity   KVM: Push struct ...
3415
  							     exception);
77c2002e7   Izik Eidus   KVM: introduce kv...
3416
3417
3418
  		unsigned offset = addr & (PAGE_SIZE-1);
  		unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
  		int ret;
bcc55cba9   Avi Kivity   KVM: x86 emulator...
3419
  		if (gpa == UNMAPPED_GVA)
ab9ae3138   Avi Kivity   KVM: Push struct ...
3420
  			return X86EMUL_PROPAGATE_FAULT;
77c2002e7   Izik Eidus   KVM: introduce kv...
3421
3422
  		ret = kvm_write_guest(vcpu->kvm, gpa, data, towrite);
  		if (ret < 0) {
c3cd7ffaf   Gleb Natapov   KVM: x86 emulator...
3423
  			r = X86EMUL_IO_NEEDED;
77c2002e7   Izik Eidus   KVM: introduce kv...
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
  			goto out;
  		}
  
  		bytes -= towrite;
  		data += towrite;
  		addr += towrite;
  	}
  out:
  	return r;
  }
6a4d75506   Nadav Har'El   KVM: nVMX: Implem...
3434
  EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
77c2002e7   Izik Eidus   KVM: introduce kv...
3435

af7cc7d1e   Xiao Guangrong   KVM: x86: introdu...
3436
3437
3438
3439
3440
  static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
  				gpa_t *gpa, struct x86_exception *exception,
  				bool write)
  {
  	u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
bebb106a5   Xiao Guangrong   KVM: MMU: cache m...
3441
3442
3443
3444
3445
  	if (vcpu_match_mmio_gva(vcpu, gva) &&
  		  check_write_user_access(vcpu, write, access,
  		  vcpu->arch.access)) {
  		*gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
  					(gva & (PAGE_SIZE - 1));
4f0226482   Xiao Guangrong   KVM: MMU: trace m...
3446
  		trace_vcpu_match_mmio(gva, *gpa, write, false);
bebb106a5   Xiao Guangrong   KVM: MMU: cache m...
3447
3448
  		return 1;
  	}
af7cc7d1e   Xiao Guangrong   KVM: x86: introdu...
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
  	if (write)
  		access |= PFERR_WRITE_MASK;
  
  	*gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
  
  	if (*gpa == UNMAPPED_GVA)
  		return -1;
  
  	/* For APIC access vmexit */
  	if ((*gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
  		return 1;
4f0226482   Xiao Guangrong   KVM: MMU: trace m...
3460
3461
  	if (vcpu_match_mmio_gpa(vcpu, *gpa)) {
  		trace_vcpu_match_mmio(gva, *gpa, write, true);
bebb106a5   Xiao Guangrong   KVM: MMU: cache m...
3462
  		return 1;
4f0226482   Xiao Guangrong   KVM: MMU: trace m...
3463
  	}
bebb106a5   Xiao Guangrong   KVM: MMU: cache m...
3464

af7cc7d1e   Xiao Guangrong   KVM: x86: introdu...
3465
3466
  	return 0;
  }
3200f405a   Marcelo Tosatti   KVM: MMU: unify s...
3467
  int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
bcc55cba9   Avi Kivity   KVM: x86 emulator...
3468
  			const void *val, int bytes)
bbd9b64e3   Carsten Otte   KVM: Portability:...
3469
3470
3471
3472
  {
  	int ret;
  
  	ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
9f8112859   Avi Kivity   KVM: Provide unlo...
3473
  	if (ret < 0)
bbd9b64e3   Carsten Otte   KVM: Portability:...
3474
  		return 0;
f57f2ef58   Xiao Guangrong   KVM: MMU: fast pr...
3475
  	kvm_mmu_pte_write(vcpu, gpa, val, bytes);
bbd9b64e3   Carsten Otte   KVM: Portability:...
3476
3477
  	return 1;
  }
77d197b2c   Xiao Guangrong   KVM: x86: abstrac...
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
  struct read_write_emulator_ops {
  	int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
  				  int bytes);
  	int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
  				  void *val, int bytes);
  	int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
  			       int bytes, void *val);
  	int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
  				    void *val, int bytes);
  	bool write;
  };
  
  static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
  {
  	if (vcpu->mmio_read_completed) {
  		memcpy(val, vcpu->mmio_data, bytes);
  		trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
  			       vcpu->mmio_phys_addr, *(u64 *)val);
  		vcpu->mmio_read_completed = 0;
  		return 1;
  	}
  
  	return 0;
  }
  
  static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
  			void *val, int bytes)
  {
  	return !kvm_read_guest(vcpu->kvm, gpa, val, bytes);
  }
  
  static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
  			 void *val, int bytes)
  {
  	return emulator_write_phys(vcpu, gpa, val, bytes);
  }
  
  static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
  {
  	trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, *(u64 *)val);
  	return vcpu_mmio_write(vcpu, gpa, bytes, val);
  }
  
  static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
  			  void *val, int bytes)
  {
  	trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, 0);
  	return X86EMUL_IO_NEEDED;
  }
  
  static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
  			   void *val, int bytes)
  {
  	memcpy(vcpu->mmio_data, val, bytes);
  	memcpy(vcpu->run->mmio.data, vcpu->mmio_data, 8);
  	return X86EMUL_CONTINUE;
  }
  
  static struct read_write_emulator_ops read_emultor = {
  	.read_write_prepare = read_prepare,
  	.read_write_emulate = read_emulate,
  	.read_write_mmio = vcpu_mmio_read,
  	.read_write_exit_mmio = read_exit_mmio,
  };
  
  static struct read_write_emulator_ops write_emultor = {
  	.read_write_emulate = write_emulate,
  	.read_write_mmio = write_mmio,
  	.read_write_exit_mmio = write_exit_mmio,
  	.write = true,
  };
22388a3c8   Xiao Guangrong   KVM: x86: cleanup...
3549
3550
3551
3552
3553
  static int emulator_read_write_onepage(unsigned long addr, void *val,
  				       unsigned int bytes,
  				       struct x86_exception *exception,
  				       struct kvm_vcpu *vcpu,
  				       struct read_write_emulator_ops *ops)
bbd9b64e3   Carsten Otte   KVM: Portability:...
3554
  {
af7cc7d1e   Xiao Guangrong   KVM: x86: introdu...
3555
3556
  	gpa_t gpa;
  	int handled, ret;
22388a3c8   Xiao Guangrong   KVM: x86: cleanup...
3557
3558
3559
3560
3561
  	bool write = ops->write;
  
  	if (ops->read_write_prepare &&
  		  ops->read_write_prepare(vcpu, val, bytes))
  		return X86EMUL_CONTINUE;
10589a469   Marcelo Tosatti   KVM: MMU: Concurr...
3562

22388a3c8   Xiao Guangrong   KVM: x86: cleanup...
3563
  	ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
bbd9b64e3   Carsten Otte   KVM: Portability:...
3564

af7cc7d1e   Xiao Guangrong   KVM: x86: introdu...
3565
  	if (ret < 0)
bbd9b64e3   Carsten Otte   KVM: Portability:...
3566
  		return X86EMUL_PROPAGATE_FAULT;
bbd9b64e3   Carsten Otte   KVM: Portability:...
3567
3568
  
  	/* For APIC access vmexit */
af7cc7d1e   Xiao Guangrong   KVM: x86: introdu...
3569
  	if (ret)
bbd9b64e3   Carsten Otte   KVM: Portability:...
3570
  		goto mmio;
22388a3c8   Xiao Guangrong   KVM: x86: cleanup...
3571
  	if (ops->read_write_emulate(vcpu, gpa, val, bytes))
bbd9b64e3   Carsten Otte   KVM: Portability:...
3572
3573
3574
3575
3576
3577
  		return X86EMUL_CONTINUE;
  
  mmio:
  	/*
  	 * Is this MMIO handled locally?
  	 */
22388a3c8   Xiao Guangrong   KVM: x86: cleanup...
3578
  	handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
70252a105   Avi Kivity   KVM: extend in-ke...
3579
  	if (handled == bytes)
bbd9b64e3   Carsten Otte   KVM: Portability:...
3580
  		return X86EMUL_CONTINUE;
bbd9b64e3   Carsten Otte   KVM: Portability:...
3581

70252a105   Avi Kivity   KVM: extend in-ke...
3582
3583
3584
  	gpa += handled;
  	bytes -= handled;
  	val += handled;
bbd9b64e3   Carsten Otte   KVM: Portability:...
3585
  	vcpu->mmio_needed = 1;
411c35b7e   Gleb Natapov   KVM: fill in run-...
3586
3587
  	vcpu->run->exit_reason = KVM_EXIT_MMIO;
  	vcpu->run->mmio.phys_addr = vcpu->mmio_phys_addr = gpa;
cef4dea07   Avi Kivity   KVM: 16-byte mmio...
3588
3589
  	vcpu->mmio_size = bytes;
  	vcpu->run->mmio.len = min(vcpu->mmio_size, 8);
22388a3c8   Xiao Guangrong   KVM: x86: cleanup...
3590
  	vcpu->run->mmio.is_write = vcpu->mmio_is_write = write;
cef4dea07   Avi Kivity   KVM: 16-byte mmio...
3591
  	vcpu->mmio_index = 0;
bbd9b64e3   Carsten Otte   KVM: Portability:...
3592

22388a3c8   Xiao Guangrong   KVM: x86: cleanup...
3593
  	return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
bbd9b64e3   Carsten Otte   KVM: Portability:...
3594
  }
22388a3c8   Xiao Guangrong   KVM: x86: cleanup...
3595
3596
3597
3598
  int emulator_read_write(struct x86_emulate_ctxt *ctxt, unsigned long addr,
  			void *val, unsigned int bytes,
  			struct x86_exception *exception,
  			struct read_write_emulator_ops *ops)
bbd9b64e3   Carsten Otte   KVM: Portability:...
3599
  {
0f65dd70a   Avi Kivity   KVM: x86 emulator...
3600
  	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
bbd9b64e3   Carsten Otte   KVM: Portability:...
3601
3602
3603
3604
3605
  	/* Crossing a page boundary? */
  	if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
  		int rc, now;
  
  		now = -addr & ~PAGE_MASK;
22388a3c8   Xiao Guangrong   KVM: x86: cleanup...
3606
3607
  		rc = emulator_read_write_onepage(addr, val, now, exception,
  						 vcpu, ops);
bbd9b64e3   Carsten Otte   KVM: Portability:...
3608
3609
3610
3611
3612
3613
  		if (rc != X86EMUL_CONTINUE)
  			return rc;
  		addr += now;
  		val += now;
  		bytes -= now;
  	}
22388a3c8   Xiao Guangrong   KVM: x86: cleanup...
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
  
  	return emulator_read_write_onepage(addr, val, bytes, exception,
  					   vcpu, ops);
  }
  
  static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
  				  unsigned long addr,
  				  void *val,
  				  unsigned int bytes,
  				  struct x86_exception *exception)
  {
  	return emulator_read_write(ctxt, addr, val, bytes,
  				   exception, &read_emultor);
  }
  
  int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
  			    unsigned long addr,
  			    const void *val,
  			    unsigned int bytes,
  			    struct x86_exception *exception)
  {
  	return emulator_read_write(ctxt, addr, (void *)val, bytes,
  				   exception, &write_emultor);
bbd9b64e3   Carsten Otte   KVM: Portability:...
3637
  }
bbd9b64e3   Carsten Otte   KVM: Portability:...
3638

daea3e73c   Avi Kivity   KVM: Make locked ...
3639
3640
3641
3642
3643
3644
3645
  #define CMPXCHG_TYPE(t, ptr, old, new) \
  	(cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
  
  #ifdef CONFIG_X86_64
  #  define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
  #else
  #  define CMPXCHG64(ptr, old, new) \
9749a6c0f   Jan Kiszka   KVM: x86: Fix 32-...
3646
  	(cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
daea3e73c   Avi Kivity   KVM: Make locked ...
3647
  #endif
0f65dd70a   Avi Kivity   KVM: x86 emulator...
3648
3649
  static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
  				     unsigned long addr,
bbd9b64e3   Carsten Otte   KVM: Portability:...
3650
3651
3652
  				     const void *old,
  				     const void *new,
  				     unsigned int bytes,
0f65dd70a   Avi Kivity   KVM: x86 emulator...
3653
  				     struct x86_exception *exception)
bbd9b64e3   Carsten Otte   KVM: Portability:...
3654
  {
0f65dd70a   Avi Kivity   KVM: x86 emulator...
3655
  	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
daea3e73c   Avi Kivity   KVM: Make locked ...
3656
3657
3658
3659
  	gpa_t gpa;
  	struct page *page;
  	char *kaddr;
  	bool exchanged;
2bacc55c7   Marcelo Tosatti   KVM: MMU: emulate...
3660

daea3e73c   Avi Kivity   KVM: Make locked ...
3661
3662
3663
  	/* guests cmpxchg8b have to be emulated atomically */
  	if (bytes > 8 || (bytes & (bytes - 1)))
  		goto emul_write;
10589a469   Marcelo Tosatti   KVM: MMU: Concurr...
3664

daea3e73c   Avi Kivity   KVM: Make locked ...
3665
  	gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
2bacc55c7   Marcelo Tosatti   KVM: MMU: emulate...
3666

daea3e73c   Avi Kivity   KVM: Make locked ...
3667
3668
3669
  	if (gpa == UNMAPPED_GVA ||
  	    (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
  		goto emul_write;
2bacc55c7   Marcelo Tosatti   KVM: MMU: emulate...
3670

daea3e73c   Avi Kivity   KVM: Make locked ...
3671
3672
  	if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
  		goto emul_write;
72dc67a69   Izik Eidus   KVM: remove the u...
3673

daea3e73c   Avi Kivity   KVM: Make locked ...
3674
  	page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
c19b8bd60   Wei Yongjun   KVM: x86 emulator...
3675
3676
3677
3678
  	if (is_error_page(page)) {
  		kvm_release_page_clean(page);
  		goto emul_write;
  	}
72dc67a69   Izik Eidus   KVM: remove the u...
3679

daea3e73c   Avi Kivity   KVM: Make locked ...
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
  	kaddr = kmap_atomic(page, KM_USER0);
  	kaddr += offset_in_page(gpa);
  	switch (bytes) {
  	case 1:
  		exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
  		break;
  	case 2:
  		exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
  		break;
  	case 4:
  		exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
  		break;
  	case 8:
  		exchanged = CMPXCHG64(kaddr, old, new);
  		break;
  	default:
  		BUG();
2bacc55c7   Marcelo Tosatti   KVM: MMU: emulate...
3697
  	}
daea3e73c   Avi Kivity   KVM: Make locked ...
3698
3699
3700
3701
3702
  	kunmap_atomic(kaddr, KM_USER0);
  	kvm_release_page_dirty(page);
  
  	if (!exchanged)
  		return X86EMUL_CMPXCHG_FAILED;
f57f2ef58   Xiao Guangrong   KVM: MMU: fast pr...
3703
  	kvm_mmu_pte_write(vcpu, gpa, new, bytes);
8f6abd06f   Gleb Natapov   KVM: x86: get rid...
3704
3705
  
  	return X86EMUL_CONTINUE;
4a5f48f66   Avi Kivity   KVM: Don't follow...
3706

3200f405a   Marcelo Tosatti   KVM: MMU: unify s...
3707
  emul_write:
daea3e73c   Avi Kivity   KVM: Make locked ...
3708
3709
  	printk_once(KERN_WARNING "kvm: emulating exchange as write
  ");
2bacc55c7   Marcelo Tosatti   KVM: MMU: emulate...
3710

0f65dd70a   Avi Kivity   KVM: x86 emulator...
3711
  	return emulator_write_emulated(ctxt, addr, new, bytes, exception);
bbd9b64e3   Carsten Otte   KVM: Portability:...
3712
  }
cf8f70bfe   Gleb Natapov   KVM: x86 emulator...
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
  static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
  {
  	/* TODO: String I/O for in kernel device */
  	int r;
  
  	if (vcpu->arch.pio.in)
  		r = kvm_io_bus_read(vcpu->kvm, KVM_PIO_BUS, vcpu->arch.pio.port,
  				    vcpu->arch.pio.size, pd);
  	else
  		r = kvm_io_bus_write(vcpu->kvm, KVM_PIO_BUS,
  				     vcpu->arch.pio.port, vcpu->arch.pio.size,
  				     pd);
  	return r;
  }
6f6fbe98c   Xiao Guangrong   KVM: x86: cleanup...
3727
3728
3729
  static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
  			       unsigned short port, void *val,
  			       unsigned int count, bool in)
cf8f70bfe   Gleb Natapov   KVM: x86 emulator...
3730
  {
6f6fbe98c   Xiao Guangrong   KVM: x86: cleanup...
3731
  	trace_kvm_pio(!in, port, size, count);
cf8f70bfe   Gleb Natapov   KVM: x86 emulator...
3732
3733
  
  	vcpu->arch.pio.port = port;
6f6fbe98c   Xiao Guangrong   KVM: x86: cleanup...
3734
  	vcpu->arch.pio.in = in;
7972995b0   Gleb Natapov   KVM: x86 emulator...
3735
  	vcpu->arch.pio.count  = count;
cf8f70bfe   Gleb Natapov   KVM: x86 emulator...
3736
3737
3738
  	vcpu->arch.pio.size = size;
  
  	if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
7972995b0   Gleb Natapov   KVM: x86 emulator...
3739
  		vcpu->arch.pio.count = 0;
cf8f70bfe   Gleb Natapov   KVM: x86 emulator...
3740
3741
3742
3743
  		return 1;
  	}
  
  	vcpu->run->exit_reason = KVM_EXIT_IO;
6f6fbe98c   Xiao Guangrong   KVM: x86: cleanup...
3744
  	vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
cf8f70bfe   Gleb Natapov   KVM: x86 emulator...
3745
3746
3747
3748
3749
3750
3751
  	vcpu->run->io.size = size;
  	vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
  	vcpu->run->io.count = count;
  	vcpu->run->io.port = port;
  
  	return 0;
  }
6f6fbe98c   Xiao Guangrong   KVM: x86: cleanup...
3752
3753
3754
  static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
  				    int size, unsigned short port, void *val,
  				    unsigned int count)
cf8f70bfe   Gleb Natapov   KVM: x86 emulator...
3755
  {
ca1d4a9e7   Avi Kivity   KVM: x86 emulator...
3756
  	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6f6fbe98c   Xiao Guangrong   KVM: x86: cleanup...
3757
  	int ret;
ca1d4a9e7   Avi Kivity   KVM: x86 emulator...
3758

6f6fbe98c   Xiao Guangrong   KVM: x86: cleanup...
3759
3760
  	if (vcpu->arch.pio.count)
  		goto data_avail;
cf8f70bfe   Gleb Natapov   KVM: x86 emulator...
3761

6f6fbe98c   Xiao Guangrong   KVM: x86: cleanup...
3762
3763
3764
3765
  	ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
  	if (ret) {
  data_avail:
  		memcpy(val, vcpu->arch.pio_data, size * count);
7972995b0   Gleb Natapov   KVM: x86 emulator...
3766
  		vcpu->arch.pio.count = 0;
cf8f70bfe   Gleb Natapov   KVM: x86 emulator...
3767
3768
  		return 1;
  	}
cf8f70bfe   Gleb Natapov   KVM: x86 emulator...
3769
3770
  	return 0;
  }
6f6fbe98c   Xiao Guangrong   KVM: x86: cleanup...
3771
3772
3773
3774
3775
3776
3777
3778
3779
  static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
  				     int size, unsigned short port,
  				     const void *val, unsigned int count)
  {
  	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  
  	memcpy(vcpu->arch.pio_data, val, size * count);
  	return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
  }
bbd9b64e3   Carsten Otte   KVM: Portability:...
3780
3781
3782
3783
  static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
  {
  	return kvm_x86_ops->get_segment_base(vcpu, seg);
  }
3cb16fe78   Avi Kivity   KVM: x86 emulator...
3784
  static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
bbd9b64e3   Carsten Otte   KVM: Portability:...
3785
  {
3cb16fe78   Avi Kivity   KVM: x86 emulator...
3786
  	kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
bbd9b64e3   Carsten Otte   KVM: Portability:...
3787
  }
f5f48ee15   Sheng Yang   KVM: VMX: Execute...
3788
3789
3790
3791
3792
3793
  int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
  {
  	if (!need_emulate_wbinvd(vcpu))
  		return X86EMUL_CONTINUE;
  
  	if (kvm_x86_ops->has_wbinvd_exit()) {
2eec73437   Jan Kiszka   KVM: x86: Avoid i...
3794
3795
3796
  		int cpu = get_cpu();
  
  		cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
f5f48ee15   Sheng Yang   KVM: VMX: Execute...
3797
3798
  		smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
  				wbinvd_ipi, NULL, 1);
2eec73437   Jan Kiszka   KVM: x86: Avoid i...
3799
  		put_cpu();
f5f48ee15   Sheng Yang   KVM: VMX: Execute...
3800
  		cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
2eec73437   Jan Kiszka   KVM: x86: Avoid i...
3801
3802
  	} else
  		wbinvd();
f5f48ee15   Sheng Yang   KVM: VMX: Execute...
3803
3804
3805
  	return X86EMUL_CONTINUE;
  }
  EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
bcaf5cc54   Avi Kivity   KVM: x86 emulator...
3806
3807
3808
3809
  static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
  {
  	kvm_emulate_wbinvd(emul_to_vcpu(ctxt));
  }
717746e38   Avi Kivity   KVM: x86 emulator...
3810
  int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long *dest)
bbd9b64e3   Carsten Otte   KVM: Portability:...
3811
  {
717746e38   Avi Kivity   KVM: x86 emulator...
3812
  	return _kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
bbd9b64e3   Carsten Otte   KVM: Portability:...
3813
  }
717746e38   Avi Kivity   KVM: x86 emulator...
3814
  int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
bbd9b64e3   Carsten Otte   KVM: Portability:...
3815
  {
338dbc978   Gleb Natapov   KVM: x86 emulator...
3816

717746e38   Avi Kivity   KVM: x86 emulator...
3817
  	return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
bbd9b64e3   Carsten Otte   KVM: Portability:...
3818
  }
52a466173   Gleb Natapov   KVM: Provide call...
3819
  static u64 mk_cr_64(u64 curr_cr, u32 new_val)
5fdbf9765   Marcelo Tosatti   KVM: x86: accesso...
3820
  {
52a466173   Gleb Natapov   KVM: Provide call...
3821
  	return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
5fdbf9765   Marcelo Tosatti   KVM: x86: accesso...
3822
  }
717746e38   Avi Kivity   KVM: x86 emulator...
3823
  static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
bbd9b64e3   Carsten Otte   KVM: Portability:...
3824
  {
717746e38   Avi Kivity   KVM: x86 emulator...
3825
  	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
52a466173   Gleb Natapov   KVM: Provide call...
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
  	unsigned long value;
  
  	switch (cr) {
  	case 0:
  		value = kvm_read_cr0(vcpu);
  		break;
  	case 2:
  		value = vcpu->arch.cr2;
  		break;
  	case 3:
9f8fe5043   Avi Kivity   KVM: Replace read...
3836
  		value = kvm_read_cr3(vcpu);
52a466173   Gleb Natapov   KVM: Provide call...
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
  		break;
  	case 4:
  		value = kvm_read_cr4(vcpu);
  		break;
  	case 8:
  		value = kvm_get_cr8(vcpu);
  		break;
  	default:
  		vcpu_printf(vcpu, "%s: unexpected cr %u
  ", __func__, cr);
  		return 0;
  	}
  
  	return value;
  }
717746e38   Avi Kivity   KVM: x86 emulator...
3852
  static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
52a466173   Gleb Natapov   KVM: Provide call...
3853
  {
717746e38   Avi Kivity   KVM: x86 emulator...
3854
  	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
0f12244fe   Gleb Natapov   KVM: x86 emulator...
3855
  	int res = 0;
52a466173   Gleb Natapov   KVM: Provide call...
3856
3857
  	switch (cr) {
  	case 0:
49a9b07ed   Avi Kivity   KVM: Fix mov cr0 ...
3858
  		res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
52a466173   Gleb Natapov   KVM: Provide call...
3859
3860
3861
3862
3863
  		break;
  	case 2:
  		vcpu->arch.cr2 = val;
  		break;
  	case 3:
2390218b6   Avi Kivity   KVM: Fix mov cr3 ...
3864
  		res = kvm_set_cr3(vcpu, val);
52a466173   Gleb Natapov   KVM: Provide call...
3865
3866
  		break;
  	case 4:
a83b29c6a   Avi Kivity   KVM: Fix mov cr4 ...
3867
  		res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
52a466173   Gleb Natapov   KVM: Provide call...
3868
3869
  		break;
  	case 8:
eea1cff9a   Andre Przywara   KVM: x86: fix CR8...
3870
  		res = kvm_set_cr8(vcpu, val);
52a466173   Gleb Natapov   KVM: Provide call...
3871
3872
3873
3874
  		break;
  	default:
  		vcpu_printf(vcpu, "%s: unexpected cr %u
  ", __func__, cr);
0f12244fe   Gleb Natapov   KVM: x86 emulator...
3875
  		res = -1;
52a466173   Gleb Natapov   KVM: Provide call...
3876
  	}
0f12244fe   Gleb Natapov   KVM: x86 emulator...
3877
3878
  
  	return res;
52a466173   Gleb Natapov   KVM: Provide call...
3879
  }
717746e38   Avi Kivity   KVM: x86 emulator...
3880
  static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
9c5372445   Gleb Natapov   KVM: Provide x86_...
3881
  {
717746e38   Avi Kivity   KVM: x86 emulator...
3882
  	return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
9c5372445   Gleb Natapov   KVM: Provide x86_...
3883
  }
4bff1e86a   Avi Kivity   KVM: x86 emulator...
3884
  static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
2dafc6c23   Gleb Natapov   KVM: x86 emulator...
3885
  {
4bff1e86a   Avi Kivity   KVM: x86 emulator...
3886
  	kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
2dafc6c23   Gleb Natapov   KVM: x86 emulator...
3887
  }
4bff1e86a   Avi Kivity   KVM: x86 emulator...
3888
  static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
160ce1f1a   Mohammed Gamal   KVM: x86 emulator...
3889
  {
4bff1e86a   Avi Kivity   KVM: x86 emulator...
3890
  	kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
160ce1f1a   Mohammed Gamal   KVM: x86 emulator...
3891
  }
1ac9d0cfb   Avi Kivity   KVM: x86 emulator...
3892
3893
3894
3895
3896
3897
3898
3899
3900
  static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
  {
  	kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
  }
  
  static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
  {
  	kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
  }
4bff1e86a   Avi Kivity   KVM: x86 emulator...
3901
3902
  static unsigned long emulator_get_cached_segment_base(
  	struct x86_emulate_ctxt *ctxt, int seg)
5951c4423   Gleb Natapov   KVM: x86 emulator...
3903
  {
4bff1e86a   Avi Kivity   KVM: x86 emulator...
3904
  	return get_segment_base(emul_to_vcpu(ctxt), seg);
5951c4423   Gleb Natapov   KVM: x86 emulator...
3905
  }
1aa366163   Avi Kivity   KVM: x86 emulator...
3906
3907
3908
  static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
  				 struct desc_struct *desc, u32 *base3,
  				 int seg)
2dafc6c23   Gleb Natapov   KVM: x86 emulator...
3909
3910
  {
  	struct kvm_segment var;
4bff1e86a   Avi Kivity   KVM: x86 emulator...
3911
  	kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
1aa366163   Avi Kivity   KVM: x86 emulator...
3912
  	*selector = var.selector;
2dafc6c23   Gleb Natapov   KVM: x86 emulator...
3913
3914
3915
3916
3917
3918
3919
3920
  
  	if (var.unusable)
  		return false;
  
  	if (var.g)
  		var.limit >>= 12;
  	set_desc_limit(desc, var.limit);
  	set_desc_base(desc, (unsigned long)var.base);
5601d05b8   Gleb Natapov   KVM: emulator: Fi...
3921
3922
3923
3924
  #ifdef CONFIG_X86_64
  	if (base3)
  		*base3 = var.base >> 32;
  #endif
2dafc6c23   Gleb Natapov   KVM: x86 emulator...
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
  	desc->type = var.type;
  	desc->s = var.s;
  	desc->dpl = var.dpl;
  	desc->p = var.present;
  	desc->avl = var.avl;
  	desc->l = var.l;
  	desc->d = var.db;
  	desc->g = var.g;
  
  	return true;
  }
1aa366163   Avi Kivity   KVM: x86 emulator...
3936
3937
3938
  static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
  				 struct desc_struct *desc, u32 base3,
  				 int seg)
2dafc6c23   Gleb Natapov   KVM: x86 emulator...
3939
  {
4bff1e86a   Avi Kivity   KVM: x86 emulator...
3940
  	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
2dafc6c23   Gleb Natapov   KVM: x86 emulator...
3941
  	struct kvm_segment var;
1aa366163   Avi Kivity   KVM: x86 emulator...
3942
  	var.selector = selector;
2dafc6c23   Gleb Natapov   KVM: x86 emulator...
3943
  	var.base = get_desc_base(desc);
5601d05b8   Gleb Natapov   KVM: emulator: Fi...
3944
3945
3946
  #ifdef CONFIG_X86_64
  	var.base |= ((u64)base3) << 32;
  #endif
2dafc6c23   Gleb Natapov   KVM: x86 emulator...
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
  	var.limit = get_desc_limit(desc);
  	if (desc->g)
  		var.limit = (var.limit << 12) | 0xfff;
  	var.type = desc->type;
  	var.present = desc->p;
  	var.dpl = desc->dpl;
  	var.db = desc->d;
  	var.s = desc->s;
  	var.l = desc->l;
  	var.g = desc->g;
  	var.avl = desc->avl;
  	var.present = desc->p;
  	var.unusable = !var.present;
  	var.padding = 0;
  
  	kvm_set_segment(vcpu, &var, seg);
  	return;
  }
717746e38   Avi Kivity   KVM: x86 emulator...
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
  static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
  			    u32 msr_index, u64 *pdata)
  {
  	return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
  }
  
  static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
  			    u32 msr_index, u64 data)
  {
  	return kvm_set_msr(emul_to_vcpu(ctxt), msr_index, data);
  }
222d21aa0   Avi Kivity   KVM: x86 emulator...
3976
3977
3978
3979
3980
  static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
  			     u32 pmc, u64 *pdata)
  {
  	return kvm_pmu_read_pmc(emul_to_vcpu(ctxt), pmc, pdata);
  }
6c3287f7c   Avi Kivity   KVM: x86 emulator...
3981
3982
3983
3984
  static void emulator_halt(struct x86_emulate_ctxt *ctxt)
  {
  	emul_to_vcpu(ctxt)->arch.halt_request = 1;
  }
5037f6f32   Avi Kivity   KVM: x86 emulator...
3985
3986
3987
  static void emulator_get_fpu(struct x86_emulate_ctxt *ctxt)
  {
  	preempt_disable();
5197b808a   Avi Kivity   KVM: Avoid using ...
3988
  	kvm_load_guest_fpu(emul_to_vcpu(ctxt));
5037f6f32   Avi Kivity   KVM: x86 emulator...
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
  	/*
  	 * CR0.TS may reference the host fpu state, not the guest fpu state,
  	 * so it may be clear at this point.
  	 */
  	clts();
  }
  
  static void emulator_put_fpu(struct x86_emulate_ctxt *ctxt)
  {
  	preempt_enable();
  }
2953538eb   Avi Kivity   KVM: x86 emulator...
4000
  static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
8a76d7f25   Joerg Roedel   KVM: x86: Add x86...
4001
  			      struct x86_instruction_info *info,
c4f035c60   Avi Kivity   KVM: x86 emulator...
4002
4003
  			      enum x86_intercept_stage stage)
  {
2953538eb   Avi Kivity   KVM: x86 emulator...
4004
  	return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
c4f035c60   Avi Kivity   KVM: x86 emulator...
4005
  }
14af3f3c5   Harvey Harrison   KVM: sparse fixes...
4006
  static struct x86_emulate_ops emulate_ops = {
1871c6020   Gleb Natapov   KVM: x86 emulator...
4007
  	.read_std            = kvm_read_guest_virt_system,
2dafc6c23   Gleb Natapov   KVM: x86 emulator...
4008
  	.write_std           = kvm_write_guest_virt_system,
1871c6020   Gleb Natapov   KVM: x86 emulator...
4009
  	.fetch               = kvm_fetch_guest_virt,
bbd9b64e3   Carsten Otte   KVM: Portability:...
4010
4011
4012
  	.read_emulated       = emulator_read_emulated,
  	.write_emulated      = emulator_write_emulated,
  	.cmpxchg_emulated    = emulator_cmpxchg_emulated,
3cb16fe78   Avi Kivity   KVM: x86 emulator...
4013
  	.invlpg              = emulator_invlpg,
cf8f70bfe   Gleb Natapov   KVM: x86 emulator...
4014
4015
  	.pio_in_emulated     = emulator_pio_in_emulated,
  	.pio_out_emulated    = emulator_pio_out_emulated,
1aa366163   Avi Kivity   KVM: x86 emulator...
4016
4017
  	.get_segment         = emulator_get_segment,
  	.set_segment         = emulator_set_segment,
5951c4423   Gleb Natapov   KVM: x86 emulator...
4018
  	.get_cached_segment_base = emulator_get_cached_segment_base,
2dafc6c23   Gleb Natapov   KVM: x86 emulator...
4019
  	.get_gdt             = emulator_get_gdt,
160ce1f1a   Mohammed Gamal   KVM: x86 emulator...
4020
  	.get_idt	     = emulator_get_idt,
1ac9d0cfb   Avi Kivity   KVM: x86 emulator...
4021
4022
  	.set_gdt             = emulator_set_gdt,
  	.set_idt	     = emulator_set_idt,
52a466173   Gleb Natapov   KVM: Provide call...
4023
4024
  	.get_cr              = emulator_get_cr,
  	.set_cr              = emulator_set_cr,
9c5372445   Gleb Natapov   KVM: Provide x86_...
4025
  	.cpl                 = emulator_get_cpl,
35aa5375d   Gleb Natapov   KVM: x86 emulator...
4026
4027
  	.get_dr              = emulator_get_dr,
  	.set_dr              = emulator_set_dr,
717746e38   Avi Kivity   KVM: x86 emulator...
4028
4029
  	.set_msr             = emulator_set_msr,
  	.get_msr             = emulator_get_msr,
222d21aa0   Avi Kivity   KVM: x86 emulator...
4030
  	.read_pmc            = emulator_read_pmc,
6c3287f7c   Avi Kivity   KVM: x86 emulator...
4031
  	.halt                = emulator_halt,
bcaf5cc54   Avi Kivity   KVM: x86 emulator...
4032
  	.wbinvd              = emulator_wbinvd,
d6aa10003   Avi Kivity   KVM: x86 emulator...
4033
  	.fix_hypercall       = emulator_fix_hypercall,
5037f6f32   Avi Kivity   KVM: x86 emulator...
4034
4035
  	.get_fpu             = emulator_get_fpu,
  	.put_fpu             = emulator_put_fpu,
c4f035c60   Avi Kivity   KVM: x86 emulator...
4036
  	.intercept           = emulator_intercept,
bbd9b64e3   Carsten Otte   KVM: Portability:...
4037
  };
5fdbf9765   Marcelo Tosatti   KVM: x86: accesso...
4038
4039
4040
4041
4042
4043
4044
  static void cache_all_regs(struct kvm_vcpu *vcpu)
  {
  	kvm_register_read(vcpu, VCPU_REGS_RAX);
  	kvm_register_read(vcpu, VCPU_REGS_RSP);
  	kvm_register_read(vcpu, VCPU_REGS_RIP);
  	vcpu->arch.regs_dirty = ~0;
  }
95cb22953   Gleb Natapov   KVM: x86 emulator...
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
  static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
  {
  	u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu, mask);
  	/*
  	 * an sti; sti; sequence only disable interrupts for the first
  	 * instruction. So, if the last instruction, be it emulated or
  	 * not, left the system with the INT_STI flag enabled, it
  	 * means that the last instruction is an sti. We should not
  	 * leave the flag on in this case. The same goes for mov ss
  	 */
  	if (!(int_shadow & mask))
  		kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
  }
54b8486f4   Gleb Natapov   KVM: x86 emulator...
4058
4059
4060
  static void inject_emulated_exception(struct kvm_vcpu *vcpu)
  {
  	struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
da9cb575b   Avi Kivity   KVM: x86 emulator...
4061
  	if (ctxt->exception.vector == PF_VECTOR)
6389ee946   Avi Kivity   KVM: Pull extra p...
4062
  		kvm_propagate_fault(vcpu, &ctxt->exception);
da9cb575b   Avi Kivity   KVM: x86 emulator...
4063
4064
4065
  	else if (ctxt->exception.error_code_valid)
  		kvm_queue_exception_e(vcpu, ctxt->exception.vector,
  				      ctxt->exception.error_code);
54b8486f4   Gleb Natapov   KVM: x86 emulator...
4066
  	else
da9cb575b   Avi Kivity   KVM: x86 emulator...
4067
  		kvm_queue_exception(vcpu, ctxt->exception.vector);
54b8486f4   Gleb Natapov   KVM: x86 emulator...
4068
  }
9dac77fa4   Avi Kivity   KVM: x86 emulator...
4069
  static void init_decode_cache(struct x86_emulate_ctxt *ctxt,
b5c9ff731   Takuya Yoshikawa   KVM: x86 emulator...
4070
4071
  			      const unsigned long *regs)
  {
9dac77fa4   Avi Kivity   KVM: x86 emulator...
4072
4073
4074
  	memset(&ctxt->twobyte, 0,
  	       (void *)&ctxt->regs - (void *)&ctxt->twobyte);
  	memcpy(ctxt->regs, regs, sizeof(ctxt->regs));
b5c9ff731   Takuya Yoshikawa   KVM: x86 emulator...
4075

9dac77fa4   Avi Kivity   KVM: x86 emulator...
4076
4077
4078
4079
4080
4081
  	ctxt->fetch.start = 0;
  	ctxt->fetch.end = 0;
  	ctxt->io_read.pos = 0;
  	ctxt->io_read.end = 0;
  	ctxt->mem_read.pos = 0;
  	ctxt->mem_read.end = 0;
b5c9ff731   Takuya Yoshikawa   KVM: x86 emulator...
4082
  }
8ec4722dd   Mohammed Gamal   KVM: Separate emu...
4083
4084
  static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
  {
adf52235b   Takuya Yoshikawa   KVM: x86 emulator...
4085
  	struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
8ec4722dd   Mohammed Gamal   KVM: Separate emu...
4086
  	int cs_db, cs_l;
2aab2c5b2   Gleb Natapov   KVM: call cache_a...
4087
4088
4089
4090
4091
4092
  	/*
  	 * TODO: fix emulate.c to use guest_read/write_register
  	 * instead of direct ->regs accesses, can save hundred cycles
  	 * on Intel for instructions that don't read/change RSP, for
  	 * for example.
  	 */
8ec4722dd   Mohammed Gamal   KVM: Separate emu...
4093
4094
4095
  	cache_all_regs(vcpu);
  
  	kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
adf52235b   Takuya Yoshikawa   KVM: x86 emulator...
4096
4097
4098
4099
4100
4101
4102
4103
  	ctxt->eflags = kvm_get_rflags(vcpu);
  	ctxt->eip = kvm_rip_read(vcpu);
  	ctxt->mode = (!is_protmode(vcpu))		? X86EMUL_MODE_REAL :
  		     (ctxt->eflags & X86_EFLAGS_VM)	? X86EMUL_MODE_VM86 :
  		     cs_l				? X86EMUL_MODE_PROT64 :
  		     cs_db				? X86EMUL_MODE_PROT32 :
  							  X86EMUL_MODE_PROT16;
  	ctxt->guest_mode = is_guest_mode(vcpu);
9dac77fa4   Avi Kivity   KVM: x86 emulator...
4104
  	init_decode_cache(ctxt, vcpu->arch.regs);
7ae441eac   Gleb Natapov   KVM: emulator: do...
4105
  	vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
8ec4722dd   Mohammed Gamal   KVM: Separate emu...
4106
  }
71f9833bb   Serge E. Hallyn   KVM: fix push of ...
4107
  int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
63995653a   Mohammed Gamal   KVM: Add kvm_inje...
4108
  {
9d74191ab   Takuya Yoshikawa   KVM: x86 emulator...
4109
  	struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
63995653a   Mohammed Gamal   KVM: Add kvm_inje...
4110
4111
4112
  	int ret;
  
  	init_emulate_ctxt(vcpu);
9dac77fa4   Avi Kivity   KVM: x86 emulator...
4113
4114
4115
  	ctxt->op_bytes = 2;
  	ctxt->ad_bytes = 2;
  	ctxt->_eip = ctxt->eip + inc_eip;
9d74191ab   Takuya Yoshikawa   KVM: x86 emulator...
4116
  	ret = emulate_int_real(ctxt, irq);
63995653a   Mohammed Gamal   KVM: Add kvm_inje...
4117
4118
4119
  
  	if (ret != X86EMUL_CONTINUE)
  		return EMULATE_FAIL;
9dac77fa4   Avi Kivity   KVM: x86 emulator...
4120
4121
  	ctxt->eip = ctxt->_eip;
  	memcpy(vcpu->arch.regs, ctxt->regs, sizeof ctxt->regs);
9d74191ab   Takuya Yoshikawa   KVM: x86 emulator...
4122
4123
  	kvm_rip_write(vcpu, ctxt->eip);
  	kvm_set_rflags(vcpu, ctxt->eflags);
63995653a   Mohammed Gamal   KVM: Add kvm_inje...
4124
4125
  
  	if (irq == NMI_VECTOR)
7460fb4a3   Avi Kivity   KVM: Fix simultan...
4126
  		vcpu->arch.nmi_pending = 0;
63995653a   Mohammed Gamal   KVM: Add kvm_inje...
4127
4128
4129
4130
4131
4132
  	else
  		vcpu->arch.interrupt.pending = false;
  
  	return EMULATE_DONE;
  }
  EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
6d77dbfc8   Gleb Natapov   KVM: inject #UD i...
4133
4134
  static int handle_emulation_failure(struct kvm_vcpu *vcpu)
  {
fc3a9157d   Joerg Roedel   KVM: X86: Don't r...
4135
  	int r = EMULATE_DONE;
6d77dbfc8   Gleb Natapov   KVM: inject #UD i...
4136
4137
  	++vcpu->stat.insn_emulation_fail;
  	trace_kvm_emulate_insn_failed(vcpu);
fc3a9157d   Joerg Roedel   KVM: X86: Don't r...
4138
4139
4140
4141
4142
4143
  	if (!is_guest_mode(vcpu)) {
  		vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
  		vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
  		vcpu->run->internal.ndata = 0;
  		r = EMULATE_FAIL;
  	}
6d77dbfc8   Gleb Natapov   KVM: inject #UD i...
4144
  	kvm_queue_exception(vcpu, UD_VECTOR);
fc3a9157d   Joerg Roedel   KVM: X86: Don't r...
4145
4146
  
  	return r;
6d77dbfc8   Gleb Natapov   KVM: inject #UD i...
4147
  }
a6f177efa   Gleb Natapov   KVM: Reenter gues...
4148
4149
4150
  static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t gva)
  {
  	gpa_t gpa;
68be08034   Gleb Natapov   KVM: x86: never r...
4151
4152
  	if (tdp_enabled)
  		return false;
a6f177efa   Gleb Natapov   KVM: Reenter gues...
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
  	/*
  	 * if emulation was due to access to shadowed page table
  	 * and it failed try to unshadow page and re-entetr the
  	 * guest to let CPU execute the instruction.
  	 */
  	if (kvm_mmu_unprotect_page_virt(vcpu, gva))
  		return true;
  
  	gpa = kvm_mmu_gva_to_gpa_system(vcpu, gva, NULL);
  
  	if (gpa == UNMAPPED_GVA)
  		return true; /* let cpu generate fault */
  
  	if (!kvm_is_error_hva(gfn_to_hva(vcpu->kvm, gpa >> PAGE_SHIFT)))
  		return true;
  
  	return false;
  }
1cb3f3ae5   Xiao Guangrong   KVM: x86: retry n...
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
  static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
  			      unsigned long cr2,  int emulation_type)
  {
  	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  	unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
  
  	last_retry_eip = vcpu->arch.last_retry_eip;
  	last_retry_addr = vcpu->arch.last_retry_addr;
  
  	/*
  	 * If the emulation is caused by #PF and it is non-page_table
  	 * writing instruction, it means the VM-EXIT is caused by shadow
  	 * page protected, we can zap the shadow page and retry this
  	 * instruction directly.
  	 *
  	 * Note: if the guest uses a non-page-table modifying instruction
  	 * on the PDE that points to the instruction, then we will unmap
  	 * the instruction and go to an infinite loop. So, we cache the
  	 * last retried eip and the last fault address, if we meet the eip
  	 * and the address again, we can break out of the potential infinite
  	 * loop.
  	 */
  	vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
  
  	if (!(emulation_type & EMULTYPE_RETRY))
  		return false;
  
  	if (x86_page_table_writing_insn(ctxt))
  		return false;
  
  	if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
  		return false;
  
  	vcpu->arch.last_retry_eip = ctxt->eip;
  	vcpu->arch.last_retry_addr = cr2;
  
  	if (!vcpu->arch.mmu.direct_map)
  		gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
  
  	kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
  
  	return true;
  }
51d8b6619   Andre Przywara   KVM: cleanup emul...
4214
4215
  int x86_emulate_instruction(struct kvm_vcpu *vcpu,
  			    unsigned long cr2,
dc25e89e0   Andre Przywara   KVM: SVM: copy in...
4216
4217
4218
  			    int emulation_type,
  			    void *insn,
  			    int insn_len)
bbd9b64e3   Carsten Otte   KVM: Portability:...
4219
  {
95cb22953   Gleb Natapov   KVM: x86 emulator...
4220
  	int r;
9d74191ab   Takuya Yoshikawa   KVM: x86 emulator...
4221
  	struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
7ae441eac   Gleb Natapov   KVM: emulator: do...
4222
  	bool writeback = true;
bbd9b64e3   Carsten Otte   KVM: Portability:...
4223

26eef70c3   Avi Kivity   KVM: Clear except...
4224
  	kvm_clear_exception_queue(vcpu);
8d7d81025   Gleb Natapov   KVM: mmio_fault_c...
4225

571008dac   Sheng Yang   KVM: x86 emulator...
4226
  	if (!(emulation_type & EMULTYPE_NO_DECODE)) {
8ec4722dd   Mohammed Gamal   KVM: Separate emu...
4227
  		init_emulate_ctxt(vcpu);
9d74191ab   Takuya Yoshikawa   KVM: x86 emulator...
4228
4229
4230
  		ctxt->interruptibility = 0;
  		ctxt->have_exception = false;
  		ctxt->perm_ok = false;
bbd9b64e3   Carsten Otte   KVM: Portability:...
4231

9d74191ab   Takuya Yoshikawa   KVM: x86 emulator...
4232
  		ctxt->only_vendor_specific_insn
4005996e4   Avi Kivity   KVM: Drop ad-hoc ...
4233
  			= emulation_type & EMULTYPE_TRAP_UD;
9d74191ab   Takuya Yoshikawa   KVM: x86 emulator...
4234
  		r = x86_decode_insn(ctxt, insn, insn_len);
bbd9b64e3   Carsten Otte   KVM: Portability:...
4235

e46479f85   Avi Kivity   KVM: Trace emulat...
4236
  		trace_kvm_emulate_insn_start(vcpu);
f2b5756bb   Avi Kivity   KVM: Add instruct...
4237
  		++vcpu->stat.insn_emulation;
1d2887e2d   Takuya Yoshikawa   KVM: x86 emulator...
4238
  		if (r != EMULATION_OK)  {
4005996e4   Avi Kivity   KVM: Drop ad-hoc ...
4239
4240
  			if (emulation_type & EMULTYPE_TRAP_UD)
  				return EMULATE_FAIL;
a6f177efa   Gleb Natapov   KVM: Reenter gues...
4241
  			if (reexecute_instruction(vcpu, cr2))
bbd9b64e3   Carsten Otte   KVM: Portability:...
4242
  				return EMULATE_DONE;
6d77dbfc8   Gleb Natapov   KVM: inject #UD i...
4243
4244
4245
  			if (emulation_type & EMULTYPE_SKIP)
  				return EMULATE_FAIL;
  			return handle_emulation_failure(vcpu);
bbd9b64e3   Carsten Otte   KVM: Portability:...
4246
4247
  		}
  	}
ba8afb6b0   Gleb Natapov   KVM: x86 emulator...
4248
  	if (emulation_type & EMULTYPE_SKIP) {
9dac77fa4   Avi Kivity   KVM: x86 emulator...
4249
  		kvm_rip_write(vcpu, ctxt->_eip);
ba8afb6b0   Gleb Natapov   KVM: x86 emulator...
4250
4251
  		return EMULATE_DONE;
  	}
1cb3f3ae5   Xiao Guangrong   KVM: x86: retry n...
4252
4253
  	if (retry_instruction(ctxt, cr2, emulation_type))
  		return EMULATE_DONE;
7ae441eac   Gleb Natapov   KVM: emulator: do...
4254
  	/* this is needed for vmware backdoor interface to work since it
4d2179e1e   Gleb Natapov   KVM: x86 emulator...
4255
  	   changes registers values  during IO operation */
7ae441eac   Gleb Natapov   KVM: emulator: do...
4256
4257
  	if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
  		vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
9dac77fa4   Avi Kivity   KVM: x86 emulator...
4258
  		memcpy(ctxt->regs, vcpu->arch.regs, sizeof ctxt->regs);
7ae441eac   Gleb Natapov   KVM: emulator: do...
4259
  	}
4d2179e1e   Gleb Natapov   KVM: x86 emulator...
4260

5cd21917d   Gleb Natapov   KVM: x86 emulator...
4261
  restart:
9d74191ab   Takuya Yoshikawa   KVM: x86 emulator...
4262
  	r = x86_emulate_insn(ctxt);
bbd9b64e3   Carsten Otte   KVM: Portability:...
4263

775fde864   Joerg Roedel   KVM: x86 emulator...
4264
4265
  	if (r == EMULATION_INTERCEPTED)
  		return EMULATE_DONE;
d2ddd1c48   Gleb Natapov   KVM: x86 emulator...
4266
  	if (r == EMULATION_FAILED) {
a6f177efa   Gleb Natapov   KVM: Reenter gues...
4267
  		if (reexecute_instruction(vcpu, cr2))
c3cd7ffaf   Gleb Natapov   KVM: x86 emulator...
4268
  			return EMULATE_DONE;
6d77dbfc8   Gleb Natapov   KVM: inject #UD i...
4269
  		return handle_emulation_failure(vcpu);
bbd9b64e3   Carsten Otte   KVM: Portability:...
4270
  	}
9d74191ab   Takuya Yoshikawa   KVM: x86 emulator...
4271
  	if (ctxt->have_exception) {
54b8486f4   Gleb Natapov   KVM: x86 emulator...
4272
  		inject_emulated_exception(vcpu);
d2ddd1c48   Gleb Natapov   KVM: x86 emulator...
4273
4274
  		r = EMULATE_DONE;
  	} else if (vcpu->arch.pio.count) {
3457e4192   Gleb Natapov   KVM: handle emula...
4275
4276
  		if (!vcpu->arch.pio.in)
  			vcpu->arch.pio.count = 0;
7ae441eac   Gleb Natapov   KVM: emulator: do...
4277
4278
  		else
  			writeback = false;
e85d28f8e   Gleb Natapov   KVM: x86 emulator...
4279
  		r = EMULATE_DO_MMIO;
7ae441eac   Gleb Natapov   KVM: emulator: do...
4280
4281
4282
  	} else if (vcpu->mmio_needed) {
  		if (!vcpu->mmio_is_write)
  			writeback = false;
e85d28f8e   Gleb Natapov   KVM: x86 emulator...
4283
  		r = EMULATE_DO_MMIO;
7ae441eac   Gleb Natapov   KVM: emulator: do...
4284
  	} else if (r == EMULATION_RESTART)
5cd21917d   Gleb Natapov   KVM: x86 emulator...
4285
  		goto restart;
d2ddd1c48   Gleb Natapov   KVM: x86 emulator...
4286
4287
  	else
  		r = EMULATE_DONE;
f850e2e60   Gleb Natapov   KVM: x86 emulator...
4288

7ae441eac   Gleb Natapov   KVM: emulator: do...
4289
  	if (writeback) {
9d74191ab   Takuya Yoshikawa   KVM: x86 emulator...
4290
4291
  		toggle_interruptibility(vcpu, ctxt->interruptibility);
  		kvm_set_rflags(vcpu, ctxt->eflags);
7ae441eac   Gleb Natapov   KVM: emulator: do...
4292
  		kvm_make_request(KVM_REQ_EVENT, vcpu);
9dac77fa4   Avi Kivity   KVM: x86 emulator...
4293
  		memcpy(vcpu->arch.regs, ctxt->regs, sizeof ctxt->regs);
7ae441eac   Gleb Natapov   KVM: emulator: do...
4294
  		vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
9d74191ab   Takuya Yoshikawa   KVM: x86 emulator...
4295
  		kvm_rip_write(vcpu, ctxt->eip);
7ae441eac   Gleb Natapov   KVM: emulator: do...
4296
4297
  	} else
  		vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
e85d28f8e   Gleb Natapov   KVM: x86 emulator...
4298
4299
  
  	return r;
de7d789ac   Carsten Otte   KVM: Portability:...
4300
  }
51d8b6619   Andre Przywara   KVM: cleanup emul...
4301
  EXPORT_SYMBOL_GPL(x86_emulate_instruction);
de7d789ac   Carsten Otte   KVM: Portability:...
4302

cf8f70bfe   Gleb Natapov   KVM: x86 emulator...
4303
  int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size, unsigned short port)
de7d789ac   Carsten Otte   KVM: Portability:...
4304
  {
cf8f70bfe   Gleb Natapov   KVM: x86 emulator...
4305
  	unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
ca1d4a9e7   Avi Kivity   KVM: x86 emulator...
4306
4307
  	int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
  					    size, port, &val, 1);
cf8f70bfe   Gleb Natapov   KVM: x86 emulator...
4308
  	/* do not return to emulator after return from userspace */
7972995b0   Gleb Natapov   KVM: x86 emulator...
4309
  	vcpu->arch.pio.count = 0;
de7d789ac   Carsten Otte   KVM: Portability:...
4310
4311
  	return ret;
  }
cf8f70bfe   Gleb Natapov   KVM: x86 emulator...
4312
  EXPORT_SYMBOL_GPL(kvm_fast_pio_out);
de7d789ac   Carsten Otte   KVM: Portability:...
4313

8cfdc0008   Zachary Amsden   KVM: x86: Make cp...
4314
4315
  static void tsc_bad(void *info)
  {
0a3aee0da   Tejun Heo   x86: Use this_cpu...
4316
  	__this_cpu_write(cpu_tsc_khz, 0);
8cfdc0008   Zachary Amsden   KVM: x86: Make cp...
4317
4318
4319
  }
  
  static void tsc_khz_changed(void *data)
c80766040   Gerd Hoffmann   KVM: Fix kvmclock...
4320
  {
8cfdc0008   Zachary Amsden   KVM: x86: Make cp...
4321
4322
4323
4324
4325
4326
4327
4328
4329
  	struct cpufreq_freqs *freq = data;
  	unsigned long khz = 0;
  
  	if (data)
  		khz = freq->new;
  	else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
  		khz = cpufreq_quick_get(raw_smp_processor_id());
  	if (!khz)
  		khz = tsc_khz;
0a3aee0da   Tejun Heo   x86: Use this_cpu...
4330
  	__this_cpu_write(cpu_tsc_khz, khz);
c80766040   Gerd Hoffmann   KVM: Fix kvmclock...
4331
  }
c80766040   Gerd Hoffmann   KVM: Fix kvmclock...
4332
4333
4334
4335
4336
4337
4338
  static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
  				     void *data)
  {
  	struct cpufreq_freqs *freq = data;
  	struct kvm *kvm;
  	struct kvm_vcpu *vcpu;
  	int i, send_ipi = 0;
8cfdc0008   Zachary Amsden   KVM: x86: Make cp...
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
  	/*
  	 * We allow guests to temporarily run on slowing clocks,
  	 * provided we notify them after, or to run on accelerating
  	 * clocks, provided we notify them before.  Thus time never
  	 * goes backwards.
  	 *
  	 * However, we have a problem.  We can't atomically update
  	 * the frequency of a given CPU from this function; it is
  	 * merely a notifier, which can be called from any CPU.
  	 * Changing the TSC frequency at arbitrary points in time
  	 * requires a recomputation of local variables related to
  	 * the TSC for each VCPU.  We must flag these local variables
  	 * to be updated and be sure the update takes place with the
  	 * new frequency before any guests proceed.
  	 *
  	 * Unfortunately, the combination of hotplug CPU and frequency
  	 * change creates an intractable locking scenario; the order
  	 * of when these callouts happen is undefined with respect to
  	 * CPU hotplug, and they can race with each other.  As such,
  	 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
  	 * undefined; you can actually have a CPU frequency change take
  	 * place in between the computation of X and the setting of the
  	 * variable.  To protect against this problem, all updates of
  	 * the per_cpu tsc_khz variable are done in an interrupt
  	 * protected IPI, and all callers wishing to update the value
  	 * must wait for a synchronous IPI to complete (which is trivial
  	 * if the caller is on the CPU already).  This establishes the
  	 * necessary total order on variable updates.
  	 *
  	 * Note that because a guest time update may take place
  	 * anytime after the setting of the VCPU's request bit, the
  	 * correct TSC value must be set before the request.  However,
  	 * to ensure the update actually makes it to any guest which
  	 * starts running in hardware virtualization between the set
  	 * and the acquisition of the spinlock, we must also ping the
  	 * CPU after setting the request bit.
  	 *
  	 */
c80766040   Gerd Hoffmann   KVM: Fix kvmclock...
4377
4378
4379
4380
  	if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
  		return 0;
  	if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
  		return 0;
8cfdc0008   Zachary Amsden   KVM: x86: Make cp...
4381
4382
  
  	smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
c80766040   Gerd Hoffmann   KVM: Fix kvmclock...
4383

e935b8372   Jan Kiszka   KVM: Convert kvm_...
4384
  	raw_spin_lock(&kvm_lock);
c80766040   Gerd Hoffmann   KVM: Fix kvmclock...
4385
  	list_for_each_entry(kvm, &vm_list, vm_list) {
988a2cae6   Gleb Natapov   KVM: Use macro to...
4386
  		kvm_for_each_vcpu(i, vcpu, kvm) {
c80766040   Gerd Hoffmann   KVM: Fix kvmclock...
4387
4388
  			if (vcpu->cpu != freq->cpu)
  				continue;
c285545f8   Zachary Amsden   KVM: x86: TSC cat...
4389
  			kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
c80766040   Gerd Hoffmann   KVM: Fix kvmclock...
4390
  			if (vcpu->cpu != smp_processor_id())
8cfdc0008   Zachary Amsden   KVM: x86: Make cp...
4391
  				send_ipi = 1;
c80766040   Gerd Hoffmann   KVM: Fix kvmclock...
4392
4393
  		}
  	}
e935b8372   Jan Kiszka   KVM: Convert kvm_...
4394
  	raw_spin_unlock(&kvm_lock);
c80766040   Gerd Hoffmann   KVM: Fix kvmclock...
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
  
  	if (freq->old < freq->new && send_ipi) {
  		/*
  		 * We upscale the frequency.  Must make the guest
  		 * doesn't see old kvmclock values while running with
  		 * the new frequency, otherwise we risk the guest sees
  		 * time go backwards.
  		 *
  		 * In case we update the frequency for another cpu
  		 * (which might be in guest context) send an interrupt
  		 * to kick the cpu out of guest context.  Next time
  		 * guest context is entered kvmclock will be updated,
  		 * so the guest will not see stale values.
  		 */
8cfdc0008   Zachary Amsden   KVM: x86: Make cp...
4409
  		smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
c80766040   Gerd Hoffmann   KVM: Fix kvmclock...
4410
4411
4412
4413
4414
  	}
  	return 0;
  }
  
  static struct notifier_block kvmclock_cpufreq_notifier_block = {
8cfdc0008   Zachary Amsden   KVM: x86: Make cp...
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
  	.notifier_call  = kvmclock_cpufreq_notifier
  };
  
  static int kvmclock_cpu_notifier(struct notifier_block *nfb,
  					unsigned long action, void *hcpu)
  {
  	unsigned int cpu = (unsigned long)hcpu;
  
  	switch (action) {
  		case CPU_ONLINE:
  		case CPU_DOWN_FAILED:
  			smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
  			break;
  		case CPU_DOWN_PREPARE:
  			smp_call_function_single(cpu, tsc_bad, NULL, 1);
  			break;
  	}
  	return NOTIFY_OK;
  }
  
  static struct notifier_block kvmclock_cpu_notifier_block = {
  	.notifier_call  = kvmclock_cpu_notifier,
  	.priority = -INT_MAX
c80766040   Gerd Hoffmann   KVM: Fix kvmclock...
4438
  };
b820cc0ca   Zachary Amsden   KVM: Separate tim...
4439
4440
4441
  static void kvm_timer_init(void)
  {
  	int cpu;
c285545f8   Zachary Amsden   KVM: x86: TSC cat...
4442
  	max_tsc_khz = tsc_khz;
8cfdc0008   Zachary Amsden   KVM: x86: Make cp...
4443
  	register_hotcpu_notifier(&kvmclock_cpu_notifier_block);
b820cc0ca   Zachary Amsden   KVM: Separate tim...
4444
  	if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
c285545f8   Zachary Amsden   KVM: x86: TSC cat...
4445
4446
4447
  #ifdef CONFIG_CPU_FREQ
  		struct cpufreq_policy policy;
  		memset(&policy, 0, sizeof(policy));
3e26f2309   Avi Kivity   KVM: Fix preempti...
4448
4449
  		cpu = get_cpu();
  		cpufreq_get_policy(&policy, cpu);
c285545f8   Zachary Amsden   KVM: x86: TSC cat...
4450
4451
  		if (policy.cpuinfo.max_freq)
  			max_tsc_khz = policy.cpuinfo.max_freq;
3e26f2309   Avi Kivity   KVM: Fix preempti...
4452
  		put_cpu();
c285545f8   Zachary Amsden   KVM: x86: TSC cat...
4453
  #endif
b820cc0ca   Zachary Amsden   KVM: Separate tim...
4454
4455
4456
  		cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
  					  CPUFREQ_TRANSITION_NOTIFIER);
  	}
c285545f8   Zachary Amsden   KVM: x86: TSC cat...
4457
4458
  	pr_debug("kvm: max_tsc_khz = %ld
  ", max_tsc_khz);
8cfdc0008   Zachary Amsden   KVM: x86: Make cp...
4459
4460
  	for_each_online_cpu(cpu)
  		smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
b820cc0ca   Zachary Amsden   KVM: Separate tim...
4461
  }
ff9d07a0e   Zhang, Yanmin   KVM: Implement pe...
4462
  static DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
f5132b013   Gleb Natapov   KVM: Expose a ver...
4463
  int kvm_is_in_guest(void)
ff9d07a0e   Zhang, Yanmin   KVM: Implement pe...
4464
  {
086c98550   Alex,Shi   KVM: use this_cpu...
4465
  	return __this_cpu_read(current_vcpu) != NULL;
ff9d07a0e   Zhang, Yanmin   KVM: Implement pe...
4466
4467
4468
4469
4470
  }
  
  static int kvm_is_user_mode(void)
  {
  	int user_mode = 3;
dcf46b944   Zhang, Yanmin   perf & kvm: Clean...
4471

086c98550   Alex,Shi   KVM: use this_cpu...
4472
4473
  	if (__this_cpu_read(current_vcpu))
  		user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
dcf46b944   Zhang, Yanmin   perf & kvm: Clean...
4474

ff9d07a0e   Zhang, Yanmin   KVM: Implement pe...
4475
4476
4477
4478
4479
4480
  	return user_mode != 0;
  }
  
  static unsigned long kvm_get_guest_ip(void)
  {
  	unsigned long ip = 0;
dcf46b944   Zhang, Yanmin   perf & kvm: Clean...
4481

086c98550   Alex,Shi   KVM: use this_cpu...
4482
4483
  	if (__this_cpu_read(current_vcpu))
  		ip = kvm_rip_read(__this_cpu_read(current_vcpu));
dcf46b944   Zhang, Yanmin   perf & kvm: Clean...
4484

ff9d07a0e   Zhang, Yanmin   KVM: Implement pe...
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
  	return ip;
  }
  
  static struct perf_guest_info_callbacks kvm_guest_cbs = {
  	.is_in_guest		= kvm_is_in_guest,
  	.is_user_mode		= kvm_is_user_mode,
  	.get_guest_ip		= kvm_get_guest_ip,
  };
  
  void kvm_before_handle_nmi(struct kvm_vcpu *vcpu)
  {
086c98550   Alex,Shi   KVM: use this_cpu...
4496
  	__this_cpu_write(current_vcpu, vcpu);
ff9d07a0e   Zhang, Yanmin   KVM: Implement pe...
4497
4498
4499
4500
4501
  }
  EXPORT_SYMBOL_GPL(kvm_before_handle_nmi);
  
  void kvm_after_handle_nmi(struct kvm_vcpu *vcpu)
  {
086c98550   Alex,Shi   KVM: use this_cpu...
4502
  	__this_cpu_write(current_vcpu, NULL);
ff9d07a0e   Zhang, Yanmin   KVM: Implement pe...
4503
4504
  }
  EXPORT_SYMBOL_GPL(kvm_after_handle_nmi);
ce88decff   Xiao Guangrong   KVM: MMU: mmio pa...
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
  static void kvm_set_mmio_spte_mask(void)
  {
  	u64 mask;
  	int maxphyaddr = boot_cpu_data.x86_phys_bits;
  
  	/*
  	 * Set the reserved bits and the present bit of an paging-structure
  	 * entry to generate page fault with PFER.RSV = 1.
  	 */
  	mask = ((1ull << (62 - maxphyaddr + 1)) - 1) << maxphyaddr;
  	mask |= 1ull;
  
  #ifdef CONFIG_X86_64
  	/*
  	 * If reserved bit is not supported, clear the present bit to disable
  	 * mmio page fault.
  	 */
  	if (maxphyaddr == 52)
  		mask &= ~1ull;
  #endif
  
  	kvm_mmu_set_mmio_spte_mask(mask);
  }
f8c16bbaa   Zhang Xiantao   KVM: Portability:...
4528
  int kvm_arch_init(void *opaque)
043405e10   Carsten Otte   KVM: Move x86 msr...
4529
  {
b820cc0ca   Zachary Amsden   KVM: Separate tim...
4530
  	int r;
f8c16bbaa   Zhang Xiantao   KVM: Portability:...
4531
  	struct kvm_x86_ops *ops = (struct kvm_x86_ops *)opaque;
f8c16bbaa   Zhang Xiantao   KVM: Portability:...
4532
4533
4534
  	if (kvm_x86_ops) {
  		printk(KERN_ERR "kvm: already loaded the other module
  ");
56c6d28a9   Zhang Xiantao   KVM: Portability:...
4535
4536
  		r = -EEXIST;
  		goto out;
f8c16bbaa   Zhang Xiantao   KVM: Portability:...
4537
4538
4539
4540
4541
  	}
  
  	if (!ops->cpu_has_kvm_support()) {
  		printk(KERN_ERR "kvm: no hardware support
  ");
56c6d28a9   Zhang Xiantao   KVM: Portability:...
4542
4543
  		r = -EOPNOTSUPP;
  		goto out;
f8c16bbaa   Zhang Xiantao   KVM: Portability:...
4544
4545
4546
4547
  	}
  	if (ops->disabled_by_bios()) {
  		printk(KERN_ERR "kvm: disabled by bios
  ");
56c6d28a9   Zhang Xiantao   KVM: Portability:...
4548
4549
  		r = -EOPNOTSUPP;
  		goto out;
f8c16bbaa   Zhang Xiantao   KVM: Portability:...
4550
  	}
97db56ce6   Avi Kivity   KVM: Initialize t...
4551
4552
4553
  	r = kvm_mmu_module_init();
  	if (r)
  		goto out;
ce88decff   Xiao Guangrong   KVM: MMU: mmio pa...
4554
  	kvm_set_mmio_spte_mask();
97db56ce6   Avi Kivity   KVM: Initialize t...
4555
  	kvm_init_msr_list();
f8c16bbaa   Zhang Xiantao   KVM: Portability:...
4556
  	kvm_x86_ops = ops;
7b52345e2   Sheng Yang   KVM: MMU: Add EPT...
4557
  	kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
4b12f0de3   Sheng Yang   KVM: Replace get_...
4558
  			PT_DIRTY_MASK, PT64_NX_MASK, 0);
c80766040   Gerd Hoffmann   KVM: Fix kvmclock...
4559

b820cc0ca   Zachary Amsden   KVM: Separate tim...
4560
  	kvm_timer_init();
c80766040   Gerd Hoffmann   KVM: Fix kvmclock...
4561

ff9d07a0e   Zhang, Yanmin   KVM: Implement pe...
4562
  	perf_register_guest_info_callbacks(&kvm_guest_cbs);
2acf923e3   Dexuan Cui   KVM: VMX: Enable ...
4563
4564
  	if (cpu_has_xsave)
  		host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
f8c16bbaa   Zhang Xiantao   KVM: Portability:...
4565
  	return 0;
56c6d28a9   Zhang Xiantao   KVM: Portability:...
4566
4567
  
  out:
56c6d28a9   Zhang Xiantao   KVM: Portability:...
4568
  	return r;
043405e10   Carsten Otte   KVM: Move x86 msr...
4569
  }
8776e5194   Hollis Blanchard   KVM: Portability:...
4570

f8c16bbaa   Zhang Xiantao   KVM: Portability:...
4571
4572
  void kvm_arch_exit(void)
  {
ff9d07a0e   Zhang, Yanmin   KVM: Implement pe...
4573
  	perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
888d256e9   Jan Kiszka   KVM: Unregister c...
4574
4575
4576
  	if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
  		cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
  					    CPUFREQ_TRANSITION_NOTIFIER);
8cfdc0008   Zachary Amsden   KVM: x86: Make cp...
4577
  	unregister_hotcpu_notifier(&kvmclock_cpu_notifier_block);
f8c16bbaa   Zhang Xiantao   KVM: Portability:...
4578
  	kvm_x86_ops = NULL;
56c6d28a9   Zhang Xiantao   KVM: Portability:...
4579
4580
  	kvm_mmu_module_exit();
  }
f8c16bbaa   Zhang Xiantao   KVM: Portability:...
4581

8776e5194   Hollis Blanchard   KVM: Portability:...
4582
4583
4584
4585
  int kvm_emulate_halt(struct kvm_vcpu *vcpu)
  {
  	++vcpu->stat.halt_exits;
  	if (irqchip_in_kernel(vcpu->kvm)) {
a45352908   Avi Kivity   KVM: Rename VCPU_...
4586
  		vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
8776e5194   Hollis Blanchard   KVM: Portability:...
4587
4588
4589
4590
4591
4592
4593
  		return 1;
  	} else {
  		vcpu->run->exit_reason = KVM_EXIT_HLT;
  		return 0;
  	}
  }
  EXPORT_SYMBOL_GPL(kvm_emulate_halt);
55cd8e5a4   Gleb Natapov   KVM: Implement ba...
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
  int kvm_hv_hypercall(struct kvm_vcpu *vcpu)
  {
  	u64 param, ingpa, outgpa, ret;
  	uint16_t code, rep_idx, rep_cnt, res = HV_STATUS_SUCCESS, rep_done = 0;
  	bool fast, longmode;
  	int cs_db, cs_l;
  
  	/*
  	 * hypercall generates UD from non zero cpl and real mode
  	 * per HYPER-V spec
  	 */
3eeb3288b   Avi Kivity   KVM: Add a helper...
4605
  	if (kvm_x86_ops->get_cpl(vcpu) != 0 || !is_protmode(vcpu)) {
55cd8e5a4   Gleb Natapov   KVM: Implement ba...
4606
4607
4608
4609
4610
4611
4612
4613
  		kvm_queue_exception(vcpu, UD_VECTOR);
  		return 0;
  	}
  
  	kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
  	longmode = is_long_mode(vcpu) && cs_l == 1;
  
  	if (!longmode) {
ccd469362   Gleb Natapov   KVM: fix Hyper-V ...
4614
4615
4616
4617
4618
4619
  		param = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDX) << 32) |
  			(kvm_register_read(vcpu, VCPU_REGS_RAX) & 0xffffffff);
  		ingpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RBX) << 32) |
  			(kvm_register_read(vcpu, VCPU_REGS_RCX) & 0xffffffff);
  		outgpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDI) << 32) |
  			(kvm_register_read(vcpu, VCPU_REGS_RSI) & 0xffffffff);
55cd8e5a4   Gleb Natapov   KVM: Implement ba...
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
  	}
  #ifdef CONFIG_X86_64
  	else {
  		param = kvm_register_read(vcpu, VCPU_REGS_RCX);
  		ingpa = kvm_register_read(vcpu, VCPU_REGS_RDX);
  		outgpa = kvm_register_read(vcpu, VCPU_REGS_R8);
  	}
  #endif
  
  	code = param & 0xffff;
  	fast = (param >> 16) & 0x1;
  	rep_cnt = (param >> 32) & 0xfff;
  	rep_idx = (param >> 48) & 0xfff;
  
  	trace_kvm_hv_hypercall(code, fast, rep_cnt, rep_idx, ingpa, outgpa);
c25bc1638   Gleb Natapov   KVM: Implement No...
4635
4636
4637
4638
4639
4640
4641
4642
  	switch (code) {
  	case HV_X64_HV_NOTIFY_LONG_SPIN_WAIT:
  		kvm_vcpu_on_spin(vcpu);
  		break;
  	default:
  		res = HV_STATUS_INVALID_HYPERCALL_CODE;
  		break;
  	}
55cd8e5a4   Gleb Natapov   KVM: Implement ba...
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
  
  	ret = res | (((u64)rep_done & 0xfff) << 32);
  	if (longmode) {
  		kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
  	} else {
  		kvm_register_write(vcpu, VCPU_REGS_RDX, ret >> 32);
  		kvm_register_write(vcpu, VCPU_REGS_RAX, ret & 0xffffffff);
  	}
  
  	return 1;
  }
8776e5194   Hollis Blanchard   KVM: Portability:...
4654
4655
4656
  int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
  {
  	unsigned long nr, a0, a1, a2, a3, ret;
2f333bcb4   Marcelo Tosatti   KVM: MMU: hyperca...
4657
  	int r = 1;
8776e5194   Hollis Blanchard   KVM: Portability:...
4658

55cd8e5a4   Gleb Natapov   KVM: Implement ba...
4659
4660
  	if (kvm_hv_hypercall_enabled(vcpu->kvm))
  		return kvm_hv_hypercall(vcpu);
5fdbf9765   Marcelo Tosatti   KVM: x86: accesso...
4661
4662
4663
4664
4665
  	nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
  	a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
  	a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
  	a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
  	a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
8776e5194   Hollis Blanchard   KVM: Portability:...
4666

229456fc3   Marcelo Tosatti   KVM: convert cust...
4667
  	trace_kvm_hypercall(nr, a0, a1, a2, a3);
2714d1d3d   Feng (Eric) Liu   KVM: Add trace ma...
4668

8776e5194   Hollis Blanchard   KVM: Portability:...
4669
4670
4671
4672
4673
4674
4675
  	if (!is_long_mode(vcpu)) {
  		nr &= 0xFFFFFFFF;
  		a0 &= 0xFFFFFFFF;
  		a1 &= 0xFFFFFFFF;
  		a2 &= 0xFFFFFFFF;
  		a3 &= 0xFFFFFFFF;
  	}
07708c4af   Jan Kiszka   KVM: x86: Disallo...
4676
4677
4678
4679
  	if (kvm_x86_ops->get_cpl(vcpu) != 0) {
  		ret = -KVM_EPERM;
  		goto out;
  	}
8776e5194   Hollis Blanchard   KVM: Portability:...
4680
  	switch (nr) {
b93463aa5   Avi Kivity   KVM: Accelerated ...
4681
4682
4683
  	case KVM_HC_VAPIC_POLL_IRQ:
  		ret = 0;
  		break;
8776e5194   Hollis Blanchard   KVM: Portability:...
4684
4685
4686
4687
  	default:
  		ret = -KVM_ENOSYS;
  		break;
  	}
07708c4af   Jan Kiszka   KVM: x86: Disallo...
4688
  out:
5fdbf9765   Marcelo Tosatti   KVM: x86: accesso...
4689
  	kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
f11c3a8d8   Amit Shah   KVM: Add stat cou...
4690
  	++vcpu->stat.hypercalls;
2f333bcb4   Marcelo Tosatti   KVM: MMU: hyperca...
4691
  	return r;
8776e5194   Hollis Blanchard   KVM: Portability:...
4692
4693
  }
  EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
d6aa10003   Avi Kivity   KVM: x86 emulator...
4694
  int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
8776e5194   Hollis Blanchard   KVM: Portability:...
4695
  {
d6aa10003   Avi Kivity   KVM: x86 emulator...
4696
  	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8776e5194   Hollis Blanchard   KVM: Portability:...
4697
  	char instruction[3];
5fdbf9765   Marcelo Tosatti   KVM: x86: accesso...
4698
  	unsigned long rip = kvm_rip_read(vcpu);
8776e5194   Hollis Blanchard   KVM: Portability:...
4699

8776e5194   Hollis Blanchard   KVM: Portability:...
4700
4701
4702
4703
4704
4705
  	/*
  	 * Blow out the MMU to ensure that no other VCPU has an active mapping
  	 * to ensure that the updated hypercall appears atomically across all
  	 * VCPUs.
  	 */
  	kvm_mmu_zap_all(vcpu->kvm);
8776e5194   Hollis Blanchard   KVM: Portability:...
4706
  	kvm_x86_ops->patch_hypercall(vcpu, instruction);
8776e5194   Hollis Blanchard   KVM: Portability:...
4707

9d74191ab   Takuya Yoshikawa   KVM: x86 emulator...
4708
  	return emulator_write_emulated(ctxt, rip, instruction, 3, NULL);
8776e5194   Hollis Blanchard   KVM: Portability:...
4709
  }
d07520607   Hollis Blanchard   KVM: Portability:...
4710
  /*
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
4711
4712
4713
4714
4715
   * Check if userspace requested an interrupt window, and that the
   * interrupt window is open.
   *
   * No need to exit to userspace if we already have an interrupt queued.
   */
851ba6922   Avi Kivity   KVM: Don't pass k...
4716
  static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
4717
  {
8061823a2   Gleb Natapov   KVM: Make kvm_cpu...
4718
  	return (!irqchip_in_kernel(vcpu->kvm) && !kvm_cpu_has_interrupt(vcpu) &&
851ba6922   Avi Kivity   KVM: Don't pass k...
4719
  		vcpu->run->request_interrupt_window &&
5df566464   Gleb Natapov   KVM: Use kvm_arch...
4720
  		kvm_arch_interrupt_allowed(vcpu));
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
4721
  }
851ba6922   Avi Kivity   KVM: Don't pass k...
4722
  static void post_kvm_run_save(struct kvm_vcpu *vcpu)
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
4723
  {
851ba6922   Avi Kivity   KVM: Don't pass k...
4724
  	struct kvm_run *kvm_run = vcpu->run;
91586a3b7   Jan Kiszka   KVM: x86: Rework ...
4725
  	kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
2d3ad1f40   Avi Kivity   KVM: Prefix contr...
4726
  	kvm_run->cr8 = kvm_get_cr8(vcpu);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
4727
  	kvm_run->apic_base = kvm_get_apic_base(vcpu);
4531220b7   Jan Kiszka   KVM: x86: Rework ...
4728
  	if (irqchip_in_kernel(vcpu->kvm))
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
4729
  		kvm_run->ready_for_interrupt_injection = 1;
4531220b7   Jan Kiszka   KVM: x86: Rework ...
4730
  	else
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
4731
  		kvm_run->ready_for_interrupt_injection =
fa9726b07   Gleb Natapov   KVM: Do not allow...
4732
4733
4734
  			kvm_arch_interrupt_allowed(vcpu) &&
  			!kvm_cpu_has_interrupt(vcpu) &&
  			!kvm_event_needs_reinjection(vcpu);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
4735
  }
b93463aa5   Avi Kivity   KVM: Accelerated ...
4736
4737
4738
4739
4740
4741
4742
4743
4744
  static void vapic_enter(struct kvm_vcpu *vcpu)
  {
  	struct kvm_lapic *apic = vcpu->arch.apic;
  	struct page *page;
  
  	if (!apic || !apic->vapic_addr)
  		return;
  
  	page = gfn_to_page(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
72dc67a69   Izik Eidus   KVM: remove the u...
4745
4746
  
  	vcpu->arch.apic->vapic_page = page;
b93463aa5   Avi Kivity   KVM: Accelerated ...
4747
4748
4749
4750
4751
  }
  
  static void vapic_exit(struct kvm_vcpu *vcpu)
  {
  	struct kvm_lapic *apic = vcpu->arch.apic;
f656ce018   Marcelo Tosatti   KVM: switch vcpu ...
4752
  	int idx;
b93463aa5   Avi Kivity   KVM: Accelerated ...
4753
4754
4755
  
  	if (!apic || !apic->vapic_addr)
  		return;
f656ce018   Marcelo Tosatti   KVM: switch vcpu ...
4756
  	idx = srcu_read_lock(&vcpu->kvm->srcu);
b93463aa5   Avi Kivity   KVM: Accelerated ...
4757
4758
  	kvm_release_page_dirty(apic->vapic_page);
  	mark_page_dirty(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
f656ce018   Marcelo Tosatti   KVM: switch vcpu ...
4759
  	srcu_read_unlock(&vcpu->kvm->srcu, idx);
b93463aa5   Avi Kivity   KVM: Accelerated ...
4760
  }
95ba82731   Gleb Natapov   KVM: SVM: Add NMI...
4761
4762
4763
4764
4765
4766
  static void update_cr8_intercept(struct kvm_vcpu *vcpu)
  {
  	int max_irr, tpr;
  
  	if (!kvm_x86_ops->update_cr8_intercept)
  		return;
88c808fd4   Avi Kivity   KVM: Protect upda...
4767
4768
  	if (!vcpu->arch.apic)
  		return;
8db3baa2d   Gleb Natapov   KVM: Disable CR8 ...
4769
4770
4771
4772
  	if (!vcpu->arch.apic->vapic_addr)
  		max_irr = kvm_lapic_find_highest_irr(vcpu);
  	else
  		max_irr = -1;
95ba82731   Gleb Natapov   KVM: SVM: Add NMI...
4773
4774
4775
4776
4777
4778
4779
4780
  
  	if (max_irr != -1)
  		max_irr >>= 4;
  
  	tpr = kvm_lapic_get_cr8(vcpu);
  
  	kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
  }
851ba6922   Avi Kivity   KVM: Don't pass k...
4781
  static void inject_pending_event(struct kvm_vcpu *vcpu)
95ba82731   Gleb Natapov   KVM: SVM: Add NMI...
4782
4783
  {
  	/* try to reinject previous events if any */
b59bb7bdf   Gleb Natapov   KVM: Move excepti...
4784
  	if (vcpu->arch.exception.pending) {
5c1c85d08   Avi Kivity   KVM: Trace except...
4785
4786
4787
  		trace_kvm_inj_exception(vcpu->arch.exception.nr,
  					vcpu->arch.exception.has_error_code,
  					vcpu->arch.exception.error_code);
b59bb7bdf   Gleb Natapov   KVM: Move excepti...
4788
4789
  		kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
  					  vcpu->arch.exception.has_error_code,
ce7ddec4b   Joerg Roedel   KVM: x86: Allow m...
4790
4791
  					  vcpu->arch.exception.error_code,
  					  vcpu->arch.exception.reinject);
b59bb7bdf   Gleb Natapov   KVM: Move excepti...
4792
4793
  		return;
  	}
95ba82731   Gleb Natapov   KVM: SVM: Add NMI...
4794
4795
4796
4797
4798
4799
  	if (vcpu->arch.nmi_injected) {
  		kvm_x86_ops->set_nmi(vcpu);
  		return;
  	}
  
  	if (vcpu->arch.interrupt.pending) {
66fd3f7f9   Gleb Natapov   KVM: Do not re-ex...
4800
  		kvm_x86_ops->set_irq(vcpu);
95ba82731   Gleb Natapov   KVM: SVM: Add NMI...
4801
4802
4803
4804
4805
4806
  		return;
  	}
  
  	/* try to inject new event if pending */
  	if (vcpu->arch.nmi_pending) {
  		if (kvm_x86_ops->nmi_allowed(vcpu)) {
7460fb4a3   Avi Kivity   KVM: Fix simultan...
4807
  			--vcpu->arch.nmi_pending;
95ba82731   Gleb Natapov   KVM: SVM: Add NMI...
4808
4809
4810
4811
4812
  			vcpu->arch.nmi_injected = true;
  			kvm_x86_ops->set_nmi(vcpu);
  		}
  	} else if (kvm_cpu_has_interrupt(vcpu)) {
  		if (kvm_x86_ops->interrupt_allowed(vcpu)) {
66fd3f7f9   Gleb Natapov   KVM: Do not re-ex...
4813
4814
4815
  			kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
  					    false);
  			kvm_x86_ops->set_irq(vcpu);
95ba82731   Gleb Natapov   KVM: SVM: Add NMI...
4816
4817
4818
  		}
  	}
  }
2acf923e3   Dexuan Cui   KVM: VMX: Enable ...
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
  static void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
  {
  	if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
  			!vcpu->guest_xcr0_loaded) {
  		/* kvm_set_xcr() also depends on this */
  		xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
  		vcpu->guest_xcr0_loaded = 1;
  	}
  }
  
  static void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
  {
  	if (vcpu->guest_xcr0_loaded) {
  		if (vcpu->arch.xcr0 != host_xcr0)
  			xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
  		vcpu->guest_xcr0_loaded = 0;
  	}
  }
7460fb4a3   Avi Kivity   KVM: Fix simultan...
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
  static void process_nmi(struct kvm_vcpu *vcpu)
  {
  	unsigned limit = 2;
  
  	/*
  	 * x86 is limited to one NMI running, and one NMI pending after it.
  	 * If an NMI is already in progress, limit further NMIs to just one.
  	 * Otherwise, allow two (and we'll inject the first one immediately).
  	 */
  	if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
  		limit = 1;
  
  	vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
  	vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
  	kvm_make_request(KVM_REQ_EVENT, vcpu);
  }
851ba6922   Avi Kivity   KVM: Don't pass k...
4853
  static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
4854
4855
  {
  	int r;
6a8b1d131   Gleb Natapov   KVM: Always reque...
4856
  	bool req_int_win = !irqchip_in_kernel(vcpu->kvm) &&
851ba6922   Avi Kivity   KVM: Don't pass k...
4857
  		vcpu->run->request_interrupt_window;
d6185f20a   Nadav Har'El   KVM: nVMX: Add KV...
4858
  	bool req_immediate_exit = 0;
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
4859

3e0075094   Avi Kivity   KVM: Simplify vcp...
4860
  	if (vcpu->requests) {
a8eeb04a4   Avi Kivity   KVM: Add mini-API...
4861
  		if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
2e53d63ac   Marcelo Tosatti   KVM: MMU: ignore ...
4862
  			kvm_mmu_unload(vcpu);
a8eeb04a4   Avi Kivity   KVM: Add mini-API...
4863
  		if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
2f5997140   Marcelo Tosatti   KVM: migrate PIT ...
4864
  			__kvm_migrate_timers(vcpu);
34c238a1d   Zachary Amsden   KVM: x86: Rename ...
4865
4866
  		if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
  			r = kvm_guest_time_update(vcpu);
8cfdc0008   Zachary Amsden   KVM: x86: Make cp...
4867
4868
4869
  			if (unlikely(r))
  				goto out;
  		}
a8eeb04a4   Avi Kivity   KVM: Add mini-API...
4870
  		if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
4731d4c7a   Marcelo Tosatti   KVM: MMU: out of ...
4871
  			kvm_mmu_sync_roots(vcpu);
a8eeb04a4   Avi Kivity   KVM: Add mini-API...
4872
  		if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
d4acf7e7a   Marcelo Tosatti   KVM: Fix race bet...
4873
  			kvm_x86_ops->tlb_flush(vcpu);
a8eeb04a4   Avi Kivity   KVM: Add mini-API...
4874
  		if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
851ba6922   Avi Kivity   KVM: Don't pass k...
4875
  			vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
b93463aa5   Avi Kivity   KVM: Accelerated ...
4876
4877
4878
  			r = 0;
  			goto out;
  		}
a8eeb04a4   Avi Kivity   KVM: Add mini-API...
4879
  		if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
851ba6922   Avi Kivity   KVM: Don't pass k...
4880
  			vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
71c4dfafc   Joerg Roedel   KVM: detect if VC...
4881
4882
4883
  			r = 0;
  			goto out;
  		}
a8eeb04a4   Avi Kivity   KVM: Add mini-API...
4884
  		if (kvm_check_request(KVM_REQ_DEACTIVATE_FPU, vcpu)) {
02daab21d   Avi Kivity   KVM: Lazify fpu a...
4885
4886
4887
  			vcpu->fpu_active = 0;
  			kvm_x86_ops->fpu_deactivate(vcpu);
  		}
af585b921   Gleb Natapov   KVM: Halt vcpu if...
4888
4889
4890
4891
4892
4893
  		if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
  			/* Page is swapped out. Do synthetic halt */
  			vcpu->arch.apf.halted = true;
  			r = 1;
  			goto out;
  		}
c9aaa8957   Glauber Costa   KVM: Steal time i...
4894
4895
  		if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
  			record_steal_time(vcpu);
7460fb4a3   Avi Kivity   KVM: Fix simultan...
4896
4897
  		if (kvm_check_request(KVM_REQ_NMI, vcpu))
  			process_nmi(vcpu);
d6185f20a   Nadav Har'El   KVM: nVMX: Add KV...
4898
4899
  		req_immediate_exit =
  			kvm_check_request(KVM_REQ_IMMEDIATE_EXIT, vcpu);
f5132b013   Gleb Natapov   KVM: Expose a ver...
4900
4901
4902
4903
  		if (kvm_check_request(KVM_REQ_PMU, vcpu))
  			kvm_handle_pmu_event(vcpu);
  		if (kvm_check_request(KVM_REQ_PMI, vcpu))
  			kvm_deliver_pmi(vcpu);
2f52d58c9   Avi Kivity   KVM: Move apic ti...
4904
  	}
b93463aa5   Avi Kivity   KVM: Accelerated ...
4905

3e0075094   Avi Kivity   KVM: Simplify vcp...
4906
4907
4908
  	r = kvm_mmu_reload(vcpu);
  	if (unlikely(r))
  		goto out;
b463a6f74   Avi Kivity   KVM: Non-atomic i...
4909
4910
4911
4912
  	if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
  		inject_pending_event(vcpu);
  
  		/* enable NMI/IRQ window open exits if needed */
7460fb4a3   Avi Kivity   KVM: Fix simultan...
4913
  		if (vcpu->arch.nmi_pending)
b463a6f74   Avi Kivity   KVM: Non-atomic i...
4914
4915
4916
4917
4918
4919
4920
4921
4922
  			kvm_x86_ops->enable_nmi_window(vcpu);
  		else if (kvm_cpu_has_interrupt(vcpu) || req_int_win)
  			kvm_x86_ops->enable_irq_window(vcpu);
  
  		if (kvm_lapic_enabled(vcpu)) {
  			update_cr8_intercept(vcpu);
  			kvm_lapic_sync_to_vapic(vcpu);
  		}
  	}
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
4923
4924
4925
  	preempt_disable();
  
  	kvm_x86_ops->prepare_guest_switch(vcpu);
2608d7a12   Avi Kivity   KVM: Allow kvm_lo...
4926
4927
  	if (vcpu->fpu_active)
  		kvm_load_guest_fpu(vcpu);
2acf923e3   Dexuan Cui   KVM: VMX: Enable ...
4928
  	kvm_load_guest_xcr0(vcpu);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
4929

6b7e2d099   Xiao Guangrong   KVM: Add "exiting...
4930
4931
4932
4933
4934
4935
  	vcpu->mode = IN_GUEST_MODE;
  
  	/* We should set ->mode before check ->requests,
  	 * see the comment in make_all_cpus_request.
  	 */
  	smp_mb();
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
4936

d94e1dc9a   Avi Kivity   KVM: Get rid of K...
4937
  	local_irq_disable();
32f884006   Marcelo Tosatti   KVM: use smp_send...
4938

6b7e2d099   Xiao Guangrong   KVM: Add "exiting...
4939
  	if (vcpu->mode == EXITING_GUEST_MODE || vcpu->requests
d94e1dc9a   Avi Kivity   KVM: Get rid of K...
4940
  	    || need_resched() || signal_pending(current)) {
6b7e2d099   Xiao Guangrong   KVM: Add "exiting...
4941
  		vcpu->mode = OUTSIDE_GUEST_MODE;
d94e1dc9a   Avi Kivity   KVM: Get rid of K...
4942
  		smp_wmb();
6c1428012   Avi Kivity   KVM: Fix unbounde...
4943
4944
  		local_irq_enable();
  		preempt_enable();
b463a6f74   Avi Kivity   KVM: Non-atomic i...
4945
  		kvm_x86_ops->cancel_injection(vcpu);
6c1428012   Avi Kivity   KVM: Fix unbounde...
4946
4947
4948
  		r = 1;
  		goto out;
  	}
f656ce018   Marcelo Tosatti   KVM: switch vcpu ...
4949
  	srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
3200f405a   Marcelo Tosatti   KVM: MMU: unify s...
4950

d6185f20a   Nadav Har'El   KVM: nVMX: Add KV...
4951
4952
  	if (req_immediate_exit)
  		smp_send_reschedule(vcpu->cpu);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
4953
  	kvm_guest_enter();
42dbaa5a0   Jan Kiszka   KVM: x86: Virtual...
4954
  	if (unlikely(vcpu->arch.switch_db_regs)) {
42dbaa5a0   Jan Kiszka   KVM: x86: Virtual...
4955
4956
4957
4958
4959
4960
  		set_debugreg(0, 7);
  		set_debugreg(vcpu->arch.eff_db[0], 0);
  		set_debugreg(vcpu->arch.eff_db[1], 1);
  		set_debugreg(vcpu->arch.eff_db[2], 2);
  		set_debugreg(vcpu->arch.eff_db[3], 3);
  	}
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
4961

229456fc3   Marcelo Tosatti   KVM: convert cust...
4962
  	trace_kvm_entry(vcpu->vcpu_id);
851ba6922   Avi Kivity   KVM: Don't pass k...
4963
  	kvm_x86_ops->run(vcpu);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
4964

24f1e32c6   Frederic Weisbecker   hw-breakpoints: R...
4965
4966
4967
4968
4969
4970
4971
  	/*
  	 * If the guest has used debug registers, at least dr7
  	 * will be disabled while returning to the host.
  	 * If we don't have active breakpoints in the host, we don't
  	 * care about the messed up debug address registers. But if
  	 * we have some of them active, restore the old state.
  	 */
59d8eb53e   Frederic Weisbecker   hw-breakpoints: W...
4972
  	if (hw_breakpoint_active())
24f1e32c6   Frederic Weisbecker   hw-breakpoints: R...
4973
  		hw_breakpoint_restore();
42dbaa5a0   Jan Kiszka   KVM: x86: Virtual...
4974

d5c1785d2   Nadav Har'El   KVM: L1 TSC handling
4975
  	vcpu->arch.last_guest_tsc = kvm_x86_ops->read_l1_tsc(vcpu);
1d5f066e0   Zachary Amsden   KVM: x86: Fix a p...
4976

6b7e2d099   Xiao Guangrong   KVM: Add "exiting...
4977
  	vcpu->mode = OUTSIDE_GUEST_MODE;
d94e1dc9a   Avi Kivity   KVM: Get rid of K...
4978
  	smp_wmb();
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
  	local_irq_enable();
  
  	++vcpu->stat.exits;
  
  	/*
  	 * We must have an instruction between local_irq_enable() and
  	 * kvm_guest_exit(), so the timer interrupt isn't delayed by
  	 * the interrupt shadow.  The stat.exits increment will do nicely.
  	 * But we need to prevent reordering, hence this barrier():
  	 */
  	barrier();
  
  	kvm_guest_exit();
  
  	preempt_enable();
f656ce018   Marcelo Tosatti   KVM: switch vcpu ...
4994
  	vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
3200f405a   Marcelo Tosatti   KVM: MMU: unify s...
4995

b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
4996
4997
4998
4999
  	/*
  	 * Profile KVM exit RIPs:
  	 */
  	if (unlikely(prof_on == KVM_PROFILING)) {
5fdbf9765   Marcelo Tosatti   KVM: x86: accesso...
5000
5001
  		unsigned long rip = kvm_rip_read(vcpu);
  		profile_hit(KVM_PROFILING, (void *)rip);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5002
  	}
298101da2   Avi Kivity   KVM: Generalize e...
5003

b93463aa5   Avi Kivity   KVM: Accelerated ...
5004
  	kvm_lapic_sync_from_vapic(vcpu);
851ba6922   Avi Kivity   KVM: Don't pass k...
5005
  	r = kvm_x86_ops->handle_exit(vcpu);
d76901750   Marcelo Tosatti   KVM: x86: do not ...
5006
5007
5008
  out:
  	return r;
  }
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5009

09cec7548   Gleb Natapov   KVM: Timer event ...
5010

851ba6922   Avi Kivity   KVM: Don't pass k...
5011
  static int __vcpu_run(struct kvm_vcpu *vcpu)
d76901750   Marcelo Tosatti   KVM: x86: do not ...
5012
5013
  {
  	int r;
f656ce018   Marcelo Tosatti   KVM: switch vcpu ...
5014
  	struct kvm *kvm = vcpu->kvm;
d76901750   Marcelo Tosatti   KVM: x86: do not ...
5015
5016
  
  	if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED)) {
1b10bf31a   Jan Kiszka   KVM: x86: Silence...
5017
5018
5019
  		pr_debug("vcpu %d received sipi with vector # %x
  ",
  			 vcpu->vcpu_id, vcpu->arch.sipi_vector);
d76901750   Marcelo Tosatti   KVM: x86: do not ...
5020
  		kvm_lapic_reset(vcpu);
5f179287f   Gleb Natapov   KVM: call kvm_arc...
5021
  		r = kvm_arch_vcpu_reset(vcpu);
d76901750   Marcelo Tosatti   KVM: x86: do not ...
5022
5023
5024
  		if (r)
  			return r;
  		vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5025
  	}
f656ce018   Marcelo Tosatti   KVM: switch vcpu ...
5026
  	vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
d76901750   Marcelo Tosatti   KVM: x86: do not ...
5027
5028
5029
5030
  	vapic_enter(vcpu);
  
  	r = 1;
  	while (r > 0) {
af585b921   Gleb Natapov   KVM: Halt vcpu if...
5031
5032
  		if (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
  		    !vcpu->arch.apf.halted)
851ba6922   Avi Kivity   KVM: Don't pass k...
5033
  			r = vcpu_enter_guest(vcpu);
d76901750   Marcelo Tosatti   KVM: x86: do not ...
5034
  		else {
f656ce018   Marcelo Tosatti   KVM: switch vcpu ...
5035
  			srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
d76901750   Marcelo Tosatti   KVM: x86: do not ...
5036
  			kvm_vcpu_block(vcpu);
f656ce018   Marcelo Tosatti   KVM: switch vcpu ...
5037
  			vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
a8eeb04a4   Avi Kivity   KVM: Add mini-API...
5038
  			if (kvm_check_request(KVM_REQ_UNHALT, vcpu))
09cec7548   Gleb Natapov   KVM: Timer event ...
5039
5040
5041
  			{
  				switch(vcpu->arch.mp_state) {
  				case KVM_MP_STATE_HALTED:
d76901750   Marcelo Tosatti   KVM: x86: do not ...
5042
  					vcpu->arch.mp_state =
09cec7548   Gleb Natapov   KVM: Timer event ...
5043
5044
  						KVM_MP_STATE_RUNNABLE;
  				case KVM_MP_STATE_RUNNABLE:
af585b921   Gleb Natapov   KVM: Halt vcpu if...
5045
  					vcpu->arch.apf.halted = false;
09cec7548   Gleb Natapov   KVM: Timer event ...
5046
5047
5048
5049
5050
5051
5052
  					break;
  				case KVM_MP_STATE_SIPI_RECEIVED:
  				default:
  					r = -EINTR;
  					break;
  				}
  			}
d76901750   Marcelo Tosatti   KVM: x86: do not ...
5053
  		}
09cec7548   Gleb Natapov   KVM: Timer event ...
5054
5055
5056
5057
5058
5059
  		if (r <= 0)
  			break;
  
  		clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
  		if (kvm_cpu_has_pending_timer(vcpu))
  			kvm_inject_pending_timer_irqs(vcpu);
851ba6922   Avi Kivity   KVM: Don't pass k...
5060
  		if (dm_request_for_irq_injection(vcpu)) {
09cec7548   Gleb Natapov   KVM: Timer event ...
5061
  			r = -EINTR;
851ba6922   Avi Kivity   KVM: Don't pass k...
5062
  			vcpu->run->exit_reason = KVM_EXIT_INTR;
09cec7548   Gleb Natapov   KVM: Timer event ...
5063
5064
  			++vcpu->stat.request_irq_exits;
  		}
af585b921   Gleb Natapov   KVM: Halt vcpu if...
5065
5066
  
  		kvm_check_async_pf_completion(vcpu);
09cec7548   Gleb Natapov   KVM: Timer event ...
5067
5068
  		if (signal_pending(current)) {
  			r = -EINTR;
851ba6922   Avi Kivity   KVM: Don't pass k...
5069
  			vcpu->run->exit_reason = KVM_EXIT_INTR;
09cec7548   Gleb Natapov   KVM: Timer event ...
5070
5071
5072
  			++vcpu->stat.signal_exits;
  		}
  		if (need_resched()) {
f656ce018   Marcelo Tosatti   KVM: switch vcpu ...
5073
  			srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
09cec7548   Gleb Natapov   KVM: Timer event ...
5074
  			kvm_resched(vcpu);
f656ce018   Marcelo Tosatti   KVM: switch vcpu ...
5075
  			vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
d76901750   Marcelo Tosatti   KVM: x86: do not ...
5076
  		}
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5077
  	}
f656ce018   Marcelo Tosatti   KVM: switch vcpu ...
5078
  	srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5079

b93463aa5   Avi Kivity   KVM: Accelerated ...
5080
  	vapic_exit(vcpu);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5081
5082
  	return r;
  }
5287f194b   Avi Kivity   KVM: Split mmio c...
5083
5084
5085
5086
5087
5088
5089
5090
5091
  static int complete_mmio(struct kvm_vcpu *vcpu)
  {
  	struct kvm_run *run = vcpu->run;
  	int r;
  
  	if (!(vcpu->arch.pio.count || vcpu->mmio_needed))
  		return 1;
  
  	if (vcpu->mmio_needed) {
5287f194b   Avi Kivity   KVM: Split mmio c...
5092
  		vcpu->mmio_needed = 0;
cef4dea07   Avi Kivity   KVM: 16-byte mmio...
5093
  		if (!vcpu->mmio_is_write)
0004c7c25   Gleb Natapov   KVM: Fix compound...
5094
5095
  			memcpy(vcpu->mmio_data + vcpu->mmio_index,
  			       run->mmio.data, 8);
cef4dea07   Avi Kivity   KVM: 16-byte mmio...
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
  		vcpu->mmio_index += 8;
  		if (vcpu->mmio_index < vcpu->mmio_size) {
  			run->exit_reason = KVM_EXIT_MMIO;
  			run->mmio.phys_addr = vcpu->mmio_phys_addr + vcpu->mmio_index;
  			memcpy(run->mmio.data, vcpu->mmio_data + vcpu->mmio_index, 8);
  			run->mmio.len = min(vcpu->mmio_size - vcpu->mmio_index, 8);
  			run->mmio.is_write = vcpu->mmio_is_write;
  			vcpu->mmio_needed = 1;
  			return 0;
  		}
  		if (vcpu->mmio_is_write)
  			return 1;
  		vcpu->mmio_read_completed = 1;
5287f194b   Avi Kivity   KVM: Split mmio c...
5109
5110
5111
5112
5113
5114
5115
5116
  	}
  	vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
  	r = emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
  	srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
  	if (r != EMULATE_DONE)
  		return 0;
  	return 1;
  }
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5117
5118
5119
5120
  int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
  {
  	int r;
  	sigset_t sigsaved;
e5c301428   Avi Kivity   KVM: Initialize f...
5121
5122
  	if (!tsk_used_math(current) && init_fpu(current))
  		return -ENOMEM;
ac9f6dc0d   Avi Kivity   KVM: Apply the ke...
5123
5124
  	if (vcpu->sigset_active)
  		sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
a45352908   Avi Kivity   KVM: Rename VCPU_...
5125
  	if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5126
  		kvm_vcpu_block(vcpu);
d76901750   Marcelo Tosatti   KVM: x86: do not ...
5127
  		clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
ac9f6dc0d   Avi Kivity   KVM: Apply the ke...
5128
5129
  		r = -EAGAIN;
  		goto out;
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5130
  	}
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5131
  	/* re-sync apic's tpr */
eea1cff9a   Andre Przywara   KVM: x86: fix CR8...
5132
5133
5134
5135
5136
5137
  	if (!irqchip_in_kernel(vcpu->kvm)) {
  		if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
  			r = -EINVAL;
  			goto out;
  		}
  	}
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5138

5287f194b   Avi Kivity   KVM: Split mmio c...
5139
5140
5141
  	r = complete_mmio(vcpu);
  	if (r <= 0)
  		goto out;
851ba6922   Avi Kivity   KVM: Don't pass k...
5142
  	r = __vcpu_run(vcpu);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5143
5144
  
  out:
f1d86e469   Marcelo Tosatti   KVM: x86: properl...
5145
  	post_kvm_run_save(vcpu);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5146
5147
  	if (vcpu->sigset_active)
  		sigprocmask(SIG_SETMASK, &sigsaved, NULL);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5148
5149
5150
5151
5152
  	return r;
  }
  
  int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
  {
7ae441eac   Gleb Natapov   KVM: emulator: do...
5153
5154
5155
5156
5157
5158
5159
5160
  	if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
  		/*
  		 * We are here if userspace calls get_regs() in the middle of
  		 * instruction emulation. Registers state needs to be copied
  		 * back from emulation context to vcpu. Usrapace shouldn't do
  		 * that usually, but some bad designed PV devices (vmware
  		 * backdoor interface) need this to work
  		 */
9dac77fa4   Avi Kivity   KVM: x86 emulator...
5161
5162
  		struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
  		memcpy(vcpu->arch.regs, ctxt->regs, sizeof ctxt->regs);
7ae441eac   Gleb Natapov   KVM: emulator: do...
5163
5164
  		vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
  	}
5fdbf9765   Marcelo Tosatti   KVM: x86: accesso...
5165
5166
5167
5168
5169
5170
5171
5172
  	regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
  	regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
  	regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
  	regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
  	regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
  	regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
  	regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
  	regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5173
  #ifdef CONFIG_X86_64
5fdbf9765   Marcelo Tosatti   KVM: x86: accesso...
5174
5175
5176
5177
5178
5179
5180
5181
  	regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
  	regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
  	regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
  	regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
  	regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
  	regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
  	regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
  	regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5182
  #endif
5fdbf9765   Marcelo Tosatti   KVM: x86: accesso...
5183
  	regs->rip = kvm_rip_read(vcpu);
91586a3b7   Jan Kiszka   KVM: x86: Rework ...
5184
  	regs->rflags = kvm_get_rflags(vcpu);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5185

b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5186
5187
5188
5189
5190
  	return 0;
  }
  
  int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
  {
7ae441eac   Gleb Natapov   KVM: emulator: do...
5191
5192
  	vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
  	vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
5fdbf9765   Marcelo Tosatti   KVM: x86: accesso...
5193
5194
5195
5196
5197
5198
5199
5200
  	kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
  	kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
  	kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
  	kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
  	kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
  	kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
  	kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
  	kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5201
  #ifdef CONFIG_X86_64
5fdbf9765   Marcelo Tosatti   KVM: x86: accesso...
5202
5203
5204
5205
5206
5207
5208
5209
  	kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
  	kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
  	kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
  	kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
  	kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
  	kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
  	kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
  	kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5210
  #endif
5fdbf9765   Marcelo Tosatti   KVM: x86: accesso...
5211
  	kvm_rip_write(vcpu, regs->rip);
91586a3b7   Jan Kiszka   KVM: x86: Rework ...
5212
  	kvm_set_rflags(vcpu, regs->rflags);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5213

b4f14abd9   Jan Kiszka   KVM: Avoid spurio...
5214
  	vcpu->arch.exception.pending = false;
3842d135f   Avi Kivity   KVM: Check for pe...
5215
  	kvm_make_request(KVM_REQ_EVENT, vcpu);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5216
5217
  	return 0;
  }
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5218
5219
5220
  void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
  {
  	struct kvm_segment cs;
3e6e0aab1   Guillaume Thouvenin   KVM: Prefixes seg...
5221
  	kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5222
5223
5224
5225
5226
5227
5228
5229
  	*db = cs.db;
  	*l = cs.l;
  }
  EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
  
  int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
  				  struct kvm_sregs *sregs)
  {
89a27f4d0   Gleb Natapov   KVM: use desc_ptr...
5230
  	struct desc_ptr dt;
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5231

3e6e0aab1   Guillaume Thouvenin   KVM: Prefixes seg...
5232
5233
5234
5235
5236
5237
  	kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
  	kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
  	kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
  	kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
  	kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
  	kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5238

3e6e0aab1   Guillaume Thouvenin   KVM: Prefixes seg...
5239
5240
  	kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
  	kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5241
5242
  
  	kvm_x86_ops->get_idt(vcpu, &dt);
89a27f4d0   Gleb Natapov   KVM: use desc_ptr...
5243
5244
  	sregs->idt.limit = dt.size;
  	sregs->idt.base = dt.address;
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5245
  	kvm_x86_ops->get_gdt(vcpu, &dt);
89a27f4d0   Gleb Natapov   KVM: use desc_ptr...
5246
5247
  	sregs->gdt.limit = dt.size;
  	sregs->gdt.base = dt.address;
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5248

4d4ec0874   Avi Kivity   KVM: Replace read...
5249
  	sregs->cr0 = kvm_read_cr0(vcpu);
ad312c7c7   Zhang Xiantao   KVM: Portability:...
5250
  	sregs->cr2 = vcpu->arch.cr2;
9f8fe5043   Avi Kivity   KVM: Replace read...
5251
  	sregs->cr3 = kvm_read_cr3(vcpu);
fc78f5193   Avi Kivity   KVM: Add accessor...
5252
  	sregs->cr4 = kvm_read_cr4(vcpu);
2d3ad1f40   Avi Kivity   KVM: Prefix contr...
5253
  	sregs->cr8 = kvm_get_cr8(vcpu);
f6801dff2   Avi Kivity   KVM: Rename vcpu-...
5254
  	sregs->efer = vcpu->arch.efer;
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5255
  	sregs->apic_base = kvm_get_apic_base(vcpu);
923c61bbc   Gleb Natapov   KVM: Remove irq_p...
5256
  	memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5257

36752c9b9   Gleb Natapov   KVM: Do not migra...
5258
  	if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
14d0bc1f7   Gleb Natapov   KVM: Get rid of g...
5259
5260
  		set_bit(vcpu->arch.interrupt.nr,
  			(unsigned long *)sregs->interrupt_bitmap);
16d7a1911   Gleb Natapov   KVM: Fix userspac...
5261

b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5262
5263
  	return 0;
  }
62d9f0dbc   Marcelo Tosatti   KVM: add ioctls t...
5264
5265
5266
  int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
  				    struct kvm_mp_state *mp_state)
  {
62d9f0dbc   Marcelo Tosatti   KVM: add ioctls t...
5267
  	mp_state->mp_state = vcpu->arch.mp_state;
62d9f0dbc   Marcelo Tosatti   KVM: add ioctls t...
5268
5269
5270
5271
5272
5273
  	return 0;
  }
  
  int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
  				    struct kvm_mp_state *mp_state)
  {
62d9f0dbc   Marcelo Tosatti   KVM: add ioctls t...
5274
  	vcpu->arch.mp_state = mp_state->mp_state;
3842d135f   Avi Kivity   KVM: Check for pe...
5275
  	kvm_make_request(KVM_REQ_EVENT, vcpu);
62d9f0dbc   Marcelo Tosatti   KVM: add ioctls t...
5276
5277
  	return 0;
  }
e269fb218   Jan Kiszka   KVM: x86: Push po...
5278
5279
  int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int reason,
  		    bool has_error_code, u32 error_code)
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5280
  {
9d74191ab   Takuya Yoshikawa   KVM: x86 emulator...
5281
  	struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
8ec4722dd   Mohammed Gamal   KVM: Separate emu...
5282
  	int ret;
e01c24261   Gleb Natapov   KVM: mark segment...
5283

8ec4722dd   Mohammed Gamal   KVM: Separate emu...
5284
  	init_emulate_ctxt(vcpu);
c697518a8   Gleb Natapov   KVM: Fix segment ...
5285

9d74191ab   Takuya Yoshikawa   KVM: x86 emulator...
5286
5287
  	ret = emulator_task_switch(ctxt, tss_selector, reason,
  				   has_error_code, error_code);
c697518a8   Gleb Natapov   KVM: Fix segment ...
5288

c697518a8   Gleb Natapov   KVM: Fix segment ...
5289
  	if (ret)
19d044372   Gleb Natapov   KVM: fix emulator...
5290
  		return EMULATE_FAIL;
37817f298   Izik Eidus   KVM: x86: hardwar...
5291

9dac77fa4   Avi Kivity   KVM: x86 emulator...
5292
  	memcpy(vcpu->arch.regs, ctxt->regs, sizeof ctxt->regs);
9d74191ab   Takuya Yoshikawa   KVM: x86 emulator...
5293
5294
  	kvm_rip_write(vcpu, ctxt->eip);
  	kvm_set_rflags(vcpu, ctxt->eflags);
3842d135f   Avi Kivity   KVM: Check for pe...
5295
  	kvm_make_request(KVM_REQ_EVENT, vcpu);
19d044372   Gleb Natapov   KVM: fix emulator...
5296
  	return EMULATE_DONE;
37817f298   Izik Eidus   KVM: x86: hardwar...
5297
5298
  }
  EXPORT_SYMBOL_GPL(kvm_task_switch);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5299
5300
5301
5302
  int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
  				  struct kvm_sregs *sregs)
  {
  	int mmu_reset_needed = 0;
63f42e023   Xiao Guangrong   KVM: fix rcu usag...
5303
  	int pending_vec, max_bits, idx;
89a27f4d0   Gleb Natapov   KVM: use desc_ptr...
5304
  	struct desc_ptr dt;
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5305

89a27f4d0   Gleb Natapov   KVM: use desc_ptr...
5306
5307
  	dt.size = sregs->idt.limit;
  	dt.address = sregs->idt.base;
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5308
  	kvm_x86_ops->set_idt(vcpu, &dt);
89a27f4d0   Gleb Natapov   KVM: use desc_ptr...
5309
5310
  	dt.size = sregs->gdt.limit;
  	dt.address = sregs->gdt.base;
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5311
  	kvm_x86_ops->set_gdt(vcpu, &dt);
ad312c7c7   Zhang Xiantao   KVM: Portability:...
5312
  	vcpu->arch.cr2 = sregs->cr2;
9f8fe5043   Avi Kivity   KVM: Replace read...
5313
  	mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
dc7e795e3   Jan Kiszka   Revert "KVM: x86:...
5314
  	vcpu->arch.cr3 = sregs->cr3;
aff48baa3   Avi Kivity   KVM: Fetch guest ...
5315
  	__set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5316

2d3ad1f40   Avi Kivity   KVM: Prefix contr...
5317
  	kvm_set_cr8(vcpu, sregs->cr8);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5318

f6801dff2   Avi Kivity   KVM: Rename vcpu-...
5319
  	mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5320
  	kvm_x86_ops->set_efer(vcpu, sregs->efer);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5321
  	kvm_set_apic_base(vcpu, sregs->apic_base);
4d4ec0874   Avi Kivity   KVM: Replace read...
5322
  	mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5323
  	kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
d73061638   Paul Knowles   KVM: Fix kvm_arch...
5324
  	vcpu->arch.cr0 = sregs->cr0;
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5325

fc78f5193   Avi Kivity   KVM: Add accessor...
5326
  	mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5327
  	kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
3ea3aa8cf   Sheng Yang   KVM: Fix OSXSAVE ...
5328
  	if (sregs->cr4 & X86_CR4_OSXSAVE)
00b27a3ef   Avi Kivity   KVM: Move cpuid c...
5329
  		kvm_update_cpuid(vcpu);
63f42e023   Xiao Guangrong   KVM: fix rcu usag...
5330
5331
  
  	idx = srcu_read_lock(&vcpu->kvm->srcu);
7c93be44a   Marcelo Tosatti   KVM: VMX: move CR...
5332
  	if (!is_long_mode(vcpu) && is_pae(vcpu)) {
9f8fe5043   Avi Kivity   KVM: Replace read...
5333
  		load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
7c93be44a   Marcelo Tosatti   KVM: VMX: move CR...
5334
5335
  		mmu_reset_needed = 1;
  	}
63f42e023   Xiao Guangrong   KVM: fix rcu usag...
5336
  	srcu_read_unlock(&vcpu->kvm->srcu, idx);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5337
5338
5339
  
  	if (mmu_reset_needed)
  		kvm_mmu_reset_context(vcpu);
923c61bbc   Gleb Natapov   KVM: Remove irq_p...
5340
5341
5342
5343
  	max_bits = (sizeof sregs->interrupt_bitmap) << 3;
  	pending_vec = find_first_bit(
  		(const unsigned long *)sregs->interrupt_bitmap, max_bits);
  	if (pending_vec < max_bits) {
66fd3f7f9   Gleb Natapov   KVM: Do not re-ex...
5344
  		kvm_queue_interrupt(vcpu, pending_vec, false);
923c61bbc   Gleb Natapov   KVM: Remove irq_p...
5345
5346
  		pr_debug("Set back pending irq %d
  ", pending_vec);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5347
  	}
3e6e0aab1   Guillaume Thouvenin   KVM: Prefixes seg...
5348
5349
5350
5351
5352
5353
  	kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
  	kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
  	kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
  	kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
  	kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
  	kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5354

3e6e0aab1   Guillaume Thouvenin   KVM: Prefixes seg...
5355
5356
  	kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
  	kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5357

5f0269f5d   Mikhail Ershov   KVM: Align cr8 th...
5358
  	update_cr8_intercept(vcpu);
9c3e4aab5   Marcelo Tosatti   KVM: x86: unhalt ...
5359
  	/* Older userspace won't unhalt the vcpu on reset. */
c5af89b68   Gleb Natapov   KVM: Introduce kv...
5360
  	if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
9c3e4aab5   Marcelo Tosatti   KVM: x86: unhalt ...
5361
  	    sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
3eeb3288b   Avi Kivity   KVM: Add a helper...
5362
  	    !is_protmode(vcpu))
9c3e4aab5   Marcelo Tosatti   KVM: x86: unhalt ...
5363
  		vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
3842d135f   Avi Kivity   KVM: Check for pe...
5364
  	kvm_make_request(KVM_REQ_EVENT, vcpu);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5365
5366
  	return 0;
  }
d0bfb940e   Jan Kiszka   KVM: New guest de...
5367
5368
  int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
  					struct kvm_guest_debug *dbg)
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5369
  {
355be0b93   Jan Kiszka   KVM: x86: Refacto...
5370
  	unsigned long rflags;
ae675ef01   Jan Kiszka   KVM: x86: Wire-up...
5371
  	int i, r;
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5372

4f926bf29   Jan Kiszka   KVM: x86: Polish ...
5373
5374
5375
  	if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
  		r = -EBUSY;
  		if (vcpu->arch.exception.pending)
2122ff5ea   Avi Kivity   KVM: move vcpu lo...
5376
  			goto out;
4f926bf29   Jan Kiszka   KVM: x86: Polish ...
5377
5378
5379
5380
5381
  		if (dbg->control & KVM_GUESTDBG_INJECT_DB)
  			kvm_queue_exception(vcpu, DB_VECTOR);
  		else
  			kvm_queue_exception(vcpu, BP_VECTOR);
  	}
91586a3b7   Jan Kiszka   KVM: x86: Rework ...
5382
5383
5384
5385
5386
  	/*
  	 * Read rflags as long as potentially injected trace flags are still
  	 * filtered out.
  	 */
  	rflags = kvm_get_rflags(vcpu);
355be0b93   Jan Kiszka   KVM: x86: Refacto...
5387
5388
5389
5390
5391
5392
  
  	vcpu->guest_debug = dbg->control;
  	if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
  		vcpu->guest_debug = 0;
  
  	if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
ae675ef01   Jan Kiszka   KVM: x86: Wire-up...
5393
5394
5395
5396
5397
5398
5399
5400
5401
  		for (i = 0; i < KVM_NR_DB_REGS; ++i)
  			vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
  		vcpu->arch.switch_db_regs =
  			(dbg->arch.debugreg[7] & DR7_BP_EN_MASK);
  	} else {
  		for (i = 0; i < KVM_NR_DB_REGS; i++)
  			vcpu->arch.eff_db[i] = vcpu->arch.db[i];
  		vcpu->arch.switch_db_regs = (vcpu->arch.dr7 & DR7_BP_EN_MASK);
  	}
f92653eeb   Jan Kiszka   KVM: x86: Add kvm...
5402
5403
5404
  	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
  		vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
  			get_segment_base(vcpu, VCPU_SREG_CS);
94fe45da4   Jan Kiszka   KVM: x86: Fix gue...
5405

91586a3b7   Jan Kiszka   KVM: x86: Rework ...
5406
5407
5408
5409
5410
  	/*
  	 * Trigger an rflags update that will inject or remove the trace
  	 * flags.
  	 */
  	kvm_set_rflags(vcpu, rflags);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5411

355be0b93   Jan Kiszka   KVM: x86: Refacto...
5412
  	kvm_x86_ops->set_guest_debug(vcpu, dbg);
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5413

4f926bf29   Jan Kiszka   KVM: x86: Polish ...
5414
  	r = 0;
d0bfb940e   Jan Kiszka   KVM: New guest de...
5415

2122ff5ea   Avi Kivity   KVM: move vcpu lo...
5416
  out:
b6c7a5dcc   Hollis Blanchard   KVM: Portability:...
5417
5418
5419
5420
5421
  
  	return r;
  }
  
  /*
8b0067913   Zhang Xiantao   KVM: Portability:...
5422
5423
5424
5425
5426
5427
5428
   * Translate a guest virtual address to a guest physical address.
   */
  int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
  				    struct kvm_translation *tr)
  {
  	unsigned long vaddr = tr->linear_address;
  	gpa_t gpa;
f656ce018   Marcelo Tosatti   KVM: switch vcpu ...
5429
  	int idx;
8b0067913   Zhang Xiantao   KVM: Portability:...
5430

f656ce018   Marcelo Tosatti   KVM: switch vcpu ...
5431
  	idx = srcu_read_lock(&vcpu->kvm->srcu);
1871c6020   Gleb Natapov   KVM: x86 emulator...
5432
  	gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
f656ce018   Marcelo Tosatti   KVM: switch vcpu ...
5433
  	srcu_read_unlock(&vcpu->kvm->srcu, idx);
8b0067913   Zhang Xiantao   KVM: Portability:...
5434
5435
5436
5437
  	tr->physical_address = gpa;
  	tr->valid = gpa != UNMAPPED_GVA;
  	tr->writeable = 1;
  	tr->usermode = 0;
8b0067913   Zhang Xiantao   KVM: Portability:...
5438
5439
5440
  
  	return 0;
  }
d07520607   Hollis Blanchard   KVM: Portability:...
5441
5442
  int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
  {
98918833a   Sheng Yang   KVM: x86: Use FPU...
5443
5444
  	struct i387_fxsave_struct *fxsave =
  			&vcpu->arch.guest_fpu.state->fxsave;
d07520607   Hollis Blanchard   KVM: Portability:...
5445

d07520607   Hollis Blanchard   KVM: Portability:...
5446
5447
5448
5449
5450
5451
5452
5453
  	memcpy(fpu->fpr, fxsave->st_space, 128);
  	fpu->fcw = fxsave->cwd;
  	fpu->fsw = fxsave->swd;
  	fpu->ftwx = fxsave->twd;
  	fpu->last_opcode = fxsave->fop;
  	fpu->last_ip = fxsave->rip;
  	fpu->last_dp = fxsave->rdp;
  	memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
d07520607   Hollis Blanchard   KVM: Portability:...
5454
5455
5456
5457
5458
  	return 0;
  }
  
  int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
  {
98918833a   Sheng Yang   KVM: x86: Use FPU...
5459
5460
  	struct i387_fxsave_struct *fxsave =
  			&vcpu->arch.guest_fpu.state->fxsave;
d07520607   Hollis Blanchard   KVM: Portability:...
5461

d07520607   Hollis Blanchard   KVM: Portability:...
5462
5463
5464
5465
5466
5467
5468
5469
  	memcpy(fxsave->st_space, fpu->fpr, 128);
  	fxsave->cwd = fpu->fcw;
  	fxsave->swd = fpu->fsw;
  	fxsave->twd = fpu->ftwx;
  	fxsave->fop = fpu->last_opcode;
  	fxsave->rip = fpu->last_ip;
  	fxsave->rdp = fpu->last_dp;
  	memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
d07520607   Hollis Blanchard   KVM: Portability:...
5470
5471
  	return 0;
  }
10ab25cd6   Jan Kiszka   KVM: x86: Propaga...
5472
  int fx_init(struct kvm_vcpu *vcpu)
d07520607   Hollis Blanchard   KVM: Portability:...
5473
  {
10ab25cd6   Jan Kiszka   KVM: x86: Propaga...
5474
5475
5476
5477
5478
  	int err;
  
  	err = fpu_alloc(&vcpu->arch.guest_fpu);
  	if (err)
  		return err;
98918833a   Sheng Yang   KVM: x86: Use FPU...
5479
  	fpu_finit(&vcpu->arch.guest_fpu);
d07520607   Hollis Blanchard   KVM: Portability:...
5480

2acf923e3   Dexuan Cui   KVM: VMX: Enable ...
5481
5482
5483
5484
  	/*
  	 * Ensure guest xcr0 is valid for loading
  	 */
  	vcpu->arch.xcr0 = XSTATE_FP;
ad312c7c7   Zhang Xiantao   KVM: Portability:...
5485
  	vcpu->arch.cr0 |= X86_CR0_ET;
10ab25cd6   Jan Kiszka   KVM: x86: Propaga...
5486
5487
  
  	return 0;
d07520607   Hollis Blanchard   KVM: Portability:...
5488
5489
  }
  EXPORT_SYMBOL_GPL(fx_init);
98918833a   Sheng Yang   KVM: x86: Use FPU...
5490
5491
5492
5493
  static void fx_free(struct kvm_vcpu *vcpu)
  {
  	fpu_free(&vcpu->arch.guest_fpu);
  }
d07520607   Hollis Blanchard   KVM: Portability:...
5494
5495
  void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
  {
2608d7a12   Avi Kivity   KVM: Allow kvm_lo...
5496
  	if (vcpu->guest_fpu_loaded)
d07520607   Hollis Blanchard   KVM: Portability:...
5497
  		return;
2acf923e3   Dexuan Cui   KVM: VMX: Enable ...
5498
5499
5500
5501
5502
5503
  	/*
  	 * Restore all possible states in the guest,
  	 * and assume host would use all available bits.
  	 * Guest xcr0 would be loaded later.
  	 */
  	kvm_put_guest_xcr0(vcpu);
d07520607   Hollis Blanchard   KVM: Portability:...
5504
  	vcpu->guest_fpu_loaded = 1;
7cf30855e   Sheng Yang   KVM: x86: Use unl...
5505
  	unlazy_fpu(current);
98918833a   Sheng Yang   KVM: x86: Use FPU...
5506
  	fpu_restore_checking(&vcpu->arch.guest_fpu);
0c04851c0   Avi Kivity   KVM: trace guest ...
5507
  	trace_kvm_fpu(1);
d07520607   Hollis Blanchard   KVM: Portability:...
5508
  }
d07520607   Hollis Blanchard   KVM: Portability:...
5509
5510
5511
  
  void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
  {
2acf923e3   Dexuan Cui   KVM: VMX: Enable ...
5512
  	kvm_put_guest_xcr0(vcpu);
d07520607   Hollis Blanchard   KVM: Portability:...
5513
5514
5515
5516
  	if (!vcpu->guest_fpu_loaded)
  		return;
  
  	vcpu->guest_fpu_loaded = 0;
98918833a   Sheng Yang   KVM: x86: Use FPU...
5517
  	fpu_save_init(&vcpu->arch.guest_fpu);
f096ed858   Avi Kivity   KVM: Add fpu_relo...
5518
  	++vcpu->stat.fpu_reload;
a8eeb04a4   Avi Kivity   KVM: Add mini-API...
5519
  	kvm_make_request(KVM_REQ_DEACTIVATE_FPU, vcpu);
0c04851c0   Avi Kivity   KVM: trace guest ...
5520
  	trace_kvm_fpu(0);
d07520607   Hollis Blanchard   KVM: Portability:...
5521
  }
e9b11c175   Zhang Xiantao   KVM: Portability:...
5522
5523
5524
  
  void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
  {
12f9a48f7   Glauber Costa   KVM: x86: release...
5525
  	kvmclock_reset(vcpu);
7f1ea2089   Joerg Roedel   KVM: x86: release...
5526

f5f48ee15   Sheng Yang   KVM: VMX: Execute...
5527
  	free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
98918833a   Sheng Yang   KVM: x86: Use FPU...
5528
  	fx_free(vcpu);
e9b11c175   Zhang Xiantao   KVM: Portability:...
5529
5530
5531
5532
5533
5534
  	kvm_x86_ops->vcpu_free(vcpu);
  }
  
  struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
  						unsigned int id)
  {
6755bae8e   Zachary Amsden   KVM: x86: Warn ab...
5535
5536
5537
5538
5539
  	if (check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
  		printk_once(KERN_WARNING
  		"kvm: SMP vm created on host with unstable TSC; "
  		"guest TSC will not be reliable
  ");
26e5215fd   Avi Kivity   KVM: Split vcpu c...
5540
5541
  	return kvm_x86_ops->vcpu_create(kvm, id);
  }
e9b11c175   Zhang Xiantao   KVM: Portability:...
5542

26e5215fd   Avi Kivity   KVM: Split vcpu c...
5543
5544
5545
  int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
  {
  	int r;
e9b11c175   Zhang Xiantao   KVM: Portability:...
5546

0bed3b568   Sheng Yang   KVM: Improve MTRR...
5547
  	vcpu->arch.mtrr_state.have_fixed = 1;
e9b11c175   Zhang Xiantao   KVM: Portability:...
5548
5549
5550
5551
5552
  	vcpu_load(vcpu);
  	r = kvm_arch_vcpu_reset(vcpu);
  	if (r == 0)
  		r = kvm_mmu_setup(vcpu);
  	vcpu_put(vcpu);
e9b11c175   Zhang Xiantao   KVM: Portability:...
5553

26e5215fd   Avi Kivity   KVM: Split vcpu c...
5554
  	return r;
e9b11c175   Zhang Xiantao   KVM: Portability:...
5555
  }
d40ccc624   Hollis Blanchard   KVM: Correct cons...
5556
  void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
e9b11c175   Zhang Xiantao   KVM: Portability:...
5557
  {
344d9588a   Gleb Natapov   KVM: Add PV MSR t...
5558
  	vcpu->arch.apf.msr_val = 0;
e9b11c175   Zhang Xiantao   KVM: Portability:...
5559
5560
5561
  	vcpu_load(vcpu);
  	kvm_mmu_unload(vcpu);
  	vcpu_put(vcpu);
98918833a   Sheng Yang   KVM: x86: Use FPU...
5562
  	fx_free(vcpu);
e9b11c175   Zhang Xiantao   KVM: Portability:...
5563
5564
5565
5566
5567
  	kvm_x86_ops->vcpu_free(vcpu);
  }
  
  int kvm_arch_vcpu_reset(struct kvm_vcpu *vcpu)
  {
7460fb4a3   Avi Kivity   KVM: Fix simultan...
5568
5569
  	atomic_set(&vcpu->arch.nmi_queued, 0);
  	vcpu->arch.nmi_pending = 0;
448fa4a9c   Jan Kiszka   KVM: x86: Reset p...
5570
  	vcpu->arch.nmi_injected = false;
42dbaa5a0   Jan Kiszka   KVM: x86: Virtual...
5571
5572
5573
5574
  	vcpu->arch.switch_db_regs = 0;
  	memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
  	vcpu->arch.dr6 = DR6_FIXED_1;
  	vcpu->arch.dr7 = DR7_FIXED_1;
3842d135f   Avi Kivity   KVM: Check for pe...
5575
  	kvm_make_request(KVM_REQ_EVENT, vcpu);
344d9588a   Gleb Natapov   KVM: Add PV MSR t...
5576
  	vcpu->arch.apf.msr_val = 0;
c9aaa8957   Glauber Costa   KVM: Steal time i...
5577
  	vcpu->arch.st.msr_val = 0;
3842d135f   Avi Kivity   KVM: Check for pe...
5578

12f9a48f7   Glauber Costa   KVM: x86: release...
5579
  	kvmclock_reset(vcpu);
af585b921   Gleb Natapov   KVM: Halt vcpu if...
5580
5581
5582
  	kvm_clear_async_pf_completion_queue(vcpu);
  	kvm_async_pf_hash_reset(vcpu);
  	vcpu->arch.apf.halted = false;
3842d135f   Avi Kivity   KVM: Check for pe...
5583

f5132b013   Gleb Natapov   KVM: Expose a ver...
5584
  	kvm_pmu_reset(vcpu);
e9b11c175   Zhang Xiantao   KVM: Portability:...
5585
5586
  	return kvm_x86_ops->vcpu_reset(vcpu);
  }
10474ae89   Alexander Graf   KVM: Activate Vir...
5587
  int kvm_arch_hardware_enable(void *garbage)
e9b11c175   Zhang Xiantao   KVM: Portability:...
5588
  {
ca84d1a24   Zachary Amsden   KVM: x86: Add clo...
5589
5590
5591
  	struct kvm *kvm;
  	struct kvm_vcpu *vcpu;
  	int i;
18863bdd6   Avi Kivity   KVM: x86 shared m...
5592
5593
  
  	kvm_shared_msr_cpu_online();
ca84d1a24   Zachary Amsden   KVM: x86: Add clo...
5594
5595
5596
  	list_for_each_entry(kvm, &vm_list, vm_list)
  		kvm_for_each_vcpu(i, vcpu, kvm)
  			if (vcpu->cpu == smp_processor_id())
c285545f8   Zachary Amsden   KVM: x86: TSC cat...
5597
  				kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
10474ae89   Alexander Graf   KVM: Activate Vir...
5598
  	return kvm_x86_ops->hardware_enable(garbage);
e9b11c175   Zhang Xiantao   KVM: Portability:...
5599
5600
5601
5602
5603
  }
  
  void kvm_arch_hardware_disable(void *garbage)
  {
  	kvm_x86_ops->hardware_disable(garbage);
3548bab50   Avi Kivity   KVM: Drop user re...
5604
  	drop_user_return_notifiers(garbage);
e9b11c175   Zhang Xiantao   KVM: Portability:...
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
  }
  
  int kvm_arch_hardware_setup(void)
  {
  	return kvm_x86_ops->hardware_setup();
  }
  
  void kvm_arch_hardware_unsetup(void)
  {
  	kvm_x86_ops->hardware_unsetup();
  }
  
  void kvm_arch_check_processor_compat(void *rtn)
  {
  	kvm_x86_ops->check_processor_compatibility(rtn);
  }
  
  int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
  {
  	struct page *page;
  	struct kvm *kvm;
  	int r;
  
  	BUG_ON(vcpu->kvm == NULL);
  	kvm = vcpu->kvm;
9aabc88fc   Avi Kivity   KVM: x86 emulator...
5630
  	vcpu->arch.emulate_ctxt.ops = &emulate_ops;
c5af89b68   Gleb Natapov   KVM: Introduce kv...
5631
  	if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_bsp(vcpu))
a45352908   Avi Kivity   KVM: Rename VCPU_...
5632
  		vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
e9b11c175   Zhang Xiantao   KVM: Portability:...
5633
  	else
a45352908   Avi Kivity   KVM: Rename VCPU_...
5634
  		vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
e9b11c175   Zhang Xiantao   KVM: Portability:...
5635
5636
5637
5638
5639
5640
  
  	page = alloc_page(GFP_KERNEL | __GFP_ZERO);
  	if (!page) {
  		r = -ENOMEM;
  		goto fail;
  	}
ad312c7c7   Zhang Xiantao   KVM: Portability:...
5641
  	vcpu->arch.pio_data = page_address(page);
e9b11c175   Zhang Xiantao   KVM: Portability:...
5642

1e993611d   Joerg Roedel   KVM: X86: Let kvm...
5643
  	kvm_init_tsc_catchup(vcpu, max_tsc_khz);
c285545f8   Zachary Amsden   KVM: x86: TSC cat...
5644

e9b11c175   Zhang Xiantao   KVM: Portability:...
5645
5646
5647
5648
5649
5650
5651
5652
5653
  	r = kvm_mmu_create(vcpu);
  	if (r < 0)
  		goto fail_free_pio_data;
  
  	if (irqchip_in_kernel(kvm)) {
  		r = kvm_create_lapic(vcpu);
  		if (r < 0)
  			goto fail_mmu_destroy;
  	}
890ca9aef   Huang Ying   KVM: Add MCE support
5654
5655
5656
5657
  	vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
  				       GFP_KERNEL);
  	if (!vcpu->arch.mce_banks) {
  		r = -ENOMEM;
443c39bc9   Wei Yongjun   KVM: x86: Fix lea...
5658
  		goto fail_free_lapic;
890ca9aef   Huang Ying   KVM: Add MCE support
5659
5660
  	}
  	vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
f5f48ee15   Sheng Yang   KVM: VMX: Execute...
5661
5662
  	if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL))
  		goto fail_free_mce_banks;
af585b921   Gleb Natapov   KVM: Halt vcpu if...
5663
  	kvm_async_pf_hash_reset(vcpu);
f5132b013   Gleb Natapov   KVM: Expose a ver...
5664
  	kvm_pmu_init(vcpu);
af585b921   Gleb Natapov   KVM: Halt vcpu if...
5665

e9b11c175   Zhang Xiantao   KVM: Portability:...
5666
  	return 0;
f5f48ee15   Sheng Yang   KVM: VMX: Execute...
5667
5668
  fail_free_mce_banks:
  	kfree(vcpu->arch.mce_banks);
443c39bc9   Wei Yongjun   KVM: x86: Fix lea...
5669
5670
  fail_free_lapic:
  	kvm_free_lapic(vcpu);
e9b11c175   Zhang Xiantao   KVM: Portability:...
5671
5672
5673
  fail_mmu_destroy:
  	kvm_mmu_destroy(vcpu);
  fail_free_pio_data:
ad312c7c7   Zhang Xiantao   KVM: Portability:...
5674
  	free_page((unsigned long)vcpu->arch.pio_data);
e9b11c175   Zhang Xiantao   KVM: Portability:...
5675
5676
5677
5678
5679
5680
  fail:
  	return r;
  }
  
  void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
  {
f656ce018   Marcelo Tosatti   KVM: switch vcpu ...
5681
  	int idx;
f5132b013   Gleb Natapov   KVM: Expose a ver...
5682
  	kvm_pmu_destroy(vcpu);
36cb93fd6   Wei Yongjun   KVM: x86: Fix pro...
5683
  	kfree(vcpu->arch.mce_banks);
e9b11c175   Zhang Xiantao   KVM: Portability:...
5684
  	kvm_free_lapic(vcpu);
f656ce018   Marcelo Tosatti   KVM: switch vcpu ...
5685
  	idx = srcu_read_lock(&vcpu->kvm->srcu);
e9b11c175   Zhang Xiantao   KVM: Portability:...
5686
  	kvm_mmu_destroy(vcpu);
f656ce018   Marcelo Tosatti   KVM: switch vcpu ...
5687
  	srcu_read_unlock(&vcpu->kvm->srcu, idx);
ad312c7c7   Zhang Xiantao   KVM: Portability:...
5688
  	free_page((unsigned long)vcpu->arch.pio_data);
e9b11c175   Zhang Xiantao   KVM: Portability:...
5689
  }
d19a9cd27   Zhang Xiantao   KVM: Portability:...
5690

d89f5eff7   Jan Kiszka   KVM: Clean up vm ...
5691
  int kvm_arch_init_vm(struct kvm *kvm)
d19a9cd27   Zhang Xiantao   KVM: Portability:...
5692
  {
f05e70ac0   Zhang Xiantao   KVM: Portability:...
5693
  	INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
4d5c5d0fe   Ben-Ami Yassour   KVM: pci device a...
5694
  	INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
d19a9cd27   Zhang Xiantao   KVM: Portability:...
5695

5550af4df   Sheng Yang   KVM: Fix guest sh...
5696
5697
  	/* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
  	set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
038f8c110   Jan Kiszka   KVM: x86: Convert...
5698
  	raw_spin_lock_init(&kvm->arch.tsc_write_lock);
53f658b3c   Marcelo Tosatti   KVM: VMX: initial...
5699

d89f5eff7   Jan Kiszka   KVM: Clean up vm ...
5700
  	return 0;
d19a9cd27   Zhang Xiantao   KVM: Portability:...
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
  }
  
  static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
  {
  	vcpu_load(vcpu);
  	kvm_mmu_unload(vcpu);
  	vcpu_put(vcpu);
  }
  
  static void kvm_free_vcpus(struct kvm *kvm)
  {
  	unsigned int i;
988a2cae6   Gleb Natapov   KVM: Use macro to...
5713
  	struct kvm_vcpu *vcpu;
d19a9cd27   Zhang Xiantao   KVM: Portability:...
5714
5715
5716
5717
  
  	/*
  	 * Unpin any mmu pages first.
  	 */
af585b921   Gleb Natapov   KVM: Halt vcpu if...
5718
5719
  	kvm_for_each_vcpu(i, vcpu, kvm) {
  		kvm_clear_async_pf_completion_queue(vcpu);
988a2cae6   Gleb Natapov   KVM: Use macro to...
5720
  		kvm_unload_vcpu_mmu(vcpu);
af585b921   Gleb Natapov   KVM: Halt vcpu if...
5721
  	}
988a2cae6   Gleb Natapov   KVM: Use macro to...
5722
5723
5724
5725
5726
5727
  	kvm_for_each_vcpu(i, vcpu, kvm)
  		kvm_arch_vcpu_free(vcpu);
  
  	mutex_lock(&kvm->lock);
  	for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
  		kvm->vcpus[i] = NULL;
d19a9cd27   Zhang Xiantao   KVM: Portability:...
5728

988a2cae6   Gleb Natapov   KVM: Use macro to...
5729
5730
  	atomic_set(&kvm->online_vcpus, 0);
  	mutex_unlock(&kvm->lock);
d19a9cd27   Zhang Xiantao   KVM: Portability:...
5731
  }
ad8ba2cd4   Sheng Yang   KVM: Add kvm_arch...
5732
5733
  void kvm_arch_sync_events(struct kvm *kvm)
  {
ba4cef31d   Sheng Yang   KVM: Fix racy in ...
5734
  	kvm_free_all_assigned_devices(kvm);
aea924f60   Xiao Guangrong   KVM: PIT: stop vp...
5735
  	kvm_free_pit(kvm);
ad8ba2cd4   Sheng Yang   KVM: Add kvm_arch...
5736
  }
d19a9cd27   Zhang Xiantao   KVM: Portability:...
5737
5738
  void kvm_arch_destroy_vm(struct kvm *kvm)
  {
6eb55818c   Sheng Yang   KVM: Enable Funct...
5739
  	kvm_iommu_unmap_guest(kvm);
d7deeeb02   Zhang Xiantao   KVM: Portability:...
5740
5741
  	kfree(kvm->arch.vpic);
  	kfree(kvm->arch.vioapic);
d19a9cd27   Zhang Xiantao   KVM: Portability:...
5742
  	kvm_free_vcpus(kvm);
3d45830c2   Avi Kivity   KVM: Free apic ac...
5743
5744
  	if (kvm->arch.apic_access_page)
  		put_page(kvm->arch.apic_access_page);
b7ebfb050   Sheng Yang   KVM: VMX: Prepare...
5745
5746
  	if (kvm->arch.ept_identity_pagetable)
  		put_page(kvm->arch.ept_identity_pagetable);
d19a9cd27   Zhang Xiantao   KVM: Portability:...
5747
  }
0de10343b   Zhang Xiantao   KVM: Portability:...
5748

f7784b8ec   Marcelo Tosatti   KVM: split kvm_ar...
5749
5750
  int kvm_arch_prepare_memory_region(struct kvm *kvm,
  				struct kvm_memory_slot *memslot,
0de10343b   Zhang Xiantao   KVM: Portability:...
5751
  				struct kvm_memory_slot old,
f7784b8ec   Marcelo Tosatti   KVM: split kvm_ar...
5752
  				struct kvm_userspace_memory_region *mem,
0de10343b   Zhang Xiantao   KVM: Portability:...
5753
5754
  				int user_alloc)
  {
f7784b8ec   Marcelo Tosatti   KVM: split kvm_ar...
5755
  	int npages = memslot->npages;
7ac77099c   Avi Kivity   KVM: Prevent inte...
5756
5757
5758
5759
5760
  	int map_flags = MAP_PRIVATE | MAP_ANONYMOUS;
  
  	/* Prevent internal slot pages from being moved by fork()/COW. */
  	if (memslot->id >= KVM_MEMORY_SLOTS)
  		map_flags = MAP_SHARED | MAP_ANONYMOUS;
0de10343b   Zhang Xiantao   KVM: Portability:...
5761
5762
5763
5764
5765
5766
  
  	/*To keep backward compatibility with older userspace,
  	 *x86 needs to hanlde !user_alloc case.
  	 */
  	if (!user_alloc) {
  		if (npages && !old.rmap) {
604b38ac0   Andrea Arcangeli   KVM: Allow browsi...
5767
  			unsigned long userspace_addr;
72dc67a69   Izik Eidus   KVM: remove the u...
5768
  			down_write(&current->mm->mmap_sem);
604b38ac0   Andrea Arcangeli   KVM: Allow browsi...
5769
5770
5771
  			userspace_addr = do_mmap(NULL, 0,
  						 npages * PAGE_SIZE,
  						 PROT_READ | PROT_WRITE,
7ac77099c   Avi Kivity   KVM: Prevent inte...
5772
  						 map_flags,
604b38ac0   Andrea Arcangeli   KVM: Allow browsi...
5773
  						 0);
72dc67a69   Izik Eidus   KVM: remove the u...
5774
  			up_write(&current->mm->mmap_sem);
0de10343b   Zhang Xiantao   KVM: Portability:...
5775

604b38ac0   Andrea Arcangeli   KVM: Allow browsi...
5776
5777
  			if (IS_ERR((void *)userspace_addr))
  				return PTR_ERR((void *)userspace_addr);
604b38ac0   Andrea Arcangeli   KVM: Allow browsi...
5778
  			memslot->userspace_addr = userspace_addr;
0de10343b   Zhang Xiantao   KVM: Portability:...
5779
5780
  		}
  	}
f7784b8ec   Marcelo Tosatti   KVM: split kvm_ar...
5781
5782
5783
5784
5785
5786
5787
5788
5789
  
  	return 0;
  }
  
  void kvm_arch_commit_memory_region(struct kvm *kvm,
  				struct kvm_userspace_memory_region *mem,
  				struct kvm_memory_slot old,
  				int user_alloc)
  {
48c0e4e90   Xiao Guangrong   KVM: MMU: move mm...
5790
  	int nr_mmu_pages = 0, npages = mem->memory_size >> PAGE_SHIFT;
f7784b8ec   Marcelo Tosatti   KVM: split kvm_ar...
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
  
  	if (!user_alloc && !old.user_alloc && old.rmap && !npages) {
  		int ret;
  
  		down_write(&current->mm->mmap_sem);
  		ret = do_munmap(current->mm, old.userspace_addr,
  				old.npages * PAGE_SIZE);
  		up_write(&current->mm->mmap_sem);
  		if (ret < 0)
  			printk(KERN_WARNING
  			       "kvm_vm_ioctl_set_memory_region: "
  			       "failed to munmap memory
  ");
  	}
48c0e4e90   Xiao Guangrong   KVM: MMU: move mm...
5805
5806
  	if (!kvm->arch.n_requested_mmu_pages)
  		nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
7c8a83b75   Marcelo Tosatti   KVM: MMU: protect...
5807
  	spin_lock(&kvm->mmu_lock);
48c0e4e90   Xiao Guangrong   KVM: MMU: move mm...
5808
  	if (nr_mmu_pages)
0de10343b   Zhang Xiantao   KVM: Portability:...
5809
  		kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
0de10343b   Zhang Xiantao   KVM: Portability:...
5810
  	kvm_mmu_slot_remove_write_access(kvm, mem->slot);
7c8a83b75   Marcelo Tosatti   KVM: MMU: protect...
5811
  	spin_unlock(&kvm->mmu_lock);
0de10343b   Zhang Xiantao   KVM: Portability:...
5812
  }
1d737c8a6   Zhang Xiantao   KVM: Portability:...
5813

34d4cb8fc   Marcelo Tosatti   KVM: MMU: nuke sh...
5814
5815
5816
  void kvm_arch_flush_shadow(struct kvm *kvm)
  {
  	kvm_mmu_zap_all(kvm);
8986ecc0e   Marcelo Tosatti   KVM: x86: check f...
5817
  	kvm_reload_remote_mmus(kvm);
34d4cb8fc   Marcelo Tosatti   KVM: MMU: nuke sh...
5818
  }
1d737c8a6   Zhang Xiantao   KVM: Portability:...
5819
5820
  int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
  {
af585b921   Gleb Natapov   KVM: Halt vcpu if...
5821
5822
5823
  	return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
  		!vcpu->arch.apf.halted)
  		|| !list_empty_careful(&vcpu->async_pf.done)
a1b37100d   Gleb Natapov   KVM: Reduce runna...
5824
  		|| vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED
7460fb4a3   Avi Kivity   KVM: Fix simultan...
5825
  		|| atomic_read(&vcpu->arch.nmi_queued) ||
a1b37100d   Gleb Natapov   KVM: Reduce runna...
5826
5827
  		(kvm_arch_interrupt_allowed(vcpu) &&
  		 kvm_cpu_has_interrupt(vcpu));
1d737c8a6   Zhang Xiantao   KVM: Portability:...
5828
  }
5736199af   Zhang Xiantao   KVM: Move kvm_vcp...
5829

5736199af   Zhang Xiantao   KVM: Move kvm_vcp...
5830
5831
  void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
  {
32f884006   Marcelo Tosatti   KVM: use smp_send...
5832
5833
  	int me;
  	int cpu = vcpu->cpu;
5736199af   Zhang Xiantao   KVM: Move kvm_vcp...
5834
5835
5836
5837
5838
  
  	if (waitqueue_active(&vcpu->wq)) {
  		wake_up_interruptible(&vcpu->wq);
  		++vcpu->stat.halt_wakeup;
  	}
32f884006   Marcelo Tosatti   KVM: use smp_send...
5839
5840
5841
  
  	me = get_cpu();
  	if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
6b7e2d099   Xiao Guangrong   KVM: Add "exiting...
5842
  		if (kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE)
32f884006   Marcelo Tosatti   KVM: use smp_send...
5843
  			smp_send_reschedule(cpu);
e9571ed54   Marcelo Tosatti   KVM: fix kvm_vcpu...
5844
  	put_cpu();
5736199af   Zhang Xiantao   KVM: Move kvm_vcp...
5845
  }
78646121e   Gleb Natapov   KVM: Fix interrup...
5846
5847
5848
5849
5850
  
  int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
  {
  	return kvm_x86_ops->interrupt_allowed(vcpu);
  }
229456fc3   Marcelo Tosatti   KVM: convert cust...
5851

f92653eeb   Jan Kiszka   KVM: x86: Add kvm...
5852
5853
5854
5855
5856
5857
5858
5859
  bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
  {
  	unsigned long current_rip = kvm_rip_read(vcpu) +
  		get_segment_base(vcpu, VCPU_SREG_CS);
  
  	return current_rip == linear_rip;
  }
  EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
94fe45da4   Jan Kiszka   KVM: x86: Fix gue...
5860
5861
5862
5863
5864
5865
  unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
  {
  	unsigned long rflags;
  
  	rflags = kvm_x86_ops->get_rflags(vcpu);
  	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
c310bac5a   Jan Kiszka   KVM: x86: Drop RF...
5866
  		rflags &= ~X86_EFLAGS_TF;
94fe45da4   Jan Kiszka   KVM: x86: Fix gue...
5867
5868
5869
5870
5871
5872
5873
  	return rflags;
  }
  EXPORT_SYMBOL_GPL(kvm_get_rflags);
  
  void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
  {
  	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
f92653eeb   Jan Kiszka   KVM: x86: Add kvm...
5874
  	    kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
c310bac5a   Jan Kiszka   KVM: x86: Drop RF...
5875
  		rflags |= X86_EFLAGS_TF;
94fe45da4   Jan Kiszka   KVM: x86: Fix gue...
5876
  	kvm_x86_ops->set_rflags(vcpu, rflags);
3842d135f   Avi Kivity   KVM: Check for pe...
5877
  	kvm_make_request(KVM_REQ_EVENT, vcpu);
94fe45da4   Jan Kiszka   KVM: x86: Fix gue...
5878
5879
  }
  EXPORT_SYMBOL_GPL(kvm_set_rflags);
56028d086   Gleb Natapov   KVM: Retry fault ...
5880
5881
5882
  void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
  {
  	int r;
fb67e14fc   Xiao Guangrong   KVM: MMU: retry #...
5883
  	if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
c4806acdc   Xiao Guangrong   KVM: MMU: fix apf...
5884
  	      is_error_page(work->page))
56028d086   Gleb Natapov   KVM: Retry fault ...
5885
5886
5887
5888
5889
  		return;
  
  	r = kvm_mmu_reload(vcpu);
  	if (unlikely(r))
  		return;
fb67e14fc   Xiao Guangrong   KVM: MMU: retry #...
5890
5891
5892
  	if (!vcpu->arch.mmu.direct_map &&
  	      work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
  		return;
56028d086   Gleb Natapov   KVM: Retry fault ...
5893
5894
  	vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
  }
af585b921   Gleb Natapov   KVM: Halt vcpu if...
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
  static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
  {
  	return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
  }
  
  static inline u32 kvm_async_pf_next_probe(u32 key)
  {
  	return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
  }
  
  static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
  {
  	u32 key = kvm_async_pf_hash_fn(gfn);
  
  	while (vcpu->arch.apf.gfns[key] != ~0)
  		key = kvm_async_pf_next_probe(key);
  
  	vcpu->arch.apf.gfns[key] = gfn;
  }
  
  static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
  {
  	int i;
  	u32 key = kvm_async_pf_hash_fn(gfn);
  
  	for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
c7d28c240   Xiao Guangrong   KVM: fix searchin...
5921
5922
  		     (vcpu->arch.apf.gfns[key] != gfn &&
  		      vcpu->arch.apf.gfns[key] != ~0); i++)
af585b921   Gleb Natapov   KVM: Halt vcpu if...
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
  		key = kvm_async_pf_next_probe(key);
  
  	return key;
  }
  
  bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
  {
  	return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
  }
  
  static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
  {
  	u32 i, j, k;
  
  	i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
  	while (true) {
  		vcpu->arch.apf.gfns[i] = ~0;
  		do {
  			j = kvm_async_pf_next_probe(j);
  			if (vcpu->arch.apf.gfns[j] == ~0)
  				return;
  			k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
  			/*
  			 * k lies cyclically in ]i,j]
  			 * |    i.k.j |
  			 * |....j i.k.| or  |.k..j i...|
  			 */
  		} while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
  		vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
  		i = j;
  	}
  }
7c90705bf   Gleb Natapov   KVM: Inject async...
5955
5956
5957
5958
5959
5960
  static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
  {
  
  	return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
  				      sizeof(val));
  }
af585b921   Gleb Natapov   KVM: Halt vcpu if...
5961
5962
5963
  void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
  				     struct kvm_async_pf *work)
  {
6389ee946   Avi Kivity   KVM: Pull extra p...
5964
  	struct x86_exception fault;
7c90705bf   Gleb Natapov   KVM: Inject async...
5965
  	trace_kvm_async_pf_not_present(work->arch.token, work->gva);
af585b921   Gleb Natapov   KVM: Halt vcpu if...
5966
  	kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
7c90705bf   Gleb Natapov   KVM: Inject async...
5967
5968
  
  	if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
fc5f06fac   Gleb Natapov   KVM: Send async P...
5969
5970
  	    (vcpu->arch.apf.send_user_only &&
  	     kvm_x86_ops->get_cpl(vcpu) == 0))
7c90705bf   Gleb Natapov   KVM: Inject async...
5971
5972
  		kvm_make_request(KVM_REQ_APF_HALT, vcpu);
  	else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
6389ee946   Avi Kivity   KVM: Pull extra p...
5973
5974
5975
5976
5977
5978
  		fault.vector = PF_VECTOR;
  		fault.error_code_valid = true;
  		fault.error_code = 0;
  		fault.nested_page_fault = false;
  		fault.address = work->arch.token;
  		kvm_inject_page_fault(vcpu, &fault);
7c90705bf   Gleb Natapov   KVM: Inject async...
5979
  	}
af585b921   Gleb Natapov   KVM: Halt vcpu if...
5980
5981
5982
5983
5984
  }
  
  void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
  				 struct kvm_async_pf *work)
  {
6389ee946   Avi Kivity   KVM: Pull extra p...
5985
  	struct x86_exception fault;
7c90705bf   Gleb Natapov   KVM: Inject async...
5986
5987
5988
5989
5990
5991
5992
5993
  	trace_kvm_async_pf_ready(work->arch.token, work->gva);
  	if (is_error_page(work->page))
  		work->arch.token = ~0; /* broadcast wakeup */
  	else
  		kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
  
  	if ((vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) &&
  	    !apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
6389ee946   Avi Kivity   KVM: Pull extra p...
5994
5995
5996
5997
5998
5999
  		fault.vector = PF_VECTOR;
  		fault.error_code_valid = true;
  		fault.error_code = 0;
  		fault.nested_page_fault = false;
  		fault.address = work->arch.token;
  		kvm_inject_page_fault(vcpu, &fault);
7c90705bf   Gleb Natapov   KVM: Inject async...
6000
  	}
e6d53e3b0   Xiao Guangrong   KVM: avoid unnece...
6001
  	vcpu->arch.apf.halted = false;
7c90705bf   Gleb Natapov   KVM: Inject async...
6002
6003
6004
6005
6006
6007
6008
6009
6010
  }
  
  bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
  {
  	if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
  		return true;
  	else
  		return !kvm_event_needs_reinjection(vcpu) &&
  			kvm_x86_ops->interrupt_allowed(vcpu);
af585b921   Gleb Natapov   KVM: Halt vcpu if...
6011
  }
229456fc3   Marcelo Tosatti   KVM: convert cust...
6012
6013
6014
6015
6016
  EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
  EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
  EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
  EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
  EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
0ac406de8   Joerg Roedel   KVM: SVM: Add tra...
6017
  EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
d8cabddf7   Joerg Roedel   KVM: SVM: Add tra...
6018
  EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
17897f366   Joerg Roedel   KVM: SVM: Add tra...
6019
  EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
236649de3   Joerg Roedel   KVM: SVM: Add tra...
6020
  EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
ec1ff7908   Joerg Roedel   KVM: SVM: Add tra...
6021
  EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
532a46b98   Joerg Roedel   KVM: SVM: Add tra...
6022
  EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
2e554e8d6   Joerg Roedel   KVM: SVM: Add kvm...
6023
  EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);