Home | History | Annotate | Line # | Download | only in acpi
apei.c revision 1.5
      1 /*	$NetBSD: apei.c,v 1.5 2024/10/27 12:13:42 riastradh Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2024 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  *
     16  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     17  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     18  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     19  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     20  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     26  * POSSIBILITY OF SUCH DAMAGE.
     27  */
     28 
     29 /*
     30  * APEI: ACPI Platform Error Interface
     31  *
     32  * https://uefi.org/specs/ACPI/6.5/18_Platform_Error_Interfaces.html
     33  *
     34  * XXX dtrace probes
     35  *
     36  * XXX call _OSC appropriately to announce to the platform that we, the
     37  * OSPM, support APEI
     38  */
     39 
     40 #include <sys/cdefs.h>
     41 __KERNEL_RCSID(0, "$NetBSD: apei.c,v 1.5 2024/10/27 12:13:42 riastradh Exp $");
     42 
     43 #include <sys/param.h>
     44 #include <sys/types.h>
     45 
     46 #include <sys/atomic.h>
     47 #include <sys/device.h>
     48 #include <sys/module.h>
     49 #include <sys/sysctl.h>
     50 #include <sys/uuid.h>
     51 
     52 #include <dev/acpi/acpireg.h>
     53 #include <dev/acpi/acpivar.h>
     54 #include <dev/acpi/apei_bertvar.h>
     55 #include <dev/acpi/apei_cper.h>
     56 #include <dev/acpi/apei_einjvar.h>
     57 #include <dev/acpi/apei_erstvar.h>
     58 #include <dev/acpi/apei_hestvar.h>
     59 #include <dev/acpi/apei_interp.h>
     60 #include <dev/acpi/apeivar.h>
     61 
     62 #define	_COMPONENT	ACPI_RESOURCE_COMPONENT
     63 ACPI_MODULE_NAME	("apei")
     64 
     65 static int apei_match(device_t, cfdata_t, void *);
     66 static void apei_attach(device_t, device_t, void *);
     67 static int apei_detach(device_t, int);
     68 
     69 static void apei_get_tables(struct apei_tab *);
     70 static void apei_put_tables(struct apei_tab *);
     71 
     72 static void apei_identify(struct apei_softc *, const char *,
     73     const ACPI_TABLE_HEADER *);
     74 
     75 CFATTACH_DECL_NEW(apei, sizeof(struct apei_softc),
     76     apei_match, apei_attach, apei_detach, NULL);
     77 
     78 static int
     79 apei_match(device_t parent, cfdata_t match, void *aux)
     80 {
     81 	struct apei_tab tab;
     82 	int prio = 0;
     83 
     84 	/*
     85 	 * If we have any of the APEI tables, match.
     86 	 */
     87 	apei_get_tables(&tab);
     88 	if (tab.bert || tab.einj || tab.erst || tab.hest)
     89 		prio = 1;
     90 	apei_put_tables(&tab);
     91 
     92 	return prio;
     93 }
     94 
     95 static void
     96 apei_attach(device_t parent, device_t self, void *aux)
     97 {
     98 	struct apei_softc *sc = device_private(self);
     99 	const struct sysctlnode *sysctl_hw_acpi;
    100 	int error;
    101 
    102 	aprint_naive("\n");
    103 	aprint_normal(": ACPI Platform Error Interface\n");
    104 
    105 	pmf_device_register(self, NULL, NULL);
    106 
    107 	sc->sc_dev = self;
    108 	apei_get_tables(&sc->sc_tab);
    109 
    110 	/*
    111 	 * Get the sysctl hw.acpi node.  This should already be created
    112 	 * but I don't see an easy way to get at it.  If this fails,
    113 	 * something is seriously wrong, so let's stop here.
    114 	 */
    115 	error = sysctl_createv(&sc->sc_sysctllog, 0,
    116 	    NULL, &sysctl_hw_acpi, 0,
    117 	    CTLTYPE_NODE, "acpi", NULL, NULL, 0, NULL, 0,
    118 	    CTL_HW, CTL_CREATE, CTL_EOL);
    119 	if (error) {
    120 		aprint_error_dev(sc->sc_dev,
    121 		    "failed to create sysctl hw.acpi: %d\n", error);
    122 		return;
    123 	}
    124 
    125 	/*
    126 	 * Create sysctl hw.acpi.apei.
    127 	 */
    128 	error = sysctl_createv(&sc->sc_sysctllog, 0,
    129 	    &sysctl_hw_acpi, &sc->sc_sysctlroot, 0,
    130 	    CTLTYPE_NODE, "apei",
    131 	    SYSCTL_DESCR("ACPI Platform Error Interface"),
    132 	    NULL, 0, NULL, 0,
    133 	    CTL_CREATE, CTL_EOL);
    134 	if (error) {
    135 		aprint_error_dev(sc->sc_dev,
    136 		    "failed to create sysctl hw.acpi.apei: %d\n", error);
    137 		return;
    138 	}
    139 
    140 	/*
    141 	 * Set up BERT, EINJ, ERST, and HEST.
    142 	 */
    143 	if (sc->sc_tab.bert) {
    144 		apei_identify(sc, "BERT", &sc->sc_tab.bert->Header);
    145 		apei_bert_attach(sc);
    146 	}
    147 	if (sc->sc_tab.einj) {
    148 		apei_identify(sc, "EINJ", &sc->sc_tab.einj->Header);
    149 		apei_einj_attach(sc);
    150 	}
    151 	if (sc->sc_tab.erst) {
    152 		apei_identify(sc, "ERST", &sc->sc_tab.erst->Header);
    153 		apei_erst_attach(sc);
    154 	}
    155 	if (sc->sc_tab.hest) {
    156 		apei_identify(sc, "HEST", &sc->sc_tab.hest->Header);
    157 		apei_hest_attach(sc);
    158 	}
    159 }
    160 
    161 static int
    162 apei_detach(device_t self, int flags)
    163 {
    164 	struct apei_softc *sc = device_private(self);
    165 	int error;
    166 
    167 	/*
    168 	 * Detach children.  We don't currently have any but this is
    169 	 * harmless without children and mandatory if we ever sprouted
    170 	 * them, so let's just leave it here for good measure.
    171 	 *
    172 	 * After this point, we are committed to detaching; failure is
    173 	 * forbidden.
    174 	 */
    175 	error = config_detach_children(self, flags);
    176 	if (error)
    177 		return error;
    178 
    179 	/*
    180 	 * Tear down all the sysctl nodes first, before the software
    181 	 * state backing them goes away.
    182 	 */
    183 	sysctl_teardown(&sc->sc_sysctllog);
    184 	sc->sc_sysctlroot = NULL;
    185 
    186 	/*
    187 	 * Detach the software state for the APEI tables.
    188 	 */
    189 	if (sc->sc_tab.hest)
    190 		apei_hest_detach(sc);
    191 	if (sc->sc_tab.erst)
    192 		apei_erst_detach(sc);
    193 	if (sc->sc_tab.einj)
    194 		apei_einj_detach(sc);
    195 	if (sc->sc_tab.bert)
    196 		apei_bert_detach(sc);
    197 
    198 	/*
    199 	 * Release the APEI tables and we're done.
    200 	 */
    201 	apei_put_tables(&sc->sc_tab);
    202 	pmf_device_deregister(self);
    203 	return 0;
    204 }
    205 
    206 /*
    207  * apei_get_tables(tab)
    208  *
    209  *	Get references to whichever APEI-related tables -- BERT, EINJ,
    210  *	ERST, HEST -- are available in the system.
    211  */
    212 static void
    213 apei_get_tables(struct apei_tab *tab)
    214 {
    215 	ACPI_STATUS rv;
    216 
    217 	/*
    218 	 * Probe the BERT -- Boot Error Record Table.
    219 	 */
    220 	rv = AcpiGetTable(ACPI_SIG_BERT, 0, (ACPI_TABLE_HEADER **)&tab->bert);
    221 	if (ACPI_FAILURE(rv))
    222 		tab->bert = NULL;
    223 
    224 	/*
    225 	 * Probe the EINJ -- Error Injection Table.
    226 	 */
    227 	rv = AcpiGetTable(ACPI_SIG_EINJ, 0, (ACPI_TABLE_HEADER **)&tab->einj);
    228 	if (ACPI_FAILURE(rv))
    229 		tab->einj = NULL;
    230 
    231 	/*
    232 	 * Probe the ERST -- Error Record Serialization Table.
    233 	 */
    234 	rv = AcpiGetTable(ACPI_SIG_ERST, 0, (ACPI_TABLE_HEADER **)&tab->erst);
    235 	if (ACPI_FAILURE(rv))
    236 		tab->erst = NULL;
    237 
    238 	/*
    239 	 * Probe the HEST -- Hardware Error Source Table.
    240 	 */
    241 	rv = AcpiGetTable(ACPI_SIG_HEST, 0, (ACPI_TABLE_HEADER **)&tab->hest);
    242 	if (ACPI_FAILURE(rv))
    243 		tab->hest = NULL;
    244 }
    245 
    246 /*
    247  * apei_put_tables(tab)
    248  *
    249  *	Release the tables acquired by apei_get_tables.
    250  */
    251 static void
    252 apei_put_tables(struct apei_tab *tab)
    253 {
    254 
    255 	if (tab->bert != NULL) {
    256 		AcpiPutTable(&tab->bert->Header);
    257 		tab->bert = NULL;
    258 	}
    259 	if (tab->einj != NULL) {
    260 		AcpiPutTable(&tab->einj->Header);
    261 		tab->einj = NULL;
    262 	}
    263 	if (tab->erst != NULL) {
    264 		AcpiPutTable(&tab->erst->Header);
    265 		tab->erst = NULL;
    266 	}
    267 	if (tab->hest != NULL) {
    268 		AcpiPutTable(&tab->hest->Header);
    269 		tab->hest = NULL;
    270 	}
    271 }
    272 
    273 /*
    274  * apei_identify(sc, name, header)
    275  *
    276  *	Identify the APEI-related table header for dmesg.
    277  */
    278 static void
    279 apei_identify(struct apei_softc *sc, const char *name,
    280     const ACPI_TABLE_HEADER *h)
    281 {
    282 
    283 	aprint_normal_dev(sc->sc_dev, "%s:"
    284 	    " OemId <%6.6s,%8.8s,%08x>"
    285 	    " AslId <%4.4s,%08x>\n",
    286 	    name,
    287 	    h->OemId, h->OemTableId, h->OemRevision,
    288 	    h->AslCompilerId, h->AslCompilerRevision);
    289 }
    290 
    291 /*
    292  * apei_cper_guid_dec(buf, uuid)
    293  *
    294  *	Decode a Common Platform Error Record UUID/GUID from an ACPI
    295  *	table at buf into a sys/uuid.h struct uuid.
    296  */
    297 static void
    298 apei_cper_guid_dec(const uint8_t buf[static 16], struct uuid *uuid)
    299 {
    300 
    301 	uuid_dec_le(buf, uuid);
    302 }
    303 
    304 /*
    305  * apei_format_guid(uuid, s)
    306  *
    307  *	Format a UUID as a string.  This uses C initializer notation,
    308  *	not UUID notation, in order to match the text in the UEFI
    309  *	specification.
    310  */
    311 static void
    312 apei_format_guid(const struct uuid *uuid, char guidstr[static 69])
    313 {
    314 
    315 	snprintf(guidstr, 69, "{0x%08x,0x%04x,0x%04x,"
    316 	    "{0x%02x,%02x,"
    317 	    "0x%02x,0x%02x,0x%02x,0x%02x,0x%02x,0x%02x}}",
    318 	    uuid->time_low, uuid->time_mid, uuid->time_hi_and_version,
    319 	    uuid->clock_seq_hi_and_reserved, uuid->clock_seq_low,
    320 	    uuid->node[0], uuid->node[1], uuid->node[2],
    321 	    uuid->node[3], uuid->node[4], uuid->node[5]);
    322 }
    323 
    324 /*
    325  * https://uefi.org/specs/UEFI/2.10/Apx_N_Common_Platform_Error_Record.html#memory-error-section
    326  */
    327 
    328 static const char *const cper_memory_error_type[] = {
    329 #define	F(LN, SN, V)	[LN] = #SN,
    330 	CPER_MEMORY_ERROR_TYPES(F)
    331 #undef	F
    332 };
    333 
    334 /*
    335  * https://uefi.org/specs/ACPI/6.5/18_Platform_Error_Interfaces.html#generic-error-status-block
    336  *
    337  * The acpica names ACPI_HEST_GEN_ERROR_* appear to coincide with this
    338  * but are designated as being intended for Generic Error Data Entries
    339  * rather than Generic Error Status Blocks.
    340  */
    341 static const char *const apei_gesb_severity[] = {
    342 	[0] = "recoverable",
    343 	[1] = "fatal",
    344 	[2] = "corrected",
    345 	[3] = "none",
    346 };
    347 
    348 /*
    349  * https://uefi.org/specs/ACPI/6.5/18_Platform_Error_Interfaces.html#generic-error-data-entry
    350  */
    351 static const char *const apei_gede_severity[] = {
    352 	[ACPI_HEST_GEN_ERROR_RECOVERABLE] = "recoverable",
    353 	[ACPI_HEST_GEN_ERROR_FATAL] = "fatal",
    354 	[ACPI_HEST_GEN_ERROR_CORRECTED] = "corrected",
    355 	[ACPI_HEST_GEN_ERROR_NONE] = "none",
    356 };
    357 
    358 /*
    359  * https://uefi.org/specs/UEFI/2.10/Apx_N_Common_Platform_Error_Record.html#memory-error-section
    360  */
    361 static const struct uuid CPER_MEMORY_ERROR_SECTION =
    362     {0xa5bc1114,0x6f64,0x4ede,0xb8,0x63,{0x3e,0x83,0xed,0x7c,0x83,0xb1}};
    363 
    364 static void
    365 apei_cper_memory_error_report(struct apei_softc *sc, const void *buf,
    366     size_t len, const char *ctx, bool ratelimitok)
    367 {
    368 	const struct cper_memory_error *ME = buf;
    369 	char bitbuf[1024];
    370 
    371 	/*
    372 	 * If we've hit the rate limit, skip printing the error.
    373 	 */
    374 	if (!ratelimitok)
    375 		goto out;
    376 
    377 	snprintb(bitbuf, sizeof(bitbuf),
    378 	    CPER_MEMORY_ERROR_VALIDATION_BITS_FMT, ME->ValidationBits);
    379 	aprint_debug_dev(sc->sc_dev, "%s: ValidationBits=%s\n", ctx, bitbuf);
    380 	if (ME->ValidationBits & CPER_MEMORY_ERROR_VALID_ERROR_STATUS) {
    381 		/*
    382 		 * https://uefi.org/specs/UEFI/2.10/Apx_N_Common_Platform_Error_Record.html#error-status
    383 		 */
    384 		/* XXX define this format somewhere */
    385 		snprintb(bitbuf, sizeof(bitbuf), "\177\020"
    386 		    "f\010\010"	"ErrorType\0"
    387 			"=\001"		"ERR_INTERNAL\0"
    388 			"=\004"		"ERR_MEM\0"
    389 			"=\005"		"ERR_TLB\0"
    390 			"=\006"		"ERR_CACHE\0"
    391 			"=\007"		"ERR_FUNCTION\0"
    392 			"=\010"		"ERR_SELFTEST\0"
    393 			"=\011"		"ERR_FLOW\0"
    394 			"=\020"		"ERR_BUS\0"
    395 			"=\021"		"ERR_MAP\0"
    396 			"=\022"		"ERR_IMPROPER\0"
    397 			"=\023"		"ERR_UNIMPL\0"
    398 			"=\024"		"ERR_LOL\0"
    399 			"=\025"		"ERR_RESPONSE\0"
    400 			"=\026"		"ERR_PARITY\0"
    401 			"=\027"		"ERR_PROTOCOL\0"
    402 			"=\030"		"ERR_ERROR\0"
    403 			"=\031"		"ERR_TIMEOUT\0"
    404 			"=\032"		"ERR_POISONED\0"
    405 		    "b\020"	"AddressError\0"
    406 		    "b\021"	"ControlError\0"
    407 		    "b\022"	"DataError\0"
    408 		    "b\023"	"ResponderDetected\0"
    409 		    "b\024"	"RequesterDetected\0"
    410 		    "b\025"	"FirstError\0"
    411 		    "b\026"	"Overflow\0"
    412 		    "\0", ME->ErrorStatus);
    413 		device_printf(sc->sc_dev, "%s: ErrorStatus=%s\n", ctx, bitbuf);
    414 	}
    415 	if (ME->ValidationBits & CPER_MEMORY_ERROR_VALID_PHYSICAL_ADDRESS) {
    416 		device_printf(sc->sc_dev, "%s: PhysicalAddress=0x%"PRIx64"\n",
    417 		    ctx, ME->PhysicalAddress);
    418 	}
    419 	if (ME->ValidationBits &
    420 	    CPER_MEMORY_ERROR_VALID_PHYSICAL_ADDRESS_MASK) {
    421 		device_printf(sc->sc_dev, "%s: PhysicalAddressMask=0x%"PRIx64
    422 		    "\n", ctx, ME->PhysicalAddressMask);
    423 	}
    424 	if (ME->ValidationBits & CPER_MEMORY_ERROR_VALID_NODE) {
    425 		device_printf(sc->sc_dev, "%s: Node=0x%"PRIx16"\n", ctx,
    426 		    ME->Node);
    427 	}
    428 	if (ME->ValidationBits & CPER_MEMORY_ERROR_VALID_CARD) {
    429 		device_printf(sc->sc_dev, "%s: Card=0x%"PRIx16"\n", ctx,
    430 		    ME->Card);
    431 	}
    432 	if (ME->ValidationBits & CPER_MEMORY_ERROR_VALID_MODULE) {
    433 		device_printf(sc->sc_dev, "%s: Module=0x%"PRIx16"\n", ctx,
    434 		    ME->Module);
    435 	}
    436 	if (ME->ValidationBits & CPER_MEMORY_ERROR_VALID_BANK) {
    437 		device_printf(sc->sc_dev, "%s: Bank=0x%"PRIx16"\n", ctx,
    438 		    ME->Bank);
    439 	}
    440 	if (ME->ValidationBits & CPER_MEMORY_ERROR_VALID_DEVICE) {
    441 		device_printf(sc->sc_dev, "%s: Device=0x%"PRIx16"\n", ctx,
    442 		    ME->Device);
    443 	}
    444 	if (ME->ValidationBits & CPER_MEMORY_ERROR_VALID_ROW) {
    445 		device_printf(sc->sc_dev, "%s: Row=0x%"PRIx16"\n", ctx,
    446 		    ME->Row);
    447 	}
    448 	if (ME->ValidationBits & CPER_MEMORY_ERROR_VALID_COLUMN) {
    449 		device_printf(sc->sc_dev, "%s: Column=0x%"PRIx16"\n", ctx,
    450 		    ME->Column);
    451 	}
    452 	if (ME->ValidationBits & CPER_MEMORY_ERROR_VALID_BIT_POSITION) {
    453 		device_printf(sc->sc_dev, "%s: BitPosition=0x%"PRIx16"\n",
    454 		    ctx, ME->BitPosition);
    455 	}
    456 	if (ME->ValidationBits & CPER_MEMORY_ERROR_VALID_REQUESTOR_ID) {
    457 		device_printf(sc->sc_dev, "%s: RequestorId=0x%"PRIx64"\n",
    458 		    ctx, ME->RequestorId);
    459 	}
    460 	if (ME->ValidationBits & CPER_MEMORY_ERROR_VALID_RESPONDER_ID) {
    461 		device_printf(sc->sc_dev, "%s: ResponderId=0x%"PRIx64"\n",
    462 		    ctx, ME->ResponderId);
    463 	}
    464 	if (ME->ValidationBits & CPER_MEMORY_ERROR_VALID_TARGET_ID) {
    465 		device_printf(sc->sc_dev, "%s: TargetId=0x%"PRIx64"\n",
    466 		    ctx, ME->TargetId);
    467 	}
    468 	if (ME->ValidationBits & CPER_MEMORY_ERROR_VALID_MEMORY_ERROR_TYPE) {
    469 		const uint8_t t = ME->MemoryErrorType;
    470 		const char *n = t < __arraycount(cper_memory_error_type)
    471 		    ? cper_memory_error_type[t] : NULL;
    472 
    473 		if (n) {
    474 			device_printf(sc->sc_dev, "%s: MemoryErrorType=%d"
    475 			    " (%s)\n", ctx, t, n);
    476 		} else {
    477 			device_printf(sc->sc_dev, "%s: MemoryErrorType=%d\n",
    478 			    ctx, t);
    479 		}
    480 	}
    481 
    482 out:	/*
    483 	 * XXX pass this through to uvm(9) or userland for decisions
    484 	 * like page retirement
    485 	 */
    486 	return;
    487 }
    488 
    489 /*
    490  * apei_cper_reports
    491  *
    492  *	Table of known Common Platform Error Record types, symbolic
    493  *	names, minimum data lengths, and functions to report them.
    494  *
    495  *	The section types and corresponding section layouts are listed
    496  *	at:
    497  *
    498  *	https://uefi.org/specs/UEFI/2.10/Apx_N_Common_Platform_Error_Record.html
    499  */
    500 static const struct apei_cper_report {
    501 	const char *name;
    502 	const struct uuid *type;
    503 	size_t minlength;
    504 	void (*func)(struct apei_softc *, const void *, size_t, const char *,
    505 	    bool);
    506 } apei_cper_reports[] = {
    507 	{ "memory", &CPER_MEMORY_ERROR_SECTION,
    508 	  sizeof(struct cper_memory_error),
    509 	  apei_cper_memory_error_report },
    510 };
    511 
    512 /*
    513  * apei_gede_report_header(sc, gede, ctx, ratelimitok, &headerlen, &report)
    514  *
    515  *	Report the header of the ith Generic Error Data Entry in the
    516  *	given context, if ratelimitok is true.
    517  *
    518  *	Return the actual length of the header in headerlen, or 0 if
    519  *	not known because the revision isn't recognized.
    520  *
    521  *	Return the report type in report, or NULL if not known because
    522  *	the section type isn't recognized.
    523  */
    524 static void
    525 apei_gede_report_header(struct apei_softc *sc,
    526     const ACPI_HEST_GENERIC_DATA *gede, const char *ctx, bool ratelimitok,
    527     size_t *headerlenp, const struct apei_cper_report **reportp)
    528 {
    529 	const ACPI_HEST_GENERIC_DATA_V300 *const gede_v3 = (const void *)gede;
    530 	struct uuid sectype;
    531 	char guidstr[69];
    532 	char buf[128];
    533 	unsigned i;
    534 
    535 	/*
    536 	 * Print the section type as a C initializer.  It would be
    537 	 * prettier to use standard hyphenated UUID notation, but that
    538 	 * notation is slightly ambiguous here (two octets could be
    539 	 * written either way, depending on Microsoft convention --
    540 	 * which influenced ACPI and UEFI -- or internet convention),
    541 	 * and the UEFI spec writes the C initializer notation, so this
    542 	 * makes it easier to search for.
    543 	 *
    544 	 * Also print out a symbolic name, if we know it.
    545 	 */
    546 	apei_cper_guid_dec(gede->SectionType, &sectype);
    547 	apei_format_guid(&sectype, guidstr);
    548 	for (i = 0; i < __arraycount(apei_cper_reports); i++) {
    549 		const struct apei_cper_report *const report =
    550 		    &apei_cper_reports[i];
    551 
    552 		if (memcmp(&sectype, report->type, sizeof(sectype)) != 0)
    553 			continue;
    554 		if (ratelimitok) {
    555 			device_printf(sc->sc_dev, "%s:"
    556 			    " SectionType=%s (%s error)\n",
    557 			    ctx, guidstr, report->name);
    558 		}
    559 		*reportp = report;
    560 		break;
    561 	}
    562 	if (i == __arraycount(apei_cper_reports)) {
    563 		if (ratelimitok) {
    564 			device_printf(sc->sc_dev, "%s: SectionType=%s\n", ctx,
    565 			    guidstr);
    566 		}
    567 		*reportp = NULL;
    568 	}
    569 
    570 	/*
    571 	 * Print the numeric severity and, if we have it, a symbolic
    572 	 * name for it.
    573 	 */
    574 	if (ratelimitok) {
    575 		device_printf(sc->sc_dev, "%s: ErrorSeverity=%"PRIu32" (%s)\n",
    576 		    ctx,
    577 		    gede->ErrorSeverity,
    578 		    (gede->ErrorSeverity < __arraycount(apei_gede_severity)
    579 			? apei_gede_severity[gede->ErrorSeverity]
    580 			: "unknown"));
    581 	}
    582 
    583 	/*
    584 	 * The Revision may not often be useful, but this is only ever
    585 	 * shown at the time of a hardware error report, not something
    586 	 * you can glean at your convenience with acpidump.  So print
    587 	 * it anyway.
    588 	 */
    589 	if (ratelimitok) {
    590 		device_printf(sc->sc_dev, "%s: Revision=0x%"PRIx16"\n", ctx,
    591 		    gede->Revision);
    592 	}
    593 
    594 	/*
    595 	 * Don't touch anything past the Revision until we've
    596 	 * determined we understand it.  Return the header length to
    597 	 * the caller, or return zero -- and stop here -- if we don't
    598 	 * know what the actual header length is.
    599 	 */
    600 	if (gede->Revision < 0x0300) {
    601 		*headerlenp = sizeof(*gede);
    602 	} else if (gede->Revision < 0x0400) {
    603 		*headerlenp = sizeof(*gede_v3);
    604 	} else {
    605 		*headerlenp = 0;
    606 		return;
    607 	}
    608 
    609 	/*
    610 	 * Print the validation bits at debug level.  Only really
    611 	 * helpful if there are bits we _don't_ know about.
    612 	 */
    613 	if (ratelimitok) {
    614 		/* XXX define this format somewhere */
    615 		snprintb(buf, sizeof(buf), "\177\020"
    616 		    "b\000"	"FRU_ID\0"
    617 		    "b\001"	"FRU_TEXT\0" /* `FRU string', sometimes */
    618 		    "b\002"	"TIMESTAMP\0"
    619 		    "\0", gede->ValidationBits);
    620 		aprint_debug_dev(sc->sc_dev, "%s: ValidationBits=%s\n", ctx,
    621 		    buf);
    622 	}
    623 
    624 	/*
    625 	 * Print the CPER section flags.
    626 	 */
    627 	if (ratelimitok) {
    628 		snprintb(buf, sizeof(buf), CPER_SECTION_FLAGS_FMT,
    629 		    gede->Flags);
    630 		device_printf(sc->sc_dev, "%s: Flags=%s\n", ctx, buf);
    631 	}
    632 
    633 	/*
    634 	 * The ErrorDataLength is unlikely to be useful for the log, so
    635 	 * print it at debug level only.
    636 	 */
    637 	if (ratelimitok) {
    638 		aprint_debug_dev(sc->sc_dev, "%s:"
    639 		    " ErrorDataLength=0x%"PRIu32"\n",
    640 		    ctx, gede->ErrorDataLength);
    641 	}
    642 
    643 	/*
    644 	 * Print the FRU Id and text, if available.
    645 	 */
    646 	if (ratelimitok &&
    647 	    (gede->ValidationBits & ACPI_HEST_GEN_VALID_FRU_ID) != 0) {
    648 		struct uuid fruid;
    649 
    650 		apei_cper_guid_dec(gede->FruId, &fruid);
    651 		apei_format_guid(&fruid, guidstr);
    652 		device_printf(sc->sc_dev, "%s: FruId=%s\n", ctx, guidstr);
    653 	}
    654 	if (ratelimitok &&
    655 	    (gede->ValidationBits & ACPI_HEST_GEN_VALID_FRU_STRING) != 0) {
    656 		device_printf(sc->sc_dev, "%s: FruText=%.20s\n",
    657 		    ctx, gede->FruText);
    658 	}
    659 
    660 	/*
    661 	 * Print the timestamp, if available by the revision number and
    662 	 * the validation bits.
    663 	 */
    664 	if (ratelimitok &&
    665 	    gede->Revision >= 0x0300 && gede->Revision < 0x0400 &&
    666 	    gede->ValidationBits & ACPI_HEST_GEN_VALID_TIMESTAMP) {
    667 		const uint8_t *const t = (const uint8_t *)&gede_v3->TimeStamp;
    668 		const uint8_t s = t[0];
    669 		const uint8_t m = t[1];
    670 		const uint8_t h = t[2];
    671 		const uint8_t f = t[3];
    672 		const uint8_t D = t[4];
    673 		const uint8_t M = t[5];
    674 		const uint8_t Y = t[6];
    675 		const uint8_t C = t[7];
    676 
    677 		device_printf(sc->sc_dev, "%s: Timestamp=0x%"PRIx64
    678 		    " (%02d%02d-%02d-%02dT%02d:%02d:%02d%s)\n",
    679 		    ctx, gede_v3->TimeStamp,
    680 		    C,Y, M, D, h,m,s,
    681 		    f & __BIT(0) ? " (event time)" : " (collect time)");
    682 	}
    683 }
    684 
    685 /*
    686  * apei_gesb_ratelimit
    687  *
    688  *	State to limit the rate of console log messages about hardware
    689  *	errors.  For each of the four severity levels in a Generic
    690  *	Error Status Block,
    691  *
    692  *	0 - Recoverable (uncorrectable),
    693  *	1 - Fatal (uncorrectable),
    694  *	2 - Corrected, and
    695  *	3 - None (including ill-formed errors),
    696  *
    697  *	we record the last time it happened, protected by a CPU simple
    698  *	lock that we only try-acquire so it is safe to use in any
    699  *	context, including non-maskable interrupt context.
    700  */
    701 
    702 static struct {
    703 	__cpu_simple_lock_t	lock;
    704 	struct timeval		lasttime;
    705 	volatile uint32_t	suppressed;
    706 } __aligned(COHERENCY_UNIT) apei_gesb_ratelimit[4] __cacheline_aligned = {
    707 	[ACPI_HEST_GEN_ERROR_RECOVERABLE] = { .lock = __SIMPLELOCK_UNLOCKED },
    708 	[ACPI_HEST_GEN_ERROR_FATAL] = { .lock = __SIMPLELOCK_UNLOCKED },
    709 	[ACPI_HEST_GEN_ERROR_CORRECTED] = { .lock = __SIMPLELOCK_UNLOCKED },
    710 	[ACPI_HEST_GEN_ERROR_NONE] = { .lock = __SIMPLELOCK_UNLOCKED },
    711 };
    712 
    713 static void
    714 atomic_incsat_32(volatile uint32_t *p)
    715 {
    716 	uint32_t o, n;
    717 
    718 	do {
    719 		o = atomic_load_relaxed(p);
    720 		if (__predict_false(o == UINT_MAX))
    721 			return;
    722 		n = o + 1;
    723 	} while (__predict_false(atomic_cas_32(p, o, n) != o));
    724 }
    725 
    726 /*
    727  * apei_gesb_ratecheck(sc, severity, suppressed)
    728  *
    729  *	Check for a rate limit on errors of the specified severity.
    730  *
    731  *	=> Return true if the error should be printed, and format into
    732  *	   the buffer suppressed a message saying how many errors were
    733  *	   previously suppressed.
    734  *
    735  *	=> Return false if the error should be suppressed because the
    736  *	   last one printed was too recent.
    737  */
    738 static bool
    739 apei_gesb_ratecheck(struct apei_softc *sc, uint32_t severity,
    740     char suppressed[static sizeof(" (4294967295 or more errors suppressed)")])
    741 {
    742 	/* one of each type per minute (XXX worth making configurable?) */
    743 	const struct timeval mininterval = {60, 0};
    744 	unsigned i = MIN(severity, ACPI_HEST_GEN_ERROR_NONE); /* paranoia */
    745 	bool ok = false;
    746 
    747 	/*
    748 	 * If the lock is contended, the rate limit is probably
    749 	 * exceeded, so it's not OK to print.
    750 	 *
    751 	 * Otherwise, with the lock held, ask ratecheck(9) whether it's
    752 	 * OK to print.
    753 	 */
    754 	if (!__cpu_simple_lock_try(&apei_gesb_ratelimit[i].lock))
    755 		goto out;
    756 	ok = ratecheck(&apei_gesb_ratelimit[i].lasttime, &mininterval);
    757 	__cpu_simple_unlock(&apei_gesb_ratelimit[i].lock);
    758 
    759 out:	/*
    760 	 * If it's OK to print, report the number of errors that were
    761 	 * suppressed.  If it's not OK to print, count a suppressed
    762 	 * error.
    763 	 */
    764 	if (ok) {
    765 		const uint32_t n =
    766 		    atomic_swap_32(&apei_gesb_ratelimit[i].suppressed, 0);
    767 
    768 		if (n == 0) {
    769 			suppressed[0] = '\0';
    770 		} else {
    771 			snprintf(suppressed,
    772 			    sizeof(" (4294967295 or more errors suppressed)"),
    773 			    " (%u%s error%s suppressed)",
    774 			    n,
    775 			    n == UINT32_MAX ? " or more" : "",
    776 			    n == 1 ? "" : "s");
    777 		}
    778 	} else {
    779 		atomic_incsat_32(&apei_gesb_ratelimit[i].suppressed);
    780 		suppressed[0] = '\0';
    781 	}
    782 	return ok;
    783 }
    784 
    785 /*
    786  * apei_gesb_report(sc, gesb, size, ctx)
    787  *
    788  *	Check a Generic Error Status Block, of at most the specified
    789  *	size in bytes, and report any errors in it.  Return the 32-bit
    790  *	Block Status in case the caller needs it to acknowledge the
    791  *	report to firmware.
    792  */
    793 uint32_t
    794 apei_gesb_report(struct apei_softc *sc, const ACPI_HEST_GENERIC_STATUS *gesb,
    795     size_t size, const char *ctx, bool *fatalp)
    796 {
    797 	uint32_t status, unknownstatus, severity, nentries, i;
    798 	uint32_t datalen, rawdatalen;
    799 	const ACPI_HEST_GENERIC_DATA *gede0, *gede;
    800 	const unsigned char *rawdata;
    801 	bool ratelimitok = false;
    802 	char suppressed[sizeof(" (4294967295 or more errors suppressed)")];
    803 	bool fatal = false;
    804 
    805 	/*
    806 	 * Verify the buffer is large enough for a Generic Error Status
    807 	 * Block before we try to touch anything in it.
    808 	 */
    809 	if (size < sizeof(*gesb)) {
    810 		ratelimitok = apei_gesb_ratecheck(sc, ACPI_HEST_GEN_ERROR_NONE,
    811 		    suppressed);
    812 		if (ratelimitok) {
    813 			device_printf(sc->sc_dev,
    814 			    "%s: truncated GESB, %zu < %zu%s\n",
    815 			    ctx, size, sizeof(*gesb), suppressed);
    816 		}
    817 		status = 0;
    818 		goto out;
    819 	}
    820 	size -= sizeof(*gesb);
    821 
    822 	/*
    823 	 * Load the status.  Access ordering rules are unclear in the
    824 	 * ACPI specification; I'm guessing that load-acquire of the
    825 	 * block status is a good idea before any other access to the
    826 	 * GESB.
    827 	 */
    828 	status = atomic_load_acquire(&gesb->BlockStatus);
    829 
    830 	/*
    831 	 * If there are no status bits set, the rest of the GESB is
    832 	 * garbage, so stop here.
    833 	 */
    834 	if (status == 0) {
    835 		/* XXX dtrace */
    836 		/* XXX DPRINTF */
    837 		goto out;
    838 	}
    839 
    840 	/*
    841 	 * Read out the severity and get the number of entries in this
    842 	 * status block.
    843 	 */
    844 	severity = gesb->ErrorSeverity;
    845 	nentries = __SHIFTOUT(status, ACPI_HEST_ERROR_ENTRY_COUNT);
    846 
    847 	/*
    848 	 * Print a message to the console and dmesg about the severity
    849 	 * of the error.
    850 	 */
    851 	ratelimitok = apei_gesb_ratecheck(sc, severity, suppressed);
    852 	if (ratelimitok) {
    853 		char statusbuf[128];
    854 
    855 		/* XXX define this format somewhere */
    856 		snprintb(statusbuf, sizeof(statusbuf), "\177\020"
    857 		    "b\000"	"UE\0"
    858 		    "b\001"	"CE\0"
    859 		    "b\002"	"MULTI_UE\0"
    860 		    "b\003"	"MULTI_CE\0"
    861 		    "f\004\010"	"GEDE_COUNT\0"
    862 		    "\0", status);
    863 
    864 		if (severity < __arraycount(apei_gesb_severity)) {
    865 			device_printf(sc->sc_dev, "%s"
    866 			    " reported hardware error%s:"
    867 			    " severity=%s nentries=%u status=%s\n",
    868 			    ctx, suppressed,
    869 			    apei_gesb_severity[severity], nentries, statusbuf);
    870 		} else {
    871 			device_printf(sc->sc_dev, "%s reported error%s:"
    872 			    " severity=%"PRIu32" nentries=%u status=%s\n",
    873 			    ctx, suppressed,
    874 			    severity, nentries, statusbuf);
    875 		}
    876 	}
    877 
    878 	/*
    879 	 * Make a determination about whether the error is fatal.
    880 	 *
    881 	 * XXX Currently we don't have any mechanism to recover from
    882 	 * uncorrectable but recoverable errors, so we treat those --
    883 	 * and anything else we don't recognize -- as fatal.
    884 	 */
    885 	switch (severity) {
    886 	case ACPI_HEST_GEN_ERROR_CORRECTED:
    887 	case ACPI_HEST_GEN_ERROR_NONE:
    888 		fatal = false;
    889 		break;
    890 	case ACPI_HEST_GEN_ERROR_FATAL:
    891 	case ACPI_HEST_GEN_ERROR_RECOVERABLE: /* XXX */
    892 	default:
    893 		fatal = true;
    894 		break;
    895 	}
    896 
    897 	/*
    898 	 * Clear the bits we know about to warn if there's anything
    899 	 * left we don't understand.
    900 	 */
    901 	unknownstatus = status;
    902 	unknownstatus &= ~ACPI_HEST_UNCORRECTABLE;
    903 	unknownstatus &= ~ACPI_HEST_MULTIPLE_UNCORRECTABLE;
    904 	unknownstatus &= ~ACPI_HEST_CORRECTABLE;
    905 	unknownstatus &= ~ACPI_HEST_MULTIPLE_CORRECTABLE;
    906 	unknownstatus &= ~ACPI_HEST_ERROR_ENTRY_COUNT;
    907 	if (ratelimitok && unknownstatus != 0) {
    908 		/* XXX dtrace */
    909 		device_printf(sc->sc_dev, "%s: unknown BlockStatus bits:"
    910 		    " 0x%"PRIx32"\n", ctx, unknownstatus);
    911 	}
    912 
    913 	/*
    914 	 * Advance past the Generic Error Status Block (GESB) header to
    915 	 * the Generic Error Data Entries (GEDEs).
    916 	 */
    917 	gede0 = gede = (const ACPI_HEST_GENERIC_DATA *)(gesb + 1);
    918 
    919 	/*
    920 	 * Verify that the data length (GEDEs) fits within the size.
    921 	 * If not, truncate the GEDEs.
    922 	 */
    923 	datalen = gesb->DataLength;
    924 	if (size < datalen) {
    925 		if (ratelimitok) {
    926 			device_printf(sc->sc_dev, "%s:"
    927 			    " GESB DataLength exceeds bounds:"
    928 			    " %zu < %"PRIu32"\n",
    929 			    ctx, size, datalen);
    930 		}
    931 		datalen = size;
    932 	}
    933 	size -= datalen;
    934 
    935 	/*
    936 	 * Report each of the Generic Error Data Entries.
    937 	 */
    938 	for (i = 0; i < nentries; i++) {
    939 		size_t headerlen;
    940 		const struct apei_cper_report *report;
    941 		char subctx[128];
    942 
    943 		/*
    944 		 * Format a subcontext to show this numbered entry of
    945 		 * the GESB.
    946 		 */
    947 		snprintf(subctx, sizeof(subctx), "%s entry %"PRIu32, ctx, i);
    948 
    949 		/*
    950 		 * If the remaining GESB data length isn't enough for a
    951 		 * GEDE header, stop here.
    952 		 */
    953 		if (datalen < sizeof(*gede)) {
    954 			if (ratelimitok) {
    955 				device_printf(sc->sc_dev, "%s:"
    956 				    " truncated GEDE: %"PRIu32" < %zu bytes\n",
    957 				    subctx, datalen, sizeof(*gede));
    958 			}
    959 			break;
    960 		}
    961 
    962 		/*
    963 		 * Print the GEDE header and get the full length (may
    964 		 * vary from revision to revision of the GEDE) and the
    965 		 * CPER report function if possible.
    966 		 */
    967 		apei_gede_report_header(sc, gede, subctx, ratelimitok,
    968 		    &headerlen, &report);
    969 
    970 		/*
    971 		 * If we don't know the header length because of an
    972 		 * unfamiliar revision, stop here.
    973 		 */
    974 		if (headerlen == 0) {
    975 			if (ratelimitok) {
    976 				device_printf(sc->sc_dev, "%s:"
    977 				    " unknown revision: 0x%"PRIx16"\n",
    978 				    subctx, gede->Revision);
    979 			}
    980 			break;
    981 		}
    982 
    983 		/*
    984 		 * Stop here if what we mapped is too small for the
    985 		 * error data length.
    986 		 */
    987 		datalen -= headerlen;
    988 		if (datalen < gede->ErrorDataLength) {
    989 			if (ratelimitok) {
    990 				device_printf(sc->sc_dev, "%s:"
    991 				    " truncated GEDE payload:"
    992 				    " %"PRIu32" < %"PRIu32" bytes\n",
    993 				    subctx, datalen, gede->ErrorDataLength);
    994 			}
    995 			break;
    996 		}
    997 
    998 		/*
    999 		 * Report the Common Platform Error Record appendix to
   1000 		 * this Generic Error Data Entry.
   1001 		 */
   1002 		if (report == NULL) {
   1003 			if (ratelimitok) {
   1004 				device_printf(sc->sc_dev, "%s:"
   1005 				    " [unknown type]\n", ctx);
   1006 			}
   1007 		} else {
   1008 			/* XXX pass ratelimit through */
   1009 			(*report->func)(sc, (const char *)gede + headerlen,
   1010 			    gede->ErrorDataLength, subctx, ratelimitok);
   1011 		}
   1012 
   1013 		/*
   1014 		 * Advance past the GEDE header and CPER data to the
   1015 		 * next GEDE.
   1016 		 */
   1017 		gede = (const ACPI_HEST_GENERIC_DATA *)((const char *)gede +
   1018 		    + headerlen + gede->ErrorDataLength);
   1019 	}
   1020 
   1021 	/*
   1022 	 * Advance past the Generic Error Data Entries (GEDEs) to the
   1023 	 * raw error data.
   1024 	 *
   1025 	 * XXX Provide Max Raw Data Length as a parameter, as found in
   1026 	 * various HEST entry types.
   1027 	 */
   1028 	rawdata = (const unsigned char *)gede0 + datalen;
   1029 
   1030 	/*
   1031 	 * Verify that the raw data length fits within the size.  If
   1032 	 * not, truncate the raw data.
   1033 	 */
   1034 	rawdatalen = gesb->RawDataLength;
   1035 	if (size < rawdatalen) {
   1036 		if (ratelimitok) {
   1037 			device_printf(sc->sc_dev, "%s:"
   1038 			    " GESB RawDataLength exceeds bounds:"
   1039 			    " %zu < %"PRIu32"\n",
   1040 			    ctx, size, rawdatalen);
   1041 		}
   1042 		rawdatalen = size;
   1043 	}
   1044 	size -= rawdatalen;
   1045 
   1046 	/*
   1047 	 * Hexdump the raw data, if any.
   1048 	 */
   1049 	if (ratelimitok && rawdatalen > 0) {
   1050 		char devctx[128];
   1051 
   1052 		snprintf(devctx, sizeof(devctx), "%s: %s: raw data",
   1053 		    device_xname(sc->sc_dev), ctx);
   1054 		hexdump(printf, devctx, rawdata, rawdatalen);
   1055 	}
   1056 
   1057 	/*
   1058 	 * If there's anything left after the raw data, warn.
   1059 	 */
   1060 	if (ratelimitok && size > 0) {
   1061 		device_printf(sc->sc_dev, "%s: excess data: %zu bytes\n",
   1062 		    ctx, size);
   1063 	}
   1064 
   1065 	/*
   1066 	 * Return the status so the caller can ack it, and tell the
   1067 	 * caller whether this error is fatal.
   1068 	 */
   1069 out:	*fatalp = fatal;
   1070 	return status;
   1071 }
   1072 
   1073 MODULE(MODULE_CLASS_DRIVER, apei, NULL);
   1074 
   1075 #ifdef _MODULE
   1076 #include "ioconf.c"
   1077 #endif
   1078 
   1079 static int
   1080 apei_modcmd(modcmd_t cmd, void *opaque)
   1081 {
   1082 	int error = 0;
   1083 
   1084 	switch (cmd) {
   1085 	case MODULE_CMD_INIT:
   1086 #ifdef _MODULE
   1087 		error = config_init_component(cfdriver_ioconf_apei,
   1088 		    cfattach_ioconf_apei, cfdata_ioconf_apei);
   1089 #endif
   1090 		return error;
   1091 	case MODULE_CMD_FINI:
   1092 #ifdef _MODULE
   1093 		error = config_fini_component(cfdriver_ioconf_apei,
   1094 		    cfattach_ioconf_apei, cfdata_ioconf_apei);
   1095 #endif
   1096 		return error;
   1097 	default:
   1098 		return ENOTTY;
   1099 	}
   1100 }
   1101