Home | History | Annotate | Line # | Download | only in acpi
acpi_ec.c revision 1.88
      1 /*	$NetBSD: acpi_ec.c,v 1.88 2023/07/18 10:02:25 riastradh Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2007 Joerg Sonnenberger <joerg (at) NetBSD.org>.
      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  *
     11  * 1. Redistributions of source code must retain the above copyright
     12  *    notice, this list of conditions and the following disclaimer.
     13  * 2. Redistributions in binary form must reproduce the above copyright
     14  *    notice, this list of conditions and the following disclaimer in
     15  *    the documentation and/or other materials provided with the
     16  *    distribution.
     17  *
     18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     19  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
     21  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
     22  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
     23  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
     24  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
     25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
     26  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
     27  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
     28  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  */
     31 
     32 /*
     33  * The ACPI Embedded Controller (EC) driver serves two different purposes:
     34  * - read and write access from ASL, e.g. to read battery state
     35  * - notification of ASL of System Control Interrupts.
     36  *
     37  * Access to the EC is serialised by sc_access_mtx and optionally the
     38  * ACPI global mutex.  Both locks are held until the request is fulfilled.
     39  * All access to the softc has to hold sc_mtx to serialise against the GPE
     40  * handler and the callout.  sc_mtx is also used for wakeup conditions.
     41  *
     42  * SCIs are processed in a kernel thread. Handling gets a bit complicated
     43  * by the lock order (sc_mtx must be acquired after sc_access_mtx and the
     44  * ACPI global mutex).
     45  *
     46  * Read and write requests spin around for a short time as many requests
     47  * can be handled instantly by the EC.  During normal processing interrupt
     48  * mode is used exclusively.  At boot and resume time interrupts are not
     49  * working and the handlers just busy loop.
     50  *
     51  * A callout is scheduled to compensate for missing interrupts on some
     52  * hardware.  If the EC doesn't process a request for 5s, it is most likely
     53  * in a wedged state.  No method to reset the EC is currently known.
     54  *
     55  * Special care has to be taken to not poll the EC in a busy loop without
     56  * delay.  This can prevent processing of Power Button events. At least some
     57  * Lenovo Thinkpads seem to be implement the Power Button Override in the EC
     58  * and the only option to recover on those models is to cut off all power.
     59  */
     60 
     61 #include <sys/cdefs.h>
     62 __KERNEL_RCSID(0, "$NetBSD: acpi_ec.c,v 1.88 2023/07/18 10:02:25 riastradh Exp $");
     63 
     64 #ifdef _KERNEL_OPT
     65 #include "opt_acpi_ec.h"
     66 #endif
     67 
     68 #include <sys/param.h>
     69 #include <sys/callout.h>
     70 #include <sys/condvar.h>
     71 #include <sys/device.h>
     72 #include <sys/kernel.h>
     73 #include <sys/kthread.h>
     74 #include <sys/mutex.h>
     75 #include <sys/systm.h>
     76 
     77 #include <dev/acpi/acpireg.h>
     78 #include <dev/acpi/acpivar.h>
     79 #include <dev/acpi/acpi_ecvar.h>
     80 
     81 #define _COMPONENT          ACPI_EC_COMPONENT
     82 ACPI_MODULE_NAME            ("acpi_ec")
     83 
     84 /* Maximum time to wait for global ACPI lock in ms */
     85 #define	EC_LOCK_TIMEOUT		5
     86 
     87 /* Maximum time to poll for completion of a command  in ms */
     88 #define	EC_POLL_TIMEOUT		5
     89 
     90 /* Maximum time to give a single EC command in s */
     91 #define EC_CMD_TIMEOUT		10
     92 
     93 /* From ACPI 3.0b, chapter 12.3 */
     94 #define EC_COMMAND_READ		0x80
     95 #define	EC_COMMAND_WRITE	0x81
     96 #define	EC_COMMAND_BURST_EN	0x82
     97 #define	EC_COMMAND_BURST_DIS	0x83
     98 #define	EC_COMMAND_QUERY	0x84
     99 
    100 /* From ACPI 3.0b, chapter 12.2.1 */
    101 #define	EC_STATUS_OBF		0x01
    102 #define	EC_STATUS_IBF		0x02
    103 #define	EC_STATUS_CMD		0x08
    104 #define	EC_STATUS_BURST		0x10
    105 #define	EC_STATUS_SCI		0x20
    106 #define	EC_STATUS_SMI		0x40
    107 
    108 #define	EC_STATUS_FMT							      \
    109 	"\x10\10IGN7\7SMI\6SCI\5BURST\4CMD\3IGN2\2IBF\1OBF"
    110 
    111 static const struct device_compatible_entry compat_data[] = {
    112 	{ .compat = "PNP0C09" },
    113 	DEVICE_COMPAT_EOL
    114 };
    115 
    116 #define	EC_STATE_ENUM(F)						      \
    117 	F(EC_STATE_QUERY, "QUERY")					      \
    118 	F(EC_STATE_QUERY_VAL, "QUERY_VAL")				      \
    119 	F(EC_STATE_READ, "READ")					      \
    120 	F(EC_STATE_READ_ADDR, "READ_ADDR")				      \
    121 	F(EC_STATE_READ_VAL, "READ_VAL")				      \
    122 	F(EC_STATE_WRITE, "WRITE")					      \
    123 	F(EC_STATE_WRITE_ADDR, "WRITE_ADDR")				      \
    124 	F(EC_STATE_WRITE_VAL, "WRITE_VAL")				      \
    125 	F(EC_STATE_FREE, "FREE")					      \
    126 
    127 enum ec_state_t {
    128 #define	F(N, S)	N,
    129 	EC_STATE_ENUM(F)
    130 #undef F
    131 };
    132 
    133 #ifdef ACPIEC_DEBUG
    134 static const char *const acpiec_state_names[] = {
    135 #define F(N, S)	[N] = S,
    136 	EC_STATE_ENUM(F)
    137 #undef F
    138 };
    139 #endif
    140 
    141 struct acpiec_softc {
    142 	device_t sc_dev;
    143 
    144 	ACPI_HANDLE sc_ech;
    145 
    146 	ACPI_HANDLE sc_gpeh;
    147 	uint8_t sc_gpebit;
    148 
    149 	bus_space_tag_t sc_data_st;
    150 	bus_space_handle_t sc_data_sh;
    151 
    152 	bus_space_tag_t sc_csr_st;
    153 	bus_space_handle_t sc_csr_sh;
    154 
    155 	bool sc_need_global_lock;
    156 	uint32_t sc_global_lock;
    157 
    158 	kmutex_t sc_mtx, sc_access_mtx;
    159 	kcondvar_t sc_cv, sc_cv_sci;
    160 	enum ec_state_t sc_state;
    161 	bool sc_got_sci;
    162 	callout_t sc_pseudo_intr;
    163 
    164 	uint8_t sc_cur_addr, sc_cur_val;
    165 };
    166 
    167 #ifdef ACPIEC_DEBUG
    168 
    169 #define	ACPIEC_DEBUG_ENUM(F)						      \
    170 	F(ACPIEC_DEBUG_REG, "REG")					      \
    171 	F(ACPIEC_DEBUG_RW, "RW")					      \
    172 	F(ACPIEC_DEBUG_QUERY, "QUERY")					      \
    173 	F(ACPIEC_DEBUG_TRANSITION, "TRANSITION")			      \
    174 	F(ACPIEC_DEBUG_INTR, "INTR")					      \
    175 
    176 enum {
    177 #define	F(N, S)	N,
    178 	ACPIEC_DEBUG_ENUM(F)
    179 #undef F
    180 };
    181 
    182 static const char *const acpiec_debug_names[] = {
    183 #define	F(N, S)	[N] = S,
    184 	ACPIEC_DEBUG_ENUM(F)
    185 #undef F
    186 };
    187 
    188 int acpiec_debug = ACPIEC_DEBUG;
    189 
    190 #define	DPRINTF(n, sc, fmt, ...) do					      \
    191 {									      \
    192 	if (acpiec_debug & __BIT(n)) {					      \
    193 		char dprintbuf[16];					      \
    194 		const char *state;					      \
    195 									      \
    196 		/* paranoia */						      \
    197 		if ((sc)->sc_state < __arraycount(acpiec_state_names)) {      \
    198 			state = acpiec_state_names[(sc)->sc_state];	      \
    199 		} else {						      \
    200 			snprintf(dprintbuf, sizeof(dprintbuf), "0x%x",	      \
    201 			    (sc)->sc_state);				      \
    202 			state = dprintbuf;				      \
    203 		}							      \
    204 									      \
    205 		device_printf((sc)->sc_dev, "(%s) [%s] "fmt,		      \
    206 		    acpiec_debug_names[n], state, ##__VA_ARGS__);	      \
    207 	}								      \
    208 } while (0)
    209 
    210 #else
    211 
    212 #define	DPRINTF(n, sc, fmt, ...)	__nothing
    213 
    214 #endif
    215 
    216 static int acpiecdt_match(device_t, cfdata_t, void *);
    217 static void acpiecdt_attach(device_t, device_t, void *);
    218 
    219 static int acpiec_match(device_t, cfdata_t, void *);
    220 static void acpiec_attach(device_t, device_t, void *);
    221 
    222 static void acpiec_common_attach(device_t, device_t, ACPI_HANDLE,
    223     bus_space_tag_t, bus_addr_t, bus_space_tag_t, bus_addr_t,
    224     ACPI_HANDLE, uint8_t);
    225 
    226 static bool acpiec_suspend(device_t, const pmf_qual_t *);
    227 static bool acpiec_resume(device_t, const pmf_qual_t *);
    228 static bool acpiec_shutdown(device_t, int);
    229 
    230 static bool acpiec_parse_gpe_package(device_t, ACPI_HANDLE,
    231     ACPI_HANDLE *, uint8_t *);
    232 
    233 static void acpiec_callout(void *);
    234 static void acpiec_gpe_query(void *);
    235 static uint32_t acpiec_gpe_handler(ACPI_HANDLE, uint32_t, void *);
    236 static ACPI_STATUS acpiec_space_setup(ACPI_HANDLE, uint32_t, void *, void **);
    237 static ACPI_STATUS acpiec_space_handler(uint32_t, ACPI_PHYSICAL_ADDRESS,
    238     uint32_t, ACPI_INTEGER *, void *, void *);
    239 
    240 static void acpiec_gpe_state_machine(device_t);
    241 
    242 CFATTACH_DECL_NEW(acpiec, sizeof(struct acpiec_softc),
    243     acpiec_match, acpiec_attach, NULL, NULL);
    244 
    245 CFATTACH_DECL_NEW(acpiecdt, sizeof(struct acpiec_softc),
    246     acpiecdt_match, acpiecdt_attach, NULL, NULL);
    247 
    248 static device_t ec_singleton = NULL;
    249 static bool acpiec_cold = false;
    250 
    251 static bool
    252 acpiecdt_find(device_t parent, ACPI_HANDLE *ec_handle,
    253     bus_addr_t *cmd_reg, bus_addr_t *data_reg, uint8_t *gpebit)
    254 {
    255 	ACPI_TABLE_ECDT *ecdt;
    256 	ACPI_STATUS rv;
    257 
    258 	rv = AcpiGetTable(ACPI_SIG_ECDT, 1, (ACPI_TABLE_HEADER **)&ecdt);
    259 	if (ACPI_FAILURE(rv))
    260 		return false;
    261 
    262 	if (ecdt->Control.BitWidth != 8 || ecdt->Data.BitWidth != 8) {
    263 		aprint_error_dev(parent,
    264 		    "ECDT register width invalid (%u/%u)\n",
    265 		    ecdt->Control.BitWidth, ecdt->Data.BitWidth);
    266 		return false;
    267 	}
    268 
    269 	rv = AcpiGetHandle(ACPI_ROOT_OBJECT, ecdt->Id, ec_handle);
    270 	if (ACPI_FAILURE(rv)) {
    271 		aprint_error_dev(parent,
    272 		    "failed to look up EC object %s: %s\n",
    273 		    ecdt->Id, AcpiFormatException(rv));
    274 		return false;
    275 	}
    276 
    277 	*cmd_reg = ecdt->Control.Address;
    278 	*data_reg = ecdt->Data.Address;
    279 	*gpebit = ecdt->Gpe;
    280 
    281 	return true;
    282 }
    283 
    284 static int
    285 acpiecdt_match(device_t parent, cfdata_t match, void *aux)
    286 {
    287 	ACPI_HANDLE ec_handle;
    288 	bus_addr_t cmd_reg, data_reg;
    289 	uint8_t gpebit;
    290 
    291 	if (acpiecdt_find(parent, &ec_handle, &cmd_reg, &data_reg, &gpebit))
    292 		return 1;
    293 	else
    294 		return 0;
    295 }
    296 
    297 static void
    298 acpiecdt_attach(device_t parent, device_t self, void *aux)
    299 {
    300 	struct acpibus_attach_args *aa = aux;
    301 	ACPI_HANDLE ec_handle;
    302 	bus_addr_t cmd_reg, data_reg;
    303 	uint8_t gpebit;
    304 
    305 	if (!acpiecdt_find(parent, &ec_handle, &cmd_reg, &data_reg, &gpebit))
    306 		panic("ECDT disappeared");
    307 
    308 	aprint_naive("\n");
    309 	aprint_normal(": ACPI Embedded Controller via ECDT\n");
    310 
    311 	acpiec_common_attach(parent, self, ec_handle, aa->aa_iot, cmd_reg,
    312 	    aa->aa_iot, data_reg, NULL, gpebit);
    313 }
    314 
    315 static int
    316 acpiec_match(device_t parent, cfdata_t match, void *aux)
    317 {
    318 	struct acpi_attach_args *aa = aux;
    319 
    320 	return acpi_compatible_match(aa, compat_data);
    321 }
    322 
    323 static void
    324 acpiec_attach(device_t parent, device_t self, void *aux)
    325 {
    326 	struct acpi_attach_args *aa = aux;
    327 	struct acpi_resources ec_res;
    328 	struct acpi_io *io0, *io1;
    329 	ACPI_HANDLE gpe_handle;
    330 	uint8_t gpebit;
    331 	ACPI_STATUS rv;
    332 
    333 	if (ec_singleton != NULL) {
    334 		aprint_naive(": using %s\n", device_xname(ec_singleton));
    335 		aprint_normal(": using %s\n", device_xname(ec_singleton));
    336 		goto fail0;
    337 	}
    338 
    339 	if (!acpi_device_present(aa->aa_node->ad_handle)) {
    340 		aprint_normal(": not present\n");
    341 		goto fail0;
    342 	}
    343 
    344 	if (!acpiec_parse_gpe_package(self, aa->aa_node->ad_handle,
    345 				      &gpe_handle, &gpebit))
    346 		goto fail0;
    347 
    348 	rv = acpi_resource_parse(self, aa->aa_node->ad_handle, "_CRS",
    349 	    &ec_res, &acpi_resource_parse_ops_default);
    350 	if (rv != AE_OK) {
    351 		aprint_error_dev(self, "resource parsing failed: %s\n",
    352 		    AcpiFormatException(rv));
    353 		goto fail0;
    354 	}
    355 
    356 	if ((io0 = acpi_res_io(&ec_res, 0)) == NULL) {
    357 		aprint_error_dev(self, "no data register resource\n");
    358 		goto fail1;
    359 	}
    360 	if ((io1 = acpi_res_io(&ec_res, 1)) == NULL) {
    361 		aprint_error_dev(self, "no CSR register resource\n");
    362 		goto fail1;
    363 	}
    364 
    365 	acpiec_common_attach(parent, self, aa->aa_node->ad_handle,
    366 	    aa->aa_iot, io1->ar_base, aa->aa_iot, io0->ar_base,
    367 	    gpe_handle, gpebit);
    368 
    369 	acpi_resource_cleanup(&ec_res);
    370 	return;
    371 
    372 fail1:	acpi_resource_cleanup(&ec_res);
    373 fail0:	if (!pmf_device_register(self, NULL, NULL))
    374 		aprint_error_dev(self, "couldn't establish power handler\n");
    375 }
    376 
    377 static void
    378 acpiec_common_attach(device_t parent, device_t self,
    379     ACPI_HANDLE ec_handle, bus_space_tag_t cmdt, bus_addr_t cmd_reg,
    380     bus_space_tag_t datat, bus_addr_t data_reg,
    381     ACPI_HANDLE gpe_handle, uint8_t gpebit)
    382 {
    383 	struct acpiec_softc *sc = device_private(self);
    384 	ACPI_STATUS rv;
    385 	ACPI_INTEGER val;
    386 
    387 	sc->sc_dev = self;
    388 
    389 	sc->sc_csr_st = cmdt;
    390 	sc->sc_data_st = datat;
    391 
    392 	sc->sc_ech = ec_handle;
    393 	sc->sc_gpeh = gpe_handle;
    394 	sc->sc_gpebit = gpebit;
    395 
    396 	sc->sc_state = EC_STATE_FREE;
    397 	mutex_init(&sc->sc_mtx, MUTEX_DRIVER, IPL_TTY);
    398 	mutex_init(&sc->sc_access_mtx, MUTEX_DEFAULT, IPL_NONE);
    399 	cv_init(&sc->sc_cv, "eccv");
    400 	cv_init(&sc->sc_cv_sci, "ecsci");
    401 
    402 	if (bus_space_map(sc->sc_data_st, data_reg, 1, 0,
    403 	    &sc->sc_data_sh) != 0) {
    404 		aprint_error_dev(self, "unable to map data register\n");
    405 		return;
    406 	}
    407 
    408 	if (bus_space_map(sc->sc_csr_st, cmd_reg, 1, 0, &sc->sc_csr_sh) != 0) {
    409 		aprint_error_dev(self, "unable to map CSR register\n");
    410 		goto post_data_map;
    411 	}
    412 
    413 	rv = acpi_eval_integer(sc->sc_ech, "_GLK", &val);
    414 	if (rv == AE_OK) {
    415 		sc->sc_need_global_lock = val != 0;
    416 	} else if (rv != AE_NOT_FOUND) {
    417 		aprint_error_dev(self, "unable to evaluate _GLK: %s\n",
    418 		    AcpiFormatException(rv));
    419 		goto post_csr_map;
    420 	} else {
    421 		sc->sc_need_global_lock = false;
    422 	}
    423 	if (sc->sc_need_global_lock)
    424 		aprint_normal_dev(self, "using global ACPI lock\n");
    425 
    426 	callout_init(&sc->sc_pseudo_intr, CALLOUT_MPSAFE);
    427 	callout_setfunc(&sc->sc_pseudo_intr, acpiec_callout, self);
    428 
    429 	rv = AcpiInstallAddressSpaceHandler(sc->sc_ech, ACPI_ADR_SPACE_EC,
    430 	    acpiec_space_handler, acpiec_space_setup, self);
    431 	if (rv != AE_OK) {
    432 		aprint_error_dev(self,
    433 		    "unable to install address space handler: %s\n",
    434 		    AcpiFormatException(rv));
    435 		goto post_csr_map;
    436 	}
    437 
    438 	rv = AcpiInstallGpeHandler(sc->sc_gpeh, sc->sc_gpebit,
    439 	    ACPI_GPE_EDGE_TRIGGERED, acpiec_gpe_handler, self);
    440 	if (rv != AE_OK) {
    441 		aprint_error_dev(self, "unable to install GPE handler: %s\n",
    442 		    AcpiFormatException(rv));
    443 		goto post_csr_map;
    444 	}
    445 
    446 	rv = AcpiEnableGpe(sc->sc_gpeh, sc->sc_gpebit);
    447 	if (rv != AE_OK) {
    448 		aprint_error_dev(self, "unable to enable GPE: %s\n",
    449 		    AcpiFormatException(rv));
    450 		goto post_csr_map;
    451 	}
    452 
    453 	if (kthread_create(PRI_NONE, KTHREAD_MPSAFE, NULL, acpiec_gpe_query,
    454 		           self, NULL, "acpiec sci thread")) {
    455 		aprint_error_dev(self, "unable to create query kthread\n");
    456 		goto post_csr_map;
    457 	}
    458 
    459 	ec_singleton = self;
    460 
    461 	if (!pmf_device_register1(self, acpiec_suspend, acpiec_resume,
    462 	    acpiec_shutdown))
    463 		aprint_error_dev(self, "couldn't establish power handler\n");
    464 
    465 	return;
    466 
    467 post_csr_map:
    468 	(void)AcpiRemoveGpeHandler(sc->sc_gpeh, sc->sc_gpebit,
    469 	    acpiec_gpe_handler);
    470 	(void)AcpiRemoveAddressSpaceHandler(sc->sc_ech,
    471 	    ACPI_ADR_SPACE_EC, acpiec_space_handler);
    472 	bus_space_unmap(sc->sc_csr_st, sc->sc_csr_sh, 1);
    473 post_data_map:
    474 	bus_space_unmap(sc->sc_data_st, sc->sc_data_sh, 1);
    475 	if (!pmf_device_register(self, NULL, NULL))
    476 		aprint_error_dev(self, "couldn't establish power handler\n");
    477 }
    478 
    479 static bool
    480 acpiec_suspend(device_t dv, const pmf_qual_t *qual)
    481 {
    482 
    483 	acpiec_cold = true;
    484 
    485 	return true;
    486 }
    487 
    488 static bool
    489 acpiec_resume(device_t dv, const pmf_qual_t *qual)
    490 {
    491 
    492 	acpiec_cold = false;
    493 
    494 	return true;
    495 }
    496 
    497 static bool
    498 acpiec_shutdown(device_t dv, int how)
    499 {
    500 
    501 	acpiec_cold = true;
    502 	return true;
    503 }
    504 
    505 static bool
    506 acpiec_parse_gpe_package(device_t self, ACPI_HANDLE ec_handle,
    507     ACPI_HANDLE *gpe_handle, uint8_t *gpebit)
    508 {
    509 	ACPI_BUFFER buf;
    510 	ACPI_OBJECT *p, *c;
    511 	ACPI_STATUS rv;
    512 
    513 	rv = acpi_eval_struct(ec_handle, "_GPE", &buf);
    514 	if (rv != AE_OK) {
    515 		aprint_error_dev(self, "unable to evaluate _GPE: %s\n",
    516 		    AcpiFormatException(rv));
    517 		return false;
    518 	}
    519 
    520 	p = buf.Pointer;
    521 
    522 	if (p->Type == ACPI_TYPE_INTEGER) {
    523 		*gpe_handle = NULL;
    524 		*gpebit = p->Integer.Value;
    525 		ACPI_FREE(p);
    526 		return true;
    527 	}
    528 
    529 	if (p->Type != ACPI_TYPE_PACKAGE) {
    530 		aprint_error_dev(self, "_GPE is neither integer nor package\n");
    531 		ACPI_FREE(p);
    532 		return false;
    533 	}
    534 
    535 	if (p->Package.Count != 2) {
    536 		aprint_error_dev(self,
    537 		    "_GPE package does not contain 2 elements\n");
    538 		ACPI_FREE(p);
    539 		return false;
    540 	}
    541 
    542 	c = &p->Package.Elements[0];
    543 	rv = acpi_eval_reference_handle(c, gpe_handle);
    544 
    545 	if (ACPI_FAILURE(rv)) {
    546 		aprint_error_dev(self, "failed to evaluate _GPE handle\n");
    547 		ACPI_FREE(p);
    548 		return false;
    549 	}
    550 
    551 	c = &p->Package.Elements[1];
    552 
    553 	if (c->Type != ACPI_TYPE_INTEGER) {
    554 		aprint_error_dev(self,
    555 		    "_GPE package needs integer as 2nd field\n");
    556 		ACPI_FREE(p);
    557 		return false;
    558 	}
    559 	*gpebit = c->Integer.Value;
    560 	ACPI_FREE(p);
    561 	return true;
    562 }
    563 
    564 static uint8_t
    565 acpiec_read_data(struct acpiec_softc *sc)
    566 {
    567 	uint8_t x;
    568 
    569 	x = bus_space_read_1(sc->sc_data_st, sc->sc_data_sh, 0);
    570 	DPRINTF(ACPIEC_DEBUG_REG, sc, "read data=0x%"PRIx8"\n", x);
    571 
    572 	return x;
    573 }
    574 
    575 static void
    576 acpiec_write_data(struct acpiec_softc *sc, uint8_t val)
    577 {
    578 
    579 	DPRINTF(ACPIEC_DEBUG_REG, sc, "write data=0x%"PRIx8"\n", val);
    580 	bus_space_write_1(sc->sc_data_st, sc->sc_data_sh, 0, val);
    581 }
    582 
    583 static uint8_t
    584 acpiec_read_status(struct acpiec_softc *sc)
    585 {
    586 	uint8_t x;
    587 
    588 	x = bus_space_read_1(sc->sc_csr_st, sc->sc_csr_sh, 0);
    589 	DPRINTF(ACPIEC_DEBUG_REG, sc, "read status=0x%"PRIx8"\n", x);
    590 
    591 	return x;
    592 }
    593 
    594 static void
    595 acpiec_write_command(struct acpiec_softc *sc, uint8_t cmd)
    596 {
    597 
    598 	DPRINTF(ACPIEC_DEBUG_REG, sc, "write command=0x%"PRIx8"\n", cmd);
    599 	bus_space_write_1(sc->sc_csr_st, sc->sc_csr_sh, 0, cmd);
    600 }
    601 
    602 static ACPI_STATUS
    603 acpiec_space_setup(ACPI_HANDLE region, uint32_t func, void *arg,
    604     void **region_arg)
    605 {
    606 
    607 	if (func == ACPI_REGION_DEACTIVATE)
    608 		*region_arg = NULL;
    609 	else
    610 		*region_arg = arg;
    611 
    612 	return AE_OK;
    613 }
    614 
    615 static void
    616 acpiec_lock(device_t dv)
    617 {
    618 	struct acpiec_softc *sc = device_private(dv);
    619 	ACPI_STATUS rv;
    620 
    621 	mutex_enter(&sc->sc_access_mtx);
    622 
    623 	if (sc->sc_need_global_lock) {
    624 		rv = AcpiAcquireGlobalLock(EC_LOCK_TIMEOUT,
    625 		    &sc->sc_global_lock);
    626 		if (rv != AE_OK) {
    627 			aprint_error_dev(dv,
    628 			    "failed to acquire global lock: %s\n",
    629 			    AcpiFormatException(rv));
    630 			return;
    631 		}
    632 	}
    633 }
    634 
    635 static void
    636 acpiec_unlock(device_t dv)
    637 {
    638 	struct acpiec_softc *sc = device_private(dv);
    639 	ACPI_STATUS rv;
    640 
    641 	if (sc->sc_need_global_lock) {
    642 		rv = AcpiReleaseGlobalLock(sc->sc_global_lock);
    643 		if (rv != AE_OK) {
    644 			aprint_error_dev(dv,
    645 			    "failed to release global lock: %s\n",
    646 			    AcpiFormatException(rv));
    647 		}
    648 	}
    649 	mutex_exit(&sc->sc_access_mtx);
    650 }
    651 
    652 static ACPI_STATUS
    653 acpiec_read(device_t dv, uint8_t addr, uint8_t *val)
    654 {
    655 	struct acpiec_softc *sc = device_private(dv);
    656 	int i, timeo = 1000 * EC_CMD_TIMEOUT;
    657 
    658 	acpiec_lock(dv);
    659 	mutex_enter(&sc->sc_mtx);
    660 
    661 	DPRINTF(ACPIEC_DEBUG_RW, sc,
    662 	    "pid %ld %s, lid %ld%s%s: read addr 0x%"PRIx8"\n",
    663 	    (long)curproc->p_pid, curproc->p_comm,
    664 	    (long)curlwp->l_lid, curlwp->l_name ? " " : "",
    665 	    curlwp->l_name ? curlwp->l_name : "",
    666 	    addr);
    667 
    668 	sc->sc_cur_addr = addr;
    669 	sc->sc_state = EC_STATE_READ;
    670 
    671 	for (i = 0; i < EC_POLL_TIMEOUT; ++i) {
    672 		acpiec_gpe_state_machine(dv);
    673 		if (sc->sc_state == EC_STATE_FREE)
    674 			goto done;
    675 		delay(1);
    676 	}
    677 
    678 	if (cold || acpiec_cold) {
    679 		while (sc->sc_state != EC_STATE_FREE && timeo-- > 0) {
    680 			delay(1000);
    681 			acpiec_gpe_state_machine(dv);
    682 		}
    683 		if (sc->sc_state != EC_STATE_FREE) {
    684 			mutex_exit(&sc->sc_mtx);
    685 			acpiec_unlock(dv);
    686 			aprint_error_dev(dv, "command timed out, state %d\n",
    687 			    sc->sc_state);
    688 			return AE_ERROR;
    689 		}
    690 	} else if (cv_timedwait(&sc->sc_cv, &sc->sc_mtx, EC_CMD_TIMEOUT * hz)) {
    691 		mutex_exit(&sc->sc_mtx);
    692 		acpiec_unlock(dv);
    693 		aprint_error_dev(dv,
    694 		    "command takes over %d sec...\n", EC_CMD_TIMEOUT);
    695 		return AE_ERROR;
    696 	}
    697 
    698 done:
    699 	DPRINTF(ACPIEC_DEBUG_RW, sc,
    700 	    "pid %ld %s, lid %ld%s%s: read addr 0x%"PRIx8": 0x%"PRIx8"\n",
    701 	    (long)curproc->p_pid, curproc->p_comm,
    702 	    (long)curlwp->l_lid, curlwp->l_name ? " " : "",
    703 	    curlwp->l_name ? curlwp->l_name : "",
    704 	    addr, sc->sc_cur_val);
    705 
    706 	*val = sc->sc_cur_val;
    707 
    708 	mutex_exit(&sc->sc_mtx);
    709 	acpiec_unlock(dv);
    710 	return AE_OK;
    711 }
    712 
    713 static ACPI_STATUS
    714 acpiec_write(device_t dv, uint8_t addr, uint8_t val)
    715 {
    716 	struct acpiec_softc *sc = device_private(dv);
    717 	int i, timeo = 1000 * EC_CMD_TIMEOUT;
    718 
    719 	acpiec_lock(dv);
    720 	mutex_enter(&sc->sc_mtx);
    721 
    722 	DPRINTF(ACPIEC_DEBUG_RW, sc,
    723 	    "pid %ld %s, lid %ld%s%s write addr 0x%"PRIx8": 0x%"PRIx8"\n",
    724 	    (long)curproc->p_pid, curproc->p_comm,
    725 	    (long)curlwp->l_lid, curlwp->l_name ? " " : "",
    726 	    curlwp->l_name ? curlwp->l_name : "",
    727 	    addr, val);
    728 
    729 	sc->sc_cur_addr = addr;
    730 	sc->sc_cur_val = val;
    731 	sc->sc_state = EC_STATE_WRITE;
    732 
    733 	for (i = 0; i < EC_POLL_TIMEOUT; ++i) {
    734 		acpiec_gpe_state_machine(dv);
    735 		if (sc->sc_state == EC_STATE_FREE)
    736 			goto done;
    737 		delay(1);
    738 	}
    739 
    740 	if (cold || acpiec_cold) {
    741 		while (sc->sc_state != EC_STATE_FREE && timeo-- > 0) {
    742 			delay(1000);
    743 			acpiec_gpe_state_machine(dv);
    744 		}
    745 		if (sc->sc_state != EC_STATE_FREE) {
    746 			mutex_exit(&sc->sc_mtx);
    747 			acpiec_unlock(dv);
    748 			aprint_error_dev(dv, "command timed out, state %d\n",
    749 			    sc->sc_state);
    750 			return AE_ERROR;
    751 		}
    752 	} else if (cv_timedwait(&sc->sc_cv, &sc->sc_mtx, EC_CMD_TIMEOUT * hz)) {
    753 		mutex_exit(&sc->sc_mtx);
    754 		acpiec_unlock(dv);
    755 		aprint_error_dev(dv,
    756 		    "command takes over %d sec...\n", EC_CMD_TIMEOUT);
    757 		return AE_ERROR;
    758 	}
    759 
    760 done:
    761 	DPRINTF(ACPIEC_DEBUG_RW, sc,
    762 	    "pid %ld %s, lid %ld%s%s: write addr 0x%"PRIx8": 0x%"PRIx8
    763 	    " done\n",
    764 	    (long)curproc->p_pid, curproc->p_comm,
    765 	    (long)curlwp->l_lid, curlwp->l_name ? " " : "",
    766 	    curlwp->l_name ? curlwp->l_name : "",
    767 	    addr, val);
    768 
    769 	mutex_exit(&sc->sc_mtx);
    770 	acpiec_unlock(dv);
    771 	return AE_OK;
    772 }
    773 
    774 /*
    775  * acpiec_space_handler(func, paddr, bitwidth, value, arg, region_arg)
    776  *
    777  *	Transfer bitwidth/8 bytes of data between paddr and *value:
    778  *	from paddr to *value when func is ACPI_READ, and the other way
    779  *	when func is ACPI_WRITE.  arg is the acpiec(4) or acpiecdt(4)
    780  *	device.  region_arg is ignored (XXX why? determined by
    781  *	acpiec_space_setup but never used by anything that I can see).
    782  *
    783  *	The caller always provides storage at *value large enough for
    784  *	an ACPI_INTEGER object, i.e., a 64-bit integer.  However,
    785  *	bitwidth may be larger; in this case the caller provides larger
    786  *	storage at *value, e.g. 128 bits as documented in
    787  *	<https://gnats.netbsd.org/55206>.
    788  *
    789  *	On reads, this fully initializes one ACPI_INTEGER's worth of
    790  *	data at *value, even if bitwidth < 64.  The integer is
    791  *	interpreted in host byte order; in other words, bytes of data
    792  *	are transferred in order between paddr and (uint8_t *)value.
    793  *	The transfer is not atomic; it may go byte-by-byte.
    794  *
    795  *	XXX This only really makes sense on little-endian systems.
    796  *	E.g., thinkpad_acpi.c assumes that a single byte is transferred
    797  *	in the low-order bits of the result.  A big-endian system could
    798  *	read a 64-bit integer in big-endian (and it did for a while!),
    799  *	but what should it do for larger reads?  Unclear!
    800  *
    801  *	XXX It's not clear whether the object at *value is always
    802  *	_aligned_ adequately for an ACPI_INTEGER object.  Currently it
    803  *	always is as long as malloc, used by AcpiOsAllocate, returns
    804  *	64-bit-aligned data.
    805  */
    806 static ACPI_STATUS
    807 acpiec_space_handler(uint32_t func, ACPI_PHYSICAL_ADDRESS paddr,
    808     uint32_t width, ACPI_INTEGER *value, void *arg, void *region_arg)
    809 {
    810 	device_t dv;
    811 	ACPI_STATUS rv;
    812 	uint8_t addr, *buf;
    813 	unsigned int i;
    814 
    815 	if (paddr > 0xff || width % 8 != 0 ||
    816 	    value == NULL || arg == NULL || paddr + width / 8 > 0x100)
    817 		return AE_BAD_PARAMETER;
    818 
    819 	addr = paddr;
    820 	dv = arg;
    821 	buf = (uint8_t *)value;
    822 
    823 	rv = AE_OK;
    824 
    825 	switch (func) {
    826 	case ACPI_READ:
    827 		for (i = 0; i < width; i += 8, ++addr, ++buf) {
    828 			rv = acpiec_read(dv, addr, buf);
    829 			if (rv != AE_OK)
    830 				break;
    831 		}
    832 		/*
    833 		 * Make sure to fully initialize at least an
    834 		 * ACPI_INTEGER-sized object.
    835 		 */
    836 		for (; i < sizeof(*value)*8; i += 8, ++buf)
    837 			*buf = 0;
    838 		break;
    839 	case ACPI_WRITE:
    840 		for (i = 0; i < width; i += 8, ++addr, ++buf) {
    841 			rv = acpiec_write(dv, addr, *buf);
    842 			if (rv != AE_OK)
    843 				break;
    844 		}
    845 		break;
    846 	default:
    847 		aprint_error("%s: invalid Address Space function called: %x\n",
    848 		    device_xname(dv), (unsigned int)func);
    849 		return AE_BAD_PARAMETER;
    850 	}
    851 
    852 	return rv;
    853 }
    854 
    855 static void
    856 acpiec_gpe_query(void *arg)
    857 {
    858 	device_t dv = arg;
    859 	struct acpiec_softc *sc = device_private(dv);
    860 	uint8_t reg;
    861 	char qxx[5];
    862 	ACPI_STATUS rv;
    863 	int i;
    864 
    865 loop:
    866 	mutex_enter(&sc->sc_mtx);
    867 
    868 	if (sc->sc_got_sci == false)
    869 		cv_wait(&sc->sc_cv_sci, &sc->sc_mtx);
    870 	DPRINTF(ACPIEC_DEBUG_QUERY, sc, "SCI query requested\n");
    871 	mutex_exit(&sc->sc_mtx);
    872 
    873 	acpiec_lock(dv);
    874 	mutex_enter(&sc->sc_mtx);
    875 
    876 	DPRINTF(ACPIEC_DEBUG_QUERY, sc, "SCI query\n");
    877 
    878 	/* The Query command can always be issued, so be defensive here. */
    879 	sc->sc_got_sci = false;
    880 	sc->sc_state = EC_STATE_QUERY;
    881 
    882 	for (i = 0; i < EC_POLL_TIMEOUT; ++i) {
    883 		acpiec_gpe_state_machine(dv);
    884 		if (sc->sc_state == EC_STATE_FREE)
    885 			goto done;
    886 		delay(1);
    887 	}
    888 
    889 	DPRINTF(ACPIEC_DEBUG_QUERY, sc, "SCI polling timeout\n");
    890 	cv_wait(&sc->sc_cv, &sc->sc_mtx);
    891 
    892 done:
    893 	reg = sc->sc_cur_val;
    894 	DPRINTF(ACPIEC_DEBUG_QUERY, sc, "SCI query: 0x%"PRIx8"\n", reg);
    895 
    896 	mutex_exit(&sc->sc_mtx);
    897 	acpiec_unlock(dv);
    898 
    899 	if (reg == 0)
    900 		goto loop; /* Spurious query result */
    901 
    902 	/*
    903 	 * Evaluate _Qxx to respond to the controller.
    904 	 */
    905 	snprintf(qxx, sizeof(qxx), "_Q%02X", (unsigned int)reg);
    906 	rv = AcpiEvaluateObject(sc->sc_ech, qxx, NULL, NULL);
    907 	if (rv != AE_OK && rv != AE_NOT_FOUND) {
    908 		aprint_error_dev(dv, "GPE query method %s failed: %s",
    909 		    qxx, AcpiFormatException(rv));
    910 	}
    911 
    912 	goto loop;
    913 }
    914 
    915 static void
    916 acpiec_gpe_state_machine(device_t dv)
    917 {
    918 	struct acpiec_softc *sc = device_private(dv);
    919 	uint8_t reg;
    920 
    921 	reg = acpiec_read_status(sc);
    922 
    923 #ifdef ACPIEC_DEBUG
    924 	if (acpiec_debug & __BIT(ACPIEC_DEBUG_TRANSITION)) {
    925 		char buf[128];
    926 
    927 		snprintb(buf, sizeof(buf), EC_STATUS_FMT, reg);
    928 		DPRINTF(ACPIEC_DEBUG_TRANSITION, sc, "%s\n", buf);
    929 	}
    930 #endif
    931 
    932 	if (reg & EC_STATUS_SCI)
    933 		sc->sc_got_sci = true;
    934 
    935 	switch (sc->sc_state) {
    936 	case EC_STATE_QUERY:
    937 		if ((reg & EC_STATUS_IBF) != 0)
    938 			break; /* Nothing of interest here. */
    939 		acpiec_write_command(sc, EC_COMMAND_QUERY);
    940 		sc->sc_state = EC_STATE_QUERY_VAL;
    941 		break;
    942 
    943 	case EC_STATE_QUERY_VAL:
    944 		if ((reg & EC_STATUS_OBF) == 0)
    945 			break; /* Nothing of interest here. */
    946 
    947 		sc->sc_cur_val = acpiec_read_data(sc);
    948 		sc->sc_state = EC_STATE_FREE;
    949 
    950 		cv_signal(&sc->sc_cv);
    951 		break;
    952 
    953 	case EC_STATE_READ:
    954 		if ((reg & EC_STATUS_IBF) != 0)
    955 			break; /* Nothing of interest here. */
    956 
    957 		acpiec_write_command(sc, EC_COMMAND_READ);
    958 		sc->sc_state = EC_STATE_READ_ADDR;
    959 		break;
    960 
    961 	case EC_STATE_READ_ADDR:
    962 		if ((reg & EC_STATUS_IBF) != 0)
    963 			break; /* Nothing of interest here. */
    964 
    965 		acpiec_write_data(sc, sc->sc_cur_addr);
    966 		sc->sc_state = EC_STATE_READ_VAL;
    967 		break;
    968 
    969 	case EC_STATE_READ_VAL:
    970 		if ((reg & EC_STATUS_OBF) == 0)
    971 			break; /* Nothing of interest here. */
    972 		sc->sc_cur_val = acpiec_read_data(sc);
    973 		sc->sc_state = EC_STATE_FREE;
    974 
    975 		cv_signal(&sc->sc_cv);
    976 		break;
    977 
    978 	case EC_STATE_WRITE:
    979 		if ((reg & EC_STATUS_IBF) != 0)
    980 			break; /* Nothing of interest here. */
    981 
    982 		acpiec_write_command(sc, EC_COMMAND_WRITE);
    983 		sc->sc_state = EC_STATE_WRITE_ADDR;
    984 		break;
    985 
    986 	case EC_STATE_WRITE_ADDR:
    987 		if ((reg & EC_STATUS_IBF) != 0)
    988 			break; /* Nothing of interest here. */
    989 		acpiec_write_data(sc, sc->sc_cur_addr);
    990 		sc->sc_state = EC_STATE_WRITE_VAL;
    991 		break;
    992 
    993 	case EC_STATE_WRITE_VAL:
    994 		if ((reg & EC_STATUS_IBF) != 0)
    995 			break; /* Nothing of interest here. */
    996 		sc->sc_state = EC_STATE_FREE;
    997 		cv_signal(&sc->sc_cv);
    998 
    999 		acpiec_write_data(sc, sc->sc_cur_val);
   1000 		break;
   1001 
   1002 	case EC_STATE_FREE:
   1003 		if (sc->sc_got_sci) {
   1004 			DPRINTF(ACPIEC_DEBUG_TRANSITION, sc,
   1005 			    "wake SCI thread\n");
   1006 			cv_signal(&sc->sc_cv_sci);
   1007 		}
   1008 		break;
   1009 	default:
   1010 		panic("invalid state");
   1011 	}
   1012 
   1013 	if (sc->sc_state != EC_STATE_FREE) {
   1014 		DPRINTF(ACPIEC_DEBUG_INTR, sc, "schedule callout\n");
   1015 		callout_schedule(&sc->sc_pseudo_intr, 1);
   1016 	}
   1017 
   1018 	DPRINTF(ACPIEC_DEBUG_TRANSITION, sc, "return\n");
   1019 }
   1020 
   1021 static void
   1022 acpiec_callout(void *arg)
   1023 {
   1024 	device_t dv = arg;
   1025 	struct acpiec_softc *sc = device_private(dv);
   1026 
   1027 	mutex_enter(&sc->sc_mtx);
   1028 	DPRINTF(ACPIEC_DEBUG_INTR, sc, "callout\n");
   1029 	acpiec_gpe_state_machine(dv);
   1030 	mutex_exit(&sc->sc_mtx);
   1031 }
   1032 
   1033 static uint32_t
   1034 acpiec_gpe_handler(ACPI_HANDLE hdl, uint32_t gpebit, void *arg)
   1035 {
   1036 	device_t dv = arg;
   1037 	struct acpiec_softc *sc = device_private(dv);
   1038 
   1039 	mutex_enter(&sc->sc_mtx);
   1040 	DPRINTF(ACPIEC_DEBUG_INTR, sc, "GPE\n");
   1041 	acpiec_gpe_state_machine(dv);
   1042 	mutex_exit(&sc->sc_mtx);
   1043 
   1044 	return ACPI_INTERRUPT_HANDLED | ACPI_REENABLE_GPE;
   1045 }
   1046 
   1047 ACPI_STATUS
   1048 acpiec_bus_read(device_t dv, u_int addr, ACPI_INTEGER *val, int width)
   1049 {
   1050 	return acpiec_space_handler(ACPI_READ, addr, width * 8, val, dv, NULL);
   1051 }
   1052 
   1053 ACPI_STATUS
   1054 acpiec_bus_write(device_t dv, u_int addr, ACPI_INTEGER val, int width)
   1055 {
   1056 	return acpiec_space_handler(ACPI_WRITE, addr, width * 8, &val, dv,
   1057 	    NULL);
   1058 }
   1059 
   1060 ACPI_HANDLE
   1061 acpiec_get_handle(device_t dv)
   1062 {
   1063 	struct acpiec_softc *sc = device_private(dv);
   1064 
   1065 	return sc->sc_ech;
   1066 }
   1067