KVM: SVM: add rdmsr support for AMD event registers
[sfrench/cifs-2.6.git] / arch / x86 / kvm / x86.c
1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * derived from drivers/kvm/kvm_main.c
5  *
6  * Copyright (C) 2006 Qumranet, Inc.
7  * Copyright (C) 2008 Qumranet, Inc.
8  * Copyright IBM Corporation, 2008
9  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
10  *
11  * Authors:
12  *   Avi Kivity   <avi@qumranet.com>
13  *   Yaniv Kamay  <yaniv@qumranet.com>
14  *   Amit Shah    <amit.shah@qumranet.com>
15  *   Ben-Ami Yassour <benami@il.ibm.com>
16  *
17  * This work is licensed under the terms of the GNU GPL, version 2.  See
18  * the COPYING file in the top-level directory.
19  *
20  */
21
22 #include <linux/kvm_host.h>
23 #include "irq.h"
24 #include "mmu.h"
25 #include "i8254.h"
26 #include "tss.h"
27 #include "kvm_cache_regs.h"
28 #include "x86.h"
29 #include "cpuid.h"
30
31 #include <linux/clocksource.h>
32 #include <linux/interrupt.h>
33 #include <linux/kvm.h>
34 #include <linux/fs.h>
35 #include <linux/vmalloc.h>
36 #include <linux/module.h>
37 #include <linux/mman.h>
38 #include <linux/highmem.h>
39 #include <linux/iommu.h>
40 #include <linux/intel-iommu.h>
41 #include <linux/cpufreq.h>
42 #include <linux/user-return-notifier.h>
43 #include <linux/srcu.h>
44 #include <linux/slab.h>
45 #include <linux/perf_event.h>
46 #include <linux/uaccess.h>
47 #include <linux/hash.h>
48 #include <linux/pci.h>
49 #include <linux/timekeeper_internal.h>
50 #include <linux/pvclock_gtod.h>
51 #include <trace/events/kvm.h>
52
53 #define CREATE_TRACE_POINTS
54 #include "trace.h"
55
56 #include <asm/debugreg.h>
57 #include <asm/msr.h>
58 #include <asm/desc.h>
59 #include <asm/mtrr.h>
60 #include <asm/mce.h>
61 #include <asm/i387.h>
62 #include <asm/fpu-internal.h> /* Ugh! */
63 #include <asm/xcr.h>
64 #include <asm/pvclock.h>
65 #include <asm/div64.h>
66
67 #define MAX_IO_MSRS 256
68 #define KVM_MAX_MCE_BANKS 32
69 #define KVM_MCE_CAP_SUPPORTED (MCG_CTL_P | MCG_SER_P)
70
71 #define emul_to_vcpu(ctxt) \
72         container_of(ctxt, struct kvm_vcpu, arch.emulate_ctxt)
73
74 /* EFER defaults:
75  * - enable syscall per default because its emulated by KVM
76  * - enable LME and LMA per default on 64 bit KVM
77  */
78 #ifdef CONFIG_X86_64
79 static
80 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
81 #else
82 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
83 #endif
84
85 #define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
86 #define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
87
88 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
89 static void process_nmi(struct kvm_vcpu *vcpu);
90 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
91
92 struct kvm_x86_ops *kvm_x86_ops;
93 EXPORT_SYMBOL_GPL(kvm_x86_ops);
94
95 static bool ignore_msrs = 0;
96 module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
97
98 unsigned int min_timer_period_us = 500;
99 module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
100
101 bool kvm_has_tsc_control;
102 EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
103 u32  kvm_max_guest_tsc_khz;
104 EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
105
106 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
107 static u32 tsc_tolerance_ppm = 250;
108 module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
109
110 static bool backwards_tsc_observed = false;
111
112 #define KVM_NR_SHARED_MSRS 16
113
114 struct kvm_shared_msrs_global {
115         int nr;
116         u32 msrs[KVM_NR_SHARED_MSRS];
117 };
118
119 struct kvm_shared_msrs {
120         struct user_return_notifier urn;
121         bool registered;
122         struct kvm_shared_msr_values {
123                 u64 host;
124                 u64 curr;
125         } values[KVM_NR_SHARED_MSRS];
126 };
127
128 static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
129 static struct kvm_shared_msrs __percpu *shared_msrs;
130
131 struct kvm_stats_debugfs_item debugfs_entries[] = {
132         { "pf_fixed", VCPU_STAT(pf_fixed) },
133         { "pf_guest", VCPU_STAT(pf_guest) },
134         { "tlb_flush", VCPU_STAT(tlb_flush) },
135         { "invlpg", VCPU_STAT(invlpg) },
136         { "exits", VCPU_STAT(exits) },
137         { "io_exits", VCPU_STAT(io_exits) },
138         { "mmio_exits", VCPU_STAT(mmio_exits) },
139         { "signal_exits", VCPU_STAT(signal_exits) },
140         { "irq_window", VCPU_STAT(irq_window_exits) },
141         { "nmi_window", VCPU_STAT(nmi_window_exits) },
142         { "halt_exits", VCPU_STAT(halt_exits) },
143         { "halt_wakeup", VCPU_STAT(halt_wakeup) },
144         { "hypercalls", VCPU_STAT(hypercalls) },
145         { "request_irq", VCPU_STAT(request_irq_exits) },
146         { "irq_exits", VCPU_STAT(irq_exits) },
147         { "host_state_reload", VCPU_STAT(host_state_reload) },
148         { "efer_reload", VCPU_STAT(efer_reload) },
149         { "fpu_reload", VCPU_STAT(fpu_reload) },
150         { "insn_emulation", VCPU_STAT(insn_emulation) },
151         { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
152         { "irq_injections", VCPU_STAT(irq_injections) },
153         { "nmi_injections", VCPU_STAT(nmi_injections) },
154         { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
155         { "mmu_pte_write", VM_STAT(mmu_pte_write) },
156         { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
157         { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
158         { "mmu_flooded", VM_STAT(mmu_flooded) },
159         { "mmu_recycled", VM_STAT(mmu_recycled) },
160         { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
161         { "mmu_unsync", VM_STAT(mmu_unsync) },
162         { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
163         { "largepages", VM_STAT(lpages) },
164         { NULL }
165 };
166
167 u64 __read_mostly host_xcr0;
168
169 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
170
171 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
172 {
173         int i;
174         for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
175                 vcpu->arch.apf.gfns[i] = ~0;
176 }
177
178 static void kvm_on_user_return(struct user_return_notifier *urn)
179 {
180         unsigned slot;
181         struct kvm_shared_msrs *locals
182                 = container_of(urn, struct kvm_shared_msrs, urn);
183         struct kvm_shared_msr_values *values;
184
185         for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
186                 values = &locals->values[slot];
187                 if (values->host != values->curr) {
188                         wrmsrl(shared_msrs_global.msrs[slot], values->host);
189                         values->curr = values->host;
190                 }
191         }
192         locals->registered = false;
193         user_return_notifier_unregister(urn);
194 }
195
196 static void shared_msr_update(unsigned slot, u32 msr)
197 {
198         u64 value;
199         unsigned int cpu = smp_processor_id();
200         struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
201
202         /* only read, and nobody should modify it at this time,
203          * so don't need lock */
204         if (slot >= shared_msrs_global.nr) {
205                 printk(KERN_ERR "kvm: invalid MSR slot!");
206                 return;
207         }
208         rdmsrl_safe(msr, &value);
209         smsr->values[slot].host = value;
210         smsr->values[slot].curr = value;
211 }
212
213 void kvm_define_shared_msr(unsigned slot, u32 msr)
214 {
215         BUG_ON(slot >= KVM_NR_SHARED_MSRS);
216         if (slot >= shared_msrs_global.nr)
217                 shared_msrs_global.nr = slot + 1;
218         shared_msrs_global.msrs[slot] = msr;
219         /* we need ensured the shared_msr_global have been updated */
220         smp_wmb();
221 }
222 EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
223
224 static void kvm_shared_msr_cpu_online(void)
225 {
226         unsigned i;
227
228         for (i = 0; i < shared_msrs_global.nr; ++i)
229                 shared_msr_update(i, shared_msrs_global.msrs[i]);
230 }
231
232 void kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
233 {
234         unsigned int cpu = smp_processor_id();
235         struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
236
237         if (((value ^ smsr->values[slot].curr) & mask) == 0)
238                 return;
239         smsr->values[slot].curr = value;
240         wrmsrl(shared_msrs_global.msrs[slot], value);
241         if (!smsr->registered) {
242                 smsr->urn.on_user_return = kvm_on_user_return;
243                 user_return_notifier_register(&smsr->urn);
244                 smsr->registered = true;
245         }
246 }
247 EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
248
249 static void drop_user_return_notifiers(void *ignore)
250 {
251         unsigned int cpu = smp_processor_id();
252         struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
253
254         if (smsr->registered)
255                 kvm_on_user_return(&smsr->urn);
256 }
257
258 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
259 {
260         return vcpu->arch.apic_base;
261 }
262 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
263
264 int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
265 {
266         u64 old_state = vcpu->arch.apic_base &
267                 (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE);
268         u64 new_state = msr_info->data &
269                 (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE);
270         u64 reserved_bits = ((~0ULL) << cpuid_maxphyaddr(vcpu)) |
271                 0x2ff | (guest_cpuid_has_x2apic(vcpu) ? 0 : X2APIC_ENABLE);
272
273         if (!msr_info->host_initiated &&
274             ((msr_info->data & reserved_bits) != 0 ||
275              new_state == X2APIC_ENABLE ||
276              (new_state == MSR_IA32_APICBASE_ENABLE &&
277               old_state == (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE)) ||
278              (new_state == (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE) &&
279               old_state == 0)))
280                 return 1;
281
282         kvm_lapic_set_base(vcpu, msr_info->data);
283         return 0;
284 }
285 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
286
287 asmlinkage __visible void kvm_spurious_fault(void)
288 {
289         /* Fault while not rebooting.  We want the trace. */
290         BUG();
291 }
292 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
293
294 #define EXCPT_BENIGN            0
295 #define EXCPT_CONTRIBUTORY      1
296 #define EXCPT_PF                2
297
298 static int exception_class(int vector)
299 {
300         switch (vector) {
301         case PF_VECTOR:
302                 return EXCPT_PF;
303         case DE_VECTOR:
304         case TS_VECTOR:
305         case NP_VECTOR:
306         case SS_VECTOR:
307         case GP_VECTOR:
308                 return EXCPT_CONTRIBUTORY;
309         default:
310                 break;
311         }
312         return EXCPT_BENIGN;
313 }
314
315 #define EXCPT_FAULT             0
316 #define EXCPT_TRAP              1
317 #define EXCPT_ABORT             2
318 #define EXCPT_INTERRUPT         3
319
320 static int exception_type(int vector)
321 {
322         unsigned int mask;
323
324         if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
325                 return EXCPT_INTERRUPT;
326
327         mask = 1 << vector;
328
329         /* #DB is trap, as instruction watchpoints are handled elsewhere */
330         if (mask & ((1 << DB_VECTOR) | (1 << BP_VECTOR) | (1 << OF_VECTOR)))
331                 return EXCPT_TRAP;
332
333         if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
334                 return EXCPT_ABORT;
335
336         /* Reserved exceptions will result in fault */
337         return EXCPT_FAULT;
338 }
339
340 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
341                 unsigned nr, bool has_error, u32 error_code,
342                 bool reinject)
343 {
344         u32 prev_nr;
345         int class1, class2;
346
347         kvm_make_request(KVM_REQ_EVENT, vcpu);
348
349         if (!vcpu->arch.exception.pending) {
350         queue:
351                 vcpu->arch.exception.pending = true;
352                 vcpu->arch.exception.has_error_code = has_error;
353                 vcpu->arch.exception.nr = nr;
354                 vcpu->arch.exception.error_code = error_code;
355                 vcpu->arch.exception.reinject = reinject;
356                 return;
357         }
358
359         /* to check exception */
360         prev_nr = vcpu->arch.exception.nr;
361         if (prev_nr == DF_VECTOR) {
362                 /* triple fault -> shutdown */
363                 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
364                 return;
365         }
366         class1 = exception_class(prev_nr);
367         class2 = exception_class(nr);
368         if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
369                 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
370                 /* generate double fault per SDM Table 5-5 */
371                 vcpu->arch.exception.pending = true;
372                 vcpu->arch.exception.has_error_code = true;
373                 vcpu->arch.exception.nr = DF_VECTOR;
374                 vcpu->arch.exception.error_code = 0;
375         } else
376                 /* replace previous exception with a new one in a hope
377                    that instruction re-execution will regenerate lost
378                    exception */
379                 goto queue;
380 }
381
382 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
383 {
384         kvm_multiple_exception(vcpu, nr, false, 0, false);
385 }
386 EXPORT_SYMBOL_GPL(kvm_queue_exception);
387
388 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
389 {
390         kvm_multiple_exception(vcpu, nr, false, 0, true);
391 }
392 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
393
394 void kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
395 {
396         if (err)
397                 kvm_inject_gp(vcpu, 0);
398         else
399                 kvm_x86_ops->skip_emulated_instruction(vcpu);
400 }
401 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
402
403 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
404 {
405         ++vcpu->stat.pf_guest;
406         vcpu->arch.cr2 = fault->address;
407         kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
408 }
409 EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
410
411 void kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
412 {
413         if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
414                 vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
415         else
416                 vcpu->arch.mmu.inject_page_fault(vcpu, fault);
417 }
418
419 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
420 {
421         atomic_inc(&vcpu->arch.nmi_queued);
422         kvm_make_request(KVM_REQ_NMI, vcpu);
423 }
424 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
425
426 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
427 {
428         kvm_multiple_exception(vcpu, nr, true, error_code, false);
429 }
430 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
431
432 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
433 {
434         kvm_multiple_exception(vcpu, nr, true, error_code, true);
435 }
436 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
437
438 /*
439  * Checks if cpl <= required_cpl; if true, return true.  Otherwise queue
440  * a #GP and return false.
441  */
442 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
443 {
444         if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
445                 return true;
446         kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
447         return false;
448 }
449 EXPORT_SYMBOL_GPL(kvm_require_cpl);
450
451 /*
452  * This function will be used to read from the physical memory of the currently
453  * running guest. The difference to kvm_read_guest_page is that this function
454  * can read from guest physical or from the guest's guest physical memory.
455  */
456 int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
457                             gfn_t ngfn, void *data, int offset, int len,
458                             u32 access)
459 {
460         gfn_t real_gfn;
461         gpa_t ngpa;
462
463         ngpa     = gfn_to_gpa(ngfn);
464         real_gfn = mmu->translate_gpa(vcpu, ngpa, access);
465         if (real_gfn == UNMAPPED_GVA)
466                 return -EFAULT;
467
468         real_gfn = gpa_to_gfn(real_gfn);
469
470         return kvm_read_guest_page(vcpu->kvm, real_gfn, data, offset, len);
471 }
472 EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
473
474 int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
475                                void *data, int offset, int len, u32 access)
476 {
477         return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
478                                        data, offset, len, access);
479 }
480
481 /*
482  * Load the pae pdptrs.  Return true is they are all valid.
483  */
484 int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
485 {
486         gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
487         unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
488         int i;
489         int ret;
490         u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
491
492         ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
493                                       offset * sizeof(u64), sizeof(pdpte),
494                                       PFERR_USER_MASK|PFERR_WRITE_MASK);
495         if (ret < 0) {
496                 ret = 0;
497                 goto out;
498         }
499         for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
500                 if (is_present_gpte(pdpte[i]) &&
501                     (pdpte[i] & vcpu->arch.mmu.rsvd_bits_mask[0][2])) {
502                         ret = 0;
503                         goto out;
504                 }
505         }
506         ret = 1;
507
508         memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
509         __set_bit(VCPU_EXREG_PDPTR,
510                   (unsigned long *)&vcpu->arch.regs_avail);
511         __set_bit(VCPU_EXREG_PDPTR,
512                   (unsigned long *)&vcpu->arch.regs_dirty);
513 out:
514
515         return ret;
516 }
517 EXPORT_SYMBOL_GPL(load_pdptrs);
518
519 static bool pdptrs_changed(struct kvm_vcpu *vcpu)
520 {
521         u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
522         bool changed = true;
523         int offset;
524         gfn_t gfn;
525         int r;
526
527         if (is_long_mode(vcpu) || !is_pae(vcpu))
528                 return false;
529
530         if (!test_bit(VCPU_EXREG_PDPTR,
531                       (unsigned long *)&vcpu->arch.regs_avail))
532                 return true;
533
534         gfn = (kvm_read_cr3(vcpu) & ~31u) >> PAGE_SHIFT;
535         offset = (kvm_read_cr3(vcpu) & ~31u) & (PAGE_SIZE - 1);
536         r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
537                                        PFERR_USER_MASK | PFERR_WRITE_MASK);
538         if (r < 0)
539                 goto out;
540         changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
541 out:
542
543         return changed;
544 }
545
546 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
547 {
548         unsigned long old_cr0 = kvm_read_cr0(vcpu);
549         unsigned long update_bits = X86_CR0_PG | X86_CR0_WP |
550                                     X86_CR0_CD | X86_CR0_NW;
551
552         cr0 |= X86_CR0_ET;
553
554 #ifdef CONFIG_X86_64
555         if (cr0 & 0xffffffff00000000UL)
556                 return 1;
557 #endif
558
559         cr0 &= ~CR0_RESERVED_BITS;
560
561         if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
562                 return 1;
563
564         if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
565                 return 1;
566
567         if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
568 #ifdef CONFIG_X86_64
569                 if ((vcpu->arch.efer & EFER_LME)) {
570                         int cs_db, cs_l;
571
572                         if (!is_pae(vcpu))
573                                 return 1;
574                         kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
575                         if (cs_l)
576                                 return 1;
577                 } else
578 #endif
579                 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
580                                                  kvm_read_cr3(vcpu)))
581                         return 1;
582         }
583
584         if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
585                 return 1;
586
587         kvm_x86_ops->set_cr0(vcpu, cr0);
588
589         if ((cr0 ^ old_cr0) & X86_CR0_PG) {
590                 kvm_clear_async_pf_completion_queue(vcpu);
591                 kvm_async_pf_hash_reset(vcpu);
592         }
593
594         if ((cr0 ^ old_cr0) & update_bits)
595                 kvm_mmu_reset_context(vcpu);
596         return 0;
597 }
598 EXPORT_SYMBOL_GPL(kvm_set_cr0);
599
600 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
601 {
602         (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
603 }
604 EXPORT_SYMBOL_GPL(kvm_lmsw);
605
606 static void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
607 {
608         if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
609                         !vcpu->guest_xcr0_loaded) {
610                 /* kvm_set_xcr() also depends on this */
611                 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
612                 vcpu->guest_xcr0_loaded = 1;
613         }
614 }
615
616 static void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
617 {
618         if (vcpu->guest_xcr0_loaded) {
619                 if (vcpu->arch.xcr0 != host_xcr0)
620                         xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
621                 vcpu->guest_xcr0_loaded = 0;
622         }
623 }
624
625 int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
626 {
627         u64 xcr0 = xcr;
628         u64 old_xcr0 = vcpu->arch.xcr0;
629         u64 valid_bits;
630
631         /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now  */
632         if (index != XCR_XFEATURE_ENABLED_MASK)
633                 return 1;
634         if (!(xcr0 & XSTATE_FP))
635                 return 1;
636         if ((xcr0 & XSTATE_YMM) && !(xcr0 & XSTATE_SSE))
637                 return 1;
638
639         /*
640          * Do not allow the guest to set bits that we do not support
641          * saving.  However, xcr0 bit 0 is always set, even if the
642          * emulated CPU does not support XSAVE (see fx_init).
643          */
644         valid_bits = vcpu->arch.guest_supported_xcr0 | XSTATE_FP;
645         if (xcr0 & ~valid_bits)
646                 return 1;
647
648         if ((!(xcr0 & XSTATE_BNDREGS)) != (!(xcr0 & XSTATE_BNDCSR)))
649                 return 1;
650
651         kvm_put_guest_xcr0(vcpu);
652         vcpu->arch.xcr0 = xcr0;
653
654         if ((xcr0 ^ old_xcr0) & XSTATE_EXTEND_MASK)
655                 kvm_update_cpuid(vcpu);
656         return 0;
657 }
658
659 int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
660 {
661         if (kvm_x86_ops->get_cpl(vcpu) != 0 ||
662             __kvm_set_xcr(vcpu, index, xcr)) {
663                 kvm_inject_gp(vcpu, 0);
664                 return 1;
665         }
666         return 0;
667 }
668 EXPORT_SYMBOL_GPL(kvm_set_xcr);
669
670 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
671 {
672         unsigned long old_cr4 = kvm_read_cr4(vcpu);
673         unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE |
674                                    X86_CR4_PAE | X86_CR4_SMEP;
675         if (cr4 & CR4_RESERVED_BITS)
676                 return 1;
677
678         if (!guest_cpuid_has_xsave(vcpu) && (cr4 & X86_CR4_OSXSAVE))
679                 return 1;
680
681         if (!guest_cpuid_has_smep(vcpu) && (cr4 & X86_CR4_SMEP))
682                 return 1;
683
684         if (!guest_cpuid_has_smap(vcpu) && (cr4 & X86_CR4_SMAP))
685                 return 1;
686
687         if (!guest_cpuid_has_fsgsbase(vcpu) && (cr4 & X86_CR4_FSGSBASE))
688                 return 1;
689
690         if (is_long_mode(vcpu)) {
691                 if (!(cr4 & X86_CR4_PAE))
692                         return 1;
693         } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
694                    && ((cr4 ^ old_cr4) & pdptr_bits)
695                    && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
696                                    kvm_read_cr3(vcpu)))
697                 return 1;
698
699         if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
700                 if (!guest_cpuid_has_pcid(vcpu))
701                         return 1;
702
703                 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
704                 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
705                         return 1;
706         }
707
708         if (kvm_x86_ops->set_cr4(vcpu, cr4))
709                 return 1;
710
711         if (((cr4 ^ old_cr4) & pdptr_bits) ||
712             (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
713                 kvm_mmu_reset_context(vcpu);
714
715         if ((cr4 ^ old_cr4) & X86_CR4_SMAP)
716                 update_permission_bitmask(vcpu, vcpu->arch.walk_mmu, false);
717
718         if ((cr4 ^ old_cr4) & X86_CR4_OSXSAVE)
719                 kvm_update_cpuid(vcpu);
720
721         return 0;
722 }
723 EXPORT_SYMBOL_GPL(kvm_set_cr4);
724
725 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
726 {
727         if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
728                 kvm_mmu_sync_roots(vcpu);
729                 kvm_mmu_flush_tlb(vcpu);
730                 return 0;
731         }
732
733         if (is_long_mode(vcpu)) {
734                 if (cr3 & CR3_L_MODE_RESERVED_BITS)
735                         return 1;
736         } else if (is_pae(vcpu) && is_paging(vcpu) &&
737                    !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
738                 return 1;
739
740         vcpu->arch.cr3 = cr3;
741         __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
742         kvm_mmu_new_cr3(vcpu);
743         return 0;
744 }
745 EXPORT_SYMBOL_GPL(kvm_set_cr3);
746
747 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
748 {
749         if (cr8 & CR8_RESERVED_BITS)
750                 return 1;
751         if (irqchip_in_kernel(vcpu->kvm))
752                 kvm_lapic_set_tpr(vcpu, cr8);
753         else
754                 vcpu->arch.cr8 = cr8;
755         return 0;
756 }
757 EXPORT_SYMBOL_GPL(kvm_set_cr8);
758
759 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
760 {
761         if (irqchip_in_kernel(vcpu->kvm))
762                 return kvm_lapic_get_cr8(vcpu);
763         else
764                 return vcpu->arch.cr8;
765 }
766 EXPORT_SYMBOL_GPL(kvm_get_cr8);
767
768 static void kvm_update_dr6(struct kvm_vcpu *vcpu)
769 {
770         if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
771                 kvm_x86_ops->set_dr6(vcpu, vcpu->arch.dr6);
772 }
773
774 static void kvm_update_dr7(struct kvm_vcpu *vcpu)
775 {
776         unsigned long dr7;
777
778         if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
779                 dr7 = vcpu->arch.guest_debug_dr7;
780         else
781                 dr7 = vcpu->arch.dr7;
782         kvm_x86_ops->set_dr7(vcpu, dr7);
783         vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
784         if (dr7 & DR7_BP_EN_MASK)
785                 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
786 }
787
788 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
789 {
790         u64 fixed = DR6_FIXED_1;
791
792         if (!guest_cpuid_has_rtm(vcpu))
793                 fixed |= DR6_RTM;
794         return fixed;
795 }
796
797 static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
798 {
799         switch (dr) {
800         case 0 ... 3:
801                 vcpu->arch.db[dr] = val;
802                 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
803                         vcpu->arch.eff_db[dr] = val;
804                 break;
805         case 4:
806                 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
807                         return 1; /* #UD */
808                 /* fall through */
809         case 6:
810                 if (val & 0xffffffff00000000ULL)
811                         return -1; /* #GP */
812                 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
813                 kvm_update_dr6(vcpu);
814                 break;
815         case 5:
816                 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
817                         return 1; /* #UD */
818                 /* fall through */
819         default: /* 7 */
820                 if (val & 0xffffffff00000000ULL)
821                         return -1; /* #GP */
822                 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
823                 kvm_update_dr7(vcpu);
824                 break;
825         }
826
827         return 0;
828 }
829
830 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
831 {
832         int res;
833
834         res = __kvm_set_dr(vcpu, dr, val);
835         if (res > 0)
836                 kvm_queue_exception(vcpu, UD_VECTOR);
837         else if (res < 0)
838                 kvm_inject_gp(vcpu, 0);
839
840         return res;
841 }
842 EXPORT_SYMBOL_GPL(kvm_set_dr);
843
844 static int _kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
845 {
846         switch (dr) {
847         case 0 ... 3:
848                 *val = vcpu->arch.db[dr];
849                 break;
850         case 4:
851                 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
852                         return 1;
853                 /* fall through */
854         case 6:
855                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
856                         *val = vcpu->arch.dr6;
857                 else
858                         *val = kvm_x86_ops->get_dr6(vcpu);
859                 break;
860         case 5:
861                 if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
862                         return 1;
863                 /* fall through */
864         default: /* 7 */
865                 *val = vcpu->arch.dr7;
866                 break;
867         }
868
869         return 0;
870 }
871
872 int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
873 {
874         if (_kvm_get_dr(vcpu, dr, val)) {
875                 kvm_queue_exception(vcpu, UD_VECTOR);
876                 return 1;
877         }
878         return 0;
879 }
880 EXPORT_SYMBOL_GPL(kvm_get_dr);
881
882 bool kvm_rdpmc(struct kvm_vcpu *vcpu)
883 {
884         u32 ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
885         u64 data;
886         int err;
887
888         err = kvm_pmu_read_pmc(vcpu, ecx, &data);
889         if (err)
890                 return err;
891         kvm_register_write(vcpu, VCPU_REGS_RAX, (u32)data);
892         kvm_register_write(vcpu, VCPU_REGS_RDX, data >> 32);
893         return err;
894 }
895 EXPORT_SYMBOL_GPL(kvm_rdpmc);
896
897 /*
898  * List of msr numbers which we expose to userspace through KVM_GET_MSRS
899  * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
900  *
901  * This list is modified at module load time to reflect the
902  * capabilities of the host cpu. This capabilities test skips MSRs that are
903  * kvm-specific. Those are put in the beginning of the list.
904  */
905
906 #define KVM_SAVE_MSRS_BEGIN     12
907 static u32 msrs_to_save[] = {
908         MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
909         MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
910         HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
911         HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
912         HV_X64_MSR_APIC_ASSIST_PAGE, MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
913         MSR_KVM_PV_EOI_EN,
914         MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
915         MSR_STAR,
916 #ifdef CONFIG_X86_64
917         MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
918 #endif
919         MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
920         MSR_IA32_FEATURE_CONTROL, MSR_IA32_BNDCFGS
921 };
922
923 static unsigned num_msrs_to_save;
924
925 static const u32 emulated_msrs[] = {
926         MSR_IA32_TSC_ADJUST,
927         MSR_IA32_TSCDEADLINE,
928         MSR_IA32_MISC_ENABLE,
929         MSR_IA32_MCG_STATUS,
930         MSR_IA32_MCG_CTL,
931 };
932
933 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
934 {
935         if (efer & efer_reserved_bits)
936                 return false;
937
938         if (efer & EFER_FFXSR) {
939                 struct kvm_cpuid_entry2 *feat;
940
941                 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
942                 if (!feat || !(feat->edx & bit(X86_FEATURE_FXSR_OPT)))
943                         return false;
944         }
945
946         if (efer & EFER_SVME) {
947                 struct kvm_cpuid_entry2 *feat;
948
949                 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
950                 if (!feat || !(feat->ecx & bit(X86_FEATURE_SVM)))
951                         return false;
952         }
953
954         return true;
955 }
956 EXPORT_SYMBOL_GPL(kvm_valid_efer);
957
958 static int set_efer(struct kvm_vcpu *vcpu, u64 efer)
959 {
960         u64 old_efer = vcpu->arch.efer;
961
962         if (!kvm_valid_efer(vcpu, efer))
963                 return 1;
964
965         if (is_paging(vcpu)
966             && (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
967                 return 1;
968
969         efer &= ~EFER_LMA;
970         efer |= vcpu->arch.efer & EFER_LMA;
971
972         kvm_x86_ops->set_efer(vcpu, efer);
973
974         /* Update reserved bits */
975         if ((efer ^ old_efer) & EFER_NX)
976                 kvm_mmu_reset_context(vcpu);
977
978         return 0;
979 }
980
981 void kvm_enable_efer_bits(u64 mask)
982 {
983        efer_reserved_bits &= ~mask;
984 }
985 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
986
987
988 /*
989  * Writes msr value into into the appropriate "register".
990  * Returns 0 on success, non-0 otherwise.
991  * Assumes vcpu_load() was already called.
992  */
993 int kvm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
994 {
995         return kvm_x86_ops->set_msr(vcpu, msr);
996 }
997
998 /*
999  * Adapt set_msr() to msr_io()'s calling convention
1000  */
1001 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1002 {
1003         struct msr_data msr;
1004
1005         msr.data = *data;
1006         msr.index = index;
1007         msr.host_initiated = true;
1008         return kvm_set_msr(vcpu, &msr);
1009 }
1010
1011 #ifdef CONFIG_X86_64
1012 struct pvclock_gtod_data {
1013         seqcount_t      seq;
1014
1015         struct { /* extract of a clocksource struct */
1016                 int vclock_mode;
1017                 cycle_t cycle_last;
1018                 cycle_t mask;
1019                 u32     mult;
1020                 u32     shift;
1021         } clock;
1022
1023         u64             boot_ns;
1024         u64             nsec_base;
1025 };
1026
1027 static struct pvclock_gtod_data pvclock_gtod_data;
1028
1029 static void update_pvclock_gtod(struct timekeeper *tk)
1030 {
1031         struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
1032         u64 boot_ns;
1033
1034         boot_ns = ktime_to_ns(ktime_add(tk->tkr.base_mono, tk->offs_boot));
1035
1036         write_seqcount_begin(&vdata->seq);
1037
1038         /* copy pvclock gtod data */
1039         vdata->clock.vclock_mode        = tk->tkr.clock->archdata.vclock_mode;
1040         vdata->clock.cycle_last         = tk->tkr.cycle_last;
1041         vdata->clock.mask               = tk->tkr.mask;
1042         vdata->clock.mult               = tk->tkr.mult;
1043         vdata->clock.shift              = tk->tkr.shift;
1044
1045         vdata->boot_ns                  = boot_ns;
1046         vdata->nsec_base                = tk->tkr.xtime_nsec;
1047
1048         write_seqcount_end(&vdata->seq);
1049 }
1050 #endif
1051
1052
1053 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
1054 {
1055         int version;
1056         int r;
1057         struct pvclock_wall_clock wc;
1058         struct timespec boot;
1059
1060         if (!wall_clock)
1061                 return;
1062
1063         r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
1064         if (r)
1065                 return;
1066
1067         if (version & 1)
1068                 ++version;  /* first time write, random junk */
1069
1070         ++version;
1071
1072         kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1073
1074         /*
1075          * The guest calculates current wall clock time by adding
1076          * system time (updated by kvm_guest_time_update below) to the
1077          * wall clock specified here.  guest system time equals host
1078          * system time for us, thus we must fill in host boot time here.
1079          */
1080         getboottime(&boot);
1081
1082         if (kvm->arch.kvmclock_offset) {
1083                 struct timespec ts = ns_to_timespec(kvm->arch.kvmclock_offset);
1084                 boot = timespec_sub(boot, ts);
1085         }
1086         wc.sec = boot.tv_sec;
1087         wc.nsec = boot.tv_nsec;
1088         wc.version = version;
1089
1090         kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
1091
1092         version++;
1093         kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1094 }
1095
1096 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
1097 {
1098         uint32_t quotient, remainder;
1099
1100         /* Don't try to replace with do_div(), this one calculates
1101          * "(dividend << 32) / divisor" */
1102         __asm__ ( "divl %4"
1103                   : "=a" (quotient), "=d" (remainder)
1104                   : "0" (0), "1" (dividend), "r" (divisor) );
1105         return quotient;
1106 }
1107
1108 static void kvm_get_time_scale(uint32_t scaled_khz, uint32_t base_khz,
1109                                s8 *pshift, u32 *pmultiplier)
1110 {
1111         uint64_t scaled64;
1112         int32_t  shift = 0;
1113         uint64_t tps64;
1114         uint32_t tps32;
1115
1116         tps64 = base_khz * 1000LL;
1117         scaled64 = scaled_khz * 1000LL;
1118         while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
1119                 tps64 >>= 1;
1120                 shift--;
1121         }
1122
1123         tps32 = (uint32_t)tps64;
1124         while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
1125                 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
1126                         scaled64 >>= 1;
1127                 else
1128                         tps32 <<= 1;
1129                 shift++;
1130         }
1131
1132         *pshift = shift;
1133         *pmultiplier = div_frac(scaled64, tps32);
1134
1135         pr_debug("%s: base_khz %u => %u, shift %d, mul %u\n",
1136                  __func__, base_khz, scaled_khz, shift, *pmultiplier);
1137 }
1138
1139 static inline u64 get_kernel_ns(void)
1140 {
1141         return ktime_get_boot_ns();
1142 }
1143
1144 #ifdef CONFIG_X86_64
1145 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
1146 #endif
1147
1148 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
1149 unsigned long max_tsc_khz;
1150
1151 static inline u64 nsec_to_cycles(struct kvm_vcpu *vcpu, u64 nsec)
1152 {
1153         return pvclock_scale_delta(nsec, vcpu->arch.virtual_tsc_mult,
1154                                    vcpu->arch.virtual_tsc_shift);
1155 }
1156
1157 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
1158 {
1159         u64 v = (u64)khz * (1000000 + ppm);
1160         do_div(v, 1000000);
1161         return v;
1162 }
1163
1164 static void kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 this_tsc_khz)
1165 {
1166         u32 thresh_lo, thresh_hi;
1167         int use_scaling = 0;
1168
1169         /* tsc_khz can be zero if TSC calibration fails */
1170         if (this_tsc_khz == 0)
1171                 return;
1172
1173         /* Compute a scale to convert nanoseconds in TSC cycles */
1174         kvm_get_time_scale(this_tsc_khz, NSEC_PER_SEC / 1000,
1175                            &vcpu->arch.virtual_tsc_shift,
1176                            &vcpu->arch.virtual_tsc_mult);
1177         vcpu->arch.virtual_tsc_khz = this_tsc_khz;
1178
1179         /*
1180          * Compute the variation in TSC rate which is acceptable
1181          * within the range of tolerance and decide if the
1182          * rate being applied is within that bounds of the hardware
1183          * rate.  If so, no scaling or compensation need be done.
1184          */
1185         thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
1186         thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
1187         if (this_tsc_khz < thresh_lo || this_tsc_khz > thresh_hi) {
1188                 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", this_tsc_khz, thresh_lo, thresh_hi);
1189                 use_scaling = 1;
1190         }
1191         kvm_x86_ops->set_tsc_khz(vcpu, this_tsc_khz, use_scaling);
1192 }
1193
1194 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1195 {
1196         u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
1197                                       vcpu->arch.virtual_tsc_mult,
1198                                       vcpu->arch.virtual_tsc_shift);
1199         tsc += vcpu->arch.this_tsc_write;
1200         return tsc;
1201 }
1202
1203 void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
1204 {
1205 #ifdef CONFIG_X86_64
1206         bool vcpus_matched;
1207         bool do_request = false;
1208         struct kvm_arch *ka = &vcpu->kvm->arch;
1209         struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1210
1211         vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1212                          atomic_read(&vcpu->kvm->online_vcpus));
1213
1214         if (vcpus_matched && gtod->clock.vclock_mode == VCLOCK_TSC)
1215                 if (!ka->use_master_clock)
1216                         do_request = 1;
1217
1218         if (!vcpus_matched && ka->use_master_clock)
1219                         do_request = 1;
1220
1221         if (do_request)
1222                 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
1223
1224         trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
1225                             atomic_read(&vcpu->kvm->online_vcpus),
1226                             ka->use_master_clock, gtod->clock.vclock_mode);
1227 #endif
1228 }
1229
1230 static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
1231 {
1232         u64 curr_offset = kvm_x86_ops->read_tsc_offset(vcpu);
1233         vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
1234 }
1235
1236 void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
1237 {
1238         struct kvm *kvm = vcpu->kvm;
1239         u64 offset, ns, elapsed;
1240         unsigned long flags;
1241         s64 usdiff;
1242         bool matched;
1243         bool already_matched;
1244         u64 data = msr->data;
1245
1246         raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
1247         offset = kvm_x86_ops->compute_tsc_offset(vcpu, data);
1248         ns = get_kernel_ns();
1249         elapsed = ns - kvm->arch.last_tsc_nsec;
1250
1251         if (vcpu->arch.virtual_tsc_khz) {
1252                 int faulted = 0;
1253
1254                 /* n.b - signed multiplication and division required */
1255                 usdiff = data - kvm->arch.last_tsc_write;
1256 #ifdef CONFIG_X86_64
1257                 usdiff = (usdiff * 1000) / vcpu->arch.virtual_tsc_khz;
1258 #else
1259                 /* do_div() only does unsigned */
1260                 asm("1: idivl %[divisor]\n"
1261                     "2: xor %%edx, %%edx\n"
1262                     "   movl $0, %[faulted]\n"
1263                     "3:\n"
1264                     ".section .fixup,\"ax\"\n"
1265                     "4: movl $1, %[faulted]\n"
1266                     "   jmp  3b\n"
1267                     ".previous\n"
1268
1269                 _ASM_EXTABLE(1b, 4b)
1270
1271                 : "=A"(usdiff), [faulted] "=r" (faulted)
1272                 : "A"(usdiff * 1000), [divisor] "rm"(vcpu->arch.virtual_tsc_khz));
1273
1274 #endif
1275                 do_div(elapsed, 1000);
1276                 usdiff -= elapsed;
1277                 if (usdiff < 0)
1278                         usdiff = -usdiff;
1279
1280                 /* idivl overflow => difference is larger than USEC_PER_SEC */
1281                 if (faulted)
1282                         usdiff = USEC_PER_SEC;
1283         } else
1284                 usdiff = USEC_PER_SEC; /* disable TSC match window below */
1285
1286         /*
1287          * Special case: TSC write with a small delta (1 second) of virtual
1288          * cycle time against real time is interpreted as an attempt to
1289          * synchronize the CPU.
1290          *
1291          * For a reliable TSC, we can match TSC offsets, and for an unstable
1292          * TSC, we add elapsed time in this computation.  We could let the
1293          * compensation code attempt to catch up if we fall behind, but
1294          * it's better to try to match offsets from the beginning.
1295          */
1296         if (usdiff < USEC_PER_SEC &&
1297             vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
1298                 if (!check_tsc_unstable()) {
1299                         offset = kvm->arch.cur_tsc_offset;
1300                         pr_debug("kvm: matched tsc offset for %llu\n", data);
1301                 } else {
1302                         u64 delta = nsec_to_cycles(vcpu, elapsed);
1303                         data += delta;
1304                         offset = kvm_x86_ops->compute_tsc_offset(vcpu, data);
1305                         pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
1306                 }
1307                 matched = true;
1308                 already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation);
1309         } else {
1310                 /*
1311                  * We split periods of matched TSC writes into generations.
1312                  * For each generation, we track the original measured
1313                  * nanosecond time, offset, and write, so if TSCs are in
1314                  * sync, we can match exact offset, and if not, we can match
1315                  * exact software computation in compute_guest_tsc()
1316                  *
1317                  * These values are tracked in kvm->arch.cur_xxx variables.
1318                  */
1319                 kvm->arch.cur_tsc_generation++;
1320                 kvm->arch.cur_tsc_nsec = ns;
1321                 kvm->arch.cur_tsc_write = data;
1322                 kvm->arch.cur_tsc_offset = offset;
1323                 matched = false;
1324                 pr_debug("kvm: new tsc generation %llu, clock %llu\n",
1325                          kvm->arch.cur_tsc_generation, data);
1326         }
1327
1328         /*
1329          * We also track th most recent recorded KHZ, write and time to
1330          * allow the matching interval to be extended at each write.
1331          */
1332         kvm->arch.last_tsc_nsec = ns;
1333         kvm->arch.last_tsc_write = data;
1334         kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
1335
1336         vcpu->arch.last_guest_tsc = data;
1337
1338         /* Keep track of which generation this VCPU has synchronized to */
1339         vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
1340         vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
1341         vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
1342
1343         if (guest_cpuid_has_tsc_adjust(vcpu) && !msr->host_initiated)
1344                 update_ia32_tsc_adjust_msr(vcpu, offset);
1345         kvm_x86_ops->write_tsc_offset(vcpu, offset);
1346         raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
1347
1348         spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
1349         if (!matched) {
1350                 kvm->arch.nr_vcpus_matched_tsc = 0;
1351         } else if (!already_matched) {
1352                 kvm->arch.nr_vcpus_matched_tsc++;
1353         }
1354
1355         kvm_track_tsc_matching(vcpu);
1356         spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
1357 }
1358
1359 EXPORT_SYMBOL_GPL(kvm_write_tsc);
1360
1361 #ifdef CONFIG_X86_64
1362
1363 static cycle_t read_tsc(void)
1364 {
1365         cycle_t ret;
1366         u64 last;
1367
1368         /*
1369          * Empirically, a fence (of type that depends on the CPU)
1370          * before rdtsc is enough to ensure that rdtsc is ordered
1371          * with respect to loads.  The various CPU manuals are unclear
1372          * as to whether rdtsc can be reordered with later loads,
1373          * but no one has ever seen it happen.
1374          */
1375         rdtsc_barrier();
1376         ret = (cycle_t)vget_cycles();
1377
1378         last = pvclock_gtod_data.clock.cycle_last;
1379
1380         if (likely(ret >= last))
1381                 return ret;
1382
1383         /*
1384          * GCC likes to generate cmov here, but this branch is extremely
1385          * predictable (it's just a funciton of time and the likely is
1386          * very likely) and there's a data dependence, so force GCC
1387          * to generate a branch instead.  I don't barrier() because
1388          * we don't actually need a barrier, and if this function
1389          * ever gets inlined it will generate worse code.
1390          */
1391         asm volatile ("");
1392         return last;
1393 }
1394
1395 static inline u64 vgettsc(cycle_t *cycle_now)
1396 {
1397         long v;
1398         struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1399
1400         *cycle_now = read_tsc();
1401
1402         v = (*cycle_now - gtod->clock.cycle_last) & gtod->clock.mask;
1403         return v * gtod->clock.mult;
1404 }
1405
1406 static int do_monotonic_boot(s64 *t, cycle_t *cycle_now)
1407 {
1408         struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1409         unsigned long seq;
1410         int mode;
1411         u64 ns;
1412
1413         do {
1414                 seq = read_seqcount_begin(&gtod->seq);
1415                 mode = gtod->clock.vclock_mode;
1416                 ns = gtod->nsec_base;
1417                 ns += vgettsc(cycle_now);
1418                 ns >>= gtod->clock.shift;
1419                 ns += gtod->boot_ns;
1420         } while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
1421         *t = ns;
1422
1423         return mode;
1424 }
1425
1426 /* returns true if host is using tsc clocksource */
1427 static bool kvm_get_time_and_clockread(s64 *kernel_ns, cycle_t *cycle_now)
1428 {
1429         /* checked again under seqlock below */
1430         if (pvclock_gtod_data.clock.vclock_mode != VCLOCK_TSC)
1431                 return false;
1432
1433         return do_monotonic_boot(kernel_ns, cycle_now) == VCLOCK_TSC;
1434 }
1435 #endif
1436
1437 /*
1438  *
1439  * Assuming a stable TSC across physical CPUS, and a stable TSC
1440  * across virtual CPUs, the following condition is possible.
1441  * Each numbered line represents an event visible to both
1442  * CPUs at the next numbered event.
1443  *
1444  * "timespecX" represents host monotonic time. "tscX" represents
1445  * RDTSC value.
1446  *
1447  *              VCPU0 on CPU0           |       VCPU1 on CPU1
1448  *
1449  * 1.  read timespec0,tsc0
1450  * 2.                                   | timespec1 = timespec0 + N
1451  *                                      | tsc1 = tsc0 + M
1452  * 3. transition to guest               | transition to guest
1453  * 4. ret0 = timespec0 + (rdtsc - tsc0) |
1454  * 5.                                   | ret1 = timespec1 + (rdtsc - tsc1)
1455  *                                      | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
1456  *
1457  * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
1458  *
1459  *      - ret0 < ret1
1460  *      - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
1461  *              ...
1462  *      - 0 < N - M => M < N
1463  *
1464  * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
1465  * always the case (the difference between two distinct xtime instances
1466  * might be smaller then the difference between corresponding TSC reads,
1467  * when updating guest vcpus pvclock areas).
1468  *
1469  * To avoid that problem, do not allow visibility of distinct
1470  * system_timestamp/tsc_timestamp values simultaneously: use a master
1471  * copy of host monotonic time values. Update that master copy
1472  * in lockstep.
1473  *
1474  * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
1475  *
1476  */
1477
1478 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
1479 {
1480 #ifdef CONFIG_X86_64
1481         struct kvm_arch *ka = &kvm->arch;
1482         int vclock_mode;
1483         bool host_tsc_clocksource, vcpus_matched;
1484
1485         vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1486                         atomic_read(&kvm->online_vcpus));
1487
1488         /*
1489          * If the host uses TSC clock, then passthrough TSC as stable
1490          * to the guest.
1491          */
1492         host_tsc_clocksource = kvm_get_time_and_clockread(
1493                                         &ka->master_kernel_ns,
1494                                         &ka->master_cycle_now);
1495
1496         ka->use_master_clock = host_tsc_clocksource && vcpus_matched
1497                                 && !backwards_tsc_observed;
1498
1499         if (ka->use_master_clock)
1500                 atomic_set(&kvm_guest_has_master_clock, 1);
1501
1502         vclock_mode = pvclock_gtod_data.clock.vclock_mode;
1503         trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
1504                                         vcpus_matched);
1505 #endif
1506 }
1507
1508 static void kvm_gen_update_masterclock(struct kvm *kvm)
1509 {
1510 #ifdef CONFIG_X86_64
1511         int i;
1512         struct kvm_vcpu *vcpu;
1513         struct kvm_arch *ka = &kvm->arch;
1514
1515         spin_lock(&ka->pvclock_gtod_sync_lock);
1516         kvm_make_mclock_inprogress_request(kvm);
1517         /* no guest entries from this point */
1518         pvclock_update_vm_gtod_copy(kvm);
1519
1520         kvm_for_each_vcpu(i, vcpu, kvm)
1521                 set_bit(KVM_REQ_CLOCK_UPDATE, &vcpu->requests);
1522
1523         /* guest entries allowed */
1524         kvm_for_each_vcpu(i, vcpu, kvm)
1525                 clear_bit(KVM_REQ_MCLOCK_INPROGRESS, &vcpu->requests);
1526
1527         spin_unlock(&ka->pvclock_gtod_sync_lock);
1528 #endif
1529 }
1530
1531 static int kvm_guest_time_update(struct kvm_vcpu *v)
1532 {
1533         unsigned long flags, this_tsc_khz;
1534         struct kvm_vcpu_arch *vcpu = &v->arch;
1535         struct kvm_arch *ka = &v->kvm->arch;
1536         s64 kernel_ns;
1537         u64 tsc_timestamp, host_tsc;
1538         struct pvclock_vcpu_time_info guest_hv_clock;
1539         u8 pvclock_flags;
1540         bool use_master_clock;
1541
1542         kernel_ns = 0;
1543         host_tsc = 0;
1544
1545         /*
1546          * If the host uses TSC clock, then passthrough TSC as stable
1547          * to the guest.
1548          */
1549         spin_lock(&ka->pvclock_gtod_sync_lock);
1550         use_master_clock = ka->use_master_clock;
1551         if (use_master_clock) {
1552                 host_tsc = ka->master_cycle_now;
1553                 kernel_ns = ka->master_kernel_ns;
1554         }
1555         spin_unlock(&ka->pvclock_gtod_sync_lock);
1556
1557         /* Keep irq disabled to prevent changes to the clock */
1558         local_irq_save(flags);
1559         this_tsc_khz = __get_cpu_var(cpu_tsc_khz);
1560         if (unlikely(this_tsc_khz == 0)) {
1561                 local_irq_restore(flags);
1562                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
1563                 return 1;
1564         }
1565         if (!use_master_clock) {
1566                 host_tsc = native_read_tsc();
1567                 kernel_ns = get_kernel_ns();
1568         }
1569
1570         tsc_timestamp = kvm_x86_ops->read_l1_tsc(v, host_tsc);
1571
1572         /*
1573          * We may have to catch up the TSC to match elapsed wall clock
1574          * time for two reasons, even if kvmclock is used.
1575          *   1) CPU could have been running below the maximum TSC rate
1576          *   2) Broken TSC compensation resets the base at each VCPU
1577          *      entry to avoid unknown leaps of TSC even when running
1578          *      again on the same CPU.  This may cause apparent elapsed
1579          *      time to disappear, and the guest to stand still or run
1580          *      very slowly.
1581          */
1582         if (vcpu->tsc_catchup) {
1583                 u64 tsc = compute_guest_tsc(v, kernel_ns);
1584                 if (tsc > tsc_timestamp) {
1585                         adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
1586                         tsc_timestamp = tsc;
1587                 }
1588         }
1589
1590         local_irq_restore(flags);
1591
1592         if (!vcpu->pv_time_enabled)
1593                 return 0;
1594
1595         if (unlikely(vcpu->hw_tsc_khz != this_tsc_khz)) {
1596                 kvm_get_time_scale(NSEC_PER_SEC / 1000, this_tsc_khz,
1597                                    &vcpu->hv_clock.tsc_shift,
1598                                    &vcpu->hv_clock.tsc_to_system_mul);
1599                 vcpu->hw_tsc_khz = this_tsc_khz;
1600         }
1601
1602         /* With all the info we got, fill in the values */
1603         vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
1604         vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
1605         vcpu->last_guest_tsc = tsc_timestamp;
1606
1607         /*
1608          * The interface expects us to write an even number signaling that the
1609          * update is finished. Since the guest won't see the intermediate
1610          * state, we just increase by 2 at the end.
1611          */
1612         vcpu->hv_clock.version += 2;
1613
1614         if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
1615                 &guest_hv_clock, sizeof(guest_hv_clock))))
1616                 return 0;
1617
1618         /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
1619         pvclock_flags = (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
1620
1621         if (vcpu->pvclock_set_guest_stopped_request) {
1622                 pvclock_flags |= PVCLOCK_GUEST_STOPPED;
1623                 vcpu->pvclock_set_guest_stopped_request = false;
1624         }
1625
1626         /* If the host uses TSC clocksource, then it is stable */
1627         if (use_master_clock)
1628                 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
1629
1630         vcpu->hv_clock.flags = pvclock_flags;
1631
1632         kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1633                                 &vcpu->hv_clock,
1634                                 sizeof(vcpu->hv_clock));
1635         return 0;
1636 }
1637
1638 /*
1639  * kvmclock updates which are isolated to a given vcpu, such as
1640  * vcpu->cpu migration, should not allow system_timestamp from
1641  * the rest of the vcpus to remain static. Otherwise ntp frequency
1642  * correction applies to one vcpu's system_timestamp but not
1643  * the others.
1644  *
1645  * So in those cases, request a kvmclock update for all vcpus.
1646  * We need to rate-limit these requests though, as they can
1647  * considerably slow guests that have a large number of vcpus.
1648  * The time for a remote vcpu to update its kvmclock is bound
1649  * by the delay we use to rate-limit the updates.
1650  */
1651
1652 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
1653
1654 static void kvmclock_update_fn(struct work_struct *work)
1655 {
1656         int i;
1657         struct delayed_work *dwork = to_delayed_work(work);
1658         struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
1659                                            kvmclock_update_work);
1660         struct kvm *kvm = container_of(ka, struct kvm, arch);
1661         struct kvm_vcpu *vcpu;
1662
1663         kvm_for_each_vcpu(i, vcpu, kvm) {
1664                 set_bit(KVM_REQ_CLOCK_UPDATE, &vcpu->requests);
1665                 kvm_vcpu_kick(vcpu);
1666         }
1667 }
1668
1669 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
1670 {
1671         struct kvm *kvm = v->kvm;
1672
1673         set_bit(KVM_REQ_CLOCK_UPDATE, &v->requests);
1674         schedule_delayed_work(&kvm->arch.kvmclock_update_work,
1675                                         KVMCLOCK_UPDATE_DELAY);
1676 }
1677
1678 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
1679
1680 static void kvmclock_sync_fn(struct work_struct *work)
1681 {
1682         struct delayed_work *dwork = to_delayed_work(work);
1683         struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
1684                                            kvmclock_sync_work);
1685         struct kvm *kvm = container_of(ka, struct kvm, arch);
1686
1687         schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
1688         schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
1689                                         KVMCLOCK_SYNC_PERIOD);
1690 }
1691
1692 static bool msr_mtrr_valid(unsigned msr)
1693 {
1694         switch (msr) {
1695         case 0x200 ... 0x200 + 2 * KVM_NR_VAR_MTRR - 1:
1696         case MSR_MTRRfix64K_00000:
1697         case MSR_MTRRfix16K_80000:
1698         case MSR_MTRRfix16K_A0000:
1699         case MSR_MTRRfix4K_C0000:
1700         case MSR_MTRRfix4K_C8000:
1701         case MSR_MTRRfix4K_D0000:
1702         case MSR_MTRRfix4K_D8000:
1703         case MSR_MTRRfix4K_E0000:
1704         case MSR_MTRRfix4K_E8000:
1705         case MSR_MTRRfix4K_F0000:
1706         case MSR_MTRRfix4K_F8000:
1707         case MSR_MTRRdefType:
1708         case MSR_IA32_CR_PAT:
1709                 return true;
1710         case 0x2f8:
1711                 return true;
1712         }
1713         return false;
1714 }
1715
1716 static bool valid_pat_type(unsigned t)
1717 {
1718         return t < 8 && (1 << t) & 0xf3; /* 0, 1, 4, 5, 6, 7 */
1719 }
1720
1721 static bool valid_mtrr_type(unsigned t)
1722 {
1723         return t < 8 && (1 << t) & 0x73; /* 0, 1, 4, 5, 6 */
1724 }
1725
1726 static bool mtrr_valid(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1727 {
1728         int i;
1729
1730         if (!msr_mtrr_valid(msr))
1731                 return false;
1732
1733         if (msr == MSR_IA32_CR_PAT) {
1734                 for (i = 0; i < 8; i++)
1735                         if (!valid_pat_type((data >> (i * 8)) & 0xff))
1736                                 return false;
1737                 return true;
1738         } else if (msr == MSR_MTRRdefType) {
1739                 if (data & ~0xcff)
1740                         return false;
1741                 return valid_mtrr_type(data & 0xff);
1742         } else if (msr >= MSR_MTRRfix64K_00000 && msr <= MSR_MTRRfix4K_F8000) {
1743                 for (i = 0; i < 8 ; i++)
1744                         if (!valid_mtrr_type((data >> (i * 8)) & 0xff))
1745                                 return false;
1746                 return true;
1747         }
1748
1749         /* variable MTRRs */
1750         return valid_mtrr_type(data & 0xff);
1751 }
1752
1753 static int set_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1754 {
1755         u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
1756
1757         if (!mtrr_valid(vcpu, msr, data))
1758                 return 1;
1759
1760         if (msr == MSR_MTRRdefType) {
1761                 vcpu->arch.mtrr_state.def_type = data;
1762                 vcpu->arch.mtrr_state.enabled = (data & 0xc00) >> 10;
1763         } else if (msr == MSR_MTRRfix64K_00000)
1764                 p[0] = data;
1765         else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
1766                 p[1 + msr - MSR_MTRRfix16K_80000] = data;
1767         else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
1768                 p[3 + msr - MSR_MTRRfix4K_C0000] = data;
1769         else if (msr == MSR_IA32_CR_PAT)
1770                 vcpu->arch.pat = data;
1771         else {  /* Variable MTRRs */
1772                 int idx, is_mtrr_mask;
1773                 u64 *pt;
1774
1775                 idx = (msr - 0x200) / 2;
1776                 is_mtrr_mask = msr - 0x200 - 2 * idx;
1777                 if (!is_mtrr_mask)
1778                         pt =
1779                           (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
1780                 else
1781                         pt =
1782                           (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
1783                 *pt = data;
1784         }
1785
1786         kvm_mmu_reset_context(vcpu);
1787         return 0;
1788 }
1789
1790 static int set_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1791 {
1792         u64 mcg_cap = vcpu->arch.mcg_cap;
1793         unsigned bank_num = mcg_cap & 0xff;
1794
1795         switch (msr) {
1796         case MSR_IA32_MCG_STATUS:
1797                 vcpu->arch.mcg_status = data;
1798                 break;
1799         case MSR_IA32_MCG_CTL:
1800                 if (!(mcg_cap & MCG_CTL_P))
1801                         return 1;
1802                 if (data != 0 && data != ~(u64)0)
1803                         return -1;
1804                 vcpu->arch.mcg_ctl = data;
1805                 break;
1806         default:
1807                 if (msr >= MSR_IA32_MC0_CTL &&
1808                     msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
1809                         u32 offset = msr - MSR_IA32_MC0_CTL;
1810                         /* only 0 or all 1s can be written to IA32_MCi_CTL
1811                          * some Linux kernels though clear bit 10 in bank 4 to
1812                          * workaround a BIOS/GART TBL issue on AMD K8s, ignore
1813                          * this to avoid an uncatched #GP in the guest
1814                          */
1815                         if ((offset & 0x3) == 0 &&
1816                             data != 0 && (data | (1 << 10)) != ~(u64)0)
1817                                 return -1;
1818                         vcpu->arch.mce_banks[offset] = data;
1819                         break;
1820                 }
1821                 return 1;
1822         }
1823         return 0;
1824 }
1825
1826 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
1827 {
1828         struct kvm *kvm = vcpu->kvm;
1829         int lm = is_long_mode(vcpu);
1830         u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
1831                 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
1832         u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
1833                 : kvm->arch.xen_hvm_config.blob_size_32;
1834         u32 page_num = data & ~PAGE_MASK;
1835         u64 page_addr = data & PAGE_MASK;
1836         u8 *page;
1837         int r;
1838
1839         r = -E2BIG;
1840         if (page_num >= blob_size)
1841                 goto out;
1842         r = -ENOMEM;
1843         page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
1844         if (IS_ERR(page)) {
1845                 r = PTR_ERR(page);
1846                 goto out;
1847         }
1848         if (kvm_write_guest(kvm, page_addr, page, PAGE_SIZE))
1849                 goto out_free;
1850         r = 0;
1851 out_free:
1852         kfree(page);
1853 out:
1854         return r;
1855 }
1856
1857 static bool kvm_hv_hypercall_enabled(struct kvm *kvm)
1858 {
1859         return kvm->arch.hv_hypercall & HV_X64_MSR_HYPERCALL_ENABLE;
1860 }
1861
1862 static bool kvm_hv_msr_partition_wide(u32 msr)
1863 {
1864         bool r = false;
1865         switch (msr) {
1866         case HV_X64_MSR_GUEST_OS_ID:
1867         case HV_X64_MSR_HYPERCALL:
1868         case HV_X64_MSR_REFERENCE_TSC:
1869         case HV_X64_MSR_TIME_REF_COUNT:
1870                 r = true;
1871                 break;
1872         }
1873
1874         return r;
1875 }
1876
1877 static int set_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1878 {
1879         struct kvm *kvm = vcpu->kvm;
1880
1881         switch (msr) {
1882         case HV_X64_MSR_GUEST_OS_ID:
1883                 kvm->arch.hv_guest_os_id = data;
1884                 /* setting guest os id to zero disables hypercall page */
1885                 if (!kvm->arch.hv_guest_os_id)
1886                         kvm->arch.hv_hypercall &= ~HV_X64_MSR_HYPERCALL_ENABLE;
1887                 break;
1888         case HV_X64_MSR_HYPERCALL: {
1889                 u64 gfn;
1890                 unsigned long addr;
1891                 u8 instructions[4];
1892
1893                 /* if guest os id is not set hypercall should remain disabled */
1894                 if (!kvm->arch.hv_guest_os_id)
1895                         break;
1896                 if (!(data & HV_X64_MSR_HYPERCALL_ENABLE)) {
1897                         kvm->arch.hv_hypercall = data;
1898                         break;
1899                 }
1900                 gfn = data >> HV_X64_MSR_HYPERCALL_PAGE_ADDRESS_SHIFT;
1901                 addr = gfn_to_hva(kvm, gfn);
1902                 if (kvm_is_error_hva(addr))
1903                         return 1;
1904                 kvm_x86_ops->patch_hypercall(vcpu, instructions);
1905                 ((unsigned char *)instructions)[3] = 0xc3; /* ret */
1906                 if (__copy_to_user((void __user *)addr, instructions, 4))
1907                         return 1;
1908                 kvm->arch.hv_hypercall = data;
1909                 mark_page_dirty(kvm, gfn);
1910                 break;
1911         }
1912         case HV_X64_MSR_REFERENCE_TSC: {
1913                 u64 gfn;
1914                 HV_REFERENCE_TSC_PAGE tsc_ref;
1915                 memset(&tsc_ref, 0, sizeof(tsc_ref));
1916                 kvm->arch.hv_tsc_page = data;
1917                 if (!(data & HV_X64_MSR_TSC_REFERENCE_ENABLE))
1918                         break;
1919                 gfn = data >> HV_X64_MSR_TSC_REFERENCE_ADDRESS_SHIFT;
1920                 if (kvm_write_guest(kvm, gfn << HV_X64_MSR_TSC_REFERENCE_ADDRESS_SHIFT,
1921                         &tsc_ref, sizeof(tsc_ref)))
1922                         return 1;
1923                 mark_page_dirty(kvm, gfn);
1924                 break;
1925         }
1926         default:
1927                 vcpu_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
1928                             "data 0x%llx\n", msr, data);
1929                 return 1;
1930         }
1931         return 0;
1932 }
1933
1934 static int set_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 data)
1935 {
1936         switch (msr) {
1937         case HV_X64_MSR_APIC_ASSIST_PAGE: {
1938                 u64 gfn;
1939                 unsigned long addr;
1940
1941                 if (!(data & HV_X64_MSR_APIC_ASSIST_PAGE_ENABLE)) {
1942                         vcpu->arch.hv_vapic = data;
1943                         if (kvm_lapic_enable_pv_eoi(vcpu, 0))
1944                                 return 1;
1945                         break;
1946                 }
1947                 gfn = data >> HV_X64_MSR_APIC_ASSIST_PAGE_ADDRESS_SHIFT;
1948                 addr = gfn_to_hva(vcpu->kvm, gfn);
1949                 if (kvm_is_error_hva(addr))
1950                         return 1;
1951                 if (__clear_user((void __user *)addr, PAGE_SIZE))
1952                         return 1;
1953                 vcpu->arch.hv_vapic = data;
1954                 mark_page_dirty(vcpu->kvm, gfn);
1955                 if (kvm_lapic_enable_pv_eoi(vcpu, gfn_to_gpa(gfn) | KVM_MSR_ENABLED))
1956                         return 1;
1957                 break;
1958         }
1959         case HV_X64_MSR_EOI:
1960                 return kvm_hv_vapic_msr_write(vcpu, APIC_EOI, data);
1961         case HV_X64_MSR_ICR:
1962                 return kvm_hv_vapic_msr_write(vcpu, APIC_ICR, data);
1963         case HV_X64_MSR_TPR:
1964                 return kvm_hv_vapic_msr_write(vcpu, APIC_TASKPRI, data);
1965         default:
1966                 vcpu_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
1967                             "data 0x%llx\n", msr, data);
1968                 return 1;
1969         }
1970
1971         return 0;
1972 }
1973
1974 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
1975 {
1976         gpa_t gpa = data & ~0x3f;
1977
1978         /* Bits 2:5 are reserved, Should be zero */
1979         if (data & 0x3c)
1980                 return 1;
1981
1982         vcpu->arch.apf.msr_val = data;
1983
1984         if (!(data & KVM_ASYNC_PF_ENABLED)) {
1985                 kvm_clear_async_pf_completion_queue(vcpu);
1986                 kvm_async_pf_hash_reset(vcpu);
1987                 return 0;
1988         }
1989
1990         if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
1991                                         sizeof(u32)))
1992                 return 1;
1993
1994         vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
1995         kvm_async_pf_wakeup_all(vcpu);
1996         return 0;
1997 }
1998
1999 static void kvmclock_reset(struct kvm_vcpu *vcpu)
2000 {
2001         vcpu->arch.pv_time_enabled = false;
2002 }
2003
2004 static void accumulate_steal_time(struct kvm_vcpu *vcpu)
2005 {
2006         u64 delta;
2007
2008         if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2009                 return;
2010
2011         delta = current->sched_info.run_delay - vcpu->arch.st.last_steal;
2012         vcpu->arch.st.last_steal = current->sched_info.run_delay;
2013         vcpu->arch.st.accum_steal = delta;
2014 }
2015
2016 static void record_steal_time(struct kvm_vcpu *vcpu)
2017 {
2018         if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2019                 return;
2020
2021         if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2022                 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
2023                 return;
2024
2025         vcpu->arch.st.steal.steal += vcpu->arch.st.accum_steal;
2026         vcpu->arch.st.steal.version += 2;
2027         vcpu->arch.st.accum_steal = 0;
2028
2029         kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2030                 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2031 }
2032
2033 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2034 {
2035         bool pr = false;
2036         u32 msr = msr_info->index;
2037         u64 data = msr_info->data;
2038
2039         switch (msr) {
2040         case MSR_AMD64_NB_CFG:
2041         case MSR_IA32_UCODE_REV:
2042         case MSR_IA32_UCODE_WRITE:
2043         case MSR_VM_HSAVE_PA:
2044         case MSR_AMD64_PATCH_LOADER:
2045         case MSR_AMD64_BU_CFG2:
2046                 break;
2047
2048         case MSR_EFER:
2049                 return set_efer(vcpu, data);
2050         case MSR_K7_HWCR:
2051                 data &= ~(u64)0x40;     /* ignore flush filter disable */
2052                 data &= ~(u64)0x100;    /* ignore ignne emulation enable */
2053                 data &= ~(u64)0x8;      /* ignore TLB cache disable */
2054                 data &= ~(u64)0x40000;  /* ignore Mc status write enable */
2055                 if (data != 0) {
2056                         vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
2057                                     data);
2058                         return 1;
2059                 }
2060                 break;
2061         case MSR_FAM10H_MMIO_CONF_BASE:
2062                 if (data != 0) {
2063                         vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
2064                                     "0x%llx\n", data);
2065                         return 1;
2066                 }
2067                 break;
2068         case MSR_IA32_DEBUGCTLMSR:
2069                 if (!data) {
2070                         /* We support the non-activated case already */
2071                         break;
2072                 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
2073                         /* Values other than LBR and BTF are vendor-specific,
2074                            thus reserved and should throw a #GP */
2075                         return 1;
2076                 }
2077                 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
2078                             __func__, data);
2079                 break;
2080         case 0x200 ... 0x2ff:
2081                 return set_msr_mtrr(vcpu, msr, data);
2082         case MSR_IA32_APICBASE:
2083                 return kvm_set_apic_base(vcpu, msr_info);
2084         case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2085                 return kvm_x2apic_msr_write(vcpu, msr, data);
2086         case MSR_IA32_TSCDEADLINE:
2087                 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2088                 break;
2089         case MSR_IA32_TSC_ADJUST:
2090                 if (guest_cpuid_has_tsc_adjust(vcpu)) {
2091                         if (!msr_info->host_initiated) {
2092                                 u64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
2093                                 kvm_x86_ops->adjust_tsc_offset(vcpu, adj, true);
2094                         }
2095                         vcpu->arch.ia32_tsc_adjust_msr = data;
2096                 }
2097                 break;
2098         case MSR_IA32_MISC_ENABLE:
2099                 vcpu->arch.ia32_misc_enable_msr = data;
2100                 break;
2101         case MSR_KVM_WALL_CLOCK_NEW:
2102         case MSR_KVM_WALL_CLOCK:
2103                 vcpu->kvm->arch.wall_clock = data;
2104                 kvm_write_wall_clock(vcpu->kvm, data);
2105                 break;
2106         case MSR_KVM_SYSTEM_TIME_NEW:
2107         case MSR_KVM_SYSTEM_TIME: {
2108                 u64 gpa_offset;
2109                 kvmclock_reset(vcpu);
2110
2111                 vcpu->arch.time = data;
2112                 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2113
2114                 /* we verify if the enable bit is set... */
2115                 if (!(data & 1))
2116                         break;
2117
2118                 gpa_offset = data & ~(PAGE_MASK | 1);
2119
2120                 if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
2121                      &vcpu->arch.pv_time, data & ~1ULL,
2122                      sizeof(struct pvclock_vcpu_time_info)))
2123                         vcpu->arch.pv_time_enabled = false;
2124                 else
2125                         vcpu->arch.pv_time_enabled = true;
2126
2127                 break;
2128         }
2129         case MSR_KVM_ASYNC_PF_EN:
2130                 if (kvm_pv_enable_async_pf(vcpu, data))
2131                         return 1;
2132                 break;
2133         case MSR_KVM_STEAL_TIME:
2134
2135                 if (unlikely(!sched_info_on()))
2136                         return 1;
2137
2138                 if (data & KVM_STEAL_RESERVED_MASK)
2139                         return 1;
2140
2141                 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
2142                                                 data & KVM_STEAL_VALID_BITS,
2143                                                 sizeof(struct kvm_steal_time)))
2144                         return 1;
2145
2146                 vcpu->arch.st.msr_val = data;
2147
2148                 if (!(data & KVM_MSR_ENABLED))
2149                         break;
2150
2151                 vcpu->arch.st.last_steal = current->sched_info.run_delay;
2152
2153                 preempt_disable();
2154                 accumulate_steal_time(vcpu);
2155                 preempt_enable();
2156
2157                 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2158
2159                 break;
2160         case MSR_KVM_PV_EOI_EN:
2161                 if (kvm_lapic_enable_pv_eoi(vcpu, data))
2162                         return 1;
2163                 break;
2164
2165         case MSR_IA32_MCG_CTL:
2166         case MSR_IA32_MCG_STATUS:
2167         case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
2168                 return set_msr_mce(vcpu, msr, data);
2169
2170         /* Performance counters are not protected by a CPUID bit,
2171          * so we should check all of them in the generic path for the sake of
2172          * cross vendor migration.
2173          * Writing a zero into the event select MSRs disables them,
2174          * which we perfectly emulate ;-). Any other value should be at least
2175          * reported, some guests depend on them.
2176          */
2177         case MSR_K7_EVNTSEL0:
2178         case MSR_K7_EVNTSEL1:
2179         case MSR_K7_EVNTSEL2:
2180         case MSR_K7_EVNTSEL3:
2181                 if (data != 0)
2182                         vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: "
2183                                     "0x%x data 0x%llx\n", msr, data);
2184                 break;
2185         /* at least RHEL 4 unconditionally writes to the perfctr registers,
2186          * so we ignore writes to make it happy.
2187          */
2188         case MSR_K7_PERFCTR0:
2189         case MSR_K7_PERFCTR1:
2190         case MSR_K7_PERFCTR2:
2191         case MSR_K7_PERFCTR3:
2192                 vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: "
2193                             "0x%x data 0x%llx\n", msr, data);
2194                 break;
2195         case MSR_P6_PERFCTR0:
2196         case MSR_P6_PERFCTR1:
2197                 pr = true;
2198         case MSR_P6_EVNTSEL0:
2199         case MSR_P6_EVNTSEL1:
2200                 if (kvm_pmu_msr(vcpu, msr))
2201                         return kvm_pmu_set_msr(vcpu, msr_info);
2202
2203                 if (pr || data != 0)
2204                         vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
2205                                     "0x%x data 0x%llx\n", msr, data);
2206                 break;
2207         case MSR_K7_CLK_CTL:
2208                 /*
2209                  * Ignore all writes to this no longer documented MSR.
2210                  * Writes are only relevant for old K7 processors,
2211                  * all pre-dating SVM, but a recommended workaround from
2212                  * AMD for these chips. It is possible to specify the
2213                  * affected processor models on the command line, hence
2214                  * the need to ignore the workaround.
2215                  */
2216                 break;
2217         case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2218                 if (kvm_hv_msr_partition_wide(msr)) {
2219                         int r;
2220                         mutex_lock(&vcpu->kvm->lock);
2221                         r = set_msr_hyperv_pw(vcpu, msr, data);
2222                         mutex_unlock(&vcpu->kvm->lock);
2223                         return r;
2224                 } else
2225                         return set_msr_hyperv(vcpu, msr, data);
2226                 break;
2227         case MSR_IA32_BBL_CR_CTL3:
2228                 /* Drop writes to this legacy MSR -- see rdmsr
2229                  * counterpart for further detail.
2230                  */
2231                 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data);
2232                 break;
2233         case MSR_AMD64_OSVW_ID_LENGTH:
2234                 if (!guest_cpuid_has_osvw(vcpu))
2235                         return 1;
2236                 vcpu->arch.osvw.length = data;
2237                 break;
2238         case MSR_AMD64_OSVW_STATUS:
2239                 if (!guest_cpuid_has_osvw(vcpu))
2240                         return 1;
2241                 vcpu->arch.osvw.status = data;
2242                 break;
2243         default:
2244                 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
2245                         return xen_hvm_config(vcpu, data);
2246                 if (kvm_pmu_msr(vcpu, msr))
2247                         return kvm_pmu_set_msr(vcpu, msr_info);
2248                 if (!ignore_msrs) {
2249                         vcpu_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
2250                                     msr, data);
2251                         return 1;
2252                 } else {
2253                         vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
2254                                     msr, data);
2255                         break;
2256                 }
2257         }
2258         return 0;
2259 }
2260 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
2261
2262
2263 /*
2264  * Reads an msr value (of 'msr_index') into 'pdata'.
2265  * Returns 0 on success, non-0 otherwise.
2266  * Assumes vcpu_load() was already called.
2267  */
2268 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
2269 {
2270         return kvm_x86_ops->get_msr(vcpu, msr_index, pdata);
2271 }
2272
2273 static int get_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2274 {
2275         u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
2276
2277         if (!msr_mtrr_valid(msr))
2278                 return 1;
2279
2280         if (msr == MSR_MTRRdefType)
2281                 *pdata = vcpu->arch.mtrr_state.def_type +
2282                          (vcpu->arch.mtrr_state.enabled << 10);
2283         else if (msr == MSR_MTRRfix64K_00000)
2284                 *pdata = p[0];
2285         else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
2286                 *pdata = p[1 + msr - MSR_MTRRfix16K_80000];
2287         else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
2288                 *pdata = p[3 + msr - MSR_MTRRfix4K_C0000];
2289         else if (msr == MSR_IA32_CR_PAT)
2290                 *pdata = vcpu->arch.pat;
2291         else {  /* Variable MTRRs */
2292                 int idx, is_mtrr_mask;
2293                 u64 *pt;
2294
2295                 idx = (msr - 0x200) / 2;
2296                 is_mtrr_mask = msr - 0x200 - 2 * idx;
2297                 if (!is_mtrr_mask)
2298                         pt =
2299                           (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
2300                 else
2301                         pt =
2302                           (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
2303                 *pdata = *pt;
2304         }
2305
2306         return 0;
2307 }
2308
2309 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2310 {
2311         u64 data;
2312         u64 mcg_cap = vcpu->arch.mcg_cap;
2313         unsigned bank_num = mcg_cap & 0xff;
2314
2315         switch (msr) {
2316         case MSR_IA32_P5_MC_ADDR:
2317         case MSR_IA32_P5_MC_TYPE:
2318                 data = 0;
2319                 break;
2320         case MSR_IA32_MCG_CAP:
2321                 data = vcpu->arch.mcg_cap;
2322                 break;
2323         case MSR_IA32_MCG_CTL:
2324                 if (!(mcg_cap & MCG_CTL_P))
2325                         return 1;
2326                 data = vcpu->arch.mcg_ctl;
2327                 break;
2328         case MSR_IA32_MCG_STATUS:
2329                 data = vcpu->arch.mcg_status;
2330                 break;
2331         default:
2332                 if (msr >= MSR_IA32_MC0_CTL &&
2333                     msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
2334                         u32 offset = msr - MSR_IA32_MC0_CTL;
2335                         data = vcpu->arch.mce_banks[offset];
2336                         break;
2337                 }
2338                 return 1;
2339         }
2340         *pdata = data;
2341         return 0;
2342 }
2343
2344 static int get_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2345 {
2346         u64 data = 0;
2347         struct kvm *kvm = vcpu->kvm;
2348
2349         switch (msr) {
2350         case HV_X64_MSR_GUEST_OS_ID:
2351                 data = kvm->arch.hv_guest_os_id;
2352                 break;
2353         case HV_X64_MSR_HYPERCALL:
2354                 data = kvm->arch.hv_hypercall;
2355                 break;
2356         case HV_X64_MSR_TIME_REF_COUNT: {
2357                 data =
2358                      div_u64(get_kernel_ns() + kvm->arch.kvmclock_offset, 100);
2359                 break;
2360         }
2361         case HV_X64_MSR_REFERENCE_TSC:
2362                 data = kvm->arch.hv_tsc_page;
2363                 break;
2364         default:
2365                 vcpu_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
2366                 return 1;
2367         }
2368
2369         *pdata = data;
2370         return 0;
2371 }
2372
2373 static int get_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2374 {
2375         u64 data = 0;
2376
2377         switch (msr) {
2378         case HV_X64_MSR_VP_INDEX: {
2379                 int r;
2380                 struct kvm_vcpu *v;
2381                 kvm_for_each_vcpu(r, v, vcpu->kvm) {
2382                         if (v == vcpu) {
2383                                 data = r;
2384                                 break;
2385                         }
2386                 }
2387                 break;
2388         }
2389         case HV_X64_MSR_EOI:
2390                 return kvm_hv_vapic_msr_read(vcpu, APIC_EOI, pdata);
2391         case HV_X64_MSR_ICR:
2392                 return kvm_hv_vapic_msr_read(vcpu, APIC_ICR, pdata);
2393         case HV_X64_MSR_TPR:
2394                 return kvm_hv_vapic_msr_read(vcpu, APIC_TASKPRI, pdata);
2395         case HV_X64_MSR_APIC_ASSIST_PAGE:
2396                 data = vcpu->arch.hv_vapic;
2397                 break;
2398         default:
2399                 vcpu_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
2400                 return 1;
2401         }
2402         *pdata = data;
2403         return 0;
2404 }
2405
2406 int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2407 {
2408         u64 data;
2409
2410         switch (msr) {
2411         case MSR_IA32_PLATFORM_ID:
2412         case MSR_IA32_EBL_CR_POWERON:
2413         case MSR_IA32_DEBUGCTLMSR:
2414         case MSR_IA32_LASTBRANCHFROMIP:
2415         case MSR_IA32_LASTBRANCHTOIP:
2416         case MSR_IA32_LASTINTFROMIP:
2417         case MSR_IA32_LASTINTTOIP:
2418         case MSR_K8_SYSCFG:
2419         case MSR_K7_HWCR:
2420         case MSR_VM_HSAVE_PA:
2421         case MSR_K7_EVNTSEL0:
2422         case MSR_K7_EVNTSEL1:
2423         case MSR_K7_EVNTSEL2:
2424         case MSR_K7_EVNTSEL3:
2425         case MSR_K7_PERFCTR0:
2426         case MSR_K7_PERFCTR1:
2427         case MSR_K7_PERFCTR2:
2428         case MSR_K7_PERFCTR3:
2429         case MSR_K8_INT_PENDING_MSG:
2430         case MSR_AMD64_NB_CFG:
2431         case MSR_FAM10H_MMIO_CONF_BASE:
2432         case MSR_AMD64_BU_CFG2:
2433                 data = 0;
2434                 break;
2435         case MSR_P6_PERFCTR0:
2436         case MSR_P6_PERFCTR1:
2437         case MSR_P6_EVNTSEL0:
2438         case MSR_P6_EVNTSEL1:
2439                 if (kvm_pmu_msr(vcpu, msr))
2440                         return kvm_pmu_get_msr(vcpu, msr, pdata);
2441                 data = 0;
2442                 break;
2443         case MSR_IA32_UCODE_REV:
2444                 data = 0x100000000ULL;
2445                 break;
2446         case MSR_MTRRcap:
2447                 data = 0x500 | KVM_NR_VAR_MTRR;
2448                 break;
2449         case 0x200 ... 0x2ff:
2450                 return get_msr_mtrr(vcpu, msr, pdata);
2451         case 0xcd: /* fsb frequency */
2452                 data = 3;
2453                 break;
2454                 /*
2455                  * MSR_EBC_FREQUENCY_ID
2456                  * Conservative value valid for even the basic CPU models.
2457                  * Models 0,1: 000 in bits 23:21 indicating a bus speed of
2458                  * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
2459                  * and 266MHz for model 3, or 4. Set Core Clock
2460                  * Frequency to System Bus Frequency Ratio to 1 (bits
2461                  * 31:24) even though these are only valid for CPU
2462                  * models > 2, however guests may end up dividing or
2463                  * multiplying by zero otherwise.
2464                  */
2465         case MSR_EBC_FREQUENCY_ID:
2466                 data = 1 << 24;
2467                 break;
2468         case MSR_IA32_APICBASE:
2469                 data = kvm_get_apic_base(vcpu);
2470                 break;
2471         case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2472                 return kvm_x2apic_msr_read(vcpu, msr, pdata);
2473                 break;
2474         case MSR_IA32_TSCDEADLINE:
2475                 data = kvm_get_lapic_tscdeadline_msr(vcpu);
2476                 break;
2477         case MSR_IA32_TSC_ADJUST:
2478                 data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
2479                 break;
2480         case MSR_IA32_MISC_ENABLE:
2481                 data = vcpu->arch.ia32_misc_enable_msr;
2482                 break;
2483         case MSR_IA32_PERF_STATUS:
2484                 /* TSC increment by tick */
2485                 data = 1000ULL;
2486                 /* CPU multiplier */
2487                 data |= (((uint64_t)4ULL) << 40);
2488                 break;
2489         case MSR_EFER:
2490                 data = vcpu->arch.efer;
2491                 break;
2492         case MSR_KVM_WALL_CLOCK:
2493         case MSR_KVM_WALL_CLOCK_NEW:
2494                 data = vcpu->kvm->arch.wall_clock;
2495                 break;
2496         case MSR_KVM_SYSTEM_TIME:
2497         case MSR_KVM_SYSTEM_TIME_NEW:
2498                 data = vcpu->arch.time;
2499                 break;
2500         case MSR_KVM_ASYNC_PF_EN:
2501                 data = vcpu->arch.apf.msr_val;
2502                 break;
2503         case MSR_KVM_STEAL_TIME:
2504                 data = vcpu->arch.st.msr_val;
2505                 break;
2506         case MSR_KVM_PV_EOI_EN:
2507                 data = vcpu->arch.pv_eoi.msr_val;
2508                 break;
2509         case MSR_IA32_P5_MC_ADDR:
2510         case MSR_IA32_P5_MC_TYPE:
2511         case MSR_IA32_MCG_CAP:
2512         case MSR_IA32_MCG_CTL:
2513         case MSR_IA32_MCG_STATUS:
2514         case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
2515                 return get_msr_mce(vcpu, msr, pdata);
2516         case MSR_K7_CLK_CTL:
2517                 /*
2518                  * Provide expected ramp-up count for K7. All other
2519                  * are set to zero, indicating minimum divisors for
2520                  * every field.
2521                  *
2522                  * This prevents guest kernels on AMD host with CPU
2523                  * type 6, model 8 and higher from exploding due to
2524                  * the rdmsr failing.
2525                  */
2526                 data = 0x20000000;
2527                 break;
2528         case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2529                 if (kvm_hv_msr_partition_wide(msr)) {
2530                         int r;
2531                         mutex_lock(&vcpu->kvm->lock);
2532                         r = get_msr_hyperv_pw(vcpu, msr, pdata);
2533                         mutex_unlock(&vcpu->kvm->lock);
2534                         return r;
2535                 } else
2536                         return get_msr_hyperv(vcpu, msr, pdata);
2537                 break;
2538         case MSR_IA32_BBL_CR_CTL3:
2539                 /* This legacy MSR exists but isn't fully documented in current
2540                  * silicon.  It is however accessed by winxp in very narrow
2541                  * scenarios where it sets bit #19, itself documented as
2542                  * a "reserved" bit.  Best effort attempt to source coherent
2543                  * read data here should the balance of the register be
2544                  * interpreted by the guest:
2545                  *
2546                  * L2 cache control register 3: 64GB range, 256KB size,
2547                  * enabled, latency 0x1, configured
2548                  */
2549                 data = 0xbe702111;
2550                 break;
2551         case MSR_AMD64_OSVW_ID_LENGTH:
2552                 if (!guest_cpuid_has_osvw(vcpu))
2553                         return 1;
2554                 data = vcpu->arch.osvw.length;
2555                 break;
2556         case MSR_AMD64_OSVW_STATUS:
2557                 if (!guest_cpuid_has_osvw(vcpu))
2558                         return 1;
2559                 data = vcpu->arch.osvw.status;
2560                 break;
2561         default:
2562                 if (kvm_pmu_msr(vcpu, msr))
2563                         return kvm_pmu_get_msr(vcpu, msr, pdata);
2564                 if (!ignore_msrs) {
2565                         vcpu_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr);
2566                         return 1;
2567                 } else {
2568                         vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n", msr);
2569                         data = 0;
2570                 }
2571                 break;
2572         }
2573         *pdata = data;
2574         return 0;
2575 }
2576 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
2577
2578 /*
2579  * Read or write a bunch of msrs. All parameters are kernel addresses.
2580  *
2581  * @return number of msrs set successfully.
2582  */
2583 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
2584                     struct kvm_msr_entry *entries,
2585                     int (*do_msr)(struct kvm_vcpu *vcpu,
2586                                   unsigned index, u64 *data))
2587 {
2588         int i, idx;
2589
2590         idx = srcu_read_lock(&vcpu->kvm->srcu);
2591         for (i = 0; i < msrs->nmsrs; ++i)
2592                 if (do_msr(vcpu, entries[i].index, &entries[i].data))
2593                         break;
2594         srcu_read_unlock(&vcpu->kvm->srcu, idx);
2595
2596         return i;
2597 }
2598
2599 /*
2600  * Read or write a bunch of msrs. Parameters are user addresses.
2601  *
2602  * @return number of msrs set successfully.
2603  */
2604 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
2605                   int (*do_msr)(struct kvm_vcpu *vcpu,
2606                                 unsigned index, u64 *data),
2607                   int writeback)
2608 {
2609         struct kvm_msrs msrs;
2610         struct kvm_msr_entry *entries;
2611         int r, n;
2612         unsigned size;
2613
2614         r = -EFAULT;
2615         if (copy_from_user(&msrs, user_msrs, sizeof msrs))
2616                 goto out;
2617
2618         r = -E2BIG;
2619         if (msrs.nmsrs >= MAX_IO_MSRS)
2620                 goto out;
2621
2622         size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
2623         entries = memdup_user(user_msrs->entries, size);
2624         if (IS_ERR(entries)) {
2625                 r = PTR_ERR(entries);
2626                 goto out;
2627         }
2628
2629         r = n = __msr_io(vcpu, &msrs, entries, do_msr);
2630         if (r < 0)
2631                 goto out_free;
2632
2633         r = -EFAULT;
2634         if (writeback && copy_to_user(user_msrs->entries, entries, size))
2635                 goto out_free;
2636
2637         r = n;
2638
2639 out_free:
2640         kfree(entries);
2641 out:
2642         return r;
2643 }
2644
2645 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
2646 {
2647         int r;
2648
2649         switch (ext) {
2650         case KVM_CAP_IRQCHIP:
2651         case KVM_CAP_HLT:
2652         case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
2653         case KVM_CAP_SET_TSS_ADDR:
2654         case KVM_CAP_EXT_CPUID:
2655         case KVM_CAP_EXT_EMUL_CPUID:
2656         case KVM_CAP_CLOCKSOURCE:
2657         case KVM_CAP_PIT:
2658         case KVM_CAP_NOP_IO_DELAY:
2659         case KVM_CAP_MP_STATE:
2660         case KVM_CAP_SYNC_MMU:
2661         case KVM_CAP_USER_NMI:
2662         case KVM_CAP_REINJECT_CONTROL:
2663         case KVM_CAP_IRQ_INJECT_STATUS:
2664         case KVM_CAP_IRQFD:
2665         case KVM_CAP_IOEVENTFD:
2666         case KVM_CAP_IOEVENTFD_NO_LENGTH:
2667         case KVM_CAP_PIT2:
2668         case KVM_CAP_PIT_STATE2:
2669         case KVM_CAP_SET_IDENTITY_MAP_ADDR:
2670         case KVM_CAP_XEN_HVM:
2671         case KVM_CAP_ADJUST_CLOCK:
2672         case KVM_CAP_VCPU_EVENTS:
2673         case KVM_CAP_HYPERV:
2674         case KVM_CAP_HYPERV_VAPIC:
2675         case KVM_CAP_HYPERV_SPIN:
2676         case KVM_CAP_PCI_SEGMENT:
2677         case KVM_CAP_DEBUGREGS:
2678         case KVM_CAP_X86_ROBUST_SINGLESTEP:
2679         case KVM_CAP_XSAVE:
2680         case KVM_CAP_ASYNC_PF:
2681         case KVM_CAP_GET_TSC_KHZ:
2682         case KVM_CAP_KVMCLOCK_CTRL:
2683         case KVM_CAP_READONLY_MEM:
2684         case KVM_CAP_HYPERV_TIME:
2685         case KVM_CAP_IOAPIC_POLARITY_IGNORED:
2686 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
2687         case KVM_CAP_ASSIGN_DEV_IRQ:
2688         case KVM_CAP_PCI_2_3:
2689 #endif
2690                 r = 1;
2691                 break;
2692         case KVM_CAP_COALESCED_MMIO:
2693                 r = KVM_COALESCED_MMIO_PAGE_OFFSET;
2694                 break;
2695         case KVM_CAP_VAPIC:
2696                 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
2697                 break;
2698         case KVM_CAP_NR_VCPUS:
2699                 r = KVM_SOFT_MAX_VCPUS;
2700                 break;
2701         case KVM_CAP_MAX_VCPUS:
2702                 r = KVM_MAX_VCPUS;
2703                 break;
2704         case KVM_CAP_NR_MEMSLOTS:
2705                 r = KVM_USER_MEM_SLOTS;
2706                 break;
2707         case KVM_CAP_PV_MMU:    /* obsolete */
2708                 r = 0;
2709                 break;
2710 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
2711         case KVM_CAP_IOMMU:
2712                 r = iommu_present(&pci_bus_type);
2713                 break;
2714 #endif
2715         case KVM_CAP_MCE:
2716                 r = KVM_MAX_MCE_BANKS;
2717                 break;
2718         case KVM_CAP_XCRS:
2719                 r = cpu_has_xsave;
2720                 break;
2721         case KVM_CAP_TSC_CONTROL:
2722                 r = kvm_has_tsc_control;
2723                 break;
2724         case KVM_CAP_TSC_DEADLINE_TIMER:
2725                 r = boot_cpu_has(X86_FEATURE_TSC_DEADLINE_TIMER);
2726                 break;
2727         default:
2728                 r = 0;
2729                 break;
2730         }
2731         return r;
2732
2733 }
2734
2735 long kvm_arch_dev_ioctl(struct file *filp,
2736                         unsigned int ioctl, unsigned long arg)
2737 {
2738         void __user *argp = (void __user *)arg;
2739         long r;
2740
2741         switch (ioctl) {
2742         case KVM_GET_MSR_INDEX_LIST: {
2743                 struct kvm_msr_list __user *user_msr_list = argp;
2744                 struct kvm_msr_list msr_list;
2745                 unsigned n;
2746
2747                 r = -EFAULT;
2748                 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
2749                         goto out;
2750                 n = msr_list.nmsrs;
2751                 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
2752                 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
2753                         goto out;
2754                 r = -E2BIG;
2755                 if (n < msr_list.nmsrs)
2756                         goto out;
2757                 r = -EFAULT;
2758                 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
2759                                  num_msrs_to_save * sizeof(u32)))
2760                         goto out;
2761                 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
2762                                  &emulated_msrs,
2763                                  ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
2764                         goto out;
2765                 r = 0;
2766                 break;
2767         }
2768         case KVM_GET_SUPPORTED_CPUID:
2769         case KVM_GET_EMULATED_CPUID: {
2770                 struct kvm_cpuid2 __user *cpuid_arg = argp;
2771                 struct kvm_cpuid2 cpuid;
2772
2773                 r = -EFAULT;
2774                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2775                         goto out;
2776
2777                 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
2778                                             ioctl);
2779                 if (r)
2780                         goto out;
2781
2782                 r = -EFAULT;
2783                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
2784                         goto out;
2785                 r = 0;
2786                 break;
2787         }
2788         case KVM_X86_GET_MCE_CAP_SUPPORTED: {
2789                 u64 mce_cap;
2790
2791                 mce_cap = KVM_MCE_CAP_SUPPORTED;
2792                 r = -EFAULT;
2793                 if (copy_to_user(argp, &mce_cap, sizeof mce_cap))
2794                         goto out;
2795                 r = 0;
2796                 break;
2797         }
2798         default:
2799                 r = -EINVAL;
2800         }
2801 out:
2802         return r;
2803 }
2804
2805 static void wbinvd_ipi(void *garbage)
2806 {
2807         wbinvd();
2808 }
2809
2810 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
2811 {
2812         return kvm_arch_has_noncoherent_dma(vcpu->kvm);
2813 }
2814
2815 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2816 {
2817         /* Address WBINVD may be executed by guest */
2818         if (need_emulate_wbinvd(vcpu)) {
2819                 if (kvm_x86_ops->has_wbinvd_exit())
2820                         cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
2821                 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
2822                         smp_call_function_single(vcpu->cpu,
2823                                         wbinvd_ipi, NULL, 1);
2824         }
2825
2826         kvm_x86_ops->vcpu_load(vcpu, cpu);
2827
2828         /* Apply any externally detected TSC adjustments (due to suspend) */
2829         if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
2830                 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
2831                 vcpu->arch.tsc_offset_adjustment = 0;
2832                 set_bit(KVM_REQ_CLOCK_UPDATE, &vcpu->requests);
2833         }
2834
2835         if (unlikely(vcpu->cpu != cpu) || check_tsc_unstable()) {
2836                 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
2837                                 native_read_tsc() - vcpu->arch.last_host_tsc;
2838                 if (tsc_delta < 0)
2839                         mark_tsc_unstable("KVM discovered backwards TSC");
2840                 if (check_tsc_unstable()) {
2841                         u64 offset = kvm_x86_ops->compute_tsc_offset(vcpu,
2842                                                 vcpu->arch.last_guest_tsc);
2843                         kvm_x86_ops->write_tsc_offset(vcpu, offset);
2844                         vcpu->arch.tsc_catchup = 1;
2845                 }
2846                 /*
2847                  * On a host with synchronized TSC, there is no need to update
2848                  * kvmclock on vcpu->cpu migration
2849                  */
2850                 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
2851                         kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2852                 if (vcpu->cpu != cpu)
2853                         kvm_migrate_timers(vcpu);
2854                 vcpu->cpu = cpu;
2855         }
2856
2857         accumulate_steal_time(vcpu);
2858         kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2859 }
2860
2861 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
2862 {
2863         kvm_x86_ops->vcpu_put(vcpu);
2864         kvm_put_guest_fpu(vcpu);
2865         vcpu->arch.last_host_tsc = native_read_tsc();
2866 }
2867
2868 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
2869                                     struct kvm_lapic_state *s)
2870 {
2871         kvm_x86_ops->sync_pir_to_irr(vcpu);
2872         memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
2873
2874         return 0;
2875 }
2876
2877 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
2878                                     struct kvm_lapic_state *s)
2879 {
2880         kvm_apic_post_state_restore(vcpu, s);
2881         update_cr8_intercept(vcpu);
2882
2883         return 0;
2884 }
2885
2886 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
2887                                     struct kvm_interrupt *irq)
2888 {
2889         if (irq->irq >= KVM_NR_INTERRUPTS)
2890                 return -EINVAL;
2891         if (irqchip_in_kernel(vcpu->kvm))
2892                 return -ENXIO;
2893
2894         kvm_queue_interrupt(vcpu, irq->irq, false);
2895         kvm_make_request(KVM_REQ_EVENT, vcpu);
2896
2897         return 0;
2898 }
2899
2900 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
2901 {
2902         kvm_inject_nmi(vcpu);
2903
2904         return 0;
2905 }
2906
2907 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
2908                                            struct kvm_tpr_access_ctl *tac)
2909 {
2910         if (tac->flags)
2911                 return -EINVAL;
2912         vcpu->arch.tpr_access_reporting = !!tac->enabled;
2913         return 0;
2914 }
2915
2916 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
2917                                         u64 mcg_cap)
2918 {
2919         int r;
2920         unsigned bank_num = mcg_cap & 0xff, bank;
2921
2922         r = -EINVAL;
2923         if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
2924                 goto out;
2925         if (mcg_cap & ~(KVM_MCE_CAP_SUPPORTED | 0xff | 0xff0000))
2926                 goto out;
2927         r = 0;
2928         vcpu->arch.mcg_cap = mcg_cap;
2929         /* Init IA32_MCG_CTL to all 1s */
2930         if (mcg_cap & MCG_CTL_P)
2931                 vcpu->arch.mcg_ctl = ~(u64)0;
2932         /* Init IA32_MCi_CTL to all 1s */
2933         for (bank = 0; bank < bank_num; bank++)
2934                 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
2935 out:
2936         return r;
2937 }
2938
2939 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
2940                                       struct kvm_x86_mce *mce)
2941 {
2942         u64 mcg_cap = vcpu->arch.mcg_cap;
2943         unsigned bank_num = mcg_cap & 0xff;
2944         u64 *banks = vcpu->arch.mce_banks;
2945
2946         if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
2947                 return -EINVAL;
2948         /*
2949          * if IA32_MCG_CTL is not all 1s, the uncorrected error
2950          * reporting is disabled
2951          */
2952         if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
2953             vcpu->arch.mcg_ctl != ~(u64)0)
2954                 return 0;
2955         banks += 4 * mce->bank;
2956         /*
2957          * if IA32_MCi_CTL is not all 1s, the uncorrected error
2958          * reporting is disabled for the bank
2959          */
2960         if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
2961                 return 0;
2962         if (mce->status & MCI_STATUS_UC) {
2963                 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
2964                     !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
2965                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2966                         return 0;
2967                 }
2968                 if (banks[1] & MCI_STATUS_VAL)
2969                         mce->status |= MCI_STATUS_OVER;
2970                 banks[2] = mce->addr;
2971                 banks[3] = mce->misc;
2972                 vcpu->arch.mcg_status = mce->mcg_status;
2973                 banks[1] = mce->status;
2974                 kvm_queue_exception(vcpu, MC_VECTOR);
2975         } else if (!(banks[1] & MCI_STATUS_VAL)
2976                    || !(banks[1] & MCI_STATUS_UC)) {
2977                 if (banks[1] & MCI_STATUS_VAL)
2978                         mce->status |= MCI_STATUS_OVER;
2979                 banks[2] = mce->addr;
2980                 banks[3] = mce->misc;
2981                 banks[1] = mce->status;
2982         } else
2983                 banks[1] |= MCI_STATUS_OVER;
2984         return 0;
2985 }
2986
2987 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
2988                                                struct kvm_vcpu_events *events)
2989 {
2990         process_nmi(vcpu);
2991         events->exception.injected =
2992                 vcpu->arch.exception.pending &&
2993                 !kvm_exception_is_soft(vcpu->arch.exception.nr);
2994         events->exception.nr = vcpu->arch.exception.nr;
2995         events->exception.has_error_code = vcpu->arch.exception.has_error_code;
2996         events->exception.pad = 0;
2997         events->exception.error_code = vcpu->arch.exception.error_code;
2998
2999         events->interrupt.injected =
3000                 vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
3001         events->interrupt.nr = vcpu->arch.interrupt.nr;
3002         events->interrupt.soft = 0;
3003         events->interrupt.shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
3004
3005         events->nmi.injected = vcpu->arch.nmi_injected;
3006         events->nmi.pending = vcpu->arch.nmi_pending != 0;
3007         events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
3008         events->nmi.pad = 0;
3009
3010         events->sipi_vector = 0; /* never valid when reporting to user space */
3011
3012         events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
3013                          | KVM_VCPUEVENT_VALID_SHADOW);
3014         memset(&events->reserved, 0, sizeof(events->reserved));
3015 }
3016
3017 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
3018                                               struct kvm_vcpu_events *events)
3019 {
3020         if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
3021                               | KVM_VCPUEVENT_VALID_SIPI_VECTOR
3022                               | KVM_VCPUEVENT_VALID_SHADOW))
3023                 return -EINVAL;
3024
3025         process_nmi(vcpu);
3026         vcpu->arch.exception.pending = events->exception.injected;
3027         vcpu->arch.exception.nr = events->exception.nr;
3028         vcpu->arch.exception.has_error_code = events->exception.has_error_code;
3029         vcpu->arch.exception.error_code = events->exception.error_code;
3030
3031         vcpu->arch.interrupt.pending = events->interrupt.injected;
3032         vcpu->arch.interrupt.nr = events->interrupt.nr;
3033         vcpu->arch.interrupt.soft = events->interrupt.soft;
3034         if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
3035                 kvm_x86_ops->set_interrupt_shadow(vcpu,
3036                                                   events->interrupt.shadow);
3037
3038         vcpu->arch.nmi_injected = events->nmi.injected;
3039         if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
3040                 vcpu->arch.nmi_pending = events->nmi.pending;
3041         kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
3042
3043         if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
3044             kvm_vcpu_has_lapic(vcpu))
3045                 vcpu->arch.apic->sipi_vector = events->sipi_vector;
3046
3047         kvm_make_request(KVM_REQ_EVENT, vcpu);
3048
3049         return 0;
3050 }
3051
3052 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
3053                                              struct kvm_debugregs *dbgregs)
3054 {
3055         unsigned long val;
3056
3057         memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
3058         _kvm_get_dr(vcpu, 6, &val);
3059         dbgregs->dr6 = val;
3060         dbgregs->dr7 = vcpu->arch.dr7;
3061         dbgregs->flags = 0;
3062         memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
3063 }
3064
3065 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
3066                                             struct kvm_debugregs *dbgregs)
3067 {
3068         if (dbgregs->flags)
3069                 return -EINVAL;
3070
3071         memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
3072         vcpu->arch.dr6 = dbgregs->dr6;
3073         kvm_update_dr6(vcpu);
3074         vcpu->arch.dr7 = dbgregs->dr7;
3075         kvm_update_dr7(vcpu);
3076
3077         return 0;
3078 }
3079
3080 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
3081                                          struct kvm_xsave *guest_xsave)
3082 {
3083         if (cpu_has_xsave) {
3084                 memcpy(guest_xsave->region,
3085                         &vcpu->arch.guest_fpu.state->xsave,
3086                         vcpu->arch.guest_xstate_size);
3087                 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] &=
3088                         vcpu->arch.guest_supported_xcr0 | XSTATE_FPSSE;
3089         } else {
3090                 memcpy(guest_xsave->region,
3091                         &vcpu->arch.guest_fpu.state->fxsave,
3092                         sizeof(struct i387_fxsave_struct));
3093                 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
3094                         XSTATE_FPSSE;
3095         }
3096 }
3097
3098 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
3099                                         struct kvm_xsave *guest_xsave)
3100 {
3101         u64 xstate_bv =
3102                 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
3103
3104         if (cpu_has_xsave) {
3105                 /*
3106                  * Here we allow setting states that are not present in
3107                  * CPUID leaf 0xD, index 0, EDX:EAX.  This is for compatibility
3108                  * with old userspace.
3109                  */
3110                 if (xstate_bv & ~kvm_supported_xcr0())
3111                         return -EINVAL;
3112                 memcpy(&vcpu->arch.guest_fpu.state->xsave,
3113                         guest_xsave->region, vcpu->arch.guest_xstate_size);
3114         } else {
3115                 if (xstate_bv & ~XSTATE_FPSSE)
3116                         return -EINVAL;
3117                 memcpy(&vcpu->arch.guest_fpu.state->fxsave,
3118                         guest_xsave->region, sizeof(struct i387_fxsave_struct));
3119         }
3120         return 0;
3121 }
3122
3123 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
3124                                         struct kvm_xcrs *guest_xcrs)
3125 {
3126         if (!cpu_has_xsave) {
3127                 guest_xcrs->nr_xcrs = 0;
3128                 return;
3129         }
3130
3131         guest_xcrs->nr_xcrs = 1;
3132         guest_xcrs->flags = 0;
3133         guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
3134         guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
3135 }
3136
3137 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
3138                                        struct kvm_xcrs *guest_xcrs)
3139 {
3140         int i, r = 0;
3141
3142         if (!cpu_has_xsave)
3143                 return -EINVAL;
3144
3145         if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
3146                 return -EINVAL;
3147
3148         for (i = 0; i < guest_xcrs->nr_xcrs; i++)
3149                 /* Only support XCR0 currently */
3150                 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
3151                         r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
3152                                 guest_xcrs->xcrs[i].value);
3153                         break;
3154                 }
3155         if (r)
3156                 r = -EINVAL;
3157         return r;
3158 }
3159
3160 /*
3161  * kvm_set_guest_paused() indicates to the guest kernel that it has been
3162  * stopped by the hypervisor.  This function will be called from the host only.
3163  * EINVAL is returned when the host attempts to set the flag for a guest that
3164  * does not support pv clocks.
3165  */
3166 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
3167 {
3168         if (!vcpu->arch.pv_time_enabled)
3169                 return -EINVAL;
3170         vcpu->arch.pvclock_set_guest_stopped_request = true;
3171         kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3172         return 0;
3173 }
3174
3175 long kvm_arch_vcpu_ioctl(struct file *filp,
3176                          unsigned int ioctl, unsigned long arg)
3177 {
3178         struct kvm_vcpu *vcpu = filp->private_data;
3179         void __user *argp = (void __user *)arg;
3180         int r;
3181         union {
3182                 struct kvm_lapic_state *lapic;
3183                 struct kvm_xsave *xsave;
3184                 struct kvm_xcrs *xcrs;
3185                 void *buffer;
3186         } u;
3187
3188         u.buffer = NULL;
3189         switch (ioctl) {
3190         case KVM_GET_LAPIC: {
3191                 r = -EINVAL;
3192                 if (!vcpu->arch.apic)
3193                         goto out;
3194                 u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
3195
3196                 r = -ENOMEM;
3197                 if (!u.lapic)
3198                         goto out;
3199                 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
3200                 if (r)
3201                         goto out;
3202                 r = -EFAULT;
3203                 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
3204                         goto out;
3205                 r = 0;
3206                 break;
3207         }
3208         case KVM_SET_LAPIC: {
3209                 r = -EINVAL;
3210                 if (!vcpu->arch.apic)
3211                         goto out;
3212                 u.lapic = memdup_user(argp, sizeof(*u.lapic));
3213                 if (IS_ERR(u.lapic))
3214                         return PTR_ERR(u.lapic);
3215
3216                 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
3217                 break;
3218         }
3219         case KVM_INTERRUPT: {
3220                 struct kvm_interrupt irq;
3221
3222                 r = -EFAULT;
3223                 if (copy_from_user(&irq, argp, sizeof irq))
3224                         goto out;
3225                 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
3226                 break;
3227         }
3228         case KVM_NMI: {
3229                 r = kvm_vcpu_ioctl_nmi(vcpu);
3230                 break;
3231         }
3232         case KVM_SET_CPUID: {
3233                 struct kvm_cpuid __user *cpuid_arg = argp;
3234                 struct kvm_cpuid cpuid;
3235
3236                 r = -EFAULT;
3237                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3238                         goto out;
3239                 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
3240                 break;
3241         }
3242         case KVM_SET_CPUID2: {
3243                 struct kvm_cpuid2 __user *cpuid_arg = argp;
3244                 struct kvm_cpuid2 cpuid;
3245
3246                 r = -EFAULT;
3247                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3248                         goto out;
3249                 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
3250                                               cpuid_arg->entries);
3251                 break;
3252         }
3253         case KVM_GET_CPUID2: {
3254                 struct kvm_cpuid2 __user *cpuid_arg = argp;
3255                 struct kvm_cpuid2 cpuid;
3256
3257                 r = -EFAULT;
3258                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3259                         goto out;
3260                 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
3261                                               cpuid_arg->entries);
3262                 if (r)
3263                         goto out;
3264                 r = -EFAULT;
3265                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
3266                         goto out;
3267                 r = 0;
3268                 break;
3269         }
3270         case KVM_GET_MSRS:
3271                 r = msr_io(vcpu, argp, kvm_get_msr, 1);
3272                 break;
3273         case KVM_SET_MSRS:
3274                 r = msr_io(vcpu, argp, do_set_msr, 0);
3275                 break;
3276         case KVM_TPR_ACCESS_REPORTING: {
3277                 struct kvm_tpr_access_ctl tac;
3278
3279                 r = -EFAULT;
3280                 if (copy_from_user(&tac, argp, sizeof tac))
3281                         goto out;
3282                 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
3283                 if (r)
3284                         goto out;
3285                 r = -EFAULT;
3286                 if (copy_to_user(argp, &tac, sizeof tac))
3287                         goto out;
3288                 r = 0;
3289                 break;
3290         };
3291         case KVM_SET_VAPIC_ADDR: {
3292                 struct kvm_vapic_addr va;
3293
3294                 r = -EINVAL;
3295                 if (!irqchip_in_kernel(vcpu->kvm))
3296                         goto out;
3297                 r = -EFAULT;
3298                 if (copy_from_user(&va, argp, sizeof va))
3299                         goto out;
3300                 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
3301                 break;
3302         }
3303         case KVM_X86_SETUP_MCE: {
3304                 u64 mcg_cap;
3305
3306                 r = -EFAULT;
3307                 if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
3308                         goto out;
3309                 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
3310                 break;