Home | History | Annotate | Line # | Download | only in acpi
acpi.c revision 1.120.4.2
      1 /*	$NetBSD: acpi.c,v 1.120.4.2 2009/09/05 11:34:26 bouyer Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2003, 2007 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Charles M. Hannum of By Noon Software, Inc.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 /*
     33  * Copyright 2001, 2003 Wasabi Systems, Inc.
     34  * All rights reserved.
     35  *
     36  * Written by Jason R. Thorpe for Wasabi Systems, Inc.
     37  *
     38  * Redistribution and use in source and binary forms, with or without
     39  * modification, are permitted provided that the following conditions
     40  * are met:
     41  * 1. Redistributions of source code must retain the above copyright
     42  *    notice, this list of conditions and the following disclaimer.
     43  * 2. Redistributions in binary form must reproduce the above copyright
     44  *    notice, this list of conditions and the following disclaimer in the
     45  *    documentation and/or other materials provided with the distribution.
     46  * 3. All advertising materials mentioning features or use of this software
     47  *    must display the following acknowledgement:
     48  *	This product includes software developed for the NetBSD Project by
     49  *	Wasabi Systems, Inc.
     50  * 4. The name of Wasabi Systems, Inc. may not be used to endorse
     51  *    or promote products derived from this software without specific prior
     52  *    written permission.
     53  *
     54  * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``AS IS'' AND
     55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     56  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     57  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL WASABI SYSTEMS, INC
     58  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     59  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     60  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     61  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     62  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     63  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     64  * POSSIBILITY OF SUCH DAMAGE.
     65  */
     66 
     67 /*
     68  * Autoconfiguration support for the Intel ACPI Component Architecture
     69  * ACPI reference implementation.
     70  */
     71 
     72 #include <sys/cdefs.h>
     73 __KERNEL_RCSID(0, "$NetBSD: acpi.c,v 1.120.4.2 2009/09/05 11:34:26 bouyer Exp $");
     74 
     75 #include "opt_acpi.h"
     76 #include "opt_pcifixup.h"
     77 
     78 #include <sys/param.h>
     79 #include <sys/systm.h>
     80 #include <sys/device.h>
     81 #include <sys/malloc.h>
     82 #include <sys/mutex.h>
     83 #include <sys/kernel.h>
     84 #include <sys/proc.h>
     85 #include <sys/sysctl.h>
     86 
     87 #include <dev/acpi/acpica.h>
     88 #include <dev/acpi/acpireg.h>
     89 #include <dev/acpi/acpivar.h>
     90 #include <dev/acpi/acpi_osd.h>
     91 #include <dev/acpi/acpi_timer.h>
     92 #include <dev/acpi/acpi_wakedev.h>
     93 #ifdef ACPIVERBOSE
     94 #include <dev/acpi/acpidevs_data.h>
     95 #endif
     96 
     97 #if defined(ACPI_PCI_FIXUP)
     98 #error The option ACPI_PCI_FIXUP has been obsoleted by PCI_INTR_FIXUP_DISABLED.  Please adjust your kernel configuration file.
     99 #endif
    100 
    101 #ifdef PCI_INTR_FIXUP_DISABLED
    102 #include <dev/pci/pcidevs.h>
    103 #endif
    104 
    105 MALLOC_DECLARE(M_ACPI);
    106 
    107 #include <machine/acpi_machdep.h>
    108 
    109 #ifdef ACPI_DEBUGGER
    110 #define	ACPI_DBGR_INIT		0x01
    111 #define	ACPI_DBGR_TABLES	0x02
    112 #define	ACPI_DBGR_ENABLE	0x04
    113 #define	ACPI_DBGR_PROBE		0x08
    114 #define	ACPI_DBGR_RUNNING	0x10
    115 
    116 static int acpi_dbgr = 0x00;
    117 #endif
    118 
    119 static ACPI_TABLE_DESC	acpi_initial_tables[128];
    120 
    121 static int	acpi_match(device_t, struct cfdata *, void *);
    122 static void	acpi_attach(device_t, device_t, void *);
    123 static void	acpi_childdet(device_t, device_t);
    124 
    125 static int	acpi_print(void *aux, const char *);
    126 
    127 static int	sysctl_hw_acpi_sleepstate(SYSCTLFN_ARGS);
    128 
    129 extern struct cfdriver acpi_cd;
    130 
    131 CFATTACH_DECL2_NEW(acpi, sizeof(struct acpi_softc),
    132     acpi_match, acpi_attach, NULL, NULL, NULL, acpi_childdet);
    133 
    134 /*
    135  * This is a flag we set when the ACPI subsystem is active.  Machine
    136  * dependent code may wish to skip other steps (such as attaching
    137  * subsystems that ACPI supercedes) when ACPI is active.
    138  */
    139 int	acpi_active;
    140 int	acpi_force_load;
    141 int	acpi_suspended = 0;
    142 
    143 /*
    144  * Pointer to the ACPI subsystem's state.  There can be only
    145  * one ACPI instance.
    146  */
    147 struct acpi_softc *acpi_softc;
    148 
    149 /*
    150  * Locking stuff.
    151  */
    152 static kmutex_t acpi_slock;
    153 static int acpi_locked;
    154 extern kmutex_t acpi_interrupt_list_mtx;
    155 
    156 /*
    157  * Ignored HIDs
    158  */
    159 static const char * const acpi_ignored_ids[] = {
    160 #if defined(i386) || defined(x86_64)
    161 	"PNP0000",	/* AT interrupt controller is handled internally */
    162 	"PNP0200",	/* AT DMA controller is handled internally */
    163 	"PNP0A??",	/* Busses aren't enumerated with ACPI yet */
    164 	"PNP0B00",	/* AT RTC is handled internally */
    165 	"PNP0C01",	/* No "System Board" driver */
    166 	"PNP0C02",	/* No "PnP motherboard register resources" driver */
    167 	"PNP0C0F",	/* ACPI PCI link devices are handled internally */
    168 #endif
    169 #if defined(x86_64)
    170 	"PNP0C04",	/* FPU is handled internally */
    171 #endif
    172 	NULL
    173 };
    174 
    175 /*
    176  * sysctl-related information
    177  */
    178 
    179 static uint64_t acpi_root_pointer;	/* found as hw.acpi.root */
    180 static int acpi_sleepstate = ACPI_STATE_S0;
    181 static char acpi_supported_states[3 * 6 + 1] = "";;
    182 
    183 /*
    184  * Prototypes.
    185  */
    186 static void		acpi_build_tree(struct acpi_softc *);
    187 static ACPI_STATUS	acpi_make_devnode(ACPI_HANDLE, UINT32, void *, void **);
    188 
    189 static void		acpi_enable_fixed_events(struct acpi_softc *);
    190 
    191 static ACPI_TABLE_HEADER *acpi_map_rsdt(void);
    192 static void		acpi_unmap_rsdt(ACPI_TABLE_HEADER *);
    193 static int		is_available_state(struct acpi_softc *, int);
    194 
    195 static bool		acpi_suspend(device_t PMF_FN_PROTO);
    196 static bool		acpi_resume(device_t PMF_FN_PROTO);
    197 
    198 /*
    199  * acpi_probe:
    200  *
    201  *	Probe for ACPI support.  This is called by the
    202  *	machine-dependent ACPI front-end.  All of the
    203  *	actual work is done by ACPICA.
    204  *
    205  *	NOTE: This is not an autoconfiguration interface function.
    206  */
    207 int
    208 acpi_probe(void)
    209 {
    210 	static int beenhere;
    211 	ACPI_TABLE_HEADER *rsdt;
    212 	ACPI_STATUS rv;
    213 
    214 	if (beenhere != 0)
    215 		panic("acpi_probe: ACPI has already been probed");
    216 	beenhere = 1;
    217 
    218 	mutex_init(&acpi_slock, MUTEX_DEFAULT, IPL_NONE);
    219 	mutex_init(&acpi_interrupt_list_mtx, MUTEX_DEFAULT, IPL_NONE);
    220 	acpi_locked = 0;
    221 
    222 	/*
    223 	 * Start up ACPICA.
    224 	 */
    225 #ifdef ACPI_DEBUGGER
    226 	if (acpi_dbgr & ACPI_DBGR_INIT)
    227 		acpi_osd_debugger();
    228 #endif
    229 
    230 	AcpiGbl_AllMethodsSerialized = FALSE;
    231 	AcpiGbl_EnableInterpreterSlack = TRUE;
    232 
    233 	rv = AcpiInitializeSubsystem();
    234 	if (ACPI_FAILURE(rv)) {
    235 		printf("ACPI: unable to initialize ACPICA: %s\n",
    236 		    AcpiFormatException(rv));
    237 		return 0;
    238 	}
    239 
    240 	rv = AcpiInitializeTables(acpi_initial_tables, 128, 0);
    241 	if (ACPI_FAILURE(rv)) {
    242 		printf("ACPI: unable to initialize ACPI tables: %s\n",
    243 		    AcpiFormatException(rv));
    244 		return 0;
    245 	}
    246 
    247 	rv = AcpiReallocateRootTable();
    248 	if (ACPI_FAILURE(rv)) {
    249 		printf("ACPI: unable to reallocate root table: %s\n",
    250 		    AcpiFormatException(rv));
    251 		return 0;
    252 	}
    253 
    254 #ifdef ACPI_DEBUGGER
    255 	if (acpi_dbgr & ACPI_DBGR_TABLES)
    256 		acpi_osd_debugger();
    257 #endif
    258 
    259 	rv = AcpiLoadTables();
    260 	if (ACPI_FAILURE(rv)) {
    261 		printf("ACPI: unable to load tables: %s\n",
    262 		    AcpiFormatException(rv));
    263 		return 0;
    264 	}
    265 
    266 	rsdt = acpi_map_rsdt();
    267 	if (rsdt == NULL) {
    268 		printf("ACPI: unable to map RSDT\n");
    269 		return 0;
    270 	}
    271 
    272 	if (!acpi_force_load && (acpi_find_quirks() & ACPI_QUIRK_BROKEN)) {
    273 		printf("ACPI: BIOS implementation in listed as broken:\n");
    274 		printf("ACPI: X/RSDT: OemId <%6.6s,%8.8s,%08x>, "
    275 		       "AslId <%4.4s,%08x>\n",
    276 			rsdt->OemId, rsdt->OemTableId,
    277 		        rsdt->OemRevision,
    278 			rsdt->AslCompilerId,
    279 		        rsdt->AslCompilerRevision);
    280 		printf("ACPI: not used. set acpi_force_load to use anyway.\n");
    281 		acpi_unmap_rsdt(rsdt);
    282 		return 0;
    283 	}
    284 
    285 	acpi_unmap_rsdt(rsdt);
    286 
    287 #if notyet
    288 	/* Install the default address space handlers. */
    289 	rv = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
    290 	    ACPI_ADR_SPACE_SYSTEM_MEMORY, ACPI_DEFAULT_HANDLER, NULL, NULL);
    291 	if (ACPI_FAILURE(rv)) {
    292 		printf("ACPI: unable to initialise SystemMemory handler: %s\n",
    293 		    AcpiFormatException(rv));
    294 		return 0;
    295 	}
    296 	rv = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
    297 	    ACPI_ADR_SPACE_SYSTEM_IO, ACPI_DEFAULT_HANDLER, NULL, NULL);
    298 	if (ACPI_FAILURE(rv)) {
    299 		printf("ACPI: unable to initialise SystemIO handler: %s\n",
    300 		     AcpiFormatException(rv));
    301 		return 0;
    302 	}
    303 	rv = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
    304 	    ACPI_ADR_SPACE_PCI_CONFIG, ACPI_DEFAULT_HANDLER, NULL, NULL);
    305 	if (ACPI_FAILURE(rv)) {
    306 		printf("ACPI: unabled to initialise PciConfig handler: %s\n",
    307 		    AcpiFormatException(rv));
    308 		return 0;
    309 	}
    310 #endif
    311 
    312 	rv = AcpiEnableSubsystem(~(ACPI_NO_HARDWARE_INIT|ACPI_NO_ACPI_ENABLE));
    313 	if (ACPI_FAILURE(rv)) {
    314 		printf("ACPI: unable to enable: %s\n", AcpiFormatException(rv));
    315 		return 0;
    316 	}
    317 
    318 	/*
    319 	 * Looks like we have ACPI!
    320 	 */
    321 
    322 	return 1;
    323 }
    324 
    325 static int
    326 acpi_submatch(device_t parent, cfdata_t cf, const int *locs, void *aux)
    327 {
    328 	struct cfattach *ca;
    329 
    330 	ca = config_cfattach_lookup(cf->cf_name, cf->cf_atname);
    331 	return (ca == &acpi_ca);
    332 }
    333 
    334 int
    335 acpi_check(device_t parent, const char *ifattr)
    336 {
    337 	return (config_search_ia(acpi_submatch, parent, ifattr, NULL) != NULL);
    338 }
    339 
    340 ACPI_PHYSICAL_ADDRESS
    341 acpi_OsGetRootPointer(void)
    342 {
    343 	ACPI_PHYSICAL_ADDRESS PhysicalAddress;
    344 
    345 	/*
    346 	 * IA-32: Use AcpiFindRootPointer() to locate the RSDP.
    347 	 *
    348 	 * IA-64: Use the EFI.
    349 	 *
    350 	 * We let MD code handle this since there are multiple
    351 	 * ways to do it.
    352 	 */
    353 
    354 	PhysicalAddress = acpi_md_OsGetRootPointer();
    355 
    356 	if (acpi_root_pointer == 0)
    357 		acpi_root_pointer = PhysicalAddress;
    358 
    359 	return PhysicalAddress;
    360 }
    361 
    362 /*
    363  * acpi_match:
    364  *
    365  *	Autoconfiguration `match' routine.
    366  */
    367 static int
    368 acpi_match(device_t parent, struct cfdata *match, void *aux)
    369 {
    370 	/*
    371 	 * XXX Check other locators?  Hard to know -- machine
    372 	 * dependent code has already checked for the presence
    373 	 * of ACPI by calling acpi_probe(), so I suppose we
    374 	 * don't really have to do anything else.
    375 	 */
    376 	return 1;
    377 }
    378 
    379 /* Remove references to child devices.
    380  *
    381  * XXX Need to reclaim any resources?
    382  */
    383 static void
    384 acpi_childdet(device_t self, device_t child)
    385 {
    386 	struct acpi_softc *sc = device_private(self);
    387 	struct acpi_scope *as;
    388 	struct acpi_devnode *ad;
    389 
    390 	TAILQ_FOREACH(as, &sc->sc_scopes, as_list) {
    391 		TAILQ_FOREACH(ad, &as->as_devnodes, ad_list) {
    392 			if (ad->ad_device == child)
    393 				ad->ad_device = NULL;
    394 		}
    395 	}
    396 }
    397 
    398 /*
    399  * acpi_attach:
    400  *
    401  *	Autoconfiguration `attach' routine.  Finish initializing
    402  *	ACPICA (some initialization was done in acpi_probe(),
    403  *	which was required to check for the presence of ACPI),
    404  *	and enable the ACPI subsystem.
    405  */
    406 static void
    407 acpi_attach(device_t parent, device_t self, void *aux)
    408 {
    409 	struct acpi_softc *sc = device_private(self);
    410 	struct acpibus_attach_args *aa = aux;
    411 	ACPI_STATUS rv;
    412 	ACPI_TABLE_HEADER *rsdt;
    413 
    414 	aprint_naive("\n");
    415 	aprint_normal(": Intel ACPICA %08x\n", ACPI_CA_VERSION);
    416 
    417 	if (acpi_softc != NULL)
    418 		panic("acpi_attach: ACPI has already been attached");
    419 
    420 	sysmon_power_settype("acpi");
    421 
    422 	rsdt = acpi_map_rsdt();
    423 	if (rsdt) {
    424 		aprint_verbose_dev(
    425 		    self,
    426 		    "X/RSDT: OemId <%6.6s,%8.8s,%08x>, AslId <%4.4s,%08x>\n",
    427 		    rsdt->OemId, rsdt->OemTableId,
    428 		    rsdt->OemRevision,
    429 		    rsdt->AslCompilerId, rsdt->AslCompilerRevision);
    430 	} else
    431 		aprint_error_dev(self, "X/RSDT: Not found\n");
    432 	acpi_unmap_rsdt(rsdt);
    433 
    434 	sc->sc_dev = self;
    435 	sc->sc_quirks = acpi_find_quirks();
    436 
    437 	sc->sc_iot = aa->aa_iot;
    438 	sc->sc_memt = aa->aa_memt;
    439 	sc->sc_pc = aa->aa_pc;
    440 	sc->sc_pciflags = aa->aa_pciflags;
    441 	sc->sc_ic = aa->aa_ic;
    442 
    443 	acpi_softc = sc;
    444 
    445 	/*
    446 	 * Register null power management handler
    447 	 */
    448 	if (!pmf_device_register(self, acpi_suspend, acpi_resume))
    449 		aprint_error_dev(self, "couldn't establish power handler\n");
    450 
    451 	/*
    452 	 * Bring ACPI on-line.
    453 	 */
    454 #ifdef ACPI_DEBUGGER
    455 	if (acpi_dbgr & ACPI_DBGR_ENABLE)
    456 		acpi_osd_debugger();
    457 #endif
    458 
    459 #define ACPI_ENABLE_PHASE1 \
    460     (ACPI_NO_HANDLER_INIT | ACPI_NO_EVENT_INIT)
    461 #define ACPI_ENABLE_PHASE2 \
    462     (ACPI_NO_HARDWARE_INIT | ACPI_NO_ACPI_ENABLE | \
    463      ACPI_NO_ADDRESS_SPACE_INIT)
    464 
    465 	rv = AcpiEnableSubsystem(ACPI_ENABLE_PHASE1);
    466 	if (ACPI_FAILURE(rv)) {
    467 		aprint_error_dev(self, "unable to enable ACPI: %s\n",
    468 		    AcpiFormatException(rv));
    469 		return;
    470 	}
    471 
    472 	acpi_md_callback();
    473 
    474 	rv = AcpiEnableSubsystem(ACPI_ENABLE_PHASE2);
    475 	if (ACPI_FAILURE(rv)) {
    476 		aprint_error_dev(self, "unable to enable ACPI: %s\n",
    477 		    AcpiFormatException(rv));
    478 		return;
    479 	}
    480 
    481 	/* early EC handler initialization if ECDT table is available */
    482 	config_found_ia(self, "acpiecdtbus", NULL, NULL);
    483 
    484 	rv = AcpiInitializeObjects(ACPI_FULL_INITIALIZATION);
    485 	if (ACPI_FAILURE(rv)) {
    486 		aprint_error_dev(self,
    487 		    "unable to initialize ACPI objects: %s\n",
    488 		    AcpiFormatException(rv));
    489 		return;
    490 	}
    491 	acpi_active = 1;
    492 
    493 	/* Our current state is "awake". */
    494 	sc->sc_sleepstate = ACPI_STATE_S0;
    495 
    496 	/* Show SCI interrupt. */
    497 	aprint_verbose_dev(self, "SCI interrupting at int %d\n",
    498 	    AcpiGbl_FADT.SciInterrupt);
    499 
    500 	/*
    501 	 * Check for fixed-hardware features.
    502 	 */
    503 	acpi_enable_fixed_events(sc);
    504 	acpitimer_init();
    505 
    506 	/*
    507 	 * Scan the namespace and build our device tree.
    508 	 */
    509 #ifdef ACPI_DEBUGGER
    510 	if (acpi_dbgr & ACPI_DBGR_PROBE)
    511 		acpi_osd_debugger();
    512 #endif
    513 	acpi_build_tree(sc);
    514 
    515 	sprintf(acpi_supported_states, "%s%s%s%s%s%s",
    516 	    is_available_state(sc, ACPI_STATE_S0) ? "S0 " : "",
    517 	    is_available_state(sc, ACPI_STATE_S1) ? "S1 " : "",
    518 	    is_available_state(sc, ACPI_STATE_S2) ? "S2 " : "",
    519 	    is_available_state(sc, ACPI_STATE_S3) ? "S3 " : "",
    520 	    is_available_state(sc, ACPI_STATE_S4) ? "S4 " : "",
    521 	    is_available_state(sc, ACPI_STATE_S5) ? "S5 " : "");
    522 
    523 #ifdef ACPI_DEBUGGER
    524 	if (acpi_dbgr & ACPI_DBGR_RUNNING)
    525 		acpi_osd_debugger();
    526 #endif
    527 }
    528 
    529 static bool
    530 acpi_suspend(device_t dv PMF_FN_ARGS)
    531 {
    532 	acpi_suspended = 1;
    533 	return true;
    534 }
    535 
    536 static bool
    537 acpi_resume(device_t dv PMF_FN_ARGS)
    538 {
    539 	acpi_suspended = 0;
    540 	return true;
    541 }
    542 
    543 #if 0
    544 /*
    545  * acpi_disable:
    546  *
    547  *	Disable ACPI.
    548  */
    549 static ACPI_STATUS
    550 acpi_disable(struct acpi_softc *sc)
    551 {
    552 	ACPI_STATUS rv = AE_OK;
    553 
    554 	if (acpi_active) {
    555 		rv = AcpiDisable();
    556 		if (ACPI_SUCCESS(rv))
    557 			acpi_active = 0;
    558 	}
    559 	return rv;
    560 }
    561 #endif
    562 
    563 struct acpi_make_devnode_state {
    564 	struct acpi_softc *softc;
    565 	struct acpi_scope *scope;
    566 };
    567 
    568 /*
    569  * acpi_build_tree:
    570  *
    571  *	Scan relevant portions of the ACPI namespace and attach
    572  *	child devices.
    573  */
    574 static void
    575 acpi_build_tree(struct acpi_softc *sc)
    576 {
    577 	static const char *scopes[] = {
    578 		"\\_PR_",	/* ACPI 1.0 processor namespace */
    579 		"\\_SB_",	/* system bus namespace */
    580 		"\\_SI_",	/* system indicator namespace */
    581 		"\\_TZ_",	/* ACPI 1.0 thermal zone namespace */
    582 		NULL,
    583 	};
    584 	struct acpi_attach_args aa;
    585 	struct acpi_make_devnode_state state;
    586 	struct acpi_scope *as;
    587 	struct acpi_devnode *ad;
    588 	ACPI_HANDLE parent;
    589 	ACPI_STATUS rv;
    590 	int i;
    591 
    592 	TAILQ_INIT(&sc->sc_scopes);
    593 
    594 	state.softc = sc;
    595 
    596 	/*
    597 	 * Scan the namespace and build our tree.
    598 	 */
    599 	for (i = 0; scopes[i] != NULL; i++) {
    600 		as = malloc(sizeof(*as), M_ACPI, M_WAITOK);
    601 		as->as_name = scopes[i];
    602 		TAILQ_INIT(&as->as_devnodes);
    603 
    604 		TAILQ_INSERT_TAIL(&sc->sc_scopes, as, as_list);
    605 
    606 		state.scope = as;
    607 
    608 		rv = AcpiGetHandle(ACPI_ROOT_OBJECT, scopes[i],
    609 		    &parent);
    610 		if (ACPI_SUCCESS(rv)) {
    611 			AcpiWalkNamespace(ACPI_TYPE_ANY, parent, 100,
    612 			    acpi_make_devnode, &state, NULL);
    613 		}
    614 
    615 		/* Now, for this namespace, try and attach the devices. */
    616 		TAILQ_FOREACH(ad, &as->as_devnodes, ad_list) {
    617 			aa.aa_node = ad;
    618 			aa.aa_iot = sc->sc_iot;
    619 			aa.aa_memt = sc->sc_memt;
    620 			aa.aa_pc = sc->sc_pc;
    621 			aa.aa_pciflags = sc->sc_pciflags;
    622 			aa.aa_ic = sc->sc_ic;
    623 
    624 			if (ad->ad_devinfo->Type == ACPI_TYPE_DEVICE) {
    625 				/*
    626 				 * XXX We only attach devices which are:
    627 				 *
    628 				 *	- present
    629 				 *	- enabled
    630 				 *	- functioning properly
    631 				 *
    632 				 * However, if enabled, it's decoding resources,
    633 				 * so we should claim them, if possible.
    634 				 * Requires changes to bus_space(9).
    635 				 */
    636 				if ((ad->ad_devinfo->Valid & ACPI_VALID_STA) ==
    637 				    ACPI_VALID_STA &&
    638 				    (ad->ad_devinfo->CurrentStatus &
    639 				     (ACPI_STA_DEV_PRESENT|ACPI_STA_DEV_ENABLED|
    640 				      ACPI_STA_DEV_OK)) !=
    641 				    (ACPI_STA_DEV_PRESENT|ACPI_STA_DEV_ENABLED|
    642 				     ACPI_STA_DEV_OK))
    643 					continue;
    644 			}
    645 
    646 			/*
    647 			 * XXX Same problem as above...
    648 			 *
    649 			 * Do this check only for devices, as e.g.
    650 			 * a Thermal Zone doesn't have a HID.
    651 			 */
    652 			if (ad->ad_devinfo->Type == ACPI_TYPE_DEVICE &&
    653 			    (ad->ad_devinfo->Valid & ACPI_VALID_HID) == 0)
    654 				continue;
    655 
    656 			/*
    657 			 * Handled internally
    658 			 */
    659 			if (ad->ad_devinfo->Type == ACPI_TYPE_PROCESSOR ||
    660 			    ad->ad_devinfo->Type == ACPI_TYPE_POWER)
    661 				continue;
    662 
    663 			/*
    664 			 * Skip ignored HIDs
    665 			 */
    666 			if (acpi_match_hid(ad->ad_devinfo, acpi_ignored_ids))
    667 				continue;
    668 
    669 			ad->ad_device = config_found_ia(sc->sc_dev,
    670 			    "acpinodebus", &aa, acpi_print);
    671 		}
    672 	}
    673 	acpi_wakedev_scan(sc);
    674 
    675 	config_found_ia(sc->sc_dev, "acpiapmbus", NULL, NULL);
    676 }
    677 
    678 #ifdef ACPI_ACTIVATE_DEV
    679 static void
    680 acpi_activate_device(ACPI_HANDLE handle, ACPI_DEVICE_INFO **di)
    681 {
    682 	ACPI_STATUS rv;
    683 	ACPI_BUFFER buf;
    684 
    685 	buf.Pointer = NULL;
    686 	buf.Length = ACPI_ALLOCATE_BUFFER;
    687 
    688 #ifdef ACPI_DEBUG
    689 	aprint_normal("acpi_activate_device: %s, old status=%x\n",
    690 	       (*di)->HardwareId.Value, (*di)->CurrentStatus);
    691 #endif
    692 
    693 	rv = acpi_allocate_resources(handle);
    694 	if (ACPI_FAILURE(rv)) {
    695 		aprint_error("acpi: activate failed for %s\n",
    696 		       (*di)->HardwareId.Value);
    697 	} else {
    698 		aprint_verbose("acpi: activated %s\n",
    699 		    (*di)->HardwareId.Value);
    700 	}
    701 
    702 	(void)AcpiGetObjectInfo(handle, &buf);
    703 	AcpiOsFree(*di);
    704 	*di = buf.Pointer;
    705 
    706 #ifdef ACPI_DEBUG
    707 	aprint_normal("acpi_activate_device: %s, new status=%x\n",
    708 	       (*di)->HardwareId.Value, (*di)->CurrentStatus);
    709 #endif
    710 }
    711 #endif /* ACPI_ACTIVATE_DEV */
    712 
    713 /*
    714  * acpi_make_devnode:
    715  *
    716  *	Make an ACPI devnode.
    717  */
    718 static ACPI_STATUS
    719 acpi_make_devnode(ACPI_HANDLE handle, UINT32 level, void *context,
    720     void **status)
    721 {
    722 	struct acpi_make_devnode_state *state = context;
    723 #if defined(ACPI_DEBUG) || defined(ACPI_EXTRA_DEBUG)
    724 	struct acpi_softc *sc = state->softc;
    725 #endif
    726 	struct acpi_scope *as = state->scope;
    727 	struct acpi_devnode *ad;
    728 	ACPI_OBJECT_TYPE type;
    729 	ACPI_BUFFER buf;
    730 	ACPI_DEVICE_INFO *devinfo;
    731 	ACPI_STATUS rv;
    732 	ACPI_NAME_UNION *anu;
    733 	int i, clear = 0;
    734 
    735 	rv = AcpiGetType(handle, &type);
    736 	if (ACPI_SUCCESS(rv)) {
    737 		buf.Pointer = NULL;
    738 		buf.Length = ACPI_ALLOCATE_BUFFER;
    739 		rv = AcpiGetObjectInfo(handle, &buf);
    740 		if (ACPI_FAILURE(rv)) {
    741 #ifdef ACPI_DEBUG
    742 			aprint_normal_dev(sc->sc_dev,
    743 			    "AcpiGetObjectInfo failed: %s\n",
    744 			    AcpiFormatException(rv));
    745 #endif
    746 			goto out; /* XXX why return OK */
    747 		}
    748 
    749 		devinfo = buf.Pointer;
    750 
    751 		switch (type) {
    752 		case ACPI_TYPE_DEVICE:
    753 #ifdef ACPI_ACTIVATE_DEV
    754 			if ((devinfo->Valid & (ACPI_VALID_STA|ACPI_VALID_HID)) ==
    755 			    (ACPI_VALID_STA|ACPI_VALID_HID) &&
    756 			    (devinfo->CurrentStatus &
    757 			     (ACPI_STA_DEV_PRESENT|ACPI_STA_DEV_ENABLED)) ==
    758 			    ACPI_STA_DEV_PRESENT)
    759 				acpi_activate_device(handle, &devinfo);
    760 
    761 			/* FALLTHROUGH */
    762 #endif
    763 
    764 		case ACPI_TYPE_PROCESSOR:
    765 		case ACPI_TYPE_THERMAL:
    766 		case ACPI_TYPE_POWER:
    767 			ad = malloc(sizeof(*ad), M_ACPI, M_NOWAIT|M_ZERO);
    768 			if (ad == NULL)
    769 				return AE_NO_MEMORY;
    770 
    771 			ad->ad_devinfo = devinfo;
    772 			ad->ad_handle = handle;
    773 			ad->ad_level = level;
    774 			ad->ad_scope = as;
    775 			ad->ad_type = type;
    776 
    777 			anu = (ACPI_NAME_UNION *)&devinfo->Name;
    778 			ad->ad_name[4] = '\0';
    779 			for (i = 3, clear = 0; i >= 0; i--) {
    780 				if (!clear && anu->Ascii[i] == '_')
    781 					ad->ad_name[i] = '\0';
    782 				else {
    783 					ad->ad_name[i] = anu->Ascii[i];
    784 					clear = 1;
    785 				}
    786 			}
    787 			if (ad->ad_name[0] == '\0')
    788 				ad->ad_name[0] = '_';
    789 
    790 			TAILQ_INSERT_TAIL(&as->as_devnodes, ad, ad_list);
    791 
    792 			if (type == ACPI_TYPE_DEVICE &&
    793 			    (ad->ad_devinfo->Valid & ACPI_VALID_HID) == 0)
    794 				goto out;
    795 
    796 #ifdef ACPI_EXTRA_DEBUG
    797 			aprint_normal_dev(sc->sc_dev,
    798 			    "HID %s found in scope %s level %d\n",
    799 			    ad->ad_devinfo->HardwareId.Value,
    800 			    as->as_name, ad->ad_level);
    801 			if (ad->ad_devinfo->Valid & ACPI_VALID_UID)
    802 				aprint_normal("       UID %s\n",
    803 				    ad->ad_devinfo->UniqueId.Value);
    804 			if (ad->ad_devinfo->Valid & ACPI_VALID_ADR)
    805 				aprint_normal("       ADR 0x%016" PRIx64 "\n",
    806 				    ad->ad_devinfo->Address);
    807 			if (ad->ad_devinfo->Valid & ACPI_VALID_STA)
    808 				aprint_normal("       STA 0x%08x\n",
    809 				    ad->ad_devinfo->CurrentStatus);
    810 #endif
    811 		}
    812 	}
    813  out:
    814 	return AE_OK;
    815 }
    816 
    817 /*
    818  * acpi_print:
    819  *
    820  *	Autoconfiguration print routine for ACPI node bus.
    821  */
    822 static int
    823 acpi_print(void *aux, const char *pnp)
    824 {
    825 	struct acpi_attach_args *aa = aux;
    826 	ACPI_STATUS rv;
    827 
    828 	if (pnp) {
    829 		if (aa->aa_node->ad_devinfo->Valid & ACPI_VALID_HID) {
    830 			char *pnpstr =
    831 			    aa->aa_node->ad_devinfo->HardwareId.Value;
    832 			char *str;
    833 
    834 			aprint_normal("%s (%s) ", aa->aa_node->ad_name,
    835 			    pnpstr);
    836 			rv = acpi_eval_string(aa->aa_node->ad_handle,
    837 			    "_STR", &str);
    838 			if (ACPI_SUCCESS(rv)) {
    839 				aprint_normal("[%s] ", str);
    840 				AcpiOsFree(str);
    841 			}
    842 #ifdef ACPIVERBOSE
    843 			else {
    844 				int i;
    845 
    846 				for (i = 0; i < sizeof(acpi_knowndevs) /
    847 				    sizeof(acpi_knowndevs[0]); i++) {
    848 					if (strcmp(acpi_knowndevs[i].pnp,
    849 					    pnpstr) == 0) {
    850 						aprint_normal("[%s] ",
    851 						    acpi_knowndevs[i].str);
    852 					}
    853 				}
    854 			}
    855 
    856 #endif
    857 			aprint_normal("at %s", pnp);
    858 		} else if (aa->aa_node->ad_devinfo->Type != ACPI_TYPE_DEVICE) {
    859 			aprint_normal("%s (ACPI Object Type '%s' "
    860 			    "[0x%02x]) ", aa->aa_node->ad_name,
    861 			     AcpiUtGetTypeName(aa->aa_node->ad_devinfo->Type),
    862 			     aa->aa_node->ad_devinfo->Type);
    863 			aprint_normal("at %s", pnp);
    864 		} else
    865 			return 0;
    866 	} else {
    867 		aprint_normal(" (%s", aa->aa_node->ad_name);
    868 		if (aa->aa_node->ad_devinfo->Valid & ACPI_VALID_HID) {
    869 			aprint_normal(", %s", aa->aa_node->ad_devinfo->HardwareId.Value);
    870 			if (aa->aa_node->ad_devinfo->Valid & ACPI_VALID_UID) {
    871 				const char *uid;
    872 
    873 				uid = aa->aa_node->ad_devinfo->UniqueId.Value;
    874 				if (uid[0] == '\0')
    875 					uid = "<null>";
    876 				aprint_normal("-%s", uid);
    877 			}
    878 		}
    879 		aprint_normal(")");
    880 	}
    881 
    882 	return UNCONF;
    883 }
    884 
    885 /*****************************************************************************
    886  * ACPI fixed-hardware feature handlers
    887  *****************************************************************************/
    888 
    889 static UINT32	acpi_fixed_button_handler(void *);
    890 static void	acpi_fixed_button_pressed(void *);
    891 
    892 /*
    893  * acpi_enable_fixed_events:
    894  *
    895  *	Enable any fixed-hardware feature handlers.
    896  */
    897 static void
    898 acpi_enable_fixed_events(struct acpi_softc *sc)
    899 {
    900 	static int beenhere;
    901 	ACPI_STATUS rv;
    902 
    903 	KASSERT(beenhere == 0);
    904 	beenhere = 1;
    905 
    906 	/*
    907 	 * Check for fixed-hardware buttons.
    908 	 */
    909 
    910 	if ((AcpiGbl_FADT.Flags & ACPI_FADT_POWER_BUTTON) == 0) {
    911 		aprint_verbose_dev(sc->sc_dev,
    912 		    "fixed-feature power button present\n");
    913 		sc->sc_smpsw_power.smpsw_name = device_xname(sc->sc_dev);
    914 		sc->sc_smpsw_power.smpsw_type = PSWITCH_TYPE_POWER;
    915 		if (sysmon_pswitch_register(&sc->sc_smpsw_power) != 0) {
    916 			aprint_error_dev(sc->sc_dev,
    917 			    "unable to register fixed power "
    918 			    "button with sysmon\n");
    919 		} else {
    920 			rv = AcpiInstallFixedEventHandler(
    921 			    ACPI_EVENT_POWER_BUTTON,
    922 			    acpi_fixed_button_handler, &sc->sc_smpsw_power);
    923 			if (ACPI_FAILURE(rv)) {
    924 				aprint_error_dev(sc->sc_dev,
    925 				    "unable to install handler "
    926 				    "for fixed power button: %s\n",
    927 				    AcpiFormatException(rv));
    928 			}
    929 		}
    930 	}
    931 
    932 	if ((AcpiGbl_FADT.Flags & ACPI_FADT_SLEEP_BUTTON) == 0) {
    933 		aprint_verbose_dev(sc->sc_dev,
    934 		    "fixed-feature sleep button present\n");
    935 		sc->sc_smpsw_sleep.smpsw_name = device_xname(sc->sc_dev);
    936 		sc->sc_smpsw_sleep.smpsw_type = PSWITCH_TYPE_SLEEP;
    937 		if (sysmon_pswitch_register(&sc->sc_smpsw_power) != 0) {
    938 			aprint_error_dev(sc->sc_dev,
    939 			    "unable to register fixed sleep "
    940 			    "button with sysmon\n");
    941 		} else {
    942 			rv = AcpiInstallFixedEventHandler(
    943 			    ACPI_EVENT_SLEEP_BUTTON,
    944 			    acpi_fixed_button_handler, &sc->sc_smpsw_sleep);
    945 			if (ACPI_FAILURE(rv)) {
    946 				aprint_error_dev(sc->sc_dev,
    947 				    "unable to install handler "
    948 				    "for fixed sleep button: %s\n",
    949 				    AcpiFormatException(rv));
    950 			}
    951 		}
    952 	}
    953 }
    954 
    955 /*
    956  * acpi_fixed_button_handler:
    957  *
    958  *	Event handler for the fixed buttons.
    959  */
    960 static UINT32
    961 acpi_fixed_button_handler(void *context)
    962 {
    963 	struct sysmon_pswitch *smpsw = context;
    964 	int rv;
    965 
    966 #ifdef ACPI_BUT_DEBUG
    967 	printf("%s: fixed button handler\n", smpsw->smpsw_name);
    968 #endif
    969 
    970 	rv = AcpiOsExecute(OSL_NOTIFY_HANDLER,
    971 	    acpi_fixed_button_pressed, smpsw);
    972 	if (ACPI_FAILURE(rv))
    973 		printf("%s: WARNING: unable to queue fixed button pressed "
    974 		    "callback: %s\n", smpsw->smpsw_name,
    975 		    AcpiFormatException(rv));
    976 
    977 	return ACPI_INTERRUPT_HANDLED;
    978 }
    979 
    980 /*
    981  * acpi_fixed_button_pressed:
    982  *
    983  *	Deal with a fixed button being pressed.
    984  */
    985 static void
    986 acpi_fixed_button_pressed(void *context)
    987 {
    988 	struct sysmon_pswitch *smpsw = context;
    989 
    990 #ifdef ACPI_BUT_DEBUG
    991 	printf("%s: fixed button pressed, calling sysmon\n",
    992 	    smpsw->smpsw_name);
    993 #endif
    994 
    995 	sysmon_pswitch_event(smpsw, PSWITCH_EVENT_PRESSED);
    996 }
    997 
    998 /*****************************************************************************
    999  * ACPI utility routines.
   1000  *****************************************************************************/
   1001 
   1002 /*
   1003  * acpi_eval_integer:
   1004  *
   1005  *	Evaluate an integer object.
   1006  */
   1007 ACPI_STATUS
   1008 acpi_eval_integer(ACPI_HANDLE handle, const char *path, ACPI_INTEGER *valp)
   1009 {
   1010 	ACPI_STATUS rv;
   1011 	ACPI_BUFFER buf;
   1012 	ACPI_OBJECT param;
   1013 
   1014 	if (handle == NULL)
   1015 		handle = ACPI_ROOT_OBJECT;
   1016 
   1017 	buf.Pointer = &param;
   1018 	buf.Length = sizeof(param);
   1019 
   1020 	rv = AcpiEvaluateObjectTyped(handle, path, NULL, &buf, ACPI_TYPE_INTEGER);
   1021 	if (ACPI_SUCCESS(rv))
   1022 		*valp = param.Integer.Value;
   1023 
   1024 	return rv;
   1025 }
   1026 
   1027 /*
   1028  * acpi_eval_string:
   1029  *
   1030  *	Evaluate a (Unicode) string object.
   1031  */
   1032 ACPI_STATUS
   1033 acpi_eval_string(ACPI_HANDLE handle, const char *path, char **stringp)
   1034 {
   1035 	ACPI_STATUS rv;
   1036 	ACPI_BUFFER buf;
   1037 
   1038 	if (handle == NULL)
   1039 		handle = ACPI_ROOT_OBJECT;
   1040 
   1041 	buf.Pointer = NULL;
   1042 	buf.Length = ACPI_ALLOCATE_BUFFER;
   1043 
   1044 	rv = AcpiEvaluateObjectTyped(handle, path, NULL, &buf, ACPI_TYPE_STRING);
   1045 	if (ACPI_SUCCESS(rv)) {
   1046 		ACPI_OBJECT *param = buf.Pointer;
   1047 		const char *ptr = param->String.Pointer;
   1048 		size_t len = param->String.Length;
   1049 		if ((*stringp = AcpiOsAllocate(len)) == NULL)
   1050 			rv = AE_NO_MEMORY;
   1051 		else
   1052 			(void)memcpy(*stringp, ptr, len);
   1053 		AcpiOsFree(param);
   1054 	}
   1055 
   1056 	return rv;
   1057 }
   1058 
   1059 
   1060 /*
   1061  * acpi_eval_struct:
   1062  *
   1063  *	Evaluate a more complex structure.
   1064  *	Caller must free buf.Pointer by AcpiOsFree().
   1065  */
   1066 ACPI_STATUS
   1067 acpi_eval_struct(ACPI_HANDLE handle, const char *path, ACPI_BUFFER *bufp)
   1068 {
   1069 	ACPI_STATUS rv;
   1070 
   1071 	if (handle == NULL)
   1072 		handle = ACPI_ROOT_OBJECT;
   1073 
   1074 	bufp->Pointer = NULL;
   1075 	bufp->Length = ACPI_ALLOCATE_BUFFER;
   1076 
   1077 	rv = AcpiEvaluateObject(handle, path, NULL, bufp);
   1078 
   1079 	return rv;
   1080 }
   1081 
   1082 /*
   1083  * acpi_foreach_package_object:
   1084  *
   1085  *	Iterate over all objects in a in a packages and pass then all
   1086  *	to a function. If the called function returns non AE_OK, the
   1087  *	iteration is stopped and that value is returned.
   1088  */
   1089 
   1090 ACPI_STATUS
   1091 acpi_foreach_package_object(ACPI_OBJECT *pkg,
   1092     ACPI_STATUS (*func)(ACPI_OBJECT *, void *),
   1093     void *arg)
   1094 {
   1095 	ACPI_STATUS rv = AE_OK;
   1096 	int i;
   1097 
   1098 	if (pkg == NULL || pkg->Type != ACPI_TYPE_PACKAGE)
   1099 		return AE_BAD_PARAMETER;
   1100 
   1101 	for (i = 0; i < pkg->Package.Count; i++) {
   1102 		rv = (*func)(&pkg->Package.Elements[i], arg);
   1103 		if (ACPI_FAILURE(rv))
   1104 			break;
   1105 	}
   1106 
   1107 	return rv;
   1108 }
   1109 
   1110 const char *
   1111 acpi_name(ACPI_HANDLE handle)
   1112 {
   1113 	static char buffer[80];
   1114 	ACPI_BUFFER buf;
   1115 	ACPI_STATUS rv;
   1116 
   1117 	buf.Length = sizeof(buffer);
   1118 	buf.Pointer = buffer;
   1119 
   1120 	rv = AcpiGetName(handle, ACPI_FULL_PATHNAME, &buf);
   1121 	if (ACPI_FAILURE(rv))
   1122 		return "(unknown acpi path)";
   1123 	return buffer;
   1124 }
   1125 
   1126 /*
   1127  * acpi_get:
   1128  *
   1129  *	Fetch data info the specified (empty) ACPI buffer.
   1130  *	Caller must free buf.Pointer by AcpiOsFree().
   1131  */
   1132 ACPI_STATUS
   1133 acpi_get(ACPI_HANDLE handle, ACPI_BUFFER *buf,
   1134     ACPI_STATUS (*getit)(ACPI_HANDLE, ACPI_BUFFER *))
   1135 {
   1136 	buf->Pointer = NULL;
   1137 	buf->Length = ACPI_ALLOCATE_BUFFER;
   1138 
   1139 	return (*getit)(handle, buf);
   1140 }
   1141 
   1142 
   1143 /*
   1144  * acpi_match_hid
   1145  *
   1146  *	Match given ids against _HID and _CIDs
   1147  */
   1148 int
   1149 acpi_match_hid(ACPI_DEVICE_INFO *ad, const char * const *ids)
   1150 {
   1151 	int i;
   1152 
   1153 	while (*ids) {
   1154 		if (ad->Valid & ACPI_VALID_HID) {
   1155 			if (pmatch(ad->HardwareId.Value, *ids, NULL) == 2)
   1156 				return 1;
   1157 		}
   1158 
   1159 		if (ad->Valid & ACPI_VALID_CID) {
   1160 			for (i = 0; i < ad->CompatibilityId.Count; i++) {
   1161 				if (pmatch(ad->CompatibilityId.Id[i].Value, *ids, NULL) == 2)
   1162 					return 1;
   1163 			}
   1164 		}
   1165 		ids++;
   1166 	}
   1167 
   1168 	return 0;
   1169 }
   1170 
   1171 /*
   1172  * acpi_wake_gpe_helper
   1173  *
   1174  *	Set/unset GPE as both Runtime and Wake
   1175  */
   1176 static void
   1177 acpi_wake_gpe_helper(ACPI_HANDLE handle, bool enable)
   1178 {
   1179 	ACPI_BUFFER buf;
   1180 	ACPI_STATUS rv;
   1181 	ACPI_OBJECT *p, *elt;
   1182 
   1183 	rv = acpi_eval_struct(handle, METHOD_NAME__PRW, &buf);
   1184 	if (ACPI_FAILURE(rv))
   1185 		return;			/* just ignore */
   1186 
   1187 	p = buf.Pointer;
   1188 	if (p->Type != ACPI_TYPE_PACKAGE || p->Package.Count < 2)
   1189 		goto out;		/* just ignore */
   1190 
   1191 	elt = p->Package.Elements;
   1192 
   1193 	/* TBD: package support */
   1194 	if (enable) {
   1195 		AcpiSetGpeType(NULL, elt[0].Integer.Value,
   1196 		    ACPI_GPE_TYPE_WAKE_RUN);
   1197 		AcpiEnableGpe(NULL, elt[0].Integer.Value, ACPI_NOT_ISR);
   1198 	} else
   1199 		AcpiDisableGpe(NULL, elt[0].Integer.Value, ACPI_NOT_ISR);
   1200 
   1201  out:
   1202 	AcpiOsFree(buf.Pointer);
   1203 }
   1204 
   1205 /*
   1206  * acpi_clear_wake_gpe
   1207  *
   1208  *	Clear GPE as both Runtime and Wake
   1209  */
   1210 void
   1211 acpi_clear_wake_gpe(ACPI_HANDLE handle)
   1212 {
   1213 	acpi_wake_gpe_helper(handle, false);
   1214 }
   1215 
   1216 /*
   1217  * acpi_set_wake_gpe
   1218  *
   1219  *	Set GPE as both Runtime and Wake
   1220  */
   1221 void
   1222 acpi_set_wake_gpe(ACPI_HANDLE handle)
   1223 {
   1224 	acpi_wake_gpe_helper(handle, true);
   1225 }
   1226 
   1227 
   1228 /*****************************************************************************
   1229  * ACPI sleep support.
   1230  *****************************************************************************/
   1231 
   1232 static int
   1233 is_available_state(struct acpi_softc *sc, int state)
   1234 {
   1235 	UINT8 type_a, type_b;
   1236 
   1237 	return ACPI_SUCCESS(AcpiGetSleepTypeData((UINT8)state,
   1238 				&type_a, &type_b));
   1239 }
   1240 
   1241 /*
   1242  * acpi_enter_sleep_state:
   1243  *
   1244  *	enter to the specified sleep state.
   1245  */
   1246 
   1247 ACPI_STATUS
   1248 acpi_enter_sleep_state(struct acpi_softc *sc, int state)
   1249 {
   1250 	int err;
   1251 	ACPI_STATUS ret = AE_OK;
   1252 
   1253 	if (state == acpi_sleepstate)
   1254 		return AE_OK;
   1255 
   1256 	aprint_normal_dev(sc->sc_dev, "entering state %d\n", state);
   1257 
   1258 	switch (state) {
   1259 	case ACPI_STATE_S0:
   1260 		break;
   1261 	case ACPI_STATE_S1:
   1262 	case ACPI_STATE_S2:
   1263 	case ACPI_STATE_S3:
   1264 	case ACPI_STATE_S4:
   1265 		if (!is_available_state(sc, state)) {
   1266 			aprint_error_dev(sc->sc_dev,
   1267 			    "ACPI S%d not available on this platform\n", state);
   1268 			break;
   1269 		}
   1270 
   1271 		acpi_wakedev_commit(sc);
   1272 
   1273 		if (state != ACPI_STATE_S1 && !pmf_system_suspend(PMF_F_NONE)) {
   1274 			aprint_error_dev(sc->sc_dev, "aborting suspend\n");
   1275 			break;
   1276 		}
   1277 
   1278 		ret = AcpiEnterSleepStatePrep(state);
   1279 		if (ACPI_FAILURE(ret)) {
   1280 			aprint_error_dev(sc->sc_dev,
   1281 			    "failed preparing to sleep (%s)\n",
   1282 			    AcpiFormatException(ret));
   1283 			break;
   1284 		}
   1285 
   1286 		acpi_sleepstate = state;
   1287 		if (state == ACPI_STATE_S1) {
   1288 			/* just enter the state */
   1289 			acpi_md_OsDisableInterrupt();
   1290 			ret = AcpiEnterSleepState((UINT8)state);
   1291 			if (ACPI_FAILURE(ret))
   1292 				aprint_error_dev(sc->sc_dev,
   1293 				    "failed to enter sleep state S1: %s\n",
   1294 				    AcpiFormatException(ret));
   1295 			AcpiLeaveSleepState((UINT8)state);
   1296 		} else {
   1297 			err = acpi_md_sleep(state);
   1298 			if (state == ACPI_STATE_S4)
   1299 				AcpiEnable();
   1300 			pmf_system_bus_resume(PMF_F_NONE);
   1301 			AcpiLeaveSleepState((UINT8)state);
   1302 			pmf_system_resume(PMF_F_NONE);
   1303 		}
   1304 
   1305 		break;
   1306 	case ACPI_STATE_S5:
   1307 		ret = AcpiEnterSleepStatePrep(ACPI_STATE_S5);
   1308 		if (ACPI_FAILURE(ret)) {
   1309 			aprint_error_dev(sc->sc_dev,
   1310 			    "failed preparing to sleep (%s)\n",
   1311 			    AcpiFormatException(ret));
   1312 			break;
   1313 		}
   1314 		DELAY(1000000);
   1315 		acpi_sleepstate = state;
   1316 		acpi_md_OsDisableInterrupt();
   1317 		AcpiEnterSleepState(ACPI_STATE_S5);
   1318 		aprint_error_dev(sc->sc_dev, "WARNING powerdown failed!\n");
   1319 		break;
   1320 	}
   1321 
   1322 	acpi_sleepstate = ACPI_STATE_S0;
   1323 	return ret;
   1324 }
   1325 
   1326 #if defined(ACPI_ACTIVATE_DEV)
   1327 /* XXX This very incomplete */
   1328 ACPI_STATUS
   1329 acpi_allocate_resources(ACPI_HANDLE handle)
   1330 {
   1331 	ACPI_BUFFER bufp, bufc, bufn;
   1332 	ACPI_RESOURCE *resp, *resc, *resn;
   1333 	ACPI_RESOURCE_IRQ *irq;
   1334 	ACPI_RESOURCE_EXTENDED_IRQ *xirq;
   1335 	ACPI_STATUS rv;
   1336 	uint delta;
   1337 
   1338 	rv = acpi_get(handle, &bufp, AcpiGetPossibleResources);
   1339 	if (ACPI_FAILURE(rv))
   1340 		goto out;
   1341 	rv = acpi_get(handle, &bufc, AcpiGetCurrentResources);
   1342 	if (ACPI_FAILURE(rv)) {
   1343 		goto out1;
   1344 	}
   1345 
   1346 	bufn.Length = 1000;
   1347 	bufn.Pointer = resn = malloc(bufn.Length, M_ACPI, M_WAITOK);
   1348 	resp = bufp.Pointer;
   1349 	resc = bufc.Pointer;
   1350 	while (resc->Type != ACPI_RESOURCE_TYPE_END_TAG &&
   1351 	       resp->Type != ACPI_RESOURCE_TYPE_END_TAG) {
   1352 		while (resc->Type != resp->Type && resp->Type != ACPI_RESOURCE_TYPE_END_TAG)
   1353 			resp = ACPI_NEXT_RESOURCE(resp);
   1354 		if (resp->Type == ACPI_RESOURCE_TYPE_END_TAG)
   1355 			break;
   1356 		/* Found identical Id */
   1357 		resn->Type = resc->Type;
   1358 		switch (resc->Type) {
   1359 		case ACPI_RESOURCE_TYPE_IRQ:
   1360 			memcpy(&resn->Data, &resp->Data,
   1361 			       sizeof(ACPI_RESOURCE_IRQ));
   1362 			irq = (ACPI_RESOURCE_IRQ *)&resn->Data;
   1363 			irq->Interrupts[0] =
   1364 			    ((ACPI_RESOURCE_IRQ *)&resp->Data)->
   1365 			        Interrupts[irq->InterruptCount-1];
   1366 			irq->InterruptCount = 1;
   1367 			resn->Length = ACPI_RS_SIZE(ACPI_RESOURCE_IRQ);
   1368 			break;
   1369 		case ACPI_RESOURCE_TYPE_EXTENDED_IRQ:
   1370 			memcpy(&resn->Data, &resp->Data,
   1371 			       sizeof(ACPI_RESOURCE_EXTENDED_IRQ));
   1372 			xirq = (ACPI_RESOURCE_EXTENDED_IRQ *)&resn->Data;
   1373 #if 0
   1374 			/*
   1375 			 * XXX not duplicating the interrupt logic above
   1376 			 * because its not clear what it accomplishes.
   1377 			 */
   1378 			xirq->Interrupts[0] =
   1379 			    ((ACPI_RESOURCE_EXT_IRQ *)&resp->Data)->
   1380 			    Interrupts[irq->NumberOfInterrupts-1];
   1381 			xirq->NumberOfInterrupts = 1;
   1382 #endif
   1383 			resn->Length = ACPI_RS_SIZE(ACPI_RESOURCE_EXTENDED_IRQ);
   1384 			break;
   1385 		case ACPI_RESOURCE_TYPE_IO:
   1386 			memcpy(&resn->Data, &resp->Data,
   1387 			       sizeof(ACPI_RESOURCE_IO));
   1388 			resn->Length = resp->Length;
   1389 			break;
   1390 		default:
   1391 			printf("acpi_allocate_resources: res=%d\n", resc->Type);
   1392 			rv = AE_BAD_DATA;
   1393 			goto out2;
   1394 		}
   1395 		resc = ACPI_NEXT_RESOURCE(resc);
   1396 		resn = ACPI_NEXT_RESOURCE(resn);
   1397 		resp = ACPI_NEXT_RESOURCE(resp);
   1398 		delta = (UINT8 *)resn - (UINT8 *)bufn.Pointer;
   1399 		if (delta >=
   1400 		    bufn.Length-ACPI_RS_SIZE(ACPI_RESOURCE_DATA)) {
   1401 			bufn.Length *= 2;
   1402 			bufn.Pointer = realloc(bufn.Pointer, bufn.Length,
   1403 					       M_ACPI, M_WAITOK);
   1404 			resn = (ACPI_RESOURCE *)((UINT8 *)bufn.Pointer + delta);
   1405 		}
   1406 	}
   1407 	if (resc->Type != ACPI_RESOURCE_TYPE_END_TAG) {
   1408 		printf("acpi_allocate_resources: resc not exhausted\n");
   1409 		rv = AE_BAD_DATA;
   1410 		goto out3;
   1411 	}
   1412 
   1413 	resn->Type = ACPI_RESOURCE_TYPE_END_TAG;
   1414 	rv = AcpiSetCurrentResources(handle, &bufn);
   1415 	if (ACPI_FAILURE(rv)) {
   1416 		printf("acpi_allocate_resources: AcpiSetCurrentResources %s\n",
   1417 		       AcpiFormatException(rv));
   1418 	}
   1419 
   1420 out3:
   1421 	free(bufn.Pointer, M_ACPI);
   1422 out2:
   1423 	AcpiOsFree(bufc.Pointer);
   1424 out1:
   1425 	AcpiOsFree(bufp.Pointer);
   1426 out:
   1427 	return rv;
   1428 }
   1429 #endif /* ACPI_ACTIVATE_DEV */
   1430 
   1431 SYSCTL_SETUP(sysctl_acpi_setup, "sysctl hw.acpi subtree setup")
   1432 {
   1433 	const struct sysctlnode *node;
   1434 	const struct sysctlnode *ssnode;
   1435 
   1436 	if (sysctl_createv(clog, 0, NULL, NULL,
   1437 	    CTLFLAG_PERMANENT,
   1438 	    CTLTYPE_NODE, "hw", NULL,
   1439 	    NULL, 0, NULL, 0,
   1440 	    CTL_HW, CTL_EOL) != 0)
   1441 		return;
   1442 
   1443 	if (sysctl_createv(clog, 0, NULL, &node,
   1444 	    CTLFLAG_PERMANENT,
   1445 	    CTLTYPE_NODE, "acpi", NULL,
   1446 	    NULL, 0, NULL, 0,
   1447 	    CTL_HW, CTL_CREATE, CTL_EOL) != 0)
   1448 		return;
   1449 
   1450 	sysctl_createv(NULL, 0, NULL, NULL, CTLFLAG_READONLY,
   1451 	    CTLTYPE_QUAD, "root",
   1452 	    SYSCTL_DESCR("ACPI root pointer"),
   1453 	    NULL, 0, &acpi_root_pointer, sizeof(acpi_root_pointer),
   1454 	    CTL_HW, node->sysctl_num, CTL_CREATE, CTL_EOL);
   1455 	sysctl_createv(NULL, 0, NULL, NULL, CTLFLAG_READONLY,
   1456 	    CTLTYPE_STRING, "supported_states",
   1457 	    SYSCTL_DESCR("Supported ACPI system states"),
   1458 	    NULL, 0, acpi_supported_states, 0,
   1459 	    CTL_HW, node->sysctl_num, CTL_CREATE, CTL_EOL);
   1460 
   1461 	/* ACPI sleepstate sysctl */
   1462 	if (sysctl_createv(NULL, 0, NULL, &node,
   1463 	    CTLFLAG_PERMANENT,
   1464 	    CTLTYPE_NODE, "machdep", NULL,
   1465 	    NULL, 0, NULL, 0, CTL_MACHDEP, CTL_EOL) != 0)
   1466 		return;
   1467 	if (sysctl_createv(NULL, 0, &node, &ssnode,
   1468 	    CTLFLAG_READWRITE, CTLTYPE_INT, "sleep_state",
   1469 	    NULL, sysctl_hw_acpi_sleepstate, 0, NULL, 0, CTL_CREATE,
   1470 	    CTL_EOL) != 0)
   1471 		return;
   1472 }
   1473 
   1474 static int
   1475 sysctl_hw_acpi_sleepstate(SYSCTLFN_ARGS)
   1476 {
   1477 	int error, t;
   1478 	struct sysctlnode node;
   1479 
   1480 	node = *rnode;
   1481 	t = acpi_sleepstate;
   1482 	node.sysctl_data = &t;
   1483 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
   1484 	if (error || newp == NULL)
   1485 		return error;
   1486 
   1487 	if (acpi_softc == NULL)
   1488 		return ENOSYS;
   1489 
   1490 	acpi_enter_sleep_state(acpi_softc, t);
   1491 
   1492 	return 0;
   1493 }
   1494 
   1495 static ACPI_TABLE_HEADER *
   1496 acpi_map_rsdt(void)
   1497 {
   1498 	ACPI_PHYSICAL_ADDRESS paddr;
   1499 	ACPI_TABLE_RSDP *rsdp;
   1500 
   1501 	paddr = AcpiOsGetRootPointer();
   1502 	if (paddr == 0) {
   1503 		printf("ACPI: couldn't get root pointer\n");
   1504 		return NULL;
   1505 	}
   1506 	rsdp = AcpiOsMapMemory(paddr, sizeof(ACPI_TABLE_RSDP));
   1507 	if (rsdp == NULL) {
   1508 		printf("ACPI: couldn't map RSDP\n");
   1509 		return NULL;
   1510 	}
   1511 	if (rsdp->Revision > 1 && rsdp->XsdtPhysicalAddress)
   1512 		paddr = (ACPI_PHYSICAL_ADDRESS)rsdp->XsdtPhysicalAddress;
   1513 	else
   1514 		paddr = (ACPI_PHYSICAL_ADDRESS)rsdp->RsdtPhysicalAddress;
   1515 	AcpiOsUnmapMemory(rsdp, sizeof(ACPI_TABLE_RSDP));
   1516 
   1517 	return AcpiOsMapMemory(paddr, sizeof(ACPI_TABLE_HEADER));
   1518 }
   1519 
   1520 static void
   1521 acpi_unmap_rsdt(ACPI_TABLE_HEADER *rsdt)
   1522 {
   1523 	if (rsdt == NULL)
   1524 		return;
   1525 
   1526 	AcpiOsUnmapMemory(rsdt, sizeof(ACPI_TABLE_HEADER));
   1527 }
   1528