1// SPDX-License-Identifier: GPL-2.0-or-later
2/*
3 * SGI NMI support routines
4 *
5 * (C) Copyright 2020 Hewlett Packard Enterprise Development LP
6 * Copyright (C) 2007-2017 Silicon Graphics, Inc. All rights reserved.
7 * Copyright (c) Mike Travis
8 */
9
10#include <linux/cpu.h>
11#include <linux/delay.h>
12#include <linux/kdb.h>
13#include <linux/kexec.h>
14#include <linux/kgdb.h>
15#include <linux/moduleparam.h>
16#include <linux/nmi.h>
17#include <linux/sched.h>
18#include <linux/sched/debug.h>
19#include <linux/slab.h>
20#include <linux/clocksource.h>
21
22#include <asm/apic.h>
23#include <asm/current.h>
24#include <asm/kdebug.h>
25#include <asm/local64.h>
26#include <asm/nmi.h>
27#include <asm/reboot.h>
28#include <asm/traps.h>
29#include <asm/uv/uv.h>
30#include <asm/uv/uv_hub.h>
31#include <asm/uv/uv_mmrs.h>
32
33/*
34 * UV handler for NMI
35 *
36 * Handle system-wide NMI events generated by the global 'power nmi' command.
37 *
38 * Basic operation is to field the NMI interrupt on each CPU and wait
39 * until all CPU's have arrived into the nmi handler.  If some CPU's do not
40 * make it into the handler, try and force them in with the IPI(NMI) signal.
41 *
42 * We also have to lessen UV Hub MMR accesses as much as possible as this
43 * disrupts the UV Hub's primary mission of directing NumaLink traffic and
44 * can cause system problems to occur.
45 *
46 * To do this we register our primary NMI notifier on the NMI_UNKNOWN
47 * chain.  This reduces the number of false NMI calls when the perf
48 * tools are running which generate an enormous number of NMIs per
49 * second (~4M/s for 1024 CPU threads).  Our secondary NMI handler is
50 * very short as it only checks that if it has been "pinged" with the
51 * IPI(NMI) signal as mentioned above, and does not read the UV Hub's MMR.
52 *
53 */
54
55static struct uv_hub_nmi_s **uv_hub_nmi_list;
56
57DEFINE_PER_CPU(struct uv_cpu_nmi_s, uv_cpu_nmi);
58
59/* Newer SMM NMI handler, not present in all systems */
60static unsigned long uvh_nmi_mmrx;		/* UVH_EVENT_OCCURRED0/1 */
61static unsigned long uvh_nmi_mmrx_clear;	/* UVH_EVENT_OCCURRED0/1_ALIAS */
62static int uvh_nmi_mmrx_shift;			/* UVH_EVENT_OCCURRED0/1_EXTIO_INT0_SHFT */
63static char *uvh_nmi_mmrx_type;			/* "EXTIO_INT0" */
64
65/* Non-zero indicates newer SMM NMI handler present */
66static unsigned long uvh_nmi_mmrx_supported;	/* UVH_EXTIO_INT0_BROADCAST */
67
68/* Indicates to BIOS that we want to use the newer SMM NMI handler */
69static unsigned long uvh_nmi_mmrx_req;		/* UVH_BIOS_KERNEL_MMR_ALIAS_2 */
70static int uvh_nmi_mmrx_req_shift;		/* 62 */
71
72/* UV hubless values */
73#define NMI_CONTROL_PORT	0x70
74#define NMI_DUMMY_PORT		0x71
75#define PAD_OWN_GPP_D_0		0x2c
76#define GPI_NMI_STS_GPP_D_0	0x164
77#define GPI_NMI_ENA_GPP_D_0	0x174
78#define STS_GPP_D_0_MASK	0x1
79#define PAD_CFG_DW0_GPP_D_0	0x4c0
80#define GPIROUTNMI		(1ul << 17)
81#define PCH_PCR_GPIO_1_BASE	0xfdae0000ul
82#define PCH_PCR_GPIO_ADDRESS(offset) (int *)((u64)(pch_base) | (u64)(offset))
83
84static u64 *pch_base;
85static unsigned long nmi_mmr;
86static unsigned long nmi_mmr_clear;
87static unsigned long nmi_mmr_pending;
88
89static atomic_t	uv_in_nmi;
90static atomic_t uv_nmi_cpu = ATOMIC_INIT(-1);
91static atomic_t uv_nmi_cpus_in_nmi = ATOMIC_INIT(-1);
92static atomic_t uv_nmi_slave_continue;
93static cpumask_var_t uv_nmi_cpu_mask;
94
95static atomic_t uv_nmi_kexec_failed;
96
97/* Values for uv_nmi_slave_continue */
98#define SLAVE_CLEAR	0
99#define SLAVE_CONTINUE	1
100#define SLAVE_EXIT	2
101
102/*
103 * Default is all stack dumps go to the console and buffer.
104 * Lower level to send to log buffer only.
105 */
106static int uv_nmi_loglevel = CONSOLE_LOGLEVEL_DEFAULT;
107module_param_named(dump_loglevel, uv_nmi_loglevel, int, 0644);
108
109/*
110 * The following values show statistics on how perf events are affecting
111 * this system.
112 */
113static int param_get_local64(char *buffer, const struct kernel_param *kp)
114{
115	return sprintf(buffer, "%lu\n", local64_read((local64_t *)kp->arg));
116}
117
118static int param_set_local64(const char *val, const struct kernel_param *kp)
119{
120	/* Clear on any write */
121	local64_set((local64_t *)kp->arg, 0);
122	return 0;
123}
124
125static const struct kernel_param_ops param_ops_local64 = {
126	.get = param_get_local64,
127	.set = param_set_local64,
128};
129#define param_check_local64(name, p) __param_check(name, p, local64_t)
130
131static local64_t uv_nmi_count;
132module_param_named(nmi_count, uv_nmi_count, local64, 0644);
133
134static local64_t uv_nmi_misses;
135module_param_named(nmi_misses, uv_nmi_misses, local64, 0644);
136
137static local64_t uv_nmi_ping_count;
138module_param_named(ping_count, uv_nmi_ping_count, local64, 0644);
139
140static local64_t uv_nmi_ping_misses;
141module_param_named(ping_misses, uv_nmi_ping_misses, local64, 0644);
142
143/*
144 * Following values allow tuning for large systems under heavy loading
145 */
146static int uv_nmi_initial_delay = 100;
147module_param_named(initial_delay, uv_nmi_initial_delay, int, 0644);
148
149static int uv_nmi_slave_delay = 100;
150module_param_named(slave_delay, uv_nmi_slave_delay, int, 0644);
151
152static int uv_nmi_loop_delay = 100;
153module_param_named(loop_delay, uv_nmi_loop_delay, int, 0644);
154
155static int uv_nmi_trigger_delay = 10000;
156module_param_named(trigger_delay, uv_nmi_trigger_delay, int, 0644);
157
158static int uv_nmi_wait_count = 100;
159module_param_named(wait_count, uv_nmi_wait_count, int, 0644);
160
161static int uv_nmi_retry_count = 500;
162module_param_named(retry_count, uv_nmi_retry_count, int, 0644);
163
164static bool uv_pch_intr_enable = true;
165static bool uv_pch_intr_now_enabled;
166module_param_named(pch_intr_enable, uv_pch_intr_enable, bool, 0644);
167
168static bool uv_pch_init_enable = true;
169module_param_named(pch_init_enable, uv_pch_init_enable, bool, 0644);
170
171static int uv_nmi_debug;
172module_param_named(debug, uv_nmi_debug, int, 0644);
173
174#define nmi_debug(fmt, ...)				\
175	do {						\
176		if (uv_nmi_debug)			\
177			pr_info(fmt, ##__VA_ARGS__);	\
178	} while (0)
179
180/* Valid NMI Actions */
181#define	ACTION_LEN	16
182static struct nmi_action {
183	char	*action;
184	char	*desc;
185} valid_acts[] = {
186	{	"kdump",	"do kernel crash dump"			},
187	{	"dump",		"dump process stack for each cpu"	},
188	{	"ips",		"dump Inst Ptr info for each cpu"	},
189	{	"kdb",		"enter KDB (needs kgdboc= assignment)"	},
190	{	"kgdb",		"enter KGDB (needs gdb target remote)"	},
191	{	"health",	"check if CPUs respond to NMI"		},
192};
193typedef char action_t[ACTION_LEN];
194static action_t uv_nmi_action = { "dump" };
195
196static int param_get_action(char *buffer, const struct kernel_param *kp)
197{
198	return sprintf(buffer, "%s\n", uv_nmi_action);
199}
200
201static int param_set_action(const char *val, const struct kernel_param *kp)
202{
203	int i;
204	int n = ARRAY_SIZE(valid_acts);
205	char arg[ACTION_LEN];
206
207	/* (remove possible '\n') */
208	strscpy(arg, val, strnchrnul(val, sizeof(arg)-1, '\n') - val + 1);
209
210	for (i = 0; i < n; i++)
211		if (!strcmp(arg, valid_acts[i].action))
212			break;
213
214	if (i < n) {
215		strscpy(uv_nmi_action, arg, sizeof(uv_nmi_action));
216		pr_info("UV: New NMI action:%s\n", uv_nmi_action);
217		return 0;
218	}
219
220	pr_err("UV: Invalid NMI action:%s, valid actions are:\n", arg);
221	for (i = 0; i < n; i++)
222		pr_err("UV: %-8s - %s\n",
223			valid_acts[i].action, valid_acts[i].desc);
224	return -EINVAL;
225}
226
227static const struct kernel_param_ops param_ops_action = {
228	.get = param_get_action,
229	.set = param_set_action,
230};
231#define param_check_action(name, p) __param_check(name, p, action_t)
232
233module_param_named(action, uv_nmi_action, action, 0644);
234
235static inline bool uv_nmi_action_is(const char *action)
236{
237	return (strncmp(uv_nmi_action, action, strlen(action)) == 0);
238}
239
240/* Setup which NMI support is present in system */
241static void uv_nmi_setup_mmrs(void)
242{
243	bool new_nmi_method_only = false;
244
245	/* First determine arch specific MMRs to handshake with BIOS */
246	if (UVH_EVENT_OCCURRED0_EXTIO_INT0_MASK) {	/* UV2,3,4 setup */
247		uvh_nmi_mmrx = UVH_EVENT_OCCURRED0;
248		uvh_nmi_mmrx_clear = UVH_EVENT_OCCURRED0_ALIAS;
249		uvh_nmi_mmrx_shift = UVH_EVENT_OCCURRED0_EXTIO_INT0_SHFT;
250		uvh_nmi_mmrx_type = "OCRD0-EXTIO_INT0";
251
252		uvh_nmi_mmrx_supported = UVH_EXTIO_INT0_BROADCAST;
253		uvh_nmi_mmrx_req = UVH_BIOS_KERNEL_MMR_ALIAS_2;
254		uvh_nmi_mmrx_req_shift = 62;
255
256	} else if (UVH_EVENT_OCCURRED1_EXTIO_INT0_MASK) { /* UV5+ setup */
257		uvh_nmi_mmrx = UVH_EVENT_OCCURRED1;
258		uvh_nmi_mmrx_clear = UVH_EVENT_OCCURRED1_ALIAS;
259		uvh_nmi_mmrx_shift = UVH_EVENT_OCCURRED1_EXTIO_INT0_SHFT;
260		uvh_nmi_mmrx_type = "OCRD1-EXTIO_INT0";
261
262		new_nmi_method_only = true;		/* Newer nmi always valid on UV5+ */
263		uvh_nmi_mmrx_req = 0;			/* no request bit to clear */
264
265	} else {
266		pr_err("UV:%s:NMI support not available on this system\n", __func__);
267		return;
268	}
269
270	/* Then find out if new NMI is supported */
271	if (new_nmi_method_only || uv_read_local_mmr(uvh_nmi_mmrx_supported)) {
272		if (uvh_nmi_mmrx_req)
273			uv_write_local_mmr(uvh_nmi_mmrx_req,
274						1UL << uvh_nmi_mmrx_req_shift);
275		nmi_mmr = uvh_nmi_mmrx;
276		nmi_mmr_clear = uvh_nmi_mmrx_clear;
277		nmi_mmr_pending = 1UL << uvh_nmi_mmrx_shift;
278		pr_info("UV: SMI NMI support: %s\n", uvh_nmi_mmrx_type);
279	} else {
280		nmi_mmr = UVH_NMI_MMR;
281		nmi_mmr_clear = UVH_NMI_MMR_CLEAR;
282		nmi_mmr_pending = 1UL << UVH_NMI_MMR_SHIFT;
283		pr_info("UV: SMI NMI support: %s\n", UVH_NMI_MMR_TYPE);
284	}
285}
286
287/* Read NMI MMR and check if NMI flag was set by BMC. */
288static inline int uv_nmi_test_mmr(struct uv_hub_nmi_s *hub_nmi)
289{
290	hub_nmi->nmi_value = uv_read_local_mmr(nmi_mmr);
291	atomic_inc(&hub_nmi->read_mmr_count);
292	return !!(hub_nmi->nmi_value & nmi_mmr_pending);
293}
294
295static inline void uv_local_mmr_clear_nmi(void)
296{
297	uv_write_local_mmr(nmi_mmr_clear, nmi_mmr_pending);
298}
299
300/*
301 * UV hubless NMI handler functions
302 */
303static inline void uv_reassert_nmi(void)
304{
305	/* (from arch/x86/include/asm/mach_traps.h) */
306	outb(0x8f, NMI_CONTROL_PORT);
307	inb(NMI_DUMMY_PORT);		/* dummy read */
308	outb(0x0f, NMI_CONTROL_PORT);
309	inb(NMI_DUMMY_PORT);		/* dummy read */
310}
311
312static void uv_init_hubless_pch_io(int offset, int mask, int data)
313{
314	int *addr = PCH_PCR_GPIO_ADDRESS(offset);
315	int readd = readl(addr);
316
317	if (mask) {			/* OR in new data */
318		int writed = (readd & ~mask) | data;
319
320		nmi_debug("UV:PCH: %p = %x & %x | %x (%x)\n",
321			addr, readd, ~mask, data, writed);
322		writel(writed, addr);
323	} else if (readd & data) {	/* clear status bit */
324		nmi_debug("UV:PCH: %p = %x\n", addr, data);
325		writel(data, addr);
326	}
327
328	(void)readl(addr);		/* flush write data */
329}
330
331static void uv_nmi_setup_hubless_intr(void)
332{
333	uv_pch_intr_now_enabled = uv_pch_intr_enable;
334
335	uv_init_hubless_pch_io(
336		PAD_CFG_DW0_GPP_D_0, GPIROUTNMI,
337		uv_pch_intr_now_enabled ? GPIROUTNMI : 0);
338
339	nmi_debug("UV:NMI: GPP_D_0 interrupt %s\n",
340		uv_pch_intr_now_enabled ? "enabled" : "disabled");
341}
342
343static struct init_nmi {
344	unsigned int	offset;
345	unsigned int	mask;
346	unsigned int	data;
347} init_nmi[] = {
348	{	/* HOSTSW_OWN_GPP_D_0 */
349	.offset = 0x84,
350	.mask = 0x1,
351	.data = 0x0,	/* ACPI Mode */
352	},
353
354/* Clear status: */
355	{	/* GPI_INT_STS_GPP_D_0 */
356	.offset = 0x104,
357	.mask = 0x0,
358	.data = 0x1,	/* Clear Status */
359	},
360	{	/* GPI_GPE_STS_GPP_D_0 */
361	.offset = 0x124,
362	.mask = 0x0,
363	.data = 0x1,	/* Clear Status */
364	},
365	{	/* GPI_SMI_STS_GPP_D_0 */
366	.offset = 0x144,
367	.mask = 0x0,
368	.data = 0x1,	/* Clear Status */
369	},
370	{	/* GPI_NMI_STS_GPP_D_0 */
371	.offset = 0x164,
372	.mask = 0x0,
373	.data = 0x1,	/* Clear Status */
374	},
375
376/* Disable interrupts: */
377	{	/* GPI_INT_EN_GPP_D_0 */
378	.offset = 0x114,
379	.mask = 0x1,
380	.data = 0x0,	/* Disable interrupt generation */
381	},
382	{	/* GPI_GPE_EN_GPP_D_0 */
383	.offset = 0x134,
384	.mask = 0x1,
385	.data = 0x0,	/* Disable interrupt generation */
386	},
387	{	/* GPI_SMI_EN_GPP_D_0 */
388	.offset = 0x154,
389	.mask = 0x1,
390	.data = 0x0,	/* Disable interrupt generation */
391	},
392	{	/* GPI_NMI_EN_GPP_D_0 */
393	.offset = 0x174,
394	.mask = 0x1,
395	.data = 0x0,	/* Disable interrupt generation */
396	},
397
398/* Setup GPP_D_0 Pad Config: */
399	{	/* PAD_CFG_DW0_GPP_D_0 */
400	.offset = 0x4c0,
401	.mask = 0xffffffff,
402	.data = 0x82020100,
403/*
404 *  31:30 Pad Reset Config (PADRSTCFG): = 2h  # PLTRST# (default)
405 *
406 *  29    RX Pad State Select (RXPADSTSEL): = 0 # Raw RX pad state directly
407 *                                                from RX buffer (default)
408 *
409 *  28    RX Raw Override to '1' (RXRAW1): = 0 # No Override
410 *
411 *  26:25 RX Level/Edge Configuration (RXEVCFG):
412 *      = 0h # Level
413 *      = 1h # Edge
414 *
415 *  23    RX Invert (RXINV): = 0 # No Inversion (signal active high)
416 *
417 *  20    GPIO Input Route IOxAPIC (GPIROUTIOXAPIC):
418 * = 0 # Routing does not cause peripheral IRQ...
419 *     # (we want an NMI not an IRQ)
420 *
421 *  19    GPIO Input Route SCI (GPIROUTSCI): = 0 # Routing does not cause SCI.
422 *  18    GPIO Input Route SMI (GPIROUTSMI): = 0 # Routing does not cause SMI.
423 *  17    GPIO Input Route NMI (GPIROUTNMI): = 1 # Routing can cause NMI.
424 *
425 *  11:10 Pad Mode (PMODE1/0): = 0h = GPIO control the Pad.
426 *   9    GPIO RX Disable (GPIORXDIS):
427 * = 0 # Enable the input buffer (active low enable)
428 *
429 *   8    GPIO TX Disable (GPIOTXDIS):
430 * = 1 # Disable the output buffer; i.e. Hi-Z
431 *
432 *   1 GPIO RX State (GPIORXSTATE): This is the current internal RX pad state..
433 *   0 GPIO TX State (GPIOTXSTATE):
434 * = 0 # (Leave at default)
435 */
436	},
437
438/* Pad Config DW1 */
439	{	/* PAD_CFG_DW1_GPP_D_0 */
440	.offset = 0x4c4,
441	.mask = 0x3c00,
442	.data = 0,	/* Termination = none (default) */
443	},
444};
445
446static void uv_init_hubless_pch_d0(void)
447{
448	int i, read;
449
450	read = *PCH_PCR_GPIO_ADDRESS(PAD_OWN_GPP_D_0);
451	if (read != 0) {
452		pr_info("UV: Hubless NMI already configured\n");
453		return;
454	}
455
456	nmi_debug("UV: Initializing UV Hubless NMI on PCH\n");
457	for (i = 0; i < ARRAY_SIZE(init_nmi); i++) {
458		uv_init_hubless_pch_io(init_nmi[i].offset,
459					init_nmi[i].mask,
460					init_nmi[i].data);
461	}
462}
463
464static int uv_nmi_test_hubless(struct uv_hub_nmi_s *hub_nmi)
465{
466	int *pstat = PCH_PCR_GPIO_ADDRESS(GPI_NMI_STS_GPP_D_0);
467	int status = *pstat;
468
469	hub_nmi->nmi_value = status;
470	atomic_inc(&hub_nmi->read_mmr_count);
471
472	if (!(status & STS_GPP_D_0_MASK))	/* Not a UV external NMI */
473		return 0;
474
475	*pstat = STS_GPP_D_0_MASK;	/* Is a UV NMI: clear GPP_D_0 status */
476	(void)*pstat;			/* Flush write */
477
478	return 1;
479}
480
481static int uv_test_nmi(struct uv_hub_nmi_s *hub_nmi)
482{
483	if (hub_nmi->hub_present)
484		return uv_nmi_test_mmr(hub_nmi);
485
486	if (hub_nmi->pch_owner)		/* Only PCH owner can check status */
487		return uv_nmi_test_hubless(hub_nmi);
488
489	return -1;
490}
491
492/*
493 * If first CPU in on this hub, set hub_nmi "in_nmi" and "owner" values and
494 * return true.  If first CPU in on the system, set global "in_nmi" flag.
495 */
496static int uv_set_in_nmi(int cpu, struct uv_hub_nmi_s *hub_nmi)
497{
498	int first = atomic_add_unless(&hub_nmi->in_nmi, 1, 1);
499
500	if (first) {
501		atomic_set(&hub_nmi->cpu_owner, cpu);
502		if (atomic_add_unless(&uv_in_nmi, 1, 1))
503			atomic_set(&uv_nmi_cpu, cpu);
504
505		atomic_inc(&hub_nmi->nmi_count);
506	}
507	return first;
508}
509
510/* Check if this is a system NMI event */
511static int uv_check_nmi(struct uv_hub_nmi_s *hub_nmi)
512{
513	int cpu = smp_processor_id();
514	int nmi = 0;
515	int nmi_detected = 0;
516
517	local64_inc(&uv_nmi_count);
518	this_cpu_inc(uv_cpu_nmi.queries);
519
520	do {
521		nmi = atomic_read(&hub_nmi->in_nmi);
522		if (nmi)
523			break;
524
525		if (raw_spin_trylock(&hub_nmi->nmi_lock)) {
526			nmi_detected = uv_test_nmi(hub_nmi);
527
528			/* Check flag for UV external NMI */
529			if (nmi_detected > 0) {
530				uv_set_in_nmi(cpu, hub_nmi);
531				nmi = 1;
532				break;
533			}
534
535			/* A non-PCH node in a hubless system waits for NMI */
536			else if (nmi_detected < 0)
537				goto slave_wait;
538
539			/* MMR/PCH NMI flag is clear */
540			raw_spin_unlock(&hub_nmi->nmi_lock);
541
542		} else {
543
544			/* Wait a moment for the HUB NMI locker to set flag */
545slave_wait:		cpu_relax();
546			udelay(uv_nmi_slave_delay);
547
548			/* Re-check hub in_nmi flag */
549			nmi = atomic_read(&hub_nmi->in_nmi);
550			if (nmi)
551				break;
552		}
553
554		/*
555		 * Check if this BMC missed setting the MMR NMI flag (or)
556		 * UV hubless system where only PCH owner can check flag
557		 */
558		if (!nmi) {
559			nmi = atomic_read(&uv_in_nmi);
560			if (nmi)
561				uv_set_in_nmi(cpu, hub_nmi);
562		}
563
564		/* If we're holding the hub lock, release it now */
565		if (nmi_detected < 0)
566			raw_spin_unlock(&hub_nmi->nmi_lock);
567
568	} while (0);
569
570	if (!nmi)
571		local64_inc(&uv_nmi_misses);
572
573	return nmi;
574}
575
576/* Need to reset the NMI MMR register, but only once per hub. */
577static inline void uv_clear_nmi(int cpu)
578{
579	struct uv_hub_nmi_s *hub_nmi = uv_hub_nmi;
580
581	if (cpu == atomic_read(&hub_nmi->cpu_owner)) {
582		atomic_set(&hub_nmi->cpu_owner, -1);
583		atomic_set(&hub_nmi->in_nmi, 0);
584		if (hub_nmi->hub_present)
585			uv_local_mmr_clear_nmi();
586		else
587			uv_reassert_nmi();
588		raw_spin_unlock(&hub_nmi->nmi_lock);
589	}
590}
591
592/* Ping non-responding CPU's attempting to force them into the NMI handler */
593static void uv_nmi_nr_cpus_ping(void)
594{
595	int cpu;
596
597	for_each_cpu(cpu, uv_nmi_cpu_mask)
598		uv_cpu_nmi_per(cpu).pinging = 1;
599
600	__apic_send_IPI_mask(uv_nmi_cpu_mask, APIC_DM_NMI);
601}
602
603/* Clean up flags for CPU's that ignored both NMI and ping */
604static void uv_nmi_cleanup_mask(void)
605{
606	int cpu;
607
608	for_each_cpu(cpu, uv_nmi_cpu_mask) {
609		uv_cpu_nmi_per(cpu).pinging =  0;
610		uv_cpu_nmi_per(cpu).state = UV_NMI_STATE_OUT;
611		cpumask_clear_cpu(cpu, uv_nmi_cpu_mask);
612	}
613}
614
615/* Loop waiting as CPU's enter NMI handler */
616static int uv_nmi_wait_cpus(int first)
617{
618	int i, j, k, n = num_online_cpus();
619	int last_k = 0, waiting = 0;
620	int cpu = smp_processor_id();
621
622	if (first) {
623		cpumask_copy(uv_nmi_cpu_mask, cpu_online_mask);
624		k = 0;
625	} else {
626		k = n - cpumask_weight(uv_nmi_cpu_mask);
627	}
628
629	/* PCH NMI causes only one CPU to respond */
630	if (first && uv_pch_intr_now_enabled) {
631		cpumask_clear_cpu(cpu, uv_nmi_cpu_mask);
632		return n - k - 1;
633	}
634
635	udelay(uv_nmi_initial_delay);
636	for (i = 0; i < uv_nmi_retry_count; i++) {
637		int loop_delay = uv_nmi_loop_delay;
638
639		for_each_cpu(j, uv_nmi_cpu_mask) {
640			if (uv_cpu_nmi_per(j).state) {
641				cpumask_clear_cpu(j, uv_nmi_cpu_mask);
642				if (++k >= n)
643					break;
644			}
645		}
646		if (k >= n) {		/* all in? */
647			k = n;
648			break;
649		}
650		if (last_k != k) {	/* abort if no new CPU's coming in */
651			last_k = k;
652			waiting = 0;
653		} else if (++waiting > uv_nmi_wait_count)
654			break;
655
656		/* Extend delay if waiting only for CPU 0: */
657		if (waiting && (n - k) == 1 &&
658		    cpumask_test_cpu(0, uv_nmi_cpu_mask))
659			loop_delay *= 100;
660
661		udelay(loop_delay);
662	}
663	atomic_set(&uv_nmi_cpus_in_nmi, k);
664	return n - k;
665}
666
667/* Wait until all slave CPU's have entered UV NMI handler */
668static void uv_nmi_wait(int master)
669{
670	/* Indicate this CPU is in: */
671	this_cpu_write(uv_cpu_nmi.state, UV_NMI_STATE_IN);
672
673	/* If not the first CPU in (the master), then we are a slave CPU */
674	if (!master)
675		return;
676
677	do {
678		/* Wait for all other CPU's to gather here */
679		if (!uv_nmi_wait_cpus(1))
680			break;
681
682		/* If not all made it in, send IPI NMI to them */
683		pr_alert("UV: Sending NMI IPI to %d CPUs: %*pbl\n",
684			 cpumask_weight(uv_nmi_cpu_mask),
685			 cpumask_pr_args(uv_nmi_cpu_mask));
686
687		uv_nmi_nr_cpus_ping();
688
689		/* If all CPU's are in, then done */
690		if (!uv_nmi_wait_cpus(0))
691			break;
692
693		pr_alert("UV: %d CPUs not in NMI loop: %*pbl\n",
694			 cpumask_weight(uv_nmi_cpu_mask),
695			 cpumask_pr_args(uv_nmi_cpu_mask));
696	} while (0);
697
698	pr_alert("UV: %d of %d CPUs in NMI\n",
699		atomic_read(&uv_nmi_cpus_in_nmi), num_online_cpus());
700}
701
702/* Dump Instruction Pointer header */
703static void uv_nmi_dump_cpu_ip_hdr(void)
704{
705	pr_info("\nUV: %4s %6s %-32s %s   (Note: PID 0 not listed)\n",
706		"CPU", "PID", "COMMAND", "IP");
707}
708
709/* Dump Instruction Pointer info */
710static void uv_nmi_dump_cpu_ip(int cpu, struct pt_regs *regs)
711{
712	pr_info("UV: %4d %6d %-32.32s %pS",
713		cpu, current->pid, current->comm, (void *)regs->ip);
714}
715
716/*
717 * Dump this CPU's state.  If action was set to "kdump" and the crash_kexec
718 * failed, then we provide "dump" as an alternate action.  Action "dump" now
719 * also includes the show "ips" (instruction pointers) action whereas the
720 * action "ips" only displays instruction pointers for the non-idle CPU's.
721 * This is an abbreviated form of the "ps" command.
722 */
723static void uv_nmi_dump_state_cpu(int cpu, struct pt_regs *regs)
724{
725	const char *dots = " ................................. ";
726
727	if (cpu == 0)
728		uv_nmi_dump_cpu_ip_hdr();
729
730	if (current->pid != 0 || !uv_nmi_action_is("ips"))
731		uv_nmi_dump_cpu_ip(cpu, regs);
732
733	if (uv_nmi_action_is("dump")) {
734		pr_info("UV:%sNMI process trace for CPU %d\n", dots, cpu);
735		show_regs(regs);
736	}
737
738	this_cpu_write(uv_cpu_nmi.state, UV_NMI_STATE_DUMP_DONE);
739}
740
741/* Trigger a slave CPU to dump it's state */
742static void uv_nmi_trigger_dump(int cpu)
743{
744	int retry = uv_nmi_trigger_delay;
745
746	if (uv_cpu_nmi_per(cpu).state != UV_NMI_STATE_IN)
747		return;
748
749	uv_cpu_nmi_per(cpu).state = UV_NMI_STATE_DUMP;
750	do {
751		cpu_relax();
752		udelay(10);
753		if (uv_cpu_nmi_per(cpu).state
754				!= UV_NMI_STATE_DUMP)
755			return;
756	} while (--retry > 0);
757
758	pr_crit("UV: CPU %d stuck in process dump function\n", cpu);
759	uv_cpu_nmi_per(cpu).state = UV_NMI_STATE_DUMP_DONE;
760}
761
762/* Wait until all CPU's ready to exit */
763static void uv_nmi_sync_exit(int master)
764{
765	atomic_dec(&uv_nmi_cpus_in_nmi);
766	if (master) {
767		while (atomic_read(&uv_nmi_cpus_in_nmi) > 0)
768			cpu_relax();
769		atomic_set(&uv_nmi_slave_continue, SLAVE_CLEAR);
770	} else {
771		while (atomic_read(&uv_nmi_slave_continue))
772			cpu_relax();
773	}
774}
775
776/* Current "health" check is to check which CPU's are responsive */
777static void uv_nmi_action_health(int cpu, struct pt_regs *regs, int master)
778{
779	if (master) {
780		int in = atomic_read(&uv_nmi_cpus_in_nmi);
781		int out = num_online_cpus() - in;
782
783		pr_alert("UV: NMI CPU health check (non-responding:%d)\n", out);
784		atomic_set(&uv_nmi_slave_continue, SLAVE_EXIT);
785	} else {
786		while (!atomic_read(&uv_nmi_slave_continue))
787			cpu_relax();
788	}
789	uv_nmi_sync_exit(master);
790}
791
792/* Walk through CPU list and dump state of each */
793static void uv_nmi_dump_state(int cpu, struct pt_regs *regs, int master)
794{
795	if (master) {
796		int tcpu;
797		int ignored = 0;
798		int saved_console_loglevel = console_loglevel;
799
800		pr_alert("UV: tracing %s for %d CPUs from CPU %d\n",
801			uv_nmi_action_is("ips") ? "IPs" : "processes",
802			atomic_read(&uv_nmi_cpus_in_nmi), cpu);
803
804		console_loglevel = uv_nmi_loglevel;
805		atomic_set(&uv_nmi_slave_continue, SLAVE_EXIT);
806		for_each_online_cpu(tcpu) {
807			if (cpumask_test_cpu(tcpu, uv_nmi_cpu_mask))
808				ignored++;
809			else if (tcpu == cpu)
810				uv_nmi_dump_state_cpu(tcpu, regs);
811			else
812				uv_nmi_trigger_dump(tcpu);
813		}
814		if (ignored)
815			pr_alert("UV: %d CPUs ignored NMI\n", ignored);
816
817		console_loglevel = saved_console_loglevel;
818		pr_alert("UV: process trace complete\n");
819	} else {
820		while (!atomic_read(&uv_nmi_slave_continue))
821			cpu_relax();
822		while (this_cpu_read(uv_cpu_nmi.state) != UV_NMI_STATE_DUMP)
823			cpu_relax();
824		uv_nmi_dump_state_cpu(cpu, regs);
825	}
826	uv_nmi_sync_exit(master);
827}
828
829static void uv_nmi_touch_watchdogs(void)
830{
831	touch_softlockup_watchdog_sync();
832	clocksource_touch_watchdog();
833	rcu_cpu_stall_reset();
834	touch_nmi_watchdog();
835}
836
837static void uv_nmi_kdump(int cpu, int main, struct pt_regs *regs)
838{
839	/* Check if kdump kernel loaded for both main and secondary CPUs */
840	if (!kexec_crash_image) {
841		if (main)
842			pr_err("UV: NMI error: kdump kernel not loaded\n");
843		return;
844	}
845
846	/* Call crash to dump system state */
847	if (main) {
848		pr_emerg("UV: NMI executing crash_kexec on CPU%d\n", cpu);
849		crash_kexec(regs);
850
851		pr_emerg("UV: crash_kexec unexpectedly returned\n");
852		atomic_set(&uv_nmi_kexec_failed, 1);
853
854	} else { /* secondary */
855
856		/* If kdump kernel fails, secondaries will exit this loop */
857		while (atomic_read(&uv_nmi_kexec_failed) == 0) {
858
859			/* Once shootdown cpus starts, they do not return */
860			run_crash_ipi_callback(regs);
861
862			mdelay(10);
863		}
864	}
865}
866
867#ifdef CONFIG_KGDB
868#ifdef CONFIG_KGDB_KDB
869static inline int uv_nmi_kdb_reason(void)
870{
871	return KDB_REASON_SYSTEM_NMI;
872}
873#else /* !CONFIG_KGDB_KDB */
874static inline int uv_nmi_kdb_reason(void)
875{
876	/* Ensure user is expecting to attach gdb remote */
877	if (uv_nmi_action_is("kgdb"))
878		return 0;
879
880	pr_err("UV: NMI error: KDB is not enabled in this kernel\n");
881	return -1;
882}
883#endif /* CONFIG_KGDB_KDB */
884
885/*
886 * Call KGDB/KDB from NMI handler
887 *
888 * Note that if both KGDB and KDB are configured, then the action of 'kgdb' or
889 * 'kdb' has no affect on which is used.  See the KGDB documentation for further
890 * information.
891 */
892static void uv_call_kgdb_kdb(int cpu, struct pt_regs *regs, int master)
893{
894	if (master) {
895		int reason = uv_nmi_kdb_reason();
896		int ret;
897
898		if (reason < 0)
899			return;
900
901		/* Call KGDB NMI handler as MASTER */
902		ret = kgdb_nmicallin(cpu, X86_TRAP_NMI, regs, reason,
903				&uv_nmi_slave_continue);
904		if (ret) {
905			pr_alert("KGDB returned error, is kgdboc set?\n");
906			atomic_set(&uv_nmi_slave_continue, SLAVE_EXIT);
907		}
908	} else {
909		/* Wait for KGDB signal that it's ready for slaves to enter */
910		int sig;
911
912		do {
913			cpu_relax();
914			sig = atomic_read(&uv_nmi_slave_continue);
915		} while (!sig);
916
917		/* Call KGDB as slave */
918		if (sig == SLAVE_CONTINUE)
919			kgdb_nmicallback(cpu, regs);
920	}
921	uv_nmi_sync_exit(master);
922}
923
924#else /* !CONFIG_KGDB */
925static inline void uv_call_kgdb_kdb(int cpu, struct pt_regs *regs, int master)
926{
927	pr_err("UV: NMI error: KGDB is not enabled in this kernel\n");
928}
929#endif /* !CONFIG_KGDB */
930
931/*
932 * UV NMI handler
933 */
934static int uv_handle_nmi(unsigned int reason, struct pt_regs *regs)
935{
936	struct uv_hub_nmi_s *hub_nmi = uv_hub_nmi;
937	int cpu = smp_processor_id();
938	int master = 0;
939	unsigned long flags;
940
941	local_irq_save(flags);
942
943	/* If not a UV System NMI, ignore */
944	if (!this_cpu_read(uv_cpu_nmi.pinging) && !uv_check_nmi(hub_nmi)) {
945		local_irq_restore(flags);
946		return NMI_DONE;
947	}
948
949	/* Indicate we are the first CPU into the NMI handler */
950	master = (atomic_read(&uv_nmi_cpu) == cpu);
951
952	/* If NMI action is "kdump", then attempt to do it */
953	if (uv_nmi_action_is("kdump")) {
954		uv_nmi_kdump(cpu, master, regs);
955
956		/* Unexpected return, revert action to "dump" */
957		if (master)
958			strscpy(uv_nmi_action, "dump", sizeof(uv_nmi_action));
959	}
960
961	/* Pause as all CPU's enter the NMI handler */
962	uv_nmi_wait(master);
963
964	/* Process actions other than "kdump": */
965	if (uv_nmi_action_is("health")) {
966		uv_nmi_action_health(cpu, regs, master);
967	} else if (uv_nmi_action_is("ips") || uv_nmi_action_is("dump")) {
968		uv_nmi_dump_state(cpu, regs, master);
969	} else if (uv_nmi_action_is("kdb") || uv_nmi_action_is("kgdb")) {
970		uv_call_kgdb_kdb(cpu, regs, master);
971	} else {
972		if (master)
973			pr_alert("UV: unknown NMI action: %s\n", uv_nmi_action);
974		uv_nmi_sync_exit(master);
975	}
976
977	/* Clear per_cpu "in_nmi" flag */
978	this_cpu_write(uv_cpu_nmi.state, UV_NMI_STATE_OUT);
979
980	/* Clear MMR NMI flag on each hub */
981	uv_clear_nmi(cpu);
982
983	/* Clear global flags */
984	if (master) {
985		if (!cpumask_empty(uv_nmi_cpu_mask))
986			uv_nmi_cleanup_mask();
987		atomic_set(&uv_nmi_cpus_in_nmi, -1);
988		atomic_set(&uv_nmi_cpu, -1);
989		atomic_set(&uv_in_nmi, 0);
990		atomic_set(&uv_nmi_kexec_failed, 0);
991		atomic_set(&uv_nmi_slave_continue, SLAVE_CLEAR);
992	}
993
994	uv_nmi_touch_watchdogs();
995	local_irq_restore(flags);
996
997	return NMI_HANDLED;
998}
999
1000/*
1001 * NMI handler for pulling in CPU's when perf events are grabbing our NMI
1002 */
1003static int uv_handle_nmi_ping(unsigned int reason, struct pt_regs *regs)
1004{
1005	int ret;
1006
1007	this_cpu_inc(uv_cpu_nmi.queries);
1008	if (!this_cpu_read(uv_cpu_nmi.pinging)) {
1009		local64_inc(&uv_nmi_ping_misses);
1010		return NMI_DONE;
1011	}
1012
1013	this_cpu_inc(uv_cpu_nmi.pings);
1014	local64_inc(&uv_nmi_ping_count);
1015	ret = uv_handle_nmi(reason, regs);
1016	this_cpu_write(uv_cpu_nmi.pinging, 0);
1017	return ret;
1018}
1019
1020static void uv_register_nmi_notifier(void)
1021{
1022	if (register_nmi_handler(NMI_UNKNOWN, uv_handle_nmi, 0, "uv"))
1023		pr_warn("UV: NMI handler failed to register\n");
1024
1025	if (register_nmi_handler(NMI_LOCAL, uv_handle_nmi_ping, 0, "uvping"))
1026		pr_warn("UV: PING NMI handler failed to register\n");
1027}
1028
1029void uv_nmi_init(void)
1030{
1031	unsigned int value;
1032
1033	/*
1034	 * Unmask NMI on all CPU's
1035	 */
1036	value = apic_read(APIC_LVT1) | APIC_DM_NMI;
1037	value &= ~APIC_LVT_MASKED;
1038	apic_write(APIC_LVT1, value);
1039}
1040
1041/* Setup HUB NMI info */
1042static void __init uv_nmi_setup_common(bool hubbed)
1043{
1044	int size = sizeof(void *) * (1 << NODES_SHIFT);
1045	int cpu;
1046
1047	uv_hub_nmi_list = kzalloc(size, GFP_KERNEL);
1048	nmi_debug("UV: NMI hub list @ 0x%p (%d)\n", uv_hub_nmi_list, size);
1049	BUG_ON(!uv_hub_nmi_list);
1050	size = sizeof(struct uv_hub_nmi_s);
1051	for_each_present_cpu(cpu) {
1052		int nid = cpu_to_node(cpu);
1053		if (uv_hub_nmi_list[nid] == NULL) {
1054			uv_hub_nmi_list[nid] = kzalloc_node(size,
1055							    GFP_KERNEL, nid);
1056			BUG_ON(!uv_hub_nmi_list[nid]);
1057			raw_spin_lock_init(&(uv_hub_nmi_list[nid]->nmi_lock));
1058			atomic_set(&uv_hub_nmi_list[nid]->cpu_owner, -1);
1059			uv_hub_nmi_list[nid]->hub_present = hubbed;
1060			uv_hub_nmi_list[nid]->pch_owner = (nid == 0);
1061		}
1062		uv_hub_nmi_per(cpu) = uv_hub_nmi_list[nid];
1063	}
1064	BUG_ON(!alloc_cpumask_var(&uv_nmi_cpu_mask, GFP_KERNEL));
1065}
1066
1067/* Setup for UV Hub systems */
1068void __init uv_nmi_setup(void)
1069{
1070	uv_nmi_setup_mmrs();
1071	uv_nmi_setup_common(true);
1072	uv_register_nmi_notifier();
1073	pr_info("UV: Hub NMI enabled\n");
1074}
1075
1076/* Setup for UV Hubless systems */
1077void __init uv_nmi_setup_hubless(void)
1078{
1079	uv_nmi_setup_common(false);
1080	pch_base = xlate_dev_mem_ptr(PCH_PCR_GPIO_1_BASE);
1081	nmi_debug("UV: PCH base:%p from 0x%lx, GPP_D_0\n",
1082		pch_base, PCH_PCR_GPIO_1_BASE);
1083	if (uv_pch_init_enable)
1084		uv_init_hubless_pch_d0();
1085	uv_init_hubless_pch_io(GPI_NMI_ENA_GPP_D_0,
1086				STS_GPP_D_0_MASK, STS_GPP_D_0_MASK);
1087	uv_nmi_setup_hubless_intr();
1088	/* Ensure NMI enabled in Processor Interface Reg: */
1089	uv_reassert_nmi();
1090	uv_register_nmi_notifier();
1091	pr_info("UV: PCH NMI enabled\n");
1092}
1093