8f1e22d3b286ccf03c90dc3bc28f120fe27a244b
[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_PERFCTR0:
2423         case MSR_K8_INT_PENDING_MSG:
2424         case MSR_AMD64_NB_CFG:
2425         case MSR_FAM10H_MMIO_CONF_BASE:
2426         case MSR_AMD64_BU_CFG2:
2427                 data = 0;
2428                 break;
2429         case MSR_P6_PERFCTR0:
2430         case MSR_P6_PERFCTR1:
2431         case MSR_P6_EVNTSEL0:
2432         case MSR_P6_EVNTSEL1:
2433                 if (kvm_pmu_msr(vcpu, msr))
2434                         return kvm_pmu_get_msr(vcpu, msr, pdata);
2435                 data = 0;
2436                 break;
2437         case MSR_IA32_UCODE_REV:
2438                 data = 0x100000000ULL;
2439                 break;
2440         case MSR_MTRRcap:
2441                 data = 0x500 | KVM_NR_VAR_MTRR;
2442                 break;
2443         case 0x200 ... 0x2ff:
2444                 return get_msr_mtrr(vcpu, msr, pdata);
2445         case 0xcd: /* fsb frequency */
2446                 data = 3;
2447                 break;
2448                 /*
2449                  * MSR_EBC_FREQUENCY_ID
2450                  * Conservative value valid for even the basic CPU models.
2451                  * Models 0,1: 000 in bits 23:21 indicating a bus speed of
2452                  * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
2453                  * and 266MHz for model 3, or 4. Set Core Clock
2454                  * Frequency to System Bus Frequency Ratio to 1 (bits
2455                  * 31:24) even though these are only valid for CPU
2456                  * models > 2, however guests may end up dividing or
2457                  * multiplying by zero otherwise.
2458                  */
2459         case MSR_EBC_FREQUENCY_ID:
2460                 data = 1 << 24;
2461                 break;
2462         case MSR_IA32_APICBASE:
2463                 data = kvm_get_apic_base(vcpu);
2464                 break;
2465         case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2466                 return kvm_x2apic_msr_read(vcpu, msr, pdata);
2467                 break;
2468         case MSR_IA32_TSCDEADLINE:
2469                 data = kvm_get_lapic_tscdeadline_msr(vcpu);
2470                 break;
2471         case MSR_IA32_TSC_ADJUST:
2472                 data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
2473                 break;
2474         case MSR_IA32_MISC_ENABLE:
2475                 data = vcpu->arch.ia32_misc_enable_msr;
2476                 break;
2477         case MSR_IA32_PERF_STATUS:
2478                 /* TSC increment by tick */
2479                 data = 1000ULL;
2480                 /* CPU multiplier */
2481                 data |= (((uint64_t)4ULL) << 40);
2482                 break;
2483         case MSR_EFER:
2484                 data = vcpu->arch.efer;
2485                 break;
2486         case MSR_KVM_WALL_CLOCK:
2487         case MSR_KVM_WALL_CLOCK_NEW:
2488                 data = vcpu->kvm->arch.wall_clock;
2489                 break;
2490         case MSR_KVM_SYSTEM_TIME:
2491         case MSR_KVM_SYSTEM_TIME_NEW:
2492                 data = vcpu->arch.time;
2493                 break;
2494         case MSR_KVM_ASYNC_PF_EN:
2495                 data = vcpu->arch.apf.msr_val;
2496                 break;
2497         case MSR_KVM_STEAL_TIME:
2498                 data = vcpu->arch.st.msr_val;
2499                 break;
2500         case MSR_KVM_PV_EOI_EN:
2501                 data = vcpu->arch.pv_eoi.msr_val;
2502                 break;
2503         case MSR_IA32_P5_MC_ADDR:
2504         case MSR_IA32_P5_MC_TYPE:
2505         case MSR_IA32_MCG_CAP:
2506         case MSR_IA32_MCG_CTL:
2507         case MSR_IA32_MCG_STATUS:
2508         case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
2509                 return get_msr_mce(vcpu, msr, pdata);
2510         case MSR_K7_CLK_CTL:
2511                 /*
2512                  * Provide expected ramp-up count for K7. All other
2513                  * are set to zero, indicating minimum divisors for
2514                  * every field.
2515                  *
2516                  * This prevents guest kernels on AMD host with CPU
2517                  * type 6, model 8 and higher from exploding due to
2518                  * the rdmsr failing.
2519                  */
2520                 data = 0x20000000;
2521                 break;
2522         case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2523                 if (kvm_hv_msr_partition_wide(msr)) {
2524                         int r;
2525                         mutex_lock(&vcpu->kvm->lock);
2526                         r = get_msr_hyperv_pw(vcpu, msr, pdata);
2527                         mutex_unlock(&vcpu->kvm->lock);
2528                         return r;
2529                 } else
2530                         return get_msr_hyperv(vcpu, msr, pdata);
2531                 break;
2532         case MSR_IA32_BBL_CR_CTL3:
2533                 /* This legacy MSR exists but isn't fully documented in current
2534                  * silicon.  It is however accessed by winxp in very narrow
2535                  * scenarios where it sets bit #19, itself documented as
2536                  * a "reserved" bit.  Best effort attempt to source coherent
2537                  * read data here should the balance of the register be
2538                  * interpreted by the guest:
2539                  *
2540                  * L2 cache control register 3: 64GB range, 256KB size,
2541                  * enabled, latency 0x1, configured
2542                  */
2543                 data = 0xbe702111;
2544                 break;
2545         case MSR_AMD64_OSVW_ID_LENGTH:
2546                 if (!guest_cpuid_has_osvw(vcpu))
2547                         return 1;
2548                 data = vcpu->arch.osvw.length;
2549                 break;
2550         case MSR_AMD64_OSVW_STATUS:
2551                 if (!guest_cpuid_has_osvw(vcpu))
2552                         return 1;
2553                 data = vcpu->arch.osvw.status;
2554                 break;
2555         default:
2556                 if (kvm_pmu_msr(vcpu, msr))
2557                         return kvm_pmu_get_msr(vcpu, msr, pdata);
2558                 if (!ignore_msrs) {
2559                         vcpu_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr);
2560                         return 1;
2561                 } else {
2562                         vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n", msr);
2563                         data = 0;
2564                 }
2565                 break;
2566         }
2567         *pdata = data;
2568         return 0;
2569 }
2570 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
2571
2572 /*
2573  * Read or write a bunch of msrs. All parameters are kernel addresses.
2574  *
2575  * @return number of msrs set successfully.
2576  */
2577 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
2578                     struct kvm_msr_entry *entries,
2579                     int (*do_msr)(struct kvm_vcpu *vcpu,
2580                                   unsigned index, u64 *data))
2581 {
2582         int i, idx;
2583
2584         idx = srcu_read_lock(&vcpu->kvm->srcu);
2585         for (i = 0; i < msrs->nmsrs; ++i)
2586                 if (do_msr(vcpu, entries[i].index, &entries[i].data))
2587                         break;
2588         srcu_read_unlock(&vcpu->kvm->srcu, idx);
2589
2590         return i;
2591 }
2592
2593 /*
2594  * Read or write a bunch of msrs. Parameters are user addresses.
2595  *
2596  * @return number of msrs set successfully.
2597  */
2598 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
2599                   int (*do_msr)(struct kvm_vcpu *vcpu,
2600                                 unsigned index, u64 *data),
2601                   int writeback)
2602 {
2603         struct kvm_msrs msrs;
2604         struct kvm_msr_entry *entries;
2605         int r, n;
2606         unsigned size;
2607
2608         r = -EFAULT;
2609         if (copy_from_user(&msrs, user_msrs, sizeof msrs))
2610                 goto out;
2611
2612         r = -E2BIG;
2613         if (msrs.nmsrs >= MAX_IO_MSRS)
2614                 goto out;
2615
2616         size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
2617         entries = memdup_user(user_msrs->entries, size);
2618         if (IS_ERR(entries)) {
2619                 r = PTR_ERR(entries);
2620                 goto out;
2621         }
2622
2623         r = n = __msr_io(vcpu, &msrs, entries, do_msr);
2624         if (r < 0)
2625                 goto out_free;
2626
2627         r = -EFAULT;
2628         if (writeback && copy_to_user(user_msrs->entries, entries, size))
2629                 goto out_free;
2630
2631         r = n;
2632
2633 out_free:
2634         kfree(entries);
2635 out:
2636         return r;
2637 }
2638
2639 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
2640 {
2641         int r;
2642
2643         switch (ext) {
2644         case KVM_CAP_IRQCHIP:
2645         case KVM_CAP_HLT:
2646         case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
2647         case KVM_CAP_SET_TSS_ADDR:
2648         case KVM_CAP_EXT_CPUID:
2649         case KVM_CAP_EXT_EMUL_CPUID:
2650         case KVM_CAP_CLOCKSOURCE:
2651         case KVM_CAP_PIT:
2652         case KVM_CAP_NOP_IO_DELAY:
2653         case KVM_CAP_MP_STATE:
2654         case KVM_CAP_SYNC_MMU:
2655         case KVM_CAP_USER_NMI:
2656         case KVM_CAP_REINJECT_CONTROL:
2657         case KVM_CAP_IRQ_INJECT_STATUS:
2658         case KVM_CAP_IRQFD:
2659         case KVM_CAP_IOEVENTFD:
2660         case KVM_CAP_IOEVENTFD_NO_LENGTH:
2661         case KVM_CAP_PIT2:
2662         case KVM_CAP_PIT_STATE2:
2663         case KVM_CAP_SET_IDENTITY_MAP_ADDR:
2664         case KVM_CAP_XEN_HVM:
2665         case KVM_CAP_ADJUST_CLOCK:
2666         case KVM_CAP_VCPU_EVENTS:
2667         case KVM_CAP_HYPERV:
2668         case KVM_CAP_HYPERV_VAPIC:
2669         case KVM_CAP_HYPERV_SPIN:
2670         case KVM_CAP_PCI_SEGMENT:
2671         case KVM_CAP_DEBUGREGS:
2672         case KVM_CAP_X86_ROBUST_SINGLESTEP:
2673         case KVM_CAP_XSAVE:
2674         case KVM_CAP_ASYNC_PF:
2675         case KVM_CAP_GET_TSC_KHZ:
2676         case KVM_CAP_KVMCLOCK_CTRL:
2677         case KVM_CAP_READONLY_MEM:
2678         case KVM_CAP_HYPERV_TIME:
2679         case KVM_CAP_IOAPIC_POLARITY_IGNORED:
2680 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
2681         case KVM_CAP_ASSIGN_DEV_IRQ:
2682         case KVM_CAP_PCI_2_3:
2683 #endif
2684                 r = 1;
2685                 break;
2686         case KVM_CAP_COALESCED_MMIO:
2687                 r = KVM_COALESCED_MMIO_PAGE_OFFSET;
2688                 break;
2689         case KVM_CAP_VAPIC:
2690                 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
2691                 break;
2692         case KVM_CAP_NR_VCPUS:
2693                 r = KVM_SOFT_MAX_VCPUS;
2694                 break;
2695         case KVM_CAP_MAX_VCPUS:
2696                 r = KVM_MAX_VCPUS;
2697                 break;
2698         case KVM_CAP_NR_MEMSLOTS:
2699                 r = KVM_USER_MEM_SLOTS;
2700                 break;
2701         case KVM_CAP_PV_MMU:    /* obsolete */
2702                 r = 0;
2703                 break;
2704 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
2705         case KVM_CAP_IOMMU:
2706                 r = iommu_present(&pci_bus_type);
2707                 break;
2708 #endif
2709         case KVM_CAP_MCE:
2710                 r = KVM_MAX_MCE_BANKS;
2711                 break;
2712         case KVM_CAP_XCRS:
2713                 r = cpu_has_xsave;
2714                 break;
2715         case KVM_CAP_TSC_CONTROL:
2716                 r = kvm_has_tsc_control;
2717                 break;
2718         case KVM_CAP_TSC_DEADLINE_TIMER:
2719                 r = boot_cpu_has(X86_FEATURE_TSC_DEADLINE_TIMER);
2720                 break;
2721         default:
2722                 r = 0;
2723                 break;
2724         }
2725         return r;
2726
2727 }
2728
2729 long kvm_arch_dev_ioctl(struct file *filp,
2730                         unsigned int ioctl, unsigned long arg)
2731 {
2732         void __user *argp = (void __user *)arg;
2733         long r;
2734
2735         switch (ioctl) {
2736         case KVM_GET_MSR_INDEX_LIST: {
2737                 struct kvm_msr_list __user *user_msr_list = argp;
2738                 struct kvm_msr_list msr_list;
2739                 unsigned n;
2740
2741                 r = -EFAULT;
2742                 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
2743                         goto out;
2744                 n = msr_list.nmsrs;
2745                 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
2746                 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
2747                         goto out;
2748                 r = -E2BIG;
2749                 if (n < msr_list.nmsrs)
2750                         goto out;
2751                 r = -EFAULT;
2752                 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
2753                                  num_msrs_to_save * sizeof(u32)))
2754                         goto out;
2755                 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
2756                                  &emulated_msrs,
2757                                  ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
2758                         goto out;
2759                 r = 0;
2760                 break;
2761         }
2762         case KVM_GET_SUPPORTED_CPUID:
2763         case KVM_GET_EMULATED_CPUID: {
2764                 struct kvm_cpuid2 __user *cpuid_arg = argp;
2765                 struct kvm_cpuid2 cpuid;
2766
2767                 r = -EFAULT;
2768                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2769                         goto out;
2770
2771                 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
2772                                             ioctl);
2773                 if (r)
2774                         goto out;
2775
2776                 r = -EFAULT;
2777                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
2778                         goto out;
2779                 r = 0;
2780                 break;
2781         }
2782         case KVM_X86_GET_MCE_CAP_SUPPORTED: {
2783                 u64 mce_cap;
2784
2785                 mce_cap = KVM_MCE_CAP_SUPPORTED;
2786                 r = -EFAULT;
2787                 if (copy_to_user(argp, &mce_cap, sizeof mce_cap))
2788                         goto out;
2789                 r = 0;
2790                 break;
2791         }
2792         default:
2793                 r = -EINVAL;
2794         }
2795 out:
2796         return r;
2797 }
2798
2799 static void wbinvd_ipi(void *garbage)
2800 {
2801         wbinvd();
2802 }
2803
2804 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
2805 {
2806         return kvm_arch_has_noncoherent_dma(vcpu->kvm);
2807 }
2808
2809 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2810 {
2811         /* Address WBINVD may be executed by guest */
2812         if (need_emulate_wbinvd(vcpu)) {
2813                 if (kvm_x86_ops->has_wbinvd_exit())
2814                         cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
2815                 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
2816                         smp_call_function_single(vcpu->cpu,
2817                                         wbinvd_ipi, NULL, 1);
2818         }
2819
2820         kvm_x86_ops->vcpu_load(vcpu, cpu);
2821
2822         /* Apply any externally detected TSC adjustments (due to suspend) */
2823         if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
2824                 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
2825                 vcpu->arch.tsc_offset_adjustment = 0;
2826                 set_bit(KVM_REQ_CLOCK_UPDATE, &vcpu->requests);
2827         }
2828
2829         if (unlikely(vcpu->cpu != cpu) || check_tsc_unstable()) {
2830                 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
2831                                 native_read_tsc() - vcpu->arch.last_host_tsc;
2832                 if (tsc_delta < 0)
2833                         mark_tsc_unstable("KVM discovered backwards TSC");
2834                 if (check_tsc_unstable()) {
2835                         u64 offset = kvm_x86_ops->compute_tsc_offset(vcpu,
2836                                                 vcpu->arch.last_guest_tsc);
2837                         kvm_x86_ops->write_tsc_offset(vcpu, offset);
2838                         vcpu->arch.tsc_catchup = 1;
2839                 }
2840                 /*
2841                  * On a host with synchronized TSC, there is no need to update
2842                  * kvmclock on vcpu->cpu migration
2843                  */
2844                 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
2845                         kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2846                 if (vcpu->cpu != cpu)
2847                         kvm_migrate_timers(vcpu);
2848                 vcpu->cpu = cpu;
2849         }
2850
2851         accumulate_steal_time(vcpu);
2852         kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2853 }
2854
2855 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
2856 {
2857         kvm_x86_ops->vcpu_put(vcpu);
2858         kvm_put_guest_fpu(vcpu);
2859         vcpu->arch.last_host_tsc = native_read_tsc();
2860 }
2861
2862 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
2863                                     struct kvm_lapic_state *s)
2864 {
2865         kvm_x86_ops->sync_pir_to_irr(vcpu);
2866         memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
2867
2868         return 0;
2869 }
2870
2871 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
2872                                     struct kvm_lapic_state *s)
2873 {
2874         kvm_apic_post_state_restore(vcpu, s);
2875         update_cr8_intercept(vcpu);
2876
2877         return 0;
2878 }
2879
2880 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
2881                                     struct kvm_interrupt *irq)
2882 {
2883         if (irq->irq >= KVM_NR_INTERRUPTS)
2884                 return -EINVAL;
2885         if (irqchip_in_kernel(vcpu->kvm))
2886                 return -ENXIO;
2887
2888         kvm_queue_interrupt(vcpu, irq->irq, false);
2889         kvm_make_request(KVM_REQ_EVENT, vcpu);
2890
2891         return 0;
2892 }
2893
2894 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
2895 {
2896         kvm_inject_nmi(vcpu);
2897
2898         return 0;
2899 }
2900
2901 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
2902                                            struct kvm_tpr_access_ctl *tac)
2903 {
2904         if (tac->flags)
2905                 return -EINVAL;
2906         vcpu->arch.tpr_access_reporting = !!tac->enabled;
2907         return 0;
2908 }
2909
2910 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
2911                                         u64 mcg_cap)
2912 {
2913         int r;
2914         unsigned bank_num = mcg_cap & 0xff, bank;
2915
2916         r = -EINVAL;
2917         if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
2918                 goto out;
2919         if (mcg_cap & ~(KVM_MCE_CAP_SUPPORTED | 0xff | 0xff0000))
2920                 goto out;
2921         r = 0;
2922         vcpu->arch.mcg_cap = mcg_cap;
2923         /* Init IA32_MCG_CTL to all 1s */
2924         if (mcg_cap & MCG_CTL_P)
2925                 vcpu->arch.mcg_ctl = ~(u64)0;
2926         /* Init IA32_MCi_CTL to all 1s */
2927         for (bank = 0; bank < bank_num; bank++)
2928                 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
2929 out:
2930         return r;
2931 }
2932
2933 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
2934                                       struct kvm_x86_mce *mce)
2935 {
2936         u64 mcg_cap = vcpu->arch.mcg_cap;
2937         unsigned bank_num = mcg_cap & 0xff;
2938         u64 *banks = vcpu->arch.mce_banks;
2939
2940         if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
2941                 return -EINVAL;
2942         /*
2943          * if IA32_MCG_CTL is not all 1s, the uncorrected error
2944          * reporting is disabled
2945          */
2946         if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
2947             vcpu->arch.mcg_ctl != ~(u64)0)
2948                 return 0;
2949         banks += 4 * mce->bank;
2950         /*
2951          * if IA32_MCi_CTL is not all 1s, the uncorrected error
2952          * reporting is disabled for the bank
2953          */
2954         if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
2955                 return 0;
2956         if (mce->status & MCI_STATUS_UC) {
2957                 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
2958                     !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
2959                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2960                         return 0;
2961                 }
2962                 if (banks[1] & MCI_STATUS_VAL)
2963                         mce->status |= MCI_STATUS_OVER;
2964                 banks[2] = mce->addr;
2965                 banks[3] = mce->misc;
2966                 vcpu->arch.mcg_status = mce->mcg_status;
2967                 banks[1] = mce->status;
2968                 kvm_queue_exception(vcpu, MC_VECTOR);
2969         } else if (!(banks[1] & MCI_STATUS_VAL)
2970                    || !(banks[1] & MCI_STATUS_UC)) {
2971                 if (banks[1] & MCI_STATUS_VAL)
2972                         mce->status |= MCI_STATUS_OVER;
2973                 banks[2] = mce->addr;
2974                 banks[3] = mce->misc;
2975                 banks[1] = mce->status;
2976         } else
2977                 banks[1] |= MCI_STATUS_OVER;
2978         return 0;
2979 }
2980
2981 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
2982                                                struct kvm_vcpu_events *events)
2983 {
2984         process_nmi(vcpu);
2985         events->exception.injected =
2986                 vcpu->arch.exception.pending &&
2987                 !kvm_exception_is_soft(vcpu->arch.exception.nr);
2988         events->exception.nr = vcpu->arch.exception.nr;
2989         events->exception.has_error_code = vcpu->arch.exception.has_error_code;
2990         events->exception.pad = 0;
2991         events->exception.error_code = vcpu->arch.exception.error_code;
2992
2993         events->interrupt.injected =
2994                 vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
2995         events->interrupt.nr = vcpu->arch.interrupt.nr;
2996         events->interrupt.soft = 0;
2997         events->interrupt.shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
2998
2999         events->nmi.injected = vcpu->arch.nmi_injected;
3000         events->nmi.pending = vcpu->arch.nmi_pending != 0;
3001         events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
3002         events->nmi.pad = 0;
3003
3004         events->sipi_vector = 0; /* never valid when reporting to user space */
3005
3006         events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
3007                          | KVM_VCPUEVENT_VALID_SHADOW);
3008         memset(&events->reserved, 0, sizeof(events->reserved));
3009 }
3010
3011 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
3012                                               struct kvm_vcpu_events *events)
3013 {
3014         if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
3015                               | KVM_VCPUEVENT_VALID_SIPI_VECTOR
3016                               | KVM_VCPUEVENT_VALID_SHADOW))
3017                 return -EINVAL;
3018
3019         process_nmi(vcpu);
3020         vcpu->arch.exception.pending = events->exception.injected;
3021         vcpu->arch.exception.nr = events->exception.nr;
3022         vcpu->arch.exception.has_error_code = events->exception.has_error_code;
3023         vcpu->arch.exception.error_code = events->exception.error_code;
3024
3025         vcpu->arch.interrupt.pending = events->interrupt.injected;
3026         vcpu->arch.interrupt.nr = events->interrupt.nr;
3027         vcpu->arch.interrupt.soft = events->interrupt.soft;
3028         if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
3029                 kvm_x86_ops->set_interrupt_shadow(vcpu,
3030                                                   events->interrupt.shadow);
3031
3032         vcpu->arch.nmi_injected = events->nmi.injected;
3033         if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
3034                 vcpu->arch.nmi_pending = events->nmi.pending;
3035         kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
3036
3037         if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
3038             kvm_vcpu_has_lapic(vcpu))
3039                 vcpu->arch.apic->sipi_vector = events->sipi_vector;
3040
3041         kvm_make_request(KVM_REQ_EVENT, vcpu);
3042
3043         return 0;
3044 }
3045
3046 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
3047                                              struct kvm_debugregs *dbgregs)
3048 {
3049         unsigned long val;
3050
3051         memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
3052         _kvm_get_dr(vcpu, 6, &val);
3053         dbgregs->dr6 = val;
3054         dbgregs->dr7 = vcpu->arch.dr7;
3055         dbgregs->flags = 0;
3056         memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
3057 }
3058
3059 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
3060                                             struct kvm_debugregs *dbgregs)
3061 {
3062         if (dbgregs->flags)
3063                 return -EINVAL;
3064
3065         memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
3066         vcpu->arch.dr6 = dbgregs->dr6;
3067         kvm_update_dr6(vcpu);
3068         vcpu->arch.dr7 = dbgregs->dr7;
3069         kvm_update_dr7(vcpu);
3070
3071         return 0;
3072 }
3073
3074 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
3075                                          struct kvm_xsave *guest_xsave)
3076 {
3077         if (cpu_has_xsave) {
3078                 memcpy(guest_xsave->region,
3079                         &vcpu->arch.guest_fpu.state->xsave,
3080                         vcpu->arch.guest_xstate_size);
3081                 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] &=
3082                         vcpu->arch.guest_supported_xcr0 | XSTATE_FPSSE;
3083         } else {
3084                 memcpy(guest_xsave->region,
3085                         &vcpu->arch.guest_fpu.state->fxsave,
3086                         sizeof(struct i387_fxsave_struct));
3087                 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
3088                         XSTATE_FPSSE;
3089         }
3090 }
3091
3092 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
3093                                         struct kvm_xsave *guest_xsave)
3094 {
3095         u64 xstate_bv =
3096                 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
3097
3098         if (cpu_has_xsave) {
3099                 /*
3100                  * Here we allow setting states that are not present in
3101                  * CPUID leaf 0xD, index 0, EDX:EAX.  This is for compatibility
3102                  * with old userspace.
3103                  */
3104                 if (xstate_bv & ~kvm_supported_xcr0())
3105                         return -EINVAL;
3106                 memcpy(&vcpu->arch.guest_fpu.state->xsave,
3107                         guest_xsave->region, vcpu->arch.guest_xstate_size);
3108         } else {
3109                 if (xstate_bv & ~XSTATE_FPSSE)
3110                         return -EINVAL;
3111                 memcpy(&vcpu->arch.guest_fpu.state->fxsave,
3112                         guest_xsave->region, sizeof(struct i387_fxsave_struct));
3113         }
3114         return 0;
3115 }
3116
3117 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
3118                                         struct kvm_xcrs *guest_xcrs)
3119 {
3120         if (!cpu_has_xsave) {
3121                 guest_xcrs->nr_xcrs = 0;
3122                 return;
3123         }
3124
3125         guest_xcrs->nr_xcrs = 1;
3126         guest_xcrs->flags = 0;
3127         guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
3128         guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
3129 }
3130
3131 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
3132                                        struct kvm_xcrs *guest_xcrs)
3133 {
3134         int i, r = 0;
3135
3136         if (!cpu_has_xsave)
3137                 return -EINVAL;
3138
3139         if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
3140                 return -EINVAL;
3141
3142         for (i = 0; i < guest_xcrs->nr_xcrs; i++)
3143                 /* Only support XCR0 currently */
3144                 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
3145                         r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
3146                                 guest_xcrs->xcrs[i].value);
3147                         break;
3148                 }
3149         if (r)
3150                 r = -EINVAL;
3151         return r;
3152 }
3153
3154 /*
3155  * kvm_set_guest_paused() indicates to the guest kernel that it has been
3156  * stopped by the hypervisor.  This function will be called from the host only.
3157  * EINVAL is returned when the host attempts to set the flag for a guest that
3158  * does not support pv clocks.
3159  */
3160 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
3161 {
3162         if (!vcpu->arch.pv_time_enabled)
3163                 return -EINVAL;
3164         vcpu->arch.pvclock_set_guest_stopped_request = true;
3165         kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3166         return 0;
3167 }
3168
3169 long kvm_arch_vcpu_ioctl(struct file *filp,
3170                          unsigned int ioctl, unsigned long arg)
3171 {
3172         struct kvm_vcpu *vcpu = filp->private_data;
3173         void __user *argp = (void __user *)arg;
3174         int r;
3175         union {
3176                 struct kvm_lapic_state *lapic;
3177                 struct kvm_xsave *xsave;
3178                 struct kvm_xcrs *xcrs;
3179                 void *buffer;
3180         } u;
3181
3182         u.buffer = NULL;
3183         switch (ioctl) {
3184         case KVM_GET_LAPIC: {
3185                 r = -EINVAL;
3186                 if (!vcpu->arch.apic)
3187                         goto out;
3188                 u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
3189
3190                 r = -ENOMEM;
3191                 if (!u.lapic)
3192                         goto out;
3193                 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
3194                 if (r)
3195                         goto out;
3196                 r = -EFAULT;
3197                 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
3198                         goto out;
3199                 r = 0;
3200                 break;
3201         }
3202         case KVM_SET_LAPIC: {
3203                 r = -EINVAL;
3204                 if (!vcpu->arch.apic)
3205                         goto out;
3206                 u.lapic = memdup_user(argp, sizeof(*u.lapic));
3207                 if (IS_ERR(u.lapic))
3208                         return PTR_ERR(u.lapic);
3209
3210                 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
3211                 break;
3212         }
3213         case KVM_INTERRUPT: {
3214                 struct kvm_interrupt irq;
3215
3216                 r = -EFAULT;
3217                 if (copy_from_user(&irq, argp, sizeof irq))
3218                         goto out;
3219                 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
3220                 break;
3221         }
3222         case KVM_NMI: {
3223                 r = kvm_vcpu_ioctl_nmi(vcpu);
3224                 break;
3225         }
3226         case KVM_SET_CPUID: {
3227                 struct kvm_cpuid __user *cpuid_arg = argp;
3228                 struct kvm_cpuid cpuid;
3229
3230                 r = -EFAULT;
3231                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3232                         goto out;
3233                 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
3234                 break;
3235         }
3236         case KVM_SET_CPUID2: {
3237                 struct kvm_cpuid2 __user *cpuid_arg = argp;
3238                 struct kvm_cpuid2 cpuid;
3239
3240                 r = -EFAULT;
3241                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3242                         goto out;
3243                 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
3244                                               cpuid_arg->entries);
3245                 break;
3246         }
3247         case KVM_GET_CPUID2: {
3248                 struct kvm_cpuid2 __user *cpuid_arg = argp;
3249                 struct kvm_cpuid2 cpuid;
3250
3251                 r = -EFAULT;
3252                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3253                         goto out;
3254                 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
3255                                               cpuid_arg->entries);
3256                 if (r)
3257                         goto out;
3258                 r = -EFAULT;
3259                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
3260                         goto out;
3261                 r = 0;
3262                 break;
3263         }
3264         case KVM_GET_MSRS:
3265                 r = msr_io(vcpu, argp, kvm_get_msr, 1);
3266                 break;
3267         case KVM_SET_MSRS:
3268                 r = msr_io(vcpu, argp, do_set_msr, 0);
3269                 break;
3270         case KVM_TPR_ACCESS_REPORTING: {
3271                 struct kvm_tpr_access_ctl tac;
3272
3273                 r = -EFAULT;
3274                 if (copy_from_user(&tac, argp, sizeof tac))
3275                         goto out;
3276                 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
3277                 if (r)
3278                         goto out;
3279                 r = -EFAULT;
3280                 if (copy_to_user(argp, &tac, sizeof tac))
3281                         goto out;
3282                 r = 0;
3283                 break;
3284         };
3285         case KVM_SET_VAPIC_ADDR: {
3286                 struct kvm_vapic_addr va;
3287
3288                 r = -EINVAL;
3289                 if (!irqchip_in_kernel(vcpu->kvm))
3290                         goto out;
3291                 r = -EFAULT;
3292                 if (copy_from_user(&va, argp, sizeof va))
3293                         goto out;
3294                 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
3295                 break;
3296         }
3297         case KVM_X86_SETUP_MCE: {
3298                 u64 mcg_cap;
3299
3300                 r = -EFAULT;
3301                 if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
3302                         goto out;
3303                 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
3304                 break;
3305         }
3306         case KVM_X86_SET_MCE: {
3307                 struct kvm_x86_mce mce;
3308
3309                 r = -EFAULT;
3310                 if (copy_from_user(&mce, argp, sizeof mce))
3311                         goto out;
3312                 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
3313                 break;
3314         }
3315         case KVM_GET_VCPU_EVENTS: {
3316                 struct kvm_vcpu_events events;
3317
3318                 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
3319
3320                 r = -EFAULT;
3321                 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
3322                         break;
3323                 r = 0;
3324                 break;
3325         }
3326         case KVM_SET_VCPU_EVENTS: {
3327                 struct kvm_vcpu_events events;
3328
3329                 r = -EFAULT;
3330                 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
3331                         break;
3332
3333                 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
3334                 break;
3335         }
3336         case KVM_GET_DEBUGREGS: {
3337                 struct kvm_debugregs dbgregs;
3338
3339                 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
3340
3341                 r = -EFAULT;
3342                 if (copy_to_user(argp, &dbgregs,
3343                                  sizeof(struct kvm_debugregs)))
3344                         break;
3345                 r = 0;
3346                 break;
3347         }
3348         case KVM_SET_DEBUGREGS: {
3349                 struct kvm_debugregs dbgregs;
3350
3351                 r = -EFAULT;
3352                 if (copy_from_user(&dbgregs, argp,
3353                                    sizeof(struct kvm_debugregs)))
3354                         break;
3355
3356                 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
3357                 break;
3358         }
3359         case KVM_GET_XSAVE: {
3360                 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
3361                 r = -ENOMEM;
3362                 if (!u.xsave)
3363                         break;
3364
3365                 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
3366
3367                 r = -EFAULT;
3368                 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
3369                         break;
3370                 r = 0;
3371                 break;
3372         }
3373         case KVM_SET_XSAVE: {
3374                 u.xsave = memdup_user(argp, sizeof(*u.xsave));
3375                 if (IS_ERR(u.xsave))
3376                         return PTR_ERR(u.xsave);
3377
3378                 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
3379                 break;
3380         }
3381         case KVM_GET_XCRS: {
3382                 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
3383                 r = -ENOMEM;
3384                 if (!u.xcrs)
3385                         break;
3386
3387                 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
3388
3389                 r = -EFAULT;
3390                 if (copy_to_user(argp, u.xcrs,
3391                                  sizeof(struct kvm_xcrs)))
3392                         break;
3393                 r = 0;
3394                 break;
3395         }
3396         case KVM_SET_XCRS: {
3397                 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
3398                 if (IS_ERR(u.xcrs))
3399                         return PTR_ERR(u.xcrs);
3400
3401                 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
3402                 break;
3403         }
3404         case KVM_SET_TSC_KHZ: {
3405                 u32 user_tsc_khz;
3406
3407                 r = -EINVAL;
3408                 user_tsc_khz = (u32)arg;
3409
3410                 if (user_tsc_khz >= kvm_max_guest_tsc_khz)
3411                         goto out;
3412
3413                 if (user_tsc_khz == 0)
3414                         user_tsc_khz = tsc_khz;
3415
3416                 kvm_set_tsc_khz(vcpu, user_tsc_khz);
3417
3418                 r = 0;
3419                 goto out;
3420         }
3421         case KVM_GET_TSC_KHZ: {
3422                 r = vcpu->arch.virtual_tsc_khz;
3423                 goto out;
3424         }
3425         case KVM_KVMCLOCK_CTRL: {
3426                 r = kvm_set_guest_paused(vcpu);
3427                 goto out;
3428         }
3429         default:
3430                 r = -EINVAL;
3431         }
3432 out:
3433         kfree(u.buffer);
3434         return r;
3435 }
3436
3437 int kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
3438 {
3439         return VM_FAULT_SIGBUS;
3440 }
3441
3442 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
3443 {
3444         int ret;
3445
3446         if (addr > (unsigned int)(-3 * PAGE_SIZE))
3447                 return -EINVAL;
3448         ret = kvm_x86_ops->set_tss_addr(kvm, addr);
3449         return ret;
3450 }
3451
3452 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
3453                                               u64 ident_addr)
3454 {
3455         kvm->arch.ept_identity_map_addr = ident_addr;
3456         return 0;
3457 }
3458
3459 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
3460                                           u32 kvm_nr_mmu_pages)
3461 {
3462         if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
3463                 return -EINVAL;
3464
3465         mutex_lock(&kvm->slots_lock);
3466
3467         kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
3468         kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
3469
3470         mutex_unlock(&kvm->slots_lock);
3471         return 0;
3472 }
3473
3474 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
3475 {
3476         return kvm->arch.n_max_mmu_pages;
3477 }
3478
3479 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3480 {
3481         int r;
3482
3483         r = 0;
3484         switch (chip->chip_id) {
3485         case KVM_IRQCHIP_PIC_MASTER:
3486                 memcpy(&chip->chip.pic,
3487                         &pic_irqchip(kvm)->pics[0],
3488                         sizeof(struct kvm_pic_state));
3489                 break;
3490         case KVM_IRQCHIP_PIC_SLAVE:
3491                 memcpy(&chip->chip.pic,
3492                         &pic_irqchip(kvm)->pics[1],
3493                         sizeof(struct kvm_pic_state));
3494                 break;
3495         case KVM_IRQCHIP_IOAPIC:
3496                 r = kvm_get_ioapic(kvm, &chip->chip.ioapic);
3497                 break;
3498         default:
3499                 r = -EINVAL;
3500                 break;
3501         }
3502         return r;
3503 }
3504
3505 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3506 {
3507         int r;
3508
3509         r = 0;
3510         switch (chip->chip_id) {
3511         case KVM_IRQCHIP_PIC_MASTER:
3512                 spin_lock(&pic_irqchip(kvm)->lock);
3513                 memcpy(&pic_irqchip(kvm)->pics[0],
3514                         &chip->chip.pic,
3515                         sizeof(struct kvm_pic_state));
3516                 spin_unlock(&pic_irqchip(kvm)->lock);
3517                 break;
3518         case KVM_IRQCHIP_PIC_SLAVE:
3519                 spin_lock(&pic_irqchip(kvm)->lock);
3520                 memcpy(&pic_irqchip(kvm)->pics[1],
3521                         &chip->chip.pic,
3522                         sizeof(struct kvm_pic_state));
3523                 spin_unlock(&pic_irqchip(kvm)->lock);
3524                 break;
3525         case KVM_IRQCHIP_IOAPIC:
3526                 r = kvm_set_ioapic(kvm, &chip->chip.ioapic);
3527                 break;
3528         default:
3529                 r = -EINVAL;
3530                 break;
3531         }
3532         kvm_pic_update_irq(pic_irqchip(kvm));
3533         return r;
3534 }
3535
3536 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3537 {
3538         int r = 0;
3539
3540         mutex_lock(&kvm->arch.vpit->pit_state.lock);
3541         memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
3542         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3543         return r;
3544 }
3545
3546 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3547 {
3548         int r = 0;
3549
3550         mutex_lock(&kvm->arch.vpit->pit_state.lock);
3551         memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
3552         kvm_pit_load_count(kvm, 0, ps->channels[0].count, 0);
3553         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3554         return r;
3555 }
3556
3557 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3558 {
3559         int r = 0;
3560
3561         mutex_lock(&kvm->arch.vpit->pit_state.lock);
3562         memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
3563                 sizeof(ps->channels));
3564         ps->flags = kvm->arch.vpit->pit_state.flags;
3565         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3566         memset(&ps->reserved, 0, sizeof(ps->reserved));
3567         return r;
3568 }
3569
3570 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3571 {
3572         int r = 0, start = 0;
3573         u32 prev_legacy, cur_legacy;
3574         mutex_lock(&kvm->arch.vpit->pit_state.lock);
3575         prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
3576         cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
3577         if (!prev_legacy && cur_legacy)
3578                 start = 1;
3579         memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
3580                sizeof(kvm->arch.vpit->pit_state.channels));
3581         kvm->arch.vpit->pit_state.flags = ps->flags;
3582         kvm_pit_load_count(kvm, 0, kvm->arch.vpit->pit_state.channels[0].count, start);
3583         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3584         return r;
3585 }
3586
3587 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
3588                                  struct kvm_reinject_control *control)
3589 {
3590         if (!kvm->arch.vpit)
3591                 return -ENXIO;
3592         mutex_lock(&kvm->arch.vpit->pit_state.lock);
3593         kvm->arch.vpit->pit_state.reinject = control->pit_reinject;
3594         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3595         return 0;
3596 }
3597
3598 /**
3599  * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
3600  * @kvm: kvm instance
3601  * @log: slot id and address to which we copy the log
3602  *
3603  * We need to keep it in mind that VCPU threads can write to the bitmap
3604  * concurrently.  So, to avoid losing data, we keep the following order for
3605  * each bit:
3606  *
3607  *   1. Take a snapshot of the bit and clear it if needed.
3608  *   2. Write protect the corresponding page.
3609  *   3. Flush TLB's if needed.
3610  *   4. Copy the snapshot to the userspace.
3611  *
3612  * Between 2 and 3, the guest may write to the page using the remaining TLB
3613  * entry.  This is not a problem because the page will be reported dirty at
3614  * step 4 using the snapshot taken before and step 3 ensures that successive
3615  * writes will be logged for the next call.
3616  */
3617 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
3618 {
3619         int r;
3620         struct kvm_memory_slot *memslot;
3621         unsigned long n, i;
3622         unsigned long *dirty_bitmap;
3623         unsigned long *dirty_bitmap_buffer;
3624         bool is_dirty = false;
3625
3626         mutex_lock(&kvm->slots_lock);
3627
3628         r = -EINVAL;
3629         if (log->slot >= KVM_USER_MEM_SLOTS)
3630                 goto out;
3631
3632         memslot = id_to_memslot(kvm->memslots, log->slot);
3633
3634         dirty_bitmap = memslot->dirty_bitmap;
3635         r = -ENOENT;
3636         if (!dirty_bitmap)
3637                 goto out;
3638
3639         n = kvm_dirty_bitmap_bytes(memslot);
3640
3641         dirty_bitmap_buffer = dirty_bitmap + n / sizeof(long);
3642         memset(dirty_bitmap_buffer, 0, n);
3643
3644         spin_lock(&kvm->mmu_lock);
3645
3646         for (i = 0; i < n / sizeof(long); i++) {
3647                 unsigned long mask;
3648                 gfn_t offset;
3649
3650                 if (!dirty_bitmap[i])
3651                         continue;
3652
3653                 is_dirty = true;
3654
3655                 mask = xchg(&dirty_bitmap[i], 0);
3656                 dirty_bitmap_buffer[i] = mask;
3657
3658                 offset = i * BITS_PER_LONG;
3659                 kvm_mmu_write_protect_pt_masked(kvm, memslot, offset, mask);
3660         }
3661
3662         spin_unlock(&kvm->mmu_lock);
3663
3664         /* See the comments in kvm_mmu_slot_remove_write_access(). */
3665         lockdep_assert_held(&kvm->slots_lock);
3666
3667         /*
3668          * All the TLBs can be flushed out of mmu lock, see the comments in
3669          * kvm_mmu_slot_remove_write_access().
3670          */
3671         if (is_dirty)
3672                 kvm_flush_remote_tlbs(kvm);
3673
3674         r = -EFAULT;
3675         if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
3676                 goto out;
3677
3678         r = 0;
3679 out:
3680         mutex_unlock(&kvm->slots_lock);
3681         return r;
3682 }
3683
3684 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
3685                         bool line_status)
3686 {
3687         if (!irqchip_in_kernel(kvm))
3688                 return -ENXIO;
3689
3690         irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
3691                                         irq_event->irq, irq_event->level,
3692                                         line_status);
3693         return 0;
3694 }
3695
3696 long kvm_arch_vm_ioctl(struct file *filp,
3697                        unsigned int ioctl, unsigned long arg)
3698 {
3699         struct kvm *kvm = filp->private_data;
3700         void __user *argp = (void __user *)arg;
3701         int r = -ENOTTY;
3702         /*
3703          * This union makes it completely explicit to gcc-3.x
3704          * that these two variables' stack usage should be
3705          * combined, not added together.
3706          */
3707         union {
3708                 struct kvm_pit_state ps;
3709                 struct kvm_pit_state2 ps2;
3710                 struct kvm_pit_config pit_config;
3711         } u;
3712
3713         switch (ioctl) {
3714         case KVM_SET_TSS_ADDR:
3715                 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
3716                 break;
3717         case KVM_SET_IDENTITY_MAP_ADDR: {
3718                 u64 ident_addr;
3719
3720                 r = -EFAULT;
3721                 if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
3722                         goto out;
3723                 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
3724                 break;
3725         }
3726         case KVM_SET_NR_MMU_PAGES:
3727                 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
3728                 break;
3729         case KVM_GET_NR_MMU_PAGES:
3730                 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
3731                 break;
3732         case KVM_CREATE_IRQCHIP: {
3733                 struct kvm_pic *vpic;
3734
3735                 mutex_lock(&kvm->lock);
3736                 r = -EEXIST;
3737                 if (kvm->arch.vpic)
3738                         goto create_irqchip_unlock;
3739                 r = -EINVAL;
3740                 if (atomic_read(&kvm->online_vcpus))
3741                         goto create_irqchip_unlock;
3742                 r = -ENOMEM;
3743                 vpic = kvm_create_pic(kvm);
3744                 if (vpic) {
3745                         r = kvm_ioapic_init(kvm);
3746                         if (r) {
3747                                 mutex_lock(&kvm->slots_lock);
3748                                 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3749                                                           &vpic->dev_master);
3750                                 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3751                                                           &vpic->dev_slave);
3752                                 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
3753                                                           &vpic->dev_eclr);
3754                                 mutex_unlock(&kvm->slots_lock);
3755                                 kfree(vpic);
3756                                 goto create_irqchip_unlock;
3757                         }
3758                 } else
3759                         goto create_irqchip_unlock;
3760                 smp_wmb();
3761                 kvm->arch.vpic = vpic;
3762                 smp_wmb();
3763                 r = kvm_setup_default_irq_routing(kvm);
3764                 if (r) {
3765                         mutex_lock(&kvm->slots_lock);
3766                         mutex_lock(&kvm->irq_lock);
3767                         kvm_ioapic_destroy(kvm);
3768                         kvm_destroy_pic(kvm);
3769                         mutex_unlock(&kvm->irq_lock);
3770                         mutex_unlock(&kvm->slots_lock);
3771                 }
3772         create_irqchip_unlock:
3773                 mutex_unlock(&kvm->lock);
3774                 break;
3775         }
3776         case KVM_CREATE_PIT:
3777                 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
3778                 goto create_pit;
3779         case KVM_CREATE_PIT2:
3780                 r = -EFAULT;
3781                 if (copy_from_user(&u.pit_config, argp,
3782                                    sizeof(struct kvm_pit_config)))
3783                         goto out;
3784         create_pit:
3785                 mutex_lock(&kvm->slots_lock);
3786                 r = -EEXIST;
3787                 if (kvm->arch.vpit)
3788                         goto create_pit_unlock;
3789                 r = -ENOMEM;
3790                 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
3791                 if (kvm->arch.vpit)
3792                         r = 0;
3793         create_pit_unlock:
3794                 mutex_unlock(&kvm->slots_lock);
3795                 break;
3796         case KVM_GET_IRQCHIP: {
3797                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3798                 struct kvm_irqchip *chip;
3799
3800                 chip = memdup_user(argp, sizeof(*chip));
3801                 if (IS_ERR(chip)) {
3802                         r = PTR_ERR(chip);
3803                         goto out;
3804                 }
3805
3806                 r = -ENXIO;
3807                 if (!irqchip_in_kernel(kvm))
3808                         goto get_irqchip_out;
3809                 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
3810                 if (r)
3811                         goto get_irqchip_out;
3812                 r = -EFAULT;
3813                 if (copy_to_user(argp, chip, sizeof *chip))
3814                         goto get_irqchip_out;
3815                 r = 0;
3816         get_irqchip_out:
3817                 kfree(chip);
3818                 break;
3819         }
3820         case KVM_SET_IRQCHIP: {
3821                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3822                 struct kvm_irqchip *chip;
3823
3824                 chip = memdup_user(argp, sizeof(*chip));
3825                 if (IS_ERR(chip)) {
3826                         r = PTR_ERR(chip);
3827                         goto out;
3828                 }
3829
3830                 r = -ENXIO;
3831                 if (!irqchip_in_kernel(kvm))
3832                         goto set_irqchip_out;
3833                 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
3834                 if (r)
3835                         goto set_irqchip_out;
3836                 r = 0;
3837         set_irqchip_out:
3838                 kfree(chip);
3839                 break;
3840         }