xref: /openbmc/linux/arch/ia64/kernel/mca.c (revision 6c33a6f4)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * File:	mca.c
4  * Purpose:	Generic MCA handling layer
5  *
6  * Copyright (C) 2003 Hewlett-Packard Co
7  *	David Mosberger-Tang <davidm@hpl.hp.com>
8  *
9  * Copyright (C) 2002 Dell Inc.
10  * Copyright (C) Matt Domsch <Matt_Domsch@dell.com>
11  *
12  * Copyright (C) 2002 Intel
13  * Copyright (C) Jenna Hall <jenna.s.hall@intel.com>
14  *
15  * Copyright (C) 2001 Intel
16  * Copyright (C) Fred Lewis <frederick.v.lewis@intel.com>
17  *
18  * Copyright (C) 2000 Intel
19  * Copyright (C) Chuck Fleckenstein <cfleck@co.intel.com>
20  *
21  * Copyright (C) 1999, 2004-2008 Silicon Graphics, Inc.
22  * Copyright (C) Vijay Chander <vijay@engr.sgi.com>
23  *
24  * Copyright (C) 2006 FUJITSU LIMITED
25  * Copyright (C) Hidetoshi Seto <seto.hidetoshi@jp.fujitsu.com>
26  *
27  * 2000-03-29 Chuck Fleckenstein <cfleck@co.intel.com>
28  *	      Fixed PAL/SAL update issues, began MCA bug fixes, logging issues,
29  *	      added min save state dump, added INIT handler.
30  *
31  * 2001-01-03 Fred Lewis <frederick.v.lewis@intel.com>
32  *	      Added setup of CMCI and CPEI IRQs, logging of corrected platform
33  *	      errors, completed code for logging of corrected & uncorrected
34  *	      machine check errors, and updated for conformance with Nov. 2000
35  *	      revision of the SAL 3.0 spec.
36  *
37  * 2002-01-04 Jenna Hall <jenna.s.hall@intel.com>
38  *	      Aligned MCA stack to 16 bytes, added platform vs. CPU error flag,
39  *	      set SAL default return values, changed error record structure to
40  *	      linked list, added init call to sal_get_state_info_size().
41  *
42  * 2002-03-25 Matt Domsch <Matt_Domsch@dell.com>
43  *	      GUID cleanups.
44  *
45  * 2003-04-15 David Mosberger-Tang <davidm@hpl.hp.com>
46  *	      Added INIT backtrace support.
47  *
48  * 2003-12-08 Keith Owens <kaos@sgi.com>
49  *	      smp_call_function() must not be called from interrupt context
50  *	      (can deadlock on tasklist_lock).
51  *	      Use keventd to call smp_call_function().
52  *
53  * 2004-02-01 Keith Owens <kaos@sgi.com>
54  *	      Avoid deadlock when using printk() for MCA and INIT records.
55  *	      Delete all record printing code, moved to salinfo_decode in user
56  *	      space.  Mark variables and functions static where possible.
57  *	      Delete dead variables and functions.  Reorder to remove the need
58  *	      for forward declarations and to consolidate related code.
59  *
60  * 2005-08-12 Keith Owens <kaos@sgi.com>
61  *	      Convert MCA/INIT handlers to use per event stacks and SAL/OS
62  *	      state.
63  *
64  * 2005-10-07 Keith Owens <kaos@sgi.com>
65  *	      Add notify_die() hooks.
66  *
67  * 2006-09-15 Hidetoshi Seto <seto.hidetoshi@jp.fujitsu.com>
68  *	      Add printing support for MCA/INIT.
69  *
70  * 2007-04-27 Russ Anderson <rja@sgi.com>
71  *	      Support multiple cpus going through OS_MCA in the same event.
72  */
73 #include <linux/jiffies.h>
74 #include <linux/types.h>
75 #include <linux/init.h>
76 #include <linux/sched/signal.h>
77 #include <linux/sched/debug.h>
78 #include <linux/sched/task.h>
79 #include <linux/interrupt.h>
80 #include <linux/irq.h>
81 #include <linux/memblock.h>
82 #include <linux/acpi.h>
83 #include <linux/timer.h>
84 #include <linux/module.h>
85 #include <linux/kernel.h>
86 #include <linux/smp.h>
87 #include <linux/workqueue.h>
88 #include <linux/cpumask.h>
89 #include <linux/kdebug.h>
90 #include <linux/cpu.h>
91 #include <linux/gfp.h>
92 
93 #include <asm/delay.h>
94 #include <asm/meminit.h>
95 #include <asm/page.h>
96 #include <asm/ptrace.h>
97 #include <asm/sal.h>
98 #include <asm/mca.h>
99 #include <asm/kexec.h>
100 
101 #include <asm/irq.h>
102 #include <asm/hw_irq.h>
103 #include <asm/tlb.h>
104 
105 #include "mca_drv.h"
106 #include "entry.h"
107 
108 #if defined(IA64_MCA_DEBUG_INFO)
109 # define IA64_MCA_DEBUG(fmt...)	printk(fmt)
110 #else
111 # define IA64_MCA_DEBUG(fmt...)
112 #endif
113 
114 #define NOTIFY_INIT(event, regs, arg, spin)				\
115 do {									\
116 	if ((notify_die((event), "INIT", (regs), (arg), 0, 0)		\
117 			== NOTIFY_STOP) && ((spin) == 1))		\
118 		ia64_mca_spin(__func__);				\
119 } while (0)
120 
121 #define NOTIFY_MCA(event, regs, arg, spin)				\
122 do {									\
123 	if ((notify_die((event), "MCA", (regs), (arg), 0, 0)		\
124 			== NOTIFY_STOP) && ((spin) == 1))		\
125 		ia64_mca_spin(__func__);				\
126 } while (0)
127 
128 /* Used by mca_asm.S */
129 DEFINE_PER_CPU(u64, ia64_mca_data); /* == __per_cpu_mca[smp_processor_id()] */
130 DEFINE_PER_CPU(u64, ia64_mca_per_cpu_pte); /* PTE to map per-CPU area */
131 DEFINE_PER_CPU(u64, ia64_mca_pal_pte);	    /* PTE to map PAL code */
132 DEFINE_PER_CPU(u64, ia64_mca_pal_base);    /* vaddr PAL code granule */
133 DEFINE_PER_CPU(u64, ia64_mca_tr_reload);   /* Flag for TR reload */
134 
135 unsigned long __per_cpu_mca[NR_CPUS];
136 
137 /* In mca_asm.S */
138 extern void			ia64_os_init_dispatch_monarch (void);
139 extern void			ia64_os_init_dispatch_slave (void);
140 
141 static int monarch_cpu = -1;
142 
143 static ia64_mc_info_t		ia64_mc_info;
144 
145 #define MAX_CPE_POLL_INTERVAL (15*60*HZ) /* 15 minutes */
146 #define MIN_CPE_POLL_INTERVAL (2*60*HZ)  /* 2 minutes */
147 #define CMC_POLL_INTERVAL     (1*60*HZ)  /* 1 minute */
148 #define CPE_HISTORY_LENGTH    5
149 #define CMC_HISTORY_LENGTH    5
150 
151 static struct timer_list cpe_poll_timer;
152 static struct timer_list cmc_poll_timer;
153 /*
154  * This variable tells whether we are currently in polling mode.
155  * Start with this in the wrong state so we won't play w/ timers
156  * before the system is ready.
157  */
158 static int cmc_polling_enabled = 1;
159 
160 /*
161  * Clearing this variable prevents CPE polling from getting activated
162  * in mca_late_init.  Use it if your system doesn't provide a CPEI,
163  * but encounters problems retrieving CPE logs.  This should only be
164  * necessary for debugging.
165  */
166 static int cpe_poll_enabled = 1;
167 
168 extern void salinfo_log_wakeup(int type, u8 *buffer, u64 size, int irqsafe);
169 
170 static int mca_init __initdata;
171 
172 /*
173  * limited & delayed printing support for MCA/INIT handler
174  */
175 
176 #define mprintk(fmt...) ia64_mca_printk(fmt)
177 
178 #define MLOGBUF_SIZE (512+256*NR_CPUS)
179 #define MLOGBUF_MSGMAX 256
180 static char mlogbuf[MLOGBUF_SIZE];
181 static DEFINE_SPINLOCK(mlogbuf_wlock);	/* mca context only */
182 static DEFINE_SPINLOCK(mlogbuf_rlock);	/* normal context only */
183 static unsigned long mlogbuf_start;
184 static unsigned long mlogbuf_end;
185 static unsigned int mlogbuf_finished = 0;
186 static unsigned long mlogbuf_timestamp = 0;
187 
188 static int loglevel_save = -1;
189 #define BREAK_LOGLEVEL(__console_loglevel)		\
190 	oops_in_progress = 1;				\
191 	if (loglevel_save < 0)				\
192 		loglevel_save = __console_loglevel;	\
193 	__console_loglevel = 15;
194 
195 #define RESTORE_LOGLEVEL(__console_loglevel)		\
196 	if (loglevel_save >= 0) {			\
197 		__console_loglevel = loglevel_save;	\
198 		loglevel_save = -1;			\
199 	}						\
200 	mlogbuf_finished = 0;				\
201 	oops_in_progress = 0;
202 
203 /*
204  * Push messages into buffer, print them later if not urgent.
205  */
206 void ia64_mca_printk(const char *fmt, ...)
207 {
208 	va_list args;
209 	int printed_len;
210 	char temp_buf[MLOGBUF_MSGMAX];
211 	char *p;
212 
213 	va_start(args, fmt);
214 	printed_len = vscnprintf(temp_buf, sizeof(temp_buf), fmt, args);
215 	va_end(args);
216 
217 	/* Copy the output into mlogbuf */
218 	if (oops_in_progress) {
219 		/* mlogbuf was abandoned, use printk directly instead. */
220 		printk("%s", temp_buf);
221 	} else {
222 		spin_lock(&mlogbuf_wlock);
223 		for (p = temp_buf; *p; p++) {
224 			unsigned long next = (mlogbuf_end + 1) % MLOGBUF_SIZE;
225 			if (next != mlogbuf_start) {
226 				mlogbuf[mlogbuf_end] = *p;
227 				mlogbuf_end = next;
228 			} else {
229 				/* buffer full */
230 				break;
231 			}
232 		}
233 		mlogbuf[mlogbuf_end] = '\0';
234 		spin_unlock(&mlogbuf_wlock);
235 	}
236 }
237 EXPORT_SYMBOL(ia64_mca_printk);
238 
239 /*
240  * Print buffered messages.
241  *  NOTE: call this after returning normal context. (ex. from salinfod)
242  */
243 void ia64_mlogbuf_dump(void)
244 {
245 	char temp_buf[MLOGBUF_MSGMAX];
246 	char *p;
247 	unsigned long index;
248 	unsigned long flags;
249 	unsigned int printed_len;
250 
251 	/* Get output from mlogbuf */
252 	while (mlogbuf_start != mlogbuf_end) {
253 		temp_buf[0] = '\0';
254 		p = temp_buf;
255 		printed_len = 0;
256 
257 		spin_lock_irqsave(&mlogbuf_rlock, flags);
258 
259 		index = mlogbuf_start;
260 		while (index != mlogbuf_end) {
261 			*p = mlogbuf[index];
262 			index = (index + 1) % MLOGBUF_SIZE;
263 			if (!*p)
264 				break;
265 			p++;
266 			if (++printed_len >= MLOGBUF_MSGMAX - 1)
267 				break;
268 		}
269 		*p = '\0';
270 		if (temp_buf[0])
271 			printk("%s", temp_buf);
272 		mlogbuf_start = index;
273 
274 		mlogbuf_timestamp = 0;
275 		spin_unlock_irqrestore(&mlogbuf_rlock, flags);
276 	}
277 }
278 EXPORT_SYMBOL(ia64_mlogbuf_dump);
279 
280 /*
281  * Call this if system is going to down or if immediate flushing messages to
282  * console is required. (ex. recovery was failed, crash dump is going to be
283  * invoked, long-wait rendezvous etc.)
284  *  NOTE: this should be called from monarch.
285  */
286 static void ia64_mlogbuf_finish(int wait)
287 {
288 	BREAK_LOGLEVEL(console_loglevel);
289 
290 	spin_lock_init(&mlogbuf_rlock);
291 	ia64_mlogbuf_dump();
292 	printk(KERN_EMERG "mlogbuf_finish: printing switched to urgent mode, "
293 		"MCA/INIT might be dodgy or fail.\n");
294 
295 	if (!wait)
296 		return;
297 
298 	/* wait for console */
299 	printk("Delaying for 5 seconds...\n");
300 	udelay(5*1000000);
301 
302 	mlogbuf_finished = 1;
303 }
304 
305 /*
306  * Print buffered messages from INIT context.
307  */
308 static void ia64_mlogbuf_dump_from_init(void)
309 {
310 	if (mlogbuf_finished)
311 		return;
312 
313 	if (mlogbuf_timestamp &&
314 			time_before(jiffies, mlogbuf_timestamp + 30 * HZ)) {
315 		printk(KERN_ERR "INIT: mlogbuf_dump is interrupted by INIT "
316 			" and the system seems to be messed up.\n");
317 		ia64_mlogbuf_finish(0);
318 		return;
319 	}
320 
321 	if (!spin_trylock(&mlogbuf_rlock)) {
322 		printk(KERN_ERR "INIT: mlogbuf_dump is interrupted by INIT. "
323 			"Generated messages other than stack dump will be "
324 			"buffered to mlogbuf and will be printed later.\n");
325 		printk(KERN_ERR "INIT: If messages would not printed after "
326 			"this INIT, wait 30sec and assert INIT again.\n");
327 		if (!mlogbuf_timestamp)
328 			mlogbuf_timestamp = jiffies;
329 		return;
330 	}
331 	spin_unlock(&mlogbuf_rlock);
332 	ia64_mlogbuf_dump();
333 }
334 
335 static inline void
336 ia64_mca_spin(const char *func)
337 {
338 	if (monarch_cpu == smp_processor_id())
339 		ia64_mlogbuf_finish(0);
340 	mprintk(KERN_EMERG "%s: spinning here, not returning to SAL\n", func);
341 	while (1)
342 		cpu_relax();
343 }
344 /*
345  * IA64_MCA log support
346  */
347 #define IA64_MAX_LOGS		2	/* Double-buffering for nested MCAs */
348 #define IA64_MAX_LOG_TYPES      4   /* MCA, INIT, CMC, CPE */
349 
350 typedef struct ia64_state_log_s
351 {
352 	spinlock_t	isl_lock;
353 	int		isl_index;
354 	unsigned long	isl_count;
355 	ia64_err_rec_t  *isl_log[IA64_MAX_LOGS]; /* need space to store header + error log */
356 } ia64_state_log_t;
357 
358 static ia64_state_log_t ia64_state_log[IA64_MAX_LOG_TYPES];
359 
360 #define IA64_LOG_LOCK_INIT(it) spin_lock_init(&ia64_state_log[it].isl_lock)
361 #define IA64_LOG_LOCK(it)      spin_lock_irqsave(&ia64_state_log[it].isl_lock, s)
362 #define IA64_LOG_UNLOCK(it)    spin_unlock_irqrestore(&ia64_state_log[it].isl_lock,s)
363 #define IA64_LOG_NEXT_INDEX(it)    ia64_state_log[it].isl_index
364 #define IA64_LOG_CURR_INDEX(it)    1 - ia64_state_log[it].isl_index
365 #define IA64_LOG_INDEX_INC(it) \
366     {ia64_state_log[it].isl_index = 1 - ia64_state_log[it].isl_index; \
367     ia64_state_log[it].isl_count++;}
368 #define IA64_LOG_INDEX_DEC(it) \
369     ia64_state_log[it].isl_index = 1 - ia64_state_log[it].isl_index
370 #define IA64_LOG_NEXT_BUFFER(it)   (void *)((ia64_state_log[it].isl_log[IA64_LOG_NEXT_INDEX(it)]))
371 #define IA64_LOG_CURR_BUFFER(it)   (void *)((ia64_state_log[it].isl_log[IA64_LOG_CURR_INDEX(it)]))
372 #define IA64_LOG_COUNT(it)         ia64_state_log[it].isl_count
373 
374 static inline void ia64_log_allocate(int it, u64 size)
375 {
376 	ia64_state_log[it].isl_log[IA64_LOG_CURR_INDEX(it)] =
377 		(ia64_err_rec_t *)memblock_alloc(size, SMP_CACHE_BYTES);
378 	if (!ia64_state_log[it].isl_log[IA64_LOG_CURR_INDEX(it)])
379 		panic("%s: Failed to allocate %llu bytes\n", __func__, size);
380 
381 	ia64_state_log[it].isl_log[IA64_LOG_NEXT_INDEX(it)] =
382 		(ia64_err_rec_t *)memblock_alloc(size, SMP_CACHE_BYTES);
383 	if (!ia64_state_log[it].isl_log[IA64_LOG_NEXT_INDEX(it)])
384 		panic("%s: Failed to allocate %llu bytes\n", __func__, size);
385 }
386 
387 /*
388  * ia64_log_init
389  *	Reset the OS ia64 log buffer
390  * Inputs   :   info_type   (SAL_INFO_TYPE_{MCA,INIT,CMC,CPE})
391  * Outputs	:	None
392  */
393 static void __init
394 ia64_log_init(int sal_info_type)
395 {
396 	u64	max_size = 0;
397 
398 	IA64_LOG_NEXT_INDEX(sal_info_type) = 0;
399 	IA64_LOG_LOCK_INIT(sal_info_type);
400 
401 	// SAL will tell us the maximum size of any error record of this type
402 	max_size = ia64_sal_get_state_info_size(sal_info_type);
403 	if (!max_size)
404 		/* alloc_bootmem() doesn't like zero-sized allocations! */
405 		return;
406 
407 	// set up OS data structures to hold error info
408 	ia64_log_allocate(sal_info_type, max_size);
409 }
410 
411 /*
412  * ia64_log_get
413  *
414  *	Get the current MCA log from SAL and copy it into the OS log buffer.
415  *
416  *  Inputs  :   info_type   (SAL_INFO_TYPE_{MCA,INIT,CMC,CPE})
417  *              irq_safe    whether you can use printk at this point
418  *  Outputs :   size        (total record length)
419  *              *buffer     (ptr to error record)
420  *
421  */
422 static u64
423 ia64_log_get(int sal_info_type, u8 **buffer, int irq_safe)
424 {
425 	sal_log_record_header_t     *log_buffer;
426 	u64                         total_len = 0;
427 	unsigned long               s;
428 
429 	IA64_LOG_LOCK(sal_info_type);
430 
431 	/* Get the process state information */
432 	log_buffer = IA64_LOG_NEXT_BUFFER(sal_info_type);
433 
434 	total_len = ia64_sal_get_state_info(sal_info_type, (u64 *)log_buffer);
435 
436 	if (total_len) {
437 		IA64_LOG_INDEX_INC(sal_info_type);
438 		IA64_LOG_UNLOCK(sal_info_type);
439 		if (irq_safe) {
440 			IA64_MCA_DEBUG("%s: SAL error record type %d retrieved. Record length = %ld\n",
441 				       __func__, sal_info_type, total_len);
442 		}
443 		*buffer = (u8 *) log_buffer;
444 		return total_len;
445 	} else {
446 		IA64_LOG_UNLOCK(sal_info_type);
447 		return 0;
448 	}
449 }
450 
451 /*
452  *  ia64_mca_log_sal_error_record
453  *
454  *  This function retrieves a specified error record type from SAL
455  *  and wakes up any processes waiting for error records.
456  *
457  *  Inputs  :   sal_info_type   (Type of error record MCA/CMC/CPE)
458  *              FIXME: remove MCA and irq_safe.
459  */
460 static void
461 ia64_mca_log_sal_error_record(int sal_info_type)
462 {
463 	u8 *buffer;
464 	sal_log_record_header_t *rh;
465 	u64 size;
466 	int irq_safe = sal_info_type != SAL_INFO_TYPE_MCA;
467 #ifdef IA64_MCA_DEBUG_INFO
468 	static const char * const rec_name[] = { "MCA", "INIT", "CMC", "CPE" };
469 #endif
470 
471 	size = ia64_log_get(sal_info_type, &buffer, irq_safe);
472 	if (!size)
473 		return;
474 
475 	salinfo_log_wakeup(sal_info_type, buffer, size, irq_safe);
476 
477 	if (irq_safe)
478 		IA64_MCA_DEBUG("CPU %d: SAL log contains %s error record\n",
479 			smp_processor_id(),
480 			sal_info_type < ARRAY_SIZE(rec_name) ? rec_name[sal_info_type] : "UNKNOWN");
481 
482 	/* Clear logs from corrected errors in case there's no user-level logger */
483 	rh = (sal_log_record_header_t *)buffer;
484 	if (rh->severity == sal_log_severity_corrected)
485 		ia64_sal_clear_state_info(sal_info_type);
486 }
487 
488 /*
489  * search_mca_table
490  *  See if the MCA surfaced in an instruction range
491  *  that has been tagged as recoverable.
492  *
493  *  Inputs
494  *	first	First address range to check
495  *	last	Last address range to check
496  *	ip	Instruction pointer, address we are looking for
497  *
498  * Return value:
499  *      1 on Success (in the table)/ 0 on Failure (not in the  table)
500  */
501 int
502 search_mca_table (const struct mca_table_entry *first,
503                 const struct mca_table_entry *last,
504                 unsigned long ip)
505 {
506         const struct mca_table_entry *curr;
507         u64 curr_start, curr_end;
508 
509         curr = first;
510         while (curr <= last) {
511                 curr_start = (u64) &curr->start_addr + curr->start_addr;
512                 curr_end = (u64) &curr->end_addr + curr->end_addr;
513 
514                 if ((ip >= curr_start) && (ip <= curr_end)) {
515                         return 1;
516                 }
517                 curr++;
518         }
519         return 0;
520 }
521 
522 /* Given an address, look for it in the mca tables. */
523 int mca_recover_range(unsigned long addr)
524 {
525 	extern struct mca_table_entry __start___mca_table[];
526 	extern struct mca_table_entry __stop___mca_table[];
527 
528 	return search_mca_table(__start___mca_table, __stop___mca_table-1, addr);
529 }
530 EXPORT_SYMBOL_GPL(mca_recover_range);
531 
532 int cpe_vector = -1;
533 int ia64_cpe_irq = -1;
534 
535 static irqreturn_t
536 ia64_mca_cpe_int_handler (int cpe_irq, void *arg)
537 {
538 	static unsigned long	cpe_history[CPE_HISTORY_LENGTH];
539 	static int		index;
540 	static DEFINE_SPINLOCK(cpe_history_lock);
541 
542 	IA64_MCA_DEBUG("%s: received interrupt vector = %#x on CPU %d\n",
543 		       __func__, cpe_irq, smp_processor_id());
544 
545 	/* SAL spec states this should run w/ interrupts enabled */
546 	local_irq_enable();
547 
548 	spin_lock(&cpe_history_lock);
549 	if (!cpe_poll_enabled && cpe_vector >= 0) {
550 
551 		int i, count = 1; /* we know 1 happened now */
552 		unsigned long now = jiffies;
553 
554 		for (i = 0; i < CPE_HISTORY_LENGTH; i++) {
555 			if (now - cpe_history[i] <= HZ)
556 				count++;
557 		}
558 
559 		IA64_MCA_DEBUG(KERN_INFO "CPE threshold %d/%d\n", count, CPE_HISTORY_LENGTH);
560 		if (count >= CPE_HISTORY_LENGTH) {
561 
562 			cpe_poll_enabled = 1;
563 			spin_unlock(&cpe_history_lock);
564 			disable_irq_nosync(local_vector_to_irq(IA64_CPE_VECTOR));
565 
566 			/*
567 			 * Corrected errors will still be corrected, but
568 			 * make sure there's a log somewhere that indicates
569 			 * something is generating more than we can handle.
570 			 */
571 			printk(KERN_WARNING "WARNING: Switching to polling CPE handler; error records may be lost\n");
572 
573 			mod_timer(&cpe_poll_timer, jiffies + MIN_CPE_POLL_INTERVAL);
574 
575 			/* lock already released, get out now */
576 			goto out;
577 		} else {
578 			cpe_history[index++] = now;
579 			if (index == CPE_HISTORY_LENGTH)
580 				index = 0;
581 		}
582 	}
583 	spin_unlock(&cpe_history_lock);
584 out:
585 	/* Get the CPE error record and log it */
586 	ia64_mca_log_sal_error_record(SAL_INFO_TYPE_CPE);
587 
588 	local_irq_disable();
589 
590 	return IRQ_HANDLED;
591 }
592 
593 /*
594  * ia64_mca_register_cpev
595  *
596  *  Register the corrected platform error vector with SAL.
597  *
598  *  Inputs
599  *      cpev        Corrected Platform Error Vector number
600  *
601  *  Outputs
602  *      None
603  */
604 void
605 ia64_mca_register_cpev (int cpev)
606 {
607 	/* Register the CPE interrupt vector with SAL */
608 	struct ia64_sal_retval isrv;
609 
610 	isrv = ia64_sal_mc_set_params(SAL_MC_PARAM_CPE_INT, SAL_MC_PARAM_MECHANISM_INT, cpev, 0, 0);
611 	if (isrv.status) {
612 		printk(KERN_ERR "Failed to register Corrected Platform "
613 		       "Error interrupt vector with SAL (status %ld)\n", isrv.status);
614 		return;
615 	}
616 
617 	IA64_MCA_DEBUG("%s: corrected platform error "
618 		       "vector %#x registered\n", __func__, cpev);
619 }
620 
621 /*
622  * ia64_mca_cmc_vector_setup
623  *
624  *  Setup the corrected machine check vector register in the processor.
625  *  (The interrupt is masked on boot. ia64_mca_late_init unmask this.)
626  *  This function is invoked on a per-processor basis.
627  *
628  * Inputs
629  *      None
630  *
631  * Outputs
632  *	None
633  */
634 void
635 ia64_mca_cmc_vector_setup (void)
636 {
637 	cmcv_reg_t	cmcv;
638 
639 	cmcv.cmcv_regval	= 0;
640 	cmcv.cmcv_mask		= 1;        /* Mask/disable interrupt at first */
641 	cmcv.cmcv_vector	= IA64_CMC_VECTOR;
642 	ia64_setreg(_IA64_REG_CR_CMCV, cmcv.cmcv_regval);
643 
644 	IA64_MCA_DEBUG("%s: CPU %d corrected machine check vector %#x registered.\n",
645 		       __func__, smp_processor_id(), IA64_CMC_VECTOR);
646 
647 	IA64_MCA_DEBUG("%s: CPU %d CMCV = %#016lx\n",
648 		       __func__, smp_processor_id(), ia64_getreg(_IA64_REG_CR_CMCV));
649 }
650 
651 /*
652  * ia64_mca_cmc_vector_disable
653  *
654  *  Mask the corrected machine check vector register in the processor.
655  *  This function is invoked on a per-processor basis.
656  *
657  * Inputs
658  *      dummy(unused)
659  *
660  * Outputs
661  *	None
662  */
663 static void
664 ia64_mca_cmc_vector_disable (void *dummy)
665 {
666 	cmcv_reg_t	cmcv;
667 
668 	cmcv.cmcv_regval = ia64_getreg(_IA64_REG_CR_CMCV);
669 
670 	cmcv.cmcv_mask = 1; /* Mask/disable interrupt */
671 	ia64_setreg(_IA64_REG_CR_CMCV, cmcv.cmcv_regval);
672 
673 	IA64_MCA_DEBUG("%s: CPU %d corrected machine check vector %#x disabled.\n",
674 		       __func__, smp_processor_id(), cmcv.cmcv_vector);
675 }
676 
677 /*
678  * ia64_mca_cmc_vector_enable
679  *
680  *  Unmask the corrected machine check vector register in the processor.
681  *  This function is invoked on a per-processor basis.
682  *
683  * Inputs
684  *      dummy(unused)
685  *
686  * Outputs
687  *	None
688  */
689 static void
690 ia64_mca_cmc_vector_enable (void *dummy)
691 {
692 	cmcv_reg_t	cmcv;
693 
694 	cmcv.cmcv_regval = ia64_getreg(_IA64_REG_CR_CMCV);
695 
696 	cmcv.cmcv_mask = 0; /* Unmask/enable interrupt */
697 	ia64_setreg(_IA64_REG_CR_CMCV, cmcv.cmcv_regval);
698 
699 	IA64_MCA_DEBUG("%s: CPU %d corrected machine check vector %#x enabled.\n",
700 		       __func__, smp_processor_id(), cmcv.cmcv_vector);
701 }
702 
703 /*
704  * ia64_mca_cmc_vector_disable_keventd
705  *
706  * Called via keventd (smp_call_function() is not safe in interrupt context) to
707  * disable the cmc interrupt vector.
708  */
709 static void
710 ia64_mca_cmc_vector_disable_keventd(struct work_struct *unused)
711 {
712 	on_each_cpu(ia64_mca_cmc_vector_disable, NULL, 0);
713 }
714 
715 /*
716  * ia64_mca_cmc_vector_enable_keventd
717  *
718  * Called via keventd (smp_call_function() is not safe in interrupt context) to
719  * enable the cmc interrupt vector.
720  */
721 static void
722 ia64_mca_cmc_vector_enable_keventd(struct work_struct *unused)
723 {
724 	on_each_cpu(ia64_mca_cmc_vector_enable, NULL, 0);
725 }
726 
727 /*
728  * ia64_mca_wakeup
729  *
730  *	Send an inter-cpu interrupt to wake-up a particular cpu.
731  *
732  *  Inputs  :   cpuid
733  *  Outputs :   None
734  */
735 static void
736 ia64_mca_wakeup(int cpu)
737 {
738 	ia64_send_ipi(cpu, IA64_MCA_WAKEUP_VECTOR, IA64_IPI_DM_INT, 0);
739 }
740 
741 /*
742  * ia64_mca_wakeup_all
743  *
744  *	Wakeup all the slave cpus which have rendez'ed previously.
745  *
746  *  Inputs  :   None
747  *  Outputs :   None
748  */
749 static void
750 ia64_mca_wakeup_all(void)
751 {
752 	int cpu;
753 
754 	/* Clear the Rendez checkin flag for all cpus */
755 	for_each_online_cpu(cpu) {
756 		if (ia64_mc_info.imi_rendez_checkin[cpu] == IA64_MCA_RENDEZ_CHECKIN_DONE)
757 			ia64_mca_wakeup(cpu);
758 	}
759 
760 }
761 
762 /*
763  * ia64_mca_rendez_interrupt_handler
764  *
765  *	This is handler used to put slave processors into spinloop
766  *	while the monarch processor does the mca handling and later
767  *	wake each slave up once the monarch is done.  The state
768  *	IA64_MCA_RENDEZ_CHECKIN_DONE indicates the cpu is rendez'ed
769  *	in SAL.  The state IA64_MCA_RENDEZ_CHECKIN_NOTDONE indicates
770  *	the cpu has come out of OS rendezvous.
771  *
772  *  Inputs  :   None
773  *  Outputs :   None
774  */
775 static irqreturn_t
776 ia64_mca_rendez_int_handler(int rendez_irq, void *arg)
777 {
778 	unsigned long flags;
779 	int cpu = smp_processor_id();
780 	struct ia64_mca_notify_die nd =
781 		{ .sos = NULL, .monarch_cpu = &monarch_cpu };
782 
783 	/* Mask all interrupts */
784 	local_irq_save(flags);
785 
786 	NOTIFY_MCA(DIE_MCA_RENDZVOUS_ENTER, get_irq_regs(), (long)&nd, 1);
787 
788 	ia64_mc_info.imi_rendez_checkin[cpu] = IA64_MCA_RENDEZ_CHECKIN_DONE;
789 	/* Register with the SAL monarch that the slave has
790 	 * reached SAL
791 	 */
792 	ia64_sal_mc_rendez();
793 
794 	NOTIFY_MCA(DIE_MCA_RENDZVOUS_PROCESS, get_irq_regs(), (long)&nd, 1);
795 
796 	/* Wait for the monarch cpu to exit. */
797 	while (monarch_cpu != -1)
798 	       cpu_relax();	/* spin until monarch leaves */
799 
800 	NOTIFY_MCA(DIE_MCA_RENDZVOUS_LEAVE, get_irq_regs(), (long)&nd, 1);
801 
802 	ia64_mc_info.imi_rendez_checkin[cpu] = IA64_MCA_RENDEZ_CHECKIN_NOTDONE;
803 	/* Enable all interrupts */
804 	local_irq_restore(flags);
805 	return IRQ_HANDLED;
806 }
807 
808 /*
809  * ia64_mca_wakeup_int_handler
810  *
811  *	The interrupt handler for processing the inter-cpu interrupt to the
812  *	slave cpu which was spinning in the rendez loop.
813  *	Since this spinning is done by turning off the interrupts and
814  *	polling on the wakeup-interrupt bit in the IRR, there is
815  *	nothing useful to be done in the handler.
816  *
817  *  Inputs  :   wakeup_irq  (Wakeup-interrupt bit)
818  *	arg		(Interrupt handler specific argument)
819  *  Outputs :   None
820  *
821  */
822 static irqreturn_t
823 ia64_mca_wakeup_int_handler(int wakeup_irq, void *arg)
824 {
825 	return IRQ_HANDLED;
826 }
827 
828 /* Function pointer for extra MCA recovery */
829 int (*ia64_mca_ucmc_extension)
830 	(void*,struct ia64_sal_os_state*)
831 	= NULL;
832 
833 int
834 ia64_reg_MCA_extension(int (*fn)(void *, struct ia64_sal_os_state *))
835 {
836 	if (ia64_mca_ucmc_extension)
837 		return 1;
838 
839 	ia64_mca_ucmc_extension = fn;
840 	return 0;
841 }
842 
843 void
844 ia64_unreg_MCA_extension(void)
845 {
846 	if (ia64_mca_ucmc_extension)
847 		ia64_mca_ucmc_extension = NULL;
848 }
849 
850 EXPORT_SYMBOL(ia64_reg_MCA_extension);
851 EXPORT_SYMBOL(ia64_unreg_MCA_extension);
852 
853 
854 static inline void
855 copy_reg(const u64 *fr, u64 fnat, unsigned long *tr, unsigned long *tnat)
856 {
857 	u64 fslot, tslot, nat;
858 	*tr = *fr;
859 	fslot = ((unsigned long)fr >> 3) & 63;
860 	tslot = ((unsigned long)tr >> 3) & 63;
861 	*tnat &= ~(1UL << tslot);
862 	nat = (fnat >> fslot) & 1;
863 	*tnat |= (nat << tslot);
864 }
865 
866 /* Change the comm field on the MCA/INT task to include the pid that
867  * was interrupted, it makes for easier debugging.  If that pid was 0
868  * (swapper or nested MCA/INIT) then use the start of the previous comm
869  * field suffixed with its cpu.
870  */
871 
872 static void
873 ia64_mca_modify_comm(const struct task_struct *previous_current)
874 {
875 	char *p, comm[sizeof(current->comm)];
876 	if (previous_current->pid)
877 		snprintf(comm, sizeof(comm), "%s %d",
878 			current->comm, previous_current->pid);
879 	else {
880 		int l;
881 		if ((p = strchr(previous_current->comm, ' ')))
882 			l = p - previous_current->comm;
883 		else
884 			l = strlen(previous_current->comm);
885 		snprintf(comm, sizeof(comm), "%s %*s %d",
886 			current->comm, l, previous_current->comm,
887 			task_thread_info(previous_current)->cpu);
888 	}
889 	memcpy(current->comm, comm, sizeof(current->comm));
890 }
891 
892 static void
893 finish_pt_regs(struct pt_regs *regs, struct ia64_sal_os_state *sos,
894 		unsigned long *nat)
895 {
896 	const pal_min_state_area_t *ms = sos->pal_min_state;
897 	const u64 *bank;
898 
899 	/* If ipsr.ic then use pmsa_{iip,ipsr,ifs}, else use
900 	 * pmsa_{xip,xpsr,xfs}
901 	 */
902 	if (ia64_psr(regs)->ic) {
903 		regs->cr_iip = ms->pmsa_iip;
904 		regs->cr_ipsr = ms->pmsa_ipsr;
905 		regs->cr_ifs = ms->pmsa_ifs;
906 	} else {
907 		regs->cr_iip = ms->pmsa_xip;
908 		regs->cr_ipsr = ms->pmsa_xpsr;
909 		regs->cr_ifs = ms->pmsa_xfs;
910 
911 		sos->iip = ms->pmsa_iip;
912 		sos->ipsr = ms->pmsa_ipsr;
913 		sos->ifs = ms->pmsa_ifs;
914 	}
915 	regs->pr = ms->pmsa_pr;
916 	regs->b0 = ms->pmsa_br0;
917 	regs->ar_rsc = ms->pmsa_rsc;
918 	copy_reg(&ms->pmsa_gr[1-1], ms->pmsa_nat_bits, &regs->r1, nat);
919 	copy_reg(&ms->pmsa_gr[2-1], ms->pmsa_nat_bits, &regs->r2, nat);
920 	copy_reg(&ms->pmsa_gr[3-1], ms->pmsa_nat_bits, &regs->r3, nat);
921 	copy_reg(&ms->pmsa_gr[8-1], ms->pmsa_nat_bits, &regs->r8, nat);
922 	copy_reg(&ms->pmsa_gr[9-1], ms->pmsa_nat_bits, &regs->r9, nat);
923 	copy_reg(&ms->pmsa_gr[10-1], ms->pmsa_nat_bits, &regs->r10, nat);
924 	copy_reg(&ms->pmsa_gr[11-1], ms->pmsa_nat_bits, &regs->r11, nat);
925 	copy_reg(&ms->pmsa_gr[12-1], ms->pmsa_nat_bits, &regs->r12, nat);
926 	copy_reg(&ms->pmsa_gr[13-1], ms->pmsa_nat_bits, &regs->r13, nat);
927 	copy_reg(&ms->pmsa_gr[14-1], ms->pmsa_nat_bits, &regs->r14, nat);
928 	copy_reg(&ms->pmsa_gr[15-1], ms->pmsa_nat_bits, &regs->r15, nat);
929 	if (ia64_psr(regs)->bn)
930 		bank = ms->pmsa_bank1_gr;
931 	else
932 		bank = ms->pmsa_bank0_gr;
933 	copy_reg(&bank[16-16], ms->pmsa_nat_bits, &regs->r16, nat);
934 	copy_reg(&bank[17-16], ms->pmsa_nat_bits, &regs->r17, nat);
935 	copy_reg(&bank[18-16], ms->pmsa_nat_bits, &regs->r18, nat);
936 	copy_reg(&bank[19-16], ms->pmsa_nat_bits, &regs->r19, nat);
937 	copy_reg(&bank[20-16], ms->pmsa_nat_bits, &regs->r20, nat);
938 	copy_reg(&bank[21-16], ms->pmsa_nat_bits, &regs->r21, nat);
939 	copy_reg(&bank[22-16], ms->pmsa_nat_bits, &regs->r22, nat);
940 	copy_reg(&bank[23-16], ms->pmsa_nat_bits, &regs->r23, nat);
941 	copy_reg(&bank[24-16], ms->pmsa_nat_bits, &regs->r24, nat);
942 	copy_reg(&bank[25-16], ms->pmsa_nat_bits, &regs->r25, nat);
943 	copy_reg(&bank[26-16], ms->pmsa_nat_bits, &regs->r26, nat);
944 	copy_reg(&bank[27-16], ms->pmsa_nat_bits, &regs->r27, nat);
945 	copy_reg(&bank[28-16], ms->pmsa_nat_bits, &regs->r28, nat);
946 	copy_reg(&bank[29-16], ms->pmsa_nat_bits, &regs->r29, nat);
947 	copy_reg(&bank[30-16], ms->pmsa_nat_bits, &regs->r30, nat);
948 	copy_reg(&bank[31-16], ms->pmsa_nat_bits, &regs->r31, nat);
949 }
950 
951 /* On entry to this routine, we are running on the per cpu stack, see
952  * mca_asm.h.  The original stack has not been touched by this event.  Some of
953  * the original stack's registers will be in the RBS on this stack.  This stack
954  * also contains a partial pt_regs and switch_stack, the rest of the data is in
955  * PAL minstate.
956  *
957  * The first thing to do is modify the original stack to look like a blocked
958  * task so we can run backtrace on the original task.  Also mark the per cpu
959  * stack as current to ensure that we use the correct task state, it also means
960  * that we can do backtrace on the MCA/INIT handler code itself.
961  */
962 
963 static struct task_struct *
964 ia64_mca_modify_original_stack(struct pt_regs *regs,
965 		const struct switch_stack *sw,
966 		struct ia64_sal_os_state *sos,
967 		const char *type)
968 {
969 	char *p;
970 	ia64_va va;
971 	extern char ia64_leave_kernel[];	/* Need asm address, not function descriptor */
972 	const pal_min_state_area_t *ms = sos->pal_min_state;
973 	struct task_struct *previous_current;
974 	struct pt_regs *old_regs;
975 	struct switch_stack *old_sw;
976 	unsigned size = sizeof(struct pt_regs) +
977 			sizeof(struct switch_stack) + 16;
978 	unsigned long *old_bspstore, *old_bsp;
979 	unsigned long *new_bspstore, *new_bsp;
980 	unsigned long old_unat, old_rnat, new_rnat, nat;
981 	u64 slots, loadrs = regs->loadrs;
982 	u64 r12 = ms->pmsa_gr[12-1], r13 = ms->pmsa_gr[13-1];
983 	u64 ar_bspstore = regs->ar_bspstore;
984 	u64 ar_bsp = regs->ar_bspstore + (loadrs >> 16);
985 	const char *msg;
986 	int cpu = smp_processor_id();
987 
988 	previous_current = curr_task(cpu);
989 	ia64_set_curr_task(cpu, current);
990 	if ((p = strchr(current->comm, ' ')))
991 		*p = '\0';
992 
993 	/* Best effort attempt to cope with MCA/INIT delivered while in
994 	 * physical mode.
995 	 */
996 	regs->cr_ipsr = ms->pmsa_ipsr;
997 	if (ia64_psr(regs)->dt == 0) {
998 		va.l = r12;
999 		if (va.f.reg == 0) {
1000 			va.f.reg = 7;
1001 			r12 = va.l;
1002 		}
1003 		va.l = r13;
1004 		if (va.f.reg == 0) {
1005 			va.f.reg = 7;
1006 			r13 = va.l;
1007 		}
1008 	}
1009 	if (ia64_psr(regs)->rt == 0) {
1010 		va.l = ar_bspstore;
1011 		if (va.f.reg == 0) {
1012 			va.f.reg = 7;
1013 			ar_bspstore = va.l;
1014 		}
1015 		va.l = ar_bsp;
1016 		if (va.f.reg == 0) {
1017 			va.f.reg = 7;
1018 			ar_bsp = va.l;
1019 		}
1020 	}
1021 
1022 	/* mca_asm.S ia64_old_stack() cannot assume that the dirty registers
1023 	 * have been copied to the old stack, the old stack may fail the
1024 	 * validation tests below.  So ia64_old_stack() must restore the dirty
1025 	 * registers from the new stack.  The old and new bspstore probably
1026 	 * have different alignments, so loadrs calculated on the old bsp
1027 	 * cannot be used to restore from the new bsp.  Calculate a suitable
1028 	 * loadrs for the new stack and save it in the new pt_regs, where
1029 	 * ia64_old_stack() can get it.
1030 	 */
1031 	old_bspstore = (unsigned long *)ar_bspstore;
1032 	old_bsp = (unsigned long *)ar_bsp;
1033 	slots = ia64_rse_num_regs(old_bspstore, old_bsp);
1034 	new_bspstore = (unsigned long *)((u64)current + IA64_RBS_OFFSET);
1035 	new_bsp = ia64_rse_skip_regs(new_bspstore, slots);
1036 	regs->loadrs = (new_bsp - new_bspstore) * 8 << 16;
1037 
1038 	/* Verify the previous stack state before we change it */
1039 	if (user_mode(regs)) {
1040 		msg = "occurred in user space";
1041 		/* previous_current is guaranteed to be valid when the task was
1042 		 * in user space, so ...
1043 		 */
1044 		ia64_mca_modify_comm(previous_current);
1045 		goto no_mod;
1046 	}
1047 
1048 	if (r13 != sos->prev_IA64_KR_CURRENT) {
1049 		msg = "inconsistent previous current and r13";
1050 		goto no_mod;
1051 	}
1052 
1053 	if (!mca_recover_range(ms->pmsa_iip)) {
1054 		if ((r12 - r13) >= KERNEL_STACK_SIZE) {
1055 			msg = "inconsistent r12 and r13";
1056 			goto no_mod;
1057 		}
1058 		if ((ar_bspstore - r13) >= KERNEL_STACK_SIZE) {
1059 			msg = "inconsistent ar.bspstore and r13";
1060 			goto no_mod;
1061 		}
1062 		va.p = old_bspstore;
1063 		if (va.f.reg < 5) {
1064 			msg = "old_bspstore is in the wrong region";
1065 			goto no_mod;
1066 		}
1067 		if ((ar_bsp - r13) >= KERNEL_STACK_SIZE) {
1068 			msg = "inconsistent ar.bsp and r13";
1069 			goto no_mod;
1070 		}
1071 		size += (ia64_rse_skip_regs(old_bspstore, slots) - old_bspstore) * 8;
1072 		if (ar_bspstore + size > r12) {
1073 			msg = "no room for blocked state";
1074 			goto no_mod;
1075 		}
1076 	}
1077 
1078 	ia64_mca_modify_comm(previous_current);
1079 
1080 	/* Make the original task look blocked.  First stack a struct pt_regs,
1081 	 * describing the state at the time of interrupt.  mca_asm.S built a
1082 	 * partial pt_regs, copy it and fill in the blanks using minstate.
1083 	 */
1084 	p = (char *)r12 - sizeof(*regs);
1085 	old_regs = (struct pt_regs *)p;
1086 	memcpy(old_regs, regs, sizeof(*regs));
1087 	old_regs->loadrs = loadrs;
1088 	old_unat = old_regs->ar_unat;
1089 	finish_pt_regs(old_regs, sos, &old_unat);
1090 
1091 	/* Next stack a struct switch_stack.  mca_asm.S built a partial
1092 	 * switch_stack, copy it and fill in the blanks using pt_regs and
1093 	 * minstate.
1094 	 *
1095 	 * In the synthesized switch_stack, b0 points to ia64_leave_kernel,
1096 	 * ar.pfs is set to 0.
1097 	 *
1098 	 * unwind.c::unw_unwind() does special processing for interrupt frames.
1099 	 * It checks if the PRED_NON_SYSCALL predicate is set, if the predicate
1100 	 * is clear then unw_unwind() does _not_ adjust bsp over pt_regs.  Not
1101 	 * that this is documented, of course.  Set PRED_NON_SYSCALL in the
1102 	 * switch_stack on the original stack so it will unwind correctly when
1103 	 * unwind.c reads pt_regs.
1104 	 *
1105 	 * thread.ksp is updated to point to the synthesized switch_stack.
1106 	 */
1107 	p -= sizeof(struct switch_stack);
1108 	old_sw = (struct switch_stack *)p;
1109 	memcpy(old_sw, sw, sizeof(*sw));
1110 	old_sw->caller_unat = old_unat;
1111 	old_sw->ar_fpsr = old_regs->ar_fpsr;
1112 	copy_reg(&ms->pmsa_gr[4-1], ms->pmsa_nat_bits, &old_sw->r4, &old_unat);
1113 	copy_reg(&ms->pmsa_gr[5-1], ms->pmsa_nat_bits, &old_sw->r5, &old_unat);
1114 	copy_reg(&ms->pmsa_gr[6-1], ms->pmsa_nat_bits, &old_sw->r6, &old_unat);
1115 	copy_reg(&ms->pmsa_gr[7-1], ms->pmsa_nat_bits, &old_sw->r7, &old_unat);
1116 	old_sw->b0 = (u64)ia64_leave_kernel;
1117 	old_sw->b1 = ms->pmsa_br1;
1118 	old_sw->ar_pfs = 0;
1119 	old_sw->ar_unat = old_unat;
1120 	old_sw->pr = old_regs->pr | (1UL << PRED_NON_SYSCALL);
1121 	previous_current->thread.ksp = (u64)p - 16;
1122 
1123 	/* Finally copy the original stack's registers back to its RBS.
1124 	 * Registers from ar.bspstore through ar.bsp at the time of the event
1125 	 * are in the current RBS, copy them back to the original stack.  The
1126 	 * copy must be done register by register because the original bspstore
1127 	 * and the current one have different alignments, so the saved RNAT
1128 	 * data occurs at different places.
1129 	 *
1130 	 * mca_asm does cover, so the old_bsp already includes all registers at
1131 	 * the time of MCA/INIT.  It also does flushrs, so all registers before
1132 	 * this function have been written to backing store on the MCA/INIT
1133 	 * stack.
1134 	 */
1135 	new_rnat = ia64_get_rnat(ia64_rse_rnat_addr(new_bspstore));
1136 	old_rnat = regs->ar_rnat;
1137 	while (slots--) {
1138 		if (ia64_rse_is_rnat_slot(new_bspstore)) {
1139 			new_rnat = ia64_get_rnat(new_bspstore++);
1140 		}
1141 		if (ia64_rse_is_rnat_slot(old_bspstore)) {
1142 			*old_bspstore++ = old_rnat;
1143 			old_rnat = 0;
1144 		}
1145 		nat = (new_rnat >> ia64_rse_slot_num(new_bspstore)) & 1UL;
1146 		old_rnat &= ~(1UL << ia64_rse_slot_num(old_bspstore));
1147 		old_rnat |= (nat << ia64_rse_slot_num(old_bspstore));
1148 		*old_bspstore++ = *new_bspstore++;
1149 	}
1150 	old_sw->ar_bspstore = (unsigned long)old_bspstore;
1151 	old_sw->ar_rnat = old_rnat;
1152 
1153 	sos->prev_task = previous_current;
1154 	return previous_current;
1155 
1156 no_mod:
1157 	mprintk(KERN_INFO "cpu %d, %s %s, original stack not modified\n",
1158 			smp_processor_id(), type, msg);
1159 	old_unat = regs->ar_unat;
1160 	finish_pt_regs(regs, sos, &old_unat);
1161 	return previous_current;
1162 }
1163 
1164 /* The monarch/slave interaction is based on monarch_cpu and requires that all
1165  * slaves have entered rendezvous before the monarch leaves.  If any cpu has
1166  * not entered rendezvous yet then wait a bit.  The assumption is that any
1167  * slave that has not rendezvoused after a reasonable time is never going to do
1168  * so.  In this context, slave includes cpus that respond to the MCA rendezvous
1169  * interrupt, as well as cpus that receive the INIT slave event.
1170  */
1171 
1172 static void
1173 ia64_wait_for_slaves(int monarch, const char *type)
1174 {
1175 	int c, i , wait;
1176 
1177 	/*
1178 	 * wait 5 seconds total for slaves (arbitrary)
1179 	 */
1180 	for (i = 0; i < 5000; i++) {
1181 		wait = 0;
1182 		for_each_online_cpu(c) {
1183 			if (c == monarch)
1184 				continue;
1185 			if (ia64_mc_info.imi_rendez_checkin[c]
1186 					== IA64_MCA_RENDEZ_CHECKIN_NOTDONE) {
1187 				udelay(1000);		/* short wait */
1188 				wait = 1;
1189 				break;
1190 			}
1191 		}
1192 		if (!wait)
1193 			goto all_in;
1194 	}
1195 
1196 	/*
1197 	 * Maybe slave(s) dead. Print buffered messages immediately.
1198 	 */
1199 	ia64_mlogbuf_finish(0);
1200 	mprintk(KERN_INFO "OS %s slave did not rendezvous on cpu", type);
1201 	for_each_online_cpu(c) {
1202 		if (c == monarch)
1203 			continue;
1204 		if (ia64_mc_info.imi_rendez_checkin[c] == IA64_MCA_RENDEZ_CHECKIN_NOTDONE)
1205 			mprintk(" %d", c);
1206 	}
1207 	mprintk("\n");
1208 	return;
1209 
1210 all_in:
1211 	mprintk(KERN_INFO "All OS %s slaves have reached rendezvous\n", type);
1212 	return;
1213 }
1214 
1215 /*  mca_insert_tr
1216  *
1217  *  Switch rid when TR reload and needed!
1218  *  iord: 1: itr, 2: itr;
1219  *
1220 */
1221 static void mca_insert_tr(u64 iord)
1222 {
1223 
1224 	int i;
1225 	u64 old_rr;
1226 	struct ia64_tr_entry *p;
1227 	unsigned long psr;
1228 	int cpu = smp_processor_id();
1229 
1230 	if (!ia64_idtrs[cpu])
1231 		return;
1232 
1233 	psr = ia64_clear_ic();
1234 	for (i = IA64_TR_ALLOC_BASE; i < IA64_TR_ALLOC_MAX; i++) {
1235 		p = ia64_idtrs[cpu] + (iord - 1) * IA64_TR_ALLOC_MAX;
1236 		if (p->pte & 0x1) {
1237 			old_rr = ia64_get_rr(p->ifa);
1238 			if (old_rr != p->rr) {
1239 				ia64_set_rr(p->ifa, p->rr);
1240 				ia64_srlz_d();
1241 			}
1242 			ia64_ptr(iord, p->ifa, p->itir >> 2);
1243 			ia64_srlz_i();
1244 			if (iord & 0x1) {
1245 				ia64_itr(0x1, i, p->ifa, p->pte, p->itir >> 2);
1246 				ia64_srlz_i();
1247 			}
1248 			if (iord & 0x2) {
1249 				ia64_itr(0x2, i, p->ifa, p->pte, p->itir >> 2);
1250 				ia64_srlz_i();
1251 			}
1252 			if (old_rr != p->rr) {
1253 				ia64_set_rr(p->ifa, old_rr);
1254 				ia64_srlz_d();
1255 			}
1256 		}
1257 	}
1258 	ia64_set_psr(psr);
1259 }
1260 
1261 /*
1262  * ia64_mca_handler
1263  *
1264  *	This is uncorrectable machine check handler called from OS_MCA
1265  *	dispatch code which is in turn called from SAL_CHECK().
1266  *	This is the place where the core of OS MCA handling is done.
1267  *	Right now the logs are extracted and displayed in a well-defined
1268  *	format. This handler code is supposed to be run only on the
1269  *	monarch processor. Once the monarch is done with MCA handling
1270  *	further MCA logging is enabled by clearing logs.
1271  *	Monarch also has the duty of sending wakeup-IPIs to pull the
1272  *	slave processors out of rendezvous spinloop.
1273  *
1274  *	If multiple processors call into OS_MCA, the first will become
1275  *	the monarch.  Subsequent cpus will be recorded in the mca_cpu
1276  *	bitmask.  After the first monarch has processed its MCA, it
1277  *	will wake up the next cpu in the mca_cpu bitmask and then go
1278  *	into the rendezvous loop.  When all processors have serviced
1279  *	their MCA, the last monarch frees up the rest of the processors.
1280  */
1281 void
1282 ia64_mca_handler(struct pt_regs *regs, struct switch_stack *sw,
1283 		 struct ia64_sal_os_state *sos)
1284 {
1285 	int recover, cpu = smp_processor_id();
1286 	struct task_struct *previous_current;
1287 	struct ia64_mca_notify_die nd =
1288 		{ .sos = sos, .monarch_cpu = &monarch_cpu, .data = &recover };
1289 	static atomic_t mca_count;
1290 	static cpumask_t mca_cpu;
1291 
1292 	if (atomic_add_return(1, &mca_count) == 1) {
1293 		monarch_cpu = cpu;
1294 		sos->monarch = 1;
1295 	} else {
1296 		cpumask_set_cpu(cpu, &mca_cpu);
1297 		sos->monarch = 0;
1298 	}
1299 	mprintk(KERN_INFO "Entered OS MCA handler. PSP=%lx cpu=%d "
1300 		"monarch=%ld\n", sos->proc_state_param, cpu, sos->monarch);
1301 
1302 	previous_current = ia64_mca_modify_original_stack(regs, sw, sos, "MCA");
1303 
1304 	NOTIFY_MCA(DIE_MCA_MONARCH_ENTER, regs, (long)&nd, 1);
1305 
1306 	ia64_mc_info.imi_rendez_checkin[cpu] = IA64_MCA_RENDEZ_CHECKIN_CONCURRENT_MCA;
1307 	if (sos->monarch) {
1308 		ia64_wait_for_slaves(cpu, "MCA");
1309 
1310 		/* Wakeup all the processors which are spinning in the
1311 		 * rendezvous loop.  They will leave SAL, then spin in the OS
1312 		 * with interrupts disabled until this monarch cpu leaves the
1313 		 * MCA handler.  That gets control back to the OS so we can
1314 		 * backtrace the other cpus, backtrace when spinning in SAL
1315 		 * does not work.
1316 		 */
1317 		ia64_mca_wakeup_all();
1318 	} else {
1319 		while (cpumask_test_cpu(cpu, &mca_cpu))
1320 			cpu_relax();	/* spin until monarch wakes us */
1321 	}
1322 
1323 	NOTIFY_MCA(DIE_MCA_MONARCH_PROCESS, regs, (long)&nd, 1);
1324 
1325 	/* Get the MCA error record and log it */
1326 	ia64_mca_log_sal_error_record(SAL_INFO_TYPE_MCA);
1327 
1328 	/* MCA error recovery */
1329 	recover = (ia64_mca_ucmc_extension
1330 		&& ia64_mca_ucmc_extension(
1331 			IA64_LOG_CURR_BUFFER(SAL_INFO_TYPE_MCA),
1332 			sos));
1333 
1334 	if (recover) {
1335 		sal_log_record_header_t *rh = IA64_LOG_CURR_BUFFER(SAL_INFO_TYPE_MCA);
1336 		rh->severity = sal_log_severity_corrected;
1337 		ia64_sal_clear_state_info(SAL_INFO_TYPE_MCA);
1338 		sos->os_status = IA64_MCA_CORRECTED;
1339 	} else {
1340 		/* Dump buffered message to console */
1341 		ia64_mlogbuf_finish(1);
1342 	}
1343 
1344 	if (__this_cpu_read(ia64_mca_tr_reload)) {
1345 		mca_insert_tr(0x1); /*Reload dynamic itrs*/
1346 		mca_insert_tr(0x2); /*Reload dynamic itrs*/
1347 	}
1348 
1349 	NOTIFY_MCA(DIE_MCA_MONARCH_LEAVE, regs, (long)&nd, 1);
1350 
1351 	if (atomic_dec_return(&mca_count) > 0) {
1352 		int i;
1353 
1354 		/* wake up the next monarch cpu,
1355 		 * and put this cpu in the rendez loop.
1356 		 */
1357 		for_each_online_cpu(i) {
1358 			if (cpumask_test_cpu(i, &mca_cpu)) {
1359 				monarch_cpu = i;
1360 				cpumask_clear_cpu(i, &mca_cpu);	/* wake next cpu */
1361 				while (monarch_cpu != -1)
1362 					cpu_relax();	/* spin until last cpu leaves */
1363 				ia64_set_curr_task(cpu, previous_current);
1364 				ia64_mc_info.imi_rendez_checkin[cpu]
1365 						= IA64_MCA_RENDEZ_CHECKIN_NOTDONE;
1366 				return;
1367 			}
1368 		}
1369 	}
1370 	ia64_set_curr_task(cpu, previous_current);
1371 	ia64_mc_info.imi_rendez_checkin[cpu] = IA64_MCA_RENDEZ_CHECKIN_NOTDONE;
1372 	monarch_cpu = -1;	/* This frees the slaves and previous monarchs */
1373 }
1374 
1375 static DECLARE_WORK(cmc_disable_work, ia64_mca_cmc_vector_disable_keventd);
1376 static DECLARE_WORK(cmc_enable_work, ia64_mca_cmc_vector_enable_keventd);
1377 
1378 /*
1379  * ia64_mca_cmc_int_handler
1380  *
1381  *  This is corrected machine check interrupt handler.
1382  *	Right now the logs are extracted and displayed in a well-defined
1383  *	format.
1384  *
1385  * Inputs
1386  *      interrupt number
1387  *      client data arg ptr
1388  *
1389  * Outputs
1390  *	None
1391  */
1392 static irqreturn_t
1393 ia64_mca_cmc_int_handler(int cmc_irq, void *arg)
1394 {
1395 	static unsigned long	cmc_history[CMC_HISTORY_LENGTH];
1396 	static int		index;
1397 	static DEFINE_SPINLOCK(cmc_history_lock);
1398 
1399 	IA64_MCA_DEBUG("%s: received interrupt vector = %#x on CPU %d\n",
1400 		       __func__, cmc_irq, smp_processor_id());
1401 
1402 	/* SAL spec states this should run w/ interrupts enabled */
1403 	local_irq_enable();
1404 
1405 	spin_lock(&cmc_history_lock);
1406 	if (!cmc_polling_enabled) {
1407 		int i, count = 1; /* we know 1 happened now */
1408 		unsigned long now = jiffies;
1409 
1410 		for (i = 0; i < CMC_HISTORY_LENGTH; i++) {
1411 			if (now - cmc_history[i] <= HZ)
1412 				count++;
1413 		}
1414 
1415 		IA64_MCA_DEBUG(KERN_INFO "CMC threshold %d/%d\n", count, CMC_HISTORY_LENGTH);
1416 		if (count >= CMC_HISTORY_LENGTH) {
1417 
1418 			cmc_polling_enabled = 1;
1419 			spin_unlock(&cmc_history_lock);
1420 			/* If we're being hit with CMC interrupts, we won't
1421 			 * ever execute the schedule_work() below.  Need to
1422 			 * disable CMC interrupts on this processor now.
1423 			 */
1424 			ia64_mca_cmc_vector_disable(NULL);
1425 			schedule_work(&cmc_disable_work);
1426 
1427 			/*
1428 			 * Corrected errors will still be corrected, but
1429 			 * make sure there's a log somewhere that indicates
1430 			 * something is generating more than we can handle.
1431 			 */
1432 			printk(KERN_WARNING "WARNING: Switching to polling CMC handler; error records may be lost\n");
1433 
1434 			mod_timer(&cmc_poll_timer, jiffies + CMC_POLL_INTERVAL);
1435 
1436 			/* lock already released, get out now */
1437 			goto out;
1438 		} else {
1439 			cmc_history[index++] = now;
1440 			if (index == CMC_HISTORY_LENGTH)
1441 				index = 0;
1442 		}
1443 	}
1444 	spin_unlock(&cmc_history_lock);
1445 out:
1446 	/* Get the CMC error record and log it */
1447 	ia64_mca_log_sal_error_record(SAL_INFO_TYPE_CMC);
1448 
1449 	local_irq_disable();
1450 
1451 	return IRQ_HANDLED;
1452 }
1453 
1454 /*
1455  *  ia64_mca_cmc_int_caller
1456  *
1457  * 	Triggered by sw interrupt from CMC polling routine.  Calls
1458  * 	real interrupt handler and either triggers a sw interrupt
1459  * 	on the next cpu or does cleanup at the end.
1460  *
1461  * Inputs
1462  *	interrupt number
1463  *	client data arg ptr
1464  * Outputs
1465  * 	handled
1466  */
1467 static irqreturn_t
1468 ia64_mca_cmc_int_caller(int cmc_irq, void *arg)
1469 {
1470 	static int start_count = -1;
1471 	unsigned int cpuid;
1472 
1473 	cpuid = smp_processor_id();
1474 
1475 	/* If first cpu, update count */
1476 	if (start_count == -1)
1477 		start_count = IA64_LOG_COUNT(SAL_INFO_TYPE_CMC);
1478 
1479 	ia64_mca_cmc_int_handler(cmc_irq, arg);
1480 
1481 	cpuid = cpumask_next(cpuid+1, cpu_online_mask);
1482 
1483 	if (cpuid < nr_cpu_ids) {
1484 		ia64_send_ipi(cpuid, IA64_CMCP_VECTOR, IA64_IPI_DM_INT, 0);
1485 	} else {
1486 		/* If no log record, switch out of polling mode */
1487 		if (start_count == IA64_LOG_COUNT(SAL_INFO_TYPE_CMC)) {
1488 
1489 			printk(KERN_WARNING "Returning to interrupt driven CMC handler\n");
1490 			schedule_work(&cmc_enable_work);
1491 			cmc_polling_enabled = 0;
1492 
1493 		} else {
1494 
1495 			mod_timer(&cmc_poll_timer, jiffies + CMC_POLL_INTERVAL);
1496 		}
1497 
1498 		start_count = -1;
1499 	}
1500 
1501 	return IRQ_HANDLED;
1502 }
1503 
1504 /*
1505  *  ia64_mca_cmc_poll
1506  *
1507  *	Poll for Corrected Machine Checks (CMCs)
1508  *
1509  * Inputs   :   dummy(unused)
1510  * Outputs  :   None
1511  *
1512  */
1513 static void
1514 ia64_mca_cmc_poll (struct timer_list *unused)
1515 {
1516 	/* Trigger a CMC interrupt cascade  */
1517 	ia64_send_ipi(cpumask_first(cpu_online_mask), IA64_CMCP_VECTOR,
1518 							IA64_IPI_DM_INT, 0);
1519 }
1520 
1521 /*
1522  *  ia64_mca_cpe_int_caller
1523  *
1524  * 	Triggered by sw interrupt from CPE polling routine.  Calls
1525  * 	real interrupt handler and either triggers a sw interrupt
1526  * 	on the next cpu or does cleanup at the end.
1527  *
1528  * Inputs
1529  *	interrupt number
1530  *	client data arg ptr
1531  * Outputs
1532  * 	handled
1533  */
1534 static irqreturn_t
1535 ia64_mca_cpe_int_caller(int cpe_irq, void *arg)
1536 {
1537 	static int start_count = -1;
1538 	static int poll_time = MIN_CPE_POLL_INTERVAL;
1539 	unsigned int cpuid;
1540 
1541 	cpuid = smp_processor_id();
1542 
1543 	/* If first cpu, update count */
1544 	if (start_count == -1)
1545 		start_count = IA64_LOG_COUNT(SAL_INFO_TYPE_CPE);
1546 
1547 	ia64_mca_cpe_int_handler(cpe_irq, arg);
1548 
1549 	cpuid = cpumask_next(cpuid+1, cpu_online_mask);
1550 
1551 	if (cpuid < NR_CPUS) {
1552 		ia64_send_ipi(cpuid, IA64_CPEP_VECTOR, IA64_IPI_DM_INT, 0);
1553 	} else {
1554 		/*
1555 		 * If a log was recorded, increase our polling frequency,
1556 		 * otherwise, backoff or return to interrupt mode.
1557 		 */
1558 		if (start_count != IA64_LOG_COUNT(SAL_INFO_TYPE_CPE)) {
1559 			poll_time = max(MIN_CPE_POLL_INTERVAL, poll_time / 2);
1560 		} else if (cpe_vector < 0) {
1561 			poll_time = min(MAX_CPE_POLL_INTERVAL, poll_time * 2);
1562 		} else {
1563 			poll_time = MIN_CPE_POLL_INTERVAL;
1564 
1565 			printk(KERN_WARNING "Returning to interrupt driven CPE handler\n");
1566 			enable_irq(local_vector_to_irq(IA64_CPE_VECTOR));
1567 			cpe_poll_enabled = 0;
1568 		}
1569 
1570 		if (cpe_poll_enabled)
1571 			mod_timer(&cpe_poll_timer, jiffies + poll_time);
1572 		start_count = -1;
1573 	}
1574 
1575 	return IRQ_HANDLED;
1576 }
1577 
1578 /*
1579  *  ia64_mca_cpe_poll
1580  *
1581  *	Poll for Corrected Platform Errors (CPEs), trigger interrupt
1582  *	on first cpu, from there it will trickle through all the cpus.
1583  *
1584  * Inputs   :   dummy(unused)
1585  * Outputs  :   None
1586  *
1587  */
1588 static void
1589 ia64_mca_cpe_poll (struct timer_list *unused)
1590 {
1591 	/* Trigger a CPE interrupt cascade  */
1592 	ia64_send_ipi(cpumask_first(cpu_online_mask), IA64_CPEP_VECTOR,
1593 							IA64_IPI_DM_INT, 0);
1594 }
1595 
1596 static int
1597 default_monarch_init_process(struct notifier_block *self, unsigned long val, void *data)
1598 {
1599 	int c;
1600 	struct task_struct *g, *t;
1601 	if (val != DIE_INIT_MONARCH_PROCESS)
1602 		return NOTIFY_DONE;
1603 #ifdef CONFIG_KEXEC
1604 	if (atomic_read(&kdump_in_progress))
1605 		return NOTIFY_DONE;
1606 #endif
1607 
1608 	/*
1609 	 * FIXME: mlogbuf will brim over with INIT stack dumps.
1610 	 * To enable show_stack from INIT, we use oops_in_progress which should
1611 	 * be used in real oops. This would cause something wrong after INIT.
1612 	 */
1613 	BREAK_LOGLEVEL(console_loglevel);
1614 	ia64_mlogbuf_dump_from_init();
1615 
1616 	printk(KERN_ERR "Processes interrupted by INIT -");
1617 	for_each_online_cpu(c) {
1618 		struct ia64_sal_os_state *s;
1619 		t = __va(__per_cpu_mca[c] + IA64_MCA_CPU_INIT_STACK_OFFSET);
1620 		s = (struct ia64_sal_os_state *)((char *)t + MCA_SOS_OFFSET);
1621 		g = s->prev_task;
1622 		if (g) {
1623 			if (g->pid)
1624 				printk(" %d", g->pid);
1625 			else
1626 				printk(" %d (cpu %d task 0x%p)", g->pid, task_cpu(g), g);
1627 		}
1628 	}
1629 	printk("\n\n");
1630 	if (read_trylock(&tasklist_lock)) {
1631 		do_each_thread (g, t) {
1632 			printk("\nBacktrace of pid %d (%s)\n", t->pid, t->comm);
1633 			show_stack(t, NULL);
1634 		} while_each_thread (g, t);
1635 		read_unlock(&tasklist_lock);
1636 	}
1637 	/* FIXME: This will not restore zapped printk locks. */
1638 	RESTORE_LOGLEVEL(console_loglevel);
1639 	return NOTIFY_DONE;
1640 }
1641 
1642 /*
1643  * C portion of the OS INIT handler
1644  *
1645  * Called from ia64_os_init_dispatch
1646  *
1647  * Inputs: pointer to pt_regs where processor info was saved.  SAL/OS state for
1648  * this event.  This code is used for both monarch and slave INIT events, see
1649  * sos->monarch.
1650  *
1651  * All INIT events switch to the INIT stack and change the previous process to
1652  * blocked status.  If one of the INIT events is the monarch then we are
1653  * probably processing the nmi button/command.  Use the monarch cpu to dump all
1654  * the processes.  The slave INIT events all spin until the monarch cpu
1655  * returns.  We can also get INIT slave events for MCA, in which case the MCA
1656  * process is the monarch.
1657  */
1658 
1659 void
1660 ia64_init_handler(struct pt_regs *regs, struct switch_stack *sw,
1661 		  struct ia64_sal_os_state *sos)
1662 {
1663 	static atomic_t slaves;
1664 	static atomic_t monarchs;
1665 	struct task_struct *previous_current;
1666 	int cpu = smp_processor_id();
1667 	struct ia64_mca_notify_die nd =
1668 		{ .sos = sos, .monarch_cpu = &monarch_cpu };
1669 
1670 	NOTIFY_INIT(DIE_INIT_ENTER, regs, (long)&nd, 0);
1671 
1672 	mprintk(KERN_INFO "Entered OS INIT handler. PSP=%lx cpu=%d monarch=%ld\n",
1673 		sos->proc_state_param, cpu, sos->monarch);
1674 	salinfo_log_wakeup(SAL_INFO_TYPE_INIT, NULL, 0, 0);
1675 
1676 	previous_current = ia64_mca_modify_original_stack(regs, sw, sos, "INIT");
1677 	sos->os_status = IA64_INIT_RESUME;
1678 
1679 	/* FIXME: Workaround for broken proms that drive all INIT events as
1680 	 * slaves.  The last slave that enters is promoted to be a monarch.
1681 	 * Remove this code in September 2006, that gives platforms a year to
1682 	 * fix their proms and get their customers updated.
1683 	 */
1684 	if (!sos->monarch && atomic_add_return(1, &slaves) == num_online_cpus()) {
1685 		mprintk(KERN_WARNING "%s: Promoting cpu %d to monarch.\n",
1686 		        __func__, cpu);
1687 		atomic_dec(&slaves);
1688 		sos->monarch = 1;
1689 	}
1690 
1691 	/* FIXME: Workaround for broken proms that drive all INIT events as
1692 	 * monarchs.  Second and subsequent monarchs are demoted to slaves.
1693 	 * Remove this code in September 2006, that gives platforms a year to
1694 	 * fix their proms and get their customers updated.
1695 	 */
1696 	if (sos->monarch && atomic_add_return(1, &monarchs) > 1) {
1697 		mprintk(KERN_WARNING "%s: Demoting cpu %d to slave.\n",
1698 			       __func__, cpu);
1699 		atomic_dec(&monarchs);
1700 		sos->monarch = 0;
1701 	}
1702 
1703 	if (!sos->monarch) {
1704 		ia64_mc_info.imi_rendez_checkin[cpu] = IA64_MCA_RENDEZ_CHECKIN_INIT;
1705 
1706 #ifdef CONFIG_KEXEC
1707 		while (monarch_cpu == -1 && !atomic_read(&kdump_in_progress))
1708 			udelay(1000);
1709 #else
1710 		while (monarch_cpu == -1)
1711 			cpu_relax();	/* spin until monarch enters */
1712 #endif
1713 
1714 		NOTIFY_INIT(DIE_INIT_SLAVE_ENTER, regs, (long)&nd, 1);
1715 		NOTIFY_INIT(DIE_INIT_SLAVE_PROCESS, regs, (long)&nd, 1);
1716 
1717 #ifdef CONFIG_KEXEC
1718 		while (monarch_cpu != -1 && !atomic_read(&kdump_in_progress))
1719 			udelay(1000);
1720 #else
1721 		while (monarch_cpu != -1)
1722 			cpu_relax();	/* spin until monarch leaves */
1723 #endif
1724 
1725 		NOTIFY_INIT(DIE_INIT_SLAVE_LEAVE, regs, (long)&nd, 1);
1726 
1727 		mprintk("Slave on cpu %d returning to normal service.\n", cpu);
1728 		ia64_set_curr_task(cpu, previous_current);
1729 		ia64_mc_info.imi_rendez_checkin[cpu] = IA64_MCA_RENDEZ_CHECKIN_NOTDONE;
1730 		atomic_dec(&slaves);
1731 		return;
1732 	}
1733 
1734 	monarch_cpu = cpu;
1735 	NOTIFY_INIT(DIE_INIT_MONARCH_ENTER, regs, (long)&nd, 1);
1736 
1737 	/*
1738 	 * Wait for a bit.  On some machines (e.g., HP's zx2000 and zx6000, INIT can be
1739 	 * generated via the BMC's command-line interface, but since the console is on the
1740 	 * same serial line, the user will need some time to switch out of the BMC before
1741 	 * the dump begins.
1742 	 */
1743 	mprintk("Delaying for 5 seconds...\n");
1744 	udelay(5*1000000);
1745 	ia64_wait_for_slaves(cpu, "INIT");
1746 	/* If nobody intercepts DIE_INIT_MONARCH_PROCESS then we drop through
1747 	 * to default_monarch_init_process() above and just print all the
1748 	 * tasks.
1749 	 */
1750 	NOTIFY_INIT(DIE_INIT_MONARCH_PROCESS, regs, (long)&nd, 1);
1751 	NOTIFY_INIT(DIE_INIT_MONARCH_LEAVE, regs, (long)&nd, 1);
1752 
1753 	mprintk("\nINIT dump complete.  Monarch on cpu %d returning to normal service.\n", cpu);
1754 	atomic_dec(&monarchs);
1755 	ia64_set_curr_task(cpu, previous_current);
1756 	monarch_cpu = -1;
1757 	return;
1758 }
1759 
1760 static int __init
1761 ia64_mca_disable_cpe_polling(char *str)
1762 {
1763 	cpe_poll_enabled = 0;
1764 	return 1;
1765 }
1766 
1767 __setup("disable_cpe_poll", ia64_mca_disable_cpe_polling);
1768 
1769 static struct irqaction cmci_irqaction = {
1770 	.handler =	ia64_mca_cmc_int_handler,
1771 	.name =		"cmc_hndlr"
1772 };
1773 
1774 static struct irqaction cmcp_irqaction = {
1775 	.handler =	ia64_mca_cmc_int_caller,
1776 	.name =		"cmc_poll"
1777 };
1778 
1779 static struct irqaction mca_rdzv_irqaction = {
1780 	.handler =	ia64_mca_rendez_int_handler,
1781 	.name =		"mca_rdzv"
1782 };
1783 
1784 static struct irqaction mca_wkup_irqaction = {
1785 	.handler =	ia64_mca_wakeup_int_handler,
1786 	.name =		"mca_wkup"
1787 };
1788 
1789 static struct irqaction mca_cpe_irqaction = {
1790 	.handler =	ia64_mca_cpe_int_handler,
1791 	.name =		"cpe_hndlr"
1792 };
1793 
1794 static struct irqaction mca_cpep_irqaction = {
1795 	.handler =	ia64_mca_cpe_int_caller,
1796 	.name =		"cpe_poll"
1797 };
1798 
1799 /* Minimal format of the MCA/INIT stacks.  The pseudo processes that run on
1800  * these stacks can never sleep, they cannot return from the kernel to user
1801  * space, they do not appear in a normal ps listing.  So there is no need to
1802  * format most of the fields.
1803  */
1804 
1805 static void
1806 format_mca_init_stack(void *mca_data, unsigned long offset,
1807 		const char *type, int cpu)
1808 {
1809 	struct task_struct *p = (struct task_struct *)((char *)mca_data + offset);
1810 	struct thread_info *ti;
1811 	memset(p, 0, KERNEL_STACK_SIZE);
1812 	ti = task_thread_info(p);
1813 	ti->flags = _TIF_MCA_INIT;
1814 	ti->preempt_count = 1;
1815 	ti->task = p;
1816 	ti->cpu = cpu;
1817 	p->stack = ti;
1818 	p->state = TASK_UNINTERRUPTIBLE;
1819 	cpumask_set_cpu(cpu, &p->cpus_mask);
1820 	INIT_LIST_HEAD(&p->tasks);
1821 	p->parent = p->real_parent = p->group_leader = p;
1822 	INIT_LIST_HEAD(&p->children);
1823 	INIT_LIST_HEAD(&p->sibling);
1824 	strncpy(p->comm, type, sizeof(p->comm)-1);
1825 }
1826 
1827 /* Caller prevents this from being called after init */
1828 static void * __ref mca_bootmem(void)
1829 {
1830 	return memblock_alloc(sizeof(struct ia64_mca_cpu), KERNEL_STACK_SIZE);
1831 }
1832 
1833 /* Do per-CPU MCA-related initialization.  */
1834 void
1835 ia64_mca_cpu_init(void *cpu_data)
1836 {
1837 	void *pal_vaddr;
1838 	void *data;
1839 	long sz = sizeof(struct ia64_mca_cpu);
1840 	int cpu = smp_processor_id();
1841 	static int first_time = 1;
1842 
1843 	/*
1844 	 * Structure will already be allocated if cpu has been online,
1845 	 * then offlined.
1846 	 */
1847 	if (__per_cpu_mca[cpu]) {
1848 		data = __va(__per_cpu_mca[cpu]);
1849 	} else {
1850 		if (first_time) {
1851 			data = mca_bootmem();
1852 			first_time = 0;
1853 		} else
1854 			data = (void *)__get_free_pages(GFP_KERNEL,
1855 							get_order(sz));
1856 		if (!data)
1857 			panic("Could not allocate MCA memory for cpu %d\n",
1858 					cpu);
1859 	}
1860 	format_mca_init_stack(data, offsetof(struct ia64_mca_cpu, mca_stack),
1861 		"MCA", cpu);
1862 	format_mca_init_stack(data, offsetof(struct ia64_mca_cpu, init_stack),
1863 		"INIT", cpu);
1864 	__this_cpu_write(ia64_mca_data, (__per_cpu_mca[cpu] = __pa(data)));
1865 
1866 	/*
1867 	 * Stash away a copy of the PTE needed to map the per-CPU page.
1868 	 * We may need it during MCA recovery.
1869 	 */
1870 	__this_cpu_write(ia64_mca_per_cpu_pte,
1871 		pte_val(mk_pte_phys(__pa(cpu_data), PAGE_KERNEL)));
1872 
1873 	/*
1874 	 * Also, stash away a copy of the PAL address and the PTE
1875 	 * needed to map it.
1876 	 */
1877 	pal_vaddr = efi_get_pal_addr();
1878 	if (!pal_vaddr)
1879 		return;
1880 	__this_cpu_write(ia64_mca_pal_base,
1881 		GRANULEROUNDDOWN((unsigned long) pal_vaddr));
1882 	__this_cpu_write(ia64_mca_pal_pte, pte_val(mk_pte_phys(__pa(pal_vaddr),
1883 							      PAGE_KERNEL)));
1884 }
1885 
1886 static int ia64_mca_cpu_online(unsigned int cpu)
1887 {
1888 	unsigned long flags;
1889 
1890 	local_irq_save(flags);
1891 	if (!cmc_polling_enabled)
1892 		ia64_mca_cmc_vector_enable(NULL);
1893 	local_irq_restore(flags);
1894 	return 0;
1895 }
1896 
1897 /*
1898  * ia64_mca_init
1899  *
1900  *  Do all the system level mca specific initialization.
1901  *
1902  *	1. Register spinloop and wakeup request interrupt vectors
1903  *
1904  *	2. Register OS_MCA handler entry point
1905  *
1906  *	3. Register OS_INIT handler entry point
1907  *
1908  *  4. Initialize MCA/CMC/INIT related log buffers maintained by the OS.
1909  *
1910  *  Note that this initialization is done very early before some kernel
1911  *  services are available.
1912  *
1913  *  Inputs  :   None
1914  *
1915  *  Outputs :   None
1916  */
1917 void __init
1918 ia64_mca_init(void)
1919 {
1920 	ia64_fptr_t *init_hldlr_ptr_monarch = (ia64_fptr_t *)ia64_os_init_dispatch_monarch;
1921 	ia64_fptr_t *init_hldlr_ptr_slave = (ia64_fptr_t *)ia64_os_init_dispatch_slave;
1922 	ia64_fptr_t *mca_hldlr_ptr = (ia64_fptr_t *)ia64_os_mca_dispatch;
1923 	int i;
1924 	long rc;
1925 	struct ia64_sal_retval isrv;
1926 	unsigned long timeout = IA64_MCA_RENDEZ_TIMEOUT; /* platform specific */
1927 	static struct notifier_block default_init_monarch_nb = {
1928 		.notifier_call = default_monarch_init_process,
1929 		.priority = 0/* we need to notified last */
1930 	};
1931 
1932 	IA64_MCA_DEBUG("%s: begin\n", __func__);
1933 
1934 	/* Clear the Rendez checkin flag for all cpus */
1935 	for(i = 0 ; i < NR_CPUS; i++)
1936 		ia64_mc_info.imi_rendez_checkin[i] = IA64_MCA_RENDEZ_CHECKIN_NOTDONE;
1937 
1938 	/*
1939 	 * Register the rendezvous spinloop and wakeup mechanism with SAL
1940 	 */
1941 
1942 	/* Register the rendezvous interrupt vector with SAL */
1943 	while (1) {
1944 		isrv = ia64_sal_mc_set_params(SAL_MC_PARAM_RENDEZ_INT,
1945 					      SAL_MC_PARAM_MECHANISM_INT,
1946 					      IA64_MCA_RENDEZ_VECTOR,
1947 					      timeout,
1948 					      SAL_MC_PARAM_RZ_ALWAYS);
1949 		rc = isrv.status;
1950 		if (rc == 0)
1951 			break;
1952 		if (rc == -2) {
1953 			printk(KERN_INFO "Increasing MCA rendezvous timeout from "
1954 				"%ld to %ld milliseconds\n", timeout, isrv.v0);
1955 			timeout = isrv.v0;
1956 			NOTIFY_MCA(DIE_MCA_NEW_TIMEOUT, NULL, timeout, 0);
1957 			continue;
1958 		}
1959 		printk(KERN_ERR "Failed to register rendezvous interrupt "
1960 		       "with SAL (status %ld)\n", rc);
1961 		return;
1962 	}
1963 
1964 	/* Register the wakeup interrupt vector with SAL */
1965 	isrv = ia64_sal_mc_set_params(SAL_MC_PARAM_RENDEZ_WAKEUP,
1966 				      SAL_MC_PARAM_MECHANISM_INT,
1967 				      IA64_MCA_WAKEUP_VECTOR,
1968 				      0, 0);
1969 	rc = isrv.status;
1970 	if (rc) {
1971 		printk(KERN_ERR "Failed to register wakeup interrupt with SAL "
1972 		       "(status %ld)\n", rc);
1973 		return;
1974 	}
1975 
1976 	IA64_MCA_DEBUG("%s: registered MCA rendezvous spinloop and wakeup mech.\n", __func__);
1977 
1978 	ia64_mc_info.imi_mca_handler        = ia64_tpa(mca_hldlr_ptr->fp);
1979 	/*
1980 	 * XXX - disable SAL checksum by setting size to 0; should be
1981 	 *	ia64_tpa(ia64_os_mca_dispatch_end) - ia64_tpa(ia64_os_mca_dispatch);
1982 	 */
1983 	ia64_mc_info.imi_mca_handler_size	= 0;
1984 
1985 	/* Register the os mca handler with SAL */
1986 	if ((rc = ia64_sal_set_vectors(SAL_VECTOR_OS_MCA,
1987 				       ia64_mc_info.imi_mca_handler,
1988 				       ia64_tpa(mca_hldlr_ptr->gp),
1989 				       ia64_mc_info.imi_mca_handler_size,
1990 				       0, 0, 0)))
1991 	{
1992 		printk(KERN_ERR "Failed to register OS MCA handler with SAL "
1993 		       "(status %ld)\n", rc);
1994 		return;
1995 	}
1996 
1997 	IA64_MCA_DEBUG("%s: registered OS MCA handler with SAL at 0x%lx, gp = 0x%lx\n", __func__,
1998 		       ia64_mc_info.imi_mca_handler, ia64_tpa(mca_hldlr_ptr->gp));
1999 
2000 	/*
2001 	 * XXX - disable SAL checksum by setting size to 0, should be
2002 	 * size of the actual init handler in mca_asm.S.
2003 	 */
2004 	ia64_mc_info.imi_monarch_init_handler		= ia64_tpa(init_hldlr_ptr_monarch->fp);
2005 	ia64_mc_info.imi_monarch_init_handler_size	= 0;
2006 	ia64_mc_info.imi_slave_init_handler		= ia64_tpa(init_hldlr_ptr_slave->fp);
2007 	ia64_mc_info.imi_slave_init_handler_size	= 0;
2008 
2009 	IA64_MCA_DEBUG("%s: OS INIT handler at %lx\n", __func__,
2010 		       ia64_mc_info.imi_monarch_init_handler);
2011 
2012 	/* Register the os init handler with SAL */
2013 	if ((rc = ia64_sal_set_vectors(SAL_VECTOR_OS_INIT,
2014 				       ia64_mc_info.imi_monarch_init_handler,
2015 				       ia64_tpa(ia64_getreg(_IA64_REG_GP)),
2016 				       ia64_mc_info.imi_monarch_init_handler_size,
2017 				       ia64_mc_info.imi_slave_init_handler,
2018 				       ia64_tpa(ia64_getreg(_IA64_REG_GP)),
2019 				       ia64_mc_info.imi_slave_init_handler_size)))
2020 	{
2021 		printk(KERN_ERR "Failed to register m/s INIT handlers with SAL "
2022 		       "(status %ld)\n", rc);
2023 		return;
2024 	}
2025 	if (register_die_notifier(&default_init_monarch_nb)) {
2026 		printk(KERN_ERR "Failed to register default monarch INIT process\n");
2027 		return;
2028 	}
2029 
2030 	IA64_MCA_DEBUG("%s: registered OS INIT handler with SAL\n", __func__);
2031 
2032 	/* Initialize the areas set aside by the OS to buffer the
2033 	 * platform/processor error states for MCA/INIT/CMC
2034 	 * handling.
2035 	 */
2036 	ia64_log_init(SAL_INFO_TYPE_MCA);
2037 	ia64_log_init(SAL_INFO_TYPE_INIT);
2038 	ia64_log_init(SAL_INFO_TYPE_CMC);
2039 	ia64_log_init(SAL_INFO_TYPE_CPE);
2040 
2041 	mca_init = 1;
2042 	printk(KERN_INFO "MCA related initialization done\n");
2043 }
2044 
2045 
2046 /*
2047  * These pieces cannot be done in ia64_mca_init() because it is called before
2048  * early_irq_init() which would wipe out our percpu irq registrations. But we
2049  * cannot leave them until ia64_mca_late_init() because by then all the other
2050  * processors have been brought online and have set their own CMC vectors to
2051  * point at a non-existant action. Called from arch_early_irq_init().
2052  */
2053 void __init ia64_mca_irq_init(void)
2054 {
2055 	/*
2056 	 *  Configure the CMCI/P vector and handler. Interrupts for CMC are
2057 	 *  per-processor, so AP CMC interrupts are setup in smp_callin() (smpboot.c).
2058 	 */
2059 	register_percpu_irq(IA64_CMC_VECTOR, &cmci_irqaction);
2060 	register_percpu_irq(IA64_CMCP_VECTOR, &cmcp_irqaction);
2061 	ia64_mca_cmc_vector_setup();       /* Setup vector on BSP */
2062 
2063 	/* Setup the MCA rendezvous interrupt vector */
2064 	register_percpu_irq(IA64_MCA_RENDEZ_VECTOR, &mca_rdzv_irqaction);
2065 
2066 	/* Setup the MCA wakeup interrupt vector */
2067 	register_percpu_irq(IA64_MCA_WAKEUP_VECTOR, &mca_wkup_irqaction);
2068 
2069 	/* Setup the CPEI/P handler */
2070 	register_percpu_irq(IA64_CPEP_VECTOR, &mca_cpep_irqaction);
2071 }
2072 
2073 /*
2074  * ia64_mca_late_init
2075  *
2076  *	Opportunity to setup things that require initialization later
2077  *	than ia64_mca_init.  Setup a timer to poll for CPEs if the
2078  *	platform doesn't support an interrupt driven mechanism.
2079  *
2080  *  Inputs  :   None
2081  *  Outputs :   Status
2082  */
2083 static int __init
2084 ia64_mca_late_init(void)
2085 {
2086 	if (!mca_init)
2087 		return 0;
2088 
2089 	/* Setup the CMCI/P vector and handler */
2090 	timer_setup(&cmc_poll_timer, ia64_mca_cmc_poll, 0);
2091 
2092 	/* Unmask/enable the vector */
2093 	cmc_polling_enabled = 0;
2094 	cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "ia64/mca:online",
2095 			  ia64_mca_cpu_online, NULL);
2096 	IA64_MCA_DEBUG("%s: CMCI/P setup and enabled.\n", __func__);
2097 
2098 	/* Setup the CPEI/P vector and handler */
2099 	cpe_vector = acpi_request_vector(ACPI_INTERRUPT_CPEI);
2100 	timer_setup(&cpe_poll_timer, ia64_mca_cpe_poll, 0);
2101 
2102 	{
2103 		unsigned int irq;
2104 
2105 		if (cpe_vector >= 0) {
2106 			/* If platform supports CPEI, enable the irq. */
2107 			irq = local_vector_to_irq(cpe_vector);
2108 			if (irq > 0) {
2109 				cpe_poll_enabled = 0;
2110 				irq_set_status_flags(irq, IRQ_PER_CPU);
2111 				setup_irq(irq, &mca_cpe_irqaction);
2112 				ia64_cpe_irq = irq;
2113 				ia64_mca_register_cpev(cpe_vector);
2114 				IA64_MCA_DEBUG("%s: CPEI/P setup and enabled.\n",
2115 					__func__);
2116 				return 0;
2117 			}
2118 			printk(KERN_ERR "%s: Failed to find irq for CPE "
2119 					"interrupt handler, vector %d\n",
2120 					__func__, cpe_vector);
2121 		}
2122 		/* If platform doesn't support CPEI, get the timer going. */
2123 		if (cpe_poll_enabled) {
2124 			ia64_mca_cpe_poll(0UL);
2125 			IA64_MCA_DEBUG("%s: CPEP setup and enabled.\n", __func__);
2126 		}
2127 	}
2128 
2129 	return 0;
2130 }
2131 
2132 device_initcall(ia64_mca_late_init);
2133