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