• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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: Instruction/Exception emulation
7  *
8  * Copyright (C) 2012  MIPS Technologies, Inc.  All rights reserved.
9  * Authors: Sanjay Lal <sanjayl@kymasys.com>
10  */
11 
12 #include <linux/errno.h>
13 #include <linux/err.h>
14 #include <linux/ktime.h>
15 #include <linux/kvm_host.h>
16 #include <linux/module.h>
17 #include <linux/vmalloc.h>
18 #include <linux/fs.h>
19 #include <linux/bootmem.h>
20 #include <linux/random.h>
21 #include <asm/page.h>
22 #include <asm/cacheflush.h>
23 #include <asm/cpu-info.h>
24 #include <asm/mmu_context.h>
25 #include <asm/tlbflush.h>
26 #include <asm/inst.h>
27 
28 #undef CONFIG_MIPS_MT
29 #include <asm/r4kcache.h>
30 #define CONFIG_MIPS_MT
31 
32 #include "opcode.h"
33 #include "interrupt.h"
34 #include "commpage.h"
35 
36 #include "trace.h"
37 
38 /*
39  * Compute the return address and do emulate branch simulation, if required.
40  * This function should be called only in branch delay slot active.
41  */
kvm_compute_return_epc(struct kvm_vcpu * vcpu,unsigned long instpc)42 unsigned long kvm_compute_return_epc(struct kvm_vcpu *vcpu,
43 	unsigned long instpc)
44 {
45 	unsigned int dspcontrol;
46 	union mips_instruction insn;
47 	struct kvm_vcpu_arch *arch = &vcpu->arch;
48 	long epc = instpc;
49 	long nextpc = KVM_INVALID_INST;
50 
51 	if (epc & 3)
52 		goto unaligned;
53 
54 	/* Read the instruction */
55 	insn.word = kvm_get_inst((uint32_t *) epc, vcpu);
56 
57 	if (insn.word == KVM_INVALID_INST)
58 		return KVM_INVALID_INST;
59 
60 	switch (insn.i_format.opcode) {
61 		/* jr and jalr are in r_format format. */
62 	case spec_op:
63 		switch (insn.r_format.func) {
64 		case jalr_op:
65 			arch->gprs[insn.r_format.rd] = epc + 8;
66 			/* Fall through */
67 		case jr_op:
68 			nextpc = arch->gprs[insn.r_format.rs];
69 			break;
70 		}
71 		break;
72 
73 		/*
74 		 * This group contains:
75 		 * bltz_op, bgez_op, bltzl_op, bgezl_op,
76 		 * bltzal_op, bgezal_op, bltzall_op, bgezall_op.
77 		 */
78 	case bcond_op:
79 		switch (insn.i_format.rt) {
80 		case bltz_op:
81 		case bltzl_op:
82 			if ((long)arch->gprs[insn.i_format.rs] < 0)
83 				epc = epc + 4 + (insn.i_format.simmediate << 2);
84 			else
85 				epc += 8;
86 			nextpc = epc;
87 			break;
88 
89 		case bgez_op:
90 		case bgezl_op:
91 			if ((long)arch->gprs[insn.i_format.rs] >= 0)
92 				epc = epc + 4 + (insn.i_format.simmediate << 2);
93 			else
94 				epc += 8;
95 			nextpc = epc;
96 			break;
97 
98 		case bltzal_op:
99 		case bltzall_op:
100 			arch->gprs[31] = epc + 8;
101 			if ((long)arch->gprs[insn.i_format.rs] < 0)
102 				epc = epc + 4 + (insn.i_format.simmediate << 2);
103 			else
104 				epc += 8;
105 			nextpc = epc;
106 			break;
107 
108 		case bgezal_op:
109 		case bgezall_op:
110 			arch->gprs[31] = epc + 8;
111 			if ((long)arch->gprs[insn.i_format.rs] >= 0)
112 				epc = epc + 4 + (insn.i_format.simmediate << 2);
113 			else
114 				epc += 8;
115 			nextpc = epc;
116 			break;
117 		case bposge32_op:
118 			if (!cpu_has_dsp)
119 				goto sigill;
120 
121 			dspcontrol = rddsp(0x01);
122 
123 			if (dspcontrol >= 32)
124 				epc = epc + 4 + (insn.i_format.simmediate << 2);
125 			else
126 				epc += 8;
127 			nextpc = epc;
128 			break;
129 		}
130 		break;
131 
132 		/* These are unconditional and in j_format. */
133 	case jal_op:
134 		arch->gprs[31] = instpc + 8;
135 	case j_op:
136 		epc += 4;
137 		epc >>= 28;
138 		epc <<= 28;
139 		epc |= (insn.j_format.target << 2);
140 		nextpc = epc;
141 		break;
142 
143 		/* These are conditional and in i_format. */
144 	case beq_op:
145 	case beql_op:
146 		if (arch->gprs[insn.i_format.rs] ==
147 		    arch->gprs[insn.i_format.rt])
148 			epc = epc + 4 + (insn.i_format.simmediate << 2);
149 		else
150 			epc += 8;
151 		nextpc = epc;
152 		break;
153 
154 	case bne_op:
155 	case bnel_op:
156 		if (arch->gprs[insn.i_format.rs] !=
157 		    arch->gprs[insn.i_format.rt])
158 			epc = epc + 4 + (insn.i_format.simmediate << 2);
159 		else
160 			epc += 8;
161 		nextpc = epc;
162 		break;
163 
164 	case blez_op:		/* not really i_format */
165 	case blezl_op:
166 		/* rt field assumed to be zero */
167 		if ((long)arch->gprs[insn.i_format.rs] <= 0)
168 			epc = epc + 4 + (insn.i_format.simmediate << 2);
169 		else
170 			epc += 8;
171 		nextpc = epc;
172 		break;
173 
174 	case bgtz_op:
175 	case bgtzl_op:
176 		/* rt field assumed to be zero */
177 		if ((long)arch->gprs[insn.i_format.rs] > 0)
178 			epc = epc + 4 + (insn.i_format.simmediate << 2);
179 		else
180 			epc += 8;
181 		nextpc = epc;
182 		break;
183 
184 		/* And now the FPA/cp1 branch instructions. */
185 	case cop1_op:
186 		kvm_err("%s: unsupported cop1_op\n", __func__);
187 		break;
188 	}
189 
190 	return nextpc;
191 
192 unaligned:
193 	kvm_err("%s: unaligned epc\n", __func__);
194 	return nextpc;
195 
196 sigill:
197 	kvm_err("%s: DSP branch but not DSP ASE\n", __func__);
198 	return nextpc;
199 }
200 
update_pc(struct kvm_vcpu * vcpu,uint32_t cause)201 enum emulation_result update_pc(struct kvm_vcpu *vcpu, uint32_t cause)
202 {
203 	unsigned long branch_pc;
204 	enum emulation_result er = EMULATE_DONE;
205 
206 	if (cause & CAUSEF_BD) {
207 		branch_pc = kvm_compute_return_epc(vcpu, vcpu->arch.pc);
208 		if (branch_pc == KVM_INVALID_INST) {
209 			er = EMULATE_FAIL;
210 		} else {
211 			vcpu->arch.pc = branch_pc;
212 			kvm_debug("BD update_pc(): New PC: %#lx\n",
213 				  vcpu->arch.pc);
214 		}
215 	} else
216 		vcpu->arch.pc += 4;
217 
218 	kvm_debug("update_pc(): New PC: %#lx\n", vcpu->arch.pc);
219 
220 	return er;
221 }
222 
223 /**
224  * kvm_mips_count_disabled() - Find whether the CP0_Count timer is disabled.
225  * @vcpu:	Virtual CPU.
226  *
227  * Returns:	1 if the CP0_Count timer is disabled by either the guest
228  *		CP0_Cause.DC bit or the count_ctl.DC bit.
229  *		0 otherwise (in which case CP0_Count timer is running).
230  */
kvm_mips_count_disabled(struct kvm_vcpu * vcpu)231 static inline int kvm_mips_count_disabled(struct kvm_vcpu *vcpu)
232 {
233 	struct mips_coproc *cop0 = vcpu->arch.cop0;
234 
235 	return	(vcpu->arch.count_ctl & KVM_REG_MIPS_COUNT_CTL_DC) ||
236 		(kvm_read_c0_guest_cause(cop0) & CAUSEF_DC);
237 }
238 
239 /**
240  * kvm_mips_ktime_to_count() - Scale ktime_t to a 32-bit count.
241  *
242  * Caches the dynamic nanosecond bias in vcpu->arch.count_dyn_bias.
243  *
244  * Assumes !kvm_mips_count_disabled(@vcpu) (guest CP0_Count timer is running).
245  */
kvm_mips_ktime_to_count(struct kvm_vcpu * vcpu,ktime_t now)246 static uint32_t kvm_mips_ktime_to_count(struct kvm_vcpu *vcpu, ktime_t now)
247 {
248 	s64 now_ns, periods;
249 	u64 delta;
250 
251 	now_ns = ktime_to_ns(now);
252 	delta = now_ns + vcpu->arch.count_dyn_bias;
253 
254 	if (delta >= vcpu->arch.count_period) {
255 		/* If delta is out of safe range the bias needs adjusting */
256 		periods = div64_s64(now_ns, vcpu->arch.count_period);
257 		vcpu->arch.count_dyn_bias = -periods * vcpu->arch.count_period;
258 		/* Recalculate delta with new bias */
259 		delta = now_ns + vcpu->arch.count_dyn_bias;
260 	}
261 
262 	/*
263 	 * We've ensured that:
264 	 *   delta < count_period
265 	 *
266 	 * Therefore the intermediate delta*count_hz will never overflow since
267 	 * at the boundary condition:
268 	 *   delta = count_period
269 	 *   delta = NSEC_PER_SEC * 2^32 / count_hz
270 	 *   delta * count_hz = NSEC_PER_SEC * 2^32
271 	 */
272 	return div_u64(delta * vcpu->arch.count_hz, NSEC_PER_SEC);
273 }
274 
275 /**
276  * kvm_mips_count_time() - Get effective current time.
277  * @vcpu:	Virtual CPU.
278  *
279  * Get effective monotonic ktime. This is usually a straightforward ktime_get(),
280  * except when the master disable bit is set in count_ctl, in which case it is
281  * count_resume, i.e. the time that the count was disabled.
282  *
283  * Returns:	Effective monotonic ktime for CP0_Count.
284  */
kvm_mips_count_time(struct kvm_vcpu * vcpu)285 static inline ktime_t kvm_mips_count_time(struct kvm_vcpu *vcpu)
286 {
287 	if (unlikely(vcpu->arch.count_ctl & KVM_REG_MIPS_COUNT_CTL_DC))
288 		return vcpu->arch.count_resume;
289 
290 	return ktime_get();
291 }
292 
293 /**
294  * kvm_mips_read_count_running() - Read the current count value as if running.
295  * @vcpu:	Virtual CPU.
296  * @now:	Kernel time to read CP0_Count at.
297  *
298  * Returns the current guest CP0_Count register at time @now and handles if the
299  * timer interrupt is pending and hasn't been handled yet.
300  *
301  * Returns:	The current value of the guest CP0_Count register.
302  */
kvm_mips_read_count_running(struct kvm_vcpu * vcpu,ktime_t now)303 static uint32_t kvm_mips_read_count_running(struct kvm_vcpu *vcpu, ktime_t now)
304 {
305 	struct mips_coproc *cop0 = vcpu->arch.cop0;
306 	ktime_t expires, threshold;
307 	uint32_t count, compare;
308 	int running;
309 
310 	/* Calculate the biased and scaled guest CP0_Count */
311 	count = vcpu->arch.count_bias + kvm_mips_ktime_to_count(vcpu, now);
312 	compare = kvm_read_c0_guest_compare(cop0);
313 
314 	/*
315 	 * Find whether CP0_Count has reached the closest timer interrupt. If
316 	 * not, we shouldn't inject it.
317 	 */
318 	if ((int32_t)(count - compare) < 0)
319 		return count;
320 
321 	/*
322 	 * The CP0_Count we're going to return has already reached the closest
323 	 * timer interrupt. Quickly check if it really is a new interrupt by
324 	 * looking at whether the interval until the hrtimer expiry time is
325 	 * less than 1/4 of the timer period.
326 	 */
327 	expires = hrtimer_get_expires(&vcpu->arch.comparecount_timer);
328 	threshold = ktime_add_ns(now, vcpu->arch.count_period / 4);
329 	if (ktime_before(expires, threshold)) {
330 		/*
331 		 * Cancel it while we handle it so there's no chance of
332 		 * interference with the timeout handler.
333 		 */
334 		running = hrtimer_cancel(&vcpu->arch.comparecount_timer);
335 
336 		/* Nothing should be waiting on the timeout */
337 		kvm_mips_callbacks->queue_timer_int(vcpu);
338 
339 		/*
340 		 * Restart the timer if it was running based on the expiry time
341 		 * we read, so that we don't push it back 2 periods.
342 		 */
343 		if (running) {
344 			expires = ktime_add_ns(expires,
345 					       vcpu->arch.count_period);
346 			hrtimer_start(&vcpu->arch.comparecount_timer, expires,
347 				      HRTIMER_MODE_ABS);
348 		}
349 	}
350 
351 	return count;
352 }
353 
354 /**
355  * kvm_mips_read_count() - Read the current count value.
356  * @vcpu:	Virtual CPU.
357  *
358  * Read the current guest CP0_Count value, taking into account whether the timer
359  * is stopped.
360  *
361  * Returns:	The current guest CP0_Count value.
362  */
kvm_mips_read_count(struct kvm_vcpu * vcpu)363 uint32_t kvm_mips_read_count(struct kvm_vcpu *vcpu)
364 {
365 	struct mips_coproc *cop0 = vcpu->arch.cop0;
366 
367 	/* If count disabled just read static copy of count */
368 	if (kvm_mips_count_disabled(vcpu))
369 		return kvm_read_c0_guest_count(cop0);
370 
371 	return kvm_mips_read_count_running(vcpu, ktime_get());
372 }
373 
374 /**
375  * kvm_mips_freeze_hrtimer() - Safely stop the hrtimer.
376  * @vcpu:	Virtual CPU.
377  * @count:	Output pointer for CP0_Count value at point of freeze.
378  *
379  * Freeze the hrtimer safely and return both the ktime and the CP0_Count value
380  * at the point it was frozen. It is guaranteed that any pending interrupts at
381  * the point it was frozen are handled, and none after that point.
382  *
383  * This is useful where the time/CP0_Count is needed in the calculation of the
384  * new parameters.
385  *
386  * Assumes !kvm_mips_count_disabled(@vcpu) (guest CP0_Count timer is running).
387  *
388  * Returns:	The ktime at the point of freeze.
389  */
kvm_mips_freeze_hrtimer(struct kvm_vcpu * vcpu,uint32_t * count)390 static ktime_t kvm_mips_freeze_hrtimer(struct kvm_vcpu *vcpu,
391 				       uint32_t *count)
392 {
393 	ktime_t now;
394 
395 	/* stop hrtimer before finding time */
396 	hrtimer_cancel(&vcpu->arch.comparecount_timer);
397 	now = ktime_get();
398 
399 	/* find count at this point and handle pending hrtimer */
400 	*count = kvm_mips_read_count_running(vcpu, now);
401 
402 	return now;
403 }
404 
405 /**
406  * kvm_mips_resume_hrtimer() - Resume hrtimer, updating expiry.
407  * @vcpu:	Virtual CPU.
408  * @now:	ktime at point of resume.
409  * @count:	CP0_Count at point of resume.
410  *
411  * Resumes the timer and updates the timer expiry based on @now and @count.
412  * This can be used in conjunction with kvm_mips_freeze_timer() when timer
413  * parameters need to be changed.
414  *
415  * It is guaranteed that a timer interrupt immediately after resume will be
416  * handled, but not if CP_Compare is exactly at @count. That case is already
417  * handled by kvm_mips_freeze_timer().
418  *
419  * Assumes !kvm_mips_count_disabled(@vcpu) (guest CP0_Count timer is running).
420  */
kvm_mips_resume_hrtimer(struct kvm_vcpu * vcpu,ktime_t now,uint32_t count)421 static void kvm_mips_resume_hrtimer(struct kvm_vcpu *vcpu,
422 				    ktime_t now, uint32_t count)
423 {
424 	struct mips_coproc *cop0 = vcpu->arch.cop0;
425 	uint32_t compare;
426 	u64 delta;
427 	ktime_t expire;
428 
429 	/* Calculate timeout (wrap 0 to 2^32) */
430 	compare = kvm_read_c0_guest_compare(cop0);
431 	delta = (u64)(uint32_t)(compare - count - 1) + 1;
432 	delta = div_u64(delta * NSEC_PER_SEC, vcpu->arch.count_hz);
433 	expire = ktime_add_ns(now, delta);
434 
435 	/* Update hrtimer to use new timeout */
436 	hrtimer_cancel(&vcpu->arch.comparecount_timer);
437 	hrtimer_start(&vcpu->arch.comparecount_timer, expire, HRTIMER_MODE_ABS);
438 }
439 
440 /**
441  * kvm_mips_write_count() - Modify the count and update timer.
442  * @vcpu:	Virtual CPU.
443  * @count:	Guest CP0_Count value to set.
444  *
445  * Sets the CP0_Count value and updates the timer accordingly.
446  */
kvm_mips_write_count(struct kvm_vcpu * vcpu,uint32_t count)447 void kvm_mips_write_count(struct kvm_vcpu *vcpu, uint32_t count)
448 {
449 	struct mips_coproc *cop0 = vcpu->arch.cop0;
450 	ktime_t now;
451 
452 	/* Calculate bias */
453 	now = kvm_mips_count_time(vcpu);
454 	vcpu->arch.count_bias = count - kvm_mips_ktime_to_count(vcpu, now);
455 
456 	if (kvm_mips_count_disabled(vcpu))
457 		/* The timer's disabled, adjust the static count */
458 		kvm_write_c0_guest_count(cop0, count);
459 	else
460 		/* Update timeout */
461 		kvm_mips_resume_hrtimer(vcpu, now, count);
462 }
463 
464 /**
465  * kvm_mips_init_count() - Initialise timer.
466  * @vcpu:	Virtual CPU.
467  *
468  * Initialise the timer to a sensible frequency, namely 100MHz, zero it, and set
469  * it going if it's enabled.
470  */
kvm_mips_init_count(struct kvm_vcpu * vcpu)471 void kvm_mips_init_count(struct kvm_vcpu *vcpu)
472 {
473 	/* 100 MHz */
474 	vcpu->arch.count_hz = 100*1000*1000;
475 	vcpu->arch.count_period = div_u64((u64)NSEC_PER_SEC << 32,
476 					  vcpu->arch.count_hz);
477 	vcpu->arch.count_dyn_bias = 0;
478 
479 	/* Starting at 0 */
480 	kvm_mips_write_count(vcpu, 0);
481 }
482 
483 /**
484  * kvm_mips_set_count_hz() - Update the frequency of the timer.
485  * @vcpu:	Virtual CPU.
486  * @count_hz:	Frequency of CP0_Count timer in Hz.
487  *
488  * Change the frequency of the CP0_Count timer. This is done atomically so that
489  * CP0_Count is continuous and no timer interrupt is lost.
490  *
491  * Returns:	-EINVAL if @count_hz is out of range.
492  *		0 on success.
493  */
kvm_mips_set_count_hz(struct kvm_vcpu * vcpu,s64 count_hz)494 int kvm_mips_set_count_hz(struct kvm_vcpu *vcpu, s64 count_hz)
495 {
496 	struct mips_coproc *cop0 = vcpu->arch.cop0;
497 	int dc;
498 	ktime_t now;
499 	u32 count;
500 
501 	/* ensure the frequency is in a sensible range... */
502 	if (count_hz <= 0 || count_hz > NSEC_PER_SEC)
503 		return -EINVAL;
504 	/* ... and has actually changed */
505 	if (vcpu->arch.count_hz == count_hz)
506 		return 0;
507 
508 	/* Safely freeze timer so we can keep it continuous */
509 	dc = kvm_mips_count_disabled(vcpu);
510 	if (dc) {
511 		now = kvm_mips_count_time(vcpu);
512 		count = kvm_read_c0_guest_count(cop0);
513 	} else {
514 		now = kvm_mips_freeze_hrtimer(vcpu, &count);
515 	}
516 
517 	/* Update the frequency */
518 	vcpu->arch.count_hz = count_hz;
519 	vcpu->arch.count_period = div_u64((u64)NSEC_PER_SEC << 32, count_hz);
520 	vcpu->arch.count_dyn_bias = 0;
521 
522 	/* Calculate adjusted bias so dynamic count is unchanged */
523 	vcpu->arch.count_bias = count - kvm_mips_ktime_to_count(vcpu, now);
524 
525 	/* Update and resume hrtimer */
526 	if (!dc)
527 		kvm_mips_resume_hrtimer(vcpu, now, count);
528 	return 0;
529 }
530 
531 /**
532  * kvm_mips_write_compare() - Modify compare and update timer.
533  * @vcpu:	Virtual CPU.
534  * @compare:	New CP0_Compare value.
535  * @ack:	Whether to acknowledge timer interrupt.
536  *
537  * Update CP0_Compare to a new value and update the timeout.
538  * If @ack, atomically acknowledge any pending timer interrupt, otherwise ensure
539  * any pending timer interrupt is preserved.
540  */
kvm_mips_write_compare(struct kvm_vcpu * vcpu,uint32_t compare,bool ack)541 void kvm_mips_write_compare(struct kvm_vcpu *vcpu, uint32_t compare, bool ack)
542 {
543 	struct mips_coproc *cop0 = vcpu->arch.cop0;
544 	int dc;
545 	u32 old_compare = kvm_read_c0_guest_compare(cop0);
546 	ktime_t now;
547 	uint32_t count;
548 
549 	/* if unchanged, must just be an ack */
550 	if (old_compare == compare) {
551 		if (!ack)
552 			return;
553 		kvm_mips_callbacks->dequeue_timer_int(vcpu);
554 		kvm_write_c0_guest_compare(cop0, compare);
555 		return;
556 	}
557 
558 	/* freeze_hrtimer() takes care of timer interrupts <= count */
559 	dc = kvm_mips_count_disabled(vcpu);
560 	if (!dc)
561 		now = kvm_mips_freeze_hrtimer(vcpu, &count);
562 
563 	if (ack)
564 		kvm_mips_callbacks->dequeue_timer_int(vcpu);
565 
566 	kvm_write_c0_guest_compare(cop0, compare);
567 
568 	/* resume_hrtimer() takes care of timer interrupts > count */
569 	if (!dc)
570 		kvm_mips_resume_hrtimer(vcpu, now, count);
571 }
572 
573 /**
574  * kvm_mips_count_disable() - Disable count.
575  * @vcpu:	Virtual CPU.
576  *
577  * Disable the CP0_Count timer. A timer interrupt on or before the final stop
578  * time will be handled but not after.
579  *
580  * Assumes CP0_Count was previously enabled but now Guest.CP0_Cause.DC or
581  * count_ctl.DC has been set (count disabled).
582  *
583  * Returns:	The time that the timer was stopped.
584  */
kvm_mips_count_disable(struct kvm_vcpu * vcpu)585 static ktime_t kvm_mips_count_disable(struct kvm_vcpu *vcpu)
586 {
587 	struct mips_coproc *cop0 = vcpu->arch.cop0;
588 	uint32_t count;
589 	ktime_t now;
590 
591 	/* Stop hrtimer */
592 	hrtimer_cancel(&vcpu->arch.comparecount_timer);
593 
594 	/* Set the static count from the dynamic count, handling pending TI */
595 	now = ktime_get();
596 	count = kvm_mips_read_count_running(vcpu, now);
597 	kvm_write_c0_guest_count(cop0, count);
598 
599 	return now;
600 }
601 
602 /**
603  * kvm_mips_count_disable_cause() - Disable count using CP0_Cause.DC.
604  * @vcpu:	Virtual CPU.
605  *
606  * Disable the CP0_Count timer and set CP0_Cause.DC. A timer interrupt on or
607  * before the final stop time will be handled if the timer isn't disabled by
608  * count_ctl.DC, but not after.
609  *
610  * Assumes CP0_Cause.DC is clear (count enabled).
611  */
kvm_mips_count_disable_cause(struct kvm_vcpu * vcpu)612 void kvm_mips_count_disable_cause(struct kvm_vcpu *vcpu)
613 {
614 	struct mips_coproc *cop0 = vcpu->arch.cop0;
615 
616 	kvm_set_c0_guest_cause(cop0, CAUSEF_DC);
617 	if (!(vcpu->arch.count_ctl & KVM_REG_MIPS_COUNT_CTL_DC))
618 		kvm_mips_count_disable(vcpu);
619 }
620 
621 /**
622  * kvm_mips_count_enable_cause() - Enable count using CP0_Cause.DC.
623  * @vcpu:	Virtual CPU.
624  *
625  * Enable the CP0_Count timer and clear CP0_Cause.DC. A timer interrupt after
626  * the start time will be handled if the timer isn't disabled by count_ctl.DC,
627  * potentially before even returning, so the caller should be careful with
628  * ordering of CP0_Cause modifications so as not to lose it.
629  *
630  * Assumes CP0_Cause.DC is set (count disabled).
631  */
kvm_mips_count_enable_cause(struct kvm_vcpu * vcpu)632 void kvm_mips_count_enable_cause(struct kvm_vcpu *vcpu)
633 {
634 	struct mips_coproc *cop0 = vcpu->arch.cop0;
635 	uint32_t count;
636 
637 	kvm_clear_c0_guest_cause(cop0, CAUSEF_DC);
638 
639 	/*
640 	 * Set the dynamic count to match the static count.
641 	 * This starts the hrtimer if count_ctl.DC allows it.
642 	 * Otherwise it conveniently updates the biases.
643 	 */
644 	count = kvm_read_c0_guest_count(cop0);
645 	kvm_mips_write_count(vcpu, count);
646 }
647 
648 /**
649  * kvm_mips_set_count_ctl() - Update the count control KVM register.
650  * @vcpu:	Virtual CPU.
651  * @count_ctl:	Count control register new value.
652  *
653  * Set the count control KVM register. The timer is updated accordingly.
654  *
655  * Returns:	-EINVAL if reserved bits are set.
656  *		0 on success.
657  */
kvm_mips_set_count_ctl(struct kvm_vcpu * vcpu,s64 count_ctl)658 int kvm_mips_set_count_ctl(struct kvm_vcpu *vcpu, s64 count_ctl)
659 {
660 	struct mips_coproc *cop0 = vcpu->arch.cop0;
661 	s64 changed = count_ctl ^ vcpu->arch.count_ctl;
662 	s64 delta;
663 	ktime_t expire, now;
664 	uint32_t count, compare;
665 
666 	/* Only allow defined bits to be changed */
667 	if (changed & ~(s64)(KVM_REG_MIPS_COUNT_CTL_DC))
668 		return -EINVAL;
669 
670 	/* Apply new value */
671 	vcpu->arch.count_ctl = count_ctl;
672 
673 	/* Master CP0_Count disable */
674 	if (changed & KVM_REG_MIPS_COUNT_CTL_DC) {
675 		/* Is CP0_Cause.DC already disabling CP0_Count? */
676 		if (kvm_read_c0_guest_cause(cop0) & CAUSEF_DC) {
677 			if (count_ctl & KVM_REG_MIPS_COUNT_CTL_DC)
678 				/* Just record the current time */
679 				vcpu->arch.count_resume = ktime_get();
680 		} else if (count_ctl & KVM_REG_MIPS_COUNT_CTL_DC) {
681 			/* disable timer and record current time */
682 			vcpu->arch.count_resume = kvm_mips_count_disable(vcpu);
683 		} else {
684 			/*
685 			 * Calculate timeout relative to static count at resume
686 			 * time (wrap 0 to 2^32).
687 			 */
688 			count = kvm_read_c0_guest_count(cop0);
689 			compare = kvm_read_c0_guest_compare(cop0);
690 			delta = (u64)(uint32_t)(compare - count - 1) + 1;
691 			delta = div_u64(delta * NSEC_PER_SEC,
692 					vcpu->arch.count_hz);
693 			expire = ktime_add_ns(vcpu->arch.count_resume, delta);
694 
695 			/* Handle pending interrupt */
696 			now = ktime_get();
697 			if (ktime_compare(now, expire) >= 0)
698 				/* Nothing should be waiting on the timeout */
699 				kvm_mips_callbacks->queue_timer_int(vcpu);
700 
701 			/* Resume hrtimer without changing bias */
702 			count = kvm_mips_read_count_running(vcpu, now);
703 			kvm_mips_resume_hrtimer(vcpu, now, count);
704 		}
705 	}
706 
707 	return 0;
708 }
709 
710 /**
711  * kvm_mips_set_count_resume() - Update the count resume KVM register.
712  * @vcpu:		Virtual CPU.
713  * @count_resume:	Count resume register new value.
714  *
715  * Set the count resume KVM register.
716  *
717  * Returns:	-EINVAL if out of valid range (0..now).
718  *		0 on success.
719  */
kvm_mips_set_count_resume(struct kvm_vcpu * vcpu,s64 count_resume)720 int kvm_mips_set_count_resume(struct kvm_vcpu *vcpu, s64 count_resume)
721 {
722 	/*
723 	 * It doesn't make sense for the resume time to be in the future, as it
724 	 * would be possible for the next interrupt to be more than a full
725 	 * period in the future.
726 	 */
727 	if (count_resume < 0 || count_resume > ktime_to_ns(ktime_get()))
728 		return -EINVAL;
729 
730 	vcpu->arch.count_resume = ns_to_ktime(count_resume);
731 	return 0;
732 }
733 
734 /**
735  * kvm_mips_count_timeout() - Push timer forward on timeout.
736  * @vcpu:	Virtual CPU.
737  *
738  * Handle an hrtimer event by push the hrtimer forward a period.
739  *
740  * Returns:	The hrtimer_restart value to return to the hrtimer subsystem.
741  */
kvm_mips_count_timeout(struct kvm_vcpu * vcpu)742 enum hrtimer_restart kvm_mips_count_timeout(struct kvm_vcpu *vcpu)
743 {
744 	/* Add the Count period to the current expiry time */
745 	hrtimer_add_expires_ns(&vcpu->arch.comparecount_timer,
746 			       vcpu->arch.count_period);
747 	return HRTIMER_RESTART;
748 }
749 
kvm_mips_emul_eret(struct kvm_vcpu * vcpu)750 enum emulation_result kvm_mips_emul_eret(struct kvm_vcpu *vcpu)
751 {
752 	struct mips_coproc *cop0 = vcpu->arch.cop0;
753 	enum emulation_result er = EMULATE_DONE;
754 
755 	if (kvm_read_c0_guest_status(cop0) & ST0_ERL) {
756 		kvm_clear_c0_guest_status(cop0, ST0_ERL);
757 		vcpu->arch.pc = kvm_read_c0_guest_errorepc(cop0);
758 	} else if (kvm_read_c0_guest_status(cop0) & ST0_EXL) {
759 		kvm_debug("[%#lx] ERET to %#lx\n", vcpu->arch.pc,
760 			  kvm_read_c0_guest_epc(cop0));
761 		kvm_clear_c0_guest_status(cop0, ST0_EXL);
762 		vcpu->arch.pc = kvm_read_c0_guest_epc(cop0);
763 
764 	} else {
765 		kvm_err("[%#lx] ERET when MIPS_SR_EXL|MIPS_SR_ERL == 0\n",
766 			vcpu->arch.pc);
767 		er = EMULATE_FAIL;
768 	}
769 
770 	return er;
771 }
772 
kvm_mips_emul_wait(struct kvm_vcpu * vcpu)773 enum emulation_result kvm_mips_emul_wait(struct kvm_vcpu *vcpu)
774 {
775 	kvm_debug("[%#lx] !!!WAIT!!! (%#lx)\n", vcpu->arch.pc,
776 		  vcpu->arch.pending_exceptions);
777 
778 	++vcpu->stat.wait_exits;
779 	trace_kvm_exit(vcpu, WAIT_EXITS);
780 	if (!vcpu->arch.pending_exceptions) {
781 		vcpu->arch.wait = 1;
782 		kvm_vcpu_block(vcpu);
783 
784 		/*
785 		 * We we are runnable, then definitely go off to user space to
786 		 * check if any I/O interrupts are pending.
787 		 */
788 		if (kvm_check_request(KVM_REQ_UNHALT, vcpu)) {
789 			clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
790 			vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
791 		}
792 	}
793 
794 	return EMULATE_DONE;
795 }
796 
797 /*
798  * XXXKYMA: Linux doesn't seem to use TLBR, return EMULATE_FAIL for now so that
799  * we can catch this, if things ever change
800  */
kvm_mips_emul_tlbr(struct kvm_vcpu * vcpu)801 enum emulation_result kvm_mips_emul_tlbr(struct kvm_vcpu *vcpu)
802 {
803 	struct mips_coproc *cop0 = vcpu->arch.cop0;
804 	uint32_t pc = vcpu->arch.pc;
805 
806 	kvm_err("[%#x] COP0_TLBR [%ld]\n", pc, kvm_read_c0_guest_index(cop0));
807 	return EMULATE_FAIL;
808 }
809 
810 /* Write Guest TLB Entry @ Index */
kvm_mips_emul_tlbwi(struct kvm_vcpu * vcpu)811 enum emulation_result kvm_mips_emul_tlbwi(struct kvm_vcpu *vcpu)
812 {
813 	struct mips_coproc *cop0 = vcpu->arch.cop0;
814 	int index = kvm_read_c0_guest_index(cop0);
815 	struct kvm_mips_tlb *tlb = NULL;
816 	uint32_t pc = vcpu->arch.pc;
817 
818 	if (index < 0 || index >= KVM_MIPS_GUEST_TLB_SIZE) {
819 		kvm_debug("%s: illegal index: %d\n", __func__, index);
820 		kvm_debug("[%#x] COP0_TLBWI [%d] (entryhi: %#lx, entrylo0: %#lx entrylo1: %#lx, mask: %#lx)\n",
821 			  pc, index, kvm_read_c0_guest_entryhi(cop0),
822 			  kvm_read_c0_guest_entrylo0(cop0),
823 			  kvm_read_c0_guest_entrylo1(cop0),
824 			  kvm_read_c0_guest_pagemask(cop0));
825 		index = (index & ~0x80000000) % KVM_MIPS_GUEST_TLB_SIZE;
826 	}
827 
828 	tlb = &vcpu->arch.guest_tlb[index];
829 	/*
830 	 * Probe the shadow host TLB for the entry being overwritten, if one
831 	 * matches, invalidate it
832 	 */
833 	kvm_mips_host_tlb_inv(vcpu, tlb->tlb_hi);
834 
835 	tlb->tlb_mask = kvm_read_c0_guest_pagemask(cop0);
836 	tlb->tlb_hi = kvm_read_c0_guest_entryhi(cop0);
837 	tlb->tlb_lo0 = kvm_read_c0_guest_entrylo0(cop0);
838 	tlb->tlb_lo1 = kvm_read_c0_guest_entrylo1(cop0);
839 
840 	kvm_debug("[%#x] COP0_TLBWI [%d] (entryhi: %#lx, entrylo0: %#lx entrylo1: %#lx, mask: %#lx)\n",
841 		  pc, index, kvm_read_c0_guest_entryhi(cop0),
842 		  kvm_read_c0_guest_entrylo0(cop0),
843 		  kvm_read_c0_guest_entrylo1(cop0),
844 		  kvm_read_c0_guest_pagemask(cop0));
845 
846 	return EMULATE_DONE;
847 }
848 
849 /* Write Guest TLB Entry @ Random Index */
kvm_mips_emul_tlbwr(struct kvm_vcpu * vcpu)850 enum emulation_result kvm_mips_emul_tlbwr(struct kvm_vcpu *vcpu)
851 {
852 	struct mips_coproc *cop0 = vcpu->arch.cop0;
853 	struct kvm_mips_tlb *tlb = NULL;
854 	uint32_t pc = vcpu->arch.pc;
855 	int index;
856 
857 	get_random_bytes(&index, sizeof(index));
858 	index &= (KVM_MIPS_GUEST_TLB_SIZE - 1);
859 
860 	tlb = &vcpu->arch.guest_tlb[index];
861 
862 	/*
863 	 * Probe the shadow host TLB for the entry being overwritten, if one
864 	 * matches, invalidate it
865 	 */
866 	kvm_mips_host_tlb_inv(vcpu, tlb->tlb_hi);
867 
868 	tlb->tlb_mask = kvm_read_c0_guest_pagemask(cop0);
869 	tlb->tlb_hi = kvm_read_c0_guest_entryhi(cop0);
870 	tlb->tlb_lo0 = kvm_read_c0_guest_entrylo0(cop0);
871 	tlb->tlb_lo1 = kvm_read_c0_guest_entrylo1(cop0);
872 
873 	kvm_debug("[%#x] COP0_TLBWR[%d] (entryhi: %#lx, entrylo0: %#lx entrylo1: %#lx)\n",
874 		  pc, index, kvm_read_c0_guest_entryhi(cop0),
875 		  kvm_read_c0_guest_entrylo0(cop0),
876 		  kvm_read_c0_guest_entrylo1(cop0));
877 
878 	return EMULATE_DONE;
879 }
880 
kvm_mips_emul_tlbp(struct kvm_vcpu * vcpu)881 enum emulation_result kvm_mips_emul_tlbp(struct kvm_vcpu *vcpu)
882 {
883 	struct mips_coproc *cop0 = vcpu->arch.cop0;
884 	long entryhi = kvm_read_c0_guest_entryhi(cop0);
885 	uint32_t pc = vcpu->arch.pc;
886 	int index = -1;
887 
888 	index = kvm_mips_guest_tlb_lookup(vcpu, entryhi);
889 
890 	kvm_write_c0_guest_index(cop0, index);
891 
892 	kvm_debug("[%#x] COP0_TLBP (entryhi: %#lx), index: %d\n", pc, entryhi,
893 		  index);
894 
895 	return EMULATE_DONE;
896 }
897 
kvm_mips_emulate_CP0(uint32_t inst,uint32_t * opc,uint32_t cause,struct kvm_run * run,struct kvm_vcpu * vcpu)898 enum emulation_result kvm_mips_emulate_CP0(uint32_t inst, uint32_t *opc,
899 					   uint32_t cause, struct kvm_run *run,
900 					   struct kvm_vcpu *vcpu)
901 {
902 	struct mips_coproc *cop0 = vcpu->arch.cop0;
903 	enum emulation_result er = EMULATE_DONE;
904 	int32_t rt, rd, copz, sel, co_bit, op;
905 	uint32_t pc = vcpu->arch.pc;
906 	unsigned long curr_pc;
907 
908 	/*
909 	 * Update PC and hold onto current PC in case there is
910 	 * an error and we want to rollback the PC
911 	 */
912 	curr_pc = vcpu->arch.pc;
913 	er = update_pc(vcpu, cause);
914 	if (er == EMULATE_FAIL)
915 		return er;
916 
917 	copz = (inst >> 21) & 0x1f;
918 	rt = (inst >> 16) & 0x1f;
919 	rd = (inst >> 11) & 0x1f;
920 	sel = inst & 0x7;
921 	co_bit = (inst >> 25) & 1;
922 
923 	if (co_bit) {
924 		op = (inst) & 0xff;
925 
926 		switch (op) {
927 		case tlbr_op:	/*  Read indexed TLB entry  */
928 			er = kvm_mips_emul_tlbr(vcpu);
929 			break;
930 		case tlbwi_op:	/*  Write indexed  */
931 			er = kvm_mips_emul_tlbwi(vcpu);
932 			break;
933 		case tlbwr_op:	/*  Write random  */
934 			er = kvm_mips_emul_tlbwr(vcpu);
935 			break;
936 		case tlbp_op:	/* TLB Probe */
937 			er = kvm_mips_emul_tlbp(vcpu);
938 			break;
939 		case rfe_op:
940 			kvm_err("!!!COP0_RFE!!!\n");
941 			break;
942 		case eret_op:
943 			er = kvm_mips_emul_eret(vcpu);
944 			goto dont_update_pc;
945 			break;
946 		case wait_op:
947 			er = kvm_mips_emul_wait(vcpu);
948 			break;
949 		}
950 	} else {
951 		switch (copz) {
952 		case mfc_op:
953 #ifdef CONFIG_KVM_MIPS_DEBUG_COP0_COUNTERS
954 			cop0->stat[rd][sel]++;
955 #endif
956 			/* Get reg */
957 			if ((rd == MIPS_CP0_COUNT) && (sel == 0)) {
958 				vcpu->arch.gprs[rt] = kvm_mips_read_count(vcpu);
959 			} else if ((rd == MIPS_CP0_ERRCTL) && (sel == 0)) {
960 				vcpu->arch.gprs[rt] = 0x0;
961 #ifdef CONFIG_KVM_MIPS_DYN_TRANS
962 				kvm_mips_trans_mfc0(inst, opc, vcpu);
963 #endif
964 			} else {
965 				vcpu->arch.gprs[rt] = cop0->reg[rd][sel];
966 
967 #ifdef CONFIG_KVM_MIPS_DYN_TRANS
968 				kvm_mips_trans_mfc0(inst, opc, vcpu);
969 #endif
970 			}
971 
972 			kvm_debug
973 			    ("[%#x] MFCz[%d][%d], vcpu->arch.gprs[%d]: %#lx\n",
974 			     pc, rd, sel, rt, vcpu->arch.gprs[rt]);
975 
976 			break;
977 
978 		case dmfc_op:
979 			vcpu->arch.gprs[rt] = cop0->reg[rd][sel];
980 			break;
981 
982 		case mtc_op:
983 #ifdef CONFIG_KVM_MIPS_DEBUG_COP0_COUNTERS
984 			cop0->stat[rd][sel]++;
985 #endif
986 			if ((rd == MIPS_CP0_TLB_INDEX)
987 			    && (vcpu->arch.gprs[rt] >=
988 				KVM_MIPS_GUEST_TLB_SIZE)) {
989 				kvm_err("Invalid TLB Index: %ld",
990 					vcpu->arch.gprs[rt]);
991 				er = EMULATE_FAIL;
992 				break;
993 			}
994 #define C0_EBASE_CORE_MASK 0xff
995 			if ((rd == MIPS_CP0_PRID) && (sel == 1)) {
996 				/* Preserve CORE number */
997 				kvm_change_c0_guest_ebase(cop0,
998 							  ~(C0_EBASE_CORE_MASK),
999 							  vcpu->arch.gprs[rt]);
1000 				kvm_err("MTCz, cop0->reg[EBASE]: %#lx\n",
1001 					kvm_read_c0_guest_ebase(cop0));
1002 			} else if (rd == MIPS_CP0_TLB_HI && sel == 0) {
1003 				uint32_t nasid =
1004 					vcpu->arch.gprs[rt] & ASID_MASK;
1005 				if ((KSEGX(vcpu->arch.gprs[rt]) != CKSEG0) &&
1006 				    ((kvm_read_c0_guest_entryhi(cop0) &
1007 				      ASID_MASK) != nasid)) {
1008 					kvm_debug("MTCz, change ASID from %#lx to %#lx\n",
1009 						kvm_read_c0_guest_entryhi(cop0)
1010 						& ASID_MASK,
1011 						vcpu->arch.gprs[rt]
1012 						& ASID_MASK);
1013 
1014 					/* Blow away the shadow host TLBs */
1015 					kvm_mips_flush_host_tlb(1);
1016 				}
1017 				kvm_write_c0_guest_entryhi(cop0,
1018 							   vcpu->arch.gprs[rt]);
1019 			}
1020 			/* Are we writing to COUNT */
1021 			else if ((rd == MIPS_CP0_COUNT) && (sel == 0)) {
1022 				kvm_mips_write_count(vcpu, vcpu->arch.gprs[rt]);
1023 				goto done;
1024 			} else if ((rd == MIPS_CP0_COMPARE) && (sel == 0)) {
1025 				kvm_debug("[%#x] MTCz, COMPARE %#lx <- %#lx\n",
1026 					  pc, kvm_read_c0_guest_compare(cop0),
1027 					  vcpu->arch.gprs[rt]);
1028 
1029 				/* If we are writing to COMPARE */
1030 				/* Clear pending timer interrupt, if any */
1031 				kvm_mips_write_compare(vcpu,
1032 						       vcpu->arch.gprs[rt],
1033 						       true);
1034 			} else if ((rd == MIPS_CP0_STATUS) && (sel == 0)) {
1035 				kvm_write_c0_guest_status(cop0,
1036 							  vcpu->arch.gprs[rt]);
1037 				/*
1038 				 * Make sure that CU1 and NMI bits are
1039 				 * never set
1040 				 */
1041 				kvm_clear_c0_guest_status(cop0,
1042 							  (ST0_CU1 | ST0_NMI));
1043 
1044 #ifdef CONFIG_KVM_MIPS_DYN_TRANS
1045 				kvm_mips_trans_mtc0(inst, opc, vcpu);
1046 #endif
1047 			} else if ((rd == MIPS_CP0_CAUSE) && (sel == 0)) {
1048 				uint32_t old_cause, new_cause;
1049 
1050 				old_cause = kvm_read_c0_guest_cause(cop0);
1051 				new_cause = vcpu->arch.gprs[rt];
1052 				/* Update R/W bits */
1053 				kvm_change_c0_guest_cause(cop0, 0x08800300,
1054 							  new_cause);
1055 				/* DC bit enabling/disabling timer? */
1056 				if ((old_cause ^ new_cause) & CAUSEF_DC) {
1057 					if (new_cause & CAUSEF_DC)
1058 						kvm_mips_count_disable_cause(vcpu);
1059 					else
1060 						kvm_mips_count_enable_cause(vcpu);
1061 				}
1062 			} else {
1063 				cop0->reg[rd][sel] = vcpu->arch.gprs[rt];
1064 #ifdef CONFIG_KVM_MIPS_DYN_TRANS
1065 				kvm_mips_trans_mtc0(inst, opc, vcpu);
1066 #endif
1067 			}
1068 
1069 			kvm_debug("[%#x] MTCz, cop0->reg[%d][%d]: %#lx\n", pc,
1070 				  rd, sel, cop0->reg[rd][sel]);
1071 			break;
1072 
1073 		case dmtc_op:
1074 			kvm_err("!!!!!!![%#lx]dmtc_op: rt: %d, rd: %d, sel: %d!!!!!!\n",
1075 				vcpu->arch.pc, rt, rd, sel);
1076 			er = EMULATE_FAIL;
1077 			break;
1078 
1079 		case mfmcz_op:
1080 #ifdef KVM_MIPS_DEBUG_COP0_COUNTERS
1081 			cop0->stat[MIPS_CP0_STATUS][0]++;
1082 #endif
1083 			if (rt != 0) {
1084 				vcpu->arch.gprs[rt] =
1085 				    kvm_read_c0_guest_status(cop0);
1086 			}
1087 			/* EI */
1088 			if (inst & 0x20) {
1089 				kvm_debug("[%#lx] mfmcz_op: EI\n",
1090 					  vcpu->arch.pc);
1091 				kvm_set_c0_guest_status(cop0, ST0_IE);
1092 			} else {
1093 				kvm_debug("[%#lx] mfmcz_op: DI\n",
1094 					  vcpu->arch.pc);
1095 				kvm_clear_c0_guest_status(cop0, ST0_IE);
1096 			}
1097 
1098 			break;
1099 
1100 		case wrpgpr_op:
1101 			{
1102 				uint32_t css =
1103 				    cop0->reg[MIPS_CP0_STATUS][2] & 0xf;
1104 				uint32_t pss =
1105 				    (cop0->reg[MIPS_CP0_STATUS][2] >> 6) & 0xf;
1106 				/*
1107 				 * We don't support any shadow register sets, so
1108 				 * SRSCtl[PSS] == SRSCtl[CSS] = 0
1109 				 */
1110 				if (css || pss) {
1111 					er = EMULATE_FAIL;
1112 					break;
1113 				}
1114 				kvm_debug("WRPGPR[%d][%d] = %#lx\n", pss, rd,
1115 					  vcpu->arch.gprs[rt]);
1116 				vcpu->arch.gprs[rd] = vcpu->arch.gprs[rt];
1117 			}
1118 			break;
1119 		default:
1120 			kvm_err("[%#lx]MachEmulateCP0: unsupported COP0, copz: 0x%x\n",
1121 				vcpu->arch.pc, copz);
1122 			er = EMULATE_FAIL;
1123 			break;
1124 		}
1125 	}
1126 
1127 done:
1128 	/* Rollback PC only if emulation was unsuccessful */
1129 	if (er == EMULATE_FAIL)
1130 		vcpu->arch.pc = curr_pc;
1131 
1132 dont_update_pc:
1133 	/*
1134 	 * This is for special instructions whose emulation
1135 	 * updates the PC, so do not overwrite the PC under
1136 	 * any circumstances
1137 	 */
1138 
1139 	return er;
1140 }
1141 
kvm_mips_emulate_store(uint32_t inst,uint32_t cause,struct kvm_run * run,struct kvm_vcpu * vcpu)1142 enum emulation_result kvm_mips_emulate_store(uint32_t inst, uint32_t cause,
1143 					     struct kvm_run *run,
1144 					     struct kvm_vcpu *vcpu)
1145 {
1146 	enum emulation_result er = EMULATE_DO_MMIO;
1147 	int32_t op, base, rt, offset;
1148 	uint32_t bytes;
1149 	void *data = run->mmio.data;
1150 	unsigned long curr_pc;
1151 
1152 	/*
1153 	 * Update PC and hold onto current PC in case there is
1154 	 * an error and we want to rollback the PC
1155 	 */
1156 	curr_pc = vcpu->arch.pc;
1157 	er = update_pc(vcpu, cause);
1158 	if (er == EMULATE_FAIL)
1159 		return er;
1160 
1161 	rt = (inst >> 16) & 0x1f;
1162 	base = (inst >> 21) & 0x1f;
1163 	offset = inst & 0xffff;
1164 	op = (inst >> 26) & 0x3f;
1165 
1166 	switch (op) {
1167 	case sb_op:
1168 		bytes = 1;
1169 		if (bytes > sizeof(run->mmio.data)) {
1170 			kvm_err("%s: bad MMIO length: %d\n", __func__,
1171 			       run->mmio.len);
1172 		}
1173 		run->mmio.phys_addr =
1174 		    kvm_mips_callbacks->gva_to_gpa(vcpu->arch.
1175 						   host_cp0_badvaddr);
1176 		if (run->mmio.phys_addr == KVM_INVALID_ADDR) {
1177 			er = EMULATE_FAIL;
1178 			break;
1179 		}
1180 		run->mmio.len = bytes;
1181 		run->mmio.is_write = 1;
1182 		vcpu->mmio_needed = 1;
1183 		vcpu->mmio_is_write = 1;
1184 		*(u8 *) data = vcpu->arch.gprs[rt];
1185 		kvm_debug("OP_SB: eaddr: %#lx, gpr: %#lx, data: %#x\n",
1186 			  vcpu->arch.host_cp0_badvaddr, vcpu->arch.gprs[rt],
1187 			  *(uint8_t *) data);
1188 
1189 		break;
1190 
1191 	case sw_op:
1192 		bytes = 4;
1193 		if (bytes > sizeof(run->mmio.data)) {
1194 			kvm_err("%s: bad MMIO length: %d\n", __func__,
1195 			       run->mmio.len);
1196 		}
1197 		run->mmio.phys_addr =
1198 		    kvm_mips_callbacks->gva_to_gpa(vcpu->arch.
1199 						   host_cp0_badvaddr);
1200 		if (run->mmio.phys_addr == KVM_INVALID_ADDR) {
1201 			er = EMULATE_FAIL;
1202 			break;
1203 		}
1204 
1205 		run->mmio.len = bytes;
1206 		run->mmio.is_write = 1;
1207 		vcpu->mmio_needed = 1;
1208 		vcpu->mmio_is_write = 1;
1209 		*(uint32_t *) data = vcpu->arch.gprs[rt];
1210 
1211 		kvm_debug("[%#lx] OP_SW: eaddr: %#lx, gpr: %#lx, data: %#x\n",
1212 			  vcpu->arch.pc, vcpu->arch.host_cp0_badvaddr,
1213 			  vcpu->arch.gprs[rt], *(uint32_t *) data);
1214 		break;
1215 
1216 	case sh_op:
1217 		bytes = 2;
1218 		if (bytes > sizeof(run->mmio.data)) {
1219 			kvm_err("%s: bad MMIO length: %d\n", __func__,
1220 			       run->mmio.len);
1221 		}
1222 		run->mmio.phys_addr =
1223 		    kvm_mips_callbacks->gva_to_gpa(vcpu->arch.
1224 						   host_cp0_badvaddr);
1225 		if (run->mmio.phys_addr == KVM_INVALID_ADDR) {
1226 			er = EMULATE_FAIL;
1227 			break;
1228 		}
1229 
1230 		run->mmio.len = bytes;
1231 		run->mmio.is_write = 1;
1232 		vcpu->mmio_needed = 1;
1233 		vcpu->mmio_is_write = 1;
1234 		*(uint16_t *) data = vcpu->arch.gprs[rt];
1235 
1236 		kvm_debug("[%#lx] OP_SH: eaddr: %#lx, gpr: %#lx, data: %#x\n",
1237 			  vcpu->arch.pc, vcpu->arch.host_cp0_badvaddr,
1238 			  vcpu->arch.gprs[rt], *(uint32_t *) data);
1239 		break;
1240 
1241 	default:
1242 		kvm_err("Store not yet supported");
1243 		er = EMULATE_FAIL;
1244 		break;
1245 	}
1246 
1247 	/* Rollback PC if emulation was unsuccessful */
1248 	if (er == EMULATE_FAIL)
1249 		vcpu->arch.pc = curr_pc;
1250 
1251 	return er;
1252 }
1253 
kvm_mips_emulate_load(uint32_t inst,uint32_t cause,struct kvm_run * run,struct kvm_vcpu * vcpu)1254 enum emulation_result kvm_mips_emulate_load(uint32_t inst, uint32_t cause,
1255 					    struct kvm_run *run,
1256 					    struct kvm_vcpu *vcpu)
1257 {
1258 	enum emulation_result er = EMULATE_DO_MMIO;
1259 	int32_t op, base, rt, offset;
1260 	uint32_t bytes;
1261 
1262 	rt = (inst >> 16) & 0x1f;
1263 	base = (inst >> 21) & 0x1f;
1264 	offset = inst & 0xffff;
1265 	op = (inst >> 26) & 0x3f;
1266 
1267 	vcpu->arch.pending_load_cause = cause;
1268 	vcpu->arch.io_gpr = rt;
1269 
1270 	switch (op) {
1271 	case lw_op:
1272 		bytes = 4;
1273 		if (bytes > sizeof(run->mmio.data)) {
1274 			kvm_err("%s: bad MMIO length: %d\n", __func__,
1275 			       run->mmio.len);
1276 			er = EMULATE_FAIL;
1277 			break;
1278 		}
1279 		run->mmio.phys_addr =
1280 		    kvm_mips_callbacks->gva_to_gpa(vcpu->arch.
1281 						   host_cp0_badvaddr);
1282 		if (run->mmio.phys_addr == KVM_INVALID_ADDR) {
1283 			er = EMULATE_FAIL;
1284 			break;
1285 		}
1286 
1287 		run->mmio.len = bytes;
1288 		run->mmio.is_write = 0;
1289 		vcpu->mmio_needed = 1;
1290 		vcpu->mmio_is_write = 0;
1291 		break;
1292 
1293 	case lh_op:
1294 	case lhu_op:
1295 		bytes = 2;
1296 		if (bytes > sizeof(run->mmio.data)) {
1297 			kvm_err("%s: bad MMIO length: %d\n", __func__,
1298 			       run->mmio.len);
1299 			er = EMULATE_FAIL;
1300 			break;
1301 		}
1302 		run->mmio.phys_addr =
1303 		    kvm_mips_callbacks->gva_to_gpa(vcpu->arch.
1304 						   host_cp0_badvaddr);
1305 		if (run->mmio.phys_addr == KVM_INVALID_ADDR) {
1306 			er = EMULATE_FAIL;
1307 			break;
1308 		}
1309 
1310 		run->mmio.len = bytes;
1311 		run->mmio.is_write = 0;
1312 		vcpu->mmio_needed = 1;
1313 		vcpu->mmio_is_write = 0;
1314 
1315 		if (op == lh_op)
1316 			vcpu->mmio_needed = 2;
1317 		else
1318 			vcpu->mmio_needed = 1;
1319 
1320 		break;
1321 
1322 	case lbu_op:
1323 	case lb_op:
1324 		bytes = 1;
1325 		if (bytes > sizeof(run->mmio.data)) {
1326 			kvm_err("%s: bad MMIO length: %d\n", __func__,
1327 			       run->mmio.len);
1328 			er = EMULATE_FAIL;
1329 			break;
1330 		}
1331 		run->mmio.phys_addr =
1332 		    kvm_mips_callbacks->gva_to_gpa(vcpu->arch.
1333 						   host_cp0_badvaddr);
1334 		if (run->mmio.phys_addr == KVM_INVALID_ADDR) {
1335 			er = EMULATE_FAIL;
1336 			break;
1337 		}
1338 
1339 		run->mmio.len = bytes;
1340 		run->mmio.is_write = 0;
1341 		vcpu->mmio_is_write = 0;
1342 
1343 		if (op == lb_op)
1344 			vcpu->mmio_needed = 2;
1345 		else
1346 			vcpu->mmio_needed = 1;
1347 
1348 		break;
1349 
1350 	default:
1351 		kvm_err("Load not yet supported");
1352 		er = EMULATE_FAIL;
1353 		break;
1354 	}
1355 
1356 	return er;
1357 }
1358 
kvm_mips_sync_icache(unsigned long va,struct kvm_vcpu * vcpu)1359 int kvm_mips_sync_icache(unsigned long va, struct kvm_vcpu *vcpu)
1360 {
1361 	unsigned long offset = (va & ~PAGE_MASK);
1362 	struct kvm *kvm = vcpu->kvm;
1363 	unsigned long pa;
1364 	gfn_t gfn;
1365 	pfn_t pfn;
1366 
1367 	gfn = va >> PAGE_SHIFT;
1368 
1369 	if (gfn >= kvm->arch.guest_pmap_npages) {
1370 		kvm_err("%s: Invalid gfn: %#llx\n", __func__, gfn);
1371 		kvm_mips_dump_host_tlbs();
1372 		kvm_arch_vcpu_dump_regs(vcpu);
1373 		return -1;
1374 	}
1375 	pfn = kvm->arch.guest_pmap[gfn];
1376 	pa = (pfn << PAGE_SHIFT) | offset;
1377 
1378 	kvm_debug("%s: va: %#lx, unmapped: %#x\n", __func__, va,
1379 		  CKSEG0ADDR(pa));
1380 
1381 	local_flush_icache_range(CKSEG0ADDR(pa), 32);
1382 	return 0;
1383 }
1384 
1385 #define MIPS_CACHE_OP_INDEX_INV         0x0
1386 #define MIPS_CACHE_OP_INDEX_LD_TAG      0x1
1387 #define MIPS_CACHE_OP_INDEX_ST_TAG      0x2
1388 #define MIPS_CACHE_OP_IMP               0x3
1389 #define MIPS_CACHE_OP_HIT_INV           0x4
1390 #define MIPS_CACHE_OP_FILL_WB_INV       0x5
1391 #define MIPS_CACHE_OP_HIT_HB            0x6
1392 #define MIPS_CACHE_OP_FETCH_LOCK        0x7
1393 
1394 #define MIPS_CACHE_ICACHE               0x0
1395 #define MIPS_CACHE_DCACHE               0x1
1396 #define MIPS_CACHE_SEC                  0x3
1397 
kvm_mips_emulate_cache(uint32_t inst,uint32_t * opc,uint32_t cause,struct kvm_run * run,struct kvm_vcpu * vcpu)1398 enum emulation_result kvm_mips_emulate_cache(uint32_t inst, uint32_t *opc,
1399 					     uint32_t cause,
1400 					     struct kvm_run *run,
1401 					     struct kvm_vcpu *vcpu)
1402 {
1403 	struct mips_coproc *cop0 = vcpu->arch.cop0;
1404 	enum emulation_result er = EMULATE_DONE;
1405 	int32_t offset, cache, op_inst, op, base;
1406 	struct kvm_vcpu_arch *arch = &vcpu->arch;
1407 	unsigned long va;
1408 	unsigned long curr_pc;
1409 
1410 	/*
1411 	 * Update PC and hold onto current PC in case there is
1412 	 * an error and we want to rollback the PC
1413 	 */
1414 	curr_pc = vcpu->arch.pc;
1415 	er = update_pc(vcpu, cause);
1416 	if (er == EMULATE_FAIL)
1417 		return er;
1418 
1419 	base = (inst >> 21) & 0x1f;
1420 	op_inst = (inst >> 16) & 0x1f;
1421 	offset = inst & 0xffff;
1422 	cache = (inst >> 16) & 0x3;
1423 	op = (inst >> 18) & 0x7;
1424 
1425 	va = arch->gprs[base] + offset;
1426 
1427 	kvm_debug("CACHE (cache: %#x, op: %#x, base[%d]: %#lx, offset: %#x\n",
1428 		  cache, op, base, arch->gprs[base], offset);
1429 
1430 	/*
1431 	 * Treat INDEX_INV as a nop, basically issued by Linux on startup to
1432 	 * invalidate the caches entirely by stepping through all the
1433 	 * ways/indexes
1434 	 */
1435 	if (op == MIPS_CACHE_OP_INDEX_INV) {
1436 		kvm_debug("@ %#lx/%#lx CACHE (cache: %#x, op: %#x, base[%d]: %#lx, offset: %#x\n",
1437 			  vcpu->arch.pc, vcpu->arch.gprs[31], cache, op, base,
1438 			  arch->gprs[base], offset);
1439 
1440 		if (cache == MIPS_CACHE_DCACHE)
1441 			r4k_blast_dcache();
1442 		else if (cache == MIPS_CACHE_ICACHE)
1443 			r4k_blast_icache();
1444 		else {
1445 			kvm_err("%s: unsupported CACHE INDEX operation\n",
1446 				__func__);
1447 			return EMULATE_FAIL;
1448 		}
1449 
1450 #ifdef CONFIG_KVM_MIPS_DYN_TRANS
1451 		kvm_mips_trans_cache_index(inst, opc, vcpu);
1452 #endif
1453 		goto done;
1454 	}
1455 
1456 	preempt_disable();
1457 	if (KVM_GUEST_KSEGX(va) == KVM_GUEST_KSEG0) {
1458 		if (kvm_mips_host_tlb_lookup(vcpu, va) < 0)
1459 			kvm_mips_handle_kseg0_tlb_fault(va, vcpu);
1460 	} else if ((KVM_GUEST_KSEGX(va) < KVM_GUEST_KSEG0) ||
1461 		   KVM_GUEST_KSEGX(va) == KVM_GUEST_KSEG23) {
1462 		int index;
1463 
1464 		/* If an entry already exists then skip */
1465 		if (kvm_mips_host_tlb_lookup(vcpu, va) >= 0)
1466 			goto skip_fault;
1467 
1468 		/*
1469 		 * If address not in the guest TLB, then give the guest a fault,
1470 		 * the resulting handler will do the right thing
1471 		 */
1472 		index = kvm_mips_guest_tlb_lookup(vcpu, (va & VPN2_MASK) |
1473 						  (kvm_read_c0_guest_entryhi
1474 						   (cop0) & ASID_MASK));
1475 
1476 		if (index < 0) {
1477 			vcpu->arch.host_cp0_entryhi = (va & VPN2_MASK);
1478 			vcpu->arch.host_cp0_badvaddr = va;
1479 			er = kvm_mips_emulate_tlbmiss_ld(cause, NULL, run,
1480 							 vcpu);
1481 			preempt_enable();
1482 			goto dont_update_pc;
1483 		} else {
1484 			struct kvm_mips_tlb *tlb = &vcpu->arch.guest_tlb[index];
1485 			/*
1486 			 * Check if the entry is valid, if not then setup a TLB
1487 			 * invalid exception to the guest
1488 			 */
1489 			if (!TLB_IS_VALID(*tlb, va)) {
1490 				er = kvm_mips_emulate_tlbinv_ld(cause, NULL,
1491 								run, vcpu);
1492 				preempt_enable();
1493 				goto dont_update_pc;
1494 			} else {
1495 				/*
1496 				 * We fault an entry from the guest tlb to the
1497 				 * shadow host TLB
1498 				 */
1499 				kvm_mips_handle_mapped_seg_tlb_fault(vcpu, tlb,
1500 								     NULL,
1501 								     NULL);
1502 			}
1503 		}
1504 	} else {
1505 		kvm_err("INVALID CACHE INDEX/ADDRESS (cache: %#x, op: %#x, base[%d]: %#lx, offset: %#x\n",
1506 			cache, op, base, arch->gprs[base], offset);
1507 		er = EMULATE_FAIL;
1508 		preempt_enable();
1509 		goto dont_update_pc;
1510 
1511 	}
1512 
1513 skip_fault:
1514 	/* XXXKYMA: Only a subset of cache ops are supported, used by Linux */
1515 	if (cache == MIPS_CACHE_DCACHE
1516 	    && (op == MIPS_CACHE_OP_FILL_WB_INV
1517 		|| op == MIPS_CACHE_OP_HIT_INV)) {
1518 		flush_dcache_line(va);
1519 
1520 #ifdef CONFIG_KVM_MIPS_DYN_TRANS
1521 		/*
1522 		 * Replace the CACHE instruction, with a SYNCI, not the same,
1523 		 * but avoids a trap
1524 		 */
1525 		kvm_mips_trans_cache_va(inst, opc, vcpu);
1526 #endif
1527 	} else if (op == MIPS_CACHE_OP_HIT_INV && cache == MIPS_CACHE_ICACHE) {
1528 		flush_dcache_line(va);
1529 		flush_icache_line(va);
1530 
1531 #ifdef CONFIG_KVM_MIPS_DYN_TRANS
1532 		/* Replace the CACHE instruction, with a SYNCI */
1533 		kvm_mips_trans_cache_va(inst, opc, vcpu);
1534 #endif
1535 	} else {
1536 		kvm_err("NO-OP CACHE (cache: %#x, op: %#x, base[%d]: %#lx, offset: %#x\n",
1537 			cache, op, base, arch->gprs[base], offset);
1538 		er = EMULATE_FAIL;
1539 		preempt_enable();
1540 		goto dont_update_pc;
1541 	}
1542 
1543 	preempt_enable();
1544 
1545 dont_update_pc:
1546 	/* Rollback PC */
1547 	vcpu->arch.pc = curr_pc;
1548 done:
1549 	return er;
1550 }
1551 
kvm_mips_emulate_inst(unsigned long cause,uint32_t * opc,struct kvm_run * run,struct kvm_vcpu * vcpu)1552 enum emulation_result kvm_mips_emulate_inst(unsigned long cause, uint32_t *opc,
1553 					    struct kvm_run *run,
1554 					    struct kvm_vcpu *vcpu)
1555 {
1556 	enum emulation_result er = EMULATE_DONE;
1557 	uint32_t inst;
1558 
1559 	/* Fetch the instruction. */
1560 	if (cause & CAUSEF_BD)
1561 		opc += 1;
1562 
1563 	inst = kvm_get_inst(opc, vcpu);
1564 
1565 	switch (((union mips_instruction)inst).r_format.opcode) {
1566 	case cop0_op:
1567 		er = kvm_mips_emulate_CP0(inst, opc, cause, run, vcpu);
1568 		break;
1569 	case sb_op:
1570 	case sh_op:
1571 	case sw_op:
1572 		er = kvm_mips_emulate_store(inst, cause, run, vcpu);
1573 		break;
1574 	case lb_op:
1575 	case lbu_op:
1576 	case lhu_op:
1577 	case lh_op:
1578 	case lw_op:
1579 		er = kvm_mips_emulate_load(inst, cause, run, vcpu);
1580 		break;
1581 
1582 	case cache_op:
1583 		++vcpu->stat.cache_exits;
1584 		trace_kvm_exit(vcpu, CACHE_EXITS);
1585 		er = kvm_mips_emulate_cache(inst, opc, cause, run, vcpu);
1586 		break;
1587 
1588 	default:
1589 		kvm_err("Instruction emulation not supported (%p/%#x)\n", opc,
1590 			inst);
1591 		kvm_arch_vcpu_dump_regs(vcpu);
1592 		er = EMULATE_FAIL;
1593 		break;
1594 	}
1595 
1596 	return er;
1597 }
1598 
kvm_mips_emulate_syscall(unsigned long cause,uint32_t * opc,struct kvm_run * run,struct kvm_vcpu * vcpu)1599 enum emulation_result kvm_mips_emulate_syscall(unsigned long cause,
1600 					       uint32_t *opc,
1601 					       struct kvm_run *run,
1602 					       struct kvm_vcpu *vcpu)
1603 {
1604 	struct mips_coproc *cop0 = vcpu->arch.cop0;
1605 	struct kvm_vcpu_arch *arch = &vcpu->arch;
1606 	enum emulation_result er = EMULATE_DONE;
1607 
1608 	if ((kvm_read_c0_guest_status(cop0) & ST0_EXL) == 0) {
1609 		/* save old pc */
1610 		kvm_write_c0_guest_epc(cop0, arch->pc);
1611 		kvm_set_c0_guest_status(cop0, ST0_EXL);
1612 
1613 		if (cause & CAUSEF_BD)
1614 			kvm_set_c0_guest_cause(cop0, CAUSEF_BD);
1615 		else
1616 			kvm_clear_c0_guest_cause(cop0, CAUSEF_BD);
1617 
1618 		kvm_debug("Delivering SYSCALL @ pc %#lx\n", arch->pc);
1619 
1620 		kvm_change_c0_guest_cause(cop0, (0xff),
1621 					  (T_SYSCALL << CAUSEB_EXCCODE));
1622 
1623 		/* Set PC to the exception entry point */
1624 		arch->pc = KVM_GUEST_KSEG0 + 0x180;
1625 
1626 	} else {
1627 		kvm_err("Trying to deliver SYSCALL when EXL is already set\n");
1628 		er = EMULATE_FAIL;
1629 	}
1630 
1631 	return er;
1632 }
1633 
kvm_mips_emulate_tlbmiss_ld(unsigned long cause,uint32_t * opc,struct kvm_run * run,struct kvm_vcpu * vcpu)1634 enum emulation_result kvm_mips_emulate_tlbmiss_ld(unsigned long cause,
1635 						  uint32_t *opc,
1636 						  struct kvm_run *run,
1637 						  struct kvm_vcpu *vcpu)
1638 {
1639 	struct mips_coproc *cop0 = vcpu->arch.cop0;
1640 	struct kvm_vcpu_arch *arch = &vcpu->arch;
1641 	unsigned long entryhi = (vcpu->arch.  host_cp0_badvaddr & VPN2_MASK) |
1642 				(kvm_read_c0_guest_entryhi(cop0) & ASID_MASK);
1643 
1644 	if ((kvm_read_c0_guest_status(cop0) & ST0_EXL) == 0) {
1645 		/* save old pc */
1646 		kvm_write_c0_guest_epc(cop0, arch->pc);
1647 		kvm_set_c0_guest_status(cop0, ST0_EXL);
1648 
1649 		if (cause & CAUSEF_BD)
1650 			kvm_set_c0_guest_cause(cop0, CAUSEF_BD);
1651 		else
1652 			kvm_clear_c0_guest_cause(cop0, CAUSEF_BD);
1653 
1654 		kvm_debug("[EXL == 0] delivering TLB MISS @ pc %#lx\n",
1655 			  arch->pc);
1656 
1657 		/* set pc to the exception entry point */
1658 		arch->pc = KVM_GUEST_KSEG0 + 0x0;
1659 
1660 	} else {
1661 		kvm_debug("[EXL == 1] delivering TLB MISS @ pc %#lx\n",
1662 			  arch->pc);
1663 
1664 		arch->pc = KVM_GUEST_KSEG0 + 0x180;
1665 	}
1666 
1667 	kvm_change_c0_guest_cause(cop0, (0xff),
1668 				  (T_TLB_LD_MISS << CAUSEB_EXCCODE));
1669 
1670 	/* setup badvaddr, context and entryhi registers for the guest */
1671 	kvm_write_c0_guest_badvaddr(cop0, vcpu->arch.host_cp0_badvaddr);
1672 	/* XXXKYMA: is the context register used by linux??? */
1673 	kvm_write_c0_guest_entryhi(cop0, entryhi);
1674 	/* Blow away the shadow host TLBs */
1675 	kvm_mips_flush_host_tlb(1);
1676 
1677 	return EMULATE_DONE;
1678 }
1679 
kvm_mips_emulate_tlbinv_ld(unsigned long cause,uint32_t * opc,struct kvm_run * run,struct kvm_vcpu * vcpu)1680 enum emulation_result kvm_mips_emulate_tlbinv_ld(unsigned long cause,
1681 						 uint32_t *opc,
1682 						 struct kvm_run *run,
1683 						 struct kvm_vcpu *vcpu)
1684 {
1685 	struct mips_coproc *cop0 = vcpu->arch.cop0;
1686 	struct kvm_vcpu_arch *arch = &vcpu->arch;
1687 	unsigned long entryhi =
1688 		(vcpu->arch.host_cp0_badvaddr & VPN2_MASK) |
1689 		(kvm_read_c0_guest_entryhi(cop0) & ASID_MASK);
1690 
1691 	if ((kvm_read_c0_guest_status(cop0) & ST0_EXL) == 0) {
1692 		/* save old pc */
1693 		kvm_write_c0_guest_epc(cop0, arch->pc);
1694 		kvm_set_c0_guest_status(cop0, ST0_EXL);
1695 
1696 		if (cause & CAUSEF_BD)
1697 			kvm_set_c0_guest_cause(cop0, CAUSEF_BD);
1698 		else
1699 			kvm_clear_c0_guest_cause(cop0, CAUSEF_BD);
1700 
1701 		kvm_debug("[EXL == 0] delivering TLB INV @ pc %#lx\n",
1702 			  arch->pc);
1703 
1704 		/* set pc to the exception entry point */
1705 		arch->pc = KVM_GUEST_KSEG0 + 0x180;
1706 
1707 	} else {
1708 		kvm_debug("[EXL == 1] delivering TLB MISS @ pc %#lx\n",
1709 			  arch->pc);
1710 		arch->pc = KVM_GUEST_KSEG0 + 0x180;
1711 	}
1712 
1713 	kvm_change_c0_guest_cause(cop0, (0xff),
1714 				  (T_TLB_LD_MISS << CAUSEB_EXCCODE));
1715 
1716 	/* setup badvaddr, context and entryhi registers for the guest */
1717 	kvm_write_c0_guest_badvaddr(cop0, vcpu->arch.host_cp0_badvaddr);
1718 	/* XXXKYMA: is the context register used by linux??? */
1719 	kvm_write_c0_guest_entryhi(cop0, entryhi);
1720 	/* Blow away the shadow host TLBs */
1721 	kvm_mips_flush_host_tlb(1);
1722 
1723 	return EMULATE_DONE;
1724 }
1725 
kvm_mips_emulate_tlbmiss_st(unsigned long cause,uint32_t * opc,struct kvm_run * run,struct kvm_vcpu * vcpu)1726 enum emulation_result kvm_mips_emulate_tlbmiss_st(unsigned long cause,
1727 						  uint32_t *opc,
1728 						  struct kvm_run *run,
1729 						  struct kvm_vcpu *vcpu)
1730 {
1731 	struct mips_coproc *cop0 = vcpu->arch.cop0;
1732 	struct kvm_vcpu_arch *arch = &vcpu->arch;
1733 	unsigned long entryhi = (vcpu->arch.host_cp0_badvaddr & VPN2_MASK) |
1734 				(kvm_read_c0_guest_entryhi(cop0) & ASID_MASK);
1735 
1736 	if ((kvm_read_c0_guest_status(cop0) & ST0_EXL) == 0) {
1737 		/* save old pc */
1738 		kvm_write_c0_guest_epc(cop0, arch->pc);
1739 		kvm_set_c0_guest_status(cop0, ST0_EXL);
1740 
1741 		if (cause & CAUSEF_BD)
1742 			kvm_set_c0_guest_cause(cop0, CAUSEF_BD);
1743 		else
1744 			kvm_clear_c0_guest_cause(cop0, CAUSEF_BD);
1745 
1746 		kvm_debug("[EXL == 0] Delivering TLB MISS @ pc %#lx\n",
1747 			  arch->pc);
1748 
1749 		/* Set PC to the exception entry point */
1750 		arch->pc = KVM_GUEST_KSEG0 + 0x0;
1751 	} else {
1752 		kvm_debug("[EXL == 1] Delivering TLB MISS @ pc %#lx\n",
1753 			  arch->pc);
1754 		arch->pc = KVM_GUEST_KSEG0 + 0x180;
1755 	}
1756 
1757 	kvm_change_c0_guest_cause(cop0, (0xff),
1758 				  (T_TLB_ST_MISS << CAUSEB_EXCCODE));
1759 
1760 	/* setup badvaddr, context and entryhi registers for the guest */
1761 	kvm_write_c0_guest_badvaddr(cop0, vcpu->arch.host_cp0_badvaddr);
1762 	/* XXXKYMA: is the context register used by linux??? */
1763 	kvm_write_c0_guest_entryhi(cop0, entryhi);
1764 	/* Blow away the shadow host TLBs */
1765 	kvm_mips_flush_host_tlb(1);
1766 
1767 	return EMULATE_DONE;
1768 }
1769 
kvm_mips_emulate_tlbinv_st(unsigned long cause,uint32_t * opc,struct kvm_run * run,struct kvm_vcpu * vcpu)1770 enum emulation_result kvm_mips_emulate_tlbinv_st(unsigned long cause,
1771 						 uint32_t *opc,
1772 						 struct kvm_run *run,
1773 						 struct kvm_vcpu *vcpu)
1774 {
1775 	struct mips_coproc *cop0 = vcpu->arch.cop0;
1776 	struct kvm_vcpu_arch *arch = &vcpu->arch;
1777 	unsigned long entryhi = (vcpu->arch.host_cp0_badvaddr & VPN2_MASK) |
1778 		(kvm_read_c0_guest_entryhi(cop0) & ASID_MASK);
1779 
1780 	if ((kvm_read_c0_guest_status(cop0) & ST0_EXL) == 0) {
1781 		/* save old pc */
1782 		kvm_write_c0_guest_epc(cop0, arch->pc);
1783 		kvm_set_c0_guest_status(cop0, ST0_EXL);
1784 
1785 		if (cause & CAUSEF_BD)
1786 			kvm_set_c0_guest_cause(cop0, CAUSEF_BD);
1787 		else
1788 			kvm_clear_c0_guest_cause(cop0, CAUSEF_BD);
1789 
1790 		kvm_debug("[EXL == 0] Delivering TLB MISS @ pc %#lx\n",
1791 			  arch->pc);
1792 
1793 		/* Set PC to the exception entry point */
1794 		arch->pc = KVM_GUEST_KSEG0 + 0x180;
1795 	} else {
1796 		kvm_debug("[EXL == 1] Delivering TLB MISS @ pc %#lx\n",
1797 			  arch->pc);
1798 		arch->pc = KVM_GUEST_KSEG0 + 0x180;
1799 	}
1800 
1801 	kvm_change_c0_guest_cause(cop0, (0xff),
1802 				  (T_TLB_ST_MISS << CAUSEB_EXCCODE));
1803 
1804 	/* setup badvaddr, context and entryhi registers for the guest */
1805 	kvm_write_c0_guest_badvaddr(cop0, vcpu->arch.host_cp0_badvaddr);
1806 	/* XXXKYMA: is the context register used by linux??? */
1807 	kvm_write_c0_guest_entryhi(cop0, entryhi);
1808 	/* Blow away the shadow host TLBs */
1809 	kvm_mips_flush_host_tlb(1);
1810 
1811 	return EMULATE_DONE;
1812 }
1813 
1814 /* TLBMOD: store into address matching TLB with Dirty bit off */
kvm_mips_handle_tlbmod(unsigned long cause,uint32_t * opc,struct kvm_run * run,struct kvm_vcpu * vcpu)1815 enum emulation_result kvm_mips_handle_tlbmod(unsigned long cause, uint32_t *opc,
1816 					     struct kvm_run *run,
1817 					     struct kvm_vcpu *vcpu)
1818 {
1819 	enum emulation_result er = EMULATE_DONE;
1820 #ifdef DEBUG
1821 	struct mips_coproc *cop0 = vcpu->arch.cop0;
1822 	unsigned long entryhi = (vcpu->arch.host_cp0_badvaddr & VPN2_MASK) |
1823 				(kvm_read_c0_guest_entryhi(cop0) & ASID_MASK);
1824 	int index;
1825 
1826 	/* If address not in the guest TLB, then we are in trouble */
1827 	index = kvm_mips_guest_tlb_lookup(vcpu, entryhi);
1828 	if (index < 0) {
1829 		/* XXXKYMA Invalidate and retry */
1830 		kvm_mips_host_tlb_inv(vcpu, vcpu->arch.host_cp0_badvaddr);
1831 		kvm_err("%s: host got TLBMOD for %#lx but entry not present in Guest TLB\n",
1832 		     __func__, entryhi);
1833 		kvm_mips_dump_guest_tlbs(vcpu);
1834 		kvm_mips_dump_host_tlbs();
1835 		return EMULATE_FAIL;
1836 	}
1837 #endif
1838 
1839 	er = kvm_mips_emulate_tlbmod(cause, opc, run, vcpu);
1840 	return er;
1841 }
1842 
kvm_mips_emulate_tlbmod(unsigned long cause,uint32_t * opc,struct kvm_run * run,struct kvm_vcpu * vcpu)1843 enum emulation_result kvm_mips_emulate_tlbmod(unsigned long cause,
1844 					      uint32_t *opc,
1845 					      struct kvm_run *run,
1846 					      struct kvm_vcpu *vcpu)
1847 {
1848 	struct mips_coproc *cop0 = vcpu->arch.cop0;
1849 	unsigned long entryhi = (vcpu->arch.host_cp0_badvaddr & VPN2_MASK) |
1850 				(kvm_read_c0_guest_entryhi(cop0) & ASID_MASK);
1851 	struct kvm_vcpu_arch *arch = &vcpu->arch;
1852 
1853 	if ((kvm_read_c0_guest_status(cop0) & ST0_EXL) == 0) {
1854 		/* save old pc */
1855 		kvm_write_c0_guest_epc(cop0, arch->pc);
1856 		kvm_set_c0_guest_status(cop0, ST0_EXL);
1857 
1858 		if (cause & CAUSEF_BD)
1859 			kvm_set_c0_guest_cause(cop0, CAUSEF_BD);
1860 		else
1861 			kvm_clear_c0_guest_cause(cop0, CAUSEF_BD);
1862 
1863 		kvm_debug("[EXL == 0] Delivering TLB MOD @ pc %#lx\n",
1864 			  arch->pc);
1865 
1866 		arch->pc = KVM_GUEST_KSEG0 + 0x180;
1867 	} else {
1868 		kvm_debug("[EXL == 1] Delivering TLB MOD @ pc %#lx\n",
1869 			  arch->pc);
1870 		arch->pc = KVM_GUEST_KSEG0 + 0x180;
1871 	}
1872 
1873 	kvm_change_c0_guest_cause(cop0, (0xff), (T_TLB_MOD << CAUSEB_EXCCODE));
1874 
1875 	/* setup badvaddr, context and entryhi registers for the guest */
1876 	kvm_write_c0_guest_badvaddr(cop0, vcpu->arch.host_cp0_badvaddr);
1877 	/* XXXKYMA: is the context register used by linux??? */
1878 	kvm_write_c0_guest_entryhi(cop0, entryhi);
1879 	/* Blow away the shadow host TLBs */
1880 	kvm_mips_flush_host_tlb(1);
1881 
1882 	return EMULATE_DONE;
1883 }
1884 
kvm_mips_emulate_fpu_exc(unsigned long cause,uint32_t * opc,struct kvm_run * run,struct kvm_vcpu * vcpu)1885 enum emulation_result kvm_mips_emulate_fpu_exc(unsigned long cause,
1886 					       uint32_t *opc,
1887 					       struct kvm_run *run,
1888 					       struct kvm_vcpu *vcpu)
1889 {
1890 	struct mips_coproc *cop0 = vcpu->arch.cop0;
1891 	struct kvm_vcpu_arch *arch = &vcpu->arch;
1892 
1893 	if ((kvm_read_c0_guest_status(cop0) & ST0_EXL) == 0) {
1894 		/* save old pc */
1895 		kvm_write_c0_guest_epc(cop0, arch->pc);
1896 		kvm_set_c0_guest_status(cop0, ST0_EXL);
1897 
1898 		if (cause & CAUSEF_BD)
1899 			kvm_set_c0_guest_cause(cop0, CAUSEF_BD);
1900 		else
1901 			kvm_clear_c0_guest_cause(cop0, CAUSEF_BD);
1902 
1903 	}
1904 
1905 	arch->pc = KVM_GUEST_KSEG0 + 0x180;
1906 
1907 	kvm_change_c0_guest_cause(cop0, (0xff),
1908 				  (T_COP_UNUSABLE << CAUSEB_EXCCODE));
1909 	kvm_change_c0_guest_cause(cop0, (CAUSEF_CE), (0x1 << CAUSEB_CE));
1910 
1911 	return EMULATE_DONE;
1912 }
1913 
kvm_mips_emulate_ri_exc(unsigned long cause,uint32_t * opc,struct kvm_run * run,struct kvm_vcpu * vcpu)1914 enum emulation_result kvm_mips_emulate_ri_exc(unsigned long cause,
1915 					      uint32_t *opc,
1916 					      struct kvm_run *run,
1917 					      struct kvm_vcpu *vcpu)
1918 {
1919 	struct mips_coproc *cop0 = vcpu->arch.cop0;
1920 	struct kvm_vcpu_arch *arch = &vcpu->arch;
1921 	enum emulation_result er = EMULATE_DONE;
1922 
1923 	if ((kvm_read_c0_guest_status(cop0) & ST0_EXL) == 0) {
1924 		/* save old pc */
1925 		kvm_write_c0_guest_epc(cop0, arch->pc);
1926 		kvm_set_c0_guest_status(cop0, ST0_EXL);
1927 
1928 		if (cause & CAUSEF_BD)
1929 			kvm_set_c0_guest_cause(cop0, CAUSEF_BD);
1930 		else
1931 			kvm_clear_c0_guest_cause(cop0, CAUSEF_BD);
1932 
1933 		kvm_debug("Delivering RI @ pc %#lx\n", arch->pc);
1934 
1935 		kvm_change_c0_guest_cause(cop0, (0xff),
1936 					  (T_RES_INST << CAUSEB_EXCCODE));
1937 
1938 		/* Set PC to the exception entry point */
1939 		arch->pc = KVM_GUEST_KSEG0 + 0x180;
1940 
1941 	} else {
1942 		kvm_err("Trying to deliver RI when EXL is already set\n");
1943 		er = EMULATE_FAIL;
1944 	}
1945 
1946 	return er;
1947 }
1948 
kvm_mips_emulate_bp_exc(unsigned long cause,uint32_t * opc,struct kvm_run * run,struct kvm_vcpu * vcpu)1949 enum emulation_result kvm_mips_emulate_bp_exc(unsigned long cause,
1950 					      uint32_t *opc,
1951 					      struct kvm_run *run,
1952 					      struct kvm_vcpu *vcpu)
1953 {
1954 	struct mips_coproc *cop0 = vcpu->arch.cop0;
1955 	struct kvm_vcpu_arch *arch = &vcpu->arch;
1956 	enum emulation_result er = EMULATE_DONE;
1957 
1958 	if ((kvm_read_c0_guest_status(cop0) & ST0_EXL) == 0) {
1959 		/* save old pc */
1960 		kvm_write_c0_guest_epc(cop0, arch->pc);
1961 		kvm_set_c0_guest_status(cop0, ST0_EXL);
1962 
1963 		if (cause & CAUSEF_BD)
1964 			kvm_set_c0_guest_cause(cop0, CAUSEF_BD);
1965 		else
1966 			kvm_clear_c0_guest_cause(cop0, CAUSEF_BD);
1967 
1968 		kvm_debug("Delivering BP @ pc %#lx\n", arch->pc);
1969 
1970 		kvm_change_c0_guest_cause(cop0, (0xff),
1971 					  (T_BREAK << CAUSEB_EXCCODE));
1972 
1973 		/* Set PC to the exception entry point */
1974 		arch->pc = KVM_GUEST_KSEG0 + 0x180;
1975 
1976 	} else {
1977 		kvm_err("Trying to deliver BP when EXL is already set\n");
1978 		er = EMULATE_FAIL;
1979 	}
1980 
1981 	return er;
1982 }
1983 
1984 /* ll/sc, rdhwr, sync emulation */
1985 
1986 #define OPCODE 0xfc000000
1987 #define BASE   0x03e00000
1988 #define RT     0x001f0000
1989 #define OFFSET 0x0000ffff
1990 #define LL     0xc0000000
1991 #define SC     0xe0000000
1992 #define SPEC0  0x00000000
1993 #define SPEC3  0x7c000000
1994 #define RD     0x0000f800
1995 #define FUNC   0x0000003f
1996 #define SYNC   0x0000000f
1997 #define RDHWR  0x0000003b
1998 
kvm_mips_handle_ri(unsigned long cause,uint32_t * opc,struct kvm_run * run,struct kvm_vcpu * vcpu)1999 enum emulation_result kvm_mips_handle_ri(unsigned long cause, uint32_t *opc,
2000 					 struct kvm_run *run,
2001 					 struct kvm_vcpu *vcpu)
2002 {
2003 	struct mips_coproc *cop0 = vcpu->arch.cop0;
2004 	struct kvm_vcpu_arch *arch = &vcpu->arch;
2005 	enum emulation_result er = EMULATE_DONE;
2006 	unsigned long curr_pc;
2007 	uint32_t inst;
2008 
2009 	/*
2010 	 * Update PC and hold onto current PC in case there is
2011 	 * an error and we want to rollback the PC
2012 	 */
2013 	curr_pc = vcpu->arch.pc;
2014 	er = update_pc(vcpu, cause);
2015 	if (er == EMULATE_FAIL)
2016 		return er;
2017 
2018 	/* Fetch the instruction. */
2019 	if (cause & CAUSEF_BD)
2020 		opc += 1;
2021 
2022 	inst = kvm_get_inst(opc, vcpu);
2023 
2024 	if (inst == KVM_INVALID_INST) {
2025 		kvm_err("%s: Cannot get inst @ %p\n", __func__, opc);
2026 		return EMULATE_FAIL;
2027 	}
2028 
2029 	if ((inst & OPCODE) == SPEC3 && (inst & FUNC) == RDHWR) {
2030 		int usermode = !KVM_GUEST_KERNEL_MODE(vcpu);
2031 		int rd = (inst & RD) >> 11;
2032 		int rt = (inst & RT) >> 16;
2033 		/* If usermode, check RDHWR rd is allowed by guest HWREna */
2034 		if (usermode && !(kvm_read_c0_guest_hwrena(cop0) & BIT(rd))) {
2035 			kvm_debug("RDHWR %#x disallowed by HWREna @ %p\n",
2036 				  rd, opc);
2037 			goto emulate_ri;
2038 		}
2039 		switch (rd) {
2040 		case 0:	/* CPU number */
2041 			arch->gprs[rt] = 0;
2042 			break;
2043 		case 1:	/* SYNCI length */
2044 			arch->gprs[rt] = min(current_cpu_data.dcache.linesz,
2045 					     current_cpu_data.icache.linesz);
2046 			break;
2047 		case 2:	/* Read count register */
2048 			arch->gprs[rt] = kvm_mips_read_count(vcpu);
2049 			break;
2050 		case 3:	/* Count register resolution */
2051 			switch (current_cpu_data.cputype) {
2052 			case CPU_20KC:
2053 			case CPU_25KF:
2054 				arch->gprs[rt] = 1;
2055 				break;
2056 			default:
2057 				arch->gprs[rt] = 2;
2058 			}
2059 			break;
2060 		case 29:
2061 			arch->gprs[rt] = kvm_read_c0_guest_userlocal(cop0);
2062 			break;
2063 
2064 		default:
2065 			kvm_debug("RDHWR %#x not supported @ %p\n", rd, opc);
2066 			goto emulate_ri;
2067 		}
2068 	} else {
2069 		kvm_debug("Emulate RI not supported @ %p: %#x\n", opc, inst);
2070 		goto emulate_ri;
2071 	}
2072 
2073 	return EMULATE_DONE;
2074 
2075 emulate_ri:
2076 	/*
2077 	 * Rollback PC (if in branch delay slot then the PC already points to
2078 	 * branch target), and pass the RI exception to the guest OS.
2079 	 */
2080 	vcpu->arch.pc = curr_pc;
2081 	return kvm_mips_emulate_ri_exc(cause, opc, run, vcpu);
2082 }
2083 
kvm_mips_complete_mmio_load(struct kvm_vcpu * vcpu,struct kvm_run * run)2084 enum emulation_result kvm_mips_complete_mmio_load(struct kvm_vcpu *vcpu,
2085 						  struct kvm_run *run)
2086 {
2087 	unsigned long *gpr = &vcpu->arch.gprs[vcpu->arch.io_gpr];
2088 	enum emulation_result er = EMULATE_DONE;
2089 	unsigned long curr_pc;
2090 
2091 	if (run->mmio.len > sizeof(*gpr)) {
2092 		kvm_err("Bad MMIO length: %d", run->mmio.len);
2093 		er = EMULATE_FAIL;
2094 		goto done;
2095 	}
2096 
2097 	/*
2098 	 * Update PC and hold onto current PC in case there is
2099 	 * an error and we want to rollback the PC
2100 	 */
2101 	curr_pc = vcpu->arch.pc;
2102 	er = update_pc(vcpu, vcpu->arch.pending_load_cause);
2103 	if (er == EMULATE_FAIL)
2104 		return er;
2105 
2106 	switch (run->mmio.len) {
2107 	case 4:
2108 		*gpr = *(int32_t *) run->mmio.data;
2109 		break;
2110 
2111 	case 2:
2112 		if (vcpu->mmio_needed == 2)
2113 			*gpr = *(int16_t *) run->mmio.data;
2114 		else
2115 			*gpr = *(int16_t *) run->mmio.data;
2116 
2117 		break;
2118 	case 1:
2119 		if (vcpu->mmio_needed == 2)
2120 			*gpr = *(int8_t *) run->mmio.data;
2121 		else
2122 			*gpr = *(u8 *) run->mmio.data;
2123 		break;
2124 	}
2125 
2126 	if (vcpu->arch.pending_load_cause & CAUSEF_BD)
2127 		kvm_debug("[%#lx] Completing %d byte BD Load to gpr %d (0x%08lx) type %d\n",
2128 			  vcpu->arch.pc, run->mmio.len, vcpu->arch.io_gpr, *gpr,
2129 			  vcpu->mmio_needed);
2130 
2131 done:
2132 	return er;
2133 }
2134 
kvm_mips_emulate_exc(unsigned long cause,uint32_t * opc,struct kvm_run * run,struct kvm_vcpu * vcpu)2135 static enum emulation_result kvm_mips_emulate_exc(unsigned long cause,
2136 						  uint32_t *opc,
2137 						  struct kvm_run *run,
2138 						  struct kvm_vcpu *vcpu)
2139 {
2140 	uint32_t exccode = (cause >> CAUSEB_EXCCODE) & 0x1f;
2141 	struct mips_coproc *cop0 = vcpu->arch.cop0;
2142 	struct kvm_vcpu_arch *arch = &vcpu->arch;
2143 	enum emulation_result er = EMULATE_DONE;
2144 
2145 	if ((kvm_read_c0_guest_status(cop0) & ST0_EXL) == 0) {
2146 		/* save old pc */
2147 		kvm_write_c0_guest_epc(cop0, arch->pc);
2148 		kvm_set_c0_guest_status(cop0, ST0_EXL);
2149 
2150 		if (cause & CAUSEF_BD)
2151 			kvm_set_c0_guest_cause(cop0, CAUSEF_BD);
2152 		else
2153 			kvm_clear_c0_guest_cause(cop0, CAUSEF_BD);
2154 
2155 		kvm_change_c0_guest_cause(cop0, (0xff),
2156 					  (exccode << CAUSEB_EXCCODE));
2157 
2158 		/* Set PC to the exception entry point */
2159 		arch->pc = KVM_GUEST_KSEG0 + 0x180;
2160 		kvm_write_c0_guest_badvaddr(cop0, vcpu->arch.host_cp0_badvaddr);
2161 
2162 		kvm_debug("Delivering EXC %d @ pc %#lx, badVaddr: %#lx\n",
2163 			  exccode, kvm_read_c0_guest_epc(cop0),
2164 			  kvm_read_c0_guest_badvaddr(cop0));
2165 	} else {
2166 		kvm_err("Trying to deliver EXC when EXL is already set\n");
2167 		er = EMULATE_FAIL;
2168 	}
2169 
2170 	return er;
2171 }
2172 
kvm_mips_check_privilege(unsigned long cause,uint32_t * opc,struct kvm_run * run,struct kvm_vcpu * vcpu)2173 enum emulation_result kvm_mips_check_privilege(unsigned long cause,
2174 					       uint32_t *opc,
2175 					       struct kvm_run *run,
2176 					       struct kvm_vcpu *vcpu)
2177 {
2178 	enum emulation_result er = EMULATE_DONE;
2179 	uint32_t exccode = (cause >> CAUSEB_EXCCODE) & 0x1f;
2180 	unsigned long badvaddr = vcpu->arch.host_cp0_badvaddr;
2181 
2182 	int usermode = !KVM_GUEST_KERNEL_MODE(vcpu);
2183 
2184 	if (usermode) {
2185 		switch (exccode) {
2186 		case T_INT:
2187 		case T_SYSCALL:
2188 		case T_BREAK:
2189 		case T_RES_INST:
2190 		case T_MSADIS:
2191 			break;
2192 
2193 		case T_COP_UNUSABLE:
2194 			if (((cause & CAUSEF_CE) >> CAUSEB_CE) == 0)
2195 				er = EMULATE_PRIV_FAIL;
2196 			break;
2197 
2198 		case T_TLB_MOD:
2199 			break;
2200 
2201 		case T_TLB_LD_MISS:
2202 			/*
2203 			 * We we are accessing Guest kernel space, then send an
2204 			 * address error exception to the guest
2205 			 */
2206 			if (badvaddr >= (unsigned long) KVM_GUEST_KSEG0) {
2207 				kvm_debug("%s: LD MISS @ %#lx\n", __func__,
2208 					  badvaddr);
2209 				cause &= ~0xff;
2210 				cause |= (T_ADDR_ERR_LD << CAUSEB_EXCCODE);
2211 				er = EMULATE_PRIV_FAIL;
2212 			}
2213 			break;
2214 
2215 		case T_TLB_ST_MISS:
2216 			/*
2217 			 * We we are accessing Guest kernel space, then send an
2218 			 * address error exception to the guest
2219 			 */
2220 			if (badvaddr >= (unsigned long) KVM_GUEST_KSEG0) {
2221 				kvm_debug("%s: ST MISS @ %#lx\n", __func__,
2222 					  badvaddr);
2223 				cause &= ~0xff;
2224 				cause |= (T_ADDR_ERR_ST << CAUSEB_EXCCODE);
2225 				er = EMULATE_PRIV_FAIL;
2226 			}
2227 			break;
2228 
2229 		case T_ADDR_ERR_ST:
2230 			kvm_debug("%s: address error ST @ %#lx\n", __func__,
2231 				  badvaddr);
2232 			if ((badvaddr & PAGE_MASK) == KVM_GUEST_COMMPAGE_ADDR) {
2233 				cause &= ~0xff;
2234 				cause |= (T_TLB_ST_MISS << CAUSEB_EXCCODE);
2235 			}
2236 			er = EMULATE_PRIV_FAIL;
2237 			break;
2238 		case T_ADDR_ERR_LD:
2239 			kvm_debug("%s: address error LD @ %#lx\n", __func__,
2240 				  badvaddr);
2241 			if ((badvaddr & PAGE_MASK) == KVM_GUEST_COMMPAGE_ADDR) {
2242 				cause &= ~0xff;
2243 				cause |= (T_TLB_LD_MISS << CAUSEB_EXCCODE);
2244 			}
2245 			er = EMULATE_PRIV_FAIL;
2246 			break;
2247 		default:
2248 			er = EMULATE_PRIV_FAIL;
2249 			break;
2250 		}
2251 	}
2252 
2253 	if (er == EMULATE_PRIV_FAIL)
2254 		kvm_mips_emulate_exc(cause, opc, run, vcpu);
2255 
2256 	return er;
2257 }
2258 
2259 /*
2260  * User Address (UA) fault, this could happen if
2261  * (1) TLB entry not present/valid in both Guest and shadow host TLBs, in this
2262  *     case we pass on the fault to the guest kernel and let it handle it.
2263  * (2) TLB entry is present in the Guest TLB but not in the shadow, in this
2264  *     case we inject the TLB from the Guest TLB into the shadow host TLB
2265  */
kvm_mips_handle_tlbmiss(unsigned long cause,uint32_t * opc,struct kvm_run * run,struct kvm_vcpu * vcpu)2266 enum emulation_result kvm_mips_handle_tlbmiss(unsigned long cause,
2267 					      uint32_t *opc,
2268 					      struct kvm_run *run,
2269 					      struct kvm_vcpu *vcpu)
2270 {
2271 	enum emulation_result er = EMULATE_DONE;
2272 	uint32_t exccode = (cause >> CAUSEB_EXCCODE) & 0x1f;
2273 	unsigned long va = vcpu->arch.host_cp0_badvaddr;
2274 	int index;
2275 
2276 	kvm_debug("kvm_mips_handle_tlbmiss: badvaddr: %#lx, entryhi: %#lx\n",
2277 		  vcpu->arch.host_cp0_badvaddr, vcpu->arch.host_cp0_entryhi);
2278 
2279 	/*
2280 	 * KVM would not have got the exception if this entry was valid in the
2281 	 * shadow host TLB. Check the Guest TLB, if the entry is not there then
2282 	 * send the guest an exception. The guest exc handler should then inject
2283 	 * an entry into the guest TLB.
2284 	 */
2285 	index = kvm_mips_guest_tlb_lookup(vcpu,
2286 					  (va & VPN2_MASK) |
2287 					  (kvm_read_c0_guest_entryhi
2288 					   (vcpu->arch.cop0) & ASID_MASK));
2289 	if (index < 0) {
2290 		if (exccode == T_TLB_LD_MISS) {
2291 			er = kvm_mips_emulate_tlbmiss_ld(cause, opc, run, vcpu);
2292 		} else if (exccode == T_TLB_ST_MISS) {
2293 			er = kvm_mips_emulate_tlbmiss_st(cause, opc, run, vcpu);
2294 		} else {
2295 			kvm_err("%s: invalid exc code: %d\n", __func__,
2296 				exccode);
2297 			er = EMULATE_FAIL;
2298 		}
2299 	} else {
2300 		struct kvm_mips_tlb *tlb = &vcpu->arch.guest_tlb[index];
2301 
2302 		/*
2303 		 * Check if the entry is valid, if not then setup a TLB invalid
2304 		 * exception to the guest
2305 		 */
2306 		if (!TLB_IS_VALID(*tlb, va)) {
2307 			if (exccode == T_TLB_LD_MISS) {
2308 				er = kvm_mips_emulate_tlbinv_ld(cause, opc, run,
2309 								vcpu);
2310 			} else if (exccode == T_TLB_ST_MISS) {
2311 				er = kvm_mips_emulate_tlbinv_st(cause, opc, run,
2312 								vcpu);
2313 			} else {
2314 				kvm_err("%s: invalid exc code: %d\n", __func__,
2315 					exccode);
2316 				er = EMULATE_FAIL;
2317 			}
2318 		} else {
2319 			kvm_debug("Injecting hi: %#lx, lo0: %#lx, lo1: %#lx into shadow host TLB\n",
2320 				  tlb->tlb_hi, tlb->tlb_lo0, tlb->tlb_lo1);
2321 			/*
2322 			 * OK we have a Guest TLB entry, now inject it into the
2323 			 * shadow host TLB
2324 			 */
2325 			kvm_mips_handle_mapped_seg_tlb_fault(vcpu, tlb, NULL,
2326 							     NULL);
2327 		}
2328 	}
2329 
2330 	return er;
2331 }
2332