xref: /openbmc/linux/arch/x86/kernel/cpu/mce/amd.c (revision 1372a51b)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  (c) 2005-2016 Advanced Micro Devices, Inc.
4  *
5  *  Written by Jacob Shin - AMD, Inc.
6  *  Maintained by: Borislav Petkov <bp@alien8.de>
7  *
8  *  All MC4_MISCi registers are shared between cores on a node.
9  */
10 #include <linux/interrupt.h>
11 #include <linux/notifier.h>
12 #include <linux/kobject.h>
13 #include <linux/percpu.h>
14 #include <linux/errno.h>
15 #include <linux/sched.h>
16 #include <linux/sysfs.h>
17 #include <linux/slab.h>
18 #include <linux/init.h>
19 #include <linux/cpu.h>
20 #include <linux/smp.h>
21 #include <linux/string.h>
22 
23 #include <asm/amd_nb.h>
24 #include <asm/traps.h>
25 #include <asm/apic.h>
26 #include <asm/mce.h>
27 #include <asm/msr.h>
28 #include <asm/trace/irq_vectors.h>
29 
30 #include "internal.h"
31 
32 #define NR_BLOCKS         5
33 #define THRESHOLD_MAX     0xFFF
34 #define INT_TYPE_APIC     0x00020000
35 #define MASK_VALID_HI     0x80000000
36 #define MASK_CNTP_HI      0x40000000
37 #define MASK_LOCKED_HI    0x20000000
38 #define MASK_LVTOFF_HI    0x00F00000
39 #define MASK_COUNT_EN_HI  0x00080000
40 #define MASK_INT_TYPE_HI  0x00060000
41 #define MASK_OVERFLOW_HI  0x00010000
42 #define MASK_ERR_COUNT_HI 0x00000FFF
43 #define MASK_BLKPTR_LO    0xFF000000
44 #define MCG_XBLK_ADDR     0xC0000400
45 
46 /* Deferred error settings */
47 #define MSR_CU_DEF_ERR		0xC0000410
48 #define MASK_DEF_LVTOFF		0x000000F0
49 #define MASK_DEF_INT_TYPE	0x00000006
50 #define DEF_LVT_OFF		0x2
51 #define DEF_INT_TYPE_APIC	0x2
52 
53 /* Scalable MCA: */
54 
55 /* Threshold LVT offset is at MSR0xC0000410[15:12] */
56 #define SMCA_THR_LVT_OFF	0xF000
57 
58 static bool thresholding_irq_en;
59 
60 static const char * const th_names[] = {
61 	"load_store",
62 	"insn_fetch",
63 	"combined_unit",
64 	"decode_unit",
65 	"northbridge",
66 	"execution_unit",
67 };
68 
69 static const char * const smca_umc_block_names[] = {
70 	"dram_ecc",
71 	"misc_umc"
72 };
73 
74 struct smca_bank_name {
75 	const char *name;	/* Short name for sysfs */
76 	const char *long_name;	/* Long name for pretty-printing */
77 };
78 
79 static struct smca_bank_name smca_names[] = {
80 	[SMCA_LS]	= { "load_store",	"Load Store Unit" },
81 	[SMCA_IF]	= { "insn_fetch",	"Instruction Fetch Unit" },
82 	[SMCA_L2_CACHE]	= { "l2_cache",		"L2 Cache" },
83 	[SMCA_DE]	= { "decode_unit",	"Decode Unit" },
84 	[SMCA_RESERVED]	= { "reserved",		"Reserved" },
85 	[SMCA_EX]	= { "execution_unit",	"Execution Unit" },
86 	[SMCA_FP]	= { "floating_point",	"Floating Point Unit" },
87 	[SMCA_L3_CACHE]	= { "l3_cache",		"L3 Cache" },
88 	[SMCA_CS]	= { "coherent_slave",	"Coherent Slave" },
89 	[SMCA_CS_V2]	= { "coherent_slave",	"Coherent Slave" },
90 	[SMCA_PIE]	= { "pie",		"Power, Interrupts, etc." },
91 	[SMCA_UMC]	= { "umc",		"Unified Memory Controller" },
92 	[SMCA_PB]	= { "param_block",	"Parameter Block" },
93 	[SMCA_PSP]	= { "psp",		"Platform Security Processor" },
94 	[SMCA_PSP_V2]	= { "psp",		"Platform Security Processor" },
95 	[SMCA_SMU]	= { "smu",		"System Management Unit" },
96 	[SMCA_SMU_V2]	= { "smu",		"System Management Unit" },
97 	[SMCA_MP5]	= { "mp5",		"Microprocessor 5 Unit" },
98 	[SMCA_NBIO]	= { "nbio",		"Northbridge IO Unit" },
99 	[SMCA_PCIE]	= { "pcie",		"PCI Express Unit" },
100 };
101 
102 static const char *smca_get_name(enum smca_bank_types t)
103 {
104 	if (t >= N_SMCA_BANK_TYPES)
105 		return NULL;
106 
107 	return smca_names[t].name;
108 }
109 
110 const char *smca_get_long_name(enum smca_bank_types t)
111 {
112 	if (t >= N_SMCA_BANK_TYPES)
113 		return NULL;
114 
115 	return smca_names[t].long_name;
116 }
117 EXPORT_SYMBOL_GPL(smca_get_long_name);
118 
119 static enum smca_bank_types smca_get_bank_type(unsigned int bank)
120 {
121 	struct smca_bank *b;
122 
123 	if (bank >= MAX_NR_BANKS)
124 		return N_SMCA_BANK_TYPES;
125 
126 	b = &smca_banks[bank];
127 	if (!b->hwid)
128 		return N_SMCA_BANK_TYPES;
129 
130 	return b->hwid->bank_type;
131 }
132 
133 static struct smca_hwid smca_hwid_mcatypes[] = {
134 	/* { bank_type, hwid_mcatype, xec_bitmap } */
135 
136 	/* Reserved type */
137 	{ SMCA_RESERVED, HWID_MCATYPE(0x00, 0x0), 0x0 },
138 
139 	/* ZN Core (HWID=0xB0) MCA types */
140 	{ SMCA_LS,	 HWID_MCATYPE(0xB0, 0x0), 0x1FFFFF },
141 	{ SMCA_IF,	 HWID_MCATYPE(0xB0, 0x1), 0x3FFF },
142 	{ SMCA_L2_CACHE, HWID_MCATYPE(0xB0, 0x2), 0xF },
143 	{ SMCA_DE,	 HWID_MCATYPE(0xB0, 0x3), 0x1FF },
144 	/* HWID 0xB0 MCATYPE 0x4 is Reserved */
145 	{ SMCA_EX,	 HWID_MCATYPE(0xB0, 0x5), 0xFFF },
146 	{ SMCA_FP,	 HWID_MCATYPE(0xB0, 0x6), 0x7F },
147 	{ SMCA_L3_CACHE, HWID_MCATYPE(0xB0, 0x7), 0xFF },
148 
149 	/* Data Fabric MCA types */
150 	{ SMCA_CS,	 HWID_MCATYPE(0x2E, 0x0), 0x1FF },
151 	{ SMCA_PIE,	 HWID_MCATYPE(0x2E, 0x1), 0x1F },
152 	{ SMCA_CS_V2,	 HWID_MCATYPE(0x2E, 0x2), 0x3FFF },
153 
154 	/* Unified Memory Controller MCA type */
155 	{ SMCA_UMC,	 HWID_MCATYPE(0x96, 0x0), 0xFF },
156 
157 	/* Parameter Block MCA type */
158 	{ SMCA_PB,	 HWID_MCATYPE(0x05, 0x0), 0x1 },
159 
160 	/* Platform Security Processor MCA type */
161 	{ SMCA_PSP,	 HWID_MCATYPE(0xFF, 0x0), 0x1 },
162 	{ SMCA_PSP_V2,	 HWID_MCATYPE(0xFF, 0x1), 0x3FFFF },
163 
164 	/* System Management Unit MCA type */
165 	{ SMCA_SMU,	 HWID_MCATYPE(0x01, 0x0), 0x1 },
166 	{ SMCA_SMU_V2,	 HWID_MCATYPE(0x01, 0x1), 0x7FF },
167 
168 	/* Microprocessor 5 Unit MCA type */
169 	{ SMCA_MP5,	 HWID_MCATYPE(0x01, 0x2), 0x3FF },
170 
171 	/* Northbridge IO Unit MCA type */
172 	{ SMCA_NBIO,	 HWID_MCATYPE(0x18, 0x0), 0x1F },
173 
174 	/* PCI Express Unit MCA type */
175 	{ SMCA_PCIE,	 HWID_MCATYPE(0x46, 0x0), 0x1F },
176 };
177 
178 struct smca_bank smca_banks[MAX_NR_BANKS];
179 EXPORT_SYMBOL_GPL(smca_banks);
180 
181 /*
182  * In SMCA enabled processors, we can have multiple banks for a given IP type.
183  * So to define a unique name for each bank, we use a temp c-string to append
184  * the MCA_IPID[InstanceId] to type's name in get_name().
185  *
186  * InstanceId is 32 bits which is 8 characters. Make sure MAX_MCATYPE_NAME_LEN
187  * is greater than 8 plus 1 (for underscore) plus length of longest type name.
188  */
189 #define MAX_MCATYPE_NAME_LEN	30
190 static char buf_mcatype[MAX_MCATYPE_NAME_LEN];
191 
192 static DEFINE_PER_CPU(struct threshold_bank **, threshold_banks);
193 static DEFINE_PER_CPU(unsigned int, bank_map);	/* see which banks are on */
194 
195 /* Map of banks that have more than MCA_MISC0 available. */
196 static DEFINE_PER_CPU(u32, smca_misc_banks_map);
197 
198 static void amd_threshold_interrupt(void);
199 static void amd_deferred_error_interrupt(void);
200 
201 static void default_deferred_error_interrupt(void)
202 {
203 	pr_err("Unexpected deferred interrupt at vector %x\n", DEFERRED_ERROR_VECTOR);
204 }
205 void (*deferred_error_int_vector)(void) = default_deferred_error_interrupt;
206 
207 static void smca_set_misc_banks_map(unsigned int bank, unsigned int cpu)
208 {
209 	u32 low, high;
210 
211 	/*
212 	 * For SMCA enabled processors, BLKPTR field of the first MISC register
213 	 * (MCx_MISC0) indicates presence of additional MISC regs set (MISC1-4).
214 	 */
215 	if (rdmsr_safe(MSR_AMD64_SMCA_MCx_CONFIG(bank), &low, &high))
216 		return;
217 
218 	if (!(low & MCI_CONFIG_MCAX))
219 		return;
220 
221 	if (rdmsr_safe(MSR_AMD64_SMCA_MCx_MISC(bank), &low, &high))
222 		return;
223 
224 	if (low & MASK_BLKPTR_LO)
225 		per_cpu(smca_misc_banks_map, cpu) |= BIT(bank);
226 
227 }
228 
229 static void smca_configure(unsigned int bank, unsigned int cpu)
230 {
231 	unsigned int i, hwid_mcatype;
232 	struct smca_hwid *s_hwid;
233 	u32 high, low;
234 	u32 smca_config = MSR_AMD64_SMCA_MCx_CONFIG(bank);
235 
236 	/* Set appropriate bits in MCA_CONFIG */
237 	if (!rdmsr_safe(smca_config, &low, &high)) {
238 		/*
239 		 * OS is required to set the MCAX bit to acknowledge that it is
240 		 * now using the new MSR ranges and new registers under each
241 		 * bank. It also means that the OS will configure deferred
242 		 * errors in the new MCx_CONFIG register. If the bit is not set,
243 		 * uncorrectable errors will cause a system panic.
244 		 *
245 		 * MCA_CONFIG[MCAX] is bit 32 (0 in the high portion of the MSR.)
246 		 */
247 		high |= BIT(0);
248 
249 		/*
250 		 * SMCA sets the Deferred Error Interrupt type per bank.
251 		 *
252 		 * MCA_CONFIG[DeferredIntTypeSupported] is bit 5, and tells us
253 		 * if the DeferredIntType bit field is available.
254 		 *
255 		 * MCA_CONFIG[DeferredIntType] is bits [38:37] ([6:5] in the
256 		 * high portion of the MSR). OS should set this to 0x1 to enable
257 		 * APIC based interrupt. First, check that no interrupt has been
258 		 * set.
259 		 */
260 		if ((low & BIT(5)) && !((high >> 5) & 0x3))
261 			high |= BIT(5);
262 
263 		wrmsr(smca_config, low, high);
264 	}
265 
266 	smca_set_misc_banks_map(bank, cpu);
267 
268 	/* Return early if this bank was already initialized. */
269 	if (smca_banks[bank].hwid)
270 		return;
271 
272 	if (rdmsr_safe_on_cpu(cpu, MSR_AMD64_SMCA_MCx_IPID(bank), &low, &high)) {
273 		pr_warn("Failed to read MCA_IPID for bank %d\n", bank);
274 		return;
275 	}
276 
277 	hwid_mcatype = HWID_MCATYPE(high & MCI_IPID_HWID,
278 				    (high & MCI_IPID_MCATYPE) >> 16);
279 
280 	for (i = 0; i < ARRAY_SIZE(smca_hwid_mcatypes); i++) {
281 		s_hwid = &smca_hwid_mcatypes[i];
282 		if (hwid_mcatype == s_hwid->hwid_mcatype) {
283 			smca_banks[bank].hwid = s_hwid;
284 			smca_banks[bank].id = low;
285 			smca_banks[bank].sysfs_id = s_hwid->count++;
286 			break;
287 		}
288 	}
289 }
290 
291 struct thresh_restart {
292 	struct threshold_block	*b;
293 	int			reset;
294 	int			set_lvt_off;
295 	int			lvt_off;
296 	u16			old_limit;
297 };
298 
299 static inline bool is_shared_bank(int bank)
300 {
301 	/*
302 	 * Scalable MCA provides for only one core to have access to the MSRs of
303 	 * a shared bank.
304 	 */
305 	if (mce_flags.smca)
306 		return false;
307 
308 	/* Bank 4 is for northbridge reporting and is thus shared */
309 	return (bank == 4);
310 }
311 
312 static const char *bank4_names(const struct threshold_block *b)
313 {
314 	switch (b->address) {
315 	/* MSR4_MISC0 */
316 	case 0x00000413:
317 		return "dram";
318 
319 	case 0xc0000408:
320 		return "ht_links";
321 
322 	case 0xc0000409:
323 		return "l3_cache";
324 
325 	default:
326 		WARN(1, "Funny MSR: 0x%08x\n", b->address);
327 		return "";
328 	}
329 };
330 
331 
332 static bool lvt_interrupt_supported(unsigned int bank, u32 msr_high_bits)
333 {
334 	/*
335 	 * bank 4 supports APIC LVT interrupts implicitly since forever.
336 	 */
337 	if (bank == 4)
338 		return true;
339 
340 	/*
341 	 * IntP: interrupt present; if this bit is set, the thresholding
342 	 * bank can generate APIC LVT interrupts
343 	 */
344 	return msr_high_bits & BIT(28);
345 }
346 
347 static int lvt_off_valid(struct threshold_block *b, int apic, u32 lo, u32 hi)
348 {
349 	int msr = (hi & MASK_LVTOFF_HI) >> 20;
350 
351 	if (apic < 0) {
352 		pr_err(FW_BUG "cpu %d, failed to setup threshold interrupt "
353 		       "for bank %d, block %d (MSR%08X=0x%x%08x)\n", b->cpu,
354 		       b->bank, b->block, b->address, hi, lo);
355 		return 0;
356 	}
357 
358 	if (apic != msr) {
359 		/*
360 		 * On SMCA CPUs, LVT offset is programmed at a different MSR, and
361 		 * the BIOS provides the value. The original field where LVT offset
362 		 * was set is reserved. Return early here:
363 		 */
364 		if (mce_flags.smca)
365 			return 0;
366 
367 		pr_err(FW_BUG "cpu %d, invalid threshold interrupt offset %d "
368 		       "for bank %d, block %d (MSR%08X=0x%x%08x)\n",
369 		       b->cpu, apic, b->bank, b->block, b->address, hi, lo);
370 		return 0;
371 	}
372 
373 	return 1;
374 };
375 
376 /* Reprogram MCx_MISC MSR behind this threshold bank. */
377 static void threshold_restart_bank(void *_tr)
378 {
379 	struct thresh_restart *tr = _tr;
380 	u32 hi, lo;
381 
382 	rdmsr(tr->b->address, lo, hi);
383 
384 	if (tr->b->threshold_limit < (hi & THRESHOLD_MAX))
385 		tr->reset = 1;	/* limit cannot be lower than err count */
386 
387 	if (tr->reset) {		/* reset err count and overflow bit */
388 		hi =
389 		    (hi & ~(MASK_ERR_COUNT_HI | MASK_OVERFLOW_HI)) |
390 		    (THRESHOLD_MAX - tr->b->threshold_limit);
391 	} else if (tr->old_limit) {	/* change limit w/o reset */
392 		int new_count = (hi & THRESHOLD_MAX) +
393 		    (tr->old_limit - tr->b->threshold_limit);
394 
395 		hi = (hi & ~MASK_ERR_COUNT_HI) |
396 		    (new_count & THRESHOLD_MAX);
397 	}
398 
399 	/* clear IntType */
400 	hi &= ~MASK_INT_TYPE_HI;
401 
402 	if (!tr->b->interrupt_capable)
403 		goto done;
404 
405 	if (tr->set_lvt_off) {
406 		if (lvt_off_valid(tr->b, tr->lvt_off, lo, hi)) {
407 			/* set new lvt offset */
408 			hi &= ~MASK_LVTOFF_HI;
409 			hi |= tr->lvt_off << 20;
410 		}
411 	}
412 
413 	if (tr->b->interrupt_enable)
414 		hi |= INT_TYPE_APIC;
415 
416  done:
417 
418 	hi |= MASK_COUNT_EN_HI;
419 	wrmsr(tr->b->address, lo, hi);
420 }
421 
422 static void mce_threshold_block_init(struct threshold_block *b, int offset)
423 {
424 	struct thresh_restart tr = {
425 		.b			= b,
426 		.set_lvt_off		= 1,
427 		.lvt_off		= offset,
428 	};
429 
430 	b->threshold_limit		= THRESHOLD_MAX;
431 	threshold_restart_bank(&tr);
432 };
433 
434 static int setup_APIC_mce_threshold(int reserved, int new)
435 {
436 	if (reserved < 0 && !setup_APIC_eilvt(new, THRESHOLD_APIC_VECTOR,
437 					      APIC_EILVT_MSG_FIX, 0))
438 		return new;
439 
440 	return reserved;
441 }
442 
443 static int setup_APIC_deferred_error(int reserved, int new)
444 {
445 	if (reserved < 0 && !setup_APIC_eilvt(new, DEFERRED_ERROR_VECTOR,
446 					      APIC_EILVT_MSG_FIX, 0))
447 		return new;
448 
449 	return reserved;
450 }
451 
452 static void deferred_error_interrupt_enable(struct cpuinfo_x86 *c)
453 {
454 	u32 low = 0, high = 0;
455 	int def_offset = -1, def_new;
456 
457 	if (rdmsr_safe(MSR_CU_DEF_ERR, &low, &high))
458 		return;
459 
460 	def_new = (low & MASK_DEF_LVTOFF) >> 4;
461 	if (!(low & MASK_DEF_LVTOFF)) {
462 		pr_err(FW_BUG "Your BIOS is not setting up LVT offset 0x2 for deferred error IRQs correctly.\n");
463 		def_new = DEF_LVT_OFF;
464 		low = (low & ~MASK_DEF_LVTOFF) | (DEF_LVT_OFF << 4);
465 	}
466 
467 	def_offset = setup_APIC_deferred_error(def_offset, def_new);
468 	if ((def_offset == def_new) &&
469 	    (deferred_error_int_vector != amd_deferred_error_interrupt))
470 		deferred_error_int_vector = amd_deferred_error_interrupt;
471 
472 	if (!mce_flags.smca)
473 		low = (low & ~MASK_DEF_INT_TYPE) | DEF_INT_TYPE_APIC;
474 
475 	wrmsr(MSR_CU_DEF_ERR, low, high);
476 }
477 
478 static u32 smca_get_block_address(unsigned int bank, unsigned int block,
479 				  unsigned int cpu)
480 {
481 	if (!block)
482 		return MSR_AMD64_SMCA_MCx_MISC(bank);
483 
484 	if (!(per_cpu(smca_misc_banks_map, cpu) & BIT(bank)))
485 		return 0;
486 
487 	return MSR_AMD64_SMCA_MCx_MISCy(bank, block - 1);
488 }
489 
490 static u32 get_block_address(u32 current_addr, u32 low, u32 high,
491 			     unsigned int bank, unsigned int block,
492 			     unsigned int cpu)
493 {
494 	u32 addr = 0, offset = 0;
495 
496 	if ((bank >= per_cpu(mce_num_banks, cpu)) || (block >= NR_BLOCKS))
497 		return addr;
498 
499 	if (mce_flags.smca)
500 		return smca_get_block_address(bank, block, cpu);
501 
502 	/* Fall back to method we used for older processors: */
503 	switch (block) {
504 	case 0:
505 		addr = msr_ops.misc(bank);
506 		break;
507 	case 1:
508 		offset = ((low & MASK_BLKPTR_LO) >> 21);
509 		if (offset)
510 			addr = MCG_XBLK_ADDR + offset;
511 		break;
512 	default:
513 		addr = ++current_addr;
514 	}
515 	return addr;
516 }
517 
518 static int
519 prepare_threshold_block(unsigned int bank, unsigned int block, u32 addr,
520 			int offset, u32 misc_high)
521 {
522 	unsigned int cpu = smp_processor_id();
523 	u32 smca_low, smca_high;
524 	struct threshold_block b;
525 	int new;
526 
527 	if (!block)
528 		per_cpu(bank_map, cpu) |= (1 << bank);
529 
530 	memset(&b, 0, sizeof(b));
531 	b.cpu			= cpu;
532 	b.bank			= bank;
533 	b.block			= block;
534 	b.address		= addr;
535 	b.interrupt_capable	= lvt_interrupt_supported(bank, misc_high);
536 
537 	if (!b.interrupt_capable)
538 		goto done;
539 
540 	b.interrupt_enable = 1;
541 
542 	if (!mce_flags.smca) {
543 		new = (misc_high & MASK_LVTOFF_HI) >> 20;
544 		goto set_offset;
545 	}
546 
547 	/* Gather LVT offset for thresholding: */
548 	if (rdmsr_safe(MSR_CU_DEF_ERR, &smca_low, &smca_high))
549 		goto out;
550 
551 	new = (smca_low & SMCA_THR_LVT_OFF) >> 12;
552 
553 set_offset:
554 	offset = setup_APIC_mce_threshold(offset, new);
555 	if (offset == new)
556 		thresholding_irq_en = true;
557 
558 done:
559 	mce_threshold_block_init(&b, offset);
560 
561 out:
562 	return offset;
563 }
564 
565 bool amd_filter_mce(struct mce *m)
566 {
567 	enum smca_bank_types bank_type = smca_get_bank_type(m->bank);
568 	struct cpuinfo_x86 *c = &boot_cpu_data;
569 	u8 xec = (m->status >> 16) & 0x3F;
570 
571 	/* See Family 17h Models 10h-2Fh Erratum #1114. */
572 	if (c->x86 == 0x17 &&
573 	    c->x86_model >= 0x10 && c->x86_model <= 0x2F &&
574 	    bank_type == SMCA_IF && xec == 10)
575 		return true;
576 
577 	return false;
578 }
579 
580 /*
581  * Turn off thresholding banks for the following conditions:
582  * - MC4_MISC thresholding is not supported on Family 0x15.
583  * - Prevent possible spurious interrupts from the IF bank on Family 0x17
584  *   Models 0x10-0x2F due to Erratum #1114.
585  */
586 static void disable_err_thresholding(struct cpuinfo_x86 *c, unsigned int bank)
587 {
588 	int i, num_msrs;
589 	u64 hwcr;
590 	bool need_toggle;
591 	u32 msrs[NR_BLOCKS];
592 
593 	if (c->x86 == 0x15 && bank == 4) {
594 		msrs[0] = 0x00000413; /* MC4_MISC0 */
595 		msrs[1] = 0xc0000408; /* MC4_MISC1 */
596 		num_msrs = 2;
597 	} else if (c->x86 == 0x17 &&
598 		   (c->x86_model >= 0x10 && c->x86_model <= 0x2F)) {
599 
600 		if (smca_get_bank_type(bank) != SMCA_IF)
601 			return;
602 
603 		msrs[0] = MSR_AMD64_SMCA_MCx_MISC(bank);
604 		num_msrs = 1;
605 	} else {
606 		return;
607 	}
608 
609 	rdmsrl(MSR_K7_HWCR, hwcr);
610 
611 	/* McStatusWrEn has to be set */
612 	need_toggle = !(hwcr & BIT(18));
613 	if (need_toggle)
614 		wrmsrl(MSR_K7_HWCR, hwcr | BIT(18));
615 
616 	/* Clear CntP bit safely */
617 	for (i = 0; i < num_msrs; i++)
618 		msr_clear_bit(msrs[i], 62);
619 
620 	/* restore old settings */
621 	if (need_toggle)
622 		wrmsrl(MSR_K7_HWCR, hwcr);
623 }
624 
625 /* cpu init entry point, called from mce.c with preempt off */
626 void mce_amd_feature_init(struct cpuinfo_x86 *c)
627 {
628 	unsigned int bank, block, cpu = smp_processor_id();
629 	u32 low = 0, high = 0, address = 0;
630 	int offset = -1;
631 
632 
633 	for (bank = 0; bank < this_cpu_read(mce_num_banks); ++bank) {
634 		if (mce_flags.smca)
635 			smca_configure(bank, cpu);
636 
637 		disable_err_thresholding(c, bank);
638 
639 		for (block = 0; block < NR_BLOCKS; ++block) {
640 			address = get_block_address(address, low, high, bank, block, cpu);
641 			if (!address)
642 				break;
643 
644 			if (rdmsr_safe(address, &low, &high))
645 				break;
646 
647 			if (!(high & MASK_VALID_HI))
648 				continue;
649 
650 			if (!(high & MASK_CNTP_HI)  ||
651 			     (high & MASK_LOCKED_HI))
652 				continue;
653 
654 			offset = prepare_threshold_block(bank, block, address, offset, high);
655 		}
656 	}
657 
658 	if (mce_flags.succor)
659 		deferred_error_interrupt_enable(c);
660 }
661 
662 int umc_normaddr_to_sysaddr(u64 norm_addr, u16 nid, u8 umc, u64 *sys_addr)
663 {
664 	u64 dram_base_addr, dram_limit_addr, dram_hole_base;
665 	/* We start from the normalized address */
666 	u64 ret_addr = norm_addr;
667 
668 	u32 tmp;
669 
670 	u8 die_id_shift, die_id_mask, socket_id_shift, socket_id_mask;
671 	u8 intlv_num_dies, intlv_num_chan, intlv_num_sockets;
672 	u8 intlv_addr_sel, intlv_addr_bit;
673 	u8 num_intlv_bits, hashed_bit;
674 	u8 lgcy_mmio_hole_en, base = 0;
675 	u8 cs_mask, cs_id = 0;
676 	bool hash_enabled = false;
677 
678 	/* Read D18F0x1B4 (DramOffset), check if base 1 is used. */
679 	if (amd_df_indirect_read(nid, 0, 0x1B4, umc, &tmp))
680 		goto out_err;
681 
682 	/* Remove HiAddrOffset from normalized address, if enabled: */
683 	if (tmp & BIT(0)) {
684 		u64 hi_addr_offset = (tmp & GENMASK_ULL(31, 20)) << 8;
685 
686 		if (norm_addr >= hi_addr_offset) {
687 			ret_addr -= hi_addr_offset;
688 			base = 1;
689 		}
690 	}
691 
692 	/* Read D18F0x110 (DramBaseAddress). */
693 	if (amd_df_indirect_read(nid, 0, 0x110 + (8 * base), umc, &tmp))
694 		goto out_err;
695 
696 	/* Check if address range is valid. */
697 	if (!(tmp & BIT(0))) {
698 		pr_err("%s: Invalid DramBaseAddress range: 0x%x.\n",
699 			__func__, tmp);
700 		goto out_err;
701 	}
702 
703 	lgcy_mmio_hole_en = tmp & BIT(1);
704 	intlv_num_chan	  = (tmp >> 4) & 0xF;
705 	intlv_addr_sel	  = (tmp >> 8) & 0x7;
706 	dram_base_addr	  = (tmp & GENMASK_ULL(31, 12)) << 16;
707 
708 	/* {0, 1, 2, 3} map to address bits {8, 9, 10, 11} respectively */
709 	if (intlv_addr_sel > 3) {
710 		pr_err("%s: Invalid interleave address select %d.\n",
711 			__func__, intlv_addr_sel);
712 		goto out_err;
713 	}
714 
715 	/* Read D18F0x114 (DramLimitAddress). */
716 	if (amd_df_indirect_read(nid, 0, 0x114 + (8 * base), umc, &tmp))
717 		goto out_err;
718 
719 	intlv_num_sockets = (tmp >> 8) & 0x1;
720 	intlv_num_dies	  = (tmp >> 10) & 0x3;
721 	dram_limit_addr	  = ((tmp & GENMASK_ULL(31, 12)) << 16) | GENMASK_ULL(27, 0);
722 
723 	intlv_addr_bit = intlv_addr_sel + 8;
724 
725 	/* Re-use intlv_num_chan by setting it equal to log2(#channels) */
726 	switch (intlv_num_chan) {
727 	case 0:	intlv_num_chan = 0; break;
728 	case 1: intlv_num_chan = 1; break;
729 	case 3: intlv_num_chan = 2; break;
730 	case 5:	intlv_num_chan = 3; break;
731 	case 7:	intlv_num_chan = 4; break;
732 
733 	case 8: intlv_num_chan = 1;
734 		hash_enabled = true;
735 		break;
736 	default:
737 		pr_err("%s: Invalid number of interleaved channels %d.\n",
738 			__func__, intlv_num_chan);
739 		goto out_err;
740 	}
741 
742 	num_intlv_bits = intlv_num_chan;
743 
744 	if (intlv_num_dies > 2) {
745 		pr_err("%s: Invalid number of interleaved nodes/dies %d.\n",
746 			__func__, intlv_num_dies);
747 		goto out_err;
748 	}
749 
750 	num_intlv_bits += intlv_num_dies;
751 
752 	/* Add a bit if sockets are interleaved. */
753 	num_intlv_bits += intlv_num_sockets;
754 
755 	/* Assert num_intlv_bits <= 4 */
756 	if (num_intlv_bits > 4) {
757 		pr_err("%s: Invalid interleave bits %d.\n",
758 			__func__, num_intlv_bits);
759 		goto out_err;
760 	}
761 
762 	if (num_intlv_bits > 0) {
763 		u64 temp_addr_x, temp_addr_i, temp_addr_y;
764 		u8 die_id_bit, sock_id_bit, cs_fabric_id;
765 
766 		/*
767 		 * Read FabricBlockInstanceInformation3_CS[BlockFabricID].
768 		 * This is the fabric id for this coherent slave. Use
769 		 * umc/channel# as instance id of the coherent slave
770 		 * for FICAA.
771 		 */
772 		if (amd_df_indirect_read(nid, 0, 0x50, umc, &tmp))
773 			goto out_err;
774 
775 		cs_fabric_id = (tmp >> 8) & 0xFF;
776 		die_id_bit   = 0;
777 
778 		/* If interleaved over more than 1 channel: */
779 		if (intlv_num_chan) {
780 			die_id_bit = intlv_num_chan;
781 			cs_mask	   = (1 << die_id_bit) - 1;
782 			cs_id	   = cs_fabric_id & cs_mask;
783 		}
784 
785 		sock_id_bit = die_id_bit;
786 
787 		/* Read D18F1x208 (SystemFabricIdMask). */
788 		if (intlv_num_dies || intlv_num_sockets)
789 			if (amd_df_indirect_read(nid, 1, 0x208, umc, &tmp))
790 				goto out_err;
791 
792 		/* If interleaved over more than 1 die. */
793 		if (intlv_num_dies) {
794 			sock_id_bit  = die_id_bit + intlv_num_dies;
795 			die_id_shift = (tmp >> 24) & 0xF;
796 			die_id_mask  = (tmp >> 8) & 0xFF;
797 
798 			cs_id |= ((cs_fabric_id & die_id_mask) >> die_id_shift) << die_id_bit;
799 		}
800 
801 		/* If interleaved over more than 1 socket. */
802 		if (intlv_num_sockets) {
803 			socket_id_shift	= (tmp >> 28) & 0xF;
804 			socket_id_mask	= (tmp >> 16) & 0xFF;
805 
806 			cs_id |= ((cs_fabric_id & socket_id_mask) >> socket_id_shift) << sock_id_bit;
807 		}
808 
809 		/*
810 		 * The pre-interleaved address consists of XXXXXXIIIYYYYY
811 		 * where III is the ID for this CS, and XXXXXXYYYYY are the
812 		 * address bits from the post-interleaved address.
813 		 * "num_intlv_bits" has been calculated to tell us how many "I"
814 		 * bits there are. "intlv_addr_bit" tells us how many "Y" bits
815 		 * there are (where "I" starts).
816 		 */
817 		temp_addr_y = ret_addr & GENMASK_ULL(intlv_addr_bit-1, 0);
818 		temp_addr_i = (cs_id << intlv_addr_bit);
819 		temp_addr_x = (ret_addr & GENMASK_ULL(63, intlv_addr_bit)) << num_intlv_bits;
820 		ret_addr    = temp_addr_x | temp_addr_i | temp_addr_y;
821 	}
822 
823 	/* Add dram base address */
824 	ret_addr += dram_base_addr;
825 
826 	/* If legacy MMIO hole enabled */
827 	if (lgcy_mmio_hole_en) {
828 		if (amd_df_indirect_read(nid, 0, 0x104, umc, &tmp))
829 			goto out_err;
830 
831 		dram_hole_base = tmp & GENMASK(31, 24);
832 		if (ret_addr >= dram_hole_base)
833 			ret_addr += (BIT_ULL(32) - dram_hole_base);
834 	}
835 
836 	if (hash_enabled) {
837 		/* Save some parentheses and grab ls-bit at the end. */
838 		hashed_bit =	(ret_addr >> 12) ^
839 				(ret_addr >> 18) ^
840 				(ret_addr >> 21) ^
841 				(ret_addr >> 30) ^
842 				cs_id;
843 
844 		hashed_bit &= BIT(0);
845 
846 		if (hashed_bit != ((ret_addr >> intlv_addr_bit) & BIT(0)))
847 			ret_addr ^= BIT(intlv_addr_bit);
848 	}
849 
850 	/* Is calculated system address is above DRAM limit address? */
851 	if (ret_addr > dram_limit_addr)
852 		goto out_err;
853 
854 	*sys_addr = ret_addr;
855 	return 0;
856 
857 out_err:
858 	return -EINVAL;
859 }
860 EXPORT_SYMBOL_GPL(umc_normaddr_to_sysaddr);
861 
862 bool amd_mce_is_memory_error(struct mce *m)
863 {
864 	/* ErrCodeExt[20:16] */
865 	u8 xec = (m->status >> 16) & 0x1f;
866 
867 	if (mce_flags.smca)
868 		return smca_get_bank_type(m->bank) == SMCA_UMC && xec == 0x0;
869 
870 	return m->bank == 4 && xec == 0x8;
871 }
872 
873 static void __log_error(unsigned int bank, u64 status, u64 addr, u64 misc)
874 {
875 	struct mce m;
876 
877 	mce_setup(&m);
878 
879 	m.status = status;
880 	m.misc   = misc;
881 	m.bank   = bank;
882 	m.tsc	 = rdtsc();
883 
884 	if (m.status & MCI_STATUS_ADDRV) {
885 		m.addr = addr;
886 
887 		/*
888 		 * Extract [55:<lsb>] where lsb is the least significant
889 		 * *valid* bit of the address bits.
890 		 */
891 		if (mce_flags.smca) {
892 			u8 lsb = (m.addr >> 56) & 0x3f;
893 
894 			m.addr &= GENMASK_ULL(55, lsb);
895 		}
896 	}
897 
898 	if (mce_flags.smca) {
899 		rdmsrl(MSR_AMD64_SMCA_MCx_IPID(bank), m.ipid);
900 
901 		if (m.status & MCI_STATUS_SYNDV)
902 			rdmsrl(MSR_AMD64_SMCA_MCx_SYND(bank), m.synd);
903 	}
904 
905 	mce_log(&m);
906 }
907 
908 asmlinkage __visible void __irq_entry smp_deferred_error_interrupt(struct pt_regs *regs)
909 {
910 	entering_irq();
911 	trace_deferred_error_apic_entry(DEFERRED_ERROR_VECTOR);
912 	inc_irq_stat(irq_deferred_error_count);
913 	deferred_error_int_vector();
914 	trace_deferred_error_apic_exit(DEFERRED_ERROR_VECTOR);
915 	exiting_ack_irq();
916 }
917 
918 /*
919  * Returns true if the logged error is deferred. False, otherwise.
920  */
921 static inline bool
922 _log_error_bank(unsigned int bank, u32 msr_stat, u32 msr_addr, u64 misc)
923 {
924 	u64 status, addr = 0;
925 
926 	rdmsrl(msr_stat, status);
927 	if (!(status & MCI_STATUS_VAL))
928 		return false;
929 
930 	if (status & MCI_STATUS_ADDRV)
931 		rdmsrl(msr_addr, addr);
932 
933 	__log_error(bank, status, addr, misc);
934 
935 	wrmsrl(msr_stat, 0);
936 
937 	return status & MCI_STATUS_DEFERRED;
938 }
939 
940 /*
941  * We have three scenarios for checking for Deferred errors:
942  *
943  * 1) Non-SMCA systems check MCA_STATUS and log error if found.
944  * 2) SMCA systems check MCA_STATUS. If error is found then log it and also
945  *    clear MCA_DESTAT.
946  * 3) SMCA systems check MCA_DESTAT, if error was not found in MCA_STATUS, and
947  *    log it.
948  */
949 static void log_error_deferred(unsigned int bank)
950 {
951 	bool defrd;
952 
953 	defrd = _log_error_bank(bank, msr_ops.status(bank),
954 					msr_ops.addr(bank), 0);
955 
956 	if (!mce_flags.smca)
957 		return;
958 
959 	/* Clear MCA_DESTAT if we logged the deferred error from MCA_STATUS. */
960 	if (defrd) {
961 		wrmsrl(MSR_AMD64_SMCA_MCx_DESTAT(bank), 0);
962 		return;
963 	}
964 
965 	/*
966 	 * Only deferred errors are logged in MCA_DE{STAT,ADDR} so just check
967 	 * for a valid error.
968 	 */
969 	_log_error_bank(bank, MSR_AMD64_SMCA_MCx_DESTAT(bank),
970 			      MSR_AMD64_SMCA_MCx_DEADDR(bank), 0);
971 }
972 
973 /* APIC interrupt handler for deferred errors */
974 static void amd_deferred_error_interrupt(void)
975 {
976 	unsigned int bank;
977 
978 	for (bank = 0; bank < this_cpu_read(mce_num_banks); ++bank)
979 		log_error_deferred(bank);
980 }
981 
982 static void log_error_thresholding(unsigned int bank, u64 misc)
983 {
984 	_log_error_bank(bank, msr_ops.status(bank), msr_ops.addr(bank), misc);
985 }
986 
987 static void log_and_reset_block(struct threshold_block *block)
988 {
989 	struct thresh_restart tr;
990 	u32 low = 0, high = 0;
991 
992 	if (!block)
993 		return;
994 
995 	if (rdmsr_safe(block->address, &low, &high))
996 		return;
997 
998 	if (!(high & MASK_OVERFLOW_HI))
999 		return;
1000 
1001 	/* Log the MCE which caused the threshold event. */
1002 	log_error_thresholding(block->bank, ((u64)high << 32) | low);
1003 
1004 	/* Reset threshold block after logging error. */
1005 	memset(&tr, 0, sizeof(tr));
1006 	tr.b = block;
1007 	threshold_restart_bank(&tr);
1008 }
1009 
1010 /*
1011  * Threshold interrupt handler will service THRESHOLD_APIC_VECTOR. The interrupt
1012  * goes off when error_count reaches threshold_limit.
1013  */
1014 static void amd_threshold_interrupt(void)
1015 {
1016 	struct threshold_block *first_block = NULL, *block = NULL, *tmp = NULL;
1017 	unsigned int bank, cpu = smp_processor_id();
1018 
1019 	for (bank = 0; bank < this_cpu_read(mce_num_banks); ++bank) {
1020 		if (!(per_cpu(bank_map, cpu) & (1 << bank)))
1021 			continue;
1022 
1023 		first_block = per_cpu(threshold_banks, cpu)[bank]->blocks;
1024 		if (!first_block)
1025 			continue;
1026 
1027 		/*
1028 		 * The first block is also the head of the list. Check it first
1029 		 * before iterating over the rest.
1030 		 */
1031 		log_and_reset_block(first_block);
1032 		list_for_each_entry_safe(block, tmp, &first_block->miscj, miscj)
1033 			log_and_reset_block(block);
1034 	}
1035 }
1036 
1037 /*
1038  * Sysfs Interface
1039  */
1040 
1041 struct threshold_attr {
1042 	struct attribute attr;
1043 	ssize_t (*show) (struct threshold_block *, char *);
1044 	ssize_t (*store) (struct threshold_block *, const char *, size_t count);
1045 };
1046 
1047 #define SHOW_FIELDS(name)						\
1048 static ssize_t show_ ## name(struct threshold_block *b, char *buf)	\
1049 {									\
1050 	return sprintf(buf, "%lu\n", (unsigned long) b->name);		\
1051 }
1052 SHOW_FIELDS(interrupt_enable)
1053 SHOW_FIELDS(threshold_limit)
1054 
1055 static ssize_t
1056 store_interrupt_enable(struct threshold_block *b, const char *buf, size_t size)
1057 {
1058 	struct thresh_restart tr;
1059 	unsigned long new;
1060 
1061 	if (!b->interrupt_capable)
1062 		return -EINVAL;
1063 
1064 	if (kstrtoul(buf, 0, &new) < 0)
1065 		return -EINVAL;
1066 
1067 	b->interrupt_enable = !!new;
1068 
1069 	memset(&tr, 0, sizeof(tr));
1070 	tr.b		= b;
1071 
1072 	smp_call_function_single(b->cpu, threshold_restart_bank, &tr, 1);
1073 
1074 	return size;
1075 }
1076 
1077 static ssize_t
1078 store_threshold_limit(struct threshold_block *b, const char *buf, size_t size)
1079 {
1080 	struct thresh_restart tr;
1081 	unsigned long new;
1082 
1083 	if (kstrtoul(buf, 0, &new) < 0)
1084 		return -EINVAL;
1085 
1086 	if (new > THRESHOLD_MAX)
1087 		new = THRESHOLD_MAX;
1088 	if (new < 1)
1089 		new = 1;
1090 
1091 	memset(&tr, 0, sizeof(tr));
1092 	tr.old_limit = b->threshold_limit;
1093 	b->threshold_limit = new;
1094 	tr.b = b;
1095 
1096 	smp_call_function_single(b->cpu, threshold_restart_bank, &tr, 1);
1097 
1098 	return size;
1099 }
1100 
1101 static ssize_t show_error_count(struct threshold_block *b, char *buf)
1102 {
1103 	u32 lo, hi;
1104 
1105 	rdmsr_on_cpu(b->cpu, b->address, &lo, &hi);
1106 
1107 	return sprintf(buf, "%u\n", ((hi & THRESHOLD_MAX) -
1108 				     (THRESHOLD_MAX - b->threshold_limit)));
1109 }
1110 
1111 static struct threshold_attr error_count = {
1112 	.attr = {.name = __stringify(error_count), .mode = 0444 },
1113 	.show = show_error_count,
1114 };
1115 
1116 #define RW_ATTR(val)							\
1117 static struct threshold_attr val = {					\
1118 	.attr	= {.name = __stringify(val), .mode = 0644 },		\
1119 	.show	= show_## val,						\
1120 	.store	= store_## val,						\
1121 };
1122 
1123 RW_ATTR(interrupt_enable);
1124 RW_ATTR(threshold_limit);
1125 
1126 static struct attribute *default_attrs[] = {
1127 	&threshold_limit.attr,
1128 	&error_count.attr,
1129 	NULL,	/* possibly interrupt_enable if supported, see below */
1130 	NULL,
1131 };
1132 
1133 #define to_block(k)	container_of(k, struct threshold_block, kobj)
1134 #define to_attr(a)	container_of(a, struct threshold_attr, attr)
1135 
1136 static ssize_t show(struct kobject *kobj, struct attribute *attr, char *buf)
1137 {
1138 	struct threshold_block *b = to_block(kobj);
1139 	struct threshold_attr *a = to_attr(attr);
1140 	ssize_t ret;
1141 
1142 	ret = a->show ? a->show(b, buf) : -EIO;
1143 
1144 	return ret;
1145 }
1146 
1147 static ssize_t store(struct kobject *kobj, struct attribute *attr,
1148 		     const char *buf, size_t count)
1149 {
1150 	struct threshold_block *b = to_block(kobj);
1151 	struct threshold_attr *a = to_attr(attr);
1152 	ssize_t ret;
1153 
1154 	ret = a->store ? a->store(b, buf, count) : -EIO;
1155 
1156 	return ret;
1157 }
1158 
1159 static const struct sysfs_ops threshold_ops = {
1160 	.show			= show,
1161 	.store			= store,
1162 };
1163 
1164 static struct kobj_type threshold_ktype = {
1165 	.sysfs_ops		= &threshold_ops,
1166 	.default_attrs		= default_attrs,
1167 };
1168 
1169 static const char *get_name(unsigned int bank, struct threshold_block *b)
1170 {
1171 	enum smca_bank_types bank_type;
1172 
1173 	if (!mce_flags.smca) {
1174 		if (b && bank == 4)
1175 			return bank4_names(b);
1176 
1177 		return th_names[bank];
1178 	}
1179 
1180 	bank_type = smca_get_bank_type(bank);
1181 	if (bank_type >= N_SMCA_BANK_TYPES)
1182 		return NULL;
1183 
1184 	if (b && bank_type == SMCA_UMC) {
1185 		if (b->block < ARRAY_SIZE(smca_umc_block_names))
1186 			return smca_umc_block_names[b->block];
1187 		return NULL;
1188 	}
1189 
1190 	if (smca_banks[bank].hwid->count == 1)
1191 		return smca_get_name(bank_type);
1192 
1193 	snprintf(buf_mcatype, MAX_MCATYPE_NAME_LEN,
1194 		 "%s_%x", smca_get_name(bank_type),
1195 			  smca_banks[bank].sysfs_id);
1196 	return buf_mcatype;
1197 }
1198 
1199 static int allocate_threshold_blocks(unsigned int cpu, unsigned int bank,
1200 				     unsigned int block, u32 address)
1201 {
1202 	struct threshold_block *b = NULL;
1203 	u32 low, high;
1204 	int err;
1205 
1206 	if ((bank >= per_cpu(mce_num_banks, cpu)) || (block >= NR_BLOCKS))
1207 		return 0;
1208 
1209 	if (rdmsr_safe_on_cpu(cpu, address, &low, &high))
1210 		return 0;
1211 
1212 	if (!(high & MASK_VALID_HI)) {
1213 		if (block)
1214 			goto recurse;
1215 		else
1216 			return 0;
1217 	}
1218 
1219 	if (!(high & MASK_CNTP_HI)  ||
1220 	     (high & MASK_LOCKED_HI))
1221 		goto recurse;
1222 
1223 	b = kzalloc(sizeof(struct threshold_block), GFP_KERNEL);
1224 	if (!b)
1225 		return -ENOMEM;
1226 
1227 	b->block		= block;
1228 	b->bank			= bank;
1229 	b->cpu			= cpu;
1230 	b->address		= address;
1231 	b->interrupt_enable	= 0;
1232 	b->interrupt_capable	= lvt_interrupt_supported(bank, high);
1233 	b->threshold_limit	= THRESHOLD_MAX;
1234 
1235 	if (b->interrupt_capable) {
1236 		threshold_ktype.default_attrs[2] = &interrupt_enable.attr;
1237 		b->interrupt_enable = 1;
1238 	} else {
1239 		threshold_ktype.default_attrs[2] = NULL;
1240 	}
1241 
1242 	INIT_LIST_HEAD(&b->miscj);
1243 
1244 	if (per_cpu(threshold_banks, cpu)[bank]->blocks) {
1245 		list_add(&b->miscj,
1246 			 &per_cpu(threshold_banks, cpu)[bank]->blocks->miscj);
1247 	} else {
1248 		per_cpu(threshold_banks, cpu)[bank]->blocks = b;
1249 	}
1250 
1251 	err = kobject_init_and_add(&b->kobj, &threshold_ktype,
1252 				   per_cpu(threshold_banks, cpu)[bank]->kobj,
1253 				   get_name(bank, b));
1254 	if (err)
1255 		goto out_free;
1256 recurse:
1257 	address = get_block_address(address, low, high, bank, ++block, cpu);
1258 	if (!address)
1259 		return 0;
1260 
1261 	err = allocate_threshold_blocks(cpu, bank, block, address);
1262 	if (err)
1263 		goto out_free;
1264 
1265 	if (b)
1266 		kobject_uevent(&b->kobj, KOBJ_ADD);
1267 
1268 	return err;
1269 
1270 out_free:
1271 	if (b) {
1272 		kobject_put(&b->kobj);
1273 		list_del(&b->miscj);
1274 		kfree(b);
1275 	}
1276 	return err;
1277 }
1278 
1279 static int __threshold_add_blocks(struct threshold_bank *b)
1280 {
1281 	struct list_head *head = &b->blocks->miscj;
1282 	struct threshold_block *pos = NULL;
1283 	struct threshold_block *tmp = NULL;
1284 	int err = 0;
1285 
1286 	err = kobject_add(&b->blocks->kobj, b->kobj, b->blocks->kobj.name);
1287 	if (err)
1288 		return err;
1289 
1290 	list_for_each_entry_safe(pos, tmp, head, miscj) {
1291 
1292 		err = kobject_add(&pos->kobj, b->kobj, pos->kobj.name);
1293 		if (err) {
1294 			list_for_each_entry_safe_reverse(pos, tmp, head, miscj)
1295 				kobject_del(&pos->kobj);
1296 
1297 			return err;
1298 		}
1299 	}
1300 	return err;
1301 }
1302 
1303 static int threshold_create_bank(unsigned int cpu, unsigned int bank)
1304 {
1305 	struct device *dev = per_cpu(mce_device, cpu);
1306 	struct amd_northbridge *nb = NULL;
1307 	struct threshold_bank *b = NULL;
1308 	const char *name = get_name(bank, NULL);
1309 	int err = 0;
1310 
1311 	if (!dev)
1312 		return -ENODEV;
1313 
1314 	if (is_shared_bank(bank)) {
1315 		nb = node_to_amd_nb(amd_get_nb_id(cpu));
1316 
1317 		/* threshold descriptor already initialized on this node? */
1318 		if (nb && nb->bank4) {
1319 			/* yes, use it */
1320 			b = nb->bank4;
1321 			err = kobject_add(b->kobj, &dev->kobj, name);
1322 			if (err)
1323 				goto out;
1324 
1325 			per_cpu(threshold_banks, cpu)[bank] = b;
1326 			refcount_inc(&b->cpus);
1327 
1328 			err = __threshold_add_blocks(b);
1329 
1330 			goto out;
1331 		}
1332 	}
1333 
1334 	b = kzalloc(sizeof(struct threshold_bank), GFP_KERNEL);
1335 	if (!b) {
1336 		err = -ENOMEM;
1337 		goto out;
1338 	}
1339 
1340 	b->kobj = kobject_create_and_add(name, &dev->kobj);
1341 	if (!b->kobj) {
1342 		err = -EINVAL;
1343 		goto out_free;
1344 	}
1345 
1346 	per_cpu(threshold_banks, cpu)[bank] = b;
1347 
1348 	if (is_shared_bank(bank)) {
1349 		refcount_set(&b->cpus, 1);
1350 
1351 		/* nb is already initialized, see above */
1352 		if (nb) {
1353 			WARN_ON(nb->bank4);
1354 			nb->bank4 = b;
1355 		}
1356 	}
1357 
1358 	err = allocate_threshold_blocks(cpu, bank, 0, msr_ops.misc(bank));
1359 	if (!err)
1360 		goto out;
1361 
1362  out_free:
1363 	kfree(b);
1364 
1365  out:
1366 	return err;
1367 }
1368 
1369 static void deallocate_threshold_block(unsigned int cpu,
1370 						 unsigned int bank)
1371 {
1372 	struct threshold_block *pos = NULL;
1373 	struct threshold_block *tmp = NULL;
1374 	struct threshold_bank *head = per_cpu(threshold_banks, cpu)[bank];
1375 
1376 	if (!head)
1377 		return;
1378 
1379 	list_for_each_entry_safe(pos, tmp, &head->blocks->miscj, miscj) {
1380 		kobject_put(&pos->kobj);
1381 		list_del(&pos->miscj);
1382 		kfree(pos);
1383 	}
1384 
1385 	kfree(per_cpu(threshold_banks, cpu)[bank]->blocks);
1386 	per_cpu(threshold_banks, cpu)[bank]->blocks = NULL;
1387 }
1388 
1389 static void __threshold_remove_blocks(struct threshold_bank *b)
1390 {
1391 	struct threshold_block *pos = NULL;
1392 	struct threshold_block *tmp = NULL;
1393 
1394 	kobject_del(b->kobj);
1395 
1396 	list_for_each_entry_safe(pos, tmp, &b->blocks->miscj, miscj)
1397 		kobject_del(&pos->kobj);
1398 }
1399 
1400 static void threshold_remove_bank(unsigned int cpu, int bank)
1401 {
1402 	struct amd_northbridge *nb;
1403 	struct threshold_bank *b;
1404 
1405 	b = per_cpu(threshold_banks, cpu)[bank];
1406 	if (!b)
1407 		return;
1408 
1409 	if (!b->blocks)
1410 		goto free_out;
1411 
1412 	if (is_shared_bank(bank)) {
1413 		if (!refcount_dec_and_test(&b->cpus)) {
1414 			__threshold_remove_blocks(b);
1415 			per_cpu(threshold_banks, cpu)[bank] = NULL;
1416 			return;
1417 		} else {
1418 			/*
1419 			 * the last CPU on this node using the shared bank is
1420 			 * going away, remove that bank now.
1421 			 */
1422 			nb = node_to_amd_nb(amd_get_nb_id(cpu));
1423 			nb->bank4 = NULL;
1424 		}
1425 	}
1426 
1427 	deallocate_threshold_block(cpu, bank);
1428 
1429 free_out:
1430 	kobject_del(b->kobj);
1431 	kobject_put(b->kobj);
1432 	kfree(b);
1433 	per_cpu(threshold_banks, cpu)[bank] = NULL;
1434 }
1435 
1436 int mce_threshold_remove_device(unsigned int cpu)
1437 {
1438 	unsigned int bank;
1439 
1440 	for (bank = 0; bank < per_cpu(mce_num_banks, cpu); ++bank) {
1441 		if (!(per_cpu(bank_map, cpu) & (1 << bank)))
1442 			continue;
1443 		threshold_remove_bank(cpu, bank);
1444 	}
1445 	kfree(per_cpu(threshold_banks, cpu));
1446 	per_cpu(threshold_banks, cpu) = NULL;
1447 	return 0;
1448 }
1449 
1450 /* create dir/files for all valid threshold banks */
1451 int mce_threshold_create_device(unsigned int cpu)
1452 {
1453 	unsigned int bank;
1454 	struct threshold_bank **bp;
1455 	int err = 0;
1456 
1457 	bp = per_cpu(threshold_banks, cpu);
1458 	if (bp)
1459 		return 0;
1460 
1461 	bp = kcalloc(per_cpu(mce_num_banks, cpu), sizeof(struct threshold_bank *),
1462 		     GFP_KERNEL);
1463 	if (!bp)
1464 		return -ENOMEM;
1465 
1466 	per_cpu(threshold_banks, cpu) = bp;
1467 
1468 	for (bank = 0; bank < per_cpu(mce_num_banks, cpu); ++bank) {
1469 		if (!(per_cpu(bank_map, cpu) & (1 << bank)))
1470 			continue;
1471 		err = threshold_create_bank(cpu, bank);
1472 		if (err)
1473 			goto err;
1474 	}
1475 	return err;
1476 err:
1477 	mce_threshold_remove_device(cpu);
1478 	return err;
1479 }
1480 
1481 static __init int threshold_init_device(void)
1482 {
1483 	unsigned lcpu = 0;
1484 
1485 	/* to hit CPUs online before the notifier is up */
1486 	for_each_online_cpu(lcpu) {
1487 		int err = mce_threshold_create_device(lcpu);
1488 
1489 		if (err)
1490 			return err;
1491 	}
1492 
1493 	if (thresholding_irq_en)
1494 		mce_threshold_vector = amd_threshold_interrupt;
1495 
1496 	return 0;
1497 }
1498 /*
1499  * there are 3 funcs which need to be _initcalled in a logic sequence:
1500  * 1. xen_late_init_mcelog
1501  * 2. mcheck_init_device
1502  * 3. threshold_init_device
1503  *
1504  * xen_late_init_mcelog must register xen_mce_chrdev_device before
1505  * native mce_chrdev_device registration if running under xen platform;
1506  *
1507  * mcheck_init_device should be inited before threshold_init_device to
1508  * initialize mce_device, otherwise a NULL ptr dereference will cause panic.
1509  *
1510  * so we use following _initcalls
1511  * 1. device_initcall(xen_late_init_mcelog);
1512  * 2. device_initcall_sync(mcheck_init_device);
1513  * 3. late_initcall(threshold_init_device);
1514  *
1515  * when running under xen, the initcall order is 1,2,3;
1516  * on baremetal, we skip 1 and we do only 2 and 3.
1517  */
1518 late_initcall(threshold_init_device);
1519