xref: /openbmc/linux/arch/mips/kernel/traps.c (revision 963287e48314d334d3c5b377dca8ea0dec4ac718)
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  * Copyright (C) 1994 - 1999, 2000, 01, 06 Ralf Baechle
7  * Copyright (C) 1995, 1996 Paul M. Antoine
8  * Copyright (C) 1998 Ulf Carlsson
9  * Copyright (C) 1999 Silicon Graphics, Inc.
10  * Kevin D. Kissell, kevink@mips.com and Carsten Langgaard, carstenl@mips.com
11  * Copyright (C) 2002, 2003, 2004, 2005, 2007  Maciej W. Rozycki
12  * Copyright (C) 2000, 2001, 2012 MIPS Technologies, Inc.  All rights reserved.
13  * Copyright (C) 2014, Imagination Technologies Ltd.
14  */
15 #include <linux/bitops.h>
16 #include <linux/bug.h>
17 #include <linux/compiler.h>
18 #include <linux/context_tracking.h>
19 #include <linux/cpu_pm.h>
20 #include <linux/kexec.h>
21 #include <linux/init.h>
22 #include <linux/kernel.h>
23 #include <linux/module.h>
24 #include <linux/extable.h>
25 #include <linux/mm.h>
26 #include <linux/sched/mm.h>
27 #include <linux/sched/debug.h>
28 #include <linux/smp.h>
29 #include <linux/spinlock.h>
30 #include <linux/kallsyms.h>
31 #include <linux/memblock.h>
32 #include <linux/interrupt.h>
33 #include <linux/ptrace.h>
34 #include <linux/kgdb.h>
35 #include <linux/kdebug.h>
36 #include <linux/kprobes.h>
37 #include <linux/notifier.h>
38 #include <linux/kdb.h>
39 #include <linux/irq.h>
40 #include <linux/perf_event.h>
41 
42 #include <asm/addrspace.h>
43 #include <asm/bootinfo.h>
44 #include <asm/branch.h>
45 #include <asm/break.h>
46 #include <asm/cop2.h>
47 #include <asm/cpu.h>
48 #include <asm/cpu-type.h>
49 #include <asm/dsp.h>
50 #include <asm/fpu.h>
51 #include <asm/fpu_emulator.h>
52 #include <asm/idle.h>
53 #include <asm/isa-rev.h>
54 #include <asm/mips-cps.h>
55 #include <asm/mips-r2-to-r6-emul.h>
56 #include <asm/mipsregs.h>
57 #include <asm/mipsmtregs.h>
58 #include <asm/module.h>
59 #include <asm/msa.h>
60 #include <asm/pgtable.h>
61 #include <asm/ptrace.h>
62 #include <asm/sections.h>
63 #include <asm/siginfo.h>
64 #include <asm/tlbdebug.h>
65 #include <asm/traps.h>
66 #include <linux/uaccess.h>
67 #include <asm/watch.h>
68 #include <asm/mmu_context.h>
69 #include <asm/types.h>
70 #include <asm/stacktrace.h>
71 #include <asm/tlbex.h>
72 #include <asm/uasm.h>
73 
74 #include <asm/mach-loongson64/cpucfg-emul.h>
75 
76 extern void check_wait(void);
77 extern asmlinkage void rollback_handle_int(void);
78 extern asmlinkage void handle_int(void);
79 extern asmlinkage void handle_adel(void);
80 extern asmlinkage void handle_ades(void);
81 extern asmlinkage void handle_ibe(void);
82 extern asmlinkage void handle_dbe(void);
83 extern asmlinkage void handle_sys(void);
84 extern asmlinkage void handle_bp(void);
85 extern asmlinkage void handle_ri(void);
86 extern asmlinkage void handle_ri_rdhwr_tlbp(void);
87 extern asmlinkage void handle_ri_rdhwr(void);
88 extern asmlinkage void handle_cpu(void);
89 extern asmlinkage void handle_ov(void);
90 extern asmlinkage void handle_tr(void);
91 extern asmlinkage void handle_msa_fpe(void);
92 extern asmlinkage void handle_fpe(void);
93 extern asmlinkage void handle_ftlb(void);
94 extern asmlinkage void handle_msa(void);
95 extern asmlinkage void handle_mdmx(void);
96 extern asmlinkage void handle_watch(void);
97 extern asmlinkage void handle_mt(void);
98 extern asmlinkage void handle_dsp(void);
99 extern asmlinkage void handle_mcheck(void);
100 extern asmlinkage void handle_reserved(void);
101 extern void tlb_do_page_fault_0(void);
102 
103 void (*board_be_init)(void);
104 int (*board_be_handler)(struct pt_regs *regs, int is_fixup);
105 void (*board_nmi_handler_setup)(void);
106 void (*board_ejtag_handler_setup)(void);
107 void (*board_bind_eic_interrupt)(int irq, int regset);
108 void (*board_ebase_setup)(void);
109 void(*board_cache_error_setup)(void);
110 
111 static void show_raw_backtrace(unsigned long reg29)
112 {
113 	unsigned long *sp = (unsigned long *)(reg29 & ~3);
114 	unsigned long addr;
115 
116 	printk("Call Trace:");
117 #ifdef CONFIG_KALLSYMS
118 	printk("\n");
119 #endif
120 	while (!kstack_end(sp)) {
121 		unsigned long __user *p =
122 			(unsigned long __user *)(unsigned long)sp++;
123 		if (__get_user(addr, p)) {
124 			printk(" (Bad stack address)");
125 			break;
126 		}
127 		if (__kernel_text_address(addr))
128 			print_ip_sym(addr);
129 	}
130 	printk("\n");
131 }
132 
133 #ifdef CONFIG_KALLSYMS
134 int raw_show_trace;
135 static int __init set_raw_show_trace(char *str)
136 {
137 	raw_show_trace = 1;
138 	return 1;
139 }
140 __setup("raw_show_trace", set_raw_show_trace);
141 #endif
142 
143 static void show_backtrace(struct task_struct *task, const struct pt_regs *regs)
144 {
145 	unsigned long sp = regs->regs[29];
146 	unsigned long ra = regs->regs[31];
147 	unsigned long pc = regs->cp0_epc;
148 
149 	if (!task)
150 		task = current;
151 
152 	if (raw_show_trace || user_mode(regs) || !__kernel_text_address(pc)) {
153 		show_raw_backtrace(sp);
154 		return;
155 	}
156 	printk("Call Trace:\n");
157 	do {
158 		print_ip_sym(pc);
159 		pc = unwind_stack(task, &sp, pc, &ra);
160 	} while (pc);
161 	pr_cont("\n");
162 }
163 
164 /*
165  * This routine abuses get_user()/put_user() to reference pointers
166  * with at least a bit of error checking ...
167  */
168 static void show_stacktrace(struct task_struct *task,
169 	const struct pt_regs *regs)
170 {
171 	const int field = 2 * sizeof(unsigned long);
172 	long stackdata;
173 	int i;
174 	unsigned long __user *sp = (unsigned long __user *)regs->regs[29];
175 
176 	printk("Stack :");
177 	i = 0;
178 	while ((unsigned long) sp & (PAGE_SIZE - 1)) {
179 		if (i && ((i % (64 / field)) == 0)) {
180 			pr_cont("\n");
181 			printk("       ");
182 		}
183 		if (i > 39) {
184 			pr_cont(" ...");
185 			break;
186 		}
187 
188 		if (__get_user(stackdata, sp++)) {
189 			pr_cont(" (Bad stack address)");
190 			break;
191 		}
192 
193 		pr_cont(" %0*lx", field, stackdata);
194 		i++;
195 	}
196 	pr_cont("\n");
197 	show_backtrace(task, regs);
198 }
199 
200 void show_stack(struct task_struct *task, unsigned long *sp)
201 {
202 	struct pt_regs regs;
203 	mm_segment_t old_fs = get_fs();
204 
205 	regs.cp0_status = KSU_KERNEL;
206 	if (sp) {
207 		regs.regs[29] = (unsigned long)sp;
208 		regs.regs[31] = 0;
209 		regs.cp0_epc = 0;
210 	} else {
211 		if (task && task != current) {
212 			regs.regs[29] = task->thread.reg29;
213 			regs.regs[31] = 0;
214 			regs.cp0_epc = task->thread.reg31;
215 		} else {
216 			prepare_frametrace(&regs);
217 		}
218 	}
219 	/*
220 	 * show_stack() deals exclusively with kernel mode, so be sure to access
221 	 * the stack in the kernel (not user) address space.
222 	 */
223 	set_fs(KERNEL_DS);
224 	show_stacktrace(task, &regs);
225 	set_fs(old_fs);
226 }
227 
228 static void show_code(unsigned int __user *pc)
229 {
230 	long i;
231 	unsigned short __user *pc16 = NULL;
232 
233 	printk("Code:");
234 
235 	if ((unsigned long)pc & 1)
236 		pc16 = (unsigned short __user *)((unsigned long)pc & ~1);
237 	for(i = -3 ; i < 6 ; i++) {
238 		unsigned int insn;
239 		if (pc16 ? __get_user(insn, pc16 + i) : __get_user(insn, pc + i)) {
240 			pr_cont(" (Bad address in epc)\n");
241 			break;
242 		}
243 		pr_cont("%c%0*x%c", (i?' ':'<'), pc16 ? 4 : 8, insn, (i?' ':'>'));
244 	}
245 	pr_cont("\n");
246 }
247 
248 static void __show_regs(const struct pt_regs *regs)
249 {
250 	const int field = 2 * sizeof(unsigned long);
251 	unsigned int cause = regs->cp0_cause;
252 	unsigned int exccode;
253 	int i;
254 
255 	show_regs_print_info(KERN_DEFAULT);
256 
257 	/*
258 	 * Saved main processor registers
259 	 */
260 	for (i = 0; i < 32; ) {
261 		if ((i % 4) == 0)
262 			printk("$%2d   :", i);
263 		if (i == 0)
264 			pr_cont(" %0*lx", field, 0UL);
265 		else if (i == 26 || i == 27)
266 			pr_cont(" %*s", field, "");
267 		else
268 			pr_cont(" %0*lx", field, regs->regs[i]);
269 
270 		i++;
271 		if ((i % 4) == 0)
272 			pr_cont("\n");
273 	}
274 
275 #ifdef CONFIG_CPU_HAS_SMARTMIPS
276 	printk("Acx    : %0*lx\n", field, regs->acx);
277 #endif
278 	if (MIPS_ISA_REV < 6) {
279 		printk("Hi    : %0*lx\n", field, regs->hi);
280 		printk("Lo    : %0*lx\n", field, regs->lo);
281 	}
282 
283 	/*
284 	 * Saved cp0 registers
285 	 */
286 	printk("epc   : %0*lx %pS\n", field, regs->cp0_epc,
287 	       (void *) regs->cp0_epc);
288 	printk("ra    : %0*lx %pS\n", field, regs->regs[31],
289 	       (void *) regs->regs[31]);
290 
291 	printk("Status: %08x	", (uint32_t) regs->cp0_status);
292 
293 	if (cpu_has_3kex) {
294 		if (regs->cp0_status & ST0_KUO)
295 			pr_cont("KUo ");
296 		if (regs->cp0_status & ST0_IEO)
297 			pr_cont("IEo ");
298 		if (regs->cp0_status & ST0_KUP)
299 			pr_cont("KUp ");
300 		if (regs->cp0_status & ST0_IEP)
301 			pr_cont("IEp ");
302 		if (regs->cp0_status & ST0_KUC)
303 			pr_cont("KUc ");
304 		if (regs->cp0_status & ST0_IEC)
305 			pr_cont("IEc ");
306 	} else if (cpu_has_4kex) {
307 		if (regs->cp0_status & ST0_KX)
308 			pr_cont("KX ");
309 		if (regs->cp0_status & ST0_SX)
310 			pr_cont("SX ");
311 		if (regs->cp0_status & ST0_UX)
312 			pr_cont("UX ");
313 		switch (regs->cp0_status & ST0_KSU) {
314 		case KSU_USER:
315 			pr_cont("USER ");
316 			break;
317 		case KSU_SUPERVISOR:
318 			pr_cont("SUPERVISOR ");
319 			break;
320 		case KSU_KERNEL:
321 			pr_cont("KERNEL ");
322 			break;
323 		default:
324 			pr_cont("BAD_MODE ");
325 			break;
326 		}
327 		if (regs->cp0_status & ST0_ERL)
328 			pr_cont("ERL ");
329 		if (regs->cp0_status & ST0_EXL)
330 			pr_cont("EXL ");
331 		if (regs->cp0_status & ST0_IE)
332 			pr_cont("IE ");
333 	}
334 	pr_cont("\n");
335 
336 	exccode = (cause & CAUSEF_EXCCODE) >> CAUSEB_EXCCODE;
337 	printk("Cause : %08x (ExcCode %02x)\n", cause, exccode);
338 
339 	if (1 <= exccode && exccode <= 5)
340 		printk("BadVA : %0*lx\n", field, regs->cp0_badvaddr);
341 
342 	printk("PrId  : %08x (%s)\n", read_c0_prid(),
343 	       cpu_name_string());
344 }
345 
346 /*
347  * FIXME: really the generic show_regs should take a const pointer argument.
348  */
349 void show_regs(struct pt_regs *regs)
350 {
351 	__show_regs(regs);
352 	dump_stack();
353 }
354 
355 void show_registers(struct pt_regs *regs)
356 {
357 	const int field = 2 * sizeof(unsigned long);
358 	mm_segment_t old_fs = get_fs();
359 
360 	__show_regs(regs);
361 	print_modules();
362 	printk("Process %s (pid: %d, threadinfo=%p, task=%p, tls=%0*lx)\n",
363 	       current->comm, current->pid, current_thread_info(), current,
364 	      field, current_thread_info()->tp_value);
365 	if (cpu_has_userlocal) {
366 		unsigned long tls;
367 
368 		tls = read_c0_userlocal();
369 		if (tls != current_thread_info()->tp_value)
370 			printk("*HwTLS: %0*lx\n", field, tls);
371 	}
372 
373 	if (!user_mode(regs))
374 		/* Necessary for getting the correct stack content */
375 		set_fs(KERNEL_DS);
376 	show_stacktrace(current, regs);
377 	show_code((unsigned int __user *) regs->cp0_epc);
378 	printk("\n");
379 	set_fs(old_fs);
380 }
381 
382 static DEFINE_RAW_SPINLOCK(die_lock);
383 
384 void __noreturn die(const char *str, struct pt_regs *regs)
385 {
386 	static int die_counter;
387 	int sig = SIGSEGV;
388 
389 	oops_enter();
390 
391 	if (notify_die(DIE_OOPS, str, regs, 0, current->thread.trap_nr,
392 		       SIGSEGV) == NOTIFY_STOP)
393 		sig = 0;
394 
395 	console_verbose();
396 	raw_spin_lock_irq(&die_lock);
397 	bust_spinlocks(1);
398 
399 	printk("%s[#%d]:\n", str, ++die_counter);
400 	show_registers(regs);
401 	add_taint(TAINT_DIE, LOCKDEP_NOW_UNRELIABLE);
402 	raw_spin_unlock_irq(&die_lock);
403 
404 	oops_exit();
405 
406 	if (in_interrupt())
407 		panic("Fatal exception in interrupt");
408 
409 	if (panic_on_oops)
410 		panic("Fatal exception");
411 
412 	if (regs && kexec_should_crash(current))
413 		crash_kexec(regs);
414 
415 	do_exit(sig);
416 }
417 
418 extern struct exception_table_entry __start___dbe_table[];
419 extern struct exception_table_entry __stop___dbe_table[];
420 
421 __asm__(
422 "	.section	__dbe_table, \"a\"\n"
423 "	.previous			\n");
424 
425 /* Given an address, look for it in the exception tables. */
426 static const struct exception_table_entry *search_dbe_tables(unsigned long addr)
427 {
428 	const struct exception_table_entry *e;
429 
430 	e = search_extable(__start___dbe_table,
431 			   __stop___dbe_table - __start___dbe_table, addr);
432 	if (!e)
433 		e = search_module_dbetables(addr);
434 	return e;
435 }
436 
437 asmlinkage void do_be(struct pt_regs *regs)
438 {
439 	const int field = 2 * sizeof(unsigned long);
440 	const struct exception_table_entry *fixup = NULL;
441 	int data = regs->cp0_cause & 4;
442 	int action = MIPS_BE_FATAL;
443 	enum ctx_state prev_state;
444 
445 	prev_state = exception_enter();
446 	/* XXX For now.	 Fixme, this searches the wrong table ...  */
447 	if (data && !user_mode(regs))
448 		fixup = search_dbe_tables(exception_epc(regs));
449 
450 	if (fixup)
451 		action = MIPS_BE_FIXUP;
452 
453 	if (board_be_handler)
454 		action = board_be_handler(regs, fixup != NULL);
455 	else
456 		mips_cm_error_report();
457 
458 	switch (action) {
459 	case MIPS_BE_DISCARD:
460 		goto out;
461 	case MIPS_BE_FIXUP:
462 		if (fixup) {
463 			regs->cp0_epc = fixup->nextinsn;
464 			goto out;
465 		}
466 		break;
467 	default:
468 		break;
469 	}
470 
471 	/*
472 	 * Assume it would be too dangerous to continue ...
473 	 */
474 	printk(KERN_ALERT "%s bus error, epc == %0*lx, ra == %0*lx\n",
475 	       data ? "Data" : "Instruction",
476 	       field, regs->cp0_epc, field, regs->regs[31]);
477 	if (notify_die(DIE_OOPS, "bus error", regs, 0, current->thread.trap_nr,
478 		       SIGBUS) == NOTIFY_STOP)
479 		goto out;
480 
481 	die_if_kernel("Oops", regs);
482 	force_sig(SIGBUS);
483 
484 out:
485 	exception_exit(prev_state);
486 }
487 
488 /*
489  * ll/sc, rdhwr, sync emulation
490  */
491 
492 #define OPCODE 0xfc000000
493 #define BASE   0x03e00000
494 #define RT     0x001f0000
495 #define OFFSET 0x0000ffff
496 #define LL     0xc0000000
497 #define SC     0xe0000000
498 #define SPEC0  0x00000000
499 #define SPEC3  0x7c000000
500 #define RD     0x0000f800
501 #define FUNC   0x0000003f
502 #define SYNC   0x0000000f
503 #define RDHWR  0x0000003b
504 
505 /*  microMIPS definitions   */
506 #define MM_POOL32A_FUNC 0xfc00ffff
507 #define MM_RDHWR        0x00006b3c
508 #define MM_RS           0x001f0000
509 #define MM_RT           0x03e00000
510 
511 /*
512  * The ll_bit is cleared by r*_switch.S
513  */
514 
515 unsigned int ll_bit;
516 struct task_struct *ll_task;
517 
518 static inline int simulate_ll(struct pt_regs *regs, unsigned int opcode)
519 {
520 	unsigned long value, __user *vaddr;
521 	long offset;
522 
523 	/*
524 	 * analyse the ll instruction that just caused a ri exception
525 	 * and put the referenced address to addr.
526 	 */
527 
528 	/* sign extend offset */
529 	offset = opcode & OFFSET;
530 	offset <<= 16;
531 	offset >>= 16;
532 
533 	vaddr = (unsigned long __user *)
534 		((unsigned long)(regs->regs[(opcode & BASE) >> 21]) + offset);
535 
536 	if ((unsigned long)vaddr & 3)
537 		return SIGBUS;
538 	if (get_user(value, vaddr))
539 		return SIGSEGV;
540 
541 	preempt_disable();
542 
543 	if (ll_task == NULL || ll_task == current) {
544 		ll_bit = 1;
545 	} else {
546 		ll_bit = 0;
547 	}
548 	ll_task = current;
549 
550 	preempt_enable();
551 
552 	regs->regs[(opcode & RT) >> 16] = value;
553 
554 	return 0;
555 }
556 
557 static inline int simulate_sc(struct pt_regs *regs, unsigned int opcode)
558 {
559 	unsigned long __user *vaddr;
560 	unsigned long reg;
561 	long offset;
562 
563 	/*
564 	 * analyse the sc instruction that just caused a ri exception
565 	 * and put the referenced address to addr.
566 	 */
567 
568 	/* sign extend offset */
569 	offset = opcode & OFFSET;
570 	offset <<= 16;
571 	offset >>= 16;
572 
573 	vaddr = (unsigned long __user *)
574 		((unsigned long)(regs->regs[(opcode & BASE) >> 21]) + offset);
575 	reg = (opcode & RT) >> 16;
576 
577 	if ((unsigned long)vaddr & 3)
578 		return SIGBUS;
579 
580 	preempt_disable();
581 
582 	if (ll_bit == 0 || ll_task != current) {
583 		regs->regs[reg] = 0;
584 		preempt_enable();
585 		return 0;
586 	}
587 
588 	preempt_enable();
589 
590 	if (put_user(regs->regs[reg], vaddr))
591 		return SIGSEGV;
592 
593 	regs->regs[reg] = 1;
594 
595 	return 0;
596 }
597 
598 /*
599  * ll uses the opcode of lwc0 and sc uses the opcode of swc0.  That is both
600  * opcodes are supposed to result in coprocessor unusable exceptions if
601  * executed on ll/sc-less processors.  That's the theory.  In practice a
602  * few processors such as NEC's VR4100 throw reserved instruction exceptions
603  * instead, so we're doing the emulation thing in both exception handlers.
604  */
605 static int simulate_llsc(struct pt_regs *regs, unsigned int opcode)
606 {
607 	if ((opcode & OPCODE) == LL) {
608 		perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS,
609 				1, regs, 0);
610 		return simulate_ll(regs, opcode);
611 	}
612 	if ((opcode & OPCODE) == SC) {
613 		perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS,
614 				1, regs, 0);
615 		return simulate_sc(regs, opcode);
616 	}
617 
618 	return -1;			/* Must be something else ... */
619 }
620 
621 /*
622  * Simulate trapping 'rdhwr' instructions to provide user accessible
623  * registers not implemented in hardware.
624  */
625 static int simulate_rdhwr(struct pt_regs *regs, int rd, int rt)
626 {
627 	struct thread_info *ti = task_thread_info(current);
628 
629 	perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS,
630 			1, regs, 0);
631 	switch (rd) {
632 	case MIPS_HWR_CPUNUM:		/* CPU number */
633 		regs->regs[rt] = smp_processor_id();
634 		return 0;
635 	case MIPS_HWR_SYNCISTEP:	/* SYNCI length */
636 		regs->regs[rt] = min(current_cpu_data.dcache.linesz,
637 				     current_cpu_data.icache.linesz);
638 		return 0;
639 	case MIPS_HWR_CC:		/* Read count register */
640 		regs->regs[rt] = read_c0_count();
641 		return 0;
642 	case MIPS_HWR_CCRES:		/* Count register resolution */
643 		switch (current_cpu_type()) {
644 		case CPU_20KC:
645 		case CPU_25KF:
646 			regs->regs[rt] = 1;
647 			break;
648 		default:
649 			regs->regs[rt] = 2;
650 		}
651 		return 0;
652 	case MIPS_HWR_ULR:		/* Read UserLocal register */
653 		regs->regs[rt] = ti->tp_value;
654 		return 0;
655 	default:
656 		return -1;
657 	}
658 }
659 
660 static int simulate_rdhwr_normal(struct pt_regs *regs, unsigned int opcode)
661 {
662 	if ((opcode & OPCODE) == SPEC3 && (opcode & FUNC) == RDHWR) {
663 		int rd = (opcode & RD) >> 11;
664 		int rt = (opcode & RT) >> 16;
665 
666 		simulate_rdhwr(regs, rd, rt);
667 		return 0;
668 	}
669 
670 	/* Not ours.  */
671 	return -1;
672 }
673 
674 static int simulate_rdhwr_mm(struct pt_regs *regs, unsigned int opcode)
675 {
676 	if ((opcode & MM_POOL32A_FUNC) == MM_RDHWR) {
677 		int rd = (opcode & MM_RS) >> 16;
678 		int rt = (opcode & MM_RT) >> 21;
679 		simulate_rdhwr(regs, rd, rt);
680 		return 0;
681 	}
682 
683 	/* Not ours.  */
684 	return -1;
685 }
686 
687 static int simulate_sync(struct pt_regs *regs, unsigned int opcode)
688 {
689 	if ((opcode & OPCODE) == SPEC0 && (opcode & FUNC) == SYNC) {
690 		perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS,
691 				1, regs, 0);
692 		return 0;
693 	}
694 
695 	return -1;			/* Must be something else ... */
696 }
697 
698 /*
699  * Loongson-3 CSR instructions emulation
700  */
701 
702 #ifdef CONFIG_CPU_LOONGSON3_CPUCFG_EMULATION
703 
704 #define LWC2             0xc8000000
705 #define RS               BASE
706 #define CSR_OPCODE2      0x00000118
707 #define CSR_OPCODE2_MASK 0x000007ff
708 #define CSR_FUNC_MASK    RT
709 #define CSR_FUNC_CPUCFG  0x8
710 
711 static int simulate_loongson3_cpucfg(struct pt_regs *regs,
712 				     unsigned int opcode)
713 {
714 	int op = opcode & OPCODE;
715 	int op2 = opcode & CSR_OPCODE2_MASK;
716 	int csr_func = (opcode & CSR_FUNC_MASK) >> 16;
717 
718 	if (op == LWC2 && op2 == CSR_OPCODE2 && csr_func == CSR_FUNC_CPUCFG) {
719 		int rd = (opcode & RD) >> 11;
720 		int rs = (opcode & RS) >> 21;
721 		__u64 sel = regs->regs[rs];
722 
723 		perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, regs, 0);
724 
725 		regs->regs[rd] = loongson3_cpucfg_read_synthesized(
726 			&current_cpu_data, sel);
727 
728 		return 0;
729 	}
730 
731 	/* Not ours.  */
732 	return -1;
733 }
734 #endif /* CONFIG_CPU_LOONGSON3_CPUCFG_EMULATION */
735 
736 asmlinkage void do_ov(struct pt_regs *regs)
737 {
738 	enum ctx_state prev_state;
739 
740 	prev_state = exception_enter();
741 	die_if_kernel("Integer overflow", regs);
742 
743 	force_sig_fault(SIGFPE, FPE_INTOVF, (void __user *)regs->cp0_epc);
744 	exception_exit(prev_state);
745 }
746 
747 #ifdef CONFIG_MIPS_FP_SUPPORT
748 
749 /*
750  * Send SIGFPE according to FCSR Cause bits, which must have already
751  * been masked against Enable bits.  This is impotant as Inexact can
752  * happen together with Overflow or Underflow, and `ptrace' can set
753  * any bits.
754  */
755 void force_fcr31_sig(unsigned long fcr31, void __user *fault_addr,
756 		     struct task_struct *tsk)
757 {
758 	int si_code = FPE_FLTUNK;
759 
760 	if (fcr31 & FPU_CSR_INV_X)
761 		si_code = FPE_FLTINV;
762 	else if (fcr31 & FPU_CSR_DIV_X)
763 		si_code = FPE_FLTDIV;
764 	else if (fcr31 & FPU_CSR_OVF_X)
765 		si_code = FPE_FLTOVF;
766 	else if (fcr31 & FPU_CSR_UDF_X)
767 		si_code = FPE_FLTUND;
768 	else if (fcr31 & FPU_CSR_INE_X)
769 		si_code = FPE_FLTRES;
770 
771 	force_sig_fault_to_task(SIGFPE, si_code, fault_addr, tsk);
772 }
773 
774 int process_fpemu_return(int sig, void __user *fault_addr, unsigned long fcr31)
775 {
776 	int si_code;
777 	struct vm_area_struct *vma;
778 
779 	switch (sig) {
780 	case 0:
781 		return 0;
782 
783 	case SIGFPE:
784 		force_fcr31_sig(fcr31, fault_addr, current);
785 		return 1;
786 
787 	case SIGBUS:
788 		force_sig_fault(SIGBUS, BUS_ADRERR, fault_addr);
789 		return 1;
790 
791 	case SIGSEGV:
792 		down_read(&current->mm->mmap_sem);
793 		vma = find_vma(current->mm, (unsigned long)fault_addr);
794 		if (vma && (vma->vm_start <= (unsigned long)fault_addr))
795 			si_code = SEGV_ACCERR;
796 		else
797 			si_code = SEGV_MAPERR;
798 		up_read(&current->mm->mmap_sem);
799 		force_sig_fault(SIGSEGV, si_code, fault_addr);
800 		return 1;
801 
802 	default:
803 		force_sig(sig);
804 		return 1;
805 	}
806 }
807 
808 static int simulate_fp(struct pt_regs *regs, unsigned int opcode,
809 		       unsigned long old_epc, unsigned long old_ra)
810 {
811 	union mips_instruction inst = { .word = opcode };
812 	void __user *fault_addr;
813 	unsigned long fcr31;
814 	int sig;
815 
816 	/* If it's obviously not an FP instruction, skip it */
817 	switch (inst.i_format.opcode) {
818 	case cop1_op:
819 	case cop1x_op:
820 	case lwc1_op:
821 	case ldc1_op:
822 	case swc1_op:
823 	case sdc1_op:
824 		break;
825 
826 	default:
827 		return -1;
828 	}
829 
830 	/*
831 	 * do_ri skipped over the instruction via compute_return_epc, undo
832 	 * that for the FPU emulator.
833 	 */
834 	regs->cp0_epc = old_epc;
835 	regs->regs[31] = old_ra;
836 
837 	/* Run the emulator */
838 	sig = fpu_emulator_cop1Handler(regs, &current->thread.fpu, 1,
839 				       &fault_addr);
840 
841 	/*
842 	 * We can't allow the emulated instruction to leave any
843 	 * enabled Cause bits set in $fcr31.
844 	 */
845 	fcr31 = mask_fcr31_x(current->thread.fpu.fcr31);
846 	current->thread.fpu.fcr31 &= ~fcr31;
847 
848 	/* Restore the hardware register state */
849 	own_fpu(1);
850 
851 	/* Send a signal if required.  */
852 	process_fpemu_return(sig, fault_addr, fcr31);
853 
854 	return 0;
855 }
856 
857 /*
858  * XXX Delayed fp exceptions when doing a lazy ctx switch XXX
859  */
860 asmlinkage void do_fpe(struct pt_regs *regs, unsigned long fcr31)
861 {
862 	enum ctx_state prev_state;
863 	void __user *fault_addr;
864 	int sig;
865 
866 	prev_state = exception_enter();
867 	if (notify_die(DIE_FP, "FP exception", regs, 0, current->thread.trap_nr,
868 		       SIGFPE) == NOTIFY_STOP)
869 		goto out;
870 
871 	/* Clear FCSR.Cause before enabling interrupts */
872 	write_32bit_cp1_register(CP1_STATUS, fcr31 & ~mask_fcr31_x(fcr31));
873 	local_irq_enable();
874 
875 	die_if_kernel("FP exception in kernel code", regs);
876 
877 	if (fcr31 & FPU_CSR_UNI_X) {
878 		/*
879 		 * Unimplemented operation exception.  If we've got the full
880 		 * software emulator on-board, let's use it...
881 		 *
882 		 * Force FPU to dump state into task/thread context.  We're
883 		 * moving a lot of data here for what is probably a single
884 		 * instruction, but the alternative is to pre-decode the FP
885 		 * register operands before invoking the emulator, which seems
886 		 * a bit extreme for what should be an infrequent event.
887 		 */
888 
889 		/* Run the emulator */
890 		sig = fpu_emulator_cop1Handler(regs, &current->thread.fpu, 1,
891 					       &fault_addr);
892 
893 		/*
894 		 * We can't allow the emulated instruction to leave any
895 		 * enabled Cause bits set in $fcr31.
896 		 */
897 		fcr31 = mask_fcr31_x(current->thread.fpu.fcr31);
898 		current->thread.fpu.fcr31 &= ~fcr31;
899 
900 		/* Restore the hardware register state */
901 		own_fpu(1);	/* Using the FPU again.	 */
902 	} else {
903 		sig = SIGFPE;
904 		fault_addr = (void __user *) regs->cp0_epc;
905 	}
906 
907 	/* Send a signal if required.  */
908 	process_fpemu_return(sig, fault_addr, fcr31);
909 
910 out:
911 	exception_exit(prev_state);
912 }
913 
914 /*
915  * MIPS MT processors may have fewer FPU contexts than CPU threads. If we've
916  * emulated more than some threshold number of instructions, force migration to
917  * a "CPU" that has FP support.
918  */
919 static void mt_ase_fp_affinity(void)
920 {
921 #ifdef CONFIG_MIPS_MT_FPAFF
922 	if (mt_fpemul_threshold > 0 &&
923 	     ((current->thread.emulated_fp++ > mt_fpemul_threshold))) {
924 		/*
925 		 * If there's no FPU present, or if the application has already
926 		 * restricted the allowed set to exclude any CPUs with FPUs,
927 		 * we'll skip the procedure.
928 		 */
929 		if (cpumask_intersects(&current->cpus_mask, &mt_fpu_cpumask)) {
930 			cpumask_t tmask;
931 
932 			current->thread.user_cpus_allowed
933 				= current->cpus_mask;
934 			cpumask_and(&tmask, &current->cpus_mask,
935 				    &mt_fpu_cpumask);
936 			set_cpus_allowed_ptr(current, &tmask);
937 			set_thread_flag(TIF_FPUBOUND);
938 		}
939 	}
940 #endif /* CONFIG_MIPS_MT_FPAFF */
941 }
942 
943 #else /* !CONFIG_MIPS_FP_SUPPORT */
944 
945 static int simulate_fp(struct pt_regs *regs, unsigned int opcode,
946 		       unsigned long old_epc, unsigned long old_ra)
947 {
948 	return -1;
949 }
950 
951 #endif /* !CONFIG_MIPS_FP_SUPPORT */
952 
953 void do_trap_or_bp(struct pt_regs *regs, unsigned int code, int si_code,
954 	const char *str)
955 {
956 	char b[40];
957 
958 #ifdef CONFIG_KGDB_LOW_LEVEL_TRAP
959 	if (kgdb_ll_trap(DIE_TRAP, str, regs, code, current->thread.trap_nr,
960 			 SIGTRAP) == NOTIFY_STOP)
961 		return;
962 #endif /* CONFIG_KGDB_LOW_LEVEL_TRAP */
963 
964 	if (notify_die(DIE_TRAP, str, regs, code, current->thread.trap_nr,
965 		       SIGTRAP) == NOTIFY_STOP)
966 		return;
967 
968 	/*
969 	 * A short test says that IRIX 5.3 sends SIGTRAP for all trap
970 	 * insns, even for trap and break codes that indicate arithmetic
971 	 * failures.  Weird ...
972 	 * But should we continue the brokenness???  --macro
973 	 */
974 	switch (code) {
975 	case BRK_OVERFLOW:
976 	case BRK_DIVZERO:
977 		scnprintf(b, sizeof(b), "%s instruction in kernel code", str);
978 		die_if_kernel(b, regs);
979 		force_sig_fault(SIGFPE,
980 				code == BRK_DIVZERO ? FPE_INTDIV : FPE_INTOVF,
981 				(void __user *) regs->cp0_epc);
982 		break;
983 	case BRK_BUG:
984 		die_if_kernel("Kernel bug detected", regs);
985 		force_sig(SIGTRAP);
986 		break;
987 	case BRK_MEMU:
988 		/*
989 		 * This breakpoint code is used by the FPU emulator to retake
990 		 * control of the CPU after executing the instruction from the
991 		 * delay slot of an emulated branch.
992 		 *
993 		 * Terminate if exception was recognized as a delay slot return
994 		 * otherwise handle as normal.
995 		 */
996 		if (do_dsemulret(regs))
997 			return;
998 
999 		die_if_kernel("Math emu break/trap", regs);
1000 		force_sig(SIGTRAP);
1001 		break;
1002 	default:
1003 		scnprintf(b, sizeof(b), "%s instruction in kernel code", str);
1004 		die_if_kernel(b, regs);
1005 		if (si_code) {
1006 			force_sig_fault(SIGTRAP, si_code, NULL);
1007 		} else {
1008 			force_sig(SIGTRAP);
1009 		}
1010 	}
1011 }
1012 
1013 asmlinkage void do_bp(struct pt_regs *regs)
1014 {
1015 	unsigned long epc = msk_isa16_mode(exception_epc(regs));
1016 	unsigned int opcode, bcode;
1017 	enum ctx_state prev_state;
1018 	mm_segment_t seg;
1019 
1020 	seg = get_fs();
1021 	if (!user_mode(regs))
1022 		set_fs(KERNEL_DS);
1023 
1024 	prev_state = exception_enter();
1025 	current->thread.trap_nr = (regs->cp0_cause >> 2) & 0x1f;
1026 	if (get_isa16_mode(regs->cp0_epc)) {
1027 		u16 instr[2];
1028 
1029 		if (__get_user(instr[0], (u16 __user *)epc))
1030 			goto out_sigsegv;
1031 
1032 		if (!cpu_has_mmips) {
1033 			/* MIPS16e mode */
1034 			bcode = (instr[0] >> 5) & 0x3f;
1035 		} else if (mm_insn_16bit(instr[0])) {
1036 			/* 16-bit microMIPS BREAK */
1037 			bcode = instr[0] & 0xf;
1038 		} else {
1039 			/* 32-bit microMIPS BREAK */
1040 			if (__get_user(instr[1], (u16 __user *)(epc + 2)))
1041 				goto out_sigsegv;
1042 			opcode = (instr[0] << 16) | instr[1];
1043 			bcode = (opcode >> 6) & ((1 << 20) - 1);
1044 		}
1045 	} else {
1046 		if (__get_user(opcode, (unsigned int __user *)epc))
1047 			goto out_sigsegv;
1048 		bcode = (opcode >> 6) & ((1 << 20) - 1);
1049 	}
1050 
1051 	/*
1052 	 * There is the ancient bug in the MIPS assemblers that the break
1053 	 * code starts left to bit 16 instead to bit 6 in the opcode.
1054 	 * Gas is bug-compatible, but not always, grrr...
1055 	 * We handle both cases with a simple heuristics.  --macro
1056 	 */
1057 	if (bcode >= (1 << 10))
1058 		bcode = ((bcode & ((1 << 10) - 1)) << 10) | (bcode >> 10);
1059 
1060 	/*
1061 	 * notify the kprobe handlers, if instruction is likely to
1062 	 * pertain to them.
1063 	 */
1064 	switch (bcode) {
1065 	case BRK_UPROBE:
1066 		if (notify_die(DIE_UPROBE, "uprobe", regs, bcode,
1067 			       current->thread.trap_nr, SIGTRAP) == NOTIFY_STOP)
1068 			goto out;
1069 		else
1070 			break;
1071 	case BRK_UPROBE_XOL:
1072 		if (notify_die(DIE_UPROBE_XOL, "uprobe_xol", regs, bcode,
1073 			       current->thread.trap_nr, SIGTRAP) == NOTIFY_STOP)
1074 			goto out;
1075 		else
1076 			break;
1077 	case BRK_KPROBE_BP:
1078 		if (notify_die(DIE_BREAK, "debug", regs, bcode,
1079 			       current->thread.trap_nr, SIGTRAP) == NOTIFY_STOP)
1080 			goto out;
1081 		else
1082 			break;
1083 	case BRK_KPROBE_SSTEPBP:
1084 		if (notify_die(DIE_SSTEPBP, "single_step", regs, bcode,
1085 			       current->thread.trap_nr, SIGTRAP) == NOTIFY_STOP)
1086 			goto out;
1087 		else
1088 			break;
1089 	default:
1090 		break;
1091 	}
1092 
1093 	do_trap_or_bp(regs, bcode, TRAP_BRKPT, "Break");
1094 
1095 out:
1096 	set_fs(seg);
1097 	exception_exit(prev_state);
1098 	return;
1099 
1100 out_sigsegv:
1101 	force_sig(SIGSEGV);
1102 	goto out;
1103 }
1104 
1105 asmlinkage void do_tr(struct pt_regs *regs)
1106 {
1107 	u32 opcode, tcode = 0;
1108 	enum ctx_state prev_state;
1109 	u16 instr[2];
1110 	mm_segment_t seg;
1111 	unsigned long epc = msk_isa16_mode(exception_epc(regs));
1112 
1113 	seg = get_fs();
1114 	if (!user_mode(regs))
1115 		set_fs(KERNEL_DS);
1116 
1117 	prev_state = exception_enter();
1118 	current->thread.trap_nr = (regs->cp0_cause >> 2) & 0x1f;
1119 	if (get_isa16_mode(regs->cp0_epc)) {
1120 		if (__get_user(instr[0], (u16 __user *)(epc + 0)) ||
1121 		    __get_user(instr[1], (u16 __user *)(epc + 2)))
1122 			goto out_sigsegv;
1123 		opcode = (instr[0] << 16) | instr[1];
1124 		/* Immediate versions don't provide a code.  */
1125 		if (!(opcode & OPCODE))
1126 			tcode = (opcode >> 12) & ((1 << 4) - 1);
1127 	} else {
1128 		if (__get_user(opcode, (u32 __user *)epc))
1129 			goto out_sigsegv;
1130 		/* Immediate versions don't provide a code.  */
1131 		if (!(opcode & OPCODE))
1132 			tcode = (opcode >> 6) & ((1 << 10) - 1);
1133 	}
1134 
1135 	do_trap_or_bp(regs, tcode, 0, "Trap");
1136 
1137 out:
1138 	set_fs(seg);
1139 	exception_exit(prev_state);
1140 	return;
1141 
1142 out_sigsegv:
1143 	force_sig(SIGSEGV);
1144 	goto out;
1145 }
1146 
1147 asmlinkage void do_ri(struct pt_regs *regs)
1148 {
1149 	unsigned int __user *epc = (unsigned int __user *)exception_epc(regs);
1150 	unsigned long old_epc = regs->cp0_epc;
1151 	unsigned long old31 = regs->regs[31];
1152 	enum ctx_state prev_state;
1153 	unsigned int opcode = 0;
1154 	int status = -1;
1155 
1156 	/*
1157 	 * Avoid any kernel code. Just emulate the R2 instruction
1158 	 * as quickly as possible.
1159 	 */
1160 	if (mipsr2_emulation && cpu_has_mips_r6 &&
1161 	    likely(user_mode(regs)) &&
1162 	    likely(get_user(opcode, epc) >= 0)) {
1163 		unsigned long fcr31 = 0;
1164 
1165 		status = mipsr2_decoder(regs, opcode, &fcr31);
1166 		switch (status) {
1167 		case 0:
1168 		case SIGEMT:
1169 			return;
1170 		case SIGILL:
1171 			goto no_r2_instr;
1172 		default:
1173 			process_fpemu_return(status,
1174 					     &current->thread.cp0_baduaddr,
1175 					     fcr31);
1176 			return;
1177 		}
1178 	}
1179 
1180 no_r2_instr:
1181 
1182 	prev_state = exception_enter();
1183 	current->thread.trap_nr = (regs->cp0_cause >> 2) & 0x1f;
1184 
1185 	if (notify_die(DIE_RI, "RI Fault", regs, 0, current->thread.trap_nr,
1186 		       SIGILL) == NOTIFY_STOP)
1187 		goto out;
1188 
1189 	die_if_kernel("Reserved instruction in kernel code", regs);
1190 
1191 	if (unlikely(compute_return_epc(regs) < 0))
1192 		goto out;
1193 
1194 	if (!get_isa16_mode(regs->cp0_epc)) {
1195 		if (unlikely(get_user(opcode, epc) < 0))
1196 			status = SIGSEGV;
1197 
1198 		if (!cpu_has_llsc && status < 0)
1199 			status = simulate_llsc(regs, opcode);
1200 
1201 		if (status < 0)
1202 			status = simulate_rdhwr_normal(regs, opcode);
1203 
1204 		if (status < 0)
1205 			status = simulate_sync(regs, opcode);
1206 
1207 		if (status < 0)
1208 			status = simulate_fp(regs, opcode, old_epc, old31);
1209 
1210 #ifdef CONFIG_CPU_LOONGSON3_CPUCFG_EMULATION
1211 		if (status < 0)
1212 			status = simulate_loongson3_cpucfg(regs, opcode);
1213 #endif
1214 	} else if (cpu_has_mmips) {
1215 		unsigned short mmop[2] = { 0 };
1216 
1217 		if (unlikely(get_user(mmop[0], (u16 __user *)epc + 0) < 0))
1218 			status = SIGSEGV;
1219 		if (unlikely(get_user(mmop[1], (u16 __user *)epc + 1) < 0))
1220 			status = SIGSEGV;
1221 		opcode = mmop[0];
1222 		opcode = (opcode << 16) | mmop[1];
1223 
1224 		if (status < 0)
1225 			status = simulate_rdhwr_mm(regs, opcode);
1226 	}
1227 
1228 	if (status < 0)
1229 		status = SIGILL;
1230 
1231 	if (unlikely(status > 0)) {
1232 		regs->cp0_epc = old_epc;		/* Undo skip-over.  */
1233 		regs->regs[31] = old31;
1234 		force_sig(status);
1235 	}
1236 
1237 out:
1238 	exception_exit(prev_state);
1239 }
1240 
1241 /*
1242  * No lock; only written during early bootup by CPU 0.
1243  */
1244 static RAW_NOTIFIER_HEAD(cu2_chain);
1245 
1246 int __ref register_cu2_notifier(struct notifier_block *nb)
1247 {
1248 	return raw_notifier_chain_register(&cu2_chain, nb);
1249 }
1250 
1251 int cu2_notifier_call_chain(unsigned long val, void *v)
1252 {
1253 	return raw_notifier_call_chain(&cu2_chain, val, v);
1254 }
1255 
1256 static int default_cu2_call(struct notifier_block *nfb, unsigned long action,
1257 	void *data)
1258 {
1259 	struct pt_regs *regs = data;
1260 
1261 	die_if_kernel("COP2: Unhandled kernel unaligned access or invalid "
1262 			      "instruction", regs);
1263 	force_sig(SIGILL);
1264 
1265 	return NOTIFY_OK;
1266 }
1267 
1268 #ifdef CONFIG_MIPS_FP_SUPPORT
1269 
1270 static int enable_restore_fp_context(int msa)
1271 {
1272 	int err, was_fpu_owner, prior_msa;
1273 	bool first_fp;
1274 
1275 	/* Initialize context if it hasn't been used already */
1276 	first_fp = init_fp_ctx(current);
1277 
1278 	if (first_fp) {
1279 		preempt_disable();
1280 		err = own_fpu_inatomic(1);
1281 		if (msa && !err) {
1282 			enable_msa();
1283 			set_thread_flag(TIF_USEDMSA);
1284 			set_thread_flag(TIF_MSA_CTX_LIVE);
1285 		}
1286 		preempt_enable();
1287 		return err;
1288 	}
1289 
1290 	/*
1291 	 * This task has formerly used the FP context.
1292 	 *
1293 	 * If this thread has no live MSA vector context then we can simply
1294 	 * restore the scalar FP context. If it has live MSA vector context
1295 	 * (that is, it has or may have used MSA since last performing a
1296 	 * function call) then we'll need to restore the vector context. This
1297 	 * applies even if we're currently only executing a scalar FP
1298 	 * instruction. This is because if we were to later execute an MSA
1299 	 * instruction then we'd either have to:
1300 	 *
1301 	 *  - Restore the vector context & clobber any registers modified by
1302 	 *    scalar FP instructions between now & then.
1303 	 *
1304 	 * or
1305 	 *
1306 	 *  - Not restore the vector context & lose the most significant bits
1307 	 *    of all vector registers.
1308 	 *
1309 	 * Neither of those options is acceptable. We cannot restore the least
1310 	 * significant bits of the registers now & only restore the most
1311 	 * significant bits later because the most significant bits of any
1312 	 * vector registers whose aliased FP register is modified now will have
1313 	 * been zeroed. We'd have no way to know that when restoring the vector
1314 	 * context & thus may load an outdated value for the most significant
1315 	 * bits of a vector register.
1316 	 */
1317 	if (!msa && !thread_msa_context_live())
1318 		return own_fpu(1);
1319 
1320 	/*
1321 	 * This task is using or has previously used MSA. Thus we require
1322 	 * that Status.FR == 1.
1323 	 */
1324 	preempt_disable();
1325 	was_fpu_owner = is_fpu_owner();
1326 	err = own_fpu_inatomic(0);
1327 	if (err)
1328 		goto out;
1329 
1330 	enable_msa();
1331 	write_msa_csr(current->thread.fpu.msacsr);
1332 	set_thread_flag(TIF_USEDMSA);
1333 
1334 	/*
1335 	 * If this is the first time that the task is using MSA and it has
1336 	 * previously used scalar FP in this time slice then we already nave
1337 	 * FP context which we shouldn't clobber. We do however need to clear
1338 	 * the upper 64b of each vector register so that this task has no
1339 	 * opportunity to see data left behind by another.
1340 	 */
1341 	prior_msa = test_and_set_thread_flag(TIF_MSA_CTX_LIVE);
1342 	if (!prior_msa && was_fpu_owner) {
1343 		init_msa_upper();
1344 
1345 		goto out;
1346 	}
1347 
1348 	if (!prior_msa) {
1349 		/*
1350 		 * Restore the least significant 64b of each vector register
1351 		 * from the existing scalar FP context.
1352 		 */
1353 		_restore_fp(current);
1354 
1355 		/*
1356 		 * The task has not formerly used MSA, so clear the upper 64b
1357 		 * of each vector register such that it cannot see data left
1358 		 * behind by another task.
1359 		 */
1360 		init_msa_upper();
1361 	} else {
1362 		/* We need to restore the vector context. */
1363 		restore_msa(current);
1364 
1365 		/* Restore the scalar FP control & status register */
1366 		if (!was_fpu_owner)
1367 			write_32bit_cp1_register(CP1_STATUS,
1368 						 current->thread.fpu.fcr31);
1369 	}
1370 
1371 out:
1372 	preempt_enable();
1373 
1374 	return 0;
1375 }
1376 
1377 #else /* !CONFIG_MIPS_FP_SUPPORT */
1378 
1379 static int enable_restore_fp_context(int msa)
1380 {
1381 	return SIGILL;
1382 }
1383 
1384 #endif /* CONFIG_MIPS_FP_SUPPORT */
1385 
1386 asmlinkage void do_cpu(struct pt_regs *regs)
1387 {
1388 	enum ctx_state prev_state;
1389 	unsigned int __user *epc;
1390 	unsigned long old_epc, old31;
1391 	unsigned int opcode;
1392 	unsigned int cpid;
1393 	int status;
1394 
1395 	prev_state = exception_enter();
1396 	cpid = (regs->cp0_cause >> CAUSEB_CE) & 3;
1397 
1398 	if (cpid != 2)
1399 		die_if_kernel("do_cpu invoked from kernel context!", regs);
1400 
1401 	switch (cpid) {
1402 	case 0:
1403 		epc = (unsigned int __user *)exception_epc(regs);
1404 		old_epc = regs->cp0_epc;
1405 		old31 = regs->regs[31];
1406 		opcode = 0;
1407 		status = -1;
1408 
1409 		if (unlikely(compute_return_epc(regs) < 0))
1410 			break;
1411 
1412 		if (!get_isa16_mode(regs->cp0_epc)) {
1413 			if (unlikely(get_user(opcode, epc) < 0))
1414 				status = SIGSEGV;
1415 
1416 			if (!cpu_has_llsc && status < 0)
1417 				status = simulate_llsc(regs, opcode);
1418 		}
1419 
1420 		if (status < 0)
1421 			status = SIGILL;
1422 
1423 		if (unlikely(status > 0)) {
1424 			regs->cp0_epc = old_epc;	/* Undo skip-over.  */
1425 			regs->regs[31] = old31;
1426 			force_sig(status);
1427 		}
1428 
1429 		break;
1430 
1431 #ifdef CONFIG_MIPS_FP_SUPPORT
1432 	case 3:
1433 		/*
1434 		 * The COP3 opcode space and consequently the CP0.Status.CU3
1435 		 * bit and the CP0.Cause.CE=3 encoding have been removed as
1436 		 * of the MIPS III ISA.  From the MIPS IV and MIPS32r2 ISAs
1437 		 * up the space has been reused for COP1X instructions, that
1438 		 * are enabled by the CP0.Status.CU1 bit and consequently
1439 		 * use the CP0.Cause.CE=1 encoding for Coprocessor Unusable
1440 		 * exceptions.  Some FPU-less processors that implement one
1441 		 * of these ISAs however use this code erroneously for COP1X
1442 		 * instructions.  Therefore we redirect this trap to the FP
1443 		 * emulator too.
1444 		 */
1445 		if (raw_cpu_has_fpu || !cpu_has_mips_4_5_64_r2_r6) {
1446 			force_sig(SIGILL);
1447 			break;
1448 		}
1449 		fallthrough;
1450 	case 1: {
1451 		void __user *fault_addr;
1452 		unsigned long fcr31;
1453 		int err, sig;
1454 
1455 		err = enable_restore_fp_context(0);
1456 
1457 		if (raw_cpu_has_fpu && !err)
1458 			break;
1459 
1460 		sig = fpu_emulator_cop1Handler(regs, &current->thread.fpu, 0,
1461 					       &fault_addr);
1462 
1463 		/*
1464 		 * We can't allow the emulated instruction to leave
1465 		 * any enabled Cause bits set in $fcr31.
1466 		 */
1467 		fcr31 = mask_fcr31_x(current->thread.fpu.fcr31);
1468 		current->thread.fpu.fcr31 &= ~fcr31;
1469 
1470 		/* Send a signal if required.  */
1471 		if (!process_fpemu_return(sig, fault_addr, fcr31) && !err)
1472 			mt_ase_fp_affinity();
1473 
1474 		break;
1475 	}
1476 #else /* CONFIG_MIPS_FP_SUPPORT */
1477 	case 1:
1478 	case 3:
1479 		force_sig(SIGILL);
1480 		break;
1481 #endif /* CONFIG_MIPS_FP_SUPPORT */
1482 
1483 	case 2:
1484 		raw_notifier_call_chain(&cu2_chain, CU2_EXCEPTION, regs);
1485 		break;
1486 	}
1487 
1488 	exception_exit(prev_state);
1489 }
1490 
1491 asmlinkage void do_msa_fpe(struct pt_regs *regs, unsigned int msacsr)
1492 {
1493 	enum ctx_state prev_state;
1494 
1495 	prev_state = exception_enter();
1496 	current->thread.trap_nr = (regs->cp0_cause >> 2) & 0x1f;
1497 	if (notify_die(DIE_MSAFP, "MSA FP exception", regs, 0,
1498 		       current->thread.trap_nr, SIGFPE) == NOTIFY_STOP)
1499 		goto out;
1500 
1501 	/* Clear MSACSR.Cause before enabling interrupts */
1502 	write_msa_csr(msacsr & ~MSA_CSR_CAUSEF);
1503 	local_irq_enable();
1504 
1505 	die_if_kernel("do_msa_fpe invoked from kernel context!", regs);
1506 	force_sig(SIGFPE);
1507 out:
1508 	exception_exit(prev_state);
1509 }
1510 
1511 asmlinkage void do_msa(struct pt_regs *regs)
1512 {
1513 	enum ctx_state prev_state;
1514 	int err;
1515 
1516 	prev_state = exception_enter();
1517 
1518 	if (!cpu_has_msa || test_thread_flag(TIF_32BIT_FPREGS)) {
1519 		force_sig(SIGILL);
1520 		goto out;
1521 	}
1522 
1523 	die_if_kernel("do_msa invoked from kernel context!", regs);
1524 
1525 	err = enable_restore_fp_context(1);
1526 	if (err)
1527 		force_sig(SIGILL);
1528 out:
1529 	exception_exit(prev_state);
1530 }
1531 
1532 asmlinkage void do_mdmx(struct pt_regs *regs)
1533 {
1534 	enum ctx_state prev_state;
1535 
1536 	prev_state = exception_enter();
1537 	force_sig(SIGILL);
1538 	exception_exit(prev_state);
1539 }
1540 
1541 /*
1542  * Called with interrupts disabled.
1543  */
1544 asmlinkage void do_watch(struct pt_regs *regs)
1545 {
1546 	enum ctx_state prev_state;
1547 
1548 	prev_state = exception_enter();
1549 	/*
1550 	 * Clear WP (bit 22) bit of cause register so we don't loop
1551 	 * forever.
1552 	 */
1553 	clear_c0_cause(CAUSEF_WP);
1554 
1555 	/*
1556 	 * If the current thread has the watch registers loaded, save
1557 	 * their values and send SIGTRAP.  Otherwise another thread
1558 	 * left the registers set, clear them and continue.
1559 	 */
1560 	if (test_tsk_thread_flag(current, TIF_LOAD_WATCH)) {
1561 		mips_read_watch_registers();
1562 		local_irq_enable();
1563 		force_sig_fault(SIGTRAP, TRAP_HWBKPT, NULL);
1564 	} else {
1565 		mips_clear_watch_registers();
1566 		local_irq_enable();
1567 	}
1568 	exception_exit(prev_state);
1569 }
1570 
1571 asmlinkage void do_mcheck(struct pt_regs *regs)
1572 {
1573 	int multi_match = regs->cp0_status & ST0_TS;
1574 	enum ctx_state prev_state;
1575 	mm_segment_t old_fs = get_fs();
1576 
1577 	prev_state = exception_enter();
1578 	show_regs(regs);
1579 
1580 	if (multi_match) {
1581 		dump_tlb_regs();
1582 		pr_info("\n");
1583 		dump_tlb_all();
1584 	}
1585 
1586 	if (!user_mode(regs))
1587 		set_fs(KERNEL_DS);
1588 
1589 	show_code((unsigned int __user *) regs->cp0_epc);
1590 
1591 	set_fs(old_fs);
1592 
1593 	/*
1594 	 * Some chips may have other causes of machine check (e.g. SB1
1595 	 * graduation timer)
1596 	 */
1597 	panic("Caught Machine Check exception - %scaused by multiple "
1598 	      "matching entries in the TLB.",
1599 	      (multi_match) ? "" : "not ");
1600 }
1601 
1602 asmlinkage void do_mt(struct pt_regs *regs)
1603 {
1604 	int subcode;
1605 
1606 	subcode = (read_vpe_c0_vpecontrol() & VPECONTROL_EXCPT)
1607 			>> VPECONTROL_EXCPT_SHIFT;
1608 	switch (subcode) {
1609 	case 0:
1610 		printk(KERN_DEBUG "Thread Underflow\n");
1611 		break;
1612 	case 1:
1613 		printk(KERN_DEBUG "Thread Overflow\n");
1614 		break;
1615 	case 2:
1616 		printk(KERN_DEBUG "Invalid YIELD Qualifier\n");
1617 		break;
1618 	case 3:
1619 		printk(KERN_DEBUG "Gating Storage Exception\n");
1620 		break;
1621 	case 4:
1622 		printk(KERN_DEBUG "YIELD Scheduler Exception\n");
1623 		break;
1624 	case 5:
1625 		printk(KERN_DEBUG "Gating Storage Scheduler Exception\n");
1626 		break;
1627 	default:
1628 		printk(KERN_DEBUG "*** UNKNOWN THREAD EXCEPTION %d ***\n",
1629 			subcode);
1630 		break;
1631 	}
1632 	die_if_kernel("MIPS MT Thread exception in kernel", regs);
1633 
1634 	force_sig(SIGILL);
1635 }
1636 
1637 
1638 asmlinkage void do_dsp(struct pt_regs *regs)
1639 {
1640 	if (cpu_has_dsp)
1641 		panic("Unexpected DSP exception");
1642 
1643 	force_sig(SIGILL);
1644 }
1645 
1646 asmlinkage void do_reserved(struct pt_regs *regs)
1647 {
1648 	/*
1649 	 * Game over - no way to handle this if it ever occurs.	 Most probably
1650 	 * caused by a new unknown cpu type or after another deadly
1651 	 * hard/software error.
1652 	 */
1653 	show_regs(regs);
1654 	panic("Caught reserved exception %ld - should not happen.",
1655 	      (regs->cp0_cause & 0x7f) >> 2);
1656 }
1657 
1658 static int __initdata l1parity = 1;
1659 static int __init nol1parity(char *s)
1660 {
1661 	l1parity = 0;
1662 	return 1;
1663 }
1664 __setup("nol1par", nol1parity);
1665 static int __initdata l2parity = 1;
1666 static int __init nol2parity(char *s)
1667 {
1668 	l2parity = 0;
1669 	return 1;
1670 }
1671 __setup("nol2par", nol2parity);
1672 
1673 /*
1674  * Some MIPS CPUs can enable/disable for cache parity detection, but do
1675  * it different ways.
1676  */
1677 static inline void parity_protection_init(void)
1678 {
1679 #define ERRCTL_PE	0x80000000
1680 #define ERRCTL_L2P	0x00800000
1681 
1682 	if (mips_cm_revision() >= CM_REV_CM3) {
1683 		ulong gcr_ectl, cp0_ectl;
1684 
1685 		/*
1686 		 * With CM3 systems we need to ensure that the L1 & L2
1687 		 * parity enables are set to the same value, since this
1688 		 * is presumed by the hardware engineers.
1689 		 *
1690 		 * If the user disabled either of L1 or L2 ECC checking,
1691 		 * disable both.
1692 		 */
1693 		l1parity &= l2parity;
1694 		l2parity &= l1parity;
1695 
1696 		/* Probe L1 ECC support */
1697 		cp0_ectl = read_c0_ecc();
1698 		write_c0_ecc(cp0_ectl | ERRCTL_PE);
1699 		back_to_back_c0_hazard();
1700 		cp0_ectl = read_c0_ecc();
1701 
1702 		/* Probe L2 ECC support */
1703 		gcr_ectl = read_gcr_err_control();
1704 
1705 		if (!(gcr_ectl & CM_GCR_ERR_CONTROL_L2_ECC_SUPPORT) ||
1706 		    !(cp0_ectl & ERRCTL_PE)) {
1707 			/*
1708 			 * One of L1 or L2 ECC checking isn't supported,
1709 			 * so we cannot enable either.
1710 			 */
1711 			l1parity = l2parity = 0;
1712 		}
1713 
1714 		/* Configure L1 ECC checking */
1715 		if (l1parity)
1716 			cp0_ectl |= ERRCTL_PE;
1717 		else
1718 			cp0_ectl &= ~ERRCTL_PE;
1719 		write_c0_ecc(cp0_ectl);
1720 		back_to_back_c0_hazard();
1721 		WARN_ON(!!(read_c0_ecc() & ERRCTL_PE) != l1parity);
1722 
1723 		/* Configure L2 ECC checking */
1724 		if (l2parity)
1725 			gcr_ectl |= CM_GCR_ERR_CONTROL_L2_ECC_EN;
1726 		else
1727 			gcr_ectl &= ~CM_GCR_ERR_CONTROL_L2_ECC_EN;
1728 		write_gcr_err_control(gcr_ectl);
1729 		gcr_ectl = read_gcr_err_control();
1730 		gcr_ectl &= CM_GCR_ERR_CONTROL_L2_ECC_EN;
1731 		WARN_ON(!!gcr_ectl != l2parity);
1732 
1733 		pr_info("Cache parity protection %sabled\n",
1734 			l1parity ? "en" : "dis");
1735 		return;
1736 	}
1737 
1738 	switch (current_cpu_type()) {
1739 	case CPU_24K:
1740 	case CPU_34K:
1741 	case CPU_74K:
1742 	case CPU_1004K:
1743 	case CPU_1074K:
1744 	case CPU_INTERAPTIV:
1745 	case CPU_PROAPTIV:
1746 	case CPU_P5600:
1747 	case CPU_QEMU_GENERIC:
1748 	case CPU_P6600:
1749 		{
1750 			unsigned long errctl;
1751 			unsigned int l1parity_present, l2parity_present;
1752 
1753 			errctl = read_c0_ecc();
1754 			errctl &= ~(ERRCTL_PE|ERRCTL_L2P);
1755 
1756 			/* probe L1 parity support */
1757 			write_c0_ecc(errctl | ERRCTL_PE);
1758 			back_to_back_c0_hazard();
1759 			l1parity_present = (read_c0_ecc() & ERRCTL_PE);
1760 
1761 			/* probe L2 parity support */
1762 			write_c0_ecc(errctl|ERRCTL_L2P);
1763 			back_to_back_c0_hazard();
1764 			l2parity_present = (read_c0_ecc() & ERRCTL_L2P);
1765 
1766 			if (l1parity_present && l2parity_present) {
1767 				if (l1parity)
1768 					errctl |= ERRCTL_PE;
1769 				if (l1parity ^ l2parity)
1770 					errctl |= ERRCTL_L2P;
1771 			} else if (l1parity_present) {
1772 				if (l1parity)
1773 					errctl |= ERRCTL_PE;
1774 			} else if (l2parity_present) {
1775 				if (l2parity)
1776 					errctl |= ERRCTL_L2P;
1777 			} else {
1778 				/* No parity available */
1779 			}
1780 
1781 			printk(KERN_INFO "Writing ErrCtl register=%08lx\n", errctl);
1782 
1783 			write_c0_ecc(errctl);
1784 			back_to_back_c0_hazard();
1785 			errctl = read_c0_ecc();
1786 			printk(KERN_INFO "Readback ErrCtl register=%08lx\n", errctl);
1787 
1788 			if (l1parity_present)
1789 				printk(KERN_INFO "Cache parity protection %sabled\n",
1790 				       (errctl & ERRCTL_PE) ? "en" : "dis");
1791 
1792 			if (l2parity_present) {
1793 				if (l1parity_present && l1parity)
1794 					errctl ^= ERRCTL_L2P;
1795 				printk(KERN_INFO "L2 cache parity protection %sabled\n",
1796 				       (errctl & ERRCTL_L2P) ? "en" : "dis");
1797 			}
1798 		}
1799 		break;
1800 
1801 	case CPU_5KC:
1802 	case CPU_5KE:
1803 	case CPU_LOONGSON32:
1804 		write_c0_ecc(0x80000000);
1805 		back_to_back_c0_hazard();
1806 		/* Set the PE bit (bit 31) in the c0_errctl register. */
1807 		printk(KERN_INFO "Cache parity protection %sabled\n",
1808 		       (read_c0_ecc() & 0x80000000) ? "en" : "dis");
1809 		break;
1810 	case CPU_20KC:
1811 	case CPU_25KF:
1812 		/* Clear the DE bit (bit 16) in the c0_status register. */
1813 		printk(KERN_INFO "Enable cache parity protection for "
1814 		       "MIPS 20KC/25KF CPUs.\n");
1815 		clear_c0_status(ST0_DE);
1816 		break;
1817 	default:
1818 		break;
1819 	}
1820 }
1821 
1822 asmlinkage void cache_parity_error(void)
1823 {
1824 	const int field = 2 * sizeof(unsigned long);
1825 	unsigned int reg_val;
1826 
1827 	/* For the moment, report the problem and hang. */
1828 	printk("Cache error exception:\n");
1829 	printk("cp0_errorepc == %0*lx\n", field, read_c0_errorepc());
1830 	reg_val = read_c0_cacheerr();
1831 	printk("c0_cacheerr == %08x\n", reg_val);
1832 
1833 	printk("Decoded c0_cacheerr: %s cache fault in %s reference.\n",
1834 	       reg_val & (1<<30) ? "secondary" : "primary",
1835 	       reg_val & (1<<31) ? "data" : "insn");
1836 	if ((cpu_has_mips_r2_r6) &&
1837 	    ((current_cpu_data.processor_id & 0xff0000) == PRID_COMP_MIPS)) {
1838 		pr_err("Error bits: %s%s%s%s%s%s%s%s\n",
1839 			reg_val & (1<<29) ? "ED " : "",
1840 			reg_val & (1<<28) ? "ET " : "",
1841 			reg_val & (1<<27) ? "ES " : "",
1842 			reg_val & (1<<26) ? "EE " : "",
1843 			reg_val & (1<<25) ? "EB " : "",
1844 			reg_val & (1<<24) ? "EI " : "",
1845 			reg_val & (1<<23) ? "E1 " : "",
1846 			reg_val & (1<<22) ? "E0 " : "");
1847 	} else {
1848 		pr_err("Error bits: %s%s%s%s%s%s%s\n",
1849 			reg_val & (1<<29) ? "ED " : "",
1850 			reg_val & (1<<28) ? "ET " : "",
1851 			reg_val & (1<<26) ? "EE " : "",
1852 			reg_val & (1<<25) ? "EB " : "",
1853 			reg_val & (1<<24) ? "EI " : "",
1854 			reg_val & (1<<23) ? "E1 " : "",
1855 			reg_val & (1<<22) ? "E0 " : "");
1856 	}
1857 	printk("IDX: 0x%08x\n", reg_val & ((1<<22)-1));
1858 
1859 #if defined(CONFIG_CPU_MIPS32) || defined(CONFIG_CPU_MIPS64)
1860 	if (reg_val & (1<<22))
1861 		printk("DErrAddr0: 0x%0*lx\n", field, read_c0_derraddr0());
1862 
1863 	if (reg_val & (1<<23))
1864 		printk("DErrAddr1: 0x%0*lx\n", field, read_c0_derraddr1());
1865 #endif
1866 
1867 	panic("Can't handle the cache error!");
1868 }
1869 
1870 asmlinkage void do_ftlb(void)
1871 {
1872 	const int field = 2 * sizeof(unsigned long);
1873 	unsigned int reg_val;
1874 
1875 	/* For the moment, report the problem and hang. */
1876 	if ((cpu_has_mips_r2_r6) &&
1877 	    (((current_cpu_data.processor_id & 0xff0000) == PRID_COMP_MIPS) ||
1878 	    ((current_cpu_data.processor_id & 0xff0000) == PRID_COMP_LOONGSON))) {
1879 		pr_err("FTLB error exception, cp0_ecc=0x%08x:\n",
1880 		       read_c0_ecc());
1881 		pr_err("cp0_errorepc == %0*lx\n", field, read_c0_errorepc());
1882 		reg_val = read_c0_cacheerr();
1883 		pr_err("c0_cacheerr == %08x\n", reg_val);
1884 
1885 		if ((reg_val & 0xc0000000) == 0xc0000000) {
1886 			pr_err("Decoded c0_cacheerr: FTLB parity error\n");
1887 		} else {
1888 			pr_err("Decoded c0_cacheerr: %s cache fault in %s reference.\n",
1889 			       reg_val & (1<<30) ? "secondary" : "primary",
1890 			       reg_val & (1<<31) ? "data" : "insn");
1891 		}
1892 	} else {
1893 		pr_err("FTLB error exception\n");
1894 	}
1895 	/* Just print the cacheerr bits for now */
1896 	cache_parity_error();
1897 }
1898 
1899 /*
1900  * SDBBP EJTAG debug exception handler.
1901  * We skip the instruction and return to the next instruction.
1902  */
1903 void ejtag_exception_handler(struct pt_regs *regs)
1904 {
1905 	const int field = 2 * sizeof(unsigned long);
1906 	unsigned long depc, old_epc, old_ra;
1907 	unsigned int debug;
1908 
1909 	printk(KERN_DEBUG "SDBBP EJTAG debug exception - not handled yet, just ignored!\n");
1910 	depc = read_c0_depc();
1911 	debug = read_c0_debug();
1912 	printk(KERN_DEBUG "c0_depc = %0*lx, DEBUG = %08x\n", field, depc, debug);
1913 	if (debug & 0x80000000) {
1914 		/*
1915 		 * In branch delay slot.
1916 		 * We cheat a little bit here and use EPC to calculate the
1917 		 * debug return address (DEPC). EPC is restored after the
1918 		 * calculation.
1919 		 */
1920 		old_epc = regs->cp0_epc;
1921 		old_ra = regs->regs[31];
1922 		regs->cp0_epc = depc;
1923 		compute_return_epc(regs);
1924 		depc = regs->cp0_epc;
1925 		regs->cp0_epc = old_epc;
1926 		regs->regs[31] = old_ra;
1927 	} else
1928 		depc += 4;
1929 	write_c0_depc(depc);
1930 
1931 #if 0
1932 	printk(KERN_DEBUG "\n\n----- Enable EJTAG single stepping ----\n\n");
1933 	write_c0_debug(debug | 0x100);
1934 #endif
1935 }
1936 
1937 /*
1938  * NMI exception handler.
1939  * No lock; only written during early bootup by CPU 0.
1940  */
1941 static RAW_NOTIFIER_HEAD(nmi_chain);
1942 
1943 int register_nmi_notifier(struct notifier_block *nb)
1944 {
1945 	return raw_notifier_chain_register(&nmi_chain, nb);
1946 }
1947 
1948 void __noreturn nmi_exception_handler(struct pt_regs *regs)
1949 {
1950 	char str[100];
1951 
1952 	nmi_enter();
1953 	raw_notifier_call_chain(&nmi_chain, 0, regs);
1954 	bust_spinlocks(1);
1955 	snprintf(str, 100, "CPU%d NMI taken, CP0_EPC=%lx\n",
1956 		 smp_processor_id(), regs->cp0_epc);
1957 	regs->cp0_epc = read_c0_errorepc();
1958 	die(str, regs);
1959 	nmi_exit();
1960 }
1961 
1962 #define VECTORSPACING 0x100	/* for EI/VI mode */
1963 
1964 unsigned long ebase;
1965 EXPORT_SYMBOL_GPL(ebase);
1966 unsigned long exception_handlers[32];
1967 unsigned long vi_handlers[64];
1968 
1969 void __init *set_except_vector(int n, void *addr)
1970 {
1971 	unsigned long handler = (unsigned long) addr;
1972 	unsigned long old_handler;
1973 
1974 #ifdef CONFIG_CPU_MICROMIPS
1975 	/*
1976 	 * Only the TLB handlers are cache aligned with an even
1977 	 * address. All other handlers are on an odd address and
1978 	 * require no modification. Otherwise, MIPS32 mode will
1979 	 * be entered when handling any TLB exceptions. That
1980 	 * would be bad...since we must stay in microMIPS mode.
1981 	 */
1982 	if (!(handler & 0x1))
1983 		handler |= 1;
1984 #endif
1985 	old_handler = xchg(&exception_handlers[n], handler);
1986 
1987 	if (n == 0 && cpu_has_divec) {
1988 #ifdef CONFIG_CPU_MICROMIPS
1989 		unsigned long jump_mask = ~((1 << 27) - 1);
1990 #else
1991 		unsigned long jump_mask = ~((1 << 28) - 1);
1992 #endif
1993 		u32 *buf = (u32 *)(ebase + 0x200);
1994 		unsigned int k0 = 26;
1995 		if ((handler & jump_mask) == ((ebase + 0x200) & jump_mask)) {
1996 			uasm_i_j(&buf, handler & ~jump_mask);
1997 			uasm_i_nop(&buf);
1998 		} else {
1999 			UASM_i_LA(&buf, k0, handler);
2000 			uasm_i_jr(&buf, k0);
2001 			uasm_i_nop(&buf);
2002 		}
2003 		local_flush_icache_range(ebase + 0x200, (unsigned long)buf);
2004 	}
2005 	return (void *)old_handler;
2006 }
2007 
2008 static void do_default_vi(void)
2009 {
2010 	show_regs(get_irq_regs());
2011 	panic("Caught unexpected vectored interrupt.");
2012 }
2013 
2014 static void *set_vi_srs_handler(int n, vi_handler_t addr, int srs)
2015 {
2016 	unsigned long handler;
2017 	unsigned long old_handler = vi_handlers[n];
2018 	int srssets = current_cpu_data.srsets;
2019 	u16 *h;
2020 	unsigned char *b;
2021 
2022 	BUG_ON(!cpu_has_veic && !cpu_has_vint);
2023 
2024 	if (addr == NULL) {
2025 		handler = (unsigned long) do_default_vi;
2026 		srs = 0;
2027 	} else
2028 		handler = (unsigned long) addr;
2029 	vi_handlers[n] = handler;
2030 
2031 	b = (unsigned char *)(ebase + 0x200 + n*VECTORSPACING);
2032 
2033 	if (srs >= srssets)
2034 		panic("Shadow register set %d not supported", srs);
2035 
2036 	if (cpu_has_veic) {
2037 		if (board_bind_eic_interrupt)
2038 			board_bind_eic_interrupt(n, srs);
2039 	} else if (cpu_has_vint) {
2040 		/* SRSMap is only defined if shadow sets are implemented */
2041 		if (srssets > 1)
2042 			change_c0_srsmap(0xf << n*4, srs << n*4);
2043 	}
2044 
2045 	if (srs == 0) {
2046 		/*
2047 		 * If no shadow set is selected then use the default handler
2048 		 * that does normal register saving and standard interrupt exit
2049 		 */
2050 		extern char except_vec_vi, except_vec_vi_lui;
2051 		extern char except_vec_vi_ori, except_vec_vi_end;
2052 		extern char rollback_except_vec_vi;
2053 		char *vec_start = using_rollback_handler() ?
2054 			&rollback_except_vec_vi : &except_vec_vi;
2055 #if defined(CONFIG_CPU_MICROMIPS) || defined(CONFIG_CPU_BIG_ENDIAN)
2056 		const int lui_offset = &except_vec_vi_lui - vec_start + 2;
2057 		const int ori_offset = &except_vec_vi_ori - vec_start + 2;
2058 #else
2059 		const int lui_offset = &except_vec_vi_lui - vec_start;
2060 		const int ori_offset = &except_vec_vi_ori - vec_start;
2061 #endif
2062 		const int handler_len = &except_vec_vi_end - vec_start;
2063 
2064 		if (handler_len > VECTORSPACING) {
2065 			/*
2066 			 * Sigh... panicing won't help as the console
2067 			 * is probably not configured :(
2068 			 */
2069 			panic("VECTORSPACING too small");
2070 		}
2071 
2072 		set_handler(((unsigned long)b - ebase), vec_start,
2073 #ifdef CONFIG_CPU_MICROMIPS
2074 				(handler_len - 1));
2075 #else
2076 				handler_len);
2077 #endif
2078 		h = (u16 *)(b + lui_offset);
2079 		*h = (handler >> 16) & 0xffff;
2080 		h = (u16 *)(b + ori_offset);
2081 		*h = (handler & 0xffff);
2082 		local_flush_icache_range((unsigned long)b,
2083 					 (unsigned long)(b+handler_len));
2084 	}
2085 	else {
2086 		/*
2087 		 * In other cases jump directly to the interrupt handler. It
2088 		 * is the handler's responsibility to save registers if required
2089 		 * (eg hi/lo) and return from the exception using "eret".
2090 		 */
2091 		u32 insn;
2092 
2093 		h = (u16 *)b;
2094 		/* j handler */
2095 #ifdef CONFIG_CPU_MICROMIPS
2096 		insn = 0xd4000000 | (((u32)handler & 0x07ffffff) >> 1);
2097 #else
2098 		insn = 0x08000000 | (((u32)handler & 0x0fffffff) >> 2);
2099 #endif
2100 		h[0] = (insn >> 16) & 0xffff;
2101 		h[1] = insn & 0xffff;
2102 		h[2] = 0;
2103 		h[3] = 0;
2104 		local_flush_icache_range((unsigned long)b,
2105 					 (unsigned long)(b+8));
2106 	}
2107 
2108 	return (void *)old_handler;
2109 }
2110 
2111 void *set_vi_handler(int n, vi_handler_t addr)
2112 {
2113 	return set_vi_srs_handler(n, addr, 0);
2114 }
2115 
2116 extern void tlb_init(void);
2117 
2118 /*
2119  * Timer interrupt
2120  */
2121 int cp0_compare_irq;
2122 EXPORT_SYMBOL_GPL(cp0_compare_irq);
2123 int cp0_compare_irq_shift;
2124 
2125 /*
2126  * Performance counter IRQ or -1 if shared with timer
2127  */
2128 int cp0_perfcount_irq;
2129 EXPORT_SYMBOL_GPL(cp0_perfcount_irq);
2130 
2131 /*
2132  * Fast debug channel IRQ or -1 if not present
2133  */
2134 int cp0_fdc_irq;
2135 EXPORT_SYMBOL_GPL(cp0_fdc_irq);
2136 
2137 static int noulri;
2138 
2139 static int __init ulri_disable(char *s)
2140 {
2141 	pr_info("Disabling ulri\n");
2142 	noulri = 1;
2143 
2144 	return 1;
2145 }
2146 __setup("noulri", ulri_disable);
2147 
2148 /* configure STATUS register */
2149 static void configure_status(void)
2150 {
2151 	/*
2152 	 * Disable coprocessors and select 32-bit or 64-bit addressing
2153 	 * and the 16/32 or 32/32 FPR register model.  Reset the BEV
2154 	 * flag that some firmware may have left set and the TS bit (for
2155 	 * IP27).  Set XX for ISA IV code to work.
2156 	 */
2157 	unsigned int status_set = ST0_CU0;
2158 #ifdef CONFIG_64BIT
2159 	status_set |= ST0_FR|ST0_KX|ST0_SX|ST0_UX;
2160 #endif
2161 	if (current_cpu_data.isa_level & MIPS_CPU_ISA_IV)
2162 		status_set |= ST0_XX;
2163 	if (cpu_has_dsp)
2164 		status_set |= ST0_MX;
2165 
2166 	change_c0_status(ST0_CU|ST0_MX|ST0_RE|ST0_FR|ST0_BEV|ST0_TS|ST0_KX|ST0_SX|ST0_UX,
2167 			 status_set);
2168 }
2169 
2170 unsigned int hwrena;
2171 EXPORT_SYMBOL_GPL(hwrena);
2172 
2173 /* configure HWRENA register */
2174 static void configure_hwrena(void)
2175 {
2176 	hwrena = cpu_hwrena_impl_bits;
2177 
2178 	if (cpu_has_mips_r2_r6)
2179 		hwrena |= MIPS_HWRENA_CPUNUM |
2180 			  MIPS_HWRENA_SYNCISTEP |
2181 			  MIPS_HWRENA_CC |
2182 			  MIPS_HWRENA_CCRES;
2183 
2184 	if (!noulri && cpu_has_userlocal)
2185 		hwrena |= MIPS_HWRENA_ULR;
2186 
2187 	if (hwrena)
2188 		write_c0_hwrena(hwrena);
2189 }
2190 
2191 static void configure_exception_vector(void)
2192 {
2193 	if (cpu_has_mips_r2_r6) {
2194 		unsigned long sr = set_c0_status(ST0_BEV);
2195 		/* If available, use WG to set top bits of EBASE */
2196 		if (cpu_has_ebase_wg) {
2197 #ifdef CONFIG_64BIT
2198 			write_c0_ebase_64(ebase | MIPS_EBASE_WG);
2199 #else
2200 			write_c0_ebase(ebase | MIPS_EBASE_WG);
2201 #endif
2202 		}
2203 		write_c0_ebase(ebase);
2204 		write_c0_status(sr);
2205 	}
2206 	if (cpu_has_veic || cpu_has_vint) {
2207 		/* Setting vector spacing enables EI/VI mode  */
2208 		change_c0_intctl(0x3e0, VECTORSPACING);
2209 	}
2210 	if (cpu_has_divec) {
2211 		if (cpu_has_mipsmt) {
2212 			unsigned int vpflags = dvpe();
2213 			set_c0_cause(CAUSEF_IV);
2214 			evpe(vpflags);
2215 		} else
2216 			set_c0_cause(CAUSEF_IV);
2217 	}
2218 }
2219 
2220 void per_cpu_trap_init(bool is_boot_cpu)
2221 {
2222 	unsigned int cpu = smp_processor_id();
2223 
2224 	configure_status();
2225 	configure_hwrena();
2226 
2227 	configure_exception_vector();
2228 
2229 	/*
2230 	 * Before R2 both interrupt numbers were fixed to 7, so on R2 only:
2231 	 *
2232 	 *  o read IntCtl.IPTI to determine the timer interrupt
2233 	 *  o read IntCtl.IPPCI to determine the performance counter interrupt
2234 	 *  o read IntCtl.IPFDC to determine the fast debug channel interrupt
2235 	 */
2236 	if (cpu_has_mips_r2_r6) {
2237 		cp0_compare_irq_shift = CAUSEB_TI - CAUSEB_IP;
2238 		cp0_compare_irq = (read_c0_intctl() >> INTCTLB_IPTI) & 7;
2239 		cp0_perfcount_irq = (read_c0_intctl() >> INTCTLB_IPPCI) & 7;
2240 		cp0_fdc_irq = (read_c0_intctl() >> INTCTLB_IPFDC) & 7;
2241 		if (!cp0_fdc_irq)
2242 			cp0_fdc_irq = -1;
2243 
2244 	} else {
2245 		cp0_compare_irq = CP0_LEGACY_COMPARE_IRQ;
2246 		cp0_compare_irq_shift = CP0_LEGACY_PERFCNT_IRQ;
2247 		cp0_perfcount_irq = -1;
2248 		cp0_fdc_irq = -1;
2249 	}
2250 
2251 	if (cpu_has_mmid)
2252 		cpu_data[cpu].asid_cache = 0;
2253 	else if (!cpu_data[cpu].asid_cache)
2254 		cpu_data[cpu].asid_cache = asid_first_version(cpu);
2255 
2256 	mmgrab(&init_mm);
2257 	current->active_mm = &init_mm;
2258 	BUG_ON(current->mm);
2259 	enter_lazy_tlb(&init_mm, current);
2260 
2261 	/* Boot CPU's cache setup in setup_arch(). */
2262 	if (!is_boot_cpu)
2263 		cpu_cache_init();
2264 	tlb_init();
2265 	TLBMISS_HANDLER_SETUP();
2266 }
2267 
2268 /* Install CPU exception handler */
2269 void set_handler(unsigned long offset, void *addr, unsigned long size)
2270 {
2271 #ifdef CONFIG_CPU_MICROMIPS
2272 	memcpy((void *)(ebase + offset), ((unsigned char *)addr - 1), size);
2273 #else
2274 	memcpy((void *)(ebase + offset), addr, size);
2275 #endif
2276 	local_flush_icache_range(ebase + offset, ebase + offset + size);
2277 }
2278 
2279 static const char panic_null_cerr[] =
2280 	"Trying to set NULL cache error exception handler\n";
2281 
2282 /*
2283  * Install uncached CPU exception handler.
2284  * This is suitable only for the cache error exception which is the only
2285  * exception handler that is being run uncached.
2286  */
2287 void set_uncached_handler(unsigned long offset, void *addr,
2288 	unsigned long size)
2289 {
2290 	unsigned long uncached_ebase = CKSEG1ADDR(ebase);
2291 
2292 	if (!addr)
2293 		panic(panic_null_cerr);
2294 
2295 	memcpy((void *)(uncached_ebase + offset), addr, size);
2296 }
2297 
2298 static int __initdata rdhwr_noopt;
2299 static int __init set_rdhwr_noopt(char *str)
2300 {
2301 	rdhwr_noopt = 1;
2302 	return 1;
2303 }
2304 
2305 __setup("rdhwr_noopt", set_rdhwr_noopt);
2306 
2307 void __init trap_init(void)
2308 {
2309 	extern char except_vec3_generic;
2310 	extern char except_vec4;
2311 	extern char except_vec3_r4000;
2312 	unsigned long i, vec_size;
2313 	phys_addr_t ebase_pa;
2314 
2315 	check_wait();
2316 
2317 	if (!cpu_has_mips_r2_r6) {
2318 		ebase = CAC_BASE;
2319 		ebase_pa = virt_to_phys((void *)ebase);
2320 		vec_size = 0x400;
2321 
2322 		memblock_reserve(ebase_pa, vec_size);
2323 	} else {
2324 		if (cpu_has_veic || cpu_has_vint)
2325 			vec_size = 0x200 + VECTORSPACING*64;
2326 		else
2327 			vec_size = PAGE_SIZE;
2328 
2329 		ebase_pa = memblock_phys_alloc(vec_size, 1 << fls(vec_size));
2330 		if (!ebase_pa)
2331 			panic("%s: Failed to allocate %lu bytes align=0x%x\n",
2332 			      __func__, vec_size, 1 << fls(vec_size));
2333 
2334 		/*
2335 		 * Try to ensure ebase resides in KSeg0 if possible.
2336 		 *
2337 		 * It shouldn't generally be in XKPhys on MIPS64 to avoid
2338 		 * hitting a poorly defined exception base for Cache Errors.
2339 		 * The allocation is likely to be in the low 512MB of physical,
2340 		 * in which case we should be able to convert to KSeg0.
2341 		 *
2342 		 * EVA is special though as it allows segments to be rearranged
2343 		 * and to become uncached during cache error handling.
2344 		 */
2345 		if (!IS_ENABLED(CONFIG_EVA) && !WARN_ON(ebase_pa >= 0x20000000))
2346 			ebase = CKSEG0ADDR(ebase_pa);
2347 		else
2348 			ebase = (unsigned long)phys_to_virt(ebase_pa);
2349 	}
2350 
2351 	if (cpu_has_mmips) {
2352 		unsigned int config3 = read_c0_config3();
2353 
2354 		if (IS_ENABLED(CONFIG_CPU_MICROMIPS))
2355 			write_c0_config3(config3 | MIPS_CONF3_ISA_OE);
2356 		else
2357 			write_c0_config3(config3 & ~MIPS_CONF3_ISA_OE);
2358 	}
2359 
2360 	if (board_ebase_setup)
2361 		board_ebase_setup();
2362 	per_cpu_trap_init(true);
2363 	memblock_set_bottom_up(false);
2364 
2365 	/*
2366 	 * Copy the generic exception handlers to their final destination.
2367 	 * This will be overridden later as suitable for a particular
2368 	 * configuration.
2369 	 */
2370 	set_handler(0x180, &except_vec3_generic, 0x80);
2371 
2372 	/*
2373 	 * Setup default vectors
2374 	 */
2375 	for (i = 0; i <= 31; i++)
2376 		set_except_vector(i, handle_reserved);
2377 
2378 	/*
2379 	 * Copy the EJTAG debug exception vector handler code to it's final
2380 	 * destination.
2381 	 */
2382 	if (cpu_has_ejtag && board_ejtag_handler_setup)
2383 		board_ejtag_handler_setup();
2384 
2385 	/*
2386 	 * Only some CPUs have the watch exceptions.
2387 	 */
2388 	if (cpu_has_watch)
2389 		set_except_vector(EXCCODE_WATCH, handle_watch);
2390 
2391 	/*
2392 	 * Initialise interrupt handlers
2393 	 */
2394 	if (cpu_has_veic || cpu_has_vint) {
2395 		int nvec = cpu_has_veic ? 64 : 8;
2396 		for (i = 0; i < nvec; i++)
2397 			set_vi_handler(i, NULL);
2398 	}
2399 	else if (cpu_has_divec)
2400 		set_handler(0x200, &except_vec4, 0x8);
2401 
2402 	/*
2403 	 * Some CPUs can enable/disable for cache parity detection, but does
2404 	 * it different ways.
2405 	 */
2406 	parity_protection_init();
2407 
2408 	/*
2409 	 * The Data Bus Errors / Instruction Bus Errors are signaled
2410 	 * by external hardware.  Therefore these two exceptions
2411 	 * may have board specific handlers.
2412 	 */
2413 	if (board_be_init)
2414 		board_be_init();
2415 
2416 	set_except_vector(EXCCODE_INT, using_rollback_handler() ?
2417 					rollback_handle_int : handle_int);
2418 	set_except_vector(EXCCODE_MOD, handle_tlbm);
2419 	set_except_vector(EXCCODE_TLBL, handle_tlbl);
2420 	set_except_vector(EXCCODE_TLBS, handle_tlbs);
2421 
2422 	set_except_vector(EXCCODE_ADEL, handle_adel);
2423 	set_except_vector(EXCCODE_ADES, handle_ades);
2424 
2425 	set_except_vector(EXCCODE_IBE, handle_ibe);
2426 	set_except_vector(EXCCODE_DBE, handle_dbe);
2427 
2428 	set_except_vector(EXCCODE_SYS, handle_sys);
2429 	set_except_vector(EXCCODE_BP, handle_bp);
2430 
2431 	if (rdhwr_noopt)
2432 		set_except_vector(EXCCODE_RI, handle_ri);
2433 	else {
2434 		if (cpu_has_vtag_icache)
2435 			set_except_vector(EXCCODE_RI, handle_ri_rdhwr_tlbp);
2436 		else if (current_cpu_type() == CPU_LOONGSON64)
2437 			set_except_vector(EXCCODE_RI, handle_ri_rdhwr_tlbp);
2438 		else
2439 			set_except_vector(EXCCODE_RI, handle_ri_rdhwr);
2440 	}
2441 
2442 	set_except_vector(EXCCODE_CPU, handle_cpu);
2443 	set_except_vector(EXCCODE_OV, handle_ov);
2444 	set_except_vector(EXCCODE_TR, handle_tr);
2445 	set_except_vector(EXCCODE_MSAFPE, handle_msa_fpe);
2446 
2447 	if (board_nmi_handler_setup)
2448 		board_nmi_handler_setup();
2449 
2450 	if (cpu_has_fpu && !cpu_has_nofpuex)
2451 		set_except_vector(EXCCODE_FPE, handle_fpe);
2452 
2453 	set_except_vector(MIPS_EXCCODE_TLBPAR, handle_ftlb);
2454 
2455 	if (cpu_has_rixiex) {
2456 		set_except_vector(EXCCODE_TLBRI, tlb_do_page_fault_0);
2457 		set_except_vector(EXCCODE_TLBXI, tlb_do_page_fault_0);
2458 	}
2459 
2460 	set_except_vector(EXCCODE_MSADIS, handle_msa);
2461 	set_except_vector(EXCCODE_MDMX, handle_mdmx);
2462 
2463 	if (cpu_has_mcheck)
2464 		set_except_vector(EXCCODE_MCHECK, handle_mcheck);
2465 
2466 	if (cpu_has_mipsmt)
2467 		set_except_vector(EXCCODE_THREAD, handle_mt);
2468 
2469 	set_except_vector(EXCCODE_DSPDIS, handle_dsp);
2470 
2471 	if (board_cache_error_setup)
2472 		board_cache_error_setup();
2473 
2474 	if (cpu_has_vce)
2475 		/* Special exception: R4[04]00 uses also the divec space. */
2476 		set_handler(0x180, &except_vec3_r4000, 0x100);
2477 	else if (cpu_has_4kex)
2478 		set_handler(0x180, &except_vec3_generic, 0x80);
2479 	else
2480 		set_handler(0x080, &except_vec3_generic, 0x80);
2481 
2482 	local_flush_icache_range(ebase, ebase + vec_size);
2483 
2484 	sort_extable(__start___dbe_table, __stop___dbe_table);
2485 
2486 	cu2_notifier(default_cu2_call, 0x80000000);	/* Run last  */
2487 }
2488 
2489 static int trap_pm_notifier(struct notifier_block *self, unsigned long cmd,
2490 			    void *v)
2491 {
2492 	switch (cmd) {
2493 	case CPU_PM_ENTER_FAILED:
2494 	case CPU_PM_EXIT:
2495 		configure_status();
2496 		configure_hwrena();
2497 		configure_exception_vector();
2498 
2499 		/* Restore register with CPU number for TLB handlers */
2500 		TLBMISS_HANDLER_RESTORE();
2501 
2502 		break;
2503 	}
2504 
2505 	return NOTIFY_OK;
2506 }
2507 
2508 static struct notifier_block trap_pm_notifier_block = {
2509 	.notifier_call = trap_pm_notifier,
2510 };
2511 
2512 static int __init trap_pm_init(void)
2513 {
2514 	return cpu_pm_register_notifier(&trap_pm_notifier_block);
2515 }
2516 arch_initcall(trap_pm_init);
2517