xref: /openbmc/linux/arch/mips/kvm/mips.c (revision b1a79260)
1 /*
2  * This file is subject to the terms and conditions of the GNU General Public
3  * License.  See the file "COPYING" in the main directory of this archive
4  * for more details.
5  *
6  * KVM/MIPS: MIPS specific KVM APIs
7  *
8  * Copyright (C) 2012  MIPS Technologies, Inc.  All rights reserved.
9  * Authors: Sanjay Lal <sanjayl@kymasys.com>
10  */
11 
12 #include <linux/bitops.h>
13 #include <linux/errno.h>
14 #include <linux/err.h>
15 #include <linux/kdebug.h>
16 #include <linux/module.h>
17 #include <linux/uaccess.h>
18 #include <linux/vmalloc.h>
19 #include <linux/sched/signal.h>
20 #include <linux/fs.h>
21 #include <linux/memblock.h>
22 #include <linux/pgtable.h>
23 
24 #include <asm/fpu.h>
25 #include <asm/page.h>
26 #include <asm/cacheflush.h>
27 #include <asm/mmu_context.h>
28 #include <asm/pgalloc.h>
29 
30 #include <linux/kvm_host.h>
31 
32 #include "interrupt.h"
33 
34 #define CREATE_TRACE_POINTS
35 #include "trace.h"
36 
37 #ifndef VECTORSPACING
38 #define VECTORSPACING 0x100	/* for EI/VI mode */
39 #endif
40 
41 struct kvm_stats_debugfs_item debugfs_entries[] = {
42 	VCPU_STAT("wait", wait_exits),
43 	VCPU_STAT("cache", cache_exits),
44 	VCPU_STAT("signal", signal_exits),
45 	VCPU_STAT("interrupt", int_exits),
46 	VCPU_STAT("cop_unusable", cop_unusable_exits),
47 	VCPU_STAT("tlbmod", tlbmod_exits),
48 	VCPU_STAT("tlbmiss_ld", tlbmiss_ld_exits),
49 	VCPU_STAT("tlbmiss_st", tlbmiss_st_exits),
50 	VCPU_STAT("addrerr_st", addrerr_st_exits),
51 	VCPU_STAT("addrerr_ld", addrerr_ld_exits),
52 	VCPU_STAT("syscall", syscall_exits),
53 	VCPU_STAT("resvd_inst", resvd_inst_exits),
54 	VCPU_STAT("break_inst", break_inst_exits),
55 	VCPU_STAT("trap_inst", trap_inst_exits),
56 	VCPU_STAT("msa_fpe", msa_fpe_exits),
57 	VCPU_STAT("fpe", fpe_exits),
58 	VCPU_STAT("msa_disabled", msa_disabled_exits),
59 	VCPU_STAT("flush_dcache", flush_dcache_exits),
60 	VCPU_STAT("vz_gpsi", vz_gpsi_exits),
61 	VCPU_STAT("vz_gsfc", vz_gsfc_exits),
62 	VCPU_STAT("vz_hc", vz_hc_exits),
63 	VCPU_STAT("vz_grr", vz_grr_exits),
64 	VCPU_STAT("vz_gva", vz_gva_exits),
65 	VCPU_STAT("vz_ghfc", vz_ghfc_exits),
66 	VCPU_STAT("vz_gpa", vz_gpa_exits),
67 	VCPU_STAT("vz_resvd", vz_resvd_exits),
68 #ifdef CONFIG_CPU_LOONGSON64
69 	VCPU_STAT("vz_cpucfg", vz_cpucfg_exits),
70 #endif
71 	VCPU_STAT("halt_successful_poll", halt_successful_poll),
72 	VCPU_STAT("halt_attempted_poll", halt_attempted_poll),
73 	VCPU_STAT("halt_poll_invalid", halt_poll_invalid),
74 	VCPU_STAT("halt_wakeup", halt_wakeup),
75 	VCPU_STAT("halt_poll_success_ns", halt_poll_success_ns),
76 	VCPU_STAT("halt_poll_fail_ns", halt_poll_fail_ns),
77 	{NULL}
78 };
79 
80 bool kvm_trace_guest_mode_change;
81 
82 int kvm_guest_mode_change_trace_reg(void)
83 {
84 	kvm_trace_guest_mode_change = true;
85 	return 0;
86 }
87 
88 void kvm_guest_mode_change_trace_unreg(void)
89 {
90 	kvm_trace_guest_mode_change = false;
91 }
92 
93 /*
94  * XXXKYMA: We are simulatoring a processor that has the WII bit set in
95  * Config7, so we are "runnable" if interrupts are pending
96  */
97 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
98 {
99 	return !!(vcpu->arch.pending_exceptions);
100 }
101 
102 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
103 {
104 	return false;
105 }
106 
107 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
108 {
109 	return 1;
110 }
111 
112 int kvm_arch_hardware_enable(void)
113 {
114 	return kvm_mips_callbacks->hardware_enable();
115 }
116 
117 void kvm_arch_hardware_disable(void)
118 {
119 	kvm_mips_callbacks->hardware_disable();
120 }
121 
122 int kvm_arch_hardware_setup(void *opaque)
123 {
124 	return 0;
125 }
126 
127 int kvm_arch_check_processor_compat(void *opaque)
128 {
129 	return 0;
130 }
131 
132 extern void kvm_init_loongson_ipi(struct kvm *kvm);
133 
134 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
135 {
136 	switch (type) {
137 	case KVM_VM_MIPS_AUTO:
138 		break;
139 	case KVM_VM_MIPS_VZ:
140 		break;
141 	default:
142 		/* Unsupported KVM type */
143 		return -EINVAL;
144 	}
145 
146 	/* Allocate page table to map GPA -> RPA */
147 	kvm->arch.gpa_mm.pgd = kvm_pgd_alloc();
148 	if (!kvm->arch.gpa_mm.pgd)
149 		return -ENOMEM;
150 
151 #ifdef CONFIG_CPU_LOONGSON64
152 	kvm_init_loongson_ipi(kvm);
153 #endif
154 
155 	return 0;
156 }
157 
158 void kvm_mips_free_vcpus(struct kvm *kvm)
159 {
160 	unsigned int i;
161 	struct kvm_vcpu *vcpu;
162 
163 	kvm_for_each_vcpu(i, vcpu, kvm) {
164 		kvm_vcpu_destroy(vcpu);
165 	}
166 
167 	mutex_lock(&kvm->lock);
168 
169 	for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
170 		kvm->vcpus[i] = NULL;
171 
172 	atomic_set(&kvm->online_vcpus, 0);
173 
174 	mutex_unlock(&kvm->lock);
175 }
176 
177 static void kvm_mips_free_gpa_pt(struct kvm *kvm)
178 {
179 	/* It should always be safe to remove after flushing the whole range */
180 	WARN_ON(!kvm_mips_flush_gpa_pt(kvm, 0, ~0));
181 	pgd_free(NULL, kvm->arch.gpa_mm.pgd);
182 }
183 
184 void kvm_arch_destroy_vm(struct kvm *kvm)
185 {
186 	kvm_mips_free_vcpus(kvm);
187 	kvm_mips_free_gpa_pt(kvm);
188 }
189 
190 long kvm_arch_dev_ioctl(struct file *filp, unsigned int ioctl,
191 			unsigned long arg)
192 {
193 	return -ENOIOCTLCMD;
194 }
195 
196 void kvm_arch_flush_shadow_all(struct kvm *kvm)
197 {
198 	/* Flush whole GPA */
199 	kvm_mips_flush_gpa_pt(kvm, 0, ~0);
200 
201 	/* Let implementation do the rest */
202 	kvm_mips_callbacks->flush_shadow_all(kvm);
203 }
204 
205 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
206 				   struct kvm_memory_slot *slot)
207 {
208 	/*
209 	 * The slot has been made invalid (ready for moving or deletion), so we
210 	 * need to ensure that it can no longer be accessed by any guest VCPUs.
211 	 */
212 
213 	spin_lock(&kvm->mmu_lock);
214 	/* Flush slot from GPA */
215 	kvm_mips_flush_gpa_pt(kvm, slot->base_gfn,
216 			      slot->base_gfn + slot->npages - 1);
217 	/* Let implementation do the rest */
218 	kvm_mips_callbacks->flush_shadow_memslot(kvm, slot);
219 	spin_unlock(&kvm->mmu_lock);
220 }
221 
222 int kvm_arch_prepare_memory_region(struct kvm *kvm,
223 				   struct kvm_memory_slot *memslot,
224 				   const struct kvm_userspace_memory_region *mem,
225 				   enum kvm_mr_change change)
226 {
227 	return 0;
228 }
229 
230 void kvm_arch_commit_memory_region(struct kvm *kvm,
231 				   const struct kvm_userspace_memory_region *mem,
232 				   struct kvm_memory_slot *old,
233 				   const struct kvm_memory_slot *new,
234 				   enum kvm_mr_change change)
235 {
236 	int needs_flush;
237 
238 	kvm_debug("%s: kvm: %p slot: %d, GPA: %llx, size: %llx, QVA: %llx\n",
239 		  __func__, kvm, mem->slot, mem->guest_phys_addr,
240 		  mem->memory_size, mem->userspace_addr);
241 
242 	/*
243 	 * If dirty page logging is enabled, write protect all pages in the slot
244 	 * ready for dirty logging.
245 	 *
246 	 * There is no need to do this in any of the following cases:
247 	 * CREATE:	No dirty mappings will already exist.
248 	 * MOVE/DELETE:	The old mappings will already have been cleaned up by
249 	 *		kvm_arch_flush_shadow_memslot()
250 	 */
251 	if (change == KVM_MR_FLAGS_ONLY &&
252 	    (!(old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
253 	     new->flags & KVM_MEM_LOG_DIRTY_PAGES)) {
254 		spin_lock(&kvm->mmu_lock);
255 		/* Write protect GPA page table entries */
256 		needs_flush = kvm_mips_mkclean_gpa_pt(kvm, new->base_gfn,
257 					new->base_gfn + new->npages - 1);
258 		/* Let implementation do the rest */
259 		if (needs_flush)
260 			kvm_mips_callbacks->flush_shadow_memslot(kvm, new);
261 		spin_unlock(&kvm->mmu_lock);
262 	}
263 }
264 
265 static inline void dump_handler(const char *symbol, void *start, void *end)
266 {
267 	u32 *p;
268 
269 	pr_debug("LEAF(%s)\n", symbol);
270 
271 	pr_debug("\t.set push\n");
272 	pr_debug("\t.set noreorder\n");
273 
274 	for (p = start; p < (u32 *)end; ++p)
275 		pr_debug("\t.word\t0x%08x\t\t# %p\n", *p, p);
276 
277 	pr_debug("\t.set\tpop\n");
278 
279 	pr_debug("\tEND(%s)\n", symbol);
280 }
281 
282 /* low level hrtimer wake routine */
283 static enum hrtimer_restart kvm_mips_comparecount_wakeup(struct hrtimer *timer)
284 {
285 	struct kvm_vcpu *vcpu;
286 
287 	vcpu = container_of(timer, struct kvm_vcpu, arch.comparecount_timer);
288 
289 	kvm_mips_callbacks->queue_timer_int(vcpu);
290 
291 	vcpu->arch.wait = 0;
292 	rcuwait_wake_up(&vcpu->wait);
293 
294 	return kvm_mips_count_timeout(vcpu);
295 }
296 
297 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
298 {
299 	return 0;
300 }
301 
302 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
303 {
304 	int err, size;
305 	void *gebase, *p, *handler, *refill_start, *refill_end;
306 	int i;
307 
308 	kvm_debug("kvm @ %p: create cpu %d at %p\n",
309 		  vcpu->kvm, vcpu->vcpu_id, vcpu);
310 
311 	err = kvm_mips_callbacks->vcpu_init(vcpu);
312 	if (err)
313 		return err;
314 
315 	hrtimer_init(&vcpu->arch.comparecount_timer, CLOCK_MONOTONIC,
316 		     HRTIMER_MODE_REL);
317 	vcpu->arch.comparecount_timer.function = kvm_mips_comparecount_wakeup;
318 
319 	/*
320 	 * Allocate space for host mode exception handlers that handle
321 	 * guest mode exits
322 	 */
323 	if (cpu_has_veic || cpu_has_vint)
324 		size = 0x200 + VECTORSPACING * 64;
325 	else
326 		size = 0x4000;
327 
328 	gebase = kzalloc(ALIGN(size, PAGE_SIZE), GFP_KERNEL);
329 
330 	if (!gebase) {
331 		err = -ENOMEM;
332 		goto out_uninit_vcpu;
333 	}
334 	kvm_debug("Allocated %d bytes for KVM Exception Handlers @ %p\n",
335 		  ALIGN(size, PAGE_SIZE), gebase);
336 
337 	/*
338 	 * Check new ebase actually fits in CP0_EBase. The lack of a write gate
339 	 * limits us to the low 512MB of physical address space. If the memory
340 	 * we allocate is out of range, just give up now.
341 	 */
342 	if (!cpu_has_ebase_wg && virt_to_phys(gebase) >= 0x20000000) {
343 		kvm_err("CP0_EBase.WG required for guest exception base %pK\n",
344 			gebase);
345 		err = -ENOMEM;
346 		goto out_free_gebase;
347 	}
348 
349 	/* Save new ebase */
350 	vcpu->arch.guest_ebase = gebase;
351 
352 	/* Build guest exception vectors dynamically in unmapped memory */
353 	handler = gebase + 0x2000;
354 
355 	/* TLB refill (or XTLB refill on 64-bit VZ where KX=1) */
356 	refill_start = gebase;
357 	if (IS_ENABLED(CONFIG_64BIT))
358 		refill_start += 0x080;
359 	refill_end = kvm_mips_build_tlb_refill_exception(refill_start, handler);
360 
361 	/* General Exception Entry point */
362 	kvm_mips_build_exception(gebase + 0x180, handler);
363 
364 	/* For vectored interrupts poke the exception code @ all offsets 0-7 */
365 	for (i = 0; i < 8; i++) {
366 		kvm_debug("L1 Vectored handler @ %p\n",
367 			  gebase + 0x200 + (i * VECTORSPACING));
368 		kvm_mips_build_exception(gebase + 0x200 + i * VECTORSPACING,
369 					 handler);
370 	}
371 
372 	/* General exit handler */
373 	p = handler;
374 	p = kvm_mips_build_exit(p);
375 
376 	/* Guest entry routine */
377 	vcpu->arch.vcpu_run = p;
378 	p = kvm_mips_build_vcpu_run(p);
379 
380 	/* Dump the generated code */
381 	pr_debug("#include <asm/asm.h>\n");
382 	pr_debug("#include <asm/regdef.h>\n");
383 	pr_debug("\n");
384 	dump_handler("kvm_vcpu_run", vcpu->arch.vcpu_run, p);
385 	dump_handler("kvm_tlb_refill", refill_start, refill_end);
386 	dump_handler("kvm_gen_exc", gebase + 0x180, gebase + 0x200);
387 	dump_handler("kvm_exit", gebase + 0x2000, vcpu->arch.vcpu_run);
388 
389 	/* Invalidate the icache for these ranges */
390 	flush_icache_range((unsigned long)gebase,
391 			   (unsigned long)gebase + ALIGN(size, PAGE_SIZE));
392 
393 	/* Init */
394 	vcpu->arch.last_sched_cpu = -1;
395 	vcpu->arch.last_exec_cpu = -1;
396 
397 	/* Initial guest state */
398 	err = kvm_mips_callbacks->vcpu_setup(vcpu);
399 	if (err)
400 		goto out_free_gebase;
401 
402 	return 0;
403 
404 out_free_gebase:
405 	kfree(gebase);
406 out_uninit_vcpu:
407 	kvm_mips_callbacks->vcpu_uninit(vcpu);
408 	return err;
409 }
410 
411 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
412 {
413 	hrtimer_cancel(&vcpu->arch.comparecount_timer);
414 
415 	kvm_mips_dump_stats(vcpu);
416 
417 	kvm_mmu_free_memory_caches(vcpu);
418 	kfree(vcpu->arch.guest_ebase);
419 
420 	kvm_mips_callbacks->vcpu_uninit(vcpu);
421 }
422 
423 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
424 					struct kvm_guest_debug *dbg)
425 {
426 	return -ENOIOCTLCMD;
427 }
428 
429 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
430 {
431 	int r = -EINTR;
432 
433 	vcpu_load(vcpu);
434 
435 	kvm_sigset_activate(vcpu);
436 
437 	if (vcpu->mmio_needed) {
438 		if (!vcpu->mmio_is_write)
439 			kvm_mips_complete_mmio_load(vcpu);
440 		vcpu->mmio_needed = 0;
441 	}
442 
443 	if (vcpu->run->immediate_exit)
444 		goto out;
445 
446 	lose_fpu(1);
447 
448 	local_irq_disable();
449 	guest_enter_irqoff();
450 	trace_kvm_enter(vcpu);
451 
452 	/*
453 	 * Make sure the read of VCPU requests in vcpu_run() callback is not
454 	 * reordered ahead of the write to vcpu->mode, or we could miss a TLB
455 	 * flush request while the requester sees the VCPU as outside of guest
456 	 * mode and not needing an IPI.
457 	 */
458 	smp_store_mb(vcpu->mode, IN_GUEST_MODE);
459 
460 	r = kvm_mips_callbacks->vcpu_run(vcpu);
461 
462 	trace_kvm_out(vcpu);
463 	guest_exit_irqoff();
464 	local_irq_enable();
465 
466 out:
467 	kvm_sigset_deactivate(vcpu);
468 
469 	vcpu_put(vcpu);
470 	return r;
471 }
472 
473 int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
474 			     struct kvm_mips_interrupt *irq)
475 {
476 	int intr = (int)irq->irq;
477 	struct kvm_vcpu *dvcpu = NULL;
478 
479 	if (intr == kvm_priority_to_irq[MIPS_EXC_INT_IPI_1] ||
480 	    intr == kvm_priority_to_irq[MIPS_EXC_INT_IPI_2] ||
481 	    intr == (-kvm_priority_to_irq[MIPS_EXC_INT_IPI_1]) ||
482 	    intr == (-kvm_priority_to_irq[MIPS_EXC_INT_IPI_2]))
483 		kvm_debug("%s: CPU: %d, INTR: %d\n", __func__, irq->cpu,
484 			  (int)intr);
485 
486 	if (irq->cpu == -1)
487 		dvcpu = vcpu;
488 	else
489 		dvcpu = vcpu->kvm->vcpus[irq->cpu];
490 
491 	if (intr == 2 || intr == 3 || intr == 4 || intr == 6) {
492 		kvm_mips_callbacks->queue_io_int(dvcpu, irq);
493 
494 	} else if (intr == -2 || intr == -3 || intr == -4 || intr == -6) {
495 		kvm_mips_callbacks->dequeue_io_int(dvcpu, irq);
496 	} else {
497 		kvm_err("%s: invalid interrupt ioctl (%d:%d)\n", __func__,
498 			irq->cpu, irq->irq);
499 		return -EINVAL;
500 	}
501 
502 	dvcpu->arch.wait = 0;
503 
504 	rcuwait_wake_up(&dvcpu->wait);
505 
506 	return 0;
507 }
508 
509 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
510 				    struct kvm_mp_state *mp_state)
511 {
512 	return -ENOIOCTLCMD;
513 }
514 
515 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
516 				    struct kvm_mp_state *mp_state)
517 {
518 	return -ENOIOCTLCMD;
519 }
520 
521 static u64 kvm_mips_get_one_regs[] = {
522 	KVM_REG_MIPS_R0,
523 	KVM_REG_MIPS_R1,
524 	KVM_REG_MIPS_R2,
525 	KVM_REG_MIPS_R3,
526 	KVM_REG_MIPS_R4,
527 	KVM_REG_MIPS_R5,
528 	KVM_REG_MIPS_R6,
529 	KVM_REG_MIPS_R7,
530 	KVM_REG_MIPS_R8,
531 	KVM_REG_MIPS_R9,
532 	KVM_REG_MIPS_R10,
533 	KVM_REG_MIPS_R11,
534 	KVM_REG_MIPS_R12,
535 	KVM_REG_MIPS_R13,
536 	KVM_REG_MIPS_R14,
537 	KVM_REG_MIPS_R15,
538 	KVM_REG_MIPS_R16,
539 	KVM_REG_MIPS_R17,
540 	KVM_REG_MIPS_R18,
541 	KVM_REG_MIPS_R19,
542 	KVM_REG_MIPS_R20,
543 	KVM_REG_MIPS_R21,
544 	KVM_REG_MIPS_R22,
545 	KVM_REG_MIPS_R23,
546 	KVM_REG_MIPS_R24,
547 	KVM_REG_MIPS_R25,
548 	KVM_REG_MIPS_R26,
549 	KVM_REG_MIPS_R27,
550 	KVM_REG_MIPS_R28,
551 	KVM_REG_MIPS_R29,
552 	KVM_REG_MIPS_R30,
553 	KVM_REG_MIPS_R31,
554 
555 #ifndef CONFIG_CPU_MIPSR6
556 	KVM_REG_MIPS_HI,
557 	KVM_REG_MIPS_LO,
558 #endif
559 	KVM_REG_MIPS_PC,
560 };
561 
562 static u64 kvm_mips_get_one_regs_fpu[] = {
563 	KVM_REG_MIPS_FCR_IR,
564 	KVM_REG_MIPS_FCR_CSR,
565 };
566 
567 static u64 kvm_mips_get_one_regs_msa[] = {
568 	KVM_REG_MIPS_MSA_IR,
569 	KVM_REG_MIPS_MSA_CSR,
570 };
571 
572 static unsigned long kvm_mips_num_regs(struct kvm_vcpu *vcpu)
573 {
574 	unsigned long ret;
575 
576 	ret = ARRAY_SIZE(kvm_mips_get_one_regs);
577 	if (kvm_mips_guest_can_have_fpu(&vcpu->arch)) {
578 		ret += ARRAY_SIZE(kvm_mips_get_one_regs_fpu) + 48;
579 		/* odd doubles */
580 		if (boot_cpu_data.fpu_id & MIPS_FPIR_F64)
581 			ret += 16;
582 	}
583 	if (kvm_mips_guest_can_have_msa(&vcpu->arch))
584 		ret += ARRAY_SIZE(kvm_mips_get_one_regs_msa) + 32;
585 	ret += kvm_mips_callbacks->num_regs(vcpu);
586 
587 	return ret;
588 }
589 
590 static int kvm_mips_copy_reg_indices(struct kvm_vcpu *vcpu, u64 __user *indices)
591 {
592 	u64 index;
593 	unsigned int i;
594 
595 	if (copy_to_user(indices, kvm_mips_get_one_regs,
596 			 sizeof(kvm_mips_get_one_regs)))
597 		return -EFAULT;
598 	indices += ARRAY_SIZE(kvm_mips_get_one_regs);
599 
600 	if (kvm_mips_guest_can_have_fpu(&vcpu->arch)) {
601 		if (copy_to_user(indices, kvm_mips_get_one_regs_fpu,
602 				 sizeof(kvm_mips_get_one_regs_fpu)))
603 			return -EFAULT;
604 		indices += ARRAY_SIZE(kvm_mips_get_one_regs_fpu);
605 
606 		for (i = 0; i < 32; ++i) {
607 			index = KVM_REG_MIPS_FPR_32(i);
608 			if (copy_to_user(indices, &index, sizeof(index)))
609 				return -EFAULT;
610 			++indices;
611 
612 			/* skip odd doubles if no F64 */
613 			if (i & 1 && !(boot_cpu_data.fpu_id & MIPS_FPIR_F64))
614 				continue;
615 
616 			index = KVM_REG_MIPS_FPR_64(i);
617 			if (copy_to_user(indices, &index, sizeof(index)))
618 				return -EFAULT;
619 			++indices;
620 		}
621 	}
622 
623 	if (kvm_mips_guest_can_have_msa(&vcpu->arch)) {
624 		if (copy_to_user(indices, kvm_mips_get_one_regs_msa,
625 				 sizeof(kvm_mips_get_one_regs_msa)))
626 			return -EFAULT;
627 		indices += ARRAY_SIZE(kvm_mips_get_one_regs_msa);
628 
629 		for (i = 0; i < 32; ++i) {
630 			index = KVM_REG_MIPS_VEC_128(i);
631 			if (copy_to_user(indices, &index, sizeof(index)))
632 				return -EFAULT;
633 			++indices;
634 		}
635 	}
636 
637 	return kvm_mips_callbacks->copy_reg_indices(vcpu, indices);
638 }
639 
640 static int kvm_mips_get_reg(struct kvm_vcpu *vcpu,
641 			    const struct kvm_one_reg *reg)
642 {
643 	struct mips_coproc *cop0 = vcpu->arch.cop0;
644 	struct mips_fpu_struct *fpu = &vcpu->arch.fpu;
645 	int ret;
646 	s64 v;
647 	s64 vs[2];
648 	unsigned int idx;
649 
650 	switch (reg->id) {
651 	/* General purpose registers */
652 	case KVM_REG_MIPS_R0 ... KVM_REG_MIPS_R31:
653 		v = (long)vcpu->arch.gprs[reg->id - KVM_REG_MIPS_R0];
654 		break;
655 #ifndef CONFIG_CPU_MIPSR6
656 	case KVM_REG_MIPS_HI:
657 		v = (long)vcpu->arch.hi;
658 		break;
659 	case KVM_REG_MIPS_LO:
660 		v = (long)vcpu->arch.lo;
661 		break;
662 #endif
663 	case KVM_REG_MIPS_PC:
664 		v = (long)vcpu->arch.pc;
665 		break;
666 
667 	/* Floating point registers */
668 	case KVM_REG_MIPS_FPR_32(0) ... KVM_REG_MIPS_FPR_32(31):
669 		if (!kvm_mips_guest_has_fpu(&vcpu->arch))
670 			return -EINVAL;
671 		idx = reg->id - KVM_REG_MIPS_FPR_32(0);
672 		/* Odd singles in top of even double when FR=0 */
673 		if (kvm_read_c0_guest_status(cop0) & ST0_FR)
674 			v = get_fpr32(&fpu->fpr[idx], 0);
675 		else
676 			v = get_fpr32(&fpu->fpr[idx & ~1], idx & 1);
677 		break;
678 	case KVM_REG_MIPS_FPR_64(0) ... KVM_REG_MIPS_FPR_64(31):
679 		if (!kvm_mips_guest_has_fpu(&vcpu->arch))
680 			return -EINVAL;
681 		idx = reg->id - KVM_REG_MIPS_FPR_64(0);
682 		/* Can't access odd doubles in FR=0 mode */
683 		if (idx & 1 && !(kvm_read_c0_guest_status(cop0) & ST0_FR))
684 			return -EINVAL;
685 		v = get_fpr64(&fpu->fpr[idx], 0);
686 		break;
687 	case KVM_REG_MIPS_FCR_IR:
688 		if (!kvm_mips_guest_has_fpu(&vcpu->arch))
689 			return -EINVAL;
690 		v = boot_cpu_data.fpu_id;
691 		break;
692 	case KVM_REG_MIPS_FCR_CSR:
693 		if (!kvm_mips_guest_has_fpu(&vcpu->arch))
694 			return -EINVAL;
695 		v = fpu->fcr31;
696 		break;
697 
698 	/* MIPS SIMD Architecture (MSA) registers */
699 	case KVM_REG_MIPS_VEC_128(0) ... KVM_REG_MIPS_VEC_128(31):
700 		if (!kvm_mips_guest_has_msa(&vcpu->arch))
701 			return -EINVAL;
702 		/* Can't access MSA registers in FR=0 mode */
703 		if (!(kvm_read_c0_guest_status(cop0) & ST0_FR))
704 			return -EINVAL;
705 		idx = reg->id - KVM_REG_MIPS_VEC_128(0);
706 #ifdef CONFIG_CPU_LITTLE_ENDIAN
707 		/* least significant byte first */
708 		vs[0] = get_fpr64(&fpu->fpr[idx], 0);
709 		vs[1] = get_fpr64(&fpu->fpr[idx], 1);
710 #else
711 		/* most significant byte first */
712 		vs[0] = get_fpr64(&fpu->fpr[idx], 1);
713 		vs[1] = get_fpr64(&fpu->fpr[idx], 0);
714 #endif
715 		break;
716 	case KVM_REG_MIPS_MSA_IR:
717 		if (!kvm_mips_guest_has_msa(&vcpu->arch))
718 			return -EINVAL;
719 		v = boot_cpu_data.msa_id;
720 		break;
721 	case KVM_REG_MIPS_MSA_CSR:
722 		if (!kvm_mips_guest_has_msa(&vcpu->arch))
723 			return -EINVAL;
724 		v = fpu->msacsr;
725 		break;
726 
727 	/* registers to be handled specially */
728 	default:
729 		ret = kvm_mips_callbacks->get_one_reg(vcpu, reg, &v);
730 		if (ret)
731 			return ret;
732 		break;
733 	}
734 	if ((reg->id & KVM_REG_SIZE_MASK) == KVM_REG_SIZE_U64) {
735 		u64 __user *uaddr64 = (u64 __user *)(long)reg->addr;
736 
737 		return put_user(v, uaddr64);
738 	} else if ((reg->id & KVM_REG_SIZE_MASK) == KVM_REG_SIZE_U32) {
739 		u32 __user *uaddr32 = (u32 __user *)(long)reg->addr;
740 		u32 v32 = (u32)v;
741 
742 		return put_user(v32, uaddr32);
743 	} else if ((reg->id & KVM_REG_SIZE_MASK) == KVM_REG_SIZE_U128) {
744 		void __user *uaddr = (void __user *)(long)reg->addr;
745 
746 		return copy_to_user(uaddr, vs, 16) ? -EFAULT : 0;
747 	} else {
748 		return -EINVAL;
749 	}
750 }
751 
752 static int kvm_mips_set_reg(struct kvm_vcpu *vcpu,
753 			    const struct kvm_one_reg *reg)
754 {
755 	struct mips_coproc *cop0 = vcpu->arch.cop0;
756 	struct mips_fpu_struct *fpu = &vcpu->arch.fpu;
757 	s64 v;
758 	s64 vs[2];
759 	unsigned int idx;
760 
761 	if ((reg->id & KVM_REG_SIZE_MASK) == KVM_REG_SIZE_U64) {
762 		u64 __user *uaddr64 = (u64 __user *)(long)reg->addr;
763 
764 		if (get_user(v, uaddr64) != 0)
765 			return -EFAULT;
766 	} else if ((reg->id & KVM_REG_SIZE_MASK) == KVM_REG_SIZE_U32) {
767 		u32 __user *uaddr32 = (u32 __user *)(long)reg->addr;
768 		s32 v32;
769 
770 		if (get_user(v32, uaddr32) != 0)
771 			return -EFAULT;
772 		v = (s64)v32;
773 	} else if ((reg->id & KVM_REG_SIZE_MASK) == KVM_REG_SIZE_U128) {
774 		void __user *uaddr = (void __user *)(long)reg->addr;
775 
776 		return copy_from_user(vs, uaddr, 16) ? -EFAULT : 0;
777 	} else {
778 		return -EINVAL;
779 	}
780 
781 	switch (reg->id) {
782 	/* General purpose registers */
783 	case KVM_REG_MIPS_R0:
784 		/* Silently ignore requests to set $0 */
785 		break;
786 	case KVM_REG_MIPS_R1 ... KVM_REG_MIPS_R31:
787 		vcpu->arch.gprs[reg->id - KVM_REG_MIPS_R0] = v;
788 		break;
789 #ifndef CONFIG_CPU_MIPSR6
790 	case KVM_REG_MIPS_HI:
791 		vcpu->arch.hi = v;
792 		break;
793 	case KVM_REG_MIPS_LO:
794 		vcpu->arch.lo = v;
795 		break;
796 #endif
797 	case KVM_REG_MIPS_PC:
798 		vcpu->arch.pc = v;
799 		break;
800 
801 	/* Floating point registers */
802 	case KVM_REG_MIPS_FPR_32(0) ... KVM_REG_MIPS_FPR_32(31):
803 		if (!kvm_mips_guest_has_fpu(&vcpu->arch))
804 			return -EINVAL;
805 		idx = reg->id - KVM_REG_MIPS_FPR_32(0);
806 		/* Odd singles in top of even double when FR=0 */
807 		if (kvm_read_c0_guest_status(cop0) & ST0_FR)
808 			set_fpr32(&fpu->fpr[idx], 0, v);
809 		else
810 			set_fpr32(&fpu->fpr[idx & ~1], idx & 1, v);
811 		break;
812 	case KVM_REG_MIPS_FPR_64(0) ... KVM_REG_MIPS_FPR_64(31):
813 		if (!kvm_mips_guest_has_fpu(&vcpu->arch))
814 			return -EINVAL;
815 		idx = reg->id - KVM_REG_MIPS_FPR_64(0);
816 		/* Can't access odd doubles in FR=0 mode */
817 		if (idx & 1 && !(kvm_read_c0_guest_status(cop0) & ST0_FR))
818 			return -EINVAL;
819 		set_fpr64(&fpu->fpr[idx], 0, v);
820 		break;
821 	case KVM_REG_MIPS_FCR_IR:
822 		if (!kvm_mips_guest_has_fpu(&vcpu->arch))
823 			return -EINVAL;
824 		/* Read-only */
825 		break;
826 	case KVM_REG_MIPS_FCR_CSR:
827 		if (!kvm_mips_guest_has_fpu(&vcpu->arch))
828 			return -EINVAL;
829 		fpu->fcr31 = v;
830 		break;
831 
832 	/* MIPS SIMD Architecture (MSA) registers */
833 	case KVM_REG_MIPS_VEC_128(0) ... KVM_REG_MIPS_VEC_128(31):
834 		if (!kvm_mips_guest_has_msa(&vcpu->arch))
835 			return -EINVAL;
836 		idx = reg->id - KVM_REG_MIPS_VEC_128(0);
837 #ifdef CONFIG_CPU_LITTLE_ENDIAN
838 		/* least significant byte first */
839 		set_fpr64(&fpu->fpr[idx], 0, vs[0]);
840 		set_fpr64(&fpu->fpr[idx], 1, vs[1]);
841 #else
842 		/* most significant byte first */
843 		set_fpr64(&fpu->fpr[idx], 1, vs[0]);
844 		set_fpr64(&fpu->fpr[idx], 0, vs[1]);
845 #endif
846 		break;
847 	case KVM_REG_MIPS_MSA_IR:
848 		if (!kvm_mips_guest_has_msa(&vcpu->arch))
849 			return -EINVAL;
850 		/* Read-only */
851 		break;
852 	case KVM_REG_MIPS_MSA_CSR:
853 		if (!kvm_mips_guest_has_msa(&vcpu->arch))
854 			return -EINVAL;
855 		fpu->msacsr = v;
856 		break;
857 
858 	/* registers to be handled specially */
859 	default:
860 		return kvm_mips_callbacks->set_one_reg(vcpu, reg, v);
861 	}
862 	return 0;
863 }
864 
865 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
866 				     struct kvm_enable_cap *cap)
867 {
868 	int r = 0;
869 
870 	if (!kvm_vm_ioctl_check_extension(vcpu->kvm, cap->cap))
871 		return -EINVAL;
872 	if (cap->flags)
873 		return -EINVAL;
874 	if (cap->args[0])
875 		return -EINVAL;
876 
877 	switch (cap->cap) {
878 	case KVM_CAP_MIPS_FPU:
879 		vcpu->arch.fpu_enabled = true;
880 		break;
881 	case KVM_CAP_MIPS_MSA:
882 		vcpu->arch.msa_enabled = true;
883 		break;
884 	default:
885 		r = -EINVAL;
886 		break;
887 	}
888 
889 	return r;
890 }
891 
892 long kvm_arch_vcpu_async_ioctl(struct file *filp, unsigned int ioctl,
893 			       unsigned long arg)
894 {
895 	struct kvm_vcpu *vcpu = filp->private_data;
896 	void __user *argp = (void __user *)arg;
897 
898 	if (ioctl == KVM_INTERRUPT) {
899 		struct kvm_mips_interrupt irq;
900 
901 		if (copy_from_user(&irq, argp, sizeof(irq)))
902 			return -EFAULT;
903 		kvm_debug("[%d] %s: irq: %d\n", vcpu->vcpu_id, __func__,
904 			  irq.irq);
905 
906 		return kvm_vcpu_ioctl_interrupt(vcpu, &irq);
907 	}
908 
909 	return -ENOIOCTLCMD;
910 }
911 
912 long kvm_arch_vcpu_ioctl(struct file *filp, unsigned int ioctl,
913 			 unsigned long arg)
914 {
915 	struct kvm_vcpu *vcpu = filp->private_data;
916 	void __user *argp = (void __user *)arg;
917 	long r;
918 
919 	vcpu_load(vcpu);
920 
921 	switch (ioctl) {
922 	case KVM_SET_ONE_REG:
923 	case KVM_GET_ONE_REG: {
924 		struct kvm_one_reg reg;
925 
926 		r = -EFAULT;
927 		if (copy_from_user(&reg, argp, sizeof(reg)))
928 			break;
929 		if (ioctl == KVM_SET_ONE_REG)
930 			r = kvm_mips_set_reg(vcpu, &reg);
931 		else
932 			r = kvm_mips_get_reg(vcpu, &reg);
933 		break;
934 	}
935 	case KVM_GET_REG_LIST: {
936 		struct kvm_reg_list __user *user_list = argp;
937 		struct kvm_reg_list reg_list;
938 		unsigned n;
939 
940 		r = -EFAULT;
941 		if (copy_from_user(&reg_list, user_list, sizeof(reg_list)))
942 			break;
943 		n = reg_list.n;
944 		reg_list.n = kvm_mips_num_regs(vcpu);
945 		if (copy_to_user(user_list, &reg_list, sizeof(reg_list)))
946 			break;
947 		r = -E2BIG;
948 		if (n < reg_list.n)
949 			break;
950 		r = kvm_mips_copy_reg_indices(vcpu, user_list->reg);
951 		break;
952 	}
953 	case KVM_ENABLE_CAP: {
954 		struct kvm_enable_cap cap;
955 
956 		r = -EFAULT;
957 		if (copy_from_user(&cap, argp, sizeof(cap)))
958 			break;
959 		r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
960 		break;
961 	}
962 	default:
963 		r = -ENOIOCTLCMD;
964 	}
965 
966 	vcpu_put(vcpu);
967 	return r;
968 }
969 
970 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
971 {
972 
973 }
974 
975 void kvm_arch_flush_remote_tlbs_memslot(struct kvm *kvm,
976 					struct kvm_memory_slot *memslot)
977 {
978 	/* Let implementation handle TLB/GVA invalidation */
979 	kvm_mips_callbacks->flush_shadow_memslot(kvm, memslot);
980 }
981 
982 long kvm_arch_vm_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg)
983 {
984 	long r;
985 
986 	switch (ioctl) {
987 	default:
988 		r = -ENOIOCTLCMD;
989 	}
990 
991 	return r;
992 }
993 
994 int kvm_arch_init(void *opaque)
995 {
996 	if (kvm_mips_callbacks) {
997 		kvm_err("kvm: module already exists\n");
998 		return -EEXIST;
999 	}
1000 
1001 	return kvm_mips_emulation_init(&kvm_mips_callbacks);
1002 }
1003 
1004 void kvm_arch_exit(void)
1005 {
1006 	kvm_mips_callbacks = NULL;
1007 }
1008 
1009 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
1010 				  struct kvm_sregs *sregs)
1011 {
1012 	return -ENOIOCTLCMD;
1013 }
1014 
1015 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
1016 				  struct kvm_sregs *sregs)
1017 {
1018 	return -ENOIOCTLCMD;
1019 }
1020 
1021 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
1022 {
1023 }
1024 
1025 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
1026 {
1027 	return -ENOIOCTLCMD;
1028 }
1029 
1030 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
1031 {
1032 	return -ENOIOCTLCMD;
1033 }
1034 
1035 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
1036 {
1037 	return VM_FAULT_SIGBUS;
1038 }
1039 
1040 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
1041 {
1042 	int r;
1043 
1044 	switch (ext) {
1045 	case KVM_CAP_ONE_REG:
1046 	case KVM_CAP_ENABLE_CAP:
1047 	case KVM_CAP_READONLY_MEM:
1048 	case KVM_CAP_SYNC_MMU:
1049 	case KVM_CAP_IMMEDIATE_EXIT:
1050 		r = 1;
1051 		break;
1052 	case KVM_CAP_NR_VCPUS:
1053 		r = num_online_cpus();
1054 		break;
1055 	case KVM_CAP_MAX_VCPUS:
1056 		r = KVM_MAX_VCPUS;
1057 		break;
1058 	case KVM_CAP_MAX_VCPU_ID:
1059 		r = KVM_MAX_VCPU_ID;
1060 		break;
1061 	case KVM_CAP_MIPS_FPU:
1062 		/* We don't handle systems with inconsistent cpu_has_fpu */
1063 		r = !!raw_cpu_has_fpu;
1064 		break;
1065 	case KVM_CAP_MIPS_MSA:
1066 		/*
1067 		 * We don't support MSA vector partitioning yet:
1068 		 * 1) It would require explicit support which can't be tested
1069 		 *    yet due to lack of support in current hardware.
1070 		 * 2) It extends the state that would need to be saved/restored
1071 		 *    by e.g. QEMU for migration.
1072 		 *
1073 		 * When vector partitioning hardware becomes available, support
1074 		 * could be added by requiring a flag when enabling
1075 		 * KVM_CAP_MIPS_MSA capability to indicate that userland knows
1076 		 * to save/restore the appropriate extra state.
1077 		 */
1078 		r = cpu_has_msa && !(boot_cpu_data.msa_id & MSA_IR_WRPF);
1079 		break;
1080 	default:
1081 		r = kvm_mips_callbacks->check_extension(kvm, ext);
1082 		break;
1083 	}
1084 	return r;
1085 }
1086 
1087 int kvm_cpu_has_pending_timer(struct kvm_vcpu *vcpu)
1088 {
1089 	return kvm_mips_pending_timer(vcpu) ||
1090 		kvm_read_c0_guest_cause(vcpu->arch.cop0) & C_TI;
1091 }
1092 
1093 int kvm_arch_vcpu_dump_regs(struct kvm_vcpu *vcpu)
1094 {
1095 	int i;
1096 	struct mips_coproc *cop0;
1097 
1098 	if (!vcpu)
1099 		return -1;
1100 
1101 	kvm_debug("VCPU Register Dump:\n");
1102 	kvm_debug("\tpc = 0x%08lx\n", vcpu->arch.pc);
1103 	kvm_debug("\texceptions: %08lx\n", vcpu->arch.pending_exceptions);
1104 
1105 	for (i = 0; i < 32; i += 4) {
1106 		kvm_debug("\tgpr%02d: %08lx %08lx %08lx %08lx\n", i,
1107 		       vcpu->arch.gprs[i],
1108 		       vcpu->arch.gprs[i + 1],
1109 		       vcpu->arch.gprs[i + 2], vcpu->arch.gprs[i + 3]);
1110 	}
1111 	kvm_debug("\thi: 0x%08lx\n", vcpu->arch.hi);
1112 	kvm_debug("\tlo: 0x%08lx\n", vcpu->arch.lo);
1113 
1114 	cop0 = vcpu->arch.cop0;
1115 	kvm_debug("\tStatus: 0x%08x, Cause: 0x%08x\n",
1116 		  kvm_read_c0_guest_status(cop0),
1117 		  kvm_read_c0_guest_cause(cop0));
1118 
1119 	kvm_debug("\tEPC: 0x%08lx\n", kvm_read_c0_guest_epc(cop0));
1120 
1121 	return 0;
1122 }
1123 
1124 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
1125 {
1126 	int i;
1127 
1128 	vcpu_load(vcpu);
1129 
1130 	for (i = 1; i < ARRAY_SIZE(vcpu->arch.gprs); i++)
1131 		vcpu->arch.gprs[i] = regs->gpr[i];
1132 	vcpu->arch.gprs[0] = 0; /* zero is special, and cannot be set. */
1133 	vcpu->arch.hi = regs->hi;
1134 	vcpu->arch.lo = regs->lo;
1135 	vcpu->arch.pc = regs->pc;
1136 
1137 	vcpu_put(vcpu);
1138 	return 0;
1139 }
1140 
1141 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
1142 {
1143 	int i;
1144 
1145 	vcpu_load(vcpu);
1146 
1147 	for (i = 0; i < ARRAY_SIZE(vcpu->arch.gprs); i++)
1148 		regs->gpr[i] = vcpu->arch.gprs[i];
1149 
1150 	regs->hi = vcpu->arch.hi;
1151 	regs->lo = vcpu->arch.lo;
1152 	regs->pc = vcpu->arch.pc;
1153 
1154 	vcpu_put(vcpu);
1155 	return 0;
1156 }
1157 
1158 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
1159 				  struct kvm_translation *tr)
1160 {
1161 	return 0;
1162 }
1163 
1164 static void kvm_mips_set_c0_status(void)
1165 {
1166 	u32 status = read_c0_status();
1167 
1168 	if (cpu_has_dsp)
1169 		status |= (ST0_MX);
1170 
1171 	write_c0_status(status);
1172 	ehb();
1173 }
1174 
1175 /*
1176  * Return value is in the form (errcode<<2 | RESUME_FLAG_HOST | RESUME_FLAG_NV)
1177  */
1178 int kvm_mips_handle_exit(struct kvm_vcpu *vcpu)
1179 {
1180 	struct kvm_run *run = vcpu->run;
1181 	u32 cause = vcpu->arch.host_cp0_cause;
1182 	u32 exccode = (cause >> CAUSEB_EXCCODE) & 0x1f;
1183 	u32 __user *opc = (u32 __user *) vcpu->arch.pc;
1184 	unsigned long badvaddr = vcpu->arch.host_cp0_badvaddr;
1185 	enum emulation_result er = EMULATE_DONE;
1186 	u32 inst;
1187 	int ret = RESUME_GUEST;
1188 
1189 	vcpu->mode = OUTSIDE_GUEST_MODE;
1190 
1191 	/* Set a default exit reason */
1192 	run->exit_reason = KVM_EXIT_UNKNOWN;
1193 	run->ready_for_interrupt_injection = 1;
1194 
1195 	/*
1196 	 * Set the appropriate status bits based on host CPU features,
1197 	 * before we hit the scheduler
1198 	 */
1199 	kvm_mips_set_c0_status();
1200 
1201 	local_irq_enable();
1202 
1203 	kvm_debug("kvm_mips_handle_exit: cause: %#x, PC: %p, kvm_run: %p, kvm_vcpu: %p\n",
1204 			cause, opc, run, vcpu);
1205 	trace_kvm_exit(vcpu, exccode);
1206 
1207 	switch (exccode) {
1208 	case EXCCODE_INT:
1209 		kvm_debug("[%d]EXCCODE_INT @ %p\n", vcpu->vcpu_id, opc);
1210 
1211 		++vcpu->stat.int_exits;
1212 
1213 		if (need_resched())
1214 			cond_resched();
1215 
1216 		ret = RESUME_GUEST;
1217 		break;
1218 
1219 	case EXCCODE_CPU:
1220 		kvm_debug("EXCCODE_CPU: @ PC: %p\n", opc);
1221 
1222 		++vcpu->stat.cop_unusable_exits;
1223 		ret = kvm_mips_callbacks->handle_cop_unusable(vcpu);
1224 		/* XXXKYMA: Might need to return to user space */
1225 		if (run->exit_reason == KVM_EXIT_IRQ_WINDOW_OPEN)
1226 			ret = RESUME_HOST;
1227 		break;
1228 
1229 	case EXCCODE_MOD:
1230 		++vcpu->stat.tlbmod_exits;
1231 		ret = kvm_mips_callbacks->handle_tlb_mod(vcpu);
1232 		break;
1233 
1234 	case EXCCODE_TLBS:
1235 		kvm_debug("TLB ST fault:  cause %#x, status %#x, PC: %p, BadVaddr: %#lx\n",
1236 			  cause, kvm_read_c0_guest_status(vcpu->arch.cop0), opc,
1237 			  badvaddr);
1238 
1239 		++vcpu->stat.tlbmiss_st_exits;
1240 		ret = kvm_mips_callbacks->handle_tlb_st_miss(vcpu);
1241 		break;
1242 
1243 	case EXCCODE_TLBL:
1244 		kvm_debug("TLB LD fault: cause %#x, PC: %p, BadVaddr: %#lx\n",
1245 			  cause, opc, badvaddr);
1246 
1247 		++vcpu->stat.tlbmiss_ld_exits;
1248 		ret = kvm_mips_callbacks->handle_tlb_ld_miss(vcpu);
1249 		break;
1250 
1251 	case EXCCODE_ADES:
1252 		++vcpu->stat.addrerr_st_exits;
1253 		ret = kvm_mips_callbacks->handle_addr_err_st(vcpu);
1254 		break;
1255 
1256 	case EXCCODE_ADEL:
1257 		++vcpu->stat.addrerr_ld_exits;
1258 		ret = kvm_mips_callbacks->handle_addr_err_ld(vcpu);
1259 		break;
1260 
1261 	case EXCCODE_SYS:
1262 		++vcpu->stat.syscall_exits;
1263 		ret = kvm_mips_callbacks->handle_syscall(vcpu);
1264 		break;
1265 
1266 	case EXCCODE_RI:
1267 		++vcpu->stat.resvd_inst_exits;
1268 		ret = kvm_mips_callbacks->handle_res_inst(vcpu);
1269 		break;
1270 
1271 	case EXCCODE_BP:
1272 		++vcpu->stat.break_inst_exits;
1273 		ret = kvm_mips_callbacks->handle_break(vcpu);
1274 		break;
1275 
1276 	case EXCCODE_TR:
1277 		++vcpu->stat.trap_inst_exits;
1278 		ret = kvm_mips_callbacks->handle_trap(vcpu);
1279 		break;
1280 
1281 	case EXCCODE_MSAFPE:
1282 		++vcpu->stat.msa_fpe_exits;
1283 		ret = kvm_mips_callbacks->handle_msa_fpe(vcpu);
1284 		break;
1285 
1286 	case EXCCODE_FPE:
1287 		++vcpu->stat.fpe_exits;
1288 		ret = kvm_mips_callbacks->handle_fpe(vcpu);
1289 		break;
1290 
1291 	case EXCCODE_MSADIS:
1292 		++vcpu->stat.msa_disabled_exits;
1293 		ret = kvm_mips_callbacks->handle_msa_disabled(vcpu);
1294 		break;
1295 
1296 	case EXCCODE_GE:
1297 		/* defer exit accounting to handler */
1298 		ret = kvm_mips_callbacks->handle_guest_exit(vcpu);
1299 		break;
1300 
1301 	default:
1302 		if (cause & CAUSEF_BD)
1303 			opc += 1;
1304 		inst = 0;
1305 		kvm_get_badinstr(opc, vcpu, &inst);
1306 		kvm_err("Exception Code: %d, not yet handled, @ PC: %p, inst: 0x%08x  BadVaddr: %#lx Status: %#x\n",
1307 			exccode, opc, inst, badvaddr,
1308 			kvm_read_c0_guest_status(vcpu->arch.cop0));
1309 		kvm_arch_vcpu_dump_regs(vcpu);
1310 		run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
1311 		ret = RESUME_HOST;
1312 		break;
1313 
1314 	}
1315 
1316 	local_irq_disable();
1317 
1318 	if (ret == RESUME_GUEST)
1319 		kvm_vz_acquire_htimer(vcpu);
1320 
1321 	if (er == EMULATE_DONE && !(ret & RESUME_HOST))
1322 		kvm_mips_deliver_interrupts(vcpu, cause);
1323 
1324 	if (!(ret & RESUME_HOST)) {
1325 		/* Only check for signals if not already exiting to userspace */
1326 		if (signal_pending(current)) {
1327 			run->exit_reason = KVM_EXIT_INTR;
1328 			ret = (-EINTR << 2) | RESUME_HOST;
1329 			++vcpu->stat.signal_exits;
1330 			trace_kvm_exit(vcpu, KVM_TRACE_EXIT_SIGNAL);
1331 		}
1332 	}
1333 
1334 	if (ret == RESUME_GUEST) {
1335 		trace_kvm_reenter(vcpu);
1336 
1337 		/*
1338 		 * Make sure the read of VCPU requests in vcpu_reenter()
1339 		 * callback is not reordered ahead of the write to vcpu->mode,
1340 		 * or we could miss a TLB flush request while the requester sees
1341 		 * the VCPU as outside of guest mode and not needing an IPI.
1342 		 */
1343 		smp_store_mb(vcpu->mode, IN_GUEST_MODE);
1344 
1345 		kvm_mips_callbacks->vcpu_reenter(vcpu);
1346 
1347 		/*
1348 		 * If FPU / MSA are enabled (i.e. the guest's FPU / MSA context
1349 		 * is live), restore FCR31 / MSACSR.
1350 		 *
1351 		 * This should be before returning to the guest exception
1352 		 * vector, as it may well cause an [MSA] FP exception if there
1353 		 * are pending exception bits unmasked. (see
1354 		 * kvm_mips_csr_die_notifier() for how that is handled).
1355 		 */
1356 		if (kvm_mips_guest_has_fpu(&vcpu->arch) &&
1357 		    read_c0_status() & ST0_CU1)
1358 			__kvm_restore_fcsr(&vcpu->arch);
1359 
1360 		if (kvm_mips_guest_has_msa(&vcpu->arch) &&
1361 		    read_c0_config5() & MIPS_CONF5_MSAEN)
1362 			__kvm_restore_msacsr(&vcpu->arch);
1363 	}
1364 	return ret;
1365 }
1366 
1367 /* Enable FPU for guest and restore context */
1368 void kvm_own_fpu(struct kvm_vcpu *vcpu)
1369 {
1370 	struct mips_coproc *cop0 = vcpu->arch.cop0;
1371 	unsigned int sr, cfg5;
1372 
1373 	preempt_disable();
1374 
1375 	sr = kvm_read_c0_guest_status(cop0);
1376 
1377 	/*
1378 	 * If MSA state is already live, it is undefined how it interacts with
1379 	 * FR=0 FPU state, and we don't want to hit reserved instruction
1380 	 * exceptions trying to save the MSA state later when CU=1 && FR=1, so
1381 	 * play it safe and save it first.
1382 	 */
1383 	if (cpu_has_msa && sr & ST0_CU1 && !(sr & ST0_FR) &&
1384 	    vcpu->arch.aux_inuse & KVM_MIPS_AUX_MSA)
1385 		kvm_lose_fpu(vcpu);
1386 
1387 	/*
1388 	 * Enable FPU for guest
1389 	 * We set FR and FRE according to guest context
1390 	 */
1391 	change_c0_status(ST0_CU1 | ST0_FR, sr);
1392 	if (cpu_has_fre) {
1393 		cfg5 = kvm_read_c0_guest_config5(cop0);
1394 		change_c0_config5(MIPS_CONF5_FRE, cfg5);
1395 	}
1396 	enable_fpu_hazard();
1397 
1398 	/* If guest FPU state not active, restore it now */
1399 	if (!(vcpu->arch.aux_inuse & KVM_MIPS_AUX_FPU)) {
1400 		__kvm_restore_fpu(&vcpu->arch);
1401 		vcpu->arch.aux_inuse |= KVM_MIPS_AUX_FPU;
1402 		trace_kvm_aux(vcpu, KVM_TRACE_AUX_RESTORE, KVM_TRACE_AUX_FPU);
1403 	} else {
1404 		trace_kvm_aux(vcpu, KVM_TRACE_AUX_ENABLE, KVM_TRACE_AUX_FPU);
1405 	}
1406 
1407 	preempt_enable();
1408 }
1409 
1410 #ifdef CONFIG_CPU_HAS_MSA
1411 /* Enable MSA for guest and restore context */
1412 void kvm_own_msa(struct kvm_vcpu *vcpu)
1413 {
1414 	struct mips_coproc *cop0 = vcpu->arch.cop0;
1415 	unsigned int sr, cfg5;
1416 
1417 	preempt_disable();
1418 
1419 	/*
1420 	 * Enable FPU if enabled in guest, since we're restoring FPU context
1421 	 * anyway. We set FR and FRE according to guest context.
1422 	 */
1423 	if (kvm_mips_guest_has_fpu(&vcpu->arch)) {
1424 		sr = kvm_read_c0_guest_status(cop0);
1425 
1426 		/*
1427 		 * If FR=0 FPU state is already live, it is undefined how it
1428 		 * interacts with MSA state, so play it safe and save it first.
1429 		 */
1430 		if (!(sr & ST0_FR) &&
1431 		    (vcpu->arch.aux_inuse & (KVM_MIPS_AUX_FPU |
1432 				KVM_MIPS_AUX_MSA)) == KVM_MIPS_AUX_FPU)
1433 			kvm_lose_fpu(vcpu);
1434 
1435 		change_c0_status(ST0_CU1 | ST0_FR, sr);
1436 		if (sr & ST0_CU1 && cpu_has_fre) {
1437 			cfg5 = kvm_read_c0_guest_config5(cop0);
1438 			change_c0_config5(MIPS_CONF5_FRE, cfg5);
1439 		}
1440 	}
1441 
1442 	/* Enable MSA for guest */
1443 	set_c0_config5(MIPS_CONF5_MSAEN);
1444 	enable_fpu_hazard();
1445 
1446 	switch (vcpu->arch.aux_inuse & (KVM_MIPS_AUX_FPU | KVM_MIPS_AUX_MSA)) {
1447 	case KVM_MIPS_AUX_FPU:
1448 		/*
1449 		 * Guest FPU state already loaded, only restore upper MSA state
1450 		 */
1451 		__kvm_restore_msa_upper(&vcpu->arch);
1452 		vcpu->arch.aux_inuse |= KVM_MIPS_AUX_MSA;
1453 		trace_kvm_aux(vcpu, KVM_TRACE_AUX_RESTORE, KVM_TRACE_AUX_MSA);
1454 		break;
1455 	case 0:
1456 		/* Neither FPU or MSA already active, restore full MSA state */
1457 		__kvm_restore_msa(&vcpu->arch);
1458 		vcpu->arch.aux_inuse |= KVM_MIPS_AUX_MSA;
1459 		if (kvm_mips_guest_has_fpu(&vcpu->arch))
1460 			vcpu->arch.aux_inuse |= KVM_MIPS_AUX_FPU;
1461 		trace_kvm_aux(vcpu, KVM_TRACE_AUX_RESTORE,
1462 			      KVM_TRACE_AUX_FPU_MSA);
1463 		break;
1464 	default:
1465 		trace_kvm_aux(vcpu, KVM_TRACE_AUX_ENABLE, KVM_TRACE_AUX_MSA);
1466 		break;
1467 	}
1468 
1469 	preempt_enable();
1470 }
1471 #endif
1472 
1473 /* Drop FPU & MSA without saving it */
1474 void kvm_drop_fpu(struct kvm_vcpu *vcpu)
1475 {
1476 	preempt_disable();
1477 	if (cpu_has_msa && vcpu->arch.aux_inuse & KVM_MIPS_AUX_MSA) {
1478 		disable_msa();
1479 		trace_kvm_aux(vcpu, KVM_TRACE_AUX_DISCARD, KVM_TRACE_AUX_MSA);
1480 		vcpu->arch.aux_inuse &= ~KVM_MIPS_AUX_MSA;
1481 	}
1482 	if (vcpu->arch.aux_inuse & KVM_MIPS_AUX_FPU) {
1483 		clear_c0_status(ST0_CU1 | ST0_FR);
1484 		trace_kvm_aux(vcpu, KVM_TRACE_AUX_DISCARD, KVM_TRACE_AUX_FPU);
1485 		vcpu->arch.aux_inuse &= ~KVM_MIPS_AUX_FPU;
1486 	}
1487 	preempt_enable();
1488 }
1489 
1490 /* Save and disable FPU & MSA */
1491 void kvm_lose_fpu(struct kvm_vcpu *vcpu)
1492 {
1493 	/*
1494 	 * With T&E, FPU & MSA get disabled in root context (hardware) when it
1495 	 * is disabled in guest context (software), but the register state in
1496 	 * the hardware may still be in use.
1497 	 * This is why we explicitly re-enable the hardware before saving.
1498 	 */
1499 
1500 	preempt_disable();
1501 	if (cpu_has_msa && vcpu->arch.aux_inuse & KVM_MIPS_AUX_MSA) {
1502 		__kvm_save_msa(&vcpu->arch);
1503 		trace_kvm_aux(vcpu, KVM_TRACE_AUX_SAVE, KVM_TRACE_AUX_FPU_MSA);
1504 
1505 		/* Disable MSA & FPU */
1506 		disable_msa();
1507 		if (vcpu->arch.aux_inuse & KVM_MIPS_AUX_FPU) {
1508 			clear_c0_status(ST0_CU1 | ST0_FR);
1509 			disable_fpu_hazard();
1510 		}
1511 		vcpu->arch.aux_inuse &= ~(KVM_MIPS_AUX_FPU | KVM_MIPS_AUX_MSA);
1512 	} else if (vcpu->arch.aux_inuse & KVM_MIPS_AUX_FPU) {
1513 		__kvm_save_fpu(&vcpu->arch);
1514 		vcpu->arch.aux_inuse &= ~KVM_MIPS_AUX_FPU;
1515 		trace_kvm_aux(vcpu, KVM_TRACE_AUX_SAVE, KVM_TRACE_AUX_FPU);
1516 
1517 		/* Disable FPU */
1518 		clear_c0_status(ST0_CU1 | ST0_FR);
1519 		disable_fpu_hazard();
1520 	}
1521 	preempt_enable();
1522 }
1523 
1524 /*
1525  * Step over a specific ctc1 to FCSR and a specific ctcmsa to MSACSR which are
1526  * used to restore guest FCSR/MSACSR state and may trigger a "harmless" FP/MSAFP
1527  * exception if cause bits are set in the value being written.
1528  */
1529 static int kvm_mips_csr_die_notify(struct notifier_block *self,
1530 				   unsigned long cmd, void *ptr)
1531 {
1532 	struct die_args *args = (struct die_args *)ptr;
1533 	struct pt_regs *regs = args->regs;
1534 	unsigned long pc;
1535 
1536 	/* Only interested in FPE and MSAFPE */
1537 	if (cmd != DIE_FP && cmd != DIE_MSAFP)
1538 		return NOTIFY_DONE;
1539 
1540 	/* Return immediately if guest context isn't active */
1541 	if (!(current->flags & PF_VCPU))
1542 		return NOTIFY_DONE;
1543 
1544 	/* Should never get here from user mode */
1545 	BUG_ON(user_mode(regs));
1546 
1547 	pc = instruction_pointer(regs);
1548 	switch (cmd) {
1549 	case DIE_FP:
1550 		/* match 2nd instruction in __kvm_restore_fcsr */
1551 		if (pc != (unsigned long)&__kvm_restore_fcsr + 4)
1552 			return NOTIFY_DONE;
1553 		break;
1554 	case DIE_MSAFP:
1555 		/* match 2nd/3rd instruction in __kvm_restore_msacsr */
1556 		if (!cpu_has_msa ||
1557 		    pc < (unsigned long)&__kvm_restore_msacsr + 4 ||
1558 		    pc > (unsigned long)&__kvm_restore_msacsr + 8)
1559 			return NOTIFY_DONE;
1560 		break;
1561 	}
1562 
1563 	/* Move PC forward a little and continue executing */
1564 	instruction_pointer(regs) += 4;
1565 
1566 	return NOTIFY_STOP;
1567 }
1568 
1569 static struct notifier_block kvm_mips_csr_die_notifier = {
1570 	.notifier_call = kvm_mips_csr_die_notify,
1571 };
1572 
1573 static u32 kvm_default_priority_to_irq[MIPS_EXC_MAX] = {
1574 	[MIPS_EXC_INT_TIMER] = C_IRQ5,
1575 	[MIPS_EXC_INT_IO_1]  = C_IRQ0,
1576 	[MIPS_EXC_INT_IPI_1] = C_IRQ1,
1577 	[MIPS_EXC_INT_IPI_2] = C_IRQ2,
1578 };
1579 
1580 static u32 kvm_loongson3_priority_to_irq[MIPS_EXC_MAX] = {
1581 	[MIPS_EXC_INT_TIMER] = C_IRQ5,
1582 	[MIPS_EXC_INT_IO_1]  = C_IRQ0,
1583 	[MIPS_EXC_INT_IO_2]  = C_IRQ1,
1584 	[MIPS_EXC_INT_IPI_1] = C_IRQ4,
1585 };
1586 
1587 u32 *kvm_priority_to_irq = kvm_default_priority_to_irq;
1588 
1589 u32 kvm_irq_to_priority(u32 irq)
1590 {
1591 	int i;
1592 
1593 	for (i = MIPS_EXC_INT_TIMER; i < MIPS_EXC_MAX; i++) {
1594 		if (kvm_priority_to_irq[i] == (1 << (irq + 8)))
1595 			return i;
1596 	}
1597 
1598 	return MIPS_EXC_MAX;
1599 }
1600 
1601 static int __init kvm_mips_init(void)
1602 {
1603 	int ret;
1604 
1605 	if (cpu_has_mmid) {
1606 		pr_warn("KVM does not yet support MMIDs. KVM Disabled\n");
1607 		return -EOPNOTSUPP;
1608 	}
1609 
1610 	ret = kvm_mips_entry_setup();
1611 	if (ret)
1612 		return ret;
1613 
1614 	ret = kvm_init(NULL, sizeof(struct kvm_vcpu), 0, THIS_MODULE);
1615 
1616 	if (ret)
1617 		return ret;
1618 
1619 	if (boot_cpu_type() == CPU_LOONGSON64)
1620 		kvm_priority_to_irq = kvm_loongson3_priority_to_irq;
1621 
1622 	register_die_notifier(&kvm_mips_csr_die_notifier);
1623 
1624 	return 0;
1625 }
1626 
1627 static void __exit kvm_mips_exit(void)
1628 {
1629 	kvm_exit();
1630 
1631 	unregister_die_notifier(&kvm_mips_csr_die_notifier);
1632 }
1633 
1634 module_init(kvm_mips_init);
1635 module_exit(kvm_mips_exit);
1636 
1637 EXPORT_TRACEPOINT_SYMBOL(kvm_exit);
1638