Linux Audio

Check our new training course

Loading...
Note: File does not exist in v3.1.
   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/vmalloc.h>
  17#include <linux/fs.h>
  18#include <linux/memblock.h>
  19#include <linux/random.h>
  20#include <asm/page.h>
  21#include <asm/cacheflush.h>
  22#include <asm/cacheops.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 "interrupt.h"
  33#include "commpage.h"
  34
  35#include "trace.h"
  36
  37/*
  38 * Compute the return address and do emulate branch simulation, if required.
  39 * This function should be called only in branch delay slot active.
  40 */
  41static int kvm_compute_return_epc(struct kvm_vcpu *vcpu, unsigned long instpc,
  42				  unsigned long *out)
  43{
  44	unsigned int dspcontrol;
  45	union mips_instruction insn;
  46	struct kvm_vcpu_arch *arch = &vcpu->arch;
  47	long epc = instpc;
  48	long nextpc;
  49	int err;
  50
  51	if (epc & 3) {
  52		kvm_err("%s: unaligned epc\n", __func__);
  53		return -EINVAL;
  54	}
  55
  56	/* Read the instruction */
  57	err = kvm_get_badinstrp((u32 *)epc, vcpu, &insn.word);
  58	if (err)
  59		return err;
  60
  61	switch (insn.i_format.opcode) {
  62		/* jr and jalr are in r_format format. */
  63	case spec_op:
  64		switch (insn.r_format.func) {
  65		case jalr_op:
  66			arch->gprs[insn.r_format.rd] = epc + 8;
  67			/* Fall through */
  68		case jr_op:
  69			nextpc = arch->gprs[insn.r_format.rs];
  70			break;
  71		default:
  72			return -EINVAL;
  73		}
  74		break;
  75
  76		/*
  77		 * This group contains:
  78		 * bltz_op, bgez_op, bltzl_op, bgezl_op,
  79		 * bltzal_op, bgezal_op, bltzall_op, bgezall_op.
  80		 */
  81	case bcond_op:
  82		switch (insn.i_format.rt) {
  83		case bltz_op:
  84		case bltzl_op:
  85			if ((long)arch->gprs[insn.i_format.rs] < 0)
  86				epc = epc + 4 + (insn.i_format.simmediate << 2);
  87			else
  88				epc += 8;
  89			nextpc = epc;
  90			break;
  91
  92		case bgez_op:
  93		case bgezl_op:
  94			if ((long)arch->gprs[insn.i_format.rs] >= 0)
  95				epc = epc + 4 + (insn.i_format.simmediate << 2);
  96			else
  97				epc += 8;
  98			nextpc = epc;
  99			break;
 100
 101		case bltzal_op:
 102		case bltzall_op:
 103			arch->gprs[31] = epc + 8;
 104			if ((long)arch->gprs[insn.i_format.rs] < 0)
 105				epc = epc + 4 + (insn.i_format.simmediate << 2);
 106			else
 107				epc += 8;
 108			nextpc = epc;
 109			break;
 110
 111		case bgezal_op:
 112		case bgezall_op:
 113			arch->gprs[31] = epc + 8;
 114			if ((long)arch->gprs[insn.i_format.rs] >= 0)
 115				epc = epc + 4 + (insn.i_format.simmediate << 2);
 116			else
 117				epc += 8;
 118			nextpc = epc;
 119			break;
 120		case bposge32_op:
 121			if (!cpu_has_dsp) {
 122				kvm_err("%s: DSP branch but not DSP ASE\n",
 123					__func__);
 124				return -EINVAL;
 125			}
 126
 127			dspcontrol = rddsp(0x01);
 128
 129			if (dspcontrol >= 32)
 130				epc = epc + 4 + (insn.i_format.simmediate << 2);
 131			else
 132				epc += 8;
 133			nextpc = epc;
 134			break;
 135		default:
 136			return -EINVAL;
 137		}
 138		break;
 139
 140		/* These are unconditional and in j_format. */
 141	case jal_op:
 142		arch->gprs[31] = instpc + 8;
 143		/* fall through */
 144	case j_op:
 145		epc += 4;
 146		epc >>= 28;
 147		epc <<= 28;
 148		epc |= (insn.j_format.target << 2);
 149		nextpc = epc;
 150		break;
 151
 152		/* These are conditional and in i_format. */
 153	case beq_op:
 154	case beql_op:
 155		if (arch->gprs[insn.i_format.rs] ==
 156		    arch->gprs[insn.i_format.rt])
 157			epc = epc + 4 + (insn.i_format.simmediate << 2);
 158		else
 159			epc += 8;
 160		nextpc = epc;
 161		break;
 162
 163	case bne_op:
 164	case bnel_op:
 165		if (arch->gprs[insn.i_format.rs] !=
 166		    arch->gprs[insn.i_format.rt])
 167			epc = epc + 4 + (insn.i_format.simmediate << 2);
 168		else
 169			epc += 8;
 170		nextpc = epc;
 171		break;
 172
 173	case blez_op:	/* POP06 */
 174#ifndef CONFIG_CPU_MIPSR6
 175	case blezl_op:	/* removed in R6 */
 176#endif
 177		if (insn.i_format.rt != 0)
 178			goto compact_branch;
 179		if ((long)arch->gprs[insn.i_format.rs] <= 0)
 180			epc = epc + 4 + (insn.i_format.simmediate << 2);
 181		else
 182			epc += 8;
 183		nextpc = epc;
 184		break;
 185
 186	case bgtz_op:	/* POP07 */
 187#ifndef CONFIG_CPU_MIPSR6
 188	case bgtzl_op:	/* removed in R6 */
 189#endif
 190		if (insn.i_format.rt != 0)
 191			goto compact_branch;
 192		if ((long)arch->gprs[insn.i_format.rs] > 0)
 193			epc = epc + 4 + (insn.i_format.simmediate << 2);
 194		else
 195			epc += 8;
 196		nextpc = epc;
 197		break;
 198
 199		/* And now the FPA/cp1 branch instructions. */
 200	case cop1_op:
 201		kvm_err("%s: unsupported cop1_op\n", __func__);
 202		return -EINVAL;
 203
 204#ifdef CONFIG_CPU_MIPSR6
 205	/* R6 added the following compact branches with forbidden slots */
 206	case blezl_op:	/* POP26 */
 207	case bgtzl_op:	/* POP27 */
 208		/* only rt == 0 isn't compact branch */
 209		if (insn.i_format.rt != 0)
 210			goto compact_branch;
 211		return -EINVAL;
 212	case pop10_op:
 213	case pop30_op:
 214		/* only rs == rt == 0 is reserved, rest are compact branches */
 215		if (insn.i_format.rs != 0 || insn.i_format.rt != 0)
 216			goto compact_branch;
 217		return -EINVAL;
 218	case pop66_op:
 219	case pop76_op:
 220		/* only rs == 0 isn't compact branch */
 221		if (insn.i_format.rs != 0)
 222			goto compact_branch;
 223		return -EINVAL;
 224compact_branch:
 225		/*
 226		 * If we've hit an exception on the forbidden slot, then
 227		 * the branch must not have been taken.
 228		 */
 229		epc += 8;
 230		nextpc = epc;
 231		break;
 232#else
 233compact_branch:
 234		/* Fall through - Compact branches not supported before R6 */
 235#endif
 236	default:
 237		return -EINVAL;
 238	}
 239
 240	*out = nextpc;
 241	return 0;
 242}
 243
 244enum emulation_result update_pc(struct kvm_vcpu *vcpu, u32 cause)
 245{
 246	int err;
 247
 248	if (cause & CAUSEF_BD) {
 249		err = kvm_compute_return_epc(vcpu, vcpu->arch.pc,
 250					     &vcpu->arch.pc);
 251		if (err)
 252			return EMULATE_FAIL;
 253	} else {
 254		vcpu->arch.pc += 4;
 255	}
 256
 257	kvm_debug("update_pc(): New PC: %#lx\n", vcpu->arch.pc);
 258
 259	return EMULATE_DONE;
 260}
 261
 262/**
 263 * kvm_get_badinstr() - Get bad instruction encoding.
 264 * @opc:	Guest pointer to faulting instruction.
 265 * @vcpu:	KVM VCPU information.
 266 *
 267 * Gets the instruction encoding of the faulting instruction, using the saved
 268 * BadInstr register value if it exists, otherwise falling back to reading guest
 269 * memory at @opc.
 270 *
 271 * Returns:	The instruction encoding of the faulting instruction.
 272 */
 273int kvm_get_badinstr(u32 *opc, struct kvm_vcpu *vcpu, u32 *out)
 274{
 275	if (cpu_has_badinstr) {
 276		*out = vcpu->arch.host_cp0_badinstr;
 277		return 0;
 278	} else {
 279		return kvm_get_inst(opc, vcpu, out);
 280	}
 281}
 282
 283/**
 284 * kvm_get_badinstrp() - Get bad prior instruction encoding.
 285 * @opc:	Guest pointer to prior faulting instruction.
 286 * @vcpu:	KVM VCPU information.
 287 *
 288 * Gets the instruction encoding of the prior faulting instruction (the branch
 289 * containing the delay slot which faulted), using the saved BadInstrP register
 290 * value if it exists, otherwise falling back to reading guest memory at @opc.
 291 *
 292 * Returns:	The instruction encoding of the prior faulting instruction.
 293 */
 294int kvm_get_badinstrp(u32 *opc, struct kvm_vcpu *vcpu, u32 *out)
 295{
 296	if (cpu_has_badinstrp) {
 297		*out = vcpu->arch.host_cp0_badinstrp;
 298		return 0;
 299	} else {
 300		return kvm_get_inst(opc, vcpu, out);
 301	}
 302}
 303
 304/**
 305 * kvm_mips_count_disabled() - Find whether the CP0_Count timer is disabled.
 306 * @vcpu:	Virtual CPU.
 307 *
 308 * Returns:	1 if the CP0_Count timer is disabled by either the guest
 309 *		CP0_Cause.DC bit or the count_ctl.DC bit.
 310 *		0 otherwise (in which case CP0_Count timer is running).
 311 */
 312int kvm_mips_count_disabled(struct kvm_vcpu *vcpu)
 313{
 314	struct mips_coproc *cop0 = vcpu->arch.cop0;
 315
 316	return	(vcpu->arch.count_ctl & KVM_REG_MIPS_COUNT_CTL_DC) ||
 317		(kvm_read_c0_guest_cause(cop0) & CAUSEF_DC);
 318}
 319
 320/**
 321 * kvm_mips_ktime_to_count() - Scale ktime_t to a 32-bit count.
 322 *
 323 * Caches the dynamic nanosecond bias in vcpu->arch.count_dyn_bias.
 324 *
 325 * Assumes !kvm_mips_count_disabled(@vcpu) (guest CP0_Count timer is running).
 326 */
 327static u32 kvm_mips_ktime_to_count(struct kvm_vcpu *vcpu, ktime_t now)
 328{
 329	s64 now_ns, periods;
 330	u64 delta;
 331
 332	now_ns = ktime_to_ns(now);
 333	delta = now_ns + vcpu->arch.count_dyn_bias;
 334
 335	if (delta >= vcpu->arch.count_period) {
 336		/* If delta is out of safe range the bias needs adjusting */
 337		periods = div64_s64(now_ns, vcpu->arch.count_period);
 338		vcpu->arch.count_dyn_bias = -periods * vcpu->arch.count_period;
 339		/* Recalculate delta with new bias */
 340		delta = now_ns + vcpu->arch.count_dyn_bias;
 341	}
 342
 343	/*
 344	 * We've ensured that:
 345	 *   delta < count_period
 346	 *
 347	 * Therefore the intermediate delta*count_hz will never overflow since
 348	 * at the boundary condition:
 349	 *   delta = count_period
 350	 *   delta = NSEC_PER_SEC * 2^32 / count_hz
 351	 *   delta * count_hz = NSEC_PER_SEC * 2^32
 352	 */
 353	return div_u64(delta * vcpu->arch.count_hz, NSEC_PER_SEC);
 354}
 355
 356/**
 357 * kvm_mips_count_time() - Get effective current time.
 358 * @vcpu:	Virtual CPU.
 359 *
 360 * Get effective monotonic ktime. This is usually a straightforward ktime_get(),
 361 * except when the master disable bit is set in count_ctl, in which case it is
 362 * count_resume, i.e. the time that the count was disabled.
 363 *
 364 * Returns:	Effective monotonic ktime for CP0_Count.
 365 */
 366static inline ktime_t kvm_mips_count_time(struct kvm_vcpu *vcpu)
 367{
 368	if (unlikely(vcpu->arch.count_ctl & KVM_REG_MIPS_COUNT_CTL_DC))
 369		return vcpu->arch.count_resume;
 370
 371	return ktime_get();
 372}
 373
 374/**
 375 * kvm_mips_read_count_running() - Read the current count value as if running.
 376 * @vcpu:	Virtual CPU.
 377 * @now:	Kernel time to read CP0_Count at.
 378 *
 379 * Returns the current guest CP0_Count register at time @now and handles if the
 380 * timer interrupt is pending and hasn't been handled yet.
 381 *
 382 * Returns:	The current value of the guest CP0_Count register.
 383 */
 384static u32 kvm_mips_read_count_running(struct kvm_vcpu *vcpu, ktime_t now)
 385{
 386	struct mips_coproc *cop0 = vcpu->arch.cop0;
 387	ktime_t expires, threshold;
 388	u32 count, compare;
 389	int running;
 390
 391	/* Calculate the biased and scaled guest CP0_Count */
 392	count = vcpu->arch.count_bias + kvm_mips_ktime_to_count(vcpu, now);
 393	compare = kvm_read_c0_guest_compare(cop0);
 394
 395	/*
 396	 * Find whether CP0_Count has reached the closest timer interrupt. If
 397	 * not, we shouldn't inject it.
 398	 */
 399	if ((s32)(count - compare) < 0)
 400		return count;
 401
 402	/*
 403	 * The CP0_Count we're going to return has already reached the closest
 404	 * timer interrupt. Quickly check if it really is a new interrupt by
 405	 * looking at whether the interval until the hrtimer expiry time is
 406	 * less than 1/4 of the timer period.
 407	 */
 408	expires = hrtimer_get_expires(&vcpu->arch.comparecount_timer);
 409	threshold = ktime_add_ns(now, vcpu->arch.count_period / 4);
 410	if (ktime_before(expires, threshold)) {
 411		/*
 412		 * Cancel it while we handle it so there's no chance of
 413		 * interference with the timeout handler.
 414		 */
 415		running = hrtimer_cancel(&vcpu->arch.comparecount_timer);
 416
 417		/* Nothing should be waiting on the timeout */
 418		kvm_mips_callbacks->queue_timer_int(vcpu);
 419
 420		/*
 421		 * Restart the timer if it was running based on the expiry time
 422		 * we read, so that we don't push it back 2 periods.
 423		 */
 424		if (running) {
 425			expires = ktime_add_ns(expires,
 426					       vcpu->arch.count_period);
 427			hrtimer_start(&vcpu->arch.comparecount_timer, expires,
 428				      HRTIMER_MODE_ABS);
 429		}
 430	}
 431
 432	return count;
 433}
 434
 435/**
 436 * kvm_mips_read_count() - Read the current count value.
 437 * @vcpu:	Virtual CPU.
 438 *
 439 * Read the current guest CP0_Count value, taking into account whether the timer
 440 * is stopped.
 441 *
 442 * Returns:	The current guest CP0_Count value.
 443 */
 444u32 kvm_mips_read_count(struct kvm_vcpu *vcpu)
 445{
 446	struct mips_coproc *cop0 = vcpu->arch.cop0;
 447
 448	/* If count disabled just read static copy of count */
 449	if (kvm_mips_count_disabled(vcpu))
 450		return kvm_read_c0_guest_count(cop0);
 451
 452	return kvm_mips_read_count_running(vcpu, ktime_get());
 453}
 454
 455/**
 456 * kvm_mips_freeze_hrtimer() - Safely stop the hrtimer.
 457 * @vcpu:	Virtual CPU.
 458 * @count:	Output pointer for CP0_Count value at point of freeze.
 459 *
 460 * Freeze the hrtimer safely and return both the ktime and the CP0_Count value
 461 * at the point it was frozen. It is guaranteed that any pending interrupts at
 462 * the point it was frozen are handled, and none after that point.
 463 *
 464 * This is useful where the time/CP0_Count is needed in the calculation of the
 465 * new parameters.
 466 *
 467 * Assumes !kvm_mips_count_disabled(@vcpu) (guest CP0_Count timer is running).
 468 *
 469 * Returns:	The ktime at the point of freeze.
 470 */
 471ktime_t kvm_mips_freeze_hrtimer(struct kvm_vcpu *vcpu, u32 *count)
 472{
 473	ktime_t now;
 474
 475	/* stop hrtimer before finding time */
 476	hrtimer_cancel(&vcpu->arch.comparecount_timer);
 477	now = ktime_get();
 478
 479	/* find count at this point and handle pending hrtimer */
 480	*count = kvm_mips_read_count_running(vcpu, now);
 481
 482	return now;
 483}
 484
 485/**
 486 * kvm_mips_resume_hrtimer() - Resume hrtimer, updating expiry.
 487 * @vcpu:	Virtual CPU.
 488 * @now:	ktime at point of resume.
 489 * @count:	CP0_Count at point of resume.
 490 *
 491 * Resumes the timer and updates the timer expiry based on @now and @count.
 492 * This can be used in conjunction with kvm_mips_freeze_timer() when timer
 493 * parameters need to be changed.
 494 *
 495 * It is guaranteed that a timer interrupt immediately after resume will be
 496 * handled, but not if CP_Compare is exactly at @count. That case is already
 497 * handled by kvm_mips_freeze_timer().
 498 *
 499 * Assumes !kvm_mips_count_disabled(@vcpu) (guest CP0_Count timer is running).
 500 */
 501static void kvm_mips_resume_hrtimer(struct kvm_vcpu *vcpu,
 502				    ktime_t now, u32 count)
 503{
 504	struct mips_coproc *cop0 = vcpu->arch.cop0;
 505	u32 compare;
 506	u64 delta;
 507	ktime_t expire;
 508
 509	/* Calculate timeout (wrap 0 to 2^32) */
 510	compare = kvm_read_c0_guest_compare(cop0);
 511	delta = (u64)(u32)(compare - count - 1) + 1;
 512	delta = div_u64(delta * NSEC_PER_SEC, vcpu->arch.count_hz);
 513	expire = ktime_add_ns(now, delta);
 514
 515	/* Update hrtimer to use new timeout */
 516	hrtimer_cancel(&vcpu->arch.comparecount_timer);
 517	hrtimer_start(&vcpu->arch.comparecount_timer, expire, HRTIMER_MODE_ABS);
 518}
 519
 520/**
 521 * kvm_mips_restore_hrtimer() - Restore hrtimer after a gap, updating expiry.
 522 * @vcpu:	Virtual CPU.
 523 * @before:	Time before Count was saved, lower bound of drift calculation.
 524 * @count:	CP0_Count at point of restore.
 525 * @min_drift:	Minimum amount of drift permitted before correction.
 526 *		Must be <= 0.
 527 *
 528 * Restores the timer from a particular @count, accounting for drift. This can
 529 * be used in conjunction with kvm_mips_freeze_timer() when a hardware timer is
 530 * to be used for a period of time, but the exact ktime corresponding to the
 531 * final Count that must be restored is not known.
 532 *
 533 * It is gauranteed that a timer interrupt immediately after restore will be
 534 * handled, but not if CP0_Compare is exactly at @count. That case should
 535 * already be handled when the hardware timer state is saved.
 536 *
 537 * Assumes !kvm_mips_count_disabled(@vcpu) (guest CP0_Count timer is not
 538 * stopped).
 539 *
 540 * Returns:	Amount of correction to count_bias due to drift.
 541 */
 542int kvm_mips_restore_hrtimer(struct kvm_vcpu *vcpu, ktime_t before,
 543			     u32 count, int min_drift)
 544{
 545	ktime_t now, count_time;
 546	u32 now_count, before_count;
 547	u64 delta;
 548	int drift, ret = 0;
 549
 550	/* Calculate expected count at before */
 551	before_count = vcpu->arch.count_bias +
 552			kvm_mips_ktime_to_count(vcpu, before);
 553
 554	/*
 555	 * Detect significantly negative drift, where count is lower than
 556	 * expected. Some negative drift is expected when hardware counter is
 557	 * set after kvm_mips_freeze_timer(), and it is harmless to allow the
 558	 * time to jump forwards a little, within reason. If the drift is too
 559	 * significant, adjust the bias to avoid a big Guest.CP0_Count jump.
 560	 */
 561	drift = count - before_count;
 562	if (drift < min_drift) {
 563		count_time = before;
 564		vcpu->arch.count_bias += drift;
 565		ret = drift;
 566		goto resume;
 567	}
 568
 569	/* Calculate expected count right now */
 570	now = ktime_get();
 571	now_count = vcpu->arch.count_bias + kvm_mips_ktime_to_count(vcpu, now);
 572
 573	/*
 574	 * Detect positive drift, where count is higher than expected, and
 575	 * adjust the bias to avoid guest time going backwards.
 576	 */
 577	drift = count - now_count;
 578	if (drift > 0) {
 579		count_time = now;
 580		vcpu->arch.count_bias += drift;
 581		ret = drift;
 582		goto resume;
 583	}
 584
 585	/* Subtract nanosecond delta to find ktime when count was read */
 586	delta = (u64)(u32)(now_count - count);
 587	delta = div_u64(delta * NSEC_PER_SEC, vcpu->arch.count_hz);
 588	count_time = ktime_sub_ns(now, delta);
 589
 590resume:
 591	/* Resume using the calculated ktime */
 592	kvm_mips_resume_hrtimer(vcpu, count_time, count);
 593	return ret;
 594}
 595
 596/**
 597 * kvm_mips_write_count() - Modify the count and update timer.
 598 * @vcpu:	Virtual CPU.
 599 * @count:	Guest CP0_Count value to set.
 600 *
 601 * Sets the CP0_Count value and updates the timer accordingly.
 602 */
 603void kvm_mips_write_count(struct kvm_vcpu *vcpu, u32 count)
 604{
 605	struct mips_coproc *cop0 = vcpu->arch.cop0;
 606	ktime_t now;
 607
 608	/* Calculate bias */
 609	now = kvm_mips_count_time(vcpu);
 610	vcpu->arch.count_bias = count - kvm_mips_ktime_to_count(vcpu, now);
 611
 612	if (kvm_mips_count_disabled(vcpu))
 613		/* The timer's disabled, adjust the static count */
 614		kvm_write_c0_guest_count(cop0, count);
 615	else
 616		/* Update timeout */
 617		kvm_mips_resume_hrtimer(vcpu, now, count);
 618}
 619
 620/**
 621 * kvm_mips_init_count() - Initialise timer.
 622 * @vcpu:	Virtual CPU.
 623 * @count_hz:	Frequency of timer.
 624 *
 625 * Initialise the timer to the specified frequency, zero it, and set it going if
 626 * it's enabled.
 627 */
 628void kvm_mips_init_count(struct kvm_vcpu *vcpu, unsigned long count_hz)
 629{
 630	vcpu->arch.count_hz = count_hz;
 631	vcpu->arch.count_period = div_u64((u64)NSEC_PER_SEC << 32, count_hz);
 632	vcpu->arch.count_dyn_bias = 0;
 633
 634	/* Starting at 0 */
 635	kvm_mips_write_count(vcpu, 0);
 636}
 637
 638/**
 639 * kvm_mips_set_count_hz() - Update the frequency of the timer.
 640 * @vcpu:	Virtual CPU.
 641 * @count_hz:	Frequency of CP0_Count timer in Hz.
 642 *
 643 * Change the frequency of the CP0_Count timer. This is done atomically so that
 644 * CP0_Count is continuous and no timer interrupt is lost.
 645 *
 646 * Returns:	-EINVAL if @count_hz is out of range.
 647 *		0 on success.
 648 */
 649int kvm_mips_set_count_hz(struct kvm_vcpu *vcpu, s64 count_hz)
 650{
 651	struct mips_coproc *cop0 = vcpu->arch.cop0;
 652	int dc;
 653	ktime_t now;
 654	u32 count;
 655
 656	/* ensure the frequency is in a sensible range... */
 657	if (count_hz <= 0 || count_hz > NSEC_PER_SEC)
 658		return -EINVAL;
 659	/* ... and has actually changed */
 660	if (vcpu->arch.count_hz == count_hz)
 661		return 0;
 662
 663	/* Safely freeze timer so we can keep it continuous */
 664	dc = kvm_mips_count_disabled(vcpu);
 665	if (dc) {
 666		now = kvm_mips_count_time(vcpu);
 667		count = kvm_read_c0_guest_count(cop0);
 668	} else {
 669		now = kvm_mips_freeze_hrtimer(vcpu, &count);
 670	}
 671
 672	/* Update the frequency */
 673	vcpu->arch.count_hz = count_hz;
 674	vcpu->arch.count_period = div_u64((u64)NSEC_PER_SEC << 32, count_hz);
 675	vcpu->arch.count_dyn_bias = 0;
 676
 677	/* Calculate adjusted bias so dynamic count is unchanged */
 678	vcpu->arch.count_bias = count - kvm_mips_ktime_to_count(vcpu, now);
 679
 680	/* Update and resume hrtimer */
 681	if (!dc)
 682		kvm_mips_resume_hrtimer(vcpu, now, count);
 683	return 0;
 684}
 685
 686/**
 687 * kvm_mips_write_compare() - Modify compare and update timer.
 688 * @vcpu:	Virtual CPU.
 689 * @compare:	New CP0_Compare value.
 690 * @ack:	Whether to acknowledge timer interrupt.
 691 *
 692 * Update CP0_Compare to a new value and update the timeout.
 693 * If @ack, atomically acknowledge any pending timer interrupt, otherwise ensure
 694 * any pending timer interrupt is preserved.
 695 */
 696void kvm_mips_write_compare(struct kvm_vcpu *vcpu, u32 compare, bool ack)
 697{
 698	struct mips_coproc *cop0 = vcpu->arch.cop0;
 699	int dc;
 700	u32 old_compare = kvm_read_c0_guest_compare(cop0);
 701	s32 delta = compare - old_compare;
 702	u32 cause;
 703	ktime_t now = ktime_set(0, 0); /* silence bogus GCC warning */
 704	u32 count;
 705
 706	/* if unchanged, must just be an ack */
 707	if (old_compare == compare) {
 708		if (!ack)
 709			return;
 710		kvm_mips_callbacks->dequeue_timer_int(vcpu);
 711		kvm_write_c0_guest_compare(cop0, compare);
 712		return;
 713	}
 714
 715	/*
 716	 * If guest CP0_Compare moves forward, CP0_GTOffset should be adjusted
 717	 * too to prevent guest CP0_Count hitting guest CP0_Compare.
 718	 *
 719	 * The new GTOffset corresponds to the new value of CP0_Compare, and is
 720	 * set prior to it being written into the guest context. We disable
 721	 * preemption until the new value is written to prevent restore of a
 722	 * GTOffset corresponding to the old CP0_Compare value.
 723	 */
 724	if (IS_ENABLED(CONFIG_KVM_MIPS_VZ) && delta > 0) {
 725		preempt_disable();
 726		write_c0_gtoffset(compare - read_c0_count());
 727		back_to_back_c0_hazard();
 728	}
 729
 730	/* freeze_hrtimer() takes care of timer interrupts <= count */
 731	dc = kvm_mips_count_disabled(vcpu);
 732	if (!dc)
 733		now = kvm_mips_freeze_hrtimer(vcpu, &count);
 734
 735	if (ack)
 736		kvm_mips_callbacks->dequeue_timer_int(vcpu);
 737	else if (IS_ENABLED(CONFIG_KVM_MIPS_VZ))
 738		/*
 739		 * With VZ, writing CP0_Compare acks (clears) CP0_Cause.TI, so
 740		 * preserve guest CP0_Cause.TI if we don't want to ack it.
 741		 */
 742		cause = kvm_read_c0_guest_cause(cop0);
 743
 744	kvm_write_c0_guest_compare(cop0, compare);
 745
 746	if (IS_ENABLED(CONFIG_KVM_MIPS_VZ)) {
 747		if (delta > 0)
 748			preempt_enable();
 749
 750		back_to_back_c0_hazard();
 751
 752		if (!ack && cause & CAUSEF_TI)
 753			kvm_write_c0_guest_cause(cop0, cause);
 754	}
 755
 756	/* resume_hrtimer() takes care of timer interrupts > count */
 757	if (!dc)
 758		kvm_mips_resume_hrtimer(vcpu, now, count);
 759
 760	/*
 761	 * If guest CP0_Compare is moving backward, we delay CP0_GTOffset change
 762	 * until after the new CP0_Compare is written, otherwise new guest
 763	 * CP0_Count could hit new guest CP0_Compare.
 764	 */
 765	if (IS_ENABLED(CONFIG_KVM_MIPS_VZ) && delta <= 0)
 766		write_c0_gtoffset(compare - read_c0_count());
 767}
 768
 769/**
 770 * kvm_mips_count_disable() - Disable count.
 771 * @vcpu:	Virtual CPU.
 772 *
 773 * Disable the CP0_Count timer. A timer interrupt on or before the final stop
 774 * time will be handled but not after.
 775 *
 776 * Assumes CP0_Count was previously enabled but now Guest.CP0_Cause.DC or
 777 * count_ctl.DC has been set (count disabled).
 778 *
 779 * Returns:	The time that the timer was stopped.
 780 */
 781static ktime_t kvm_mips_count_disable(struct kvm_vcpu *vcpu)
 782{
 783	struct mips_coproc *cop0 = vcpu->arch.cop0;
 784	u32 count;
 785	ktime_t now;
 786
 787	/* Stop hrtimer */
 788	hrtimer_cancel(&vcpu->arch.comparecount_timer);
 789
 790	/* Set the static count from the dynamic count, handling pending TI */
 791	now = ktime_get();
 792	count = kvm_mips_read_count_running(vcpu, now);
 793	kvm_write_c0_guest_count(cop0, count);
 794
 795	return now;
 796}
 797
 798/**
 799 * kvm_mips_count_disable_cause() - Disable count using CP0_Cause.DC.
 800 * @vcpu:	Virtual CPU.
 801 *
 802 * Disable the CP0_Count timer and set CP0_Cause.DC. A timer interrupt on or
 803 * before the final stop time will be handled if the timer isn't disabled by
 804 * count_ctl.DC, but not after.
 805 *
 806 * Assumes CP0_Cause.DC is clear (count enabled).
 807 */
 808void kvm_mips_count_disable_cause(struct kvm_vcpu *vcpu)
 809{
 810	struct mips_coproc *cop0 = vcpu->arch.cop0;
 811
 812	kvm_set_c0_guest_cause(cop0, CAUSEF_DC);
 813	if (!(vcpu->arch.count_ctl & KVM_REG_MIPS_COUNT_CTL_DC))
 814		kvm_mips_count_disable(vcpu);
 815}
 816
 817/**
 818 * kvm_mips_count_enable_cause() - Enable count using CP0_Cause.DC.
 819 * @vcpu:	Virtual CPU.
 820 *
 821 * Enable the CP0_Count timer and clear CP0_Cause.DC. A timer interrupt after
 822 * the start time will be handled if the timer isn't disabled by count_ctl.DC,
 823 * potentially before even returning, so the caller should be careful with
 824 * ordering of CP0_Cause modifications so as not to lose it.
 825 *
 826 * Assumes CP0_Cause.DC is set (count disabled).
 827 */
 828void kvm_mips_count_enable_cause(struct kvm_vcpu *vcpu)
 829{
 830	struct mips_coproc *cop0 = vcpu->arch.cop0;
 831	u32 count;
 832
 833	kvm_clear_c0_guest_cause(cop0, CAUSEF_DC);
 834
 835	/*
 836	 * Set the dynamic count to match the static count.
 837	 * This starts the hrtimer if count_ctl.DC allows it.
 838	 * Otherwise it conveniently updates the biases.
 839	 */
 840	count = kvm_read_c0_guest_count(cop0);
 841	kvm_mips_write_count(vcpu, count);
 842}
 843
 844/**
 845 * kvm_mips_set_count_ctl() - Update the count control KVM register.
 846 * @vcpu:	Virtual CPU.
 847 * @count_ctl:	Count control register new value.
 848 *
 849 * Set the count control KVM register. The timer is updated accordingly.
 850 *
 851 * Returns:	-EINVAL if reserved bits are set.
 852 *		0 on success.
 853 */
 854int kvm_mips_set_count_ctl(struct kvm_vcpu *vcpu, s64 count_ctl)
 855{
 856	struct mips_coproc *cop0 = vcpu->arch.cop0;
 857	s64 changed = count_ctl ^ vcpu->arch.count_ctl;
 858	s64 delta;
 859	ktime_t expire, now;
 860	u32 count, compare;
 861
 862	/* Only allow defined bits to be changed */
 863	if (changed & ~(s64)(KVM_REG_MIPS_COUNT_CTL_DC))
 864		return -EINVAL;
 865
 866	/* Apply new value */
 867	vcpu->arch.count_ctl = count_ctl;
 868
 869	/* Master CP0_Count disable */
 870	if (changed & KVM_REG_MIPS_COUNT_CTL_DC) {
 871		/* Is CP0_Cause.DC already disabling CP0_Count? */
 872		if (kvm_read_c0_guest_cause(cop0) & CAUSEF_DC) {
 873			if (count_ctl & KVM_REG_MIPS_COUNT_CTL_DC)
 874				/* Just record the current time */
 875				vcpu->arch.count_resume = ktime_get();
 876		} else if (count_ctl & KVM_REG_MIPS_COUNT_CTL_DC) {
 877			/* disable timer and record current time */
 878			vcpu->arch.count_resume = kvm_mips_count_disable(vcpu);
 879		} else {
 880			/*
 881			 * Calculate timeout relative to static count at resume
 882			 * time (wrap 0 to 2^32).
 883			 */
 884			count = kvm_read_c0_guest_count(cop0);
 885			compare = kvm_read_c0_guest_compare(cop0);
 886			delta = (u64)(u32)(compare - count - 1) + 1;
 887			delta = div_u64(delta * NSEC_PER_SEC,
 888					vcpu->arch.count_hz);
 889			expire = ktime_add_ns(vcpu->arch.count_resume, delta);
 890
 891			/* Handle pending interrupt */
 892			now = ktime_get();
 893			if (ktime_compare(now, expire) >= 0)
 894				/* Nothing should be waiting on the timeout */
 895				kvm_mips_callbacks->queue_timer_int(vcpu);
 896
 897			/* Resume hrtimer without changing bias */
 898			count = kvm_mips_read_count_running(vcpu, now);
 899			kvm_mips_resume_hrtimer(vcpu, now, count);
 900		}
 901	}
 902
 903	return 0;
 904}
 905
 906/**
 907 * kvm_mips_set_count_resume() - Update the count resume KVM register.
 908 * @vcpu:		Virtual CPU.
 909 * @count_resume:	Count resume register new value.
 910 *
 911 * Set the count resume KVM register.
 912 *
 913 * Returns:	-EINVAL if out of valid range (0..now).
 914 *		0 on success.
 915 */
 916int kvm_mips_set_count_resume(struct kvm_vcpu *vcpu, s64 count_resume)
 917{
 918	/*
 919	 * It doesn't make sense for the resume time to be in the future, as it
 920	 * would be possible for the next interrupt to be more than a full
 921	 * period in the future.
 922	 */
 923	if (count_resume < 0 || count_resume > ktime_to_ns(ktime_get()))
 924		return -EINVAL;
 925
 926	vcpu->arch.count_resume = ns_to_ktime(count_resume);
 927	return 0;
 928}
 929
 930/**
 931 * kvm_mips_count_timeout() - Push timer forward on timeout.
 932 * @vcpu:	Virtual CPU.
 933 *
 934 * Handle an hrtimer event by push the hrtimer forward a period.
 935 *
 936 * Returns:	The hrtimer_restart value to return to the hrtimer subsystem.
 937 */
 938enum hrtimer_restart kvm_mips_count_timeout(struct kvm_vcpu *vcpu)
 939{
 940	/* Add the Count period to the current expiry time */
 941	hrtimer_add_expires_ns(&vcpu->arch.comparecount_timer,
 942			       vcpu->arch.count_period);
 943	return HRTIMER_RESTART;
 944}
 945
 946enum emulation_result kvm_mips_emul_eret(struct kvm_vcpu *vcpu)
 947{
 948	struct mips_coproc *cop0 = vcpu->arch.cop0;
 949	enum emulation_result er = EMULATE_DONE;
 950
 951	if (kvm_read_c0_guest_status(cop0) & ST0_ERL) {
 952		kvm_clear_c0_guest_status(cop0, ST0_ERL);
 953		vcpu->arch.pc = kvm_read_c0_guest_errorepc(cop0);
 954	} else if (kvm_read_c0_guest_status(cop0) & ST0_EXL) {
 955		kvm_debug("[%#lx] ERET to %#lx\n", vcpu->arch.pc,
 956			  kvm_read_c0_guest_epc(cop0));
 957		kvm_clear_c0_guest_status(cop0, ST0_EXL);
 958		vcpu->arch.pc = kvm_read_c0_guest_epc(cop0);
 959
 960	} else {
 961		kvm_err("[%#lx] ERET when MIPS_SR_EXL|MIPS_SR_ERL == 0\n",
 962			vcpu->arch.pc);
 963		er = EMULATE_FAIL;
 964	}
 965
 966	return er;
 967}
 968
 969enum emulation_result kvm_mips_emul_wait(struct kvm_vcpu *vcpu)
 970{
 971	kvm_debug("[%#lx] !!!WAIT!!! (%#lx)\n", vcpu->arch.pc,
 972		  vcpu->arch.pending_exceptions);
 973
 974	++vcpu->stat.wait_exits;
 975	trace_kvm_exit(vcpu, KVM_TRACE_EXIT_WAIT);
 976	if (!vcpu->arch.pending_exceptions) {
 977		kvm_vz_lose_htimer(vcpu);
 978		vcpu->arch.wait = 1;
 979		kvm_vcpu_block(vcpu);
 980
 981		/*
 982		 * We we are runnable, then definitely go off to user space to
 983		 * check if any I/O interrupts are pending.
 984		 */
 985		if (kvm_check_request(KVM_REQ_UNHALT, vcpu)) {
 986			kvm_clear_request(KVM_REQ_UNHALT, vcpu);
 987			vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
 988		}
 989	}
 990
 991	return EMULATE_DONE;
 992}
 993
 994static void kvm_mips_change_entryhi(struct kvm_vcpu *vcpu,
 995				    unsigned long entryhi)
 996{
 997	struct mips_coproc *cop0 = vcpu->arch.cop0;
 998	struct mm_struct *kern_mm = &vcpu->arch.guest_kernel_mm;
 999	int cpu, i;
1000	u32 nasid = entryhi & KVM_ENTRYHI_ASID;
1001
1002	if (((kvm_read_c0_guest_entryhi(cop0) & KVM_ENTRYHI_ASID) != nasid)) {
1003		trace_kvm_asid_change(vcpu, kvm_read_c0_guest_entryhi(cop0) &
1004				      KVM_ENTRYHI_ASID, nasid);
1005
1006		/*
1007		 * Flush entries from the GVA page tables.
1008		 * Guest user page table will get flushed lazily on re-entry to
1009		 * guest user if the guest ASID actually changes.
1010		 */
1011		kvm_mips_flush_gva_pt(kern_mm->pgd, KMF_KERN);
1012
1013		/*
1014		 * Regenerate/invalidate kernel MMU context.
1015		 * The user MMU context will be regenerated lazily on re-entry
1016		 * to guest user if the guest ASID actually changes.
1017		 */
1018		preempt_disable();
1019		cpu = smp_processor_id();
1020		get_new_mmu_context(kern_mm);
1021		for_each_possible_cpu(i)
1022			if (i != cpu)
1023				set_cpu_context(i, kern_mm, 0);
1024		preempt_enable();
1025	}
1026	kvm_write_c0_guest_entryhi(cop0, entryhi);
1027}
1028
1029enum emulation_result kvm_mips_emul_tlbr(struct kvm_vcpu *vcpu)
1030{
1031	struct mips_coproc *cop0 = vcpu->arch.cop0;
1032	struct kvm_mips_tlb *tlb;
1033	unsigned long pc = vcpu->arch.pc;
1034	int index;
1035
1036	index = kvm_read_c0_guest_index(cop0);
1037	if (index < 0 || index >= KVM_MIPS_GUEST_TLB_SIZE) {
1038		/* UNDEFINED */
1039		kvm_debug("[%#lx] TLBR Index %#x out of range\n", pc, index);
1040		index &= KVM_MIPS_GUEST_TLB_SIZE - 1;
1041	}
1042
1043	tlb = &vcpu->arch.guest_tlb[index];
1044	kvm_write_c0_guest_pagemask(cop0, tlb->tlb_mask);
1045	kvm_write_c0_guest_entrylo0(cop0, tlb->tlb_lo[0]);
1046	kvm_write_c0_guest_entrylo1(cop0, tlb->tlb_lo[1]);
1047	kvm_mips_change_entryhi(vcpu, tlb->tlb_hi);
1048
1049	return EMULATE_DONE;
1050}
1051
1052/**
1053 * kvm_mips_invalidate_guest_tlb() - Indicates a change in guest MMU map.
1054 * @vcpu:	VCPU with changed mappings.
1055 * @tlb:	TLB entry being removed.
1056 *
1057 * This is called to indicate a single change in guest MMU mappings, so that we
1058 * can arrange TLB flushes on this and other CPUs.
1059 */
1060static void kvm_mips_invalidate_guest_tlb(struct kvm_vcpu *vcpu,
1061					  struct kvm_mips_tlb *tlb)
1062{
1063	struct mm_struct *kern_mm = &vcpu->arch.guest_kernel_mm;
1064	struct mm_struct *user_mm = &vcpu->arch.guest_user_mm;
1065	int cpu, i;
1066	bool user;
1067
1068	/* No need to flush for entries which are already invalid */
1069	if (!((tlb->tlb_lo[0] | tlb->tlb_lo[1]) & ENTRYLO_V))
1070		return;
1071	/* Don't touch host kernel page tables or TLB mappings */
1072	if ((unsigned long)tlb->tlb_hi > 0x7fffffff)
1073		return;
1074	/* User address space doesn't need flushing for KSeg2/3 changes */
1075	user = tlb->tlb_hi < KVM_GUEST_KSEG0;
1076
1077	preempt_disable();
1078
1079	/* Invalidate page table entries */
1080	kvm_trap_emul_invalidate_gva(vcpu, tlb->tlb_hi & VPN2_MASK, user);
1081
1082	/*
1083	 * Probe the shadow host TLB for the entry being overwritten, if one
1084	 * matches, invalidate it
1085	 */
1086	kvm_mips_host_tlb_inv(vcpu, tlb->tlb_hi, user, true);
1087
1088	/* Invalidate the whole ASID on other CPUs */
1089	cpu = smp_processor_id();
1090	for_each_possible_cpu(i) {
1091		if (i == cpu)
1092			continue;
1093		if (user)
1094			set_cpu_context(i, user_mm, 0);
1095		set_cpu_context(i, kern_mm, 0);
1096	}
1097
1098	preempt_enable();
1099}
1100
1101/* Write Guest TLB Entry @ Index */
1102enum emulation_result kvm_mips_emul_tlbwi(struct kvm_vcpu *vcpu)
1103{
1104	struct mips_coproc *cop0 = vcpu->arch.cop0;
1105	int index = kvm_read_c0_guest_index(cop0);
1106	struct kvm_mips_tlb *tlb = NULL;
1107	unsigned long pc = vcpu->arch.pc;
1108
1109	if (index < 0 || index >= KVM_MIPS_GUEST_TLB_SIZE) {
1110		kvm_debug("%s: illegal index: %d\n", __func__, index);
1111		kvm_debug("[%#lx] COP0_TLBWI [%d] (entryhi: %#lx, entrylo0: %#lx entrylo1: %#lx, mask: %#lx)\n",
1112			  pc, index, kvm_read_c0_guest_entryhi(cop0),
1113			  kvm_read_c0_guest_entrylo0(cop0),
1114			  kvm_read_c0_guest_entrylo1(cop0),
1115			  kvm_read_c0_guest_pagemask(cop0));
1116		index = (index & ~0x80000000) % KVM_MIPS_GUEST_TLB_SIZE;
1117	}
1118
1119	tlb = &vcpu->arch.guest_tlb[index];
1120
1121	kvm_mips_invalidate_guest_tlb(vcpu, tlb);
1122
1123	tlb->tlb_mask = kvm_read_c0_guest_pagemask(cop0);
1124	tlb->tlb_hi = kvm_read_c0_guest_entryhi(cop0);
1125	tlb->tlb_lo[0] = kvm_read_c0_guest_entrylo0(cop0);
1126	tlb->tlb_lo[1] = kvm_read_c0_guest_entrylo1(cop0);
1127
1128	kvm_debug("[%#lx] COP0_TLBWI [%d] (entryhi: %#lx, entrylo0: %#lx entrylo1: %#lx, mask: %#lx)\n",
1129		  pc, index, kvm_read_c0_guest_entryhi(cop0),
1130		  kvm_read_c0_guest_entrylo0(cop0),
1131		  kvm_read_c0_guest_entrylo1(cop0),
1132		  kvm_read_c0_guest_pagemask(cop0));
1133
1134	return EMULATE_DONE;
1135}
1136
1137/* Write Guest TLB Entry @ Random Index */
1138enum emulation_result kvm_mips_emul_tlbwr(struct kvm_vcpu *vcpu)
1139{
1140	struct mips_coproc *cop0 = vcpu->arch.cop0;
1141	struct kvm_mips_tlb *tlb = NULL;
1142	unsigned long pc = vcpu->arch.pc;
1143	int index;
1144
1145	index = prandom_u32_max(KVM_MIPS_GUEST_TLB_SIZE);
1146	tlb = &vcpu->arch.guest_tlb[index];
1147
1148	kvm_mips_invalidate_guest_tlb(vcpu, tlb);
1149
1150	tlb->tlb_mask = kvm_read_c0_guest_pagemask(cop0);
1151	tlb->tlb_hi = kvm_read_c0_guest_entryhi(cop0);
1152	tlb->tlb_lo[0] = kvm_read_c0_guest_entrylo0(cop0);
1153	tlb->tlb_lo[1] = kvm_read_c0_guest_entrylo1(cop0);
1154
1155	kvm_debug("[%#lx] COP0_TLBWR[%d] (entryhi: %#lx, entrylo0: %#lx entrylo1: %#lx)\n",
1156		  pc, index, kvm_read_c0_guest_entryhi(cop0),
1157		  kvm_read_c0_guest_entrylo0(cop0),
1158		  kvm_read_c0_guest_entrylo1(cop0));
1159
1160	return EMULATE_DONE;
1161}
1162
1163enum emulation_result kvm_mips_emul_tlbp(struct kvm_vcpu *vcpu)
1164{
1165	struct mips_coproc *cop0 = vcpu->arch.cop0;
1166	long entryhi = kvm_read_c0_guest_entryhi(cop0);
1167	unsigned long pc = vcpu->arch.pc;
1168	int index = -1;
1169
1170	index = kvm_mips_guest_tlb_lookup(vcpu, entryhi);
1171
1172	kvm_write_c0_guest_index(cop0, index);
1173
1174	kvm_debug("[%#lx] COP0_TLBP (entryhi: %#lx), index: %d\n", pc, entryhi,
1175		  index);
1176
1177	return EMULATE_DONE;
1178}
1179
1180/**
1181 * kvm_mips_config1_wrmask() - Find mask of writable bits in guest Config1
1182 * @vcpu:	Virtual CPU.
1183 *
1184 * Finds the mask of bits which are writable in the guest's Config1 CP0
1185 * register, by userland (currently read-only to the guest).
1186 */
1187unsigned int kvm_mips_config1_wrmask(struct kvm_vcpu *vcpu)
1188{
1189	unsigned int mask = 0;
1190
1191	/* Permit FPU to be present if FPU is supported */
1192	if (kvm_mips_guest_can_have_fpu(&vcpu->arch))
1193		mask |= MIPS_CONF1_FP;
1194
1195	return mask;
1196}
1197
1198/**
1199 * kvm_mips_config3_wrmask() - Find mask of writable bits in guest Config3
1200 * @vcpu:	Virtual CPU.
1201 *
1202 * Finds the mask of bits which are writable in the guest's Config3 CP0
1203 * register, by userland (currently read-only to the guest).
1204 */
1205unsigned int kvm_mips_config3_wrmask(struct kvm_vcpu *vcpu)
1206{
1207	/* Config4 and ULRI are optional */
1208	unsigned int mask = MIPS_CONF_M | MIPS_CONF3_ULRI;
1209
1210	/* Permit MSA to be present if MSA is supported */
1211	if (kvm_mips_guest_can_have_msa(&vcpu->arch))
1212		mask |= MIPS_CONF3_MSA;
1213
1214	return mask;
1215}
1216
1217/**
1218 * kvm_mips_config4_wrmask() - Find mask of writable bits in guest Config4
1219 * @vcpu:	Virtual CPU.
1220 *
1221 * Finds the mask of bits which are writable in the guest's Config4 CP0
1222 * register, by userland (currently read-only to the guest).
1223 */
1224unsigned int kvm_mips_config4_wrmask(struct kvm_vcpu *vcpu)
1225{
1226	/* Config5 is optional */
1227	unsigned int mask = MIPS_CONF_M;
1228
1229	/* KScrExist */
1230	mask |= 0xfc << MIPS_CONF4_KSCREXIST_SHIFT;
1231
1232	return mask;
1233}
1234
1235/**
1236 * kvm_mips_config5_wrmask() - Find mask of writable bits in guest Config5
1237 * @vcpu:	Virtual CPU.
1238 *
1239 * Finds the mask of bits which are writable in the guest's Config5 CP0
1240 * register, by the guest itself.
1241 */
1242unsigned int kvm_mips_config5_wrmask(struct kvm_vcpu *vcpu)
1243{
1244	unsigned int mask = 0;
1245
1246	/* Permit MSAEn changes if MSA supported and enabled */
1247	if (kvm_mips_guest_has_msa(&vcpu->arch))
1248		mask |= MIPS_CONF5_MSAEN;
1249
1250	/*
1251	 * Permit guest FPU mode changes if FPU is enabled and the relevant
1252	 * feature exists according to FIR register.
1253	 */
1254	if (kvm_mips_guest_has_fpu(&vcpu->arch)) {
1255		if (cpu_has_fre)
1256			mask |= MIPS_CONF5_FRE;
1257		/* We don't support UFR or UFE */
1258	}
1259
1260	return mask;
1261}
1262
1263enum emulation_result kvm_mips_emulate_CP0(union mips_instruction inst,
1264					   u32 *opc, u32 cause,
1265					   struct kvm_run *run,
1266					   struct kvm_vcpu *vcpu)
1267{
1268	struct mips_coproc *cop0 = vcpu->arch.cop0;
1269	enum emulation_result er = EMULATE_DONE;
1270	u32 rt, rd, sel;
1271	unsigned long curr_pc;
1272
1273	/*
1274	 * Update PC and hold onto current PC in case there is
1275	 * an error and we want to rollback the PC
1276	 */
1277	curr_pc = vcpu->arch.pc;
1278	er = update_pc(vcpu, cause);
1279	if (er == EMULATE_FAIL)
1280		return er;
1281
1282	if (inst.co_format.co) {
1283		switch (inst.co_format.func) {
1284		case tlbr_op:	/*  Read indexed TLB entry  */
1285			er = kvm_mips_emul_tlbr(vcpu);
1286			break;
1287		case tlbwi_op:	/*  Write indexed  */
1288			er = kvm_mips_emul_tlbwi(vcpu);
1289			break;
1290		case tlbwr_op:	/*  Write random  */
1291			er = kvm_mips_emul_tlbwr(vcpu);
1292			break;
1293		case tlbp_op:	/* TLB Probe */
1294			er = kvm_mips_emul_tlbp(vcpu);
1295			break;
1296		case rfe_op:
1297			kvm_err("!!!COP0_RFE!!!\n");
1298			break;
1299		case eret_op:
1300			er = kvm_mips_emul_eret(vcpu);
1301			goto dont_update_pc;
1302		case wait_op:
1303			er = kvm_mips_emul_wait(vcpu);
1304			break;
1305		case hypcall_op:
1306			er = kvm_mips_emul_hypcall(vcpu, inst);
1307			break;
1308		}
1309	} else {
1310		rt = inst.c0r_format.rt;
1311		rd = inst.c0r_format.rd;
1312		sel = inst.c0r_format.sel;
1313
1314		switch (inst.c0r_format.rs) {
1315		case mfc_op:
1316#ifdef CONFIG_KVM_MIPS_DEBUG_COP0_COUNTERS
1317			cop0->stat[rd][sel]++;
1318#endif
1319			/* Get reg */
1320			if ((rd == MIPS_CP0_COUNT) && (sel == 0)) {
1321				vcpu->arch.gprs[rt] =
1322				    (s32)kvm_mips_read_count(vcpu);
1323			} else if ((rd == MIPS_CP0_ERRCTL) && (sel == 0)) {
1324				vcpu->arch.gprs[rt] = 0x0;
1325#ifdef CONFIG_KVM_MIPS_DYN_TRANS
1326				kvm_mips_trans_mfc0(inst, opc, vcpu);
1327#endif
1328			} else {
1329				vcpu->arch.gprs[rt] = (s32)cop0->reg[rd][sel];
1330
1331#ifdef CONFIG_KVM_MIPS_DYN_TRANS
1332				kvm_mips_trans_mfc0(inst, opc, vcpu);
1333#endif
1334			}
1335
1336			trace_kvm_hwr(vcpu, KVM_TRACE_MFC0,
1337				      KVM_TRACE_COP0(rd, sel),
1338				      vcpu->arch.gprs[rt]);
1339			break;
1340
1341		case dmfc_op:
1342			vcpu->arch.gprs[rt] = cop0->reg[rd][sel];
1343
1344			trace_kvm_hwr(vcpu, KVM_TRACE_DMFC0,
1345				      KVM_TRACE_COP0(rd, sel),
1346				      vcpu->arch.gprs[rt]);
1347			break;
1348
1349		case mtc_op:
1350#ifdef CONFIG_KVM_MIPS_DEBUG_COP0_COUNTERS
1351			cop0->stat[rd][sel]++;
1352#endif
1353			trace_kvm_hwr(vcpu, KVM_TRACE_MTC0,
1354				      KVM_TRACE_COP0(rd, sel),
1355				      vcpu->arch.gprs[rt]);
1356
1357			if ((rd == MIPS_CP0_TLB_INDEX)
1358			    && (vcpu->arch.gprs[rt] >=
1359				KVM_MIPS_GUEST_TLB_SIZE)) {
1360				kvm_err("Invalid TLB Index: %ld",
1361					vcpu->arch.gprs[rt]);
1362				er = EMULATE_FAIL;
1363				break;
1364			}
1365			if ((rd == MIPS_CP0_PRID) && (sel == 1)) {
1366				/*
1367				 * Preserve core number, and keep the exception
1368				 * base in guest KSeg0.
1369				 */
1370				kvm_change_c0_guest_ebase(cop0, 0x1ffff000,
1371							  vcpu->arch.gprs[rt]);
1372			} else if (rd == MIPS_CP0_TLB_HI && sel == 0) {
1373				kvm_mips_change_entryhi(vcpu,
1374							vcpu->arch.gprs[rt]);
1375			}
1376			/* Are we writing to COUNT */
1377			else if ((rd == MIPS_CP0_COUNT) && (sel == 0)) {
1378				kvm_mips_write_count(vcpu, vcpu->arch.gprs[rt]);
1379				goto done;
1380			} else if ((rd == MIPS_CP0_COMPARE) && (sel == 0)) {
1381				/* If we are writing to COMPARE */
1382				/* Clear pending timer interrupt, if any */
1383				kvm_mips_write_compare(vcpu,
1384						       vcpu->arch.gprs[rt],
1385						       true);
1386			} else if ((rd == MIPS_CP0_STATUS) && (sel == 0)) {
1387				unsigned int old_val, val, change;
1388
1389				old_val = kvm_read_c0_guest_status(cop0);
1390				val = vcpu->arch.gprs[rt];
1391				change = val ^ old_val;
1392
1393				/* Make sure that the NMI bit is never set */
1394				val &= ~ST0_NMI;
1395
1396				/*
1397				 * Don't allow CU1 or FR to be set unless FPU
1398				 * capability enabled and exists in guest
1399				 * configuration.
1400				 */
1401				if (!kvm_mips_guest_has_fpu(&vcpu->arch))
1402					val &= ~(ST0_CU1 | ST0_FR);
1403
1404				/*
1405				 * Also don't allow FR to be set if host doesn't
1406				 * support it.
1407				 */
1408				if (!(current_cpu_data.fpu_id & MIPS_FPIR_F64))
1409					val &= ~ST0_FR;
1410
1411
1412				/* Handle changes in FPU mode */
1413				preempt_disable();
1414
1415				/*
1416				 * FPU and Vector register state is made
1417				 * UNPREDICTABLE by a change of FR, so don't
1418				 * even bother saving it.
1419				 */
1420				if (change & ST0_FR)
1421					kvm_drop_fpu(vcpu);
1422
1423				/*
1424				 * If MSA state is already live, it is undefined
1425				 * how it interacts with FR=0 FPU state, and we
1426				 * don't want to hit reserved instruction
1427				 * exceptions trying to save the MSA state later
1428				 * when CU=1 && FR=1, so play it safe and save
1429				 * it first.
1430				 */
1431				if (change & ST0_CU1 && !(val & ST0_FR) &&
1432				    vcpu->arch.aux_inuse & KVM_MIPS_AUX_MSA)
1433					kvm_lose_fpu(vcpu);
1434
1435				/*
1436				 * Propagate CU1 (FPU enable) changes
1437				 * immediately if the FPU context is already
1438				 * loaded. When disabling we leave the context
1439				 * loaded so it can be quickly enabled again in
1440				 * the near future.
1441				 */
1442				if (change & ST0_CU1 &&
1443				    vcpu->arch.aux_inuse & KVM_MIPS_AUX_FPU)
1444					change_c0_status(ST0_CU1, val);
1445
1446				preempt_enable();
1447
1448				kvm_write_c0_guest_status(cop0, val);
1449
1450#ifdef CONFIG_KVM_MIPS_DYN_TRANS
1451				/*
1452				 * If FPU present, we need CU1/FR bits to take
1453				 * effect fairly soon.
1454				 */
1455				if (!kvm_mips_guest_has_fpu(&vcpu->arch))
1456					kvm_mips_trans_mtc0(inst, opc, vcpu);
1457#endif
1458			} else if ((rd == MIPS_CP0_CONFIG) && (sel == 5)) {
1459				unsigned int old_val, val, change, wrmask;
1460
1461				old_val = kvm_read_c0_guest_config5(cop0);
1462				val = vcpu->arch.gprs[rt];
1463
1464				/* Only a few bits are writable in Config5 */
1465				wrmask = kvm_mips_config5_wrmask(vcpu);
1466				change = (val ^ old_val) & wrmask;
1467				val = old_val ^ change;
1468
1469
1470				/* Handle changes in FPU/MSA modes */
1471				preempt_disable();
1472
1473				/*
1474				 * Propagate FRE changes immediately if the FPU
1475				 * context is already loaded.
1476				 */
1477				if (change & MIPS_CONF5_FRE &&
1478				    vcpu->arch.aux_inuse & KVM_MIPS_AUX_FPU)
1479					change_c0_config5(MIPS_CONF5_FRE, val);
1480
1481				/*
1482				 * Propagate MSAEn changes immediately if the
1483				 * MSA context is already loaded. When disabling
1484				 * we leave the context loaded so it can be
1485				 * quickly enabled again in the near future.
1486				 */
1487				if (change & MIPS_CONF5_MSAEN &&
1488				    vcpu->arch.aux_inuse & KVM_MIPS_AUX_MSA)
1489					change_c0_config5(MIPS_CONF5_MSAEN,
1490							  val);
1491
1492				preempt_enable();
1493
1494				kvm_write_c0_guest_config5(cop0, val);
1495			} else if ((rd == MIPS_CP0_CAUSE) && (sel == 0)) {
1496				u32 old_cause, new_cause;
1497
1498				old_cause = kvm_read_c0_guest_cause(cop0);
1499				new_cause = vcpu->arch.gprs[rt];
1500				/* Update R/W bits */
1501				kvm_change_c0_guest_cause(cop0, 0x08800300,
1502							  new_cause);
1503				/* DC bit enabling/disabling timer? */
1504				if ((old_cause ^ new_cause) & CAUSEF_DC) {
1505					if (new_cause & CAUSEF_DC)
1506						kvm_mips_count_disable_cause(vcpu);
1507					else
1508						kvm_mips_count_enable_cause(vcpu);
1509				}
1510			} else if ((rd == MIPS_CP0_HWRENA) && (sel == 0)) {
1511				u32 mask = MIPS_HWRENA_CPUNUM |
1512					   MIPS_HWRENA_SYNCISTEP |
1513					   MIPS_HWRENA_CC |
1514					   MIPS_HWRENA_CCRES;
1515
1516				if (kvm_read_c0_guest_config3(cop0) &
1517				    MIPS_CONF3_ULRI)
1518					mask |= MIPS_HWRENA_ULR;
1519				cop0->reg[rd][sel] = vcpu->arch.gprs[rt] & mask;
1520			} else {
1521				cop0->reg[rd][sel] = vcpu->arch.gprs[rt];
1522#ifdef CONFIG_KVM_MIPS_DYN_TRANS
1523				kvm_mips_trans_mtc0(inst, opc, vcpu);
1524#endif
1525			}
1526			break;
1527
1528		case dmtc_op:
1529			kvm_err("!!!!!!![%#lx]dmtc_op: rt: %d, rd: %d, sel: %d!!!!!!\n",
1530				vcpu->arch.pc, rt, rd, sel);
1531			trace_kvm_hwr(vcpu, KVM_TRACE_DMTC0,
1532				      KVM_TRACE_COP0(rd, sel),
1533				      vcpu->arch.gprs[rt]);
1534			er = EMULATE_FAIL;
1535			break;
1536
1537		case mfmc0_op:
1538#ifdef KVM_MIPS_DEBUG_COP0_COUNTERS
1539			cop0->stat[MIPS_CP0_STATUS][0]++;
1540#endif
1541			if (rt != 0)
1542				vcpu->arch.gprs[rt] =
1543				    kvm_read_c0_guest_status(cop0);
1544			/* EI */
1545			if (inst.mfmc0_format.sc) {
1546				kvm_debug("[%#lx] mfmc0_op: EI\n",
1547					  vcpu->arch.pc);
1548				kvm_set_c0_guest_status(cop0, ST0_IE);
1549			} else {
1550				kvm_debug("[%#lx] mfmc0_op: DI\n",
1551					  vcpu->arch.pc);
1552				kvm_clear_c0_guest_status(cop0, ST0_IE);
1553			}
1554
1555			break;
1556
1557		case wrpgpr_op:
1558			{
1559				u32 css = cop0->reg[MIPS_CP0_STATUS][2] & 0xf;
1560				u32 pss =
1561				    (cop0->reg[MIPS_CP0_STATUS][2] >> 6) & 0xf;
1562				/*
1563				 * We don't support any shadow register sets, so
1564				 * SRSCtl[PSS] == SRSCtl[CSS] = 0
1565				 */
1566				if (css || pss) {
1567					er = EMULATE_FAIL;
1568					break;
1569				}
1570				kvm_debug("WRPGPR[%d][%d] = %#lx\n", pss, rd,
1571					  vcpu->arch.gprs[rt]);
1572				vcpu->arch.gprs[rd] = vcpu->arch.gprs[rt];
1573			}
1574			break;
1575		default:
1576			kvm_err("[%#lx]MachEmulateCP0: unsupported COP0, copz: 0x%x\n",
1577				vcpu->arch.pc, inst.c0r_format.rs);
1578			er = EMULATE_FAIL;
1579			break;
1580		}
1581	}
1582
1583done:
1584	/* Rollback PC only if emulation was unsuccessful */
1585	if (er == EMULATE_FAIL)
1586		vcpu->arch.pc = curr_pc;
1587
1588dont_update_pc:
1589	/*
1590	 * This is for special instructions whose emulation
1591	 * updates the PC, so do not overwrite the PC under
1592	 * any circumstances
1593	 */
1594
1595	return er;
1596}
1597
1598enum emulation_result kvm_mips_emulate_store(union mips_instruction inst,
1599					     u32 cause,
1600					     struct kvm_run *run,
1601					     struct kvm_vcpu *vcpu)
1602{
1603	enum emulation_result er;
1604	u32 rt;
1605	void *data = run->mmio.data;
1606	unsigned long curr_pc;
1607
1608	/*
1609	 * Update PC and hold onto current PC in case there is
1610	 * an error and we want to rollback the PC
1611	 */
1612	curr_pc = vcpu->arch.pc;
1613	er = update_pc(vcpu, cause);
1614	if (er == EMULATE_FAIL)
1615		return er;
1616
1617	rt = inst.i_format.rt;
1618
1619	run->mmio.phys_addr = kvm_mips_callbacks->gva_to_gpa(
1620						vcpu->arch.host_cp0_badvaddr);
1621	if (run->mmio.phys_addr == KVM_INVALID_ADDR)
1622		goto out_fail;
1623
1624	switch (inst.i_format.opcode) {
1625#if defined(CONFIG_64BIT) && defined(CONFIG_KVM_MIPS_VZ)
1626	case sd_op:
1627		run->mmio.len = 8;
1628		*(u64 *)data = vcpu->arch.gprs[rt];
1629
1630		kvm_debug("[%#lx] OP_SD: eaddr: %#lx, gpr: %#lx, data: %#llx\n",
1631			  vcpu->arch.pc, vcpu->arch.host_cp0_badvaddr,
1632			  vcpu->arch.gprs[rt], *(u64 *)data);
1633		break;
1634#endif
1635
1636	case sw_op:
1637		run->mmio.len = 4;
1638		*(u32 *)data = vcpu->arch.gprs[rt];
1639
1640		kvm_debug("[%#lx] OP_SW: eaddr: %#lx, gpr: %#lx, data: %#x\n",
1641			  vcpu->arch.pc, vcpu->arch.host_cp0_badvaddr,
1642			  vcpu->arch.gprs[rt], *(u32 *)data);
1643		break;
1644
1645	case sh_op:
1646		run->mmio.len = 2;
1647		*(u16 *)data = vcpu->arch.gprs[rt];
1648
1649		kvm_debug("[%#lx] OP_SH: eaddr: %#lx, gpr: %#lx, data: %#x\n",
1650			  vcpu->arch.pc, vcpu->arch.host_cp0_badvaddr,
1651			  vcpu->arch.gprs[rt], *(u16 *)data);
1652		break;
1653
1654	case sb_op:
1655		run->mmio.len = 1;
1656		*(u8 *)data = vcpu->arch.gprs[rt];
1657
1658		kvm_debug("[%#lx] OP_SB: eaddr: %#lx, gpr: %#lx, data: %#x\n",
1659			  vcpu->arch.pc, vcpu->arch.host_cp0_badvaddr,
1660			  vcpu->arch.gprs[rt], *(u8 *)data);
1661		break;
1662
1663	default:
1664		kvm_err("Store not yet supported (inst=0x%08x)\n",
1665			inst.word);
1666		goto out_fail;
1667	}
1668
1669	run->mmio.is_write = 1;
1670	vcpu->mmio_needed = 1;
1671	vcpu->mmio_is_write = 1;
1672	return EMULATE_DO_MMIO;
1673
1674out_fail:
1675	/* Rollback PC if emulation was unsuccessful */
1676	vcpu->arch.pc = curr_pc;
1677	return EMULATE_FAIL;
1678}
1679
1680enum emulation_result kvm_mips_emulate_load(union mips_instruction inst,
1681					    u32 cause, struct kvm_run *run,
1682					    struct kvm_vcpu *vcpu)
1683{
1684	enum emulation_result er;
1685	unsigned long curr_pc;
1686	u32 op, rt;
1687
1688	rt = inst.i_format.rt;
1689	op = inst.i_format.opcode;
1690
1691	/*
1692	 * Find the resume PC now while we have safe and easy access to the
1693	 * prior branch instruction, and save it for
1694	 * kvm_mips_complete_mmio_load() to restore later.
1695	 */
1696	curr_pc = vcpu->arch.pc;
1697	er = update_pc(vcpu, cause);
1698	if (er == EMULATE_FAIL)
1699		return er;
1700	vcpu->arch.io_pc = vcpu->arch.pc;
1701	vcpu->arch.pc = curr_pc;
1702
1703	vcpu->arch.io_gpr = rt;
1704
1705	run->mmio.phys_addr = kvm_mips_callbacks->gva_to_gpa(
1706						vcpu->arch.host_cp0_badvaddr);
1707	if (run->mmio.phys_addr == KVM_INVALID_ADDR)
1708		return EMULATE_FAIL;
1709
1710	vcpu->mmio_needed = 2;	/* signed */
1711	switch (op) {
1712#if defined(CONFIG_64BIT) && defined(CONFIG_KVM_MIPS_VZ)
1713	case ld_op:
1714		run->mmio.len = 8;
1715		break;
1716
1717	case lwu_op:
1718		vcpu->mmio_needed = 1;	/* unsigned */
1719		/* fall through */
1720#endif
1721	case lw_op:
1722		run->mmio.len = 4;
1723		break;
1724
1725	case lhu_op:
1726		vcpu->mmio_needed = 1;	/* unsigned */
1727		/* fall through */
1728	case lh_op:
1729		run->mmio.len = 2;
1730		break;
1731
1732	case lbu_op:
1733		vcpu->mmio_needed = 1;	/* unsigned */
1734		/* fall through */
1735	case lb_op:
1736		run->mmio.len = 1;
1737		break;
1738
1739	default:
1740		kvm_err("Load not yet supported (inst=0x%08x)\n",
1741			inst.word);
1742		vcpu->mmio_needed = 0;
1743		return EMULATE_FAIL;
1744	}
1745
1746	run->mmio.is_write = 0;
1747	vcpu->mmio_is_write = 0;
1748	return EMULATE_DO_MMIO;
1749}
1750
1751#ifndef CONFIG_KVM_MIPS_VZ
1752static enum emulation_result kvm_mips_guest_cache_op(int (*fn)(unsigned long),
1753						     unsigned long curr_pc,
1754						     unsigned long addr,
1755						     struct kvm_run *run,
1756						     struct kvm_vcpu *vcpu,
1757						     u32 cause)
1758{
1759	int err;
1760
1761	for (;;) {
1762		/* Carefully attempt the cache operation */
1763		kvm_trap_emul_gva_lockless_begin(vcpu);
1764		err = fn(addr);
1765		kvm_trap_emul_gva_lockless_end(vcpu);
1766
1767		if (likely(!err))
1768			return EMULATE_DONE;
1769
1770		/*
1771		 * Try to handle the fault and retry, maybe we just raced with a
1772		 * GVA invalidation.
1773		 */
1774		switch (kvm_trap_emul_gva_fault(vcpu, addr, false)) {
1775		case KVM_MIPS_GVA:
1776		case KVM_MIPS_GPA:
1777			/* bad virtual or physical address */
1778			return EMULATE_FAIL;
1779		case KVM_MIPS_TLB:
1780			/* no matching guest TLB */
1781			vcpu->arch.host_cp0_badvaddr = addr;
1782			vcpu->arch.pc = curr_pc;
1783			kvm_mips_emulate_tlbmiss_ld(cause, NULL, run, vcpu);
1784			return EMULATE_EXCEPT;
1785		case KVM_MIPS_TLBINV:
1786			/* invalid matching guest TLB */
1787			vcpu->arch.host_cp0_badvaddr = addr;
1788			vcpu->arch.pc = curr_pc;
1789			kvm_mips_emulate_tlbinv_ld(cause, NULL, run, vcpu);
1790			return EMULATE_EXCEPT;
1791		default:
1792			break;
1793		};
1794	}
1795}
1796
1797enum emulation_result kvm_mips_emulate_cache(union mips_instruction inst,
1798					     u32 *opc, u32 cause,
1799					     struct kvm_run *run,
1800					     struct kvm_vcpu *vcpu)
1801{
1802	enum emulation_result er = EMULATE_DONE;
1803	u32 cache, op_inst, op, base;
1804	s16 offset;
1805	struct kvm_vcpu_arch *arch = &vcpu->arch;
1806	unsigned long va;
1807	unsigned long curr_pc;
1808
1809	/*
1810	 * Update PC and hold onto current PC in case there is
1811	 * an error and we want to rollback the PC
1812	 */
1813	curr_pc = vcpu->arch.pc;
1814	er = update_pc(vcpu, cause);
1815	if (er == EMULATE_FAIL)
1816		return er;
1817
1818	base = inst.i_format.rs;
1819	op_inst = inst.i_format.rt;
1820	if (cpu_has_mips_r6)
1821		offset = inst.spec3_format.simmediate;
1822	else
1823		offset = inst.i_format.simmediate;
1824	cache = op_inst & CacheOp_Cache;
1825	op = op_inst & CacheOp_Op;
1826
1827	va = arch->gprs[base] + offset;
1828
1829	kvm_debug("CACHE (cache: %#x, op: %#x, base[%d]: %#lx, offset: %#x\n",
1830		  cache, op, base, arch->gprs[base], offset);
1831
1832	/*
1833	 * Treat INDEX_INV as a nop, basically issued by Linux on startup to
1834	 * invalidate the caches entirely by stepping through all the
1835	 * ways/indexes
1836	 */
1837	if (op == Index_Writeback_Inv) {
1838		kvm_debug("@ %#lx/%#lx CACHE (cache: %#x, op: %#x, base[%d]: %#lx, offset: %#x\n",
1839			  vcpu->arch.pc, vcpu->arch.gprs[31], cache, op, base,
1840			  arch->gprs[base], offset);
1841
1842		if (cache == Cache_D) {
1843#ifdef CONFIG_CPU_R4K_CACHE_TLB
1844			r4k_blast_dcache();
1845#else
1846			switch (boot_cpu_type()) {
1847			case CPU_CAVIUM_OCTEON3:
1848				/* locally flush icache */
1849				local_flush_icache_range(0, 0);
1850				break;
1851			default:
1852				__flush_cache_all();
1853				break;
1854			}
1855#endif
1856		} else if (cache == Cache_I) {
1857#ifdef CONFIG_CPU_R4K_CACHE_TLB
1858			r4k_blast_icache();
1859#else
1860			switch (boot_cpu_type()) {
1861			case CPU_CAVIUM_OCTEON3:
1862				/* locally flush icache */
1863				local_flush_icache_range(0, 0);
1864				break;
1865			default:
1866				flush_icache_all();
1867				break;
1868			}
1869#endif
1870		} else {
1871			kvm_err("%s: unsupported CACHE INDEX operation\n",
1872				__func__);
1873			return EMULATE_FAIL;
1874		}
1875
1876#ifdef CONFIG_KVM_MIPS_DYN_TRANS
1877		kvm_mips_trans_cache_index(inst, opc, vcpu);
1878#endif
1879		goto done;
1880	}
1881
1882	/* XXXKYMA: Only a subset of cache ops are supported, used by Linux */
1883	if (op_inst == Hit_Writeback_Inv_D || op_inst == Hit_Invalidate_D) {
1884		/*
1885		 * Perform the dcache part of icache synchronisation on the
1886		 * guest's behalf.
1887		 */
1888		er = kvm_mips_guest_cache_op(protected_writeback_dcache_line,
1889					     curr_pc, va, run, vcpu, cause);
1890		if (er != EMULATE_DONE)
1891			goto done;
1892#ifdef CONFIG_KVM_MIPS_DYN_TRANS
1893		/*
1894		 * Replace the CACHE instruction, with a SYNCI, not the same,
1895		 * but avoids a trap
1896		 */
1897		kvm_mips_trans_cache_va(inst, opc, vcpu);
1898#endif
1899	} else if (op_inst == Hit_Invalidate_I) {
1900		/* Perform the icache synchronisation on the guest's behalf */
1901		er = kvm_mips_guest_cache_op(protected_writeback_dcache_line,
1902					     curr_pc, va, run, vcpu, cause);
1903		if (er != EMULATE_DONE)
1904			goto done;
1905		er = kvm_mips_guest_cache_op(protected_flush_icache_line,
1906					     curr_pc, va, run, vcpu, cause);
1907		if (er != EMULATE_DONE)
1908			goto done;
1909
1910#ifdef CONFIG_KVM_MIPS_DYN_TRANS
1911		/* Replace the CACHE instruction, with a SYNCI */
1912		kvm_mips_trans_cache_va(inst, opc, vcpu);
1913#endif
1914	} else {
1915		kvm_err("NO-OP CACHE (cache: %#x, op: %#x, base[%d]: %#lx, offset: %#x\n",
1916			cache, op, base, arch->gprs[base], offset);
1917		er = EMULATE_FAIL;
1918	}
1919
1920done:
1921	/* Rollback PC only if emulation was unsuccessful */
1922	if (er == EMULATE_FAIL)
1923		vcpu->arch.pc = curr_pc;
1924	/* Guest exception needs guest to resume */
1925	if (er == EMULATE_EXCEPT)
1926		er = EMULATE_DONE;
1927
1928	return er;
1929}
1930
1931enum emulation_result kvm_mips_emulate_inst(u32 cause, u32 *opc,
1932					    struct kvm_run *run,
1933					    struct kvm_vcpu *vcpu)
1934{
1935	union mips_instruction inst;
1936	enum emulation_result er = EMULATE_DONE;
1937	int err;
1938
1939	/* Fetch the instruction. */
1940	if (cause & CAUSEF_BD)
1941		opc += 1;
1942	err = kvm_get_badinstr(opc, vcpu, &inst.word);
1943	if (err)
1944		return EMULATE_FAIL;
1945
1946	switch (inst.r_format.opcode) {
1947	case cop0_op:
1948		er = kvm_mips_emulate_CP0(inst, opc, cause, run, vcpu);
1949		break;
1950
1951#ifndef CONFIG_CPU_MIPSR6
1952	case cache_op:
1953		++vcpu->stat.cache_exits;
1954		trace_kvm_exit(vcpu, KVM_TRACE_EXIT_CACHE);
1955		er = kvm_mips_emulate_cache(inst, opc, cause, run, vcpu);
1956		break;
1957#else
1958	case spec3_op:
1959		switch (inst.spec3_format.func) {
1960		case cache6_op:
1961			++vcpu->stat.cache_exits;
1962			trace_kvm_exit(vcpu, KVM_TRACE_EXIT_CACHE);
1963			er = kvm_mips_emulate_cache(inst, opc, cause, run,
1964						    vcpu);
1965			break;
1966		default:
1967			goto unknown;
1968		};
1969		break;
1970unknown:
1971#endif
1972
1973	default:
1974		kvm_err("Instruction emulation not supported (%p/%#x)\n", opc,
1975			inst.word);
1976		kvm_arch_vcpu_dump_regs(vcpu);
1977		er = EMULATE_FAIL;
1978		break;
1979	}
1980
1981	return er;
1982}
1983#endif /* CONFIG_KVM_MIPS_VZ */
1984
1985/**
1986 * kvm_mips_guest_exception_base() - Find guest exception vector base address.
1987 *
1988 * Returns:	The base address of the current guest exception vector, taking
1989 *		both Guest.CP0_Status.BEV and Guest.CP0_EBase into account.
1990 */
1991long kvm_mips_guest_exception_base(struct kvm_vcpu *vcpu)
1992{
1993	struct mips_coproc *cop0 = vcpu->arch.cop0;
1994
1995	if (kvm_read_c0_guest_status(cop0) & ST0_BEV)
1996		return KVM_GUEST_CKSEG1ADDR(0x1fc00200);
1997	else
1998		return kvm_read_c0_guest_ebase(cop0) & MIPS_EBASE_BASE;
1999}
2000
2001enum emulation_result kvm_mips_emulate_syscall(u32 cause,
2002					       u32 *opc,
2003					       struct kvm_run *run,
2004					       struct kvm_vcpu *vcpu)
2005{
2006	struct mips_coproc *cop0 = vcpu->arch.cop0;
2007	struct kvm_vcpu_arch *arch = &vcpu->arch;
2008	enum emulation_result er = EMULATE_DONE;
2009
2010	if ((kvm_read_c0_guest_status(cop0) & ST0_EXL) == 0) {
2011		/* save old pc */
2012		kvm_write_c0_guest_epc(cop0, arch->pc);
2013		kvm_set_c0_guest_status(cop0, ST0_EXL);
2014
2015		if (cause & CAUSEF_BD)
2016			kvm_set_c0_guest_cause(cop0, CAUSEF_BD);
2017		else
2018			kvm_clear_c0_guest_cause(cop0, CAUSEF_BD);
2019
2020		kvm_debug("Delivering SYSCALL @ pc %#lx\n", arch->pc);
2021
2022		kvm_change_c0_guest_cause(cop0, (0xff),
2023					  (EXCCODE_SYS << CAUSEB_EXCCODE));
2024
2025		/* Set PC to the exception entry point */
2026		arch->pc = kvm_mips_guest_exception_base(vcpu) + 0x180;
2027
2028	} else {
2029		kvm_err("Trying to deliver SYSCALL when EXL is already set\n");
2030		er = EMULATE_FAIL;
2031	}
2032
2033	return er;
2034}
2035
2036enum emulation_result kvm_mips_emulate_tlbmiss_ld(u32 cause,
2037						  u32 *opc,
2038						  struct kvm_run *run,
2039						  struct kvm_vcpu *vcpu)
2040{
2041	struct mips_coproc *cop0 = vcpu->arch.cop0;
2042	struct kvm_vcpu_arch *arch = &vcpu->arch;
2043	unsigned long entryhi = (vcpu->arch.  host_cp0_badvaddr & VPN2_MASK) |
2044			(kvm_read_c0_guest_entryhi(cop0) & KVM_ENTRYHI_ASID);
2045
2046	if ((kvm_read_c0_guest_status(cop0) & ST0_EXL) == 0) {
2047		/* save old pc */
2048		kvm_write_c0_guest_epc(cop0, arch->pc);
2049		kvm_set_c0_guest_status(cop0, ST0_EXL);
2050
2051		if (cause & CAUSEF_BD)
2052			kvm_set_c0_guest_cause(cop0, CAUSEF_BD);
2053		else
2054			kvm_clear_c0_guest_cause(cop0, CAUSEF_BD);
2055
2056		kvm_debug("[EXL == 0] delivering TLB MISS @ pc %#lx\n",
2057			  arch->pc);
2058
2059		/* set pc to the exception entry point */
2060		arch->pc = kvm_mips_guest_exception_base(vcpu) + 0x0;
2061
2062	} else {
2063		kvm_debug("[EXL == 1] delivering TLB MISS @ pc %#lx\n",
2064			  arch->pc);
2065
2066		arch->pc = kvm_mips_guest_exception_base(vcpu) + 0x180;
2067	}
2068
2069	kvm_change_c0_guest_cause(cop0, (0xff),
2070				  (EXCCODE_TLBL << CAUSEB_EXCCODE));
2071
2072	/* setup badvaddr, context and entryhi registers for the guest */
2073	kvm_write_c0_guest_badvaddr(cop0, vcpu->arch.host_cp0_badvaddr);
2074	/* XXXKYMA: is the context register used by linux??? */
2075	kvm_write_c0_guest_entryhi(cop0, entryhi);
2076
2077	return EMULATE_DONE;
2078}
2079
2080enum emulation_result kvm_mips_emulate_tlbinv_ld(u32 cause,
2081						 u32 *opc,
2082						 struct kvm_run *run,
2083						 struct kvm_vcpu *vcpu)
2084{
2085	struct mips_coproc *cop0 = vcpu->arch.cop0;
2086	struct kvm_vcpu_arch *arch = &vcpu->arch;
2087	unsigned long entryhi =
2088		(vcpu->arch.host_cp0_badvaddr & VPN2_MASK) |
2089		(kvm_read_c0_guest_entryhi(cop0) & KVM_ENTRYHI_ASID);
2090
2091	if ((kvm_read_c0_guest_status(cop0) & ST0_EXL) == 0) {
2092		/* save old pc */
2093		kvm_write_c0_guest_epc(cop0, arch->pc);
2094		kvm_set_c0_guest_status(cop0, ST0_EXL);
2095
2096		if (cause & CAUSEF_BD)
2097			kvm_set_c0_guest_cause(cop0, CAUSEF_BD);
2098		else
2099			kvm_clear_c0_guest_cause(cop0, CAUSEF_BD);
2100
2101		kvm_debug("[EXL == 0] delivering TLB INV @ pc %#lx\n",
2102			  arch->pc);
2103	} else {
2104		kvm_debug("[EXL == 1] delivering TLB MISS @ pc %#lx\n",
2105			  arch->pc);
2106	}
2107
2108	/* set pc to the exception entry point */
2109	arch->pc = kvm_mips_guest_exception_base(vcpu) + 0x180;
2110
2111	kvm_change_c0_guest_cause(cop0, (0xff),
2112				  (EXCCODE_TLBL << CAUSEB_EXCCODE));
2113
2114	/* setup badvaddr, context and entryhi registers for the guest */
2115	kvm_write_c0_guest_badvaddr(cop0, vcpu->arch.host_cp0_badvaddr);
2116	/* XXXKYMA: is the context register used by linux??? */
2117	kvm_write_c0_guest_entryhi(cop0, entryhi);
2118
2119	return EMULATE_DONE;
2120}
2121
2122enum emulation_result kvm_mips_emulate_tlbmiss_st(u32 cause,
2123						  u32 *opc,
2124						  struct kvm_run *run,
2125						  struct kvm_vcpu *vcpu)
2126{
2127	struct mips_coproc *cop0 = vcpu->arch.cop0;
2128	struct kvm_vcpu_arch *arch = &vcpu->arch;
2129	unsigned long entryhi = (vcpu->arch.host_cp0_badvaddr & VPN2_MASK) |
2130			(kvm_read_c0_guest_entryhi(cop0) & KVM_ENTRYHI_ASID);
2131
2132	if ((kvm_read_c0_guest_status(cop0) & ST0_EXL) == 0) {
2133		/* save old pc */
2134		kvm_write_c0_guest_epc(cop0, arch->pc);
2135		kvm_set_c0_guest_status(cop0, ST0_EXL);
2136
2137		if (cause & CAUSEF_BD)
2138			kvm_set_c0_guest_cause(cop0, CAUSEF_BD);
2139		else
2140			kvm_clear_c0_guest_cause(cop0, CAUSEF_BD);
2141
2142		kvm_debug("[EXL == 0] Delivering TLB MISS @ pc %#lx\n",
2143			  arch->pc);
2144
2145		/* Set PC to the exception entry point */
2146		arch->pc = kvm_mips_guest_exception_base(vcpu) + 0x0;
2147	} else {
2148		kvm_debug("[EXL == 1] Delivering TLB MISS @ pc %#lx\n",
2149			  arch->pc);
2150		arch->pc = kvm_mips_guest_exception_base(vcpu) + 0x180;
2151	}
2152
2153	kvm_change_c0_guest_cause(cop0, (0xff),
2154				  (EXCCODE_TLBS << CAUSEB_EXCCODE));
2155
2156	/* setup badvaddr, context and entryhi registers for the guest */
2157	kvm_write_c0_guest_badvaddr(cop0, vcpu->arch.host_cp0_badvaddr);
2158	/* XXXKYMA: is the context register used by linux??? */
2159	kvm_write_c0_guest_entryhi(cop0, entryhi);
2160
2161	return EMULATE_DONE;
2162}
2163
2164enum emulation_result kvm_mips_emulate_tlbinv_st(u32 cause,
2165						 u32 *opc,
2166						 struct kvm_run *run,
2167						 struct kvm_vcpu *vcpu)
2168{
2169	struct mips_coproc *cop0 = vcpu->arch.cop0;
2170	struct kvm_vcpu_arch *arch = &vcpu->arch;
2171	unsigned long entryhi = (vcpu->arch.host_cp0_badvaddr & VPN2_MASK) |
2172		(kvm_read_c0_guest_entryhi(cop0) & KVM_ENTRYHI_ASID);
2173
2174	if ((kvm_read_c0_guest_status(cop0) & ST0_EXL) == 0) {
2175		/* save old pc */
2176		kvm_write_c0_guest_epc(cop0, arch->pc);
2177		kvm_set_c0_guest_status(cop0, ST0_EXL);
2178
2179		if (cause & CAUSEF_BD)
2180			kvm_set_c0_guest_cause(cop0, CAUSEF_BD);
2181		else
2182			kvm_clear_c0_guest_cause(cop0, CAUSEF_BD);
2183
2184		kvm_debug("[EXL == 0] Delivering TLB MISS @ pc %#lx\n",
2185			  arch->pc);
2186	} else {
2187		kvm_debug("[EXL == 1] Delivering TLB MISS @ pc %#lx\n",
2188			  arch->pc);
2189	}
2190
2191	/* Set PC to the exception entry point */
2192	arch->pc = kvm_mips_guest_exception_base(vcpu) + 0x180;
2193
2194	kvm_change_c0_guest_cause(cop0, (0xff),
2195				  (EXCCODE_TLBS << CAUSEB_EXCCODE));
2196
2197	/* setup badvaddr, context and entryhi registers for the guest */
2198	kvm_write_c0_guest_badvaddr(cop0, vcpu->arch.host_cp0_badvaddr);
2199	/* XXXKYMA: is the context register used by linux??? */
2200	kvm_write_c0_guest_entryhi(cop0, entryhi);
2201
2202	return EMULATE_DONE;
2203}
2204
2205enum emulation_result kvm_mips_emulate_tlbmod(u32 cause,
2206					      u32 *opc,
2207					      struct kvm_run *run,
2208					      struct kvm_vcpu *vcpu)
2209{
2210	struct mips_coproc *cop0 = vcpu->arch.cop0;
2211	unsigned long entryhi = (vcpu->arch.host_cp0_badvaddr & VPN2_MASK) |
2212			(kvm_read_c0_guest_entryhi(cop0) & KVM_ENTRYHI_ASID);
2213	struct kvm_vcpu_arch *arch = &vcpu->arch;
2214
2215	if ((kvm_read_c0_guest_status(cop0) & ST0_EXL) == 0) {
2216		/* save old pc */
2217		kvm_write_c0_guest_epc(cop0, arch->pc);
2218		kvm_set_c0_guest_status(cop0, ST0_EXL);
2219
2220		if (cause & CAUSEF_BD)
2221			kvm_set_c0_guest_cause(cop0, CAUSEF_BD);
2222		else
2223			kvm_clear_c0_guest_cause(cop0, CAUSEF_BD);
2224
2225		kvm_debug("[EXL == 0] Delivering TLB MOD @ pc %#lx\n",
2226			  arch->pc);
2227	} else {
2228		kvm_debug("[EXL == 1] Delivering TLB MOD @ pc %#lx\n",
2229			  arch->pc);
2230	}
2231
2232	arch->pc = kvm_mips_guest_exception_base(vcpu) + 0x180;
2233
2234	kvm_change_c0_guest_cause(cop0, (0xff),
2235				  (EXCCODE_MOD << CAUSEB_EXCCODE));
2236
2237	/* setup badvaddr, context and entryhi registers for the guest */
2238	kvm_write_c0_guest_badvaddr(cop0, vcpu->arch.host_cp0_badvaddr);
2239	/* XXXKYMA: is the context register used by linux??? */
2240	kvm_write_c0_guest_entryhi(cop0, entryhi);
2241
2242	return EMULATE_DONE;
2243}
2244
2245enum emulation_result kvm_mips_emulate_fpu_exc(u32 cause,
2246					       u32 *opc,
2247					       struct kvm_run *run,
2248					       struct kvm_vcpu *vcpu)
2249{
2250	struct mips_coproc *cop0 = vcpu->arch.cop0;
2251	struct kvm_vcpu_arch *arch = &vcpu->arch;
2252
2253	if ((kvm_read_c0_guest_status(cop0) & ST0_EXL) == 0) {
2254		/* save old pc */
2255		kvm_write_c0_guest_epc(cop0, arch->pc);
2256		kvm_set_c0_guest_status(cop0, ST0_EXL);
2257
2258		if (cause & CAUSEF_BD)
2259			kvm_set_c0_guest_cause(cop0, CAUSEF_BD);
2260		else
2261			kvm_clear_c0_guest_cause(cop0, CAUSEF_BD);
2262
2263	}
2264
2265	arch->pc = kvm_mips_guest_exception_base(vcpu) + 0x180;
2266
2267	kvm_change_c0_guest_cause(cop0, (0xff),
2268				  (EXCCODE_CPU << CAUSEB_EXCCODE));
2269	kvm_change_c0_guest_cause(cop0, (CAUSEF_CE), (0x1 << CAUSEB_CE));
2270
2271	return EMULATE_DONE;
2272}
2273
2274enum emulation_result kvm_mips_emulate_ri_exc(u32 cause,
2275					      u32 *opc,
2276					      struct kvm_run *run,
2277					      struct kvm_vcpu *vcpu)
2278{
2279	struct mips_coproc *cop0 = vcpu->arch.cop0;
2280	struct kvm_vcpu_arch *arch = &vcpu->arch;
2281	enum emulation_result er = EMULATE_DONE;
2282
2283	if ((kvm_read_c0_guest_status(cop0) & ST0_EXL) == 0) {
2284		/* save old pc */
2285		kvm_write_c0_guest_epc(cop0, arch->pc);
2286		kvm_set_c0_guest_status(cop0, ST0_EXL);
2287
2288		if (cause & CAUSEF_BD)
2289			kvm_set_c0_guest_cause(cop0, CAUSEF_BD);
2290		else
2291			kvm_clear_c0_guest_cause(cop0, CAUSEF_BD);
2292
2293		kvm_debug("Delivering RI @ pc %#lx\n", arch->pc);
2294
2295		kvm_change_c0_guest_cause(cop0, (0xff),
2296					  (EXCCODE_RI << CAUSEB_EXCCODE));
2297
2298		/* Set PC to the exception entry point */
2299		arch->pc = kvm_mips_guest_exception_base(vcpu) + 0x180;
2300
2301	} else {
2302		kvm_err("Trying to deliver RI when EXL is already set\n");
2303		er = EMULATE_FAIL;
2304	}
2305
2306	return er;
2307}
2308
2309enum emulation_result kvm_mips_emulate_bp_exc(u32 cause,
2310					      u32 *opc,
2311					      struct kvm_run *run,
2312					      struct kvm_vcpu *vcpu)
2313{
2314	struct mips_coproc *cop0 = vcpu->arch.cop0;
2315	struct kvm_vcpu_arch *arch = &vcpu->arch;
2316	enum emulation_result er = EMULATE_DONE;
2317
2318	if ((kvm_read_c0_guest_status(cop0) & ST0_EXL) == 0) {
2319		/* save old pc */
2320		kvm_write_c0_guest_epc(cop0, arch->pc);
2321		kvm_set_c0_guest_status(cop0, ST0_EXL);
2322
2323		if (cause & CAUSEF_BD)
2324			kvm_set_c0_guest_cause(cop0, CAUSEF_BD);
2325		else
2326			kvm_clear_c0_guest_cause(cop0, CAUSEF_BD);
2327
2328		kvm_debug("Delivering BP @ pc %#lx\n", arch->pc);
2329
2330		kvm_change_c0_guest_cause(cop0, (0xff),
2331					  (EXCCODE_BP << CAUSEB_EXCCODE));
2332
2333		/* Set PC to the exception entry point */
2334		arch->pc = kvm_mips_guest_exception_base(vcpu) + 0x180;
2335
2336	} else {
2337		kvm_err("Trying to deliver BP when EXL is already set\n");
2338		er = EMULATE_FAIL;
2339	}
2340
2341	return er;
2342}
2343
2344enum emulation_result kvm_mips_emulate_trap_exc(u32 cause,
2345						u32 *opc,
2346						struct kvm_run *run,
2347						struct kvm_vcpu *vcpu)
2348{
2349	struct mips_coproc *cop0 = vcpu->arch.cop0;
2350	struct kvm_vcpu_arch *arch = &vcpu->arch;
2351	enum emulation_result er = EMULATE_DONE;
2352
2353	if ((kvm_read_c0_guest_status(cop0) & ST0_EXL) == 0) {
2354		/* save old pc */
2355		kvm_write_c0_guest_epc(cop0, arch->pc);
2356		kvm_set_c0_guest_status(cop0, ST0_EXL);
2357
2358		if (cause & CAUSEF_BD)
2359			kvm_set_c0_guest_cause(cop0, CAUSEF_BD);
2360		else
2361			kvm_clear_c0_guest_cause(cop0, CAUSEF_BD);
2362
2363		kvm_debug("Delivering TRAP @ pc %#lx\n", arch->pc);
2364
2365		kvm_change_c0_guest_cause(cop0, (0xff),
2366					  (EXCCODE_TR << CAUSEB_EXCCODE));
2367
2368		/* Set PC to the exception entry point */
2369		arch->pc = kvm_mips_guest_exception_base(vcpu) + 0x180;
2370
2371	} else {
2372		kvm_err("Trying to deliver TRAP when EXL is already set\n");
2373		er = EMULATE_FAIL;
2374	}
2375
2376	return er;
2377}
2378
2379enum emulation_result kvm_mips_emulate_msafpe_exc(u32 cause,
2380						  u32 *opc,
2381						  struct kvm_run *run,
2382						  struct kvm_vcpu *vcpu)
2383{
2384	struct mips_coproc *cop0 = vcpu->arch.cop0;
2385	struct kvm_vcpu_arch *arch = &vcpu->arch;
2386	enum emulation_result er = EMULATE_DONE;
2387
2388	if ((kvm_read_c0_guest_status(cop0) & ST0_EXL) == 0) {
2389		/* save old pc */
2390		kvm_write_c0_guest_epc(cop0, arch->pc);
2391		kvm_set_c0_guest_status(cop0, ST0_EXL);
2392
2393		if (cause & CAUSEF_BD)
2394			kvm_set_c0_guest_cause(cop0, CAUSEF_BD);
2395		else
2396			kvm_clear_c0_guest_cause(cop0, CAUSEF_BD);
2397
2398		kvm_debug("Delivering MSAFPE @ pc %#lx\n", arch->pc);
2399
2400		kvm_change_c0_guest_cause(cop0, (0xff),
2401					  (EXCCODE_MSAFPE << CAUSEB_EXCCODE));
2402
2403		/* Set PC to the exception entry point */
2404		arch->pc = kvm_mips_guest_exception_base(vcpu) + 0x180;
2405
2406	} else {
2407		kvm_err("Trying to deliver MSAFPE when EXL is already set\n");
2408		er = EMULATE_FAIL;
2409	}
2410
2411	return er;
2412}
2413
2414enum emulation_result kvm_mips_emulate_fpe_exc(u32 cause,
2415					       u32 *opc,
2416					       struct kvm_run *run,
2417					       struct kvm_vcpu *vcpu)
2418{
2419	struct mips_coproc *cop0 = vcpu->arch.cop0;
2420	struct kvm_vcpu_arch *arch = &vcpu->arch;
2421	enum emulation_result er = EMULATE_DONE;
2422
2423	if ((kvm_read_c0_guest_status(cop0) & ST0_EXL) == 0) {
2424		/* save old pc */
2425		kvm_write_c0_guest_epc(cop0, arch->pc);
2426		kvm_set_c0_guest_status(cop0, ST0_EXL);
2427
2428		if (cause & CAUSEF_BD)
2429			kvm_set_c0_guest_cause(cop0, CAUSEF_BD);
2430		else
2431			kvm_clear_c0_guest_cause(cop0, CAUSEF_BD);
2432
2433		kvm_debug("Delivering FPE @ pc %#lx\n", arch->pc);
2434
2435		kvm_change_c0_guest_cause(cop0, (0xff),
2436					  (EXCCODE_FPE << CAUSEB_EXCCODE));
2437
2438		/* Set PC to the exception entry point */
2439		arch->pc = kvm_mips_guest_exception_base(vcpu) + 0x180;
2440
2441	} else {
2442		kvm_err("Trying to deliver FPE when EXL is already set\n");
2443		er = EMULATE_FAIL;
2444	}
2445
2446	return er;
2447}
2448
2449enum emulation_result kvm_mips_emulate_msadis_exc(u32 cause,
2450						  u32 *opc,
2451						  struct kvm_run *run,
2452						  struct kvm_vcpu *vcpu)
2453{
2454	struct mips_coproc *cop0 = vcpu->arch.cop0;
2455	struct kvm_vcpu_arch *arch = &vcpu->arch;
2456	enum emulation_result er = EMULATE_DONE;
2457
2458	if ((kvm_read_c0_guest_status(cop0) & ST0_EXL) == 0) {
2459		/* save old pc */
2460		kvm_write_c0_guest_epc(cop0, arch->pc);
2461		kvm_set_c0_guest_status(cop0, ST0_EXL);
2462
2463		if (cause & CAUSEF_BD)
2464			kvm_set_c0_guest_cause(cop0, CAUSEF_BD);
2465		else
2466			kvm_clear_c0_guest_cause(cop0, CAUSEF_BD);
2467
2468		kvm_debug("Delivering MSADIS @ pc %#lx\n", arch->pc);
2469
2470		kvm_change_c0_guest_cause(cop0, (0xff),
2471					  (EXCCODE_MSADIS << CAUSEB_EXCCODE));
2472
2473		/* Set PC to the exception entry point */
2474		arch->pc = kvm_mips_guest_exception_base(vcpu) + 0x180;
2475
2476	} else {
2477		kvm_err("Trying to deliver MSADIS when EXL is already set\n");
2478		er = EMULATE_FAIL;
2479	}
2480
2481	return er;
2482}
2483
2484enum emulation_result kvm_mips_handle_ri(u32 cause, u32 *opc,
2485					 struct kvm_run *run,
2486					 struct kvm_vcpu *vcpu)
2487{
2488	struct mips_coproc *cop0 = vcpu->arch.cop0;
2489	struct kvm_vcpu_arch *arch = &vcpu->arch;
2490	enum emulation_result er = EMULATE_DONE;
2491	unsigned long curr_pc;
2492	union mips_instruction inst;
2493	int err;
2494
2495	/*
2496	 * Update PC and hold onto current PC in case there is
2497	 * an error and we want to rollback the PC
2498	 */
2499	curr_pc = vcpu->arch.pc;
2500	er = update_pc(vcpu, cause);
2501	if (er == EMULATE_FAIL)
2502		return er;
2503
2504	/* Fetch the instruction. */
2505	if (cause & CAUSEF_BD)
2506		opc += 1;
2507	err = kvm_get_badinstr(opc, vcpu, &inst.word);
2508	if (err) {
2509		kvm_err("%s: Cannot get inst @ %p (%d)\n", __func__, opc, err);
2510		return EMULATE_FAIL;
2511	}
2512
2513	if (inst.r_format.opcode == spec3_op &&
2514	    inst.r_format.func == rdhwr_op &&
2515	    inst.r_format.rs == 0 &&
2516	    (inst.r_format.re >> 3) == 0) {
2517		int usermode = !KVM_GUEST_KERNEL_MODE(vcpu);
2518		int rd = inst.r_format.rd;
2519		int rt = inst.r_format.rt;
2520		int sel = inst.r_format.re & 0x7;
2521
2522		/* If usermode, check RDHWR rd is allowed by guest HWREna */
2523		if (usermode && !(kvm_read_c0_guest_hwrena(cop0) & BIT(rd))) {
2524			kvm_debug("RDHWR %#x disallowed by HWREna @ %p\n",
2525				  rd, opc);
2526			goto emulate_ri;
2527		}
2528		switch (rd) {
2529		case MIPS_HWR_CPUNUM:		/* CPU number */
2530			arch->gprs[rt] = vcpu->vcpu_id;
2531			break;
2532		case MIPS_HWR_SYNCISTEP:	/* SYNCI length */
2533			arch->gprs[rt] = min(current_cpu_data.dcache.linesz,
2534					     current_cpu_data.icache.linesz);
2535			break;
2536		case MIPS_HWR_CC:		/* Read count register */
2537			arch->gprs[rt] = (s32)kvm_mips_read_count(vcpu);
2538			break;
2539		case MIPS_HWR_CCRES:		/* Count register resolution */
2540			switch (current_cpu_data.cputype) {
2541			case CPU_20KC:
2542			case CPU_25KF:
2543				arch->gprs[rt] = 1;
2544				break;
2545			default:
2546				arch->gprs[rt] = 2;
2547			}
2548			break;
2549		case MIPS_HWR_ULR:		/* Read UserLocal register */
2550			arch->gprs[rt] = kvm_read_c0_guest_userlocal(cop0);
2551			break;
2552
2553		default:
2554			kvm_debug("RDHWR %#x not supported @ %p\n", rd, opc);
2555			goto emulate_ri;
2556		}
2557
2558		trace_kvm_hwr(vcpu, KVM_TRACE_RDHWR, KVM_TRACE_HWR(rd, sel),
2559			      vcpu->arch.gprs[rt]);
2560	} else {
2561		kvm_debug("Emulate RI not supported @ %p: %#x\n",
2562			  opc, inst.word);
2563		goto emulate_ri;
2564	}
2565
2566	return EMULATE_DONE;
2567
2568emulate_ri:
2569	/*
2570	 * Rollback PC (if in branch delay slot then the PC already points to
2571	 * branch target), and pass the RI exception to the guest OS.
2572	 */
2573	vcpu->arch.pc = curr_pc;
2574	return kvm_mips_emulate_ri_exc(cause, opc, run, vcpu);
2575}
2576
2577enum emulation_result kvm_mips_complete_mmio_load(struct kvm_vcpu *vcpu,
2578						  struct kvm_run *run)
2579{
2580	unsigned long *gpr = &vcpu->arch.gprs[vcpu->arch.io_gpr];
2581	enum emulation_result er = EMULATE_DONE;
2582
2583	if (run->mmio.len > sizeof(*gpr)) {
2584		kvm_err("Bad MMIO length: %d", run->mmio.len);
2585		er = EMULATE_FAIL;
2586		goto done;
2587	}
2588
2589	/* Restore saved resume PC */
2590	vcpu->arch.pc = vcpu->arch.io_pc;
2591
2592	switch (run->mmio.len) {
2593	case 8:
2594		*gpr = *(s64 *)run->mmio.data;
2595		break;
2596
2597	case 4:
2598		if (vcpu->mmio_needed == 2)
2599			*gpr = *(s32 *)run->mmio.data;
2600		else
2601			*gpr = *(u32 *)run->mmio.data;
2602		break;
2603
2604	case 2:
2605		if (vcpu->mmio_needed == 2)
2606			*gpr = *(s16 *) run->mmio.data;
2607		else
2608			*gpr = *(u16 *)run->mmio.data;
2609
2610		break;
2611	case 1:
2612		if (vcpu->mmio_needed == 2)
2613			*gpr = *(s8 *) run->mmio.data;
2614		else
2615			*gpr = *(u8 *) run->mmio.data;
2616		break;
2617	}
2618
2619done:
2620	return er;
2621}
2622
2623static enum emulation_result kvm_mips_emulate_exc(u32 cause,
2624						  u32 *opc,
2625						  struct kvm_run *run,
2626						  struct kvm_vcpu *vcpu)
2627{
2628	u32 exccode = (cause >> CAUSEB_EXCCODE) & 0x1f;
2629	struct mips_coproc *cop0 = vcpu->arch.cop0;
2630	struct kvm_vcpu_arch *arch = &vcpu->arch;
2631	enum emulation_result er = EMULATE_DONE;
2632
2633	if ((kvm_read_c0_guest_status(cop0) & ST0_EXL) == 0) {
2634		/* save old pc */
2635		kvm_write_c0_guest_epc(cop0, arch->pc);
2636		kvm_set_c0_guest_status(cop0, ST0_EXL);
2637
2638		if (cause & CAUSEF_BD)
2639			kvm_set_c0_guest_cause(cop0, CAUSEF_BD);
2640		else
2641			kvm_clear_c0_guest_cause(cop0, CAUSEF_BD);
2642
2643		kvm_change_c0_guest_cause(cop0, (0xff),
2644					  (exccode << CAUSEB_EXCCODE));
2645
2646		/* Set PC to the exception entry point */
2647		arch->pc = kvm_mips_guest_exception_base(vcpu) + 0x180;
2648		kvm_write_c0_guest_badvaddr(cop0, vcpu->arch.host_cp0_badvaddr);
2649
2650		kvm_debug("Delivering EXC %d @ pc %#lx, badVaddr: %#lx\n",
2651			  exccode, kvm_read_c0_guest_epc(cop0),
2652			  kvm_read_c0_guest_badvaddr(cop0));
2653	} else {
2654		kvm_err("Trying to deliver EXC when EXL is already set\n");
2655		er = EMULATE_FAIL;
2656	}
2657
2658	return er;
2659}
2660
2661enum emulation_result kvm_mips_check_privilege(u32 cause,
2662					       u32 *opc,
2663					       struct kvm_run *run,
2664					       struct kvm_vcpu *vcpu)
2665{
2666	enum emulation_result er = EMULATE_DONE;
2667	u32 exccode = (cause >> CAUSEB_EXCCODE) & 0x1f;
2668	unsigned long badvaddr = vcpu->arch.host_cp0_badvaddr;
2669
2670	int usermode = !KVM_GUEST_KERNEL_MODE(vcpu);
2671
2672	if (usermode) {
2673		switch (exccode) {
2674		case EXCCODE_INT:
2675		case EXCCODE_SYS:
2676		case EXCCODE_BP:
2677		case EXCCODE_RI:
2678		case EXCCODE_TR:
2679		case EXCCODE_MSAFPE:
2680		case EXCCODE_FPE:
2681		case EXCCODE_MSADIS:
2682			break;
2683
2684		case EXCCODE_CPU:
2685			if (((cause & CAUSEF_CE) >> CAUSEB_CE) == 0)
2686				er = EMULATE_PRIV_FAIL;
2687			break;
2688
2689		case EXCCODE_MOD:
2690			break;
2691
2692		case EXCCODE_TLBL:
2693			/*
2694			 * We we are accessing Guest kernel space, then send an
2695			 * address error exception to the guest
2696			 */
2697			if (badvaddr >= (unsigned long) KVM_GUEST_KSEG0) {
2698				kvm_debug("%s: LD MISS @ %#lx\n", __func__,
2699					  badvaddr);
2700				cause &= ~0xff;
2701				cause |= (EXCCODE_ADEL << CAUSEB_EXCCODE);
2702				er = EMULATE_PRIV_FAIL;
2703			}
2704			break;
2705
2706		case EXCCODE_TLBS:
2707			/*
2708			 * We we are accessing Guest kernel space, then send an
2709			 * address error exception to the guest
2710			 */
2711			if (badvaddr >= (unsigned long) KVM_GUEST_KSEG0) {
2712				kvm_debug("%s: ST MISS @ %#lx\n", __func__,
2713					  badvaddr);
2714				cause &= ~0xff;
2715				cause |= (EXCCODE_ADES << CAUSEB_EXCCODE);
2716				er = EMULATE_PRIV_FAIL;
2717			}
2718			break;
2719
2720		case EXCCODE_ADES:
2721			kvm_debug("%s: address error ST @ %#lx\n", __func__,
2722				  badvaddr);
2723			if ((badvaddr & PAGE_MASK) == KVM_GUEST_COMMPAGE_ADDR) {
2724				cause &= ~0xff;
2725				cause |= (EXCCODE_TLBS << CAUSEB_EXCCODE);
2726			}
2727			er = EMULATE_PRIV_FAIL;
2728			break;
2729		case EXCCODE_ADEL:
2730			kvm_debug("%s: address error LD @ %#lx\n", __func__,
2731				  badvaddr);
2732			if ((badvaddr & PAGE_MASK) == KVM_GUEST_COMMPAGE_ADDR) {
2733				cause &= ~0xff;
2734				cause |= (EXCCODE_TLBL << CAUSEB_EXCCODE);
2735			}
2736			er = EMULATE_PRIV_FAIL;
2737			break;
2738		default:
2739			er = EMULATE_PRIV_FAIL;
2740			break;
2741		}
2742	}
2743
2744	if (er == EMULATE_PRIV_FAIL)
2745		kvm_mips_emulate_exc(cause, opc, run, vcpu);
2746
2747	return er;
2748}
2749
2750/*
2751 * User Address (UA) fault, this could happen if
2752 * (1) TLB entry not present/valid in both Guest and shadow host TLBs, in this
2753 *     case we pass on the fault to the guest kernel and let it handle it.
2754 * (2) TLB entry is present in the Guest TLB but not in the shadow, in this
2755 *     case we inject the TLB from the Guest TLB into the shadow host TLB
2756 */
2757enum emulation_result kvm_mips_handle_tlbmiss(u32 cause,
2758					      u32 *opc,
2759					      struct kvm_run *run,
2760					      struct kvm_vcpu *vcpu,
2761					      bool write_fault)
2762{
2763	enum emulation_result er = EMULATE_DONE;
2764	u32 exccode = (cause >> CAUSEB_EXCCODE) & 0x1f;
2765	unsigned long va = vcpu->arch.host_cp0_badvaddr;
2766	int index;
2767
2768	kvm_debug("kvm_mips_handle_tlbmiss: badvaddr: %#lx\n",
2769		  vcpu->arch.host_cp0_badvaddr);
2770
2771	/*
2772	 * KVM would not have got the exception if this entry was valid in the
2773	 * shadow host TLB. Check the Guest TLB, if the entry is not there then
2774	 * send the guest an exception. The guest exc handler should then inject
2775	 * an entry into the guest TLB.
2776	 */
2777	index = kvm_mips_guest_tlb_lookup(vcpu,
2778		      (va & VPN2_MASK) |
2779		      (kvm_read_c0_guest_entryhi(vcpu->arch.cop0) &
2780		       KVM_ENTRYHI_ASID));
2781	if (index < 0) {
2782		if (exccode == EXCCODE_TLBL) {
2783			er = kvm_mips_emulate_tlbmiss_ld(cause, opc, run, vcpu);
2784		} else if (exccode == EXCCODE_TLBS) {
2785			er = kvm_mips_emulate_tlbmiss_st(cause, opc, run, vcpu);
2786		} else {
2787			kvm_err("%s: invalid exc code: %d\n", __func__,
2788				exccode);
2789			er = EMULATE_FAIL;
2790		}
2791	} else {
2792		struct kvm_mips_tlb *tlb = &vcpu->arch.guest_tlb[index];
2793
2794		/*
2795		 * Check if the entry is valid, if not then setup a TLB invalid
2796		 * exception to the guest
2797		 */
2798		if (!TLB_IS_VALID(*tlb, va)) {
2799			if (exccode == EXCCODE_TLBL) {
2800				er = kvm_mips_emulate_tlbinv_ld(cause, opc, run,
2801								vcpu);
2802			} else if (exccode == EXCCODE_TLBS) {
2803				er = kvm_mips_emulate_tlbinv_st(cause, opc, run,
2804								vcpu);
2805			} else {
2806				kvm_err("%s: invalid exc code: %d\n", __func__,
2807					exccode);
2808				er = EMULATE_FAIL;
2809			}
2810		} else {
2811			kvm_debug("Injecting hi: %#lx, lo0: %#lx, lo1: %#lx into shadow host TLB\n",
2812				  tlb->tlb_hi, tlb->tlb_lo[0], tlb->tlb_lo[1]);
2813			/*
2814			 * OK we have a Guest TLB entry, now inject it into the
2815			 * shadow host TLB
2816			 */
2817			if (kvm_mips_handle_mapped_seg_tlb_fault(vcpu, tlb, va,
2818								 write_fault)) {
2819				kvm_err("%s: handling mapped seg tlb fault for %lx, index: %u, vcpu: %p, ASID: %#lx\n",
2820					__func__, va, index, vcpu,
2821					read_c0_entryhi());
2822				er = EMULATE_FAIL;
2823			}
2824		}
2825	}
2826
2827	return er;
2828}