Home | History | Annotate | Line # | Download | only in acpi
acpi_ec.c revision 1.87
      1 /*	$NetBSD: acpi_ec.c,v 1.87 2023/07/18 10:02:09 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.87 2023/07/18 10:02:09 riastradh Exp $");
     63 
     64 #include <sys/param.h>
     65 #include <sys/callout.h>
     66 #include <sys/condvar.h>
     67 #include <sys/device.h>
     68 #include <sys/kernel.h>
     69 #include <sys/kthread.h>
     70 #include <sys/mutex.h>
     71 #include <sys/systm.h>
     72 
     73 #include <dev/acpi/acpireg.h>
     74 #include <dev/acpi/acpivar.h>
     75 #include <dev/acpi/acpi_ecvar.h>
     76 
     77 #define _COMPONENT          ACPI_EC_COMPONENT
     78 ACPI_MODULE_NAME            ("acpi_ec")
     79 
     80 /* Maximum time to wait for global ACPI lock in ms */
     81 #define	EC_LOCK_TIMEOUT		5
     82 
     83 /* Maximum time to poll for completion of a command  in ms */
     84 #define	EC_POLL_TIMEOUT		5
     85 
     86 /* Maximum time to give a single EC command in s */
     87 #define EC_CMD_TIMEOUT		10
     88 
     89 /* From ACPI 3.0b, chapter 12.3 */
     90 #define EC_COMMAND_READ		0x80
     91 #define	EC_COMMAND_WRITE	0x81
     92 #define	EC_COMMAND_BURST_EN	0x82
     93 #define	EC_COMMAND_BURST_DIS	0x83
     94 #define	EC_COMMAND_QUERY	0x84
     95 
     96 /* From ACPI 3.0b, chapter 12.2.1 */
     97 #define	EC_STATUS_OBF		0x01
     98 #define	EC_STATUS_IBF		0x02
     99 #define	EC_STATUS_CMD		0x08
    100 #define	EC_STATUS_BURST		0x10
    101 #define	EC_STATUS_SCI		0x20
    102 #define	EC_STATUS_SMI		0x40
    103 
    104 static const struct device_compatible_entry compat_data[] = {
    105 	{ .compat = "PNP0C09" },
    106 	DEVICE_COMPAT_EOL
    107 };
    108 
    109 enum ec_state_t {
    110 	EC_STATE_QUERY,
    111 	EC_STATE_QUERY_VAL,
    112 	EC_STATE_READ,
    113 	EC_STATE_READ_ADDR,
    114 	EC_STATE_READ_VAL,
    115 	EC_STATE_WRITE,
    116 	EC_STATE_WRITE_ADDR,
    117 	EC_STATE_WRITE_VAL,
    118 	EC_STATE_FREE
    119 };
    120 
    121 struct acpiec_softc {
    122 	device_t sc_dev;
    123 
    124 	ACPI_HANDLE sc_ech;
    125 
    126 	ACPI_HANDLE sc_gpeh;
    127 	uint8_t sc_gpebit;
    128 
    129 	bus_space_tag_t sc_data_st;
    130 	bus_space_handle_t sc_data_sh;
    131 
    132 	bus_space_tag_t sc_csr_st;
    133 	bus_space_handle_t sc_csr_sh;
    134 
    135 	bool sc_need_global_lock;
    136 	uint32_t sc_global_lock;
    137 
    138 	kmutex_t sc_mtx, sc_access_mtx;
    139 	kcondvar_t sc_cv, sc_cv_sci;
    140 	enum ec_state_t sc_state;
    141 	bool sc_got_sci;
    142 	callout_t sc_pseudo_intr;
    143 
    144 	uint8_t sc_cur_addr, sc_cur_val;
    145 };
    146 
    147 static int acpiecdt_match(device_t, cfdata_t, void *);
    148 static void acpiecdt_attach(device_t, device_t, void *);
    149 
    150 static int acpiec_match(device_t, cfdata_t, void *);
    151 static void acpiec_attach(device_t, device_t, void *);
    152 
    153 static void acpiec_common_attach(device_t, device_t, ACPI_HANDLE,
    154     bus_space_tag_t, bus_addr_t, bus_space_tag_t, bus_addr_t,
    155     ACPI_HANDLE, uint8_t);
    156 
    157 static bool acpiec_suspend(device_t, const pmf_qual_t *);
    158 static bool acpiec_resume(device_t, const pmf_qual_t *);
    159 static bool acpiec_shutdown(device_t, int);
    160 
    161 static bool acpiec_parse_gpe_package(device_t, ACPI_HANDLE,
    162     ACPI_HANDLE *, uint8_t *);
    163 
    164 static void acpiec_callout(void *);
    165 static void acpiec_gpe_query(void *);
    166 static uint32_t acpiec_gpe_handler(ACPI_HANDLE, uint32_t, void *);
    167 static ACPI_STATUS acpiec_space_setup(ACPI_HANDLE, uint32_t, void *, void **);
    168 static ACPI_STATUS acpiec_space_handler(uint32_t, ACPI_PHYSICAL_ADDRESS,
    169     uint32_t, ACPI_INTEGER *, void *, void *);
    170 
    171 static void acpiec_gpe_state_machine(device_t);
    172 
    173 CFATTACH_DECL_NEW(acpiec, sizeof(struct acpiec_softc),
    174     acpiec_match, acpiec_attach, NULL, NULL);
    175 
    176 CFATTACH_DECL_NEW(acpiecdt, sizeof(struct acpiec_softc),
    177     acpiecdt_match, acpiecdt_attach, NULL, NULL);
    178 
    179 static device_t ec_singleton = NULL;
    180 static bool acpiec_cold = false;
    181 
    182 static bool
    183 acpiecdt_find(device_t parent, ACPI_HANDLE *ec_handle,
    184     bus_addr_t *cmd_reg, bus_addr_t *data_reg, uint8_t *gpebit)
    185 {
    186 	ACPI_TABLE_ECDT *ecdt;
    187 	ACPI_STATUS rv;
    188 
    189 	rv = AcpiGetTable(ACPI_SIG_ECDT, 1, (ACPI_TABLE_HEADER **)&ecdt);
    190 	if (ACPI_FAILURE(rv))
    191 		return false;
    192 
    193 	if (ecdt->Control.BitWidth != 8 || ecdt->Data.BitWidth != 8) {
    194 		aprint_error_dev(parent,
    195 		    "ECDT register width invalid (%u/%u)\n",
    196 		    ecdt->Control.BitWidth, ecdt->Data.BitWidth);
    197 		return false;
    198 	}
    199 
    200 	rv = AcpiGetHandle(ACPI_ROOT_OBJECT, ecdt->Id, ec_handle);
    201 	if (ACPI_FAILURE(rv)) {
    202 		aprint_error_dev(parent,
    203 		    "failed to look up EC object %s: %s\n",
    204 		    ecdt->Id, AcpiFormatException(rv));
    205 		return false;
    206 	}
    207 
    208 	*cmd_reg = ecdt->Control.Address;
    209 	*data_reg = ecdt->Data.Address;
    210 	*gpebit = ecdt->Gpe;
    211 
    212 	return true;
    213 }
    214 
    215 static int
    216 acpiecdt_match(device_t parent, cfdata_t match, void *aux)
    217 {
    218 	ACPI_HANDLE ec_handle;
    219 	bus_addr_t cmd_reg, data_reg;
    220 	uint8_t gpebit;
    221 
    222 	if (acpiecdt_find(parent, &ec_handle, &cmd_reg, &data_reg, &gpebit))
    223 		return 1;
    224 	else
    225 		return 0;
    226 }
    227 
    228 static void
    229 acpiecdt_attach(device_t parent, device_t self, void *aux)
    230 {
    231 	struct acpibus_attach_args *aa = aux;
    232 	ACPI_HANDLE ec_handle;
    233 	bus_addr_t cmd_reg, data_reg;
    234 	uint8_t gpebit;
    235 
    236 	if (!acpiecdt_find(parent, &ec_handle, &cmd_reg, &data_reg, &gpebit))
    237 		panic("ECDT disappeared");
    238 
    239 	aprint_naive("\n");
    240 	aprint_normal(": ACPI Embedded Controller via ECDT\n");
    241 
    242 	acpiec_common_attach(parent, self, ec_handle, aa->aa_iot, cmd_reg,
    243 	    aa->aa_iot, data_reg, NULL, gpebit);
    244 }
    245 
    246 static int
    247 acpiec_match(device_t parent, cfdata_t match, void *aux)
    248 {
    249 	struct acpi_attach_args *aa = aux;
    250 
    251 	return acpi_compatible_match(aa, compat_data);
    252 }
    253 
    254 static void
    255 acpiec_attach(device_t parent, device_t self, void *aux)
    256 {
    257 	struct acpi_attach_args *aa = aux;
    258 	struct acpi_resources ec_res;
    259 	struct acpi_io *io0, *io1;
    260 	ACPI_HANDLE gpe_handle;
    261 	uint8_t gpebit;
    262 	ACPI_STATUS rv;
    263 
    264 	if (ec_singleton != NULL) {
    265 		aprint_naive(": using %s\n", device_xname(ec_singleton));
    266 		aprint_normal(": using %s\n", device_xname(ec_singleton));
    267 		goto fail0;
    268 	}
    269 
    270 	if (!acpi_device_present(aa->aa_node->ad_handle)) {
    271 		aprint_normal(": not present\n");
    272 		goto fail0;
    273 	}
    274 
    275 	if (!acpiec_parse_gpe_package(self, aa->aa_node->ad_handle,
    276 				      &gpe_handle, &gpebit))
    277 		goto fail0;
    278 
    279 	rv = acpi_resource_parse(self, aa->aa_node->ad_handle, "_CRS",
    280 	    &ec_res, &acpi_resource_parse_ops_default);
    281 	if (rv != AE_OK) {
    282 		aprint_error_dev(self, "resource parsing failed: %s\n",
    283 		    AcpiFormatException(rv));
    284 		goto fail0;
    285 	}
    286 
    287 	if ((io0 = acpi_res_io(&ec_res, 0)) == NULL) {
    288 		aprint_error_dev(self, "no data register resource\n");
    289 		goto fail1;
    290 	}
    291 	if ((io1 = acpi_res_io(&ec_res, 1)) == NULL) {
    292 		aprint_error_dev(self, "no CSR register resource\n");
    293 		goto fail1;
    294 	}
    295 
    296 	acpiec_common_attach(parent, self, aa->aa_node->ad_handle,
    297 	    aa->aa_iot, io1->ar_base, aa->aa_iot, io0->ar_base,
    298 	    gpe_handle, gpebit);
    299 
    300 	acpi_resource_cleanup(&ec_res);
    301 	return;
    302 
    303 fail1:	acpi_resource_cleanup(&ec_res);
    304 fail0:	if (!pmf_device_register(self, NULL, NULL))
    305 		aprint_error_dev(self, "couldn't establish power handler\n");
    306 }
    307 
    308 static void
    309 acpiec_common_attach(device_t parent, device_t self,
    310     ACPI_HANDLE ec_handle, bus_space_tag_t cmdt, bus_addr_t cmd_reg,
    311     bus_space_tag_t datat, bus_addr_t data_reg,
    312     ACPI_HANDLE gpe_handle, uint8_t gpebit)
    313 {
    314 	struct acpiec_softc *sc = device_private(self);
    315 	ACPI_STATUS rv;
    316 	ACPI_INTEGER val;
    317 
    318 	sc->sc_dev = self;
    319 
    320 	sc->sc_csr_st = cmdt;
    321 	sc->sc_data_st = datat;
    322 
    323 	sc->sc_ech = ec_handle;
    324 	sc->sc_gpeh = gpe_handle;
    325 	sc->sc_gpebit = gpebit;
    326 
    327 	sc->sc_state = EC_STATE_FREE;
    328 	mutex_init(&sc->sc_mtx, MUTEX_DRIVER, IPL_TTY);
    329 	mutex_init(&sc->sc_access_mtx, MUTEX_DEFAULT, IPL_NONE);
    330 	cv_init(&sc->sc_cv, "eccv");
    331 	cv_init(&sc->sc_cv_sci, "ecsci");
    332 
    333 	if (bus_space_map(sc->sc_data_st, data_reg, 1, 0,
    334 	    &sc->sc_data_sh) != 0) {
    335 		aprint_error_dev(self, "unable to map data register\n");
    336 		return;
    337 	}
    338 
    339 	if (bus_space_map(sc->sc_csr_st, cmd_reg, 1, 0, &sc->sc_csr_sh) != 0) {
    340 		aprint_error_dev(self, "unable to map CSR register\n");
    341 		goto post_data_map;
    342 	}
    343 
    344 	rv = acpi_eval_integer(sc->sc_ech, "_GLK", &val);
    345 	if (rv == AE_OK) {
    346 		sc->sc_need_global_lock = val != 0;
    347 	} else if (rv != AE_NOT_FOUND) {
    348 		aprint_error_dev(self, "unable to evaluate _GLK: %s\n",
    349 		    AcpiFormatException(rv));
    350 		goto post_csr_map;
    351 	} else {
    352 		sc->sc_need_global_lock = false;
    353 	}
    354 	if (sc->sc_need_global_lock)
    355 		aprint_normal_dev(self, "using global ACPI lock\n");
    356 
    357 	callout_init(&sc->sc_pseudo_intr, CALLOUT_MPSAFE);
    358 	callout_setfunc(&sc->sc_pseudo_intr, acpiec_callout, self);
    359 
    360 	rv = AcpiInstallAddressSpaceHandler(sc->sc_ech, ACPI_ADR_SPACE_EC,
    361 	    acpiec_space_handler, acpiec_space_setup, self);
    362 	if (rv != AE_OK) {
    363 		aprint_error_dev(self,
    364 		    "unable to install address space handler: %s\n",
    365 		    AcpiFormatException(rv));
    366 		goto post_csr_map;
    367 	}
    368 
    369 	rv = AcpiInstallGpeHandler(sc->sc_gpeh, sc->sc_gpebit,
    370 	    ACPI_GPE_EDGE_TRIGGERED, acpiec_gpe_handler, self);
    371 	if (rv != AE_OK) {
    372 		aprint_error_dev(self, "unable to install GPE handler: %s\n",
    373 		    AcpiFormatException(rv));
    374 		goto post_csr_map;
    375 	}
    376 
    377 	rv = AcpiEnableGpe(sc->sc_gpeh, sc->sc_gpebit);
    378 	if (rv != AE_OK) {
    379 		aprint_error_dev(self, "unable to enable GPE: %s\n",
    380 		    AcpiFormatException(rv));
    381 		goto post_csr_map;
    382 	}
    383 
    384 	if (kthread_create(PRI_NONE, KTHREAD_MPSAFE, NULL, acpiec_gpe_query,
    385 		           self, NULL, "acpiec sci thread")) {
    386 		aprint_error_dev(self, "unable to create query kthread\n");
    387 		goto post_csr_map;
    388 	}
    389 
    390 	ec_singleton = self;
    391 
    392 	if (!pmf_device_register1(self, acpiec_suspend, acpiec_resume,
    393 	    acpiec_shutdown))
    394 		aprint_error_dev(self, "couldn't establish power handler\n");
    395 
    396 	return;
    397 
    398 post_csr_map:
    399 	(void)AcpiRemoveGpeHandler(sc->sc_gpeh, sc->sc_gpebit,
    400 	    acpiec_gpe_handler);
    401 	(void)AcpiRemoveAddressSpaceHandler(sc->sc_ech,
    402 	    ACPI_ADR_SPACE_EC, acpiec_space_handler);
    403 	bus_space_unmap(sc->sc_csr_st, sc->sc_csr_sh, 1);
    404 post_data_map:
    405 	bus_space_unmap(sc->sc_data_st, sc->sc_data_sh, 1);
    406 	if (!pmf_device_register(self, NULL, NULL))
    407 		aprint_error_dev(self, "couldn't establish power handler\n");
    408 }
    409 
    410 static bool
    411 acpiec_suspend(device_t dv, const pmf_qual_t *qual)
    412 {
    413 
    414 	acpiec_cold = true;
    415 
    416 	return true;
    417 }
    418 
    419 static bool
    420 acpiec_resume(device_t dv, const pmf_qual_t *qual)
    421 {
    422 
    423 	acpiec_cold = false;
    424 
    425 	return true;
    426 }
    427 
    428 static bool
    429 acpiec_shutdown(device_t dv, int how)
    430 {
    431 
    432 	acpiec_cold = true;
    433 	return true;
    434 }
    435 
    436 static bool
    437 acpiec_parse_gpe_package(device_t self, ACPI_HANDLE ec_handle,
    438     ACPI_HANDLE *gpe_handle, uint8_t *gpebit)
    439 {
    440 	ACPI_BUFFER buf;
    441 	ACPI_OBJECT *p, *c;
    442 	ACPI_STATUS rv;
    443 
    444 	rv = acpi_eval_struct(ec_handle, "_GPE", &buf);
    445 	if (rv != AE_OK) {
    446 		aprint_error_dev(self, "unable to evaluate _GPE: %s\n",
    447 		    AcpiFormatException(rv));
    448 		return false;
    449 	}
    450 
    451 	p = buf.Pointer;
    452 
    453 	if (p->Type == ACPI_TYPE_INTEGER) {
    454 		*gpe_handle = NULL;
    455 		*gpebit = p->Integer.Value;
    456 		ACPI_FREE(p);
    457 		return true;
    458 	}
    459 
    460 	if (p->Type != ACPI_TYPE_PACKAGE) {
    461 		aprint_error_dev(self, "_GPE is neither integer nor package\n");
    462 		ACPI_FREE(p);
    463 		return false;
    464 	}
    465 
    466 	if (p->Package.Count != 2) {
    467 		aprint_error_dev(self,
    468 		    "_GPE package does not contain 2 elements\n");
    469 		ACPI_FREE(p);
    470 		return false;
    471 	}
    472 
    473 	c = &p->Package.Elements[0];
    474 	rv = acpi_eval_reference_handle(c, gpe_handle);
    475 
    476 	if (ACPI_FAILURE(rv)) {
    477 		aprint_error_dev(self, "failed to evaluate _GPE handle\n");
    478 		ACPI_FREE(p);
    479 		return false;
    480 	}
    481 
    482 	c = &p->Package.Elements[1];
    483 
    484 	if (c->Type != ACPI_TYPE_INTEGER) {
    485 		aprint_error_dev(self,
    486 		    "_GPE package needs integer as 2nd field\n");
    487 		ACPI_FREE(p);
    488 		return false;
    489 	}
    490 	*gpebit = c->Integer.Value;
    491 	ACPI_FREE(p);
    492 	return true;
    493 }
    494 
    495 static uint8_t
    496 acpiec_read_data(struct acpiec_softc *sc)
    497 {
    498 	return bus_space_read_1(sc->sc_data_st, sc->sc_data_sh, 0);
    499 }
    500 
    501 static void
    502 acpiec_write_data(struct acpiec_softc *sc, uint8_t val)
    503 {
    504 	bus_space_write_1(sc->sc_data_st, sc->sc_data_sh, 0, val);
    505 }
    506 
    507 static uint8_t
    508 acpiec_read_status(struct acpiec_softc *sc)
    509 {
    510 	return bus_space_read_1(sc->sc_csr_st, sc->sc_csr_sh, 0);
    511 }
    512 
    513 static void
    514 acpiec_write_command(struct acpiec_softc *sc, uint8_t cmd)
    515 {
    516 	bus_space_write_1(sc->sc_csr_st, sc->sc_csr_sh, 0, cmd);
    517 }
    518 
    519 static ACPI_STATUS
    520 acpiec_space_setup(ACPI_HANDLE region, uint32_t func, void *arg,
    521     void **region_arg)
    522 {
    523 
    524 	if (func == ACPI_REGION_DEACTIVATE)
    525 		*region_arg = NULL;
    526 	else
    527 		*region_arg = arg;
    528 
    529 	return AE_OK;
    530 }
    531 
    532 static void
    533 acpiec_lock(device_t dv)
    534 {
    535 	struct acpiec_softc *sc = device_private(dv);
    536 	ACPI_STATUS rv;
    537 
    538 	mutex_enter(&sc->sc_access_mtx);
    539 
    540 	if (sc->sc_need_global_lock) {
    541 		rv = AcpiAcquireGlobalLock(EC_LOCK_TIMEOUT,
    542 		    &sc->sc_global_lock);
    543 		if (rv != AE_OK) {
    544 			aprint_error_dev(dv,
    545 			    "failed to acquire global lock: %s\n",
    546 			    AcpiFormatException(rv));
    547 			return;
    548 		}
    549 	}
    550 }
    551 
    552 static void
    553 acpiec_unlock(device_t dv)
    554 {
    555 	struct acpiec_softc *sc = device_private(dv);
    556 	ACPI_STATUS rv;
    557 
    558 	if (sc->sc_need_global_lock) {
    559 		rv = AcpiReleaseGlobalLock(sc->sc_global_lock);
    560 		if (rv != AE_OK) {
    561 			aprint_error_dev(dv,
    562 			    "failed to release global lock: %s\n",
    563 			    AcpiFormatException(rv));
    564 		}
    565 	}
    566 	mutex_exit(&sc->sc_access_mtx);
    567 }
    568 
    569 static ACPI_STATUS
    570 acpiec_read(device_t dv, uint8_t addr, uint8_t *val)
    571 {
    572 	struct acpiec_softc *sc = device_private(dv);
    573 	int i, timeo = 1000 * EC_CMD_TIMEOUT;
    574 
    575 	acpiec_lock(dv);
    576 	mutex_enter(&sc->sc_mtx);
    577 
    578 	sc->sc_cur_addr = addr;
    579 	sc->sc_state = EC_STATE_READ;
    580 
    581 	for (i = 0; i < EC_POLL_TIMEOUT; ++i) {
    582 		acpiec_gpe_state_machine(dv);
    583 		if (sc->sc_state == EC_STATE_FREE)
    584 			goto done;
    585 		delay(1);
    586 	}
    587 
    588 	if (cold || acpiec_cold) {
    589 		while (sc->sc_state != EC_STATE_FREE && timeo-- > 0) {
    590 			delay(1000);
    591 			acpiec_gpe_state_machine(dv);
    592 		}
    593 		if (sc->sc_state != EC_STATE_FREE) {
    594 			mutex_exit(&sc->sc_mtx);
    595 			acpiec_unlock(dv);
    596 			aprint_error_dev(dv, "command timed out, state %d\n",
    597 			    sc->sc_state);
    598 			return AE_ERROR;
    599 		}
    600 	} else if (cv_timedwait(&sc->sc_cv, &sc->sc_mtx, EC_CMD_TIMEOUT * hz)) {
    601 		mutex_exit(&sc->sc_mtx);
    602 		acpiec_unlock(dv);
    603 		aprint_error_dev(dv,
    604 		    "command takes over %d sec...\n", EC_CMD_TIMEOUT);
    605 		return AE_ERROR;
    606 	}
    607 
    608 done:
    609 	*val = sc->sc_cur_val;
    610 
    611 	mutex_exit(&sc->sc_mtx);
    612 	acpiec_unlock(dv);
    613 	return AE_OK;
    614 }
    615 
    616 static ACPI_STATUS
    617 acpiec_write(device_t dv, uint8_t addr, uint8_t val)
    618 {
    619 	struct acpiec_softc *sc = device_private(dv);
    620 	int i, timeo = 1000 * EC_CMD_TIMEOUT;
    621 
    622 	acpiec_lock(dv);
    623 	mutex_enter(&sc->sc_mtx);
    624 
    625 	sc->sc_cur_addr = addr;
    626 	sc->sc_cur_val = val;
    627 	sc->sc_state = EC_STATE_WRITE;
    628 
    629 	for (i = 0; i < EC_POLL_TIMEOUT; ++i) {
    630 		acpiec_gpe_state_machine(dv);
    631 		if (sc->sc_state == EC_STATE_FREE)
    632 			goto done;
    633 		delay(1);
    634 	}
    635 
    636 	if (cold || acpiec_cold) {
    637 		while (sc->sc_state != EC_STATE_FREE && timeo-- > 0) {
    638 			delay(1000);
    639 			acpiec_gpe_state_machine(dv);
    640 		}
    641 		if (sc->sc_state != EC_STATE_FREE) {
    642 			mutex_exit(&sc->sc_mtx);
    643 			acpiec_unlock(dv);
    644 			aprint_error_dev(dv, "command timed out, state %d\n",
    645 			    sc->sc_state);
    646 			return AE_ERROR;
    647 		}
    648 	} else if (cv_timedwait(&sc->sc_cv, &sc->sc_mtx, EC_CMD_TIMEOUT * hz)) {
    649 		mutex_exit(&sc->sc_mtx);
    650 		acpiec_unlock(dv);
    651 		aprint_error_dev(dv,
    652 		    "command takes over %d sec...\n", EC_CMD_TIMEOUT);
    653 		return AE_ERROR;
    654 	}
    655 
    656 done:
    657 	mutex_exit(&sc->sc_mtx);
    658 	acpiec_unlock(dv);
    659 	return AE_OK;
    660 }
    661 
    662 /*
    663  * acpiec_space_handler(func, paddr, bitwidth, value, arg, region_arg)
    664  *
    665  *	Transfer bitwidth/8 bytes of data between paddr and *value:
    666  *	from paddr to *value when func is ACPI_READ, and the other way
    667  *	when func is ACPI_WRITE.  arg is the acpiec(4) or acpiecdt(4)
    668  *	device.  region_arg is ignored (XXX why? determined by
    669  *	acpiec_space_setup but never used by anything that I can see).
    670  *
    671  *	The caller always provides storage at *value large enough for
    672  *	an ACPI_INTEGER object, i.e., a 64-bit integer.  However,
    673  *	bitwidth may be larger; in this case the caller provides larger
    674  *	storage at *value, e.g. 128 bits as documented in
    675  *	<https://gnats.netbsd.org/55206>.
    676  *
    677  *	On reads, this fully initializes one ACPI_INTEGER's worth of
    678  *	data at *value, even if bitwidth < 64.  The integer is
    679  *	interpreted in host byte order; in other words, bytes of data
    680  *	are transferred in order between paddr and (uint8_t *)value.
    681  *	The transfer is not atomic; it may go byte-by-byte.
    682  *
    683  *	XXX This only really makes sense on little-endian systems.
    684  *	E.g., thinkpad_acpi.c assumes that a single byte is transferred
    685  *	in the low-order bits of the result.  A big-endian system could
    686  *	read a 64-bit integer in big-endian (and it did for a while!),
    687  *	but what should it do for larger reads?  Unclear!
    688  *
    689  *	XXX It's not clear whether the object at *value is always
    690  *	_aligned_ adequately for an ACPI_INTEGER object.  Currently it
    691  *	always is as long as malloc, used by AcpiOsAllocate, returns
    692  *	64-bit-aligned data.
    693  */
    694 static ACPI_STATUS
    695 acpiec_space_handler(uint32_t func, ACPI_PHYSICAL_ADDRESS paddr,
    696     uint32_t width, ACPI_INTEGER *value, void *arg, void *region_arg)
    697 {
    698 	device_t dv;
    699 	ACPI_STATUS rv;
    700 	uint8_t addr, *buf;
    701 	unsigned int i;
    702 
    703 	if (paddr > 0xff || width % 8 != 0 ||
    704 	    value == NULL || arg == NULL || paddr + width / 8 > 0x100)
    705 		return AE_BAD_PARAMETER;
    706 
    707 	addr = paddr;
    708 	dv = arg;
    709 	buf = (uint8_t *)value;
    710 
    711 	rv = AE_OK;
    712 
    713 	switch (func) {
    714 	case ACPI_READ:
    715 		for (i = 0; i < width; i += 8, ++addr, ++buf) {
    716 			rv = acpiec_read(dv, addr, buf);
    717 			if (rv != AE_OK)
    718 				break;
    719 		}
    720 		/*
    721 		 * Make sure to fully initialize at least an
    722 		 * ACPI_INTEGER-sized object.
    723 		 */
    724 		for (; i < sizeof(*value)*8; i += 8, ++buf)
    725 			*buf = 0;
    726 		break;
    727 	case ACPI_WRITE:
    728 		for (i = 0; i < width; i += 8, ++addr, ++buf) {
    729 			rv = acpiec_write(dv, addr, *buf);
    730 			if (rv != AE_OK)
    731 				break;
    732 		}
    733 		break;
    734 	default:
    735 		aprint_error("%s: invalid Address Space function called: %x\n",
    736 		    device_xname(dv), (unsigned int)func);
    737 		return AE_BAD_PARAMETER;
    738 	}
    739 
    740 	return rv;
    741 }
    742 
    743 static void
    744 acpiec_gpe_query(void *arg)
    745 {
    746 	device_t dv = arg;
    747 	struct acpiec_softc *sc = device_private(dv);
    748 	uint8_t reg;
    749 	char qxx[5];
    750 	ACPI_STATUS rv;
    751 	int i;
    752 
    753 loop:
    754 	mutex_enter(&sc->sc_mtx);
    755 
    756 	if (sc->sc_got_sci == false)
    757 		cv_wait(&sc->sc_cv_sci, &sc->sc_mtx);
    758 	mutex_exit(&sc->sc_mtx);
    759 
    760 	acpiec_lock(dv);
    761 	mutex_enter(&sc->sc_mtx);
    762 
    763 	/* The Query command can always be issued, so be defensive here. */
    764 	sc->sc_got_sci = false;
    765 	sc->sc_state = EC_STATE_QUERY;
    766 
    767 	for (i = 0; i < EC_POLL_TIMEOUT; ++i) {
    768 		acpiec_gpe_state_machine(dv);
    769 		if (sc->sc_state == EC_STATE_FREE)
    770 			goto done;
    771 		delay(1);
    772 	}
    773 
    774 	cv_wait(&sc->sc_cv, &sc->sc_mtx);
    775 
    776 done:
    777 	reg = sc->sc_cur_val;
    778 
    779 	mutex_exit(&sc->sc_mtx);
    780 	acpiec_unlock(dv);
    781 
    782 	if (reg == 0)
    783 		goto loop; /* Spurious query result */
    784 
    785 	/*
    786 	 * Evaluate _Qxx to respond to the controller.
    787 	 */
    788 	snprintf(qxx, sizeof(qxx), "_Q%02X", (unsigned int)reg);
    789 	rv = AcpiEvaluateObject(sc->sc_ech, qxx, NULL, NULL);
    790 	if (rv != AE_OK && rv != AE_NOT_FOUND) {
    791 		aprint_error_dev(dv, "GPE query method %s failed: %s",
    792 		    qxx, AcpiFormatException(rv));
    793 	}
    794 
    795 	goto loop;
    796 }
    797 
    798 static void
    799 acpiec_gpe_state_machine(device_t dv)
    800 {
    801 	struct acpiec_softc *sc = device_private(dv);
    802 	uint8_t reg;
    803 
    804 	reg = acpiec_read_status(sc);
    805 
    806 	if (reg & EC_STATUS_SCI)
    807 		sc->sc_got_sci = true;
    808 
    809 	switch (sc->sc_state) {
    810 	case EC_STATE_QUERY:
    811 		if ((reg & EC_STATUS_IBF) != 0)
    812 			break; /* Nothing of interest here. */
    813 		acpiec_write_command(sc, EC_COMMAND_QUERY);
    814 		sc->sc_state = EC_STATE_QUERY_VAL;
    815 		break;
    816 
    817 	case EC_STATE_QUERY_VAL:
    818 		if ((reg & EC_STATUS_OBF) == 0)
    819 			break; /* Nothing of interest here. */
    820 
    821 		sc->sc_cur_val = acpiec_read_data(sc);
    822 		sc->sc_state = EC_STATE_FREE;
    823 
    824 		cv_signal(&sc->sc_cv);
    825 		break;
    826 
    827 	case EC_STATE_READ:
    828 		if ((reg & EC_STATUS_IBF) != 0)
    829 			break; /* Nothing of interest here. */
    830 
    831 		acpiec_write_command(sc, EC_COMMAND_READ);
    832 		sc->sc_state = EC_STATE_READ_ADDR;
    833 		break;
    834 
    835 	case EC_STATE_READ_ADDR:
    836 		if ((reg & EC_STATUS_IBF) != 0)
    837 			break; /* Nothing of interest here. */
    838 
    839 		acpiec_write_data(sc, sc->sc_cur_addr);
    840 		sc->sc_state = EC_STATE_READ_VAL;
    841 		break;
    842 
    843 	case EC_STATE_READ_VAL:
    844 		if ((reg & EC_STATUS_OBF) == 0)
    845 			break; /* Nothing of interest here. */
    846 		sc->sc_cur_val = acpiec_read_data(sc);
    847 		sc->sc_state = EC_STATE_FREE;
    848 
    849 		cv_signal(&sc->sc_cv);
    850 		break;
    851 
    852 	case EC_STATE_WRITE:
    853 		if ((reg & EC_STATUS_IBF) != 0)
    854 			break; /* Nothing of interest here. */
    855 
    856 		acpiec_write_command(sc, EC_COMMAND_WRITE);
    857 		sc->sc_state = EC_STATE_WRITE_ADDR;
    858 		break;
    859 
    860 	case EC_STATE_WRITE_ADDR:
    861 		if ((reg & EC_STATUS_IBF) != 0)
    862 			break; /* Nothing of interest here. */
    863 		acpiec_write_data(sc, sc->sc_cur_addr);
    864 		sc->sc_state = EC_STATE_WRITE_VAL;
    865 		break;
    866 
    867 	case EC_STATE_WRITE_VAL:
    868 		if ((reg & EC_STATUS_IBF) != 0)
    869 			break; /* Nothing of interest here. */
    870 		sc->sc_state = EC_STATE_FREE;
    871 		cv_signal(&sc->sc_cv);
    872 
    873 		acpiec_write_data(sc, sc->sc_cur_val);
    874 		break;
    875 
    876 	case EC_STATE_FREE:
    877 		if (sc->sc_got_sci)
    878 			cv_signal(&sc->sc_cv_sci);
    879 		break;
    880 	default:
    881 		panic("invalid state");
    882 	}
    883 
    884 	if (sc->sc_state != EC_STATE_FREE)
    885 		callout_schedule(&sc->sc_pseudo_intr, 1);
    886 }
    887 
    888 static void
    889 acpiec_callout(void *arg)
    890 {
    891 	device_t dv = arg;
    892 	struct acpiec_softc *sc = device_private(dv);
    893 
    894 	mutex_enter(&sc->sc_mtx);
    895 	acpiec_gpe_state_machine(dv);
    896 	mutex_exit(&sc->sc_mtx);
    897 }
    898 
    899 static uint32_t
    900 acpiec_gpe_handler(ACPI_HANDLE hdl, uint32_t gpebit, void *arg)
    901 {
    902 	device_t dv = arg;
    903 	struct acpiec_softc *sc = device_private(dv);
    904 
    905 	mutex_enter(&sc->sc_mtx);
    906 	acpiec_gpe_state_machine(dv);
    907 	mutex_exit(&sc->sc_mtx);
    908 
    909 	return ACPI_INTERRUPT_HANDLED | ACPI_REENABLE_GPE;
    910 }
    911 
    912 ACPI_STATUS
    913 acpiec_bus_read(device_t dv, u_int addr, ACPI_INTEGER *val, int width)
    914 {
    915 	return acpiec_space_handler(ACPI_READ, addr, width * 8, val, dv, NULL);
    916 }
    917 
    918 ACPI_STATUS
    919 acpiec_bus_write(device_t dv, u_int addr, ACPI_INTEGER val, int width)
    920 {
    921 	return acpiec_space_handler(ACPI_WRITE, addr, width * 8, &val, dv,
    922 	    NULL);
    923 }
    924 
    925 ACPI_HANDLE
    926 acpiec_get_handle(device_t dv)
    927 {
    928 	struct acpiec_softc *sc = device_private(dv);
    929 
    930 	return sc->sc_ech;
    931 }
    932