1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #include <sys/mca_x86.h>
28 #include <sys/cpu_module_impl.h>
29 #include <sys/cpu_module_ms.h>
30 #include <sys/cmn_err.h>
31 #include <sys/cpuvar.h>
32 #include <sys/pghw.h>
33 #include <sys/x86_archext.h>
34 #include <sys/sysmacros.h>
35 #include <sys/regset.h>
36 #include <sys/privregs.h>
37 #include <sys/systm.h>
38 #include <sys/types.h>
39 #include <sys/log.h>
40 #include <sys/psw.h>
41 #include <sys/fm/protocol.h>
42 #include <sys/fm/util.h>
43 #include <sys/errorq.h>
44 #include <sys/mca_x86.h>
45 #include <sys/fm/cpu/GMCA.h>
46 #include <sys/sysevent.h>
47 #include <sys/ontrap.h>
48 
49 #include "gcpu.h"
50 
51 /*
52  * Clear to log telemetry found at initialization.  While processor docs
53  * say you should process this telemetry on all but Intel family 0x6
54  * there are way too many exceptions and we want to avoid bogus
55  * diagnoses.
56  */
57 int gcpu_suppress_log_on_init = 1;
58 
59 /*
60  * gcpu_mca_stack_flag is a debug assist option to capture a stack trace at
61  * error logout time.  The stack will be included in the ereport if the
62  * error type selects stack inclusion, or in all cases if
63  * gcpu_mca_stack_ereport_include is nonzero.
64  */
65 int gcpu_mca_stack_flag = 0;
66 int gcpu_mca_stack_ereport_include = 0;
67 
68 /*
69  * The number of times to re-read MCA telemetry to try to obtain a
70  * consistent snapshot if we find it to be changing under our feet.
71  */
72 int gcpu_mca_telemetry_retries = 5;
73 
74 #ifndef __xpv
75 int gcpu_mca_cmci_throttling_threshold = 10;
76 int gcpu_mca_cmci_reenable_threshold = 1000;
77 #endif
78 
79 static gcpu_error_disp_t gcpu_errtypes[] = {
80 
81 	/*
82 	 * Unclassified
83 	 */
84 	{
85 		FM_EREPORT_CPU_GENERIC_UNCLASSIFIED,
86 		NULL,
87 		FM_EREPORT_PAYLOAD_FLAGS_COMMON,
88 		MCAX86_SIMPLE_UNCLASSIFIED_MASKON,
89 		MCAX86_SIMPLE_UNCLASSIFIED_MASKOFF
90 	},
91 
92 	/*
93 	 * Microcode ROM Parity Error
94 	 */
95 	{
96 		FM_EREPORT_CPU_GENERIC_MC_CODE_PARITY,
97 		NULL,
98 		FM_EREPORT_PAYLOAD_FLAGS_COMMON,
99 		MCAX86_SIMPLE_MC_CODE_PARITY_MASKON,
100 		MCAX86_SIMPLE_MC_CODE_PARITY_MASKOFF
101 	},
102 
103 	/*
104 	 * External - BINIT# from another processor during power-on config
105 	 */
106 	{
107 		FM_EREPORT_CPU_GENERIC_EXTERNAL,
108 		NULL,
109 		FM_EREPORT_PAYLOAD_FLAGS_COMMON,
110 		MCAX86_SIMPLE_EXTERNAL_MASKON,
111 		MCAX86_SIMPLE_EXTERNAL_MASKOFF
112 	},
113 
114 	/*
115 	 * Functional redundancy check master/slave error
116 	 */
117 	{
118 		FM_EREPORT_CPU_GENERIC_FRC,
119 		NULL,
120 		FM_EREPORT_PAYLOAD_FLAGS_COMMON,
121 		MCAX86_SIMPLE_FRC_MASKON,
122 		MCAX86_SIMPLE_FRC_MASKOFF
123 	},
124 
125 	/*
126 	 * Internal parity error
127 	 */
128 	{
129 		FM_EREPORT_CPU_GENERIC_INTERNAL_PARITY,
130 		NULL,
131 		FM_EREPORT_PAYLOAD_FLAGS_COMMON,
132 		MCAX86_SIMPLE_INTERNAL_PARITY_MASKON,
133 		MCAX86_SIMPLE_INTERNAL_PARITY_MASKOFF
134 	},
135 
136 
137 	/*
138 	 * Internal timer error
139 	 */
140 	{
141 		FM_EREPORT_CPU_GENERIC_INTERNAL_TIMER,
142 		NULL,
143 		FM_EREPORT_PAYLOAD_FLAGS_COMMON,
144 		MCAX86_SIMPLE_INTERNAL_TIMER_MASKON,
145 		MCAX86_SIMPLE_INTERNAL_TIMER_MASKOFF
146 	},
147 
148 	/*
149 	 * Internal unclassified
150 	 */
151 	{
152 		FM_EREPORT_CPU_GENERIC_INTERNAL_UNCLASS,
153 		NULL,
154 		FM_EREPORT_PAYLOAD_FLAGS_COMMON,
155 		MCAX86_SIMPLE_INTERNAL_UNCLASS_MASK_MASKON,
156 		MCAX86_SIMPLE_INTERNAL_UNCLASS_MASK_MASKOFF
157 	},
158 
159 	/*
160 	 * Compound error codes - generic memory hierarchy
161 	 */
162 	{
163 		FM_EREPORT_CPU_GENERIC_GENMEMHIER,
164 		NULL,
165 		FM_EREPORT_PAYLOAD_FLAGS_COMMON, /* yes, no compound name */
166 		MCAX86_COMPOUND_GENERIC_MEMHIER_MASKON,
167 		MCAX86_COMPOUND_GENERIC_MEMHIER_MASKOFF
168 	},
169 
170 	/*
171 	 * Compound error codes - TLB errors
172 	 */
173 	{
174 		FM_EREPORT_CPU_GENERIC_TLB,
175 		"%1$s" "TLB" "%2$s" "_ERR",
176 		FM_EREPORT_PAYLOAD_FLAGS_COMPOUND_ERR,
177 		MCAX86_COMPOUND_TLB_MASKON,
178 		MCAX86_COMPOUND_TLB_MASKOFF
179 	},
180 
181 	/*
182 	 * Compound error codes - memory hierarchy
183 	 */
184 	{
185 		FM_EREPORT_CPU_GENERIC_MEMHIER,
186 		"%1$s" "CACHE" "%2$s" "_" "%3$s" "_ERR",
187 		FM_EREPORT_PAYLOAD_FLAGS_COMPOUND_ERR,
188 		MCAX86_COMPOUND_MEMHIER_MASKON,
189 		MCAX86_COMPOUND_MEMHIER_MASKOFF
190 	},
191 
192 	/*
193 	 * Compound error codes - bus and interconnect errors
194 	 */
195 	{
196 		FM_EREPORT_CPU_GENERIC_BUS_INTERCONNECT,
197 		"BUS" "%2$s" "_" "%4$s" "_" "%3$s" "_" "%5$s" "_" "%6$s" "_ERR",
198 		FM_EREPORT_PAYLOAD_FLAGS_COMPOUND_ERR,
199 		MCAX86_COMPOUND_BUS_INTERCONNECT_MASKON,
200 		MCAX86_COMPOUND_BUS_INTERCONNECT_MASKOFF
201 	},
202 	/*
203 	 * Compound error codes - memory controller errors
204 	 */
205 	{
206 		FM_EREPORT_CPU_GENERIC_MEMORY_CONTROLLER,
207 		"MC" "_" "%8$s" "_" "%9$s" "_ERR",
208 		FM_EREPORT_PAYLOAD_FLAGS_COMPOUND_ERR,
209 		MCAX86_COMPOUND_MEMORY_CONTROLLER_MASKON,
210 		MCAX86_COMPOUND_MEMORY_CONTROLLER_MASKOFF
211 	},
212 };
213 
214 static gcpu_error_disp_t gcpu_unknown = {
215 	FM_EREPORT_CPU_GENERIC_UNKNOWN,
216 	"UNKNOWN",
217 	FM_EREPORT_PAYLOAD_FLAGS_COMMON,
218 	0,
219 	0
220 };
221 
222 static errorq_t *gcpu_mca_queue;
223 static kmutex_t gcpu_mca_queue_lock;
224 
225 #ifdef __xpv
226 static int isxpv = 1;
227 #else
228 static int isxpv = 0;
229 #endif
230 
231 static const gcpu_error_disp_t *
232 gcpu_disp_match(uint16_t code)
233 {
234 	const gcpu_error_disp_t *ged = gcpu_errtypes;
235 	int i;
236 
237 	for (i = 0; i < sizeof (gcpu_errtypes) / sizeof (gcpu_error_disp_t);
238 	    i++, ged++) {
239 		uint16_t on = ged->ged_errcode_mask_on;
240 		uint16_t off = ged->ged_errcode_mask_off;
241 
242 		if ((code & on) == on && (code & off) == 0)
243 			return (ged);
244 	}
245 
246 	return (NULL);
247 }
248 
249 static uint8_t
250 bit_strip(uint16_t code, uint16_t mask, uint16_t shift)
251 {
252 	return ((uint8_t)(code & mask) >> shift);
253 }
254 
255 #define	BIT_STRIP(code, name) \
256 	bit_strip(code, MCAX86_ERRCODE_##name##_MASK, \
257 	MCAX86_ERRCODE_##name##_SHIFT)
258 
259 #define	GCPU_MNEMONIC_UNDEF	"undefined"
260 #define	GCPU_MNEMONIC_RESVD	"reserved"
261 
262 /*
263  * Mappings of TT, LL, RRRR, PP, II and T values to compound error name
264  * mnemonics and to ereport class name components.
265  */
266 
267 struct gcpu_mnexp {
268 	const char *mne_compound;	/* used in expanding compound errname */
269 	const char *mne_ereport;	/* used in expanding ereport class */
270 };
271 
272 static struct gcpu_mnexp gcpu_TT_mnemonics[] = { /* MCAX86_ERRCODE_TT_* */
273 	{ "I", FM_EREPORT_CPU_GENERIC_TT_INSTR },		/* INSTR */
274 	{ "D", FM_EREPORT_CPU_GENERIC_TT_DATA },		/* DATA */
275 	{ "G", FM_EREPORT_CPU_GENERIC_TT_GEN },			/* GEN */
276 	{ GCPU_MNEMONIC_UNDEF, "" }
277 };
278 
279 static struct gcpu_mnexp gcpu_LL_mnemonics[] = { /* MCAX86_ERRCODE_LL_* */
280 	{ "LO", FM_EREPORT_CPU_GENERIC_LL_L0 },			/* L0 */
281 	{ "L1",	FM_EREPORT_CPU_GENERIC_LL_L1 },			/* L1 */
282 	{ "L2",	FM_EREPORT_CPU_GENERIC_LL_L2 },			/* L2 */
283 	{ "LG", FM_EREPORT_CPU_GENERIC_LL_LG }			/* LG */
284 };
285 
286 static struct gcpu_mnexp gcpu_RRRR_mnemonics[] = { /* MCAX86_ERRCODE_RRRR_* */
287 	{ "ERR", FM_EREPORT_CPU_GENERIC_RRRR_ERR },		/* ERR */
288 	{ "RD",	FM_EREPORT_CPU_GENERIC_RRRR_RD },		/* RD */
289 	{ "WR", FM_EREPORT_CPU_GENERIC_RRRR_WR },		/* WR */
290 	{ "DRD", FM_EREPORT_CPU_GENERIC_RRRR_DRD },		/* DRD */
291 	{ "DWR", FM_EREPORT_CPU_GENERIC_RRRR_DWR },		/* DWR */
292 	{ "IRD", FM_EREPORT_CPU_GENERIC_RRRR_IRD },		/* IRD */
293 	{ "PREFETCH", FM_EREPORT_CPU_GENERIC_RRRR_PREFETCH },	/* PREFETCH */
294 	{ "EVICT", FM_EREPORT_CPU_GENERIC_RRRR_EVICT },		/* EVICT */
295 	{ "SNOOP", FM_EREPORT_CPU_GENERIC_RRRR_SNOOP },		/* SNOOP */
296 };
297 
298 static struct gcpu_mnexp gcpu_PP_mnemonics[] = { /* MCAX86_ERRCODE_PP_* */
299 	{ "SRC", FM_EREPORT_CPU_GENERIC_PP_SRC },		/* SRC */
300 	{ "RES", FM_EREPORT_CPU_GENERIC_PP_RES },		/* RES */
301 	{ "OBS", FM_EREPORT_CPU_GENERIC_PP_OBS },		/* OBS */
302 	{ "", FM_EREPORT_CPU_GENERIC_PP_GEN }			/* GEN */
303 };
304 
305 static struct gcpu_mnexp gcpu_II_mnemonics[] = { /* MCAX86_ERRCODE_II_* */
306 	{ "M", FM_EREPORT_CPU_GENERIC_II_MEM },			/* MEM */
307 	{ GCPU_MNEMONIC_RESVD, "" },
308 	{ "IO", FM_EREPORT_CPU_GENERIC_II_IO },			/* IO */
309 	{ "", FM_EREPORT_CPU_GENERIC_II_GEN }			/* GEN */
310 };
311 
312 static struct gcpu_mnexp gcpu_T_mnemonics[] = {	 /* MCAX86_ERRCODE_T_* */
313 	{ "NOTIMEOUT", FM_EREPORT_CPU_GENERIC_T_NOTIMEOUT },	/* NONE */
314 	{ "TIMEOUT", FM_EREPORT_CPU_GENERIC_T_TIMEOUT }		/* TIMEOUT */
315 };
316 
317 static struct gcpu_mnexp gcpu_CCCC_mnemonics[] = { /* MCAX86_ERRCODE_CCCC_* */
318 	{ "CH0", FM_EREPORT_CPU_GENERIC_CCCC },		/* CH0 */
319 	{ "CH1", FM_EREPORT_CPU_GENERIC_CCCC },		/* CH1 */
320 	{ "CH2", FM_EREPORT_CPU_GENERIC_CCCC },		/* CH2 */
321 	{ "CH3", FM_EREPORT_CPU_GENERIC_CCCC },		/* CH3 */
322 	{ "CH4", FM_EREPORT_CPU_GENERIC_CCCC },		/* CH4 */
323 	{ "CH5", FM_EREPORT_CPU_GENERIC_CCCC },		/* CH5 */
324 	{ "CH6", FM_EREPORT_CPU_GENERIC_CCCC },		/* CH6 */
325 	{ "CH7", FM_EREPORT_CPU_GENERIC_CCCC },		/* CH7 */
326 	{ "CH8", FM_EREPORT_CPU_GENERIC_CCCC },		/* CH8 */
327 	{ "CH9", FM_EREPORT_CPU_GENERIC_CCCC },		/* CH9 */
328 	{ "CH10", FM_EREPORT_CPU_GENERIC_CCCC },	/* CH10 */
329 	{ "CH11", FM_EREPORT_CPU_GENERIC_CCCC },	/* CH11 */
330 	{ "CH12", FM_EREPORT_CPU_GENERIC_CCCC },	/* CH12 */
331 	{ "CH13", FM_EREPORT_CPU_GENERIC_CCCC },	/* CH13 */
332 	{ "CH14", FM_EREPORT_CPU_GENERIC_CCCC },	/* CH14 */
333 	{ "CH", FM_EREPORT_CPU_GENERIC_CCCC }		/* GEN */
334 };
335 
336 static struct gcpu_mnexp gcpu_MMM_mnemonics[] = { /* MCAX86_ERRCODE_MMM_* */
337 	{ "GEN", FM_EREPORT_CPU_GENERIC_MMM_ERR },	/* GEN ERR */
338 	{ "RD", FM_EREPORT_CPU_GENERIC_MMM_RD },	/* READ  */
339 	{ "WR", FM_EREPORT_CPU_GENERIC_MMM_WR },	/* WRITE  */
340 	{ "ADDR_CMD", FM_EREPORT_CPU_GENERIC_MMM_ADRCMD },	/* ADDR, CMD  */
341 	{ GCPU_MNEMONIC_RESVD, ""},			/* RESERVED  */
342 	{ GCPU_MNEMONIC_RESVD, ""},			/* RESERVED  */
343 	{ GCPU_MNEMONIC_RESVD, ""},			/* RESERVED  */
344 	{ GCPU_MNEMONIC_RESVD, ""}			/* RESERVED  */
345 };
346 
347 enum gcpu_mn_namespace {
348 	GCPU_MN_NAMESPACE_COMPOUND,
349 	GCPU_MN_NAMESPACE_EREPORT
350 };
351 
352 static const char *
353 gcpu_mnemonic(const struct gcpu_mnexp *tbl, size_t tbl_sz, uint8_t val,
354     enum gcpu_mn_namespace nspace)
355 {
356 	if (val >= tbl_sz)
357 		return (GCPU_MNEMONIC_UNDEF);	/* for all namespaces */
358 
359 	switch (nspace) {
360 	case GCPU_MN_NAMESPACE_COMPOUND:
361 		return (tbl[val].mne_compound);
362 		/*NOTREACHED*/
363 
364 	case GCPU_MN_NAMESPACE_EREPORT:
365 		return (tbl[val].mne_ereport);
366 		/*NOTREACHED*/
367 
368 	default:
369 		return (GCPU_MNEMONIC_UNDEF);
370 		/*NOTREACHED*/
371 	}
372 }
373 
374 /*
375  * The ereport class leaf component is either a simple string with no
376  * format specifiers, or a string with one or more embedded %n$s specifiers -
377  * positional selection for string arguments.  The kernel snprintf does
378  * not support %n$ (and teaching it to do so is too big a headache) so
379  * we will expand this restricted format string ourselves.
380  */
381 
382 #define	GCPU_CLASS_VARCOMPS	9
383 
384 #define	GCPU_MNEMONIC(code, name, nspace) \
385 	gcpu_mnemonic(gcpu_##name##_mnemonics, \
386 	sizeof (gcpu_##name##_mnemonics) / sizeof (struct gcpu_mnexp), \
387 	BIT_STRIP(code, name), nspace)
388 
389 static void
390 gcpu_mn_fmt(const char *fmt, char *buf, size_t buflen, uint64_t status,
391     enum gcpu_mn_namespace nspace)
392 {
393 	uint16_t code = MCAX86_ERRCODE(status);
394 	const char *mn[GCPU_CLASS_VARCOMPS];
395 	char *p = buf;			/* current position in buf */
396 	char *q = buf + buflen;		/* pointer past last char in buf */
397 	int which, expfmtchar, error;
398 	char c;
399 
400 	mn[0] = GCPU_MNEMONIC(code, TT, nspace);
401 	mn[1] = GCPU_MNEMONIC(code, LL, nspace);
402 	mn[2] = GCPU_MNEMONIC(code, RRRR, nspace);
403 	mn[3] = GCPU_MNEMONIC(code, PP, nspace);
404 	mn[4] = GCPU_MNEMONIC(code, II, nspace);
405 	mn[5] = GCPU_MNEMONIC(code, T, nspace);
406 	mn[6] = (status & MSR_MC_STATUS_UC) ? "_uc" : "";
407 	mn[7] = GCPU_MNEMONIC(code, CCCC, nspace);
408 	mn[8] = GCPU_MNEMONIC(code, MMM, nspace);
409 
410 	while (p < q - 1 && (c = *fmt++) != '\0') {
411 		if (c != '%') {
412 			/* not the beginning of a format specifier - copy */
413 			*p++ = c;
414 			continue;
415 		}
416 
417 		error = 0;
418 		which = -1;
419 		expfmtchar = -1;
420 
421 nextfmt:
422 		if ((c = *fmt++) == '\0')
423 			break;	/* early termination of fmt specifier */
424 
425 		switch (c) {
426 		case '1':
427 		case '2':
428 		case '3':
429 		case '4':
430 		case '5':
431 		case '6':
432 		case '7':
433 		case '8':
434 		case '9':
435 			if (which != -1) { /* allow only one positional digit */
436 				error++;
437 				break;
438 			}
439 			which = c - '1';
440 			goto nextfmt;
441 			/*NOTREACHED*/
442 
443 		case '$':
444 			if (which == -1) { /* no position specified */
445 				error++;
446 				break;
447 			}
448 			expfmtchar = 's';
449 			goto nextfmt;
450 			/*NOTREACHED*/
451 
452 		case 's':
453 			if (expfmtchar != 's') {
454 				error++;
455 				break;
456 			}
457 			(void) snprintf(p, (uintptr_t)q - (uintptr_t)p, "%s",
458 			    mn[which]);
459 			p += strlen(p);
460 			break;
461 
462 		default:
463 			error++;
464 			break;
465 		}
466 
467 		if (error)
468 			break;
469 	}
470 
471 	*p = '\0';	/* NUL termination */
472 }
473 
474 static void
475 gcpu_erpt_clsfmt(const char *fmt, char *buf, size_t buflen, uint64_t status,
476     const char *cpuclass, const char *leafclass)
477 {
478 	char *p = buf;			/* current position in buf */
479 	char *q = buf + buflen;		/* pointer past last char in buf */
480 
481 	(void) snprintf(buf, (uintptr_t)q - (uintptr_t)p, "%s.%s.",
482 	    FM_ERROR_CPU, cpuclass ? cpuclass : FM_EREPORT_CPU_GENERIC);
483 
484 	p += strlen(p);
485 	if (p >= q)
486 		return;
487 
488 	if (leafclass == NULL) {
489 		gcpu_mn_fmt(fmt, p, (uintptr_t)q - (uintptr_t)p, status,
490 		    GCPU_MN_NAMESPACE_EREPORT);
491 	} else {
492 		(void) snprintf(p, (uintptr_t)q - (uintptr_t)p, "%s",
493 		    leafclass);
494 	}
495 }
496 
497 /*
498  * Create an "hc" scheme FMRI identifying the given cpu with
499  * motherboard/chip/core/strand instance numbers.
500  */
501 static nvlist_t *
502 gcpu_fmri_create(cmi_hdl_t hdl, nv_alloc_t *nva)
503 {
504 	nvlist_t *nvl;
505 
506 	if ((nvl = fm_nvlist_create(nva)) == NULL)
507 		return (NULL);
508 
509 	fm_fmri_hc_set(nvl, FM_HC_SCHEME_VERSION, NULL, NULL, 4,
510 	    "motherboard", 0,
511 	    "chip", cmi_hdl_chipid(hdl),
512 	    "core", cmi_hdl_coreid(hdl),
513 	    "strand", cmi_hdl_strandid(hdl));
514 
515 	return (nvl);
516 }
517 
518 int gcpu_bleat_count_thresh = 5;
519 hrtime_t gcpu_bleat_min_interval = 10 * 1000000000ULL;
520 
521 /*
522  * Called when we are unable to propogate a logout structure onto an
523  * errorq for subsequent ereport preparation and logging etc.  The caller
524  * should usually only decide to call this for severe errors - those we
525  * suspect we may need to panic for.
526  */
527 static void
528 gcpu_bleat(cmi_hdl_t hdl, gcpu_logout_t *gcl)
529 {
530 	hrtime_t now  = gethrtime_waitfree();
531 	static hrtime_t gcpu_last_bleat;
532 	gcpu_bank_logout_t *gbl;
533 	static int bleatcount;
534 	int i;
535 
536 	/*
537 	 * Throttle spamming of the console.  The first gcpu_bleat_count_thresh
538 	 * can come as fast as we like, but once we've spammed that many
539 	 * to the console we require a minimum interval to pass before
540 	 * any more complaints.
541 	 */
542 	if (++bleatcount > gcpu_bleat_count_thresh) {
543 		if (now - gcpu_last_bleat < gcpu_bleat_min_interval)
544 			return;
545 		else
546 			bleatcount = 0;
547 	}
548 	gcpu_last_bleat = now;
549 
550 	cmn_err(CE_WARN,
551 	    "Machine-Check Errors unlogged on chip %d core %d strand %d, "
552 	    "raw dump follows", cmi_hdl_chipid(hdl), cmi_hdl_coreid(hdl),
553 	    cmi_hdl_strandid(hdl));
554 	cmn_err(CE_WARN, "MCG_STATUS 0x%016llx",
555 	    (u_longlong_t)gcl->gcl_mcg_status);
556 	for (i = 0, gbl = &gcl->gcl_data[0]; i < gcl->gcl_nbanks; i++, gbl++) {
557 		uint64_t status = gbl->gbl_status;
558 
559 		if (!(status & MSR_MC_STATUS_VAL))
560 			continue;
561 
562 		switch (status & (MSR_MC_STATUS_ADDRV | MSR_MC_STATUS_MISCV)) {
563 		case MSR_MC_STATUS_ADDRV | MSR_MC_STATUS_MISCV:
564 			cmn_err(CE_WARN, "Bank %d (offset 0x%llx) "
565 			    "STAT 0x%016llx ADDR 0x%016llx MISC 0x%016llx",
566 			    i, IA32_MSR_MC(i, STATUS),
567 			    (u_longlong_t)status,
568 			    (u_longlong_t)gbl->gbl_addr,
569 			    (u_longlong_t)gbl->gbl_misc);
570 			break;
571 
572 		case MSR_MC_STATUS_ADDRV:
573 			cmn_err(CE_WARN, "Bank %d (offset 0x%llx) "
574 			    "STAT 0x%016llx ADDR 0x%016llx",
575 			    i, IA32_MSR_MC(i, STATUS),
576 			    (u_longlong_t)status,
577 			    (u_longlong_t)gbl->gbl_addr);
578 			break;
579 
580 		case MSR_MC_STATUS_MISCV:
581 			cmn_err(CE_WARN, "Bank %d (offset 0x%llx) "
582 			    "STAT 0x%016llx MISC 0x%016llx",
583 			    i, IA32_MSR_MC(i, STATUS),
584 			    (u_longlong_t)status,
585 			    (u_longlong_t)gbl->gbl_misc);
586 			break;
587 
588 		default:
589 			cmn_err(CE_WARN, "Bank %d (offset 0x%llx) "
590 			    "STAT 0x%016llx",
591 			    i, IA32_MSR_MC(i, STATUS),
592 			    (u_longlong_t)status);
593 			break;
594 
595 		}
596 	}
597 }
598 
599 #define	_GCPU_BSTATUS(status, what) \
600 	FM_EREPORT_PAYLOAD_NAME_MC_STATUS_##what, DATA_TYPE_BOOLEAN_VALUE, \
601 	(status) & MSR_MC_STATUS_##what ? B_TRUE : B_FALSE
602 
603 static void
604 gcpu_ereport_add_logout(nvlist_t *ereport, const gcpu_logout_t *gcl,
605     uint_t bankno, const gcpu_error_disp_t *ged, uint16_t code)
606 {
607 	uint64_t members = ged ? ged->ged_ereport_members :
608 	    FM_EREPORT_PAYLOAD_FLAGS_COMMON;
609 	uint64_t mcg = gcl->gcl_mcg_status;
610 	int mcip = mcg & MCG_STATUS_MCIP;
611 	const gcpu_bank_logout_t *gbl = &gcl->gcl_data[bankno];
612 	uint64_t bstat = gbl->gbl_status;
613 
614 	/*
615 	 * Include the compound error name if requested and if this
616 	 * is a compound error type.
617 	 */
618 	if (members & FM_EREPORT_PAYLOAD_FLAG_COMPOUND_ERR && ged &&
619 	    ged->ged_compound_fmt != NULL) {
620 		char buf[FM_MAX_CLASS];
621 
622 		gcpu_mn_fmt(ged->ged_compound_fmt, buf, sizeof (buf), code,
623 		    GCPU_MN_NAMESPACE_COMPOUND);
624 		fm_payload_set(ereport, FM_EREPORT_PAYLOAD_NAME_COMPOUND_ERR,
625 		    DATA_TYPE_STRING, buf, NULL);
626 	}
627 
628 	/*
629 	 * Include disposition information for this error
630 	 */
631 	if (members & FM_EREPORT_PAYLOAD_FLAG_DISP &&
632 	    gbl->gbl_disp != 0) {
633 		int i, empty = 1;
634 		char buf[128];
635 		char *p = buf, *q = buf + 128;
636 		static struct _gcpu_disp_name {
637 			uint64_t dv;
638 			const char *dn;
639 		} disp_names[] = {
640 			{ CMI_ERRDISP_CURCTXBAD,
641 			    "processor_context_corrupt" },
642 			{ CMI_ERRDISP_RIPV_INVALID,
643 			    "return_ip_invalid" },
644 			{ CMI_ERRDISP_UC_UNCONSTRAINED,
645 			    "unconstrained" },
646 			{ CMI_ERRDISP_FORCEFATAL,
647 			    "forcefatal" },
648 			{ CMI_ERRDISP_IGNORED,
649 			    "ignored" },
650 			{ CMI_ERRDISP_PCC_CLEARED,
651 			    "corrupt_context_cleared" },
652 			{ CMI_ERRDISP_UC_CLEARED,
653 			    "uncorrected_data_cleared" },
654 			{ CMI_ERRDISP_POISONED,
655 			    "poisoned" },
656 			{ CMI_ERRDISP_INCONSISTENT,
657 			    "telemetry_unstable" },
658 		};
659 
660 		for (i = 0; i < sizeof (disp_names) /
661 		    sizeof (struct _gcpu_disp_name); i++) {
662 			if ((gbl->gbl_disp & disp_names[i].dv) == 0)
663 				continue;
664 
665 			(void) snprintf(p, (uintptr_t)q - (uintptr_t)p,
666 			    "%s%s", empty ? "" : ",", disp_names[i].dn);
667 			p += strlen(p);
668 			empty = 0;
669 		}
670 
671 		if (p != buf)
672 			fm_payload_set(ereport, FM_EREPORT_PAYLOAD_NAME_DISP,
673 			    DATA_TYPE_STRING, buf, NULL);
674 	}
675 
676 	/*
677 	 * If MCG_STATUS is included add that and an indication of whether
678 	 * this ereport was the result of a machine check or poll.
679 	 */
680 	if (members & FM_EREPORT_PAYLOAD_FLAG_MCG_STATUS) {
681 		fm_payload_set(ereport, FM_EREPORT_PAYLOAD_NAME_MCG_STATUS,
682 		    DATA_TYPE_UINT64, mcg, NULL);
683 
684 		fm_payload_set(ereport, FM_EREPORT_PAYLOAD_NAME_MCG_STATUS_MCIP,
685 		    DATA_TYPE_BOOLEAN_VALUE, mcip ? B_TRUE : B_FALSE, NULL);
686 	}
687 
688 	/*
689 	 * If an instruction pointer is to be included add one provided
690 	 * MCG_STATUS indicated it is valid; meaningless for polled events.
691 	 */
692 	if (mcip && members & FM_EREPORT_PAYLOAD_FLAG_IP &&
693 	    mcg & MCG_STATUS_EIPV) {
694 		fm_payload_set(ereport, FM_EREPORT_PAYLOAD_NAME_IP,
695 		    DATA_TYPE_UINT64, gcl->gcl_ip, NULL);
696 	}
697 
698 	/*
699 	 * Add an indication of whether the trap occured during privileged code.
700 	 */
701 	if (mcip && members & FM_EREPORT_PAYLOAD_FLAG_PRIV) {
702 		fm_payload_set(ereport, FM_EREPORT_PAYLOAD_NAME_PRIV,
703 		    DATA_TYPE_BOOLEAN_VALUE,
704 		    gcl->gcl_flags & GCPU_GCL_F_PRIV ? B_TRUE : B_FALSE, NULL);
705 	}
706 
707 	/*
708 	 * If requested, add the index of the MCA bank.  This indicates the
709 	 * n'th bank of 4 MCA registers, and does not necessarily correspond
710 	 * to MCi_* - use the bank offset to correlate
711 	 */
712 	if (members & FM_EREPORT_PAYLOAD_FLAG_BANK_NUM) {
713 		fm_payload_set(ereport,
714 		    /* Bank number */
715 		    FM_EREPORT_PAYLOAD_NAME_BANK_NUM, DATA_TYPE_UINT8, bankno,
716 		    /* Offset of MCi_CTL */
717 		    FM_EREPORT_PAYLOAD_NAME_BANK_MSR_OFFSET, DATA_TYPE_UINT64,
718 		    IA32_MSR_MC(bankno, CTL),
719 		    NULL);
720 	}
721 
722 	/*
723 	 * Add MCi_STATUS if requested, and decode it.
724 	 */
725 	if (members & FM_EREPORT_PAYLOAD_FLAG_MC_STATUS) {
726 		const char *tbes[] = {
727 			"No tracking",			/* 00 */
728 			"Green - below threshold",	/* 01 */
729 			"Yellow - above threshold",	/* 10 */
730 			"Reserved"			/* 11 */
731 		};
732 
733 		fm_payload_set(ereport,
734 		    /* Bank MCi_STATUS */
735 		    FM_EREPORT_PAYLOAD_NAME_MC_STATUS, DATA_TYPE_UINT64, bstat,
736 		    /* Overflow? */
737 		    _GCPU_BSTATUS(bstat, OVER),
738 		    /* Uncorrected? */
739 		    _GCPU_BSTATUS(bstat, UC),
740 		    /* Enabled? */
741 		    _GCPU_BSTATUS(bstat, EN),
742 		    /* Processor context corrupt? */
743 		    _GCPU_BSTATUS(bstat, PCC),
744 		    /* Error code */
745 		    FM_EREPORT_PAYLOAD_NAME_MC_STATUS_ERRCODE,
746 		    DATA_TYPE_UINT16, MCAX86_ERRCODE(bstat),
747 		    /* Model-specific error code */
748 		    FM_EREPORT_PAYLOAD_NAME_MC_STATUS_EXTERRCODE,
749 		    DATA_TYPE_UINT16, MCAX86_MSERRCODE(bstat),
750 		    NULL);
751 
752 		/*
753 		 * If MCG_CAP.TES_P indicates that that thresholding info
754 		 * is present in the architural component of the bank status
755 		 * then include threshold information for this bank.
756 		 */
757 		if (gcl->gcl_flags & GCPU_GCL_F_TES_P) {
758 			fm_payload_set(ereport,
759 			    FM_EREPORT_PAYLOAD_NAME_MC_STATUS_TES,
760 			    DATA_TYPE_STRING, tbes[MCAX86_TBES_VALUE(bstat)],
761 			    NULL);
762 		}
763 	}
764 
765 	/*
766 	 * MCi_ADDR info if requested and valid.
767 	 */
768 	if (members & FM_EREPORT_PAYLOAD_FLAG_MC_ADDR &&
769 	    bstat & MSR_MC_STATUS_ADDRV) {
770 		fm_payload_set(ereport, FM_EREPORT_PAYLOAD_NAME_MC_ADDR,
771 		    DATA_TYPE_UINT64, gbl->gbl_addr, NULL);
772 	}
773 
774 	/*
775 	 * MCi_MISC if requested and MCi_STATUS.MISCV).
776 	 */
777 	if (members & FM_EREPORT_PAYLOAD_FLAG_MC_MISC &&
778 	    bstat & MSR_MC_STATUS_MISCV) {
779 		fm_payload_set(ereport, FM_EREPORT_PAYLOAD_NAME_MC_MISC,
780 		    DATA_TYPE_UINT64, gbl->gbl_misc, NULL);
781 	}
782 
783 }
784 
785 /*
786  * Construct and post an ereport based on the logout information from a
787  * single MCA bank.  We are not necessarily running on the cpu that
788  * detected the error.
789  */
790 static void
791 gcpu_ereport_post(const gcpu_logout_t *gcl, int bankidx,
792     const gcpu_error_disp_t *ged, cms_cookie_t mscookie, uint64_t status)
793 {
794 	gcpu_data_t *gcpu = gcl->gcl_gcpu;
795 	cmi_hdl_t hdl = gcpu->gcpu_hdl;
796 	const gcpu_bank_logout_t *gbl = &gcl->gcl_data[bankidx];
797 	const char *cpuclass = NULL, *leafclass = NULL;
798 	uint16_t code = MCAX86_ERRCODE(status);
799 	errorq_elem_t *eqep, *scr_eqep;
800 	nvlist_t *ereport, *detector;
801 	char buf[FM_MAX_CLASS];
802 	const char *classfmt;
803 	nv_alloc_t *nva;
804 
805 	if (panicstr) {
806 		if ((eqep = errorq_reserve(ereport_errorq)) == NULL)
807 			return;
808 		ereport = errorq_elem_nvl(ereport_errorq, eqep);
809 
810 		/*
811 		 * Allocate another element for scratch space, but fallback
812 		 * to the one we have if that fails.  We'd like to use the
813 		 * additional scratch space for nvlist construction.
814 		 */
815 		if ((scr_eqep = errorq_reserve(ereport_errorq)) != NULL)
816 			nva = errorq_elem_nva(ereport_errorq, scr_eqep);
817 		else
818 			nva = errorq_elem_nva(ereport_errorq, eqep);
819 	} else {
820 		ereport = fm_nvlist_create(NULL);
821 		nva = NULL;
822 	}
823 
824 	if (ereport == NULL)
825 		return;
826 
827 	/*
828 	 * Common payload data required by the protocol:
829 	 *	- ereport class
830 	 *	- detector
831 	 *	- ENA
832 	 */
833 
834 	/*
835 	 * Ereport class - call into model-specific support to allow it to
836 	 * provide a cpu class or leaf class, otherwise calculate our own.
837 	 */
838 	cms_ereport_class(hdl, mscookie, &cpuclass, &leafclass);
839 	classfmt = ged ?  ged->ged_class_fmt : FM_EREPORT_CPU_GENERIC_UNKNOWN;
840 	gcpu_erpt_clsfmt(classfmt, buf, sizeof (buf), status, cpuclass,
841 	    leafclass);
842 
843 	/*
844 	 * The detector FMRI.
845 	 */
846 	if ((detector = cms_ereport_detector(hdl, mscookie, nva)) == NULL)
847 		detector = gcpu_fmri_create(hdl, nva);
848 
849 	/*
850 	 * Should we define a new ENA format 3?? for chip/core/strand?
851 	 * It will be better when virtualized.
852 	 */
853 	fm_ereport_set(ereport, FM_EREPORT_VERSION, buf,
854 	    fm_ena_generate_cpu(gcl->gcl_timestamp,
855 	    cmi_hdl_chipid(hdl) << 6 | cmi_hdl_coreid(hdl) << 3 |
856 	    cmi_hdl_strandid(hdl), FM_ENA_FMT1), detector, NULL);
857 
858 	if (panicstr) {
859 		fm_nvlist_destroy(detector, FM_NVA_RETAIN);
860 		nv_alloc_reset(nva);
861 	} else {
862 		fm_nvlist_destroy(detector, FM_NVA_FREE);
863 	}
864 
865 	/*
866 	 * Add the architectural ereport class-specific payload data.
867 	 */
868 	gcpu_ereport_add_logout(ereport, gcl, bankidx, ged, code);
869 
870 	/*
871 	 * Allow model-specific code to add ereport members.
872 	 */
873 	cms_ereport_add_logout(hdl, ereport, nva, bankidx, gbl->gbl_status,
874 	    gbl->gbl_addr, gbl->gbl_misc, gcl->gcl_ms_logout, mscookie);
875 
876 	/*
877 	 * Include stack if options is turned on and either selected in
878 	 * the payload member bitmask or inclusion is forced.
879 	 */
880 	if (gcpu_mca_stack_flag &&
881 	    (cms_ereport_includestack(hdl, mscookie) ==
882 	    B_TRUE || gcpu_mca_stack_ereport_include)) {
883 		fm_payload_stack_add(ereport, gcl->gcl_stack,
884 		    gcl->gcl_stackdepth);
885 	}
886 
887 	/*
888 	 * If injection has taken place anytime in the past then note this
889 	 * on the ereport.
890 	 */
891 	if (cmi_inj_tainted() == B_TRUE) {
892 		fm_payload_set(ereport, "__injected", DATA_TYPE_BOOLEAN_VALUE,
893 		    B_TRUE, NULL);
894 	}
895 
896 	/*
897 	 * Post ereport.
898 	 */
899 	if (panicstr) {
900 		errorq_commit(ereport_errorq, eqep, ERRORQ_SYNC);
901 		if (scr_eqep)
902 			errorq_cancel(ereport_errorq, scr_eqep);
903 	} else {
904 		(void) fm_ereport_post(ereport, EVCH_TRYHARD);
905 		fm_nvlist_destroy(ereport, FM_NVA_FREE);
906 	}
907 
908 }
909 
910 /*ARGSUSED*/
911 void
912 gcpu_mca_drain(void *ignored, const void *data, const errorq_elem_t *eqe)
913 {
914 	const gcpu_logout_t *gcl = data;
915 	const gcpu_bank_logout_t *gbl;
916 	int i;
917 
918 	for (i = 0, gbl = &gcl->gcl_data[0]; i < gcl->gcl_nbanks; i++, gbl++) {
919 		const gcpu_error_disp_t *gened;
920 		cms_cookie_t mscookie;
921 
922 		if (gbl->gbl_status & MSR_MC_STATUS_VAL &&
923 		    !(gbl->gbl_disp & CMI_ERRDISP_INCONSISTENT)) {
924 			uint16_t code = MCAX86_ERRCODE(gbl->gbl_status);
925 
926 			/*
927 			 * Perform a match based on IA32 MCA architectural
928 			 * components alone.
929 			 */
930 			gened = gcpu_disp_match(code); /* may be NULL */
931 
932 			/*
933 			 * Now see if an model-specific match can be made.
934 			 */
935 			mscookie = cms_disp_match(gcl->gcl_gcpu->gcpu_hdl, i,
936 			    gbl->gbl_status, gbl->gbl_addr, gbl->gbl_misc,
937 			    gcl->gcl_ms_logout);
938 
939 			/*
940 			 * Prepare and dispatch an ereport for logging and
941 			 * diagnosis.
942 			 */
943 			gcpu_ereport_post(gcl, i, gened, mscookie,
944 			    gbl->gbl_status);
945 		} else if (gbl->gbl_status & MSR_MC_STATUS_VAL &&
946 		    (gbl->gbl_disp & CMI_ERRDISP_INCONSISTENT)) {
947 			/*
948 			 * Telemetry kept changing as we tried to read
949 			 * it.  Force an unknown ereport leafclass but
950 			 * keep the telemetry unchanged for logging.
951 			 */
952 			gcpu_ereport_post(gcl, i, &gcpu_unknown, NULL,
953 			    gbl->gbl_status);
954 		}
955 	}
956 }
957 
958 static size_t gcpu_mca_queue_datasz = 0;
959 
960 /*
961  * The following code is ready to make a weak attempt at growing the
962  * errorq structure size.  Since it is not foolproof (we don't know
963  * who may already be producing to the outgoing errorq) our caller
964  * instead assures that we'll always be called with no greater data
965  * size than on our first call.
966  */
967 static void
968 gcpu_errorq_init(size_t datasz)
969 {
970 	int slots;
971 
972 	mutex_enter(&gcpu_mca_queue_lock);
973 
974 	if (gcpu_mca_queue_datasz >= datasz) {
975 		mutex_exit(&gcpu_mca_queue_lock);
976 		return;
977 	}
978 
979 	membar_producer();
980 	if (gcpu_mca_queue) {
981 		gcpu_mca_queue_datasz = 0;
982 		errorq_destroy(gcpu_mca_queue);
983 	}
984 
985 	slots = MAX(GCPU_MCA_ERRS_PERCPU * max_ncpus, GCPU_MCA_MIN_ERRORS);
986 	slots = MIN(slots, GCPU_MCA_MAX_ERRORS);
987 
988 	gcpu_mca_queue = errorq_create("gcpu_mca_queue", gcpu_mca_drain,
989 	    NULL, slots, datasz, 1, ERRORQ_VITAL);
990 
991 	if (gcpu_mca_queue != NULL)
992 		gcpu_mca_queue_datasz = datasz;
993 
994 	mutex_exit(&gcpu_mca_queue_lock);
995 }
996 
997 /*
998  * Perform MCA initialization as described in section 14.6 of Intel 64
999  * and IA-32 Architectures Software Developer's Manual Volume 3A.
1000  */
1001 
1002 static uint_t global_nbanks;
1003 
1004 void
1005 gcpu_mca_init(cmi_hdl_t hdl)
1006 {
1007 	gcpu_data_t *gcpu = cmi_hdl_getcmidata(hdl);
1008 	uint64_t cap;
1009 	uint_t vendor = cmi_hdl_vendor(hdl);
1010 	uint_t family = cmi_hdl_family(hdl);
1011 	gcpu_mca_t *mca = &gcpu->gcpu_mca;
1012 	int mcg_ctl_present;
1013 	uint_t nbanks;
1014 	uint32_t ctl_skip_mask = 0;
1015 	uint32_t status_skip_mask = 0;
1016 	size_t mslsz;
1017 	int i;
1018 #ifndef __xpv
1019 	int mcg_ctl2_present;
1020 	uint32_t cmci_capable = 0;
1021 #endif
1022 
1023 	if (gcpu == NULL)
1024 		return;
1025 
1026 	/*
1027 	 * Protect from some silly /etc/system settings.
1028 	 */
1029 	if (gcpu_mca_telemetry_retries < 0 || gcpu_mca_telemetry_retries > 100)
1030 		gcpu_mca_telemetry_retries = 5;
1031 
1032 	if (cmi_hdl_rdmsr(hdl, IA32_MSR_MCG_CAP, &cap) != CMI_SUCCESS)
1033 		return;
1034 
1035 	/*
1036 	 * CPU startup code only calls cmi_mca_init if x86_feature indicates
1037 	 * both MCA and MCE support (i.e., X86_MCA).  P5, K6, and earlier
1038 	 * processors, which have their own * more primitive way of doing
1039 	 * machine checks, will not have cmi_mca_init called since their
1040 	 * CPUID information will not indicate both MCA and MCE features.
1041 	 */
1042 	ASSERT(x86_feature & X86_MCA);
1043 
1044 	/*
1045 	 * Determine whether the IA32_MCG_CTL register is present.  If it
1046 	 * is we will enable all features by writing -1 to it towards
1047 	 * the end of this initialization;  if it is absent then volume 3A
1048 	 * says we must nonetheless continue to initialize the individual
1049 	 * banks.
1050 	 */
1051 	mcg_ctl_present = cap & MCG_CAP_CTL_P;
1052 #ifndef __xpv
1053 	mcg_ctl2_present = cap & MCG_CAP_CTL2_P;
1054 #endif
1055 
1056 	/*
1057 	 * We squirell values away for inspection/debugging.
1058 	 */
1059 	mca->gcpu_mca_bioscfg.bios_mcg_cap = cap;
1060 	if (mcg_ctl_present)
1061 		(void) cmi_hdl_rdmsr(hdl, IA32_MSR_MCG_CTL,
1062 		    &mca->gcpu_mca_bioscfg.bios_mcg_ctl);
1063 
1064 	/*
1065 	 * Determine the number of error-reporting banks implemented.
1066 	 */
1067 	mca->gcpu_mca_nbanks = nbanks = cap & MCG_CAP_COUNT_MASK;
1068 
1069 	if (nbanks != 0 && global_nbanks == 0)
1070 		global_nbanks = nbanks;	/* no race - BSP will get here first */
1071 
1072 	/*
1073 	 * If someone is hiding the number of banks (perhaps we are fully
1074 	 * virtualized?) or if this processor has more banks than the
1075 	 * first to set global_nbanks then bail.  The latter requirement
1076 	 * is because we need to size our errorq data structure and we
1077 	 * don't want to have to grow the errorq (destroy and recreate)
1078 	 * which may just lose some telemetry.
1079 	 */
1080 	if (nbanks == 0 || nbanks > global_nbanks)
1081 		return;
1082 
1083 	mca->gcpu_mca_bioscfg.bios_bankcfg = kmem_zalloc(nbanks *
1084 	    sizeof (struct gcpu_bios_bankcfg), KM_SLEEP);
1085 
1086 	/*
1087 	 * Calculate the size we need to allocate for a gcpu_logout_t
1088 	 * with a gcl_data array big enough for all banks of this cpu.
1089 	 * Add any space requested by the model-specific logout support.
1090 	 */
1091 	mslsz = cms_logout_size(hdl);
1092 	mca->gcpu_mca_lgsz = sizeof (gcpu_logout_t) +
1093 	    (nbanks - 1) * sizeof (gcpu_bank_logout_t) + mslsz;
1094 
1095 	for (i = 0; i < GCPU_MCA_LOGOUT_NUM; i++) {
1096 		gcpu_logout_t *gcl;
1097 
1098 		mca->gcpu_mca_logout[i] = gcl =
1099 		    kmem_zalloc(mca->gcpu_mca_lgsz, KM_SLEEP);
1100 		gcl->gcl_gcpu = gcpu;
1101 		gcl->gcl_nbanks = nbanks;
1102 		gcl->gcl_ms_logout = (mslsz == 0) ? NULL :
1103 		    (char *)(&gcl->gcl_data[0]) + nbanks *
1104 		    sizeof (gcpu_bank_logout_t);
1105 
1106 	}
1107 
1108 #ifdef __xpv
1109 	gcpu_xpv_mca_init(nbanks);
1110 #endif
1111 
1112 	mca->gcpu_mca_nextpoll_idx = GCPU_MCA_LOGOUT_POLLER_1;
1113 
1114 #ifndef __xpv
1115 	mca->gcpu_bank_cmci = kmem_zalloc(sizeof (gcpu_mca_cmci_t) * nbanks,
1116 	    KM_SLEEP);
1117 #endif
1118 
1119 	/*
1120 	 * Create our errorq to transport the logout structures.  This
1121 	 * can fail so users of gcpu_mca_queue must be prepared for NULL.
1122 	 */
1123 	gcpu_errorq_init(mca->gcpu_mca_lgsz);
1124 
1125 	/*
1126 	 * Not knowing which, if any, banks are shared between cores we
1127 	 * assure serialization of MCA bank initialization by each cpu
1128 	 * on the chip.  On chip architectures in which some banks are
1129 	 * shared this will mean the shared resource is initialized more
1130 	 * than once - we're simply aiming to avoid simultaneous MSR writes
1131 	 * to the shared resource.
1132 	 *
1133 	 * Even with these precautions, some platforms may yield a GP fault
1134 	 * if a core other than a designated master tries to write anything
1135 	 * but all 0's to MCi_{STATUS,ADDR,CTL}.  So we will perform
1136 	 * those writes under on_trap protection.
1137 	 */
1138 	mutex_enter(&gcpu->gcpu_shared->gcpus_cfglock);
1139 
1140 	/*
1141 	 * Initialize poller data, but don't start polling yet.
1142 	 */
1143 	gcpu_mca_poll_init(hdl);
1144 
1145 	/*
1146 	 * Work out which MCA banks we will initialize.  In MCA logout
1147 	 * code we will only read those banks which we initialize here.
1148 	 */
1149 	for (i = 0; i < nbanks; i++) {
1150 		boolean_t skipctl = cms_bankctl_skipinit(hdl, i);
1151 		boolean_t skipstatus = cms_bankstatus_skipinit(hdl, i);
1152 
1153 		if (!cms_present(hdl)) {
1154 			/*
1155 			 * Model-specific support is not present, try to use
1156 			 * sane defaults.
1157 			 *
1158 			 * On AMD family 6 processors, reports about spurious
1159 			 * machine checks indicate that bank 0 should be
1160 			 * skipped.
1161 			 *
1162 			 * On Intel family 6 processors, the documentation tells
1163 			 * us not to write to MC0_CTL.
1164 			 *
1165 			 */
1166 			if (i == 0 && family == 6) {
1167 				switch (vendor) {
1168 				case X86_VENDOR_AMD:
1169 					skipstatus = B_TRUE;
1170 					/*FALLTHRU*/
1171 				case X86_VENDOR_Intel:
1172 					skipctl = B_TRUE;
1173 					break;
1174 				}
1175 			}
1176 		}
1177 
1178 		ctl_skip_mask |= skipctl << i;
1179 		status_skip_mask |= skipstatus << i;
1180 
1181 		if (skipctl && skipstatus)
1182 			continue;
1183 
1184 		/*
1185 		 * Record which MCA banks were enabled, from the point of view
1186 		 * of the whole chip (if some cores share a bank we must be
1187 		 * sure either can logout from it).
1188 		 */
1189 		atomic_or_32(&gcpu->gcpu_shared->gcpus_actv_banks, 1 << i);
1190 
1191 #ifndef __xpv
1192 		/*
1193 		 * check CMCI capability
1194 		 */
1195 		if (mcg_ctl2_present) {
1196 			uint64_t ctl2;
1197 			uint32_t cap = 0;
1198 			(void) cmi_hdl_rdmsr(hdl, IA32_MSR_MC_CTL2(i), &ctl2);
1199 			if (ctl2 & MSR_MC_CTL2_EN)
1200 				continue;
1201 			ctl2 |= MSR_MC_CTL2_EN;
1202 			(void) cmi_hdl_wrmsr(hdl, IA32_MSR_MC_CTL2(i), ctl2);
1203 			(void) cmi_hdl_rdmsr(hdl, IA32_MSR_MC_CTL2(i), &ctl2);
1204 			mca->gcpu_bank_cmci[i].cmci_cap = cap =
1205 			    (ctl2 & MSR_MC_CTL2_EN) ? 1 : 0;
1206 			if (cap)
1207 				cmci_capable ++;
1208 			/*
1209 			 * Set threshold to 1 while unset the en field, to avoid
1210 			 * CMCI trigged before APIC LVT entry init.
1211 			 */
1212 			ctl2 = ctl2 & (~MSR_MC_CTL2_EN) | 1;
1213 			(void) cmi_hdl_wrmsr(hdl, IA32_MSR_MC_CTL2(i), ctl2);
1214 
1215 			/*
1216 			 * init cmci related count
1217 			 */
1218 			mca->gcpu_bank_cmci[i].cmci_enabled = 0;
1219 			mca->gcpu_bank_cmci[i].drtcmci = 0;
1220 			mca->gcpu_bank_cmci[i].ncmci = 0;
1221 		}
1222 #endif
1223 	}
1224 
1225 #ifndef __xpv
1226 	if (cmci_capable)
1227 		cmi_enable_cmci = 1;
1228 #endif
1229 
1230 #ifndef __xpv
1231 	/*
1232 	 * Log any valid telemetry lurking in the MCA banks, but do not
1233 	 * clear the status registers.  Ignore the disposition returned -
1234 	 * we have already paniced or reset for any nasty errors found here.
1235 	 *
1236 	 * Intel vol 3A says that we should not do this on family 0x6,
1237 	 * and that for any extended family the BIOS clears things
1238 	 * on power-on reset so you'll only potentially find valid telemetry
1239 	 * on warm reset (we do it for both - on power-on reset we should
1240 	 * just see zeroes).
1241 	 *
1242 	 * AMD docs since K7 say we should process anything we find here.
1243 	 */
1244 	if (!gcpu_suppress_log_on_init &&
1245 	    (vendor == X86_VENDOR_Intel && family >= 0xf ||
1246 	    vendor == X86_VENDOR_AMD))
1247 		gcpu_mca_logout(hdl, NULL, -1ULL, NULL, B_FALSE,
1248 		    GCPU_MPT_WHAT_POKE_ERR);
1249 
1250 	/*
1251 	 * Initialize all MCi_CTL and clear all MCi_STATUS, allowing the
1252 	 * model-specific module the power of veto.
1253 	 */
1254 	for (i = 0; i < nbanks; i++) {
1255 		struct gcpu_bios_bankcfg *bcfgp =
1256 		    mca->gcpu_mca_bioscfg.bios_bankcfg + i;
1257 
1258 		/*
1259 		 * Stash inherited bank MCA state, even for banks we will
1260 		 * not initialize ourselves.  Do not read the MISC register
1261 		 * unconditionally - on some processors that will #GP on
1262 		 * banks that do not implement the MISC register (would be
1263 		 * caught by on_trap, anyway).
1264 		 */
1265 		(void) cmi_hdl_rdmsr(hdl, IA32_MSR_MC(i, CTL),
1266 		    &bcfgp->bios_bank_ctl);
1267 
1268 		(void) cmi_hdl_rdmsr(hdl, IA32_MSR_MC(i, STATUS),
1269 		    &bcfgp->bios_bank_status);
1270 
1271 		if (bcfgp->bios_bank_status & MSR_MC_STATUS_ADDRV)
1272 			(void) cmi_hdl_rdmsr(hdl, IA32_MSR_MC(i, ADDR),
1273 			    &bcfgp->bios_bank_addr);
1274 
1275 		/*
1276 		 * In some old BIOS the status value after boot can indicate
1277 		 * MISCV when there is actually no MISC register for
1278 		 * that bank.  The following read could therefore
1279 		 * aggravate a general protection fault.  This should be
1280 		 * caught by on_trap, but the #GP fault handler is busted
1281 		 * and can suffer a double fault even before we get to
1282 		 * trap() to check for on_trap protection.  Until that
1283 		 * issue is fixed we remove the one access that we know
1284 		 * can cause a #GP.
1285 		 *
1286 		 * if (bcfgp->bios_bank_status & MSR_MC_STATUS_MISCV)
1287 		 *	(void) cmi_hdl_rdmsr(hdl, IA32_MSR_MC(i, MISC),
1288 		 *	    &bcfgp->bios_bank_misc);
1289 		 */
1290 		bcfgp->bios_bank_misc = 0;
1291 
1292 		if (!(ctl_skip_mask & (1 << i))) {
1293 			(void) cmi_hdl_wrmsr(hdl, IA32_MSR_MC(i, CTL),
1294 			    cms_bankctl_val(hdl, i, -1ULL));
1295 		}
1296 
1297 		if (!(status_skip_mask & (1 << i))) {
1298 			(void) cmi_hdl_wrmsr(hdl, IA32_MSR_MC(i, STATUS),
1299 			    cms_bankstatus_val(hdl, i, 0ULL));
1300 		}
1301 	}
1302 #endif
1303 	/*
1304 	 * Now let the model-specific support perform further initialization
1305 	 * of non-architectural features.
1306 	 */
1307 	cms_mca_init(hdl, nbanks);
1308 
1309 #ifndef __xpv
1310 	(void) cmi_hdl_wrmsr(hdl, IA32_MSR_MCG_STATUS, 0ULL);
1311 	membar_producer();
1312 
1313 	/* enable all machine-check features */
1314 	if (mcg_ctl_present)
1315 		(void) cmi_hdl_wrmsr(hdl, IA32_MSR_MCG_CTL,
1316 		    cms_mcgctl_val(hdl, nbanks, -1ULL));
1317 #endif
1318 
1319 	mutex_exit(&gcpu->gcpu_shared->gcpus_cfglock);
1320 
1321 #ifndef __xpv
1322 	/* enable machine-check exception in CR4 */
1323 	cmi_hdl_enable_mce(hdl);
1324 #endif
1325 }
1326 
1327 static uint64_t
1328 gcpu_mca_process(cmi_hdl_t hdl, struct regs *rp, int nerr, gcpu_data_t *gcpu,
1329     gcpu_logout_t *gcl, int ismc, gcpu_mce_status_t *mcesp)
1330 {
1331 	int curctxbad = 0, unconstrained = 0, forcefatal = 0;
1332 	gcpu_mca_t *mca = &gcpu->gcpu_mca;
1333 	int nbanks = mca->gcpu_mca_nbanks;
1334 	gcpu_mce_status_t mce;
1335 	gcpu_bank_logout_t *gbl;
1336 	uint64_t disp = 0;
1337 	int i;
1338 
1339 	if (mcesp == NULL)
1340 		mcesp = &mce;
1341 
1342 	mcesp->mce_nerr = nerr;
1343 
1344 	mcesp->mce_npcc = mcesp->mce_npcc_ok = mcesp->mce_nuc =
1345 	    mcesp->mce_nuc_ok = mcesp->mce_nuc_poisoned =
1346 	    mcesp->mce_forcefatal = mcesp->mce_ignored = 0;
1347 
1348 	/*
1349 	 * If this a machine check then if the return instruction pointer
1350 	 * is not valid the current context is lost.
1351 	 */
1352 	if (ismc && !(gcl->gcl_mcg_status & MCG_STATUS_RIPV))
1353 		disp |= CMI_ERRDISP_RIPV_INVALID;
1354 
1355 	for (i = 0, gbl = &gcl->gcl_data[0]; i < nbanks; i++, gbl++) {
1356 		uint64_t mcistatus = gbl->gbl_status;
1357 		uint32_t ms_scope;
1358 		int pcc, uc;
1359 		int poisoned;
1360 
1361 		if (!(mcistatus & MSR_MC_STATUS_VAL))
1362 			continue;
1363 
1364 		if (gbl->gbl_disp & CMI_ERRDISP_INCONSISTENT)
1365 			continue;
1366 
1367 		pcc = (mcistatus & MSR_MC_STATUS_PCC) != 0;
1368 		uc = (mcistatus & MSR_MC_STATUS_UC) != 0;
1369 		mcesp->mce_npcc += pcc;
1370 		mcesp->mce_nuc += uc;
1371 
1372 		ms_scope = cms_error_action(hdl, ismc, i, mcistatus,
1373 		    gbl->gbl_addr, gbl->gbl_misc, gcl->gcl_ms_logout);
1374 
1375 		if (pcc && ms_scope & CMS_ERRSCOPE_CURCONTEXT_OK) {
1376 			pcc = 0;
1377 			mcesp->mce_npcc_ok++;
1378 			gbl->gbl_disp |= CMI_ERRDISP_PCC_CLEARED;
1379 		}
1380 
1381 		if (uc && ms_scope & CMS_ERRSCOPE_CLEARED_UC) {
1382 			uc = 0;
1383 			mcesp->mce_nuc_ok++;
1384 			gbl->gbl_disp |= CMI_ERRDISP_UC_CLEARED;
1385 		}
1386 
1387 		if (uc) {
1388 			poisoned = (ms_scope & CMS_ERRSCOPE_POISONED) != 0;
1389 			if (poisoned) {
1390 				mcesp->mce_nuc_poisoned++;
1391 				gbl->gbl_disp |= CMI_ERRDISP_POISONED;
1392 			}
1393 		}
1394 
1395 		if ((ms_scope & CMS_ERRSCOPE_IGNORE_ERR) == 0) {
1396 			/*
1397 			 * We're not being instructed to ignore the error,
1398 			 * so apply our standard disposition logic to it.
1399 			 */
1400 			if (uc && !poisoned) {
1401 				unconstrained++;
1402 				gbl->gbl_disp |= disp |
1403 				    CMI_ERRDISP_UC_UNCONSTRAINED;
1404 			}
1405 
1406 			if (pcc && ismc) {
1407 				curctxbad++;
1408 				gbl->gbl_disp |= disp |
1409 				    CMI_ERRDISP_CURCTXBAD;
1410 			}
1411 
1412 			/*
1413 			 * Even if the above may not indicate that the error
1414 			 * is terminal, model-specific support may insist
1415 			 * that we treat it as such.  Such errors wil be
1416 			 * fatal even if discovered via poll.
1417 			 */
1418 			if (ms_scope & CMS_ERRSCOPE_FORCE_FATAL) {
1419 				forcefatal++;
1420 				mcesp->mce_forcefatal++;
1421 				gbl->gbl_disp |= disp |
1422 				    CMI_ERRDISP_FORCEFATAL;
1423 			}
1424 		} else {
1425 			mcesp->mce_ignored++;
1426 			gbl->gbl_disp |= disp | CMI_ERRDISP_IGNORED;
1427 		}
1428 	}
1429 
1430 	if (unconstrained > 0)
1431 		disp |= CMI_ERRDISP_UC_UNCONSTRAINED;
1432 
1433 	if (curctxbad > 0)
1434 		disp |= CMI_ERRDISP_CURCTXBAD;
1435 
1436 	if (forcefatal > 0)
1437 		disp |= CMI_ERRDISP_FORCEFATAL;
1438 
1439 	if (gcpu_mca_queue != NULL) {
1440 		int how;
1441 
1442 		if (ismc) {
1443 			how = cmi_mce_response(rp, disp) ?
1444 			    ERRORQ_ASYNC :	/* no panic, so arrange drain */
1445 			    ERRORQ_SYNC;	/* panic flow will drain */
1446 		} else {
1447 			how = (disp & CMI_ERRDISP_FORCEFATAL &&
1448 			    cmi_panic_on_ue()) ?
1449 			    ERRORQ_SYNC :	/* poller will panic */
1450 			    ERRORQ_ASYNC;	/* no panic */
1451 		}
1452 
1453 		errorq_dispatch(gcpu_mca_queue, gcl, mca->gcpu_mca_lgsz, how);
1454 	} else if (disp != 0) {
1455 		gcpu_bleat(hdl, gcl);
1456 	}
1457 
1458 	mcesp->mce_disp = disp;
1459 
1460 	return (disp);
1461 }
1462 
1463 /*
1464  * Gather error telemetry from our source, and then submit it for
1465  * processing.
1466  */
1467 
1468 #define	IS_MCE_CANDIDATE(status) (((status) & MSR_MC_STATUS_EN) != 0 && \
1469 	((status) & (MSR_MC_STATUS_UC | MSR_MC_STATUS_PCC)) != 0)
1470 
1471 #define	STATUS_EQV(s1, s2) \
1472 	(((s1) & ~MSR_MC_STATUS_OVER) == ((s2) & ~MSR_MC_STATUS_OVER))
1473 
1474 static uint32_t gcpu_deferrred_polled_clears;
1475 
1476 #ifndef __xpv
1477 static void
1478 gcpu_cmci_logout(cmi_hdl_t hdl, int bank, gcpu_mca_cmci_t *bank_cmci_p,
1479     uint64_t status, int what)
1480 {
1481 	uint64_t ctl2;
1482 
1483 	if (bank_cmci_p->cmci_cap && (what == GCPU_MPT_WHAT_CYC_ERR) &&
1484 	    (!(status & MSR_MC_STATUS_VAL) || ((status & MSR_MC_STATUS_VAL) &&
1485 	    !(status & MSR_MC_STATUS_CEC_MASK)))) {
1486 
1487 		if (!(bank_cmci_p->cmci_enabled)) {
1488 			/*
1489 			 * when cmci is disabled, and the bank has no error or
1490 			 * no corrected error for
1491 			 * gcpu_mca_cmci_reenable_threshold consecutive polls,
1492 			 * turn on this bank's cmci.
1493 			 */
1494 
1495 			bank_cmci_p->drtcmci ++;
1496 
1497 			if (bank_cmci_p->drtcmci >=
1498 			    gcpu_mca_cmci_reenable_threshold) {
1499 
1500 				/* turn on cmci */
1501 
1502 				(void) cmi_hdl_rdmsr(hdl,
1503 				    IA32_MSR_MC_CTL2(bank), &ctl2);
1504 				ctl2 |= MSR_MC_CTL2_EN;
1505 				(void) cmi_hdl_wrmsr(hdl,
1506 				    IA32_MSR_MC_CTL2(bank), ctl2);
1507 
1508 				/* reset counter and set flag */
1509 				bank_cmci_p->drtcmci = 0;
1510 				bank_cmci_p->cmci_enabled = 1;
1511 			}
1512 		} else {
1513 			/*
1514 			 * when cmci is enabled,if is in cyclic poll and the
1515 			 * bank has no error or no corrected error, reset ncmci
1516 			 * counter
1517 			 */
1518 			bank_cmci_p->ncmci = 0;
1519 		}
1520 	}
1521 }
1522 
1523 static void
1524 gcpu_cmci_throttle(cmi_hdl_t hdl, int bank, gcpu_mca_cmci_t *bank_cmci_p,
1525     int what)
1526 {
1527 	uint64_t ctl2 = 0;
1528 
1529 	/*
1530 	 * if cmci of this bank occurred beyond
1531 	 * gcpu_mca_cmci_throttling_threshold between 2 polls,
1532 	 * turn off this bank's CMCI;
1533 	 */
1534 	if (bank_cmci_p->cmci_enabled && what == GCPU_MPT_WHAT_CMCI_ERR) {
1535 
1536 		/* if it is cmci trap, increase the count */
1537 		bank_cmci_p->ncmci++;
1538 
1539 		if (bank_cmci_p->ncmci >= gcpu_mca_cmci_throttling_threshold) {
1540 
1541 			/* turn off cmci */
1542 
1543 			(void) cmi_hdl_rdmsr(hdl, IA32_MSR_MC_CTL2(bank),
1544 			    &ctl2);
1545 			ctl2 &= ~MSR_MC_CTL2_EN;
1546 			(void) cmi_hdl_wrmsr(hdl, IA32_MSR_MC_CTL2(bank),
1547 			    ctl2);
1548 
1549 			/* clear the flag and count */
1550 
1551 			bank_cmci_p->cmci_enabled = 0;
1552 			bank_cmci_p->ncmci = 0;
1553 		}
1554 	}
1555 }
1556 #endif
1557 
1558 static void
1559 clear_mc(int first, int last, int ismc, boolean_t clrstatus,
1560     cmi_hdl_t hdl, gcpu_logout_t *gcl, gcpu_logout_t *pgcl)
1561 {
1562 	int i;
1563 	gcpu_bank_logout_t *gbl, *pgbl;
1564 	uint64_t status;
1565 
1566 	for (i = first, gbl = &gcl->gcl_data[first]; i < last; i++, gbl++) {
1567 		status = gbl->gbl_status;
1568 		if (status == 0)
1569 			continue;
1570 		if (clrstatus == B_FALSE)
1571 			goto serialize;
1572 
1573 		/*
1574 		 * For i86xpv we always clear status in order to invalidate
1575 		 * the interposed telemetry.
1576 		 *
1577 		 * For native machine checks we always clear status here.  For
1578 		 * native polls we must be a little more cautious since there
1579 		 * is an outside chance that we may clear telemetry from a
1580 		 * shared MCA bank on which a sibling core is machine checking.
1581 		 *
1582 		 * For polled observations of errors that look like they may
1583 		 * produce a machine check (UC/PCC and ENabled, although these
1584 		 * do not guarantee a machine check on error occurence)
1585 		 * we will not clear the status at this wakeup unless
1586 		 * we saw the same status at the previous poll.	 We will
1587 		 * always process and log the current observations - it
1588 		 * is only the clearing of MCi_STATUS which may be
1589 		 * deferred until the next wakeup.
1590 		 */
1591 		if (isxpv || ismc || !IS_MCE_CANDIDATE(status)) {
1592 			(void) cmi_hdl_wrmsr(hdl, IA32_MSR_MC(i, STATUS), 0ULL);
1593 			goto serialize;
1594 		}
1595 
1596 		/*
1597 		 * We have a polled observation of a machine check
1598 		 * candidate.  If we saw essentially the same status at the
1599 		 * last poll then clear the status now since this appears
1600 		 * not to be a #MC candidate after all.	 If we see quite
1601 		 * different status now then do not clear, but reconsider at
1602 		 * the next poll.  In no actual machine check clears
1603 		 * the status in the interim then the status should not
1604 		 * keep changing forever (meaning we'd never clear it)
1605 		 * since before long we'll simply have latched the highest-
1606 		 * priority error and set the OVerflow bit.  Nonetheless
1607 		 * we count how many times we defer clearing and after
1608 		 * a while insist on clearing the status.
1609 		 */
1610 		pgbl = &pgcl->gcl_data[i];
1611 		if (pgbl->gbl_clrdefcnt != 0) {
1612 			/* We deferred clear on this bank at last wakeup */
1613 			if (STATUS_EQV(status, pgcl->gcl_data[i].gbl_status) ||
1614 			    pgbl->gbl_clrdefcnt > 5) {
1615 				/*
1616 				 * Status is unchanged so clear it now and,
1617 				 * since we have already logged this info,
1618 				 * avoid logging it again.
1619 				 */
1620 				gbl->gbl_status = 0;
1621 				(void) cmi_hdl_wrmsr(hdl,
1622 				    IA32_MSR_MC(i, STATUS), 0ULL);
1623 			} else {
1624 				/* Record deferral for next wakeup */
1625 				gbl->gbl_clrdefcnt = pgbl->gbl_clrdefcnt + 1;
1626 			}
1627 		} else {
1628 			/* Record initial deferral for next wakeup */
1629 			gbl->gbl_clrdefcnt = 1;
1630 			gcpu_deferrred_polled_clears++;
1631 		}
1632 
1633 serialize:
1634 		{
1635 #ifdef __xpv
1636 			;
1637 #else
1638 			/*
1639 			 * Intel Vol 3A says to execute a serializing
1640 			 * instruction here, ie CPUID.	Well WRMSR is also
1641 			 * defined to be serializing, so the status clear above
1642 			 * should suffice.  To be a good citizen, and since
1643 			 * some clears are deferred, we'll execute a CPUID
1644 			 * instruction here.
1645 			 */
1646 			struct cpuid_regs tmp;
1647 			(void) __cpuid_insn(&tmp);
1648 #endif
1649 		}
1650 	}
1651 }
1652 
1653 /*ARGSUSED5*/
1654 void
1655 gcpu_mca_logout(cmi_hdl_t hdl, struct regs *rp, uint64_t bankmask,
1656     gcpu_mce_status_t *mcesp, boolean_t clrstatus, int what)
1657 {
1658 	gcpu_data_t *gcpu = cmi_hdl_getcmidata(hdl);
1659 	gcpu_mca_t *mca = &gcpu->gcpu_mca;
1660 	int nbanks = mca->gcpu_mca_nbanks;
1661 	gcpu_bank_logout_t *gbl;
1662 	gcpu_logout_t *gcl, *pgcl;
1663 	int ismc = (rp != NULL);
1664 	int ispoll = !ismc;
1665 	int i, nerr = 0;
1666 	cmi_errno_t err;
1667 	uint64_t mcg_status;
1668 	uint64_t disp;
1669 	uint64_t cap;
1670 	int first = 0;
1671 	int last = 0;
1672 	int willpanic = 0;
1673 
1674 	if (cmi_hdl_rdmsr(hdl, IA32_MSR_MCG_STATUS, &mcg_status) !=
1675 	    CMI_SUCCESS || cmi_hdl_rdmsr(hdl, IA32_MSR_MCG_CAP, &cap) !=
1676 	    CMI_SUCCESS) {
1677 		if (mcesp != NULL)
1678 			mcesp->mce_nerr = mcesp->mce_disp = 0;
1679 		return;
1680 	}
1681 
1682 	if (ismc) {
1683 		gcl = mca->gcpu_mca_logout[GCPU_MCA_LOGOUT_EXCEPTION];
1684 	} else {
1685 		int pidx = mca->gcpu_mca_nextpoll_idx;
1686 		int ppidx = (pidx == GCPU_MCA_LOGOUT_POLLER_1) ?
1687 		    GCPU_MCA_LOGOUT_POLLER_2 : GCPU_MCA_LOGOUT_POLLER_1;
1688 
1689 		gcl = mca->gcpu_mca_logout[pidx];	/* current logout */
1690 		pgcl = mca->gcpu_mca_logout[ppidx];	/* previous logout */
1691 		mca->gcpu_mca_nextpoll_idx = ppidx;	/* switch next time */
1692 	}
1693 
1694 	gcl->gcl_timestamp = gethrtime_waitfree();
1695 	gcl->gcl_mcg_status = mcg_status;
1696 	gcl->gcl_ip = rp ? rp->r_pc : 0;
1697 
1698 	gcl->gcl_flags = (rp && USERMODE(rp->r_cs)) ? GCPU_GCL_F_PRIV : 0;
1699 	if (cap & MCG_CAP_TES_P)
1700 		gcl->gcl_flags |= GCPU_GCL_F_TES_P;
1701 
1702 	for (i = 0, gbl = &gcl->gcl_data[0]; i < nbanks; i++, gbl++) {
1703 		uint64_t status, status2, addr, misc;
1704 		int retries = gcpu_mca_telemetry_retries;
1705 
1706 		gbl->gbl_status = 0;
1707 		gbl->gbl_disp = 0;
1708 		gbl->gbl_clrdefcnt = 0;
1709 
1710 		/*
1711 		 * Only logout from MCA banks we have initialized from at
1712 		 * least one core.  If a core shares an MCA bank with another
1713 		 * but perhaps lost the race to initialize it, then it must
1714 		 * still be allowed to logout from the shared bank.
1715 		 */
1716 		if (!(gcpu->gcpu_shared->gcpus_actv_banks & 1 << i))
1717 			continue;
1718 
1719 		/*
1720 		 * On a poll look only at the banks we've been asked to check.
1721 		 */
1722 		if (rp == NULL && !(bankmask & 1 << i))
1723 			continue;
1724 
1725 
1726 		if (cmi_hdl_rdmsr(hdl, IA32_MSR_MC(i, STATUS), &status) !=
1727 		    CMI_SUCCESS)
1728 			continue;
1729 
1730 #ifndef __xpv
1731 		gcpu_cmci_logout(hdl, i, &mca->gcpu_bank_cmci[i], status, what);
1732 #endif
1733 
1734 retry:
1735 		if (!(status & MSR_MC_STATUS_VAL))
1736 			continue;
1737 
1738 		if (first == 0)
1739 			first = i;
1740 		last = i;
1741 
1742 		addr = -1;
1743 		misc = 0;
1744 
1745 		if (status & MSR_MC_STATUS_ADDRV)
1746 			(void) cmi_hdl_rdmsr(hdl, IA32_MSR_MC(i, ADDR), &addr);
1747 
1748 		if (status & MSR_MC_STATUS_MISCV)
1749 			(void) cmi_hdl_rdmsr(hdl, IA32_MSR_MC(i, MISC), &misc);
1750 
1751 #ifndef __xpv
1752 		gcpu_cmci_throttle(hdl, i, &mca->gcpu_bank_cmci[i], what);
1753 #endif
1754 
1755 		/*
1756 		 * Allow the model-specific code to extract bank telemetry.
1757 		 */
1758 		cms_bank_logout(hdl, i, status, addr, misc, gcl->gcl_ms_logout);
1759 
1760 		/*
1761 		 * Not all cpu models assure us that the status/address/misc
1762 		 * data will not change during the above sequence of MSR reads,
1763 		 * or that it can only change by the addition of the OVerflow
1764 		 * bit to the status register.  If the status has changed
1765 		 * other than in the overflow bit then we attempt to reread
1766 		 * for a consistent snapshot, but eventually give up and
1767 		 * go with what we've got.  We only perform this check
1768 		 * for a poll - a further #MC during a #MC will reset, and
1769 		 * polled errors should not overwrite higher-priority
1770 		 * trapping errors (but could set the overflow bit).
1771 		 */
1772 		if (ispoll && (err = cmi_hdl_rdmsr(hdl, IA32_MSR_MC(i, STATUS),
1773 		    &status2)) == CMI_SUCCESS) {
1774 			if (!STATUS_EQV(status, status2)) {
1775 				if (retries-- > 0) {
1776 					status = status2;
1777 					goto retry;
1778 				} else {
1779 					gbl->gbl_disp |=
1780 					    CMI_ERRDISP_INCONSISTENT;
1781 				}
1782 			}
1783 		} else if (ispoll && err != CMI_SUCCESS) {
1784 			gbl->gbl_disp |= CMI_ERRDISP_INCONSISTENT;
1785 		}
1786 
1787 		nerr++;
1788 		gbl->gbl_status = status;
1789 		gbl->gbl_addr = addr;
1790 		gbl->gbl_misc = misc;
1791 	}
1792 
1793 	if (gcpu_mca_stack_flag)
1794 		gcl->gcl_stackdepth = getpcstack(gcl->gcl_stack, FM_STK_DEPTH);
1795 	else
1796 		gcl->gcl_stackdepth = 0;
1797 
1798 	/*
1799 	 * Decide our disposition for this error or errors, and submit for
1800 	 * logging and subsequent diagnosis.
1801 	 */
1802 	if (nerr != 0) {
1803 		disp = gcpu_mca_process(hdl, rp, nerr, gcpu, gcl, ismc, mcesp);
1804 
1805 		willpanic = (ismc && cmi_mce_response(rp, disp) == 0);
1806 
1807 		if (!willpanic)
1808 			clear_mc(first, last, ismc, clrstatus, hdl, gcl, pgcl);
1809 	} else {
1810 		disp = 0;
1811 		if (mcesp) {
1812 			mcesp->mce_nerr = mcesp->mce_disp = 0;
1813 		}
1814 	}
1815 
1816 	/*
1817 	 * Clear MCG_STATUS if MCIP is set (machine check in progress).
1818 	 * If a second #MC had occured before now the system would have
1819 	 * reset.  We can only do thise once gcpu_mca_process has copied
1820 	 * the logout structure.
1821 	 */
1822 	if (ismc && mcg_status & MCG_STATUS_MCIP)
1823 		(void) cmi_hdl_wrmsr(hdl, IA32_MSR_MCG_STATUS, 0);
1824 
1825 	/*
1826 	 * At this point we have read and logged all telemetry that is visible
1827 	 * under the MCA.  On architectures for which the NorthBridge is
1828 	 * on-chip this may include NB-observed errors, but where the NB
1829 	 * is off chip it may have been the source of the #MC request and
1830 	 * so we must call into the memory-controller driver to give it
1831 	 * a chance to log errors.
1832 	 */
1833 	if (ismc) {
1834 		cmi_mc_logout(hdl, 1, willpanic);
1835 	}
1836 }
1837 
1838 #ifndef __xpv
1839 int gcpu_mca_trap_vomit_summary = 0;
1840 
1841 /*
1842  * On a native machine check exception we come here from mcetrap via
1843  * cmi_mca_trap.  A machine check on one cpu of a chip does not trap others
1844  * cpus of the chip, so it is possible that another cpu on this chip could
1845  * initiate a poll while we're in the #mc handler;  it is also possible that
1846  * this trap has occured during a poll on this cpu.  So we must acquire
1847  * the chip-wide poll lock, but be careful to avoid deadlock.
1848  *
1849  * The 'data' pointer cannot be NULL due to init order.
1850  */
1851 uint64_t
1852 gcpu_mca_trap(cmi_hdl_t hdl, struct regs *rp)
1853 {
1854 	gcpu_data_t *gcpu = cmi_hdl_getcmidata(hdl);
1855 	kmutex_t *poll_lock = NULL;
1856 	gcpu_mce_status_t mce;
1857 	uint64_t mcg_status;
1858 	int tooklock = 0;
1859 
1860 	if (cmi_hdl_rdmsr(hdl, IA32_MSR_MCG_STATUS, &mcg_status) !=
1861 	    CMI_SUCCESS || !(mcg_status & MCG_STATUS_MCIP))
1862 		return (0);
1863 
1864 	/*
1865 	 * Synchronize with any poller from another core that may happen
1866 	 * to share access to one or more of the MCA banks.
1867 	 */
1868 	if (gcpu->gcpu_shared != NULL)
1869 		poll_lock = &gcpu->gcpu_shared->gcpus_poll_lock;
1870 
1871 	if (poll_lock != NULL && !mutex_owned(poll_lock)) {
1872 		/*
1873 		 * The lock is not owned by the thread we have
1874 		 * interrupted.  Spin for this adaptive lock.
1875 		 */
1876 		while (!mutex_tryenter(poll_lock)) {
1877 			while (mutex_owner(poll_lock) != NULL)
1878 				;
1879 		}
1880 		tooklock = 1;
1881 	}
1882 
1883 	gcpu_mca_logout(hdl, rp, 0, &mce, B_TRUE, GCPU_MPT_WHAT_MC_ERR);
1884 
1885 	if (tooklock)
1886 		mutex_exit(poll_lock);
1887 
1888 	/*
1889 	 * gcpu_mca_trap_vomit_summary may be set for debug assistance.
1890 	 */
1891 	if (mce.mce_nerr != 0 && gcpu_mca_trap_vomit_summary) {
1892 		cmn_err(CE_WARN, "MCE: %u errors, disp=0x%llx, "
1893 		    "%u PCC (%u ok), "
1894 		    "%u UC (%d ok, %u poisoned), "
1895 		    "%u forcefatal, %u ignored",
1896 		    mce.mce_nerr, (u_longlong_t)mce.mce_disp,
1897 		    mce.mce_npcc, mce.mce_npcc_ok,
1898 		    mce.mce_nuc, mce.mce_nuc_ok, mce.mce_nuc_poisoned,
1899 		    mce.mce_forcefatal, mce.mce_ignored);
1900 	}
1901 
1902 	return (mce.mce_disp);
1903 }
1904 #endif
1905 
1906 /*ARGSUSED*/
1907 void
1908 gcpu_faulted_enter(cmi_hdl_t hdl)
1909 {
1910 	/* Nothing to do here */
1911 }
1912 
1913 /*ARGSUSED*/
1914 void
1915 gcpu_faulted_exit(cmi_hdl_t hdl)
1916 {
1917 	gcpu_data_t *gcpu = cmi_hdl_getcmidata(hdl);
1918 
1919 	gcpu->gcpu_mca.gcpu_mca_flags |= GCPU_MCA_F_UNFAULTING;
1920 }
1921 
1922 /*
1923  * Write the requested values to the indicated MSRs.  Having no knowledge
1924  * of the model-specific requirements for writing to these model-specific
1925  * registers, we will only blindly write to those MSRs if the 'force'
1926  * argument is nonzero.  That option should only be used in prototyping
1927  * and debugging.
1928  */
1929 /*ARGSUSED*/
1930 cmi_errno_t
1931 gcpu_msrinject(cmi_hdl_t hdl, cmi_mca_regs_t *regs, uint_t nregs,
1932     int force)
1933 {
1934 	int i, errs = 0;
1935 
1936 	for (i = 0; i < nregs; i++) {
1937 		uint_t msr = regs[i].cmr_msrnum;
1938 		uint64_t val = regs[i].cmr_msrval;
1939 
1940 		if (cms_present(hdl)) {
1941 			if (cms_msrinject(hdl, msr, val) != CMS_SUCCESS)
1942 				errs++;
1943 		} else if (force) {
1944 			errs += (cmi_hdl_wrmsr(hdl, msr, val) != CMI_SUCCESS);
1945 		} else {
1946 			errs++;
1947 		}
1948 	}
1949 
1950 	return (errs == 0 ? CMI_SUCCESS : CMIERR_UNKNOWN);
1951 }
1952