xref: /openbmc/linux/arch/powerpc/kernel/traps.c (revision 11cb0a25f71818ca7ab4856548ecfd83c169aa4d)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  Copyright (C) 1995-1996  Gary Thomas (gdt@linuxppc.org)
4  *  Copyright 2007-2010 Freescale Semiconductor, Inc.
5  *
6  *  Modified by Cort Dougan (cort@cs.nmt.edu)
7  *  and Paul Mackerras (paulus@samba.org)
8  */
9 
10 /*
11  * This file handles the architecture-dependent parts of hardware exceptions
12  */
13 
14 #include <linux/errno.h>
15 #include <linux/sched.h>
16 #include <linux/sched/debug.h>
17 #include <linux/kernel.h>
18 #include <linux/mm.h>
19 #include <linux/pkeys.h>
20 #include <linux/stddef.h>
21 #include <linux/unistd.h>
22 #include <linux/ptrace.h>
23 #include <linux/user.h>
24 #include <linux/interrupt.h>
25 #include <linux/init.h>
26 #include <linux/extable.h>
27 #include <linux/module.h>	/* print_modules */
28 #include <linux/prctl.h>
29 #include <linux/delay.h>
30 #include <linux/kprobes.h>
31 #include <linux/kexec.h>
32 #include <linux/backlight.h>
33 #include <linux/bug.h>
34 #include <linux/kdebug.h>
35 #include <linux/ratelimit.h>
36 #include <linux/context_tracking.h>
37 #include <linux/smp.h>
38 #include <linux/console.h>
39 #include <linux/kmsg_dump.h>
40 
41 #include <asm/emulated_ops.h>
42 #include <linux/uaccess.h>
43 #include <asm/debugfs.h>
44 #include <asm/io.h>
45 #include <asm/machdep.h>
46 #include <asm/rtas.h>
47 #include <asm/pmc.h>
48 #include <asm/reg.h>
49 #ifdef CONFIG_PMAC_BACKLIGHT
50 #include <asm/backlight.h>
51 #endif
52 #ifdef CONFIG_PPC64
53 #include <asm/firmware.h>
54 #include <asm/processor.h>
55 #include <asm/tm.h>
56 #endif
57 #include <asm/kexec.h>
58 #include <asm/ppc-opcode.h>
59 #include <asm/rio.h>
60 #include <asm/fadump.h>
61 #include <asm/switch_to.h>
62 #include <asm/tm.h>
63 #include <asm/debug.h>
64 #include <asm/asm-prototypes.h>
65 #include <asm/hmi.h>
66 #include <sysdev/fsl_pci.h>
67 #include <asm/kprobes.h>
68 #include <asm/stacktrace.h>
69 #include <asm/nmi.h>
70 
71 #if defined(CONFIG_DEBUGGER) || defined(CONFIG_KEXEC_CORE)
72 int (*__debugger)(struct pt_regs *regs) __read_mostly;
73 int (*__debugger_ipi)(struct pt_regs *regs) __read_mostly;
74 int (*__debugger_bpt)(struct pt_regs *regs) __read_mostly;
75 int (*__debugger_sstep)(struct pt_regs *regs) __read_mostly;
76 int (*__debugger_iabr_match)(struct pt_regs *regs) __read_mostly;
77 int (*__debugger_break_match)(struct pt_regs *regs) __read_mostly;
78 int (*__debugger_fault_handler)(struct pt_regs *regs) __read_mostly;
79 
80 EXPORT_SYMBOL(__debugger);
81 EXPORT_SYMBOL(__debugger_ipi);
82 EXPORT_SYMBOL(__debugger_bpt);
83 EXPORT_SYMBOL(__debugger_sstep);
84 EXPORT_SYMBOL(__debugger_iabr_match);
85 EXPORT_SYMBOL(__debugger_break_match);
86 EXPORT_SYMBOL(__debugger_fault_handler);
87 #endif
88 
89 /* Transactional Memory trap debug */
90 #ifdef TM_DEBUG_SW
91 #define TM_DEBUG(x...) printk(KERN_INFO x)
92 #else
93 #define TM_DEBUG(x...) do { } while(0)
94 #endif
95 
96 static const char *signame(int signr)
97 {
98 	switch (signr) {
99 	case SIGBUS:	return "bus error";
100 	case SIGFPE:	return "floating point exception";
101 	case SIGILL:	return "illegal instruction";
102 	case SIGSEGV:	return "segfault";
103 	case SIGTRAP:	return "unhandled trap";
104 	}
105 
106 	return "unknown signal";
107 }
108 
109 /*
110  * Trap & Exception support
111  */
112 
113 #ifdef CONFIG_PMAC_BACKLIGHT
114 static void pmac_backlight_unblank(void)
115 {
116 	mutex_lock(&pmac_backlight_mutex);
117 	if (pmac_backlight) {
118 		struct backlight_properties *props;
119 
120 		props = &pmac_backlight->props;
121 		props->brightness = props->max_brightness;
122 		props->power = FB_BLANK_UNBLANK;
123 		backlight_update_status(pmac_backlight);
124 	}
125 	mutex_unlock(&pmac_backlight_mutex);
126 }
127 #else
128 static inline void pmac_backlight_unblank(void) { }
129 #endif
130 
131 /*
132  * If oops/die is expected to crash the machine, return true here.
133  *
134  * This should not be expected to be 100% accurate, there may be
135  * notifiers registered or other unexpected conditions that may bring
136  * down the kernel. Or if the current process in the kernel is holding
137  * locks or has other critical state, the kernel may become effectively
138  * unusable anyway.
139  */
140 bool die_will_crash(void)
141 {
142 	if (should_fadump_crash())
143 		return true;
144 	if (kexec_should_crash(current))
145 		return true;
146 	if (in_interrupt() || panic_on_oops ||
147 			!current->pid || is_global_init(current))
148 		return true;
149 
150 	return false;
151 }
152 
153 static arch_spinlock_t die_lock = __ARCH_SPIN_LOCK_UNLOCKED;
154 static int die_owner = -1;
155 static unsigned int die_nest_count;
156 static int die_counter;
157 
158 extern void panic_flush_kmsg_start(void)
159 {
160 	/*
161 	 * These are mostly taken from kernel/panic.c, but tries to do
162 	 * relatively minimal work. Don't use delay functions (TB may
163 	 * be broken), don't crash dump (need to set a firmware log),
164 	 * don't run notifiers. We do want to get some information to
165 	 * Linux console.
166 	 */
167 	console_verbose();
168 	bust_spinlocks(1);
169 }
170 
171 extern void panic_flush_kmsg_end(void)
172 {
173 	printk_safe_flush_on_panic();
174 	kmsg_dump(KMSG_DUMP_PANIC);
175 	bust_spinlocks(0);
176 	debug_locks_off();
177 	console_flush_on_panic(CONSOLE_FLUSH_PENDING);
178 }
179 
180 static unsigned long oops_begin(struct pt_regs *regs)
181 {
182 	int cpu;
183 	unsigned long flags;
184 
185 	oops_enter();
186 
187 	/* racy, but better than risking deadlock. */
188 	raw_local_irq_save(flags);
189 	cpu = smp_processor_id();
190 	if (!arch_spin_trylock(&die_lock)) {
191 		if (cpu == die_owner)
192 			/* nested oops. should stop eventually */;
193 		else
194 			arch_spin_lock(&die_lock);
195 	}
196 	die_nest_count++;
197 	die_owner = cpu;
198 	console_verbose();
199 	bust_spinlocks(1);
200 	if (machine_is(powermac))
201 		pmac_backlight_unblank();
202 	return flags;
203 }
204 NOKPROBE_SYMBOL(oops_begin);
205 
206 static void oops_end(unsigned long flags, struct pt_regs *regs,
207 			       int signr)
208 {
209 	bust_spinlocks(0);
210 	add_taint(TAINT_DIE, LOCKDEP_NOW_UNRELIABLE);
211 	die_nest_count--;
212 	oops_exit();
213 	printk("\n");
214 	if (!die_nest_count) {
215 		/* Nest count reaches zero, release the lock. */
216 		die_owner = -1;
217 		arch_spin_unlock(&die_lock);
218 	}
219 	raw_local_irq_restore(flags);
220 
221 	/*
222 	 * system_reset_excption handles debugger, crash dump, panic, for 0x100
223 	 */
224 	if (TRAP(regs) == 0x100)
225 		return;
226 
227 	crash_fadump(regs, "die oops");
228 
229 	if (kexec_should_crash(current))
230 		crash_kexec(regs);
231 
232 	if (!signr)
233 		return;
234 
235 	/*
236 	 * While our oops output is serialised by a spinlock, output
237 	 * from panic() called below can race and corrupt it. If we
238 	 * know we are going to panic, delay for 1 second so we have a
239 	 * chance to get clean backtraces from all CPUs that are oopsing.
240 	 */
241 	if (in_interrupt() || panic_on_oops || !current->pid ||
242 	    is_global_init(current)) {
243 		mdelay(MSEC_PER_SEC);
244 	}
245 
246 	if (panic_on_oops)
247 		panic("Fatal exception");
248 	do_exit(signr);
249 }
250 NOKPROBE_SYMBOL(oops_end);
251 
252 static char *get_mmu_str(void)
253 {
254 	if (early_radix_enabled())
255 		return " MMU=Radix";
256 	if (early_mmu_has_feature(MMU_FTR_HPTE_TABLE))
257 		return " MMU=Hash";
258 	return "";
259 }
260 
261 static int __die(const char *str, struct pt_regs *regs, long err)
262 {
263 	printk("Oops: %s, sig: %ld [#%d]\n", str, err, ++die_counter);
264 
265 	printk("%s PAGE_SIZE=%luK%s%s%s%s%s%s %s\n",
266 	       IS_ENABLED(CONFIG_CPU_LITTLE_ENDIAN) ? "LE" : "BE",
267 	       PAGE_SIZE / 1024, get_mmu_str(),
268 	       IS_ENABLED(CONFIG_PREEMPT) ? " PREEMPT" : "",
269 	       IS_ENABLED(CONFIG_SMP) ? " SMP" : "",
270 	       IS_ENABLED(CONFIG_SMP) ? (" NR_CPUS=" __stringify(NR_CPUS)) : "",
271 	       debug_pagealloc_enabled() ? " DEBUG_PAGEALLOC" : "",
272 	       IS_ENABLED(CONFIG_NUMA) ? " NUMA" : "",
273 	       ppc_md.name ? ppc_md.name : "");
274 
275 	if (notify_die(DIE_OOPS, str, regs, err, 255, SIGSEGV) == NOTIFY_STOP)
276 		return 1;
277 
278 	print_modules();
279 	show_regs(regs);
280 
281 	return 0;
282 }
283 NOKPROBE_SYMBOL(__die);
284 
285 void die(const char *str, struct pt_regs *regs, long err)
286 {
287 	unsigned long flags;
288 
289 	/*
290 	 * system_reset_excption handles debugger, crash dump, panic, for 0x100
291 	 */
292 	if (TRAP(regs) != 0x100) {
293 		if (debugger(regs))
294 			return;
295 	}
296 
297 	flags = oops_begin(regs);
298 	if (__die(str, regs, err))
299 		err = 0;
300 	oops_end(flags, regs, err);
301 }
302 NOKPROBE_SYMBOL(die);
303 
304 void user_single_step_report(struct pt_regs *regs)
305 {
306 	force_sig_fault(SIGTRAP, TRAP_TRACE, (void __user *)regs->nip);
307 }
308 
309 static void show_signal_msg(int signr, struct pt_regs *regs, int code,
310 			    unsigned long addr)
311 {
312 	static DEFINE_RATELIMIT_STATE(rs, DEFAULT_RATELIMIT_INTERVAL,
313 				      DEFAULT_RATELIMIT_BURST);
314 
315 	if (!show_unhandled_signals)
316 		return;
317 
318 	if (!unhandled_signal(current, signr))
319 		return;
320 
321 	if (!__ratelimit(&rs))
322 		return;
323 
324 	pr_info("%s[%d]: %s (%d) at %lx nip %lx lr %lx code %x",
325 		current->comm, current->pid, signame(signr), signr,
326 		addr, regs->nip, regs->link, code);
327 
328 	print_vma_addr(KERN_CONT " in ", regs->nip);
329 
330 	pr_cont("\n");
331 
332 	show_user_instructions(regs);
333 }
334 
335 static bool exception_common(int signr, struct pt_regs *regs, int code,
336 			      unsigned long addr)
337 {
338 	if (!user_mode(regs)) {
339 		die("Exception in kernel mode", regs, signr);
340 		return false;
341 	}
342 
343 	show_signal_msg(signr, regs, code, addr);
344 
345 	if (arch_irqs_disabled() && !arch_irq_disabled_regs(regs))
346 		local_irq_enable();
347 
348 	current->thread.trap_nr = code;
349 
350 	return true;
351 }
352 
353 void _exception_pkey(struct pt_regs *regs, unsigned long addr, int key)
354 {
355 	if (!exception_common(SIGSEGV, regs, SEGV_PKUERR, addr))
356 		return;
357 
358 	force_sig_pkuerr((void __user *) addr, key);
359 }
360 
361 void _exception(int signr, struct pt_regs *regs, int code, unsigned long addr)
362 {
363 	if (!exception_common(signr, regs, code, addr))
364 		return;
365 
366 	force_sig_fault(signr, code, (void __user *)addr);
367 }
368 
369 /*
370  * The interrupt architecture has a quirk in that the HV interrupts excluding
371  * the NMIs (0x100 and 0x200) do not clear MSR[RI] at entry. The first thing
372  * that an interrupt handler must do is save off a GPR into a scratch register,
373  * and all interrupts on POWERNV (HV=1) use the HSPRG1 register as scratch.
374  * Therefore an NMI can clobber an HV interrupt's live HSPRG1 without noticing
375  * that it is non-reentrant, which leads to random data corruption.
376  *
377  * The solution is for NMI interrupts in HV mode to check if they originated
378  * from these critical HV interrupt regions. If so, then mark them not
379  * recoverable.
380  *
381  * An alternative would be for HV NMIs to use SPRG for scratch to avoid the
382  * HSPRG1 clobber, however this would cause guest SPRG to be clobbered. Linux
383  * guests should always have MSR[RI]=0 when its scratch SPRG is in use, so
384  * that would work. However any other guest OS that may have the SPRG live
385  * and MSR[RI]=1 could encounter silent corruption.
386  *
387  * Builds that do not support KVM could take this second option to increase
388  * the recoverability of NMIs.
389  */
390 void hv_nmi_check_nonrecoverable(struct pt_regs *regs)
391 {
392 #ifdef CONFIG_PPC_POWERNV
393 	unsigned long kbase = (unsigned long)_stext;
394 	unsigned long nip = regs->nip;
395 
396 	if (!(regs->msr & MSR_RI))
397 		return;
398 	if (!(regs->msr & MSR_HV))
399 		return;
400 	if (regs->msr & MSR_PR)
401 		return;
402 
403 	/*
404 	 * Now test if the interrupt has hit a range that may be using
405 	 * HSPRG1 without having RI=0 (i.e., an HSRR interrupt). The
406 	 * problem ranges all run un-relocated. Test real and virt modes
407 	 * at the same time by droping the high bit of the nip (virt mode
408 	 * entry points still have the +0x4000 offset).
409 	 */
410 	nip &= ~0xc000000000000000ULL;
411 	if ((nip >= 0x500 && nip < 0x600) || (nip >= 0x4500 && nip < 0x4600))
412 		goto nonrecoverable;
413 	if ((nip >= 0x980 && nip < 0xa00) || (nip >= 0x4980 && nip < 0x4a00))
414 		goto nonrecoverable;
415 	if ((nip >= 0xe00 && nip < 0xec0) || (nip >= 0x4e00 && nip < 0x4ec0))
416 		goto nonrecoverable;
417 	if ((nip >= 0xf80 && nip < 0xfa0) || (nip >= 0x4f80 && nip < 0x4fa0))
418 		goto nonrecoverable;
419 
420 	/* Trampoline code runs un-relocated so subtract kbase. */
421 	if (nip >= (unsigned long)(start_real_trampolines - kbase) &&
422 			nip < (unsigned long)(end_real_trampolines - kbase))
423 		goto nonrecoverable;
424 	if (nip >= (unsigned long)(start_virt_trampolines - kbase) &&
425 			nip < (unsigned long)(end_virt_trampolines - kbase))
426 		goto nonrecoverable;
427 	return;
428 
429 nonrecoverable:
430 	regs->msr &= ~MSR_RI;
431 #endif
432 }
433 
434 void system_reset_exception(struct pt_regs *regs)
435 {
436 	unsigned long hsrr0, hsrr1;
437 	bool saved_hsrrs = false;
438 	u8 ftrace_enabled = this_cpu_get_ftrace_enabled();
439 
440 	this_cpu_set_ftrace_enabled(0);
441 
442 	nmi_enter();
443 
444 	/*
445 	 * System reset can interrupt code where HSRRs are live and MSR[RI]=1.
446 	 * The system reset interrupt itself may clobber HSRRs (e.g., to call
447 	 * OPAL), so save them here and restore them before returning.
448 	 *
449 	 * Machine checks don't need to save HSRRs, as the real mode handler
450 	 * is careful to avoid them, and the regular handler is not delivered
451 	 * as an NMI.
452 	 */
453 	if (cpu_has_feature(CPU_FTR_HVMODE)) {
454 		hsrr0 = mfspr(SPRN_HSRR0);
455 		hsrr1 = mfspr(SPRN_HSRR1);
456 		saved_hsrrs = true;
457 	}
458 
459 	hv_nmi_check_nonrecoverable(regs);
460 
461 	__this_cpu_inc(irq_stat.sreset_irqs);
462 
463 	/* See if any machine dependent calls */
464 	if (ppc_md.system_reset_exception) {
465 		if (ppc_md.system_reset_exception(regs))
466 			goto out;
467 	}
468 
469 	if (debugger(regs))
470 		goto out;
471 
472 	kmsg_dump(KMSG_DUMP_OOPS);
473 	/*
474 	 * A system reset is a request to dump, so we always send
475 	 * it through the crashdump code (if fadump or kdump are
476 	 * registered).
477 	 */
478 	crash_fadump(regs, "System Reset");
479 
480 	crash_kexec(regs);
481 
482 	/*
483 	 * We aren't the primary crash CPU. We need to send it
484 	 * to a holding pattern to avoid it ending up in the panic
485 	 * code.
486 	 */
487 	crash_kexec_secondary(regs);
488 
489 	/*
490 	 * No debugger or crash dump registered, print logs then
491 	 * panic.
492 	 */
493 	die("System Reset", regs, SIGABRT);
494 
495 	mdelay(2*MSEC_PER_SEC); /* Wait a little while for others to print */
496 	add_taint(TAINT_DIE, LOCKDEP_NOW_UNRELIABLE);
497 	nmi_panic(regs, "System Reset");
498 
499 out:
500 #ifdef CONFIG_PPC_BOOK3S_64
501 	BUG_ON(get_paca()->in_nmi == 0);
502 	if (get_paca()->in_nmi > 1)
503 		die("Unrecoverable nested System Reset", regs, SIGABRT);
504 #endif
505 	/* Must die if the interrupt is not recoverable */
506 	if (!(regs->msr & MSR_RI)) {
507 		/* For the reason explained in die_mce, nmi_exit before die */
508 		nmi_exit();
509 		die("Unrecoverable System Reset", regs, SIGABRT);
510 	}
511 
512 	if (saved_hsrrs) {
513 		mtspr(SPRN_HSRR0, hsrr0);
514 		mtspr(SPRN_HSRR1, hsrr1);
515 	}
516 
517 	nmi_exit();
518 
519 	this_cpu_set_ftrace_enabled(ftrace_enabled);
520 
521 	/* What should we do here? We could issue a shutdown or hard reset. */
522 }
523 NOKPROBE_SYMBOL(system_reset_exception);
524 
525 /*
526  * I/O accesses can cause machine checks on powermacs.
527  * Check if the NIP corresponds to the address of a sync
528  * instruction for which there is an entry in the exception
529  * table.
530  *  -- paulus.
531  */
532 static inline int check_io_access(struct pt_regs *regs)
533 {
534 #ifdef CONFIG_PPC32
535 	unsigned long msr = regs->msr;
536 	const struct exception_table_entry *entry;
537 	unsigned int *nip = (unsigned int *)regs->nip;
538 
539 	if (((msr & 0xffff0000) == 0 || (msr & (0x80000 | 0x40000)))
540 	    && (entry = search_exception_tables(regs->nip)) != NULL) {
541 		/*
542 		 * Check that it's a sync instruction, or somewhere
543 		 * in the twi; isync; nop sequence that inb/inw/inl uses.
544 		 * As the address is in the exception table
545 		 * we should be able to read the instr there.
546 		 * For the debug message, we look at the preceding
547 		 * load or store.
548 		 */
549 		if (*nip == PPC_INST_NOP)
550 			nip -= 2;
551 		else if (*nip == PPC_INST_ISYNC)
552 			--nip;
553 		if (*nip == PPC_INST_SYNC || (*nip >> 26) == OP_TRAP) {
554 			unsigned int rb;
555 
556 			--nip;
557 			rb = (*nip >> 11) & 0x1f;
558 			printk(KERN_DEBUG "%s bad port %lx at %p\n",
559 			       (*nip & 0x100)? "OUT to": "IN from",
560 			       regs->gpr[rb] - _IO_BASE, nip);
561 			regs->msr |= MSR_RI;
562 			regs->nip = extable_fixup(entry);
563 			return 1;
564 		}
565 	}
566 #endif /* CONFIG_PPC32 */
567 	return 0;
568 }
569 
570 #ifdef CONFIG_PPC_ADV_DEBUG_REGS
571 /* On 4xx, the reason for the machine check or program exception
572    is in the ESR. */
573 #define get_reason(regs)	((regs)->dsisr)
574 #define REASON_FP		ESR_FP
575 #define REASON_ILLEGAL		(ESR_PIL | ESR_PUO)
576 #define REASON_PRIVILEGED	ESR_PPR
577 #define REASON_TRAP		ESR_PTR
578 #define REASON_PREFIXED		0
579 #define REASON_BOUNDARY		0
580 
581 /* single-step stuff */
582 #define single_stepping(regs)	(current->thread.debug.dbcr0 & DBCR0_IC)
583 #define clear_single_step(regs)	(current->thread.debug.dbcr0 &= ~DBCR0_IC)
584 #define clear_br_trace(regs)	do {} while(0)
585 #else
586 /* On non-4xx, the reason for the machine check or program
587    exception is in the MSR. */
588 #define get_reason(regs)	((regs)->msr)
589 #define REASON_TM		SRR1_PROGTM
590 #define REASON_FP		SRR1_PROGFPE
591 #define REASON_ILLEGAL		SRR1_PROGILL
592 #define REASON_PRIVILEGED	SRR1_PROGPRIV
593 #define REASON_TRAP		SRR1_PROGTRAP
594 #define REASON_PREFIXED		SRR1_PREFIXED
595 #define REASON_BOUNDARY		SRR1_BOUNDARY
596 
597 #define single_stepping(regs)	((regs)->msr & MSR_SE)
598 #define clear_single_step(regs)	((regs)->msr &= ~MSR_SE)
599 #define clear_br_trace(regs)	((regs)->msr &= ~MSR_BE)
600 #endif
601 
602 #define inst_length(reason)	(((reason) & REASON_PREFIXED) ? 8 : 4)
603 
604 #if defined(CONFIG_E500)
605 int machine_check_e500mc(struct pt_regs *regs)
606 {
607 	unsigned long mcsr = mfspr(SPRN_MCSR);
608 	unsigned long pvr = mfspr(SPRN_PVR);
609 	unsigned long reason = mcsr;
610 	int recoverable = 1;
611 
612 	if (reason & MCSR_LD) {
613 		recoverable = fsl_rio_mcheck_exception(regs);
614 		if (recoverable == 1)
615 			goto silent_out;
616 	}
617 
618 	printk("Machine check in kernel mode.\n");
619 	printk("Caused by (from MCSR=%lx): ", reason);
620 
621 	if (reason & MCSR_MCP)
622 		pr_cont("Machine Check Signal\n");
623 
624 	if (reason & MCSR_ICPERR) {
625 		pr_cont("Instruction Cache Parity Error\n");
626 
627 		/*
628 		 * This is recoverable by invalidating the i-cache.
629 		 */
630 		mtspr(SPRN_L1CSR1, mfspr(SPRN_L1CSR1) | L1CSR1_ICFI);
631 		while (mfspr(SPRN_L1CSR1) & L1CSR1_ICFI)
632 			;
633 
634 		/*
635 		 * This will generally be accompanied by an instruction
636 		 * fetch error report -- only treat MCSR_IF as fatal
637 		 * if it wasn't due to an L1 parity error.
638 		 */
639 		reason &= ~MCSR_IF;
640 	}
641 
642 	if (reason & MCSR_DCPERR_MC) {
643 		pr_cont("Data Cache Parity Error\n");
644 
645 		/*
646 		 * In write shadow mode we auto-recover from the error, but it
647 		 * may still get logged and cause a machine check.  We should
648 		 * only treat the non-write shadow case as non-recoverable.
649 		 */
650 		/* On e6500 core, L1 DCWS (Data cache write shadow mode) bit
651 		 * is not implemented but L1 data cache always runs in write
652 		 * shadow mode. Hence on data cache parity errors HW will
653 		 * automatically invalidate the L1 Data Cache.
654 		 */
655 		if (PVR_VER(pvr) != PVR_VER_E6500) {
656 			if (!(mfspr(SPRN_L1CSR2) & L1CSR2_DCWS))
657 				recoverable = 0;
658 		}
659 	}
660 
661 	if (reason & MCSR_L2MMU_MHIT) {
662 		pr_cont("Hit on multiple TLB entries\n");
663 		recoverable = 0;
664 	}
665 
666 	if (reason & MCSR_NMI)
667 		pr_cont("Non-maskable interrupt\n");
668 
669 	if (reason & MCSR_IF) {
670 		pr_cont("Instruction Fetch Error Report\n");
671 		recoverable = 0;
672 	}
673 
674 	if (reason & MCSR_LD) {
675 		pr_cont("Load Error Report\n");
676 		recoverable = 0;
677 	}
678 
679 	if (reason & MCSR_ST) {
680 		pr_cont("Store Error Report\n");
681 		recoverable = 0;
682 	}
683 
684 	if (reason & MCSR_LDG) {
685 		pr_cont("Guarded Load Error Report\n");
686 		recoverable = 0;
687 	}
688 
689 	if (reason & MCSR_TLBSYNC)
690 		pr_cont("Simultaneous tlbsync operations\n");
691 
692 	if (reason & MCSR_BSL2_ERR) {
693 		pr_cont("Level 2 Cache Error\n");
694 		recoverable = 0;
695 	}
696 
697 	if (reason & MCSR_MAV) {
698 		u64 addr;
699 
700 		addr = mfspr(SPRN_MCAR);
701 		addr |= (u64)mfspr(SPRN_MCARU) << 32;
702 
703 		pr_cont("Machine Check %s Address: %#llx\n",
704 		       reason & MCSR_MEA ? "Effective" : "Physical", addr);
705 	}
706 
707 silent_out:
708 	mtspr(SPRN_MCSR, mcsr);
709 	return mfspr(SPRN_MCSR) == 0 && recoverable;
710 }
711 
712 int machine_check_e500(struct pt_regs *regs)
713 {
714 	unsigned long reason = mfspr(SPRN_MCSR);
715 
716 	if (reason & MCSR_BUS_RBERR) {
717 		if (fsl_rio_mcheck_exception(regs))
718 			return 1;
719 		if (fsl_pci_mcheck_exception(regs))
720 			return 1;
721 	}
722 
723 	printk("Machine check in kernel mode.\n");
724 	printk("Caused by (from MCSR=%lx): ", reason);
725 
726 	if (reason & MCSR_MCP)
727 		pr_cont("Machine Check Signal\n");
728 	if (reason & MCSR_ICPERR)
729 		pr_cont("Instruction Cache Parity Error\n");
730 	if (reason & MCSR_DCP_PERR)
731 		pr_cont("Data Cache Push Parity Error\n");
732 	if (reason & MCSR_DCPERR)
733 		pr_cont("Data Cache Parity Error\n");
734 	if (reason & MCSR_BUS_IAERR)
735 		pr_cont("Bus - Instruction Address Error\n");
736 	if (reason & MCSR_BUS_RAERR)
737 		pr_cont("Bus - Read Address Error\n");
738 	if (reason & MCSR_BUS_WAERR)
739 		pr_cont("Bus - Write Address Error\n");
740 	if (reason & MCSR_BUS_IBERR)
741 		pr_cont("Bus - Instruction Data Error\n");
742 	if (reason & MCSR_BUS_RBERR)
743 		pr_cont("Bus - Read Data Bus Error\n");
744 	if (reason & MCSR_BUS_WBERR)
745 		pr_cont("Bus - Write Data Bus Error\n");
746 	if (reason & MCSR_BUS_IPERR)
747 		pr_cont("Bus - Instruction Parity Error\n");
748 	if (reason & MCSR_BUS_RPERR)
749 		pr_cont("Bus - Read Parity Error\n");
750 
751 	return 0;
752 }
753 
754 int machine_check_generic(struct pt_regs *regs)
755 {
756 	return 0;
757 }
758 #elif defined(CONFIG_PPC32)
759 int machine_check_generic(struct pt_regs *regs)
760 {
761 	unsigned long reason = regs->msr;
762 
763 	printk("Machine check in kernel mode.\n");
764 	printk("Caused by (from SRR1=%lx): ", reason);
765 	switch (reason & 0x601F0000) {
766 	case 0x80000:
767 		pr_cont("Machine check signal\n");
768 		break;
769 	case 0x40000:
770 	case 0x140000:	/* 7450 MSS error and TEA */
771 		pr_cont("Transfer error ack signal\n");
772 		break;
773 	case 0x20000:
774 		pr_cont("Data parity error signal\n");
775 		break;
776 	case 0x10000:
777 		pr_cont("Address parity error signal\n");
778 		break;
779 	case 0x20000000:
780 		pr_cont("L1 Data Cache error\n");
781 		break;
782 	case 0x40000000:
783 		pr_cont("L1 Instruction Cache error\n");
784 		break;
785 	case 0x00100000:
786 		pr_cont("L2 data cache parity error\n");
787 		break;
788 	default:
789 		pr_cont("Unknown values in msr\n");
790 	}
791 	return 0;
792 }
793 #endif /* everything else */
794 
795 void die_mce(const char *str, struct pt_regs *regs, long err)
796 {
797 	/*
798 	 * The machine check wants to kill the interrupted context, but
799 	 * do_exit() checks for in_interrupt() and panics in that case, so
800 	 * exit the irq/nmi before calling die.
801 	 */
802 	if (!IS_ENABLED(CONFIG_PPC_BOOK3S_64))
803 		nmi_exit();
804 	die(str, regs, err);
805 }
806 NOKPROBE_SYMBOL(die_mce);
807 
808 void machine_check_exception(struct pt_regs *regs)
809 {
810 	int recover = 0;
811 
812 	/*
813 	 * BOOK3S_64 does not call this handler as a non-maskable interrupt
814 	 * (it uses its own early real-mode handler to handle the MCE proper
815 	 * and then raises irq_work to call this handler when interrupts are
816 	 * enabled).
817 	 *
818 	 * This is silly. The BOOK3S_64 should just call a different function
819 	 * rather than expecting semantics to magically change. Something
820 	 * like 'non_nmi_machine_check_exception()', perhaps?
821 	 */
822 	const bool nmi = !IS_ENABLED(CONFIG_PPC_BOOK3S_64);
823 
824 	if (nmi) nmi_enter();
825 
826 	__this_cpu_inc(irq_stat.mce_exceptions);
827 
828 	add_taint(TAINT_MACHINE_CHECK, LOCKDEP_NOW_UNRELIABLE);
829 
830 	/* See if any machine dependent calls. In theory, we would want
831 	 * to call the CPU first, and call the ppc_md. one if the CPU
832 	 * one returns a positive number. However there is existing code
833 	 * that assumes the board gets a first chance, so let's keep it
834 	 * that way for now and fix things later. --BenH.
835 	 */
836 	if (ppc_md.machine_check_exception)
837 		recover = ppc_md.machine_check_exception(regs);
838 	else if (cur_cpu_spec->machine_check)
839 		recover = cur_cpu_spec->machine_check(regs);
840 
841 	if (recover > 0)
842 		goto bail;
843 
844 	if (debugger_fault_handler(regs))
845 		goto bail;
846 
847 	if (check_io_access(regs))
848 		goto bail;
849 
850 	die_mce("Machine check", regs, SIGBUS);
851 
852 bail:
853 	/* Must die if the interrupt is not recoverable */
854 	if (!(regs->msr & MSR_RI))
855 		die_mce("Unrecoverable Machine check", regs, SIGBUS);
856 
857 	if (nmi) nmi_exit();
858 }
859 NOKPROBE_SYMBOL(machine_check_exception);
860 
861 void SMIException(struct pt_regs *regs)
862 {
863 	die("System Management Interrupt", regs, SIGABRT);
864 }
865 
866 #ifdef CONFIG_VSX
867 static void p9_hmi_special_emu(struct pt_regs *regs)
868 {
869 	unsigned int ra, rb, t, i, sel, instr, rc;
870 	const void __user *addr;
871 	u8 vbuf[16] __aligned(16), *vdst;
872 	unsigned long ea, msr, msr_mask;
873 	bool swap;
874 
875 	if (__get_user_inatomic(instr, (unsigned int __user *)regs->nip))
876 		return;
877 
878 	/*
879 	 * lxvb16x	opcode: 0x7c0006d8
880 	 * lxvd2x	opcode: 0x7c000698
881 	 * lxvh8x	opcode: 0x7c000658
882 	 * lxvw4x	opcode: 0x7c000618
883 	 */
884 	if ((instr & 0xfc00073e) != 0x7c000618) {
885 		pr_devel("HMI vec emu: not vector CI %i:%s[%d] nip=%016lx"
886 			 " instr=%08x\n",
887 			 smp_processor_id(), current->comm, current->pid,
888 			 regs->nip, instr);
889 		return;
890 	}
891 
892 	/* Grab vector registers into the task struct */
893 	msr = regs->msr; /* Grab msr before we flush the bits */
894 	flush_vsx_to_thread(current);
895 	enable_kernel_altivec();
896 
897 	/*
898 	 * Is userspace running with a different endian (this is rare but
899 	 * not impossible)
900 	 */
901 	swap = (msr & MSR_LE) != (MSR_KERNEL & MSR_LE);
902 
903 	/* Decode the instruction */
904 	ra = (instr >> 16) & 0x1f;
905 	rb = (instr >> 11) & 0x1f;
906 	t = (instr >> 21) & 0x1f;
907 	if (instr & 1)
908 		vdst = (u8 *)&current->thread.vr_state.vr[t];
909 	else
910 		vdst = (u8 *)&current->thread.fp_state.fpr[t][0];
911 
912 	/* Grab the vector address */
913 	ea = regs->gpr[rb] + (ra ? regs->gpr[ra] : 0);
914 	if (is_32bit_task())
915 		ea &= 0xfffffffful;
916 	addr = (__force const void __user *)ea;
917 
918 	/* Check it */
919 	if (!access_ok(addr, 16)) {
920 		pr_devel("HMI vec emu: bad access %i:%s[%d] nip=%016lx"
921 			 " instr=%08x addr=%016lx\n",
922 			 smp_processor_id(), current->comm, current->pid,
923 			 regs->nip, instr, (unsigned long)addr);
924 		return;
925 	}
926 
927 	/* Read the vector */
928 	rc = 0;
929 	if ((unsigned long)addr & 0xfUL)
930 		/* unaligned case */
931 		rc = __copy_from_user_inatomic(vbuf, addr, 16);
932 	else
933 		__get_user_atomic_128_aligned(vbuf, addr, rc);
934 	if (rc) {
935 		pr_devel("HMI vec emu: page fault %i:%s[%d] nip=%016lx"
936 			 " instr=%08x addr=%016lx\n",
937 			 smp_processor_id(), current->comm, current->pid,
938 			 regs->nip, instr, (unsigned long)addr);
939 		return;
940 	}
941 
942 	pr_devel("HMI vec emu: emulated vector CI %i:%s[%d] nip=%016lx"
943 		 " instr=%08x addr=%016lx\n",
944 		 smp_processor_id(), current->comm, current->pid, regs->nip,
945 		 instr, (unsigned long) addr);
946 
947 	/* Grab instruction "selector" */
948 	sel = (instr >> 6) & 3;
949 
950 	/*
951 	 * Check to make sure the facility is actually enabled. This
952 	 * could happen if we get a false positive hit.
953 	 *
954 	 * lxvd2x/lxvw4x always check MSR VSX sel = 0,2
955 	 * lxvh8x/lxvb16x check MSR VSX or VEC depending on VSR used sel = 1,3
956 	 */
957 	msr_mask = MSR_VSX;
958 	if ((sel & 1) && (instr & 1)) /* lxvh8x & lxvb16x + VSR >= 32 */
959 		msr_mask = MSR_VEC;
960 	if (!(msr & msr_mask)) {
961 		pr_devel("HMI vec emu: MSR fac clear %i:%s[%d] nip=%016lx"
962 			 " instr=%08x msr:%016lx\n",
963 			 smp_processor_id(), current->comm, current->pid,
964 			 regs->nip, instr, msr);
965 		return;
966 	}
967 
968 	/* Do logging here before we modify sel based on endian */
969 	switch (sel) {
970 	case 0:	/* lxvw4x */
971 		PPC_WARN_EMULATED(lxvw4x, regs);
972 		break;
973 	case 1: /* lxvh8x */
974 		PPC_WARN_EMULATED(lxvh8x, regs);
975 		break;
976 	case 2: /* lxvd2x */
977 		PPC_WARN_EMULATED(lxvd2x, regs);
978 		break;
979 	case 3: /* lxvb16x */
980 		PPC_WARN_EMULATED(lxvb16x, regs);
981 		break;
982 	}
983 
984 #ifdef __LITTLE_ENDIAN__
985 	/*
986 	 * An LE kernel stores the vector in the task struct as an LE
987 	 * byte array (effectively swapping both the components and
988 	 * the content of the components). Those instructions expect
989 	 * the components to remain in ascending address order, so we
990 	 * swap them back.
991 	 *
992 	 * If we are running a BE user space, the expectation is that
993 	 * of a simple memcpy, so forcing the emulation to look like
994 	 * a lxvb16x should do the trick.
995 	 */
996 	if (swap)
997 		sel = 3;
998 
999 	switch (sel) {
1000 	case 0:	/* lxvw4x */
1001 		for (i = 0; i < 4; i++)
1002 			((u32 *)vdst)[i] = ((u32 *)vbuf)[3-i];
1003 		break;
1004 	case 1: /* lxvh8x */
1005 		for (i = 0; i < 8; i++)
1006 			((u16 *)vdst)[i] = ((u16 *)vbuf)[7-i];
1007 		break;
1008 	case 2: /* lxvd2x */
1009 		for (i = 0; i < 2; i++)
1010 			((u64 *)vdst)[i] = ((u64 *)vbuf)[1-i];
1011 		break;
1012 	case 3: /* lxvb16x */
1013 		for (i = 0; i < 16; i++)
1014 			vdst[i] = vbuf[15-i];
1015 		break;
1016 	}
1017 #else /* __LITTLE_ENDIAN__ */
1018 	/* On a big endian kernel, a BE userspace only needs a memcpy */
1019 	if (!swap)
1020 		sel = 3;
1021 
1022 	/* Otherwise, we need to swap the content of the components */
1023 	switch (sel) {
1024 	case 0:	/* lxvw4x */
1025 		for (i = 0; i < 4; i++)
1026 			((u32 *)vdst)[i] = cpu_to_le32(((u32 *)vbuf)[i]);
1027 		break;
1028 	case 1: /* lxvh8x */
1029 		for (i = 0; i < 8; i++)
1030 			((u16 *)vdst)[i] = cpu_to_le16(((u16 *)vbuf)[i]);
1031 		break;
1032 	case 2: /* lxvd2x */
1033 		for (i = 0; i < 2; i++)
1034 			((u64 *)vdst)[i] = cpu_to_le64(((u64 *)vbuf)[i]);
1035 		break;
1036 	case 3: /* lxvb16x */
1037 		memcpy(vdst, vbuf, 16);
1038 		break;
1039 	}
1040 #endif /* !__LITTLE_ENDIAN__ */
1041 
1042 	/* Go to next instruction */
1043 	regs->nip += 4;
1044 }
1045 #endif /* CONFIG_VSX */
1046 
1047 void handle_hmi_exception(struct pt_regs *regs)
1048 {
1049 	struct pt_regs *old_regs;
1050 
1051 	old_regs = set_irq_regs(regs);
1052 	irq_enter();
1053 
1054 #ifdef CONFIG_VSX
1055 	/* Real mode flagged P9 special emu is needed */
1056 	if (local_paca->hmi_p9_special_emu) {
1057 		local_paca->hmi_p9_special_emu = 0;
1058 
1059 		/*
1060 		 * We don't want to take page faults while doing the
1061 		 * emulation, we just replay the instruction if necessary.
1062 		 */
1063 		pagefault_disable();
1064 		p9_hmi_special_emu(regs);
1065 		pagefault_enable();
1066 	}
1067 #endif /* CONFIG_VSX */
1068 
1069 	if (ppc_md.handle_hmi_exception)
1070 		ppc_md.handle_hmi_exception(regs);
1071 
1072 	irq_exit();
1073 	set_irq_regs(old_regs);
1074 }
1075 
1076 void unknown_exception(struct pt_regs *regs)
1077 {
1078 	enum ctx_state prev_state = exception_enter();
1079 
1080 	printk("Bad trap at PC: %lx, SR: %lx, vector=%lx\n",
1081 	       regs->nip, regs->msr, regs->trap);
1082 
1083 	_exception(SIGTRAP, regs, TRAP_UNK, 0);
1084 
1085 	exception_exit(prev_state);
1086 }
1087 
1088 void unknown_async_exception(struct pt_regs *regs)
1089 {
1090 	enum ctx_state prev_state = exception_enter();
1091 
1092 	printk("Bad trap at PC: %lx, SR: %lx, vector=%lx\n",
1093 	       regs->nip, regs->msr, regs->trap);
1094 
1095 	_exception(SIGTRAP, regs, TRAP_UNK, 0);
1096 
1097 	exception_exit(prev_state);
1098 }
1099 
1100 void instruction_breakpoint_exception(struct pt_regs *regs)
1101 {
1102 	enum ctx_state prev_state = exception_enter();
1103 
1104 	if (notify_die(DIE_IABR_MATCH, "iabr_match", regs, 5,
1105 					5, SIGTRAP) == NOTIFY_STOP)
1106 		goto bail;
1107 	if (debugger_iabr_match(regs))
1108 		goto bail;
1109 	_exception(SIGTRAP, regs, TRAP_BRKPT, regs->nip);
1110 
1111 bail:
1112 	exception_exit(prev_state);
1113 }
1114 
1115 void RunModeException(struct pt_regs *regs)
1116 {
1117 	_exception(SIGTRAP, regs, TRAP_UNK, 0);
1118 }
1119 
1120 void single_step_exception(struct pt_regs *regs)
1121 {
1122 	enum ctx_state prev_state = exception_enter();
1123 
1124 	clear_single_step(regs);
1125 	clear_br_trace(regs);
1126 
1127 	if (kprobe_post_handler(regs))
1128 		return;
1129 
1130 	if (notify_die(DIE_SSTEP, "single_step", regs, 5,
1131 					5, SIGTRAP) == NOTIFY_STOP)
1132 		goto bail;
1133 	if (debugger_sstep(regs))
1134 		goto bail;
1135 
1136 	_exception(SIGTRAP, regs, TRAP_TRACE, regs->nip);
1137 
1138 bail:
1139 	exception_exit(prev_state);
1140 }
1141 NOKPROBE_SYMBOL(single_step_exception);
1142 
1143 /*
1144  * After we have successfully emulated an instruction, we have to
1145  * check if the instruction was being single-stepped, and if so,
1146  * pretend we got a single-step exception.  This was pointed out
1147  * by Kumar Gala.  -- paulus
1148  */
1149 static void emulate_single_step(struct pt_regs *regs)
1150 {
1151 	if (single_stepping(regs))
1152 		single_step_exception(regs);
1153 }
1154 
1155 static inline int __parse_fpscr(unsigned long fpscr)
1156 {
1157 	int ret = FPE_FLTUNK;
1158 
1159 	/* Invalid operation */
1160 	if ((fpscr & FPSCR_VE) && (fpscr & FPSCR_VX))
1161 		ret = FPE_FLTINV;
1162 
1163 	/* Overflow */
1164 	else if ((fpscr & FPSCR_OE) && (fpscr & FPSCR_OX))
1165 		ret = FPE_FLTOVF;
1166 
1167 	/* Underflow */
1168 	else if ((fpscr & FPSCR_UE) && (fpscr & FPSCR_UX))
1169 		ret = FPE_FLTUND;
1170 
1171 	/* Divide by zero */
1172 	else if ((fpscr & FPSCR_ZE) && (fpscr & FPSCR_ZX))
1173 		ret = FPE_FLTDIV;
1174 
1175 	/* Inexact result */
1176 	else if ((fpscr & FPSCR_XE) && (fpscr & FPSCR_XX))
1177 		ret = FPE_FLTRES;
1178 
1179 	return ret;
1180 }
1181 
1182 static void parse_fpe(struct pt_regs *regs)
1183 {
1184 	int code = 0;
1185 
1186 	flush_fp_to_thread(current);
1187 
1188 #ifdef CONFIG_PPC_FPU_REGS
1189 	code = __parse_fpscr(current->thread.fp_state.fpscr);
1190 #endif
1191 
1192 	_exception(SIGFPE, regs, code, regs->nip);
1193 }
1194 
1195 /*
1196  * Illegal instruction emulation support.  Originally written to
1197  * provide the PVR to user applications using the mfspr rd, PVR.
1198  * Return non-zero if we can't emulate, or -EFAULT if the associated
1199  * memory access caused an access fault.  Return zero on success.
1200  *
1201  * There are a couple of ways to do this, either "decode" the instruction
1202  * or directly match lots of bits.  In this case, matching lots of
1203  * bits is faster and easier.
1204  *
1205  */
1206 static int emulate_string_inst(struct pt_regs *regs, u32 instword)
1207 {
1208 	u8 rT = (instword >> 21) & 0x1f;
1209 	u8 rA = (instword >> 16) & 0x1f;
1210 	u8 NB_RB = (instword >> 11) & 0x1f;
1211 	u32 num_bytes;
1212 	unsigned long EA;
1213 	int pos = 0;
1214 
1215 	/* Early out if we are an invalid form of lswx */
1216 	if ((instword & PPC_INST_STRING_MASK) == PPC_INST_LSWX)
1217 		if ((rT == rA) || (rT == NB_RB))
1218 			return -EINVAL;
1219 
1220 	EA = (rA == 0) ? 0 : regs->gpr[rA];
1221 
1222 	switch (instword & PPC_INST_STRING_MASK) {
1223 		case PPC_INST_LSWX:
1224 		case PPC_INST_STSWX:
1225 			EA += NB_RB;
1226 			num_bytes = regs->xer & 0x7f;
1227 			break;
1228 		case PPC_INST_LSWI:
1229 		case PPC_INST_STSWI:
1230 			num_bytes = (NB_RB == 0) ? 32 : NB_RB;
1231 			break;
1232 		default:
1233 			return -EINVAL;
1234 	}
1235 
1236 	while (num_bytes != 0)
1237 	{
1238 		u8 val;
1239 		u32 shift = 8 * (3 - (pos & 0x3));
1240 
1241 		/* if process is 32-bit, clear upper 32 bits of EA */
1242 		if ((regs->msr & MSR_64BIT) == 0)
1243 			EA &= 0xFFFFFFFF;
1244 
1245 		switch ((instword & PPC_INST_STRING_MASK)) {
1246 			case PPC_INST_LSWX:
1247 			case PPC_INST_LSWI:
1248 				if (get_user(val, (u8 __user *)EA))
1249 					return -EFAULT;
1250 				/* first time updating this reg,
1251 				 * zero it out */
1252 				if (pos == 0)
1253 					regs->gpr[rT] = 0;
1254 				regs->gpr[rT] |= val << shift;
1255 				break;
1256 			case PPC_INST_STSWI:
1257 			case PPC_INST_STSWX:
1258 				val = regs->gpr[rT] >> shift;
1259 				if (put_user(val, (u8 __user *)EA))
1260 					return -EFAULT;
1261 				break;
1262 		}
1263 		/* move EA to next address */
1264 		EA += 1;
1265 		num_bytes--;
1266 
1267 		/* manage our position within the register */
1268 		if (++pos == 4) {
1269 			pos = 0;
1270 			if (++rT == 32)
1271 				rT = 0;
1272 		}
1273 	}
1274 
1275 	return 0;
1276 }
1277 
1278 static int emulate_popcntb_inst(struct pt_regs *regs, u32 instword)
1279 {
1280 	u32 ra,rs;
1281 	unsigned long tmp;
1282 
1283 	ra = (instword >> 16) & 0x1f;
1284 	rs = (instword >> 21) & 0x1f;
1285 
1286 	tmp = regs->gpr[rs];
1287 	tmp = tmp - ((tmp >> 1) & 0x5555555555555555ULL);
1288 	tmp = (tmp & 0x3333333333333333ULL) + ((tmp >> 2) & 0x3333333333333333ULL);
1289 	tmp = (tmp + (tmp >> 4)) & 0x0f0f0f0f0f0f0f0fULL;
1290 	regs->gpr[ra] = tmp;
1291 
1292 	return 0;
1293 }
1294 
1295 static int emulate_isel(struct pt_regs *regs, u32 instword)
1296 {
1297 	u8 rT = (instword >> 21) & 0x1f;
1298 	u8 rA = (instword >> 16) & 0x1f;
1299 	u8 rB = (instword >> 11) & 0x1f;
1300 	u8 BC = (instword >> 6) & 0x1f;
1301 	u8 bit;
1302 	unsigned long tmp;
1303 
1304 	tmp = (rA == 0) ? 0 : regs->gpr[rA];
1305 	bit = (regs->ccr >> (31 - BC)) & 0x1;
1306 
1307 	regs->gpr[rT] = bit ? tmp : regs->gpr[rB];
1308 
1309 	return 0;
1310 }
1311 
1312 #ifdef CONFIG_PPC_TRANSACTIONAL_MEM
1313 static inline bool tm_abort_check(struct pt_regs *regs, int cause)
1314 {
1315         /* If we're emulating a load/store in an active transaction, we cannot
1316          * emulate it as the kernel operates in transaction suspended context.
1317          * We need to abort the transaction.  This creates a persistent TM
1318          * abort so tell the user what caused it with a new code.
1319 	 */
1320 	if (MSR_TM_TRANSACTIONAL(regs->msr)) {
1321 		tm_enable();
1322 		tm_abort(cause);
1323 		return true;
1324 	}
1325 	return false;
1326 }
1327 #else
1328 static inline bool tm_abort_check(struct pt_regs *regs, int reason)
1329 {
1330 	return false;
1331 }
1332 #endif
1333 
1334 static int emulate_instruction(struct pt_regs *regs)
1335 {
1336 	u32 instword;
1337 	u32 rd;
1338 
1339 	if (!user_mode(regs))
1340 		return -EINVAL;
1341 	CHECK_FULL_REGS(regs);
1342 
1343 	if (get_user(instword, (u32 __user *)(regs->nip)))
1344 		return -EFAULT;
1345 
1346 	/* Emulate the mfspr rD, PVR. */
1347 	if ((instword & PPC_INST_MFSPR_PVR_MASK) == PPC_INST_MFSPR_PVR) {
1348 		PPC_WARN_EMULATED(mfpvr, regs);
1349 		rd = (instword >> 21) & 0x1f;
1350 		regs->gpr[rd] = mfspr(SPRN_PVR);
1351 		return 0;
1352 	}
1353 
1354 	/* Emulating the dcba insn is just a no-op.  */
1355 	if ((instword & PPC_INST_DCBA_MASK) == PPC_INST_DCBA) {
1356 		PPC_WARN_EMULATED(dcba, regs);
1357 		return 0;
1358 	}
1359 
1360 	/* Emulate the mcrxr insn.  */
1361 	if ((instword & PPC_INST_MCRXR_MASK) == PPC_INST_MCRXR) {
1362 		int shift = (instword >> 21) & 0x1c;
1363 		unsigned long msk = 0xf0000000UL >> shift;
1364 
1365 		PPC_WARN_EMULATED(mcrxr, regs);
1366 		regs->ccr = (regs->ccr & ~msk) | ((regs->xer >> shift) & msk);
1367 		regs->xer &= ~0xf0000000UL;
1368 		return 0;
1369 	}
1370 
1371 	/* Emulate load/store string insn. */
1372 	if ((instword & PPC_INST_STRING_GEN_MASK) == PPC_INST_STRING) {
1373 		if (tm_abort_check(regs,
1374 				   TM_CAUSE_EMULATE | TM_CAUSE_PERSISTENT))
1375 			return -EINVAL;
1376 		PPC_WARN_EMULATED(string, regs);
1377 		return emulate_string_inst(regs, instword);
1378 	}
1379 
1380 	/* Emulate the popcntb (Population Count Bytes) instruction. */
1381 	if ((instword & PPC_INST_POPCNTB_MASK) == PPC_INST_POPCNTB) {
1382 		PPC_WARN_EMULATED(popcntb, regs);
1383 		return emulate_popcntb_inst(regs, instword);
1384 	}
1385 
1386 	/* Emulate isel (Integer Select) instruction */
1387 	if ((instword & PPC_INST_ISEL_MASK) == PPC_INST_ISEL) {
1388 		PPC_WARN_EMULATED(isel, regs);
1389 		return emulate_isel(regs, instword);
1390 	}
1391 
1392 	/* Emulate sync instruction variants */
1393 	if ((instword & PPC_INST_SYNC_MASK) == PPC_INST_SYNC) {
1394 		PPC_WARN_EMULATED(sync, regs);
1395 		asm volatile("sync");
1396 		return 0;
1397 	}
1398 
1399 #ifdef CONFIG_PPC64
1400 	/* Emulate the mfspr rD, DSCR. */
1401 	if ((((instword & PPC_INST_MFSPR_DSCR_USER_MASK) ==
1402 		PPC_INST_MFSPR_DSCR_USER) ||
1403 	     ((instword & PPC_INST_MFSPR_DSCR_MASK) ==
1404 		PPC_INST_MFSPR_DSCR)) &&
1405 			cpu_has_feature(CPU_FTR_DSCR)) {
1406 		PPC_WARN_EMULATED(mfdscr, regs);
1407 		rd = (instword >> 21) & 0x1f;
1408 		regs->gpr[rd] = mfspr(SPRN_DSCR);
1409 		return 0;
1410 	}
1411 	/* Emulate the mtspr DSCR, rD. */
1412 	if ((((instword & PPC_INST_MTSPR_DSCR_USER_MASK) ==
1413 		PPC_INST_MTSPR_DSCR_USER) ||
1414 	     ((instword & PPC_INST_MTSPR_DSCR_MASK) ==
1415 		PPC_INST_MTSPR_DSCR)) &&
1416 			cpu_has_feature(CPU_FTR_DSCR)) {
1417 		PPC_WARN_EMULATED(mtdscr, regs);
1418 		rd = (instword >> 21) & 0x1f;
1419 		current->thread.dscr = regs->gpr[rd];
1420 		current->thread.dscr_inherit = 1;
1421 		mtspr(SPRN_DSCR, current->thread.dscr);
1422 		return 0;
1423 	}
1424 #endif
1425 
1426 	return -EINVAL;
1427 }
1428 
1429 int is_valid_bugaddr(unsigned long addr)
1430 {
1431 	return is_kernel_addr(addr);
1432 }
1433 
1434 #ifdef CONFIG_MATH_EMULATION
1435 static int emulate_math(struct pt_regs *regs)
1436 {
1437 	int ret;
1438 	extern int do_mathemu(struct pt_regs *regs);
1439 
1440 	ret = do_mathemu(regs);
1441 	if (ret >= 0)
1442 		PPC_WARN_EMULATED(math, regs);
1443 
1444 	switch (ret) {
1445 	case 0:
1446 		emulate_single_step(regs);
1447 		return 0;
1448 	case 1: {
1449 			int code = 0;
1450 			code = __parse_fpscr(current->thread.fp_state.fpscr);
1451 			_exception(SIGFPE, regs, code, regs->nip);
1452 			return 0;
1453 		}
1454 	case -EFAULT:
1455 		_exception(SIGSEGV, regs, SEGV_MAPERR, regs->nip);
1456 		return 0;
1457 	}
1458 
1459 	return -1;
1460 }
1461 #else
1462 static inline int emulate_math(struct pt_regs *regs) { return -1; }
1463 #endif
1464 
1465 void program_check_exception(struct pt_regs *regs)
1466 {
1467 	enum ctx_state prev_state = exception_enter();
1468 	unsigned int reason = get_reason(regs);
1469 
1470 	/* We can now get here via a FP Unavailable exception if the core
1471 	 * has no FPU, in that case the reason flags will be 0 */
1472 
1473 	if (reason & REASON_FP) {
1474 		/* IEEE FP exception */
1475 		parse_fpe(regs);
1476 		goto bail;
1477 	}
1478 	if (reason & REASON_TRAP) {
1479 		unsigned long bugaddr;
1480 		/* Debugger is first in line to stop recursive faults in
1481 		 * rcu_lock, notify_die, or atomic_notifier_call_chain */
1482 		if (debugger_bpt(regs))
1483 			goto bail;
1484 
1485 		if (kprobe_handler(regs))
1486 			goto bail;
1487 
1488 		/* trap exception */
1489 		if (notify_die(DIE_BPT, "breakpoint", regs, 5, 5, SIGTRAP)
1490 				== NOTIFY_STOP)
1491 			goto bail;
1492 
1493 		bugaddr = regs->nip;
1494 		/*
1495 		 * Fixup bugaddr for BUG_ON() in real mode
1496 		 */
1497 		if (!is_kernel_addr(bugaddr) && !(regs->msr & MSR_IR))
1498 			bugaddr += PAGE_OFFSET;
1499 
1500 		if (!(regs->msr & MSR_PR) &&  /* not user-mode */
1501 		    report_bug(bugaddr, regs) == BUG_TRAP_TYPE_WARN) {
1502 			regs->nip += 4;
1503 			goto bail;
1504 		}
1505 		_exception(SIGTRAP, regs, TRAP_BRKPT, regs->nip);
1506 		goto bail;
1507 	}
1508 #ifdef CONFIG_PPC_TRANSACTIONAL_MEM
1509 	if (reason & REASON_TM) {
1510 		/* This is a TM "Bad Thing Exception" program check.
1511 		 * This occurs when:
1512 		 * -  An rfid/hrfid/mtmsrd attempts to cause an illegal
1513 		 *    transition in TM states.
1514 		 * -  A trechkpt is attempted when transactional.
1515 		 * -  A treclaim is attempted when non transactional.
1516 		 * -  A tend is illegally attempted.
1517 		 * -  writing a TM SPR when transactional.
1518 		 *
1519 		 * If usermode caused this, it's done something illegal and
1520 		 * gets a SIGILL slap on the wrist.  We call it an illegal
1521 		 * operand to distinguish from the instruction just being bad
1522 		 * (e.g. executing a 'tend' on a CPU without TM!); it's an
1523 		 * illegal /placement/ of a valid instruction.
1524 		 */
1525 		if (user_mode(regs)) {
1526 			_exception(SIGILL, regs, ILL_ILLOPN, regs->nip);
1527 			goto bail;
1528 		} else {
1529 			printk(KERN_EMERG "Unexpected TM Bad Thing exception "
1530 			       "at %lx (msr 0x%lx) tm_scratch=%llx\n",
1531 			       regs->nip, regs->msr, get_paca()->tm_scratch);
1532 			die("Unrecoverable exception", regs, SIGABRT);
1533 		}
1534 	}
1535 #endif
1536 
1537 	/*
1538 	 * If we took the program check in the kernel skip down to sending a
1539 	 * SIGILL. The subsequent cases all relate to emulating instructions
1540 	 * which we should only do for userspace. We also do not want to enable
1541 	 * interrupts for kernel faults because that might lead to further
1542 	 * faults, and loose the context of the original exception.
1543 	 */
1544 	if (!user_mode(regs))
1545 		goto sigill;
1546 
1547 	/* We restore the interrupt state now */
1548 	if (!arch_irq_disabled_regs(regs))
1549 		local_irq_enable();
1550 
1551 	/* (reason & REASON_ILLEGAL) would be the obvious thing here,
1552 	 * but there seems to be a hardware bug on the 405GP (RevD)
1553 	 * that means ESR is sometimes set incorrectly - either to
1554 	 * ESR_DST (!?) or 0.  In the process of chasing this with the
1555 	 * hardware people - not sure if it can happen on any illegal
1556 	 * instruction or only on FP instructions, whether there is a
1557 	 * pattern to occurrences etc. -dgibson 31/Mar/2003
1558 	 */
1559 	if (!emulate_math(regs))
1560 		goto bail;
1561 
1562 	/* Try to emulate it if we should. */
1563 	if (reason & (REASON_ILLEGAL | REASON_PRIVILEGED)) {
1564 		switch (emulate_instruction(regs)) {
1565 		case 0:
1566 			regs->nip += 4;
1567 			emulate_single_step(regs);
1568 			goto bail;
1569 		case -EFAULT:
1570 			_exception(SIGSEGV, regs, SEGV_MAPERR, regs->nip);
1571 			goto bail;
1572 		}
1573 	}
1574 
1575 sigill:
1576 	if (reason & REASON_PRIVILEGED)
1577 		_exception(SIGILL, regs, ILL_PRVOPC, regs->nip);
1578 	else
1579 		_exception(SIGILL, regs, ILL_ILLOPC, regs->nip);
1580 
1581 bail:
1582 	exception_exit(prev_state);
1583 }
1584 NOKPROBE_SYMBOL(program_check_exception);
1585 
1586 /*
1587  * This occurs when running in hypervisor mode on POWER6 or later
1588  * and an illegal instruction is encountered.
1589  */
1590 void emulation_assist_interrupt(struct pt_regs *regs)
1591 {
1592 	regs->msr |= REASON_ILLEGAL;
1593 	program_check_exception(regs);
1594 }
1595 NOKPROBE_SYMBOL(emulation_assist_interrupt);
1596 
1597 void alignment_exception(struct pt_regs *regs)
1598 {
1599 	enum ctx_state prev_state = exception_enter();
1600 	int sig, code, fixed = 0;
1601 	unsigned long  reason;
1602 
1603 	/* We restore the interrupt state now */
1604 	if (!arch_irq_disabled_regs(regs))
1605 		local_irq_enable();
1606 
1607 	reason = get_reason(regs);
1608 
1609 	if (reason & REASON_BOUNDARY) {
1610 		sig = SIGBUS;
1611 		code = BUS_ADRALN;
1612 		goto bad;
1613 	}
1614 
1615 	if (tm_abort_check(regs, TM_CAUSE_ALIGNMENT | TM_CAUSE_PERSISTENT))
1616 		goto bail;
1617 
1618 	/* we don't implement logging of alignment exceptions */
1619 	if (!(current->thread.align_ctl & PR_UNALIGN_SIGBUS))
1620 		fixed = fix_alignment(regs);
1621 
1622 	if (fixed == 1) {
1623 		/* skip over emulated instruction */
1624 		regs->nip += inst_length(reason);
1625 		emulate_single_step(regs);
1626 		goto bail;
1627 	}
1628 
1629 	/* Operand address was bad */
1630 	if (fixed == -EFAULT) {
1631 		sig = SIGSEGV;
1632 		code = SEGV_ACCERR;
1633 	} else {
1634 		sig = SIGBUS;
1635 		code = BUS_ADRALN;
1636 	}
1637 bad:
1638 	if (user_mode(regs))
1639 		_exception(sig, regs, code, regs->dar);
1640 	else
1641 		bad_page_fault(regs, sig);
1642 
1643 bail:
1644 	exception_exit(prev_state);
1645 }
1646 
1647 void StackOverflow(struct pt_regs *regs)
1648 {
1649 	pr_crit("Kernel stack overflow in process %s[%d], r1=%lx\n",
1650 		current->comm, task_pid_nr(current), regs->gpr[1]);
1651 	debugger(regs);
1652 	show_regs(regs);
1653 	panic("kernel stack overflow");
1654 }
1655 
1656 void stack_overflow_exception(struct pt_regs *regs)
1657 {
1658 	enum ctx_state prev_state = exception_enter();
1659 
1660 	die("Kernel stack overflow", regs, SIGSEGV);
1661 
1662 	exception_exit(prev_state);
1663 }
1664 
1665 void kernel_fp_unavailable_exception(struct pt_regs *regs)
1666 {
1667 	enum ctx_state prev_state = exception_enter();
1668 
1669 	printk(KERN_EMERG "Unrecoverable FP Unavailable Exception "
1670 			  "%lx at %lx\n", regs->trap, regs->nip);
1671 	die("Unrecoverable FP Unavailable Exception", regs, SIGABRT);
1672 
1673 	exception_exit(prev_state);
1674 }
1675 
1676 void altivec_unavailable_exception(struct pt_regs *regs)
1677 {
1678 	enum ctx_state prev_state = exception_enter();
1679 
1680 	if (user_mode(regs)) {
1681 		/* A user program has executed an altivec instruction,
1682 		   but this kernel doesn't support altivec. */
1683 		_exception(SIGILL, regs, ILL_ILLOPC, regs->nip);
1684 		goto bail;
1685 	}
1686 
1687 	printk(KERN_EMERG "Unrecoverable VMX/Altivec Unavailable Exception "
1688 			"%lx at %lx\n", regs->trap, regs->nip);
1689 	die("Unrecoverable VMX/Altivec Unavailable Exception", regs, SIGABRT);
1690 
1691 bail:
1692 	exception_exit(prev_state);
1693 }
1694 
1695 void vsx_unavailable_exception(struct pt_regs *regs)
1696 {
1697 	if (user_mode(regs)) {
1698 		/* A user program has executed an vsx instruction,
1699 		   but this kernel doesn't support vsx. */
1700 		_exception(SIGILL, regs, ILL_ILLOPC, regs->nip);
1701 		return;
1702 	}
1703 
1704 	printk(KERN_EMERG "Unrecoverable VSX Unavailable Exception "
1705 			"%lx at %lx\n", regs->trap, regs->nip);
1706 	die("Unrecoverable VSX Unavailable Exception", regs, SIGABRT);
1707 }
1708 
1709 #ifdef CONFIG_PPC64
1710 static void tm_unavailable(struct pt_regs *regs)
1711 {
1712 #ifdef CONFIG_PPC_TRANSACTIONAL_MEM
1713 	if (user_mode(regs)) {
1714 		current->thread.load_tm++;
1715 		regs->msr |= MSR_TM;
1716 		tm_enable();
1717 		tm_restore_sprs(&current->thread);
1718 		return;
1719 	}
1720 #endif
1721 	pr_emerg("Unrecoverable TM Unavailable Exception "
1722 			"%lx at %lx\n", regs->trap, regs->nip);
1723 	die("Unrecoverable TM Unavailable Exception", regs, SIGABRT);
1724 }
1725 
1726 void facility_unavailable_exception(struct pt_regs *regs)
1727 {
1728 	static char *facility_strings[] = {
1729 		[FSCR_FP_LG] = "FPU",
1730 		[FSCR_VECVSX_LG] = "VMX/VSX",
1731 		[FSCR_DSCR_LG] = "DSCR",
1732 		[FSCR_PM_LG] = "PMU SPRs",
1733 		[FSCR_BHRB_LG] = "BHRB",
1734 		[FSCR_TM_LG] = "TM",
1735 		[FSCR_EBB_LG] = "EBB",
1736 		[FSCR_TAR_LG] = "TAR",
1737 		[FSCR_MSGP_LG] = "MSGP",
1738 		[FSCR_SCV_LG] = "SCV",
1739 		[FSCR_PREFIX_LG] = "PREFIX",
1740 	};
1741 	char *facility = "unknown";
1742 	u64 value;
1743 	u32 instword, rd;
1744 	u8 status;
1745 	bool hv;
1746 
1747 	hv = (TRAP(regs) == 0xf80);
1748 	if (hv)
1749 		value = mfspr(SPRN_HFSCR);
1750 	else
1751 		value = mfspr(SPRN_FSCR);
1752 
1753 	status = value >> 56;
1754 	if ((hv || status >= 2) &&
1755 	    (status < ARRAY_SIZE(facility_strings)) &&
1756 	    facility_strings[status])
1757 		facility = facility_strings[status];
1758 
1759 	/* We should not have taken this interrupt in kernel */
1760 	if (!user_mode(regs)) {
1761 		pr_emerg("Facility '%s' unavailable (%d) exception in kernel mode at %lx\n",
1762 			 facility, status, regs->nip);
1763 		die("Unexpected facility unavailable exception", regs, SIGABRT);
1764 	}
1765 
1766 	/* We restore the interrupt state now */
1767 	if (!arch_irq_disabled_regs(regs))
1768 		local_irq_enable();
1769 
1770 	if (status == FSCR_DSCR_LG) {
1771 		/*
1772 		 * User is accessing the DSCR register using the problem
1773 		 * state only SPR number (0x03) either through a mfspr or
1774 		 * a mtspr instruction. If it is a write attempt through
1775 		 * a mtspr, then we set the inherit bit. This also allows
1776 		 * the user to write or read the register directly in the
1777 		 * future by setting via the FSCR DSCR bit. But in case it
1778 		 * is a read DSCR attempt through a mfspr instruction, we
1779 		 * just emulate the instruction instead. This code path will
1780 		 * always emulate all the mfspr instructions till the user
1781 		 * has attempted at least one mtspr instruction. This way it
1782 		 * preserves the same behaviour when the user is accessing
1783 		 * the DSCR through privilege level only SPR number (0x11)
1784 		 * which is emulated through illegal instruction exception.
1785 		 * We always leave HFSCR DSCR set.
1786 		 */
1787 		if (get_user(instword, (u32 __user *)(regs->nip))) {
1788 			pr_err("Failed to fetch the user instruction\n");
1789 			return;
1790 		}
1791 
1792 		/* Write into DSCR (mtspr 0x03, RS) */
1793 		if ((instword & PPC_INST_MTSPR_DSCR_USER_MASK)
1794 				== PPC_INST_MTSPR_DSCR_USER) {
1795 			rd = (instword >> 21) & 0x1f;
1796 			current->thread.dscr = regs->gpr[rd];
1797 			current->thread.dscr_inherit = 1;
1798 			current->thread.fscr |= FSCR_DSCR;
1799 			mtspr(SPRN_FSCR, current->thread.fscr);
1800 		}
1801 
1802 		/* Read from DSCR (mfspr RT, 0x03) */
1803 		if ((instword & PPC_INST_MFSPR_DSCR_USER_MASK)
1804 				== PPC_INST_MFSPR_DSCR_USER) {
1805 			if (emulate_instruction(regs)) {
1806 				pr_err("DSCR based mfspr emulation failed\n");
1807 				return;
1808 			}
1809 			regs->nip += 4;
1810 			emulate_single_step(regs);
1811 		}
1812 		return;
1813 	}
1814 
1815 	if (status == FSCR_TM_LG) {
1816 		/*
1817 		 * If we're here then the hardware is TM aware because it
1818 		 * generated an exception with FSRM_TM set.
1819 		 *
1820 		 * If cpu_has_feature(CPU_FTR_TM) is false, then either firmware
1821 		 * told us not to do TM, or the kernel is not built with TM
1822 		 * support.
1823 		 *
1824 		 * If both of those things are true, then userspace can spam the
1825 		 * console by triggering the printk() below just by continually
1826 		 * doing tbegin (or any TM instruction). So in that case just
1827 		 * send the process a SIGILL immediately.
1828 		 */
1829 		if (!cpu_has_feature(CPU_FTR_TM))
1830 			goto out;
1831 
1832 		tm_unavailable(regs);
1833 		return;
1834 	}
1835 
1836 	pr_err_ratelimited("%sFacility '%s' unavailable (%d), exception at 0x%lx, MSR=%lx\n",
1837 		hv ? "Hypervisor " : "", facility, status, regs->nip, regs->msr);
1838 
1839 out:
1840 	_exception(SIGILL, regs, ILL_ILLOPC, regs->nip);
1841 }
1842 #endif
1843 
1844 #ifdef CONFIG_PPC_TRANSACTIONAL_MEM
1845 
1846 void fp_unavailable_tm(struct pt_regs *regs)
1847 {
1848 	/* Note:  This does not handle any kind of FP laziness. */
1849 
1850 	TM_DEBUG("FP Unavailable trap whilst transactional at 0x%lx, MSR=%lx\n",
1851 		 regs->nip, regs->msr);
1852 
1853         /* We can only have got here if the task started using FP after
1854          * beginning the transaction.  So, the transactional regs are just a
1855          * copy of the checkpointed ones.  But, we still need to recheckpoint
1856          * as we're enabling FP for the process; it will return, abort the
1857          * transaction, and probably retry but now with FP enabled.  So the
1858          * checkpointed FP registers need to be loaded.
1859 	 */
1860 	tm_reclaim_current(TM_CAUSE_FAC_UNAV);
1861 
1862 	/*
1863 	 * Reclaim initially saved out bogus (lazy) FPRs to ckfp_state, and
1864 	 * then it was overwrite by the thr->fp_state by tm_reclaim_thread().
1865 	 *
1866 	 * At this point, ck{fp,vr}_state contains the exact values we want to
1867 	 * recheckpoint.
1868 	 */
1869 
1870 	/* Enable FP for the task: */
1871 	current->thread.load_fp = 1;
1872 
1873 	/*
1874 	 * Recheckpoint all the checkpointed ckpt, ck{fp, vr}_state registers.
1875 	 */
1876 	tm_recheckpoint(&current->thread);
1877 }
1878 
1879 void altivec_unavailable_tm(struct pt_regs *regs)
1880 {
1881 	/* See the comments in fp_unavailable_tm().  This function operates
1882 	 * the same way.
1883 	 */
1884 
1885 	TM_DEBUG("Vector Unavailable trap whilst transactional at 0x%lx,"
1886 		 "MSR=%lx\n",
1887 		 regs->nip, regs->msr);
1888 	tm_reclaim_current(TM_CAUSE_FAC_UNAV);
1889 	current->thread.load_vec = 1;
1890 	tm_recheckpoint(&current->thread);
1891 	current->thread.used_vr = 1;
1892 }
1893 
1894 void vsx_unavailable_tm(struct pt_regs *regs)
1895 {
1896 	/* See the comments in fp_unavailable_tm().  This works similarly,
1897 	 * though we're loading both FP and VEC registers in here.
1898 	 *
1899 	 * If FP isn't in use, load FP regs.  If VEC isn't in use, load VEC
1900 	 * regs.  Either way, set MSR_VSX.
1901 	 */
1902 
1903 	TM_DEBUG("VSX Unavailable trap whilst transactional at 0x%lx,"
1904 		 "MSR=%lx\n",
1905 		 regs->nip, regs->msr);
1906 
1907 	current->thread.used_vsr = 1;
1908 
1909 	/* This reclaims FP and/or VR regs if they're already enabled */
1910 	tm_reclaim_current(TM_CAUSE_FAC_UNAV);
1911 
1912 	current->thread.load_vec = 1;
1913 	current->thread.load_fp = 1;
1914 
1915 	tm_recheckpoint(&current->thread);
1916 }
1917 #endif /* CONFIG_PPC_TRANSACTIONAL_MEM */
1918 
1919 static void performance_monitor_exception_nmi(struct pt_regs *regs)
1920 {
1921 	nmi_enter();
1922 
1923 	__this_cpu_inc(irq_stat.pmu_irqs);
1924 
1925 	perf_irq(regs);
1926 
1927 	nmi_exit();
1928 }
1929 
1930 static void performance_monitor_exception_async(struct pt_regs *regs)
1931 {
1932 	irq_enter();
1933 
1934 	__this_cpu_inc(irq_stat.pmu_irqs);
1935 
1936 	perf_irq(regs);
1937 
1938 	irq_exit();
1939 }
1940 
1941 void performance_monitor_exception(struct pt_regs *regs)
1942 {
1943 	/*
1944 	 * On 64-bit, if perf interrupts hit in a local_irq_disable
1945 	 * (soft-masked) region, we consider them as NMIs. This is required to
1946 	 * prevent hash faults on user addresses when reading callchains (and
1947 	 * looks better from an irq tracing perspective).
1948 	 */
1949 	if (IS_ENABLED(CONFIG_PPC64) && unlikely(arch_irq_disabled_regs(regs)))
1950 		performance_monitor_exception_nmi(regs);
1951 	else
1952 		performance_monitor_exception_async(regs);
1953 }
1954 
1955 #ifdef CONFIG_PPC_ADV_DEBUG_REGS
1956 static void handle_debug(struct pt_regs *regs, unsigned long debug_status)
1957 {
1958 	int changed = 0;
1959 	/*
1960 	 * Determine the cause of the debug event, clear the
1961 	 * event flags and send a trap to the handler. Torez
1962 	 */
1963 	if (debug_status & (DBSR_DAC1R | DBSR_DAC1W)) {
1964 		dbcr_dac(current) &= ~(DBCR_DAC1R | DBCR_DAC1W);
1965 #ifdef CONFIG_PPC_ADV_DEBUG_DAC_RANGE
1966 		current->thread.debug.dbcr2 &= ~DBCR2_DAC12MODE;
1967 #endif
1968 		do_send_trap(regs, mfspr(SPRN_DAC1), debug_status,
1969 			     5);
1970 		changed |= 0x01;
1971 	}  else if (debug_status & (DBSR_DAC2R | DBSR_DAC2W)) {
1972 		dbcr_dac(current) &= ~(DBCR_DAC2R | DBCR_DAC2W);
1973 		do_send_trap(regs, mfspr(SPRN_DAC2), debug_status,
1974 			     6);
1975 		changed |= 0x01;
1976 	}  else if (debug_status & DBSR_IAC1) {
1977 		current->thread.debug.dbcr0 &= ~DBCR0_IAC1;
1978 		dbcr_iac_range(current) &= ~DBCR_IAC12MODE;
1979 		do_send_trap(regs, mfspr(SPRN_IAC1), debug_status,
1980 			     1);
1981 		changed |= 0x01;
1982 	}  else if (debug_status & DBSR_IAC2) {
1983 		current->thread.debug.dbcr0 &= ~DBCR0_IAC2;
1984 		do_send_trap(regs, mfspr(SPRN_IAC2), debug_status,
1985 			     2);
1986 		changed |= 0x01;
1987 	}  else if (debug_status & DBSR_IAC3) {
1988 		current->thread.debug.dbcr0 &= ~DBCR0_IAC3;
1989 		dbcr_iac_range(current) &= ~DBCR_IAC34MODE;
1990 		do_send_trap(regs, mfspr(SPRN_IAC3), debug_status,
1991 			     3);
1992 		changed |= 0x01;
1993 	}  else if (debug_status & DBSR_IAC4) {
1994 		current->thread.debug.dbcr0 &= ~DBCR0_IAC4;
1995 		do_send_trap(regs, mfspr(SPRN_IAC4), debug_status,
1996 			     4);
1997 		changed |= 0x01;
1998 	}
1999 	/*
2000 	 * At the point this routine was called, the MSR(DE) was turned off.
2001 	 * Check all other debug flags and see if that bit needs to be turned
2002 	 * back on or not.
2003 	 */
2004 	if (DBCR_ACTIVE_EVENTS(current->thread.debug.dbcr0,
2005 			       current->thread.debug.dbcr1))
2006 		regs->msr |= MSR_DE;
2007 	else
2008 		/* Make sure the IDM flag is off */
2009 		current->thread.debug.dbcr0 &= ~DBCR0_IDM;
2010 
2011 	if (changed & 0x01)
2012 		mtspr(SPRN_DBCR0, current->thread.debug.dbcr0);
2013 }
2014 
2015 void DebugException(struct pt_regs *regs)
2016 {
2017 	unsigned long debug_status = regs->dsisr;
2018 
2019 	current->thread.debug.dbsr = debug_status;
2020 
2021 	/* Hack alert: On BookE, Branch Taken stops on the branch itself, while
2022 	 * on server, it stops on the target of the branch. In order to simulate
2023 	 * the server behaviour, we thus restart right away with a single step
2024 	 * instead of stopping here when hitting a BT
2025 	 */
2026 	if (debug_status & DBSR_BT) {
2027 		regs->msr &= ~MSR_DE;
2028 
2029 		/* Disable BT */
2030 		mtspr(SPRN_DBCR0, mfspr(SPRN_DBCR0) & ~DBCR0_BT);
2031 		/* Clear the BT event */
2032 		mtspr(SPRN_DBSR, DBSR_BT);
2033 
2034 		/* Do the single step trick only when coming from userspace */
2035 		if (user_mode(regs)) {
2036 			current->thread.debug.dbcr0 &= ~DBCR0_BT;
2037 			current->thread.debug.dbcr0 |= DBCR0_IDM | DBCR0_IC;
2038 			regs->msr |= MSR_DE;
2039 			return;
2040 		}
2041 
2042 		if (kprobe_post_handler(regs))
2043 			return;
2044 
2045 		if (notify_die(DIE_SSTEP, "block_step", regs, 5,
2046 			       5, SIGTRAP) == NOTIFY_STOP) {
2047 			return;
2048 		}
2049 		if (debugger_sstep(regs))
2050 			return;
2051 	} else if (debug_status & DBSR_IC) { 	/* Instruction complete */
2052 		regs->msr &= ~MSR_DE;
2053 
2054 		/* Disable instruction completion */
2055 		mtspr(SPRN_DBCR0, mfspr(SPRN_DBCR0) & ~DBCR0_IC);
2056 		/* Clear the instruction completion event */
2057 		mtspr(SPRN_DBSR, DBSR_IC);
2058 
2059 		if (kprobe_post_handler(regs))
2060 			return;
2061 
2062 		if (notify_die(DIE_SSTEP, "single_step", regs, 5,
2063 			       5, SIGTRAP) == NOTIFY_STOP) {
2064 			return;
2065 		}
2066 
2067 		if (debugger_sstep(regs))
2068 			return;
2069 
2070 		if (user_mode(regs)) {
2071 			current->thread.debug.dbcr0 &= ~DBCR0_IC;
2072 			if (DBCR_ACTIVE_EVENTS(current->thread.debug.dbcr0,
2073 					       current->thread.debug.dbcr1))
2074 				regs->msr |= MSR_DE;
2075 			else
2076 				/* Make sure the IDM bit is off */
2077 				current->thread.debug.dbcr0 &= ~DBCR0_IDM;
2078 		}
2079 
2080 		_exception(SIGTRAP, regs, TRAP_TRACE, regs->nip);
2081 	} else
2082 		handle_debug(regs, debug_status);
2083 }
2084 NOKPROBE_SYMBOL(DebugException);
2085 #endif /* CONFIG_PPC_ADV_DEBUG_REGS */
2086 
2087 #ifdef CONFIG_ALTIVEC
2088 void altivec_assist_exception(struct pt_regs *regs)
2089 {
2090 	int err;
2091 
2092 	if (!user_mode(regs)) {
2093 		printk(KERN_EMERG "VMX/Altivec assist exception in kernel mode"
2094 		       " at %lx\n", regs->nip);
2095 		die("Kernel VMX/Altivec assist exception", regs, SIGILL);
2096 	}
2097 
2098 	flush_altivec_to_thread(current);
2099 
2100 	PPC_WARN_EMULATED(altivec, regs);
2101 	err = emulate_altivec(regs);
2102 	if (err == 0) {
2103 		regs->nip += 4;		/* skip emulated instruction */
2104 		emulate_single_step(regs);
2105 		return;
2106 	}
2107 
2108 	if (err == -EFAULT) {
2109 		/* got an error reading the instruction */
2110 		_exception(SIGSEGV, regs, SEGV_ACCERR, regs->nip);
2111 	} else {
2112 		/* didn't recognize the instruction */
2113 		/* XXX quick hack for now: set the non-Java bit in the VSCR */
2114 		printk_ratelimited(KERN_ERR "Unrecognized altivec instruction "
2115 				   "in %s at %lx\n", current->comm, regs->nip);
2116 		current->thread.vr_state.vscr.u[3] |= 0x10000;
2117 	}
2118 }
2119 #endif /* CONFIG_ALTIVEC */
2120 
2121 #ifdef CONFIG_FSL_BOOKE
2122 void CacheLockingException(struct pt_regs *regs)
2123 {
2124 	unsigned long error_code = regs->dsisr;
2125 
2126 	/* We treat cache locking instructions from the user
2127 	 * as priv ops, in the future we could try to do
2128 	 * something smarter
2129 	 */
2130 	if (error_code & (ESR_DLK|ESR_ILK))
2131 		_exception(SIGILL, regs, ILL_PRVOPC, regs->nip);
2132 	return;
2133 }
2134 #endif /* CONFIG_FSL_BOOKE */
2135 
2136 #ifdef CONFIG_SPE
2137 void SPEFloatingPointException(struct pt_regs *regs)
2138 {
2139 	extern int do_spe_mathemu(struct pt_regs *regs);
2140 	unsigned long spefscr;
2141 	int fpexc_mode;
2142 	int code = FPE_FLTUNK;
2143 	int err;
2144 
2145 	/* We restore the interrupt state now */
2146 	if (!arch_irq_disabled_regs(regs))
2147 		local_irq_enable();
2148 
2149 	flush_spe_to_thread(current);
2150 
2151 	spefscr = current->thread.spefscr;
2152 	fpexc_mode = current->thread.fpexc_mode;
2153 
2154 	if ((spefscr & SPEFSCR_FOVF) && (fpexc_mode & PR_FP_EXC_OVF)) {
2155 		code = FPE_FLTOVF;
2156 	}
2157 	else if ((spefscr & SPEFSCR_FUNF) && (fpexc_mode & PR_FP_EXC_UND)) {
2158 		code = FPE_FLTUND;
2159 	}
2160 	else if ((spefscr & SPEFSCR_FDBZ) && (fpexc_mode & PR_FP_EXC_DIV))
2161 		code = FPE_FLTDIV;
2162 	else if ((spefscr & SPEFSCR_FINV) && (fpexc_mode & PR_FP_EXC_INV)) {
2163 		code = FPE_FLTINV;
2164 	}
2165 	else if ((spefscr & (SPEFSCR_FG | SPEFSCR_FX)) && (fpexc_mode & PR_FP_EXC_RES))
2166 		code = FPE_FLTRES;
2167 
2168 	err = do_spe_mathemu(regs);
2169 	if (err == 0) {
2170 		regs->nip += 4;		/* skip emulated instruction */
2171 		emulate_single_step(regs);
2172 		return;
2173 	}
2174 
2175 	if (err == -EFAULT) {
2176 		/* got an error reading the instruction */
2177 		_exception(SIGSEGV, regs, SEGV_ACCERR, regs->nip);
2178 	} else if (err == -EINVAL) {
2179 		/* didn't recognize the instruction */
2180 		printk(KERN_ERR "unrecognized spe instruction "
2181 		       "in %s at %lx\n", current->comm, regs->nip);
2182 	} else {
2183 		_exception(SIGFPE, regs, code, regs->nip);
2184 	}
2185 
2186 	return;
2187 }
2188 
2189 void SPEFloatingPointRoundException(struct pt_regs *regs)
2190 {
2191 	extern int speround_handler(struct pt_regs *regs);
2192 	int err;
2193 
2194 	/* We restore the interrupt state now */
2195 	if (!arch_irq_disabled_regs(regs))
2196 		local_irq_enable();
2197 
2198 	preempt_disable();
2199 	if (regs->msr & MSR_SPE)
2200 		giveup_spe(current);
2201 	preempt_enable();
2202 
2203 	regs->nip -= 4;
2204 	err = speround_handler(regs);
2205 	if (err == 0) {
2206 		regs->nip += 4;		/* skip emulated instruction */
2207 		emulate_single_step(regs);
2208 		return;
2209 	}
2210 
2211 	if (err == -EFAULT) {
2212 		/* got an error reading the instruction */
2213 		_exception(SIGSEGV, regs, SEGV_ACCERR, regs->nip);
2214 	} else if (err == -EINVAL) {
2215 		/* didn't recognize the instruction */
2216 		printk(KERN_ERR "unrecognized spe instruction "
2217 		       "in %s at %lx\n", current->comm, regs->nip);
2218 	} else {
2219 		_exception(SIGFPE, regs, FPE_FLTUNK, regs->nip);
2220 		return;
2221 	}
2222 }
2223 #endif
2224 
2225 /*
2226  * We enter here if we get an unrecoverable exception, that is, one
2227  * that happened at a point where the RI (recoverable interrupt) bit
2228  * in the MSR is 0.  This indicates that SRR0/1 are live, and that
2229  * we therefore lost state by taking this exception.
2230  */
2231 void unrecoverable_exception(struct pt_regs *regs)
2232 {
2233 	pr_emerg("Unrecoverable exception %lx at %lx (msr=%lx)\n",
2234 		 regs->trap, regs->nip, regs->msr);
2235 	die("Unrecoverable exception", regs, SIGABRT);
2236 }
2237 NOKPROBE_SYMBOL(unrecoverable_exception);
2238 
2239 #if defined(CONFIG_BOOKE_WDT) || defined(CONFIG_40x)
2240 /*
2241  * Default handler for a Watchdog exception,
2242  * spins until a reboot occurs
2243  */
2244 void __attribute__ ((weak)) WatchdogHandler(struct pt_regs *regs)
2245 {
2246 	/* Generic WatchdogHandler, implement your own */
2247 	mtspr(SPRN_TCR, mfspr(SPRN_TCR)&(~TCR_WIE));
2248 	return;
2249 }
2250 
2251 void WatchdogException(struct pt_regs *regs)
2252 {
2253 	printk (KERN_EMERG "PowerPC Book-E Watchdog Exception\n");
2254 	WatchdogHandler(regs);
2255 }
2256 #endif
2257 
2258 /*
2259  * We enter here if we discover during exception entry that we are
2260  * running in supervisor mode with a userspace value in the stack pointer.
2261  */
2262 void kernel_bad_stack(struct pt_regs *regs)
2263 {
2264 	printk(KERN_EMERG "Bad kernel stack pointer %lx at %lx\n",
2265 	       regs->gpr[1], regs->nip);
2266 	die("Bad kernel stack pointer", regs, SIGABRT);
2267 }
2268 NOKPROBE_SYMBOL(kernel_bad_stack);
2269 
2270 void __init trap_init(void)
2271 {
2272 }
2273 
2274 
2275 #ifdef CONFIG_PPC_EMULATED_STATS
2276 
2277 #define WARN_EMULATED_SETUP(type)	.type = { .name = #type }
2278 
2279 struct ppc_emulated ppc_emulated = {
2280 #ifdef CONFIG_ALTIVEC
2281 	WARN_EMULATED_SETUP(altivec),
2282 #endif
2283 	WARN_EMULATED_SETUP(dcba),
2284 	WARN_EMULATED_SETUP(dcbz),
2285 	WARN_EMULATED_SETUP(fp_pair),
2286 	WARN_EMULATED_SETUP(isel),
2287 	WARN_EMULATED_SETUP(mcrxr),
2288 	WARN_EMULATED_SETUP(mfpvr),
2289 	WARN_EMULATED_SETUP(multiple),
2290 	WARN_EMULATED_SETUP(popcntb),
2291 	WARN_EMULATED_SETUP(spe),
2292 	WARN_EMULATED_SETUP(string),
2293 	WARN_EMULATED_SETUP(sync),
2294 	WARN_EMULATED_SETUP(unaligned),
2295 #ifdef CONFIG_MATH_EMULATION
2296 	WARN_EMULATED_SETUP(math),
2297 #endif
2298 #ifdef CONFIG_VSX
2299 	WARN_EMULATED_SETUP(vsx),
2300 #endif
2301 #ifdef CONFIG_PPC64
2302 	WARN_EMULATED_SETUP(mfdscr),
2303 	WARN_EMULATED_SETUP(mtdscr),
2304 	WARN_EMULATED_SETUP(lq_stq),
2305 	WARN_EMULATED_SETUP(lxvw4x),
2306 	WARN_EMULATED_SETUP(lxvh8x),
2307 	WARN_EMULATED_SETUP(lxvd2x),
2308 	WARN_EMULATED_SETUP(lxvb16x),
2309 #endif
2310 };
2311 
2312 u32 ppc_warn_emulated;
2313 
2314 void ppc_warn_emulated_print(const char *type)
2315 {
2316 	pr_warn_ratelimited("%s used emulated %s instruction\n", current->comm,
2317 			    type);
2318 }
2319 
2320 static int __init ppc_warn_emulated_init(void)
2321 {
2322 	struct dentry *dir;
2323 	unsigned int i;
2324 	struct ppc_emulated_entry *entries = (void *)&ppc_emulated;
2325 
2326 	dir = debugfs_create_dir("emulated_instructions",
2327 				 powerpc_debugfs_root);
2328 
2329 	debugfs_create_u32("do_warn", 0644, dir, &ppc_warn_emulated);
2330 
2331 	for (i = 0; i < sizeof(ppc_emulated)/sizeof(*entries); i++)
2332 		debugfs_create_u32(entries[i].name, 0644, dir,
2333 				   (u32 *)&entries[i].val.counter);
2334 
2335 	return 0;
2336 }
2337 
2338 device_initcall(ppc_warn_emulated_init);
2339 
2340 #endif /* CONFIG_PPC_EMULATED_STATS */
2341