acpi.c revision 159476
1/*-
2 * Copyright (c) 2000 Takanori Watanabe <takawata@jp.freebsd.org>
3 * Copyright (c) 2000 Mitsuru IWASAKI <iwasaki@jp.freebsd.org>
4 * Copyright (c) 2000, 2001 Michael Smith
5 * Copyright (c) 2000 BSDi
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
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 the
15 *    documentation and/or other materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 */
29
30#include <sys/cdefs.h>
31__FBSDID("$FreeBSD: head/sys/dev/acpica/acpi.c 159476 2006-06-10 08:04:38Z njl $");
32
33#include "opt_acpi.h"
34#include <sys/param.h>
35#include <sys/kernel.h>
36#include <sys/proc.h>
37#include <sys/fcntl.h>
38#include <sys/malloc.h>
39#include <sys/module.h>
40#include <sys/bus.h>
41#include <sys/conf.h>
42#include <sys/ioccom.h>
43#include <sys/reboot.h>
44#include <sys/sysctl.h>
45#include <sys/ctype.h>
46#include <sys/linker.h>
47#include <sys/power.h>
48#include <sys/sbuf.h>
49#include <sys/smp.h>
50
51#include <machine/resource.h>
52#include <machine/bus.h>
53#include <sys/rman.h>
54#include <isa/isavar.h>
55#include <isa/pnpvar.h>
56
57#include <contrib/dev/acpica/acpi.h>
58#include <dev/acpica/acpivar.h>
59#include <dev/acpica/acpiio.h>
60#include <contrib/dev/acpica/achware.h>
61#include <contrib/dev/acpica/acnamesp.h>
62
63#include "pci_if.h"
64#include <dev/pci/pcivar.h>
65#include <dev/pci/pci_private.h>
66
67MALLOC_DEFINE(M_ACPIDEV, "acpidev", "ACPI devices");
68
69/* Hooks for the ACPI CA debugging infrastructure */
70#define _COMPONENT	ACPI_BUS
71ACPI_MODULE_NAME("ACPI")
72
73static d_open_t		acpiopen;
74static d_close_t	acpiclose;
75static d_ioctl_t	acpiioctl;
76
77static struct cdevsw acpi_cdevsw = {
78	.d_version =	D_VERSION,
79	.d_open =	acpiopen,
80	.d_close =	acpiclose,
81	.d_ioctl =	acpiioctl,
82	.d_name =	"acpi",
83};
84
85/* Global mutex for locking access to the ACPI subsystem. */
86struct mtx	acpi_mutex;
87
88/* Bitmap of device quirks. */
89int		acpi_quirks;
90
91static int	acpi_modevent(struct module *mod, int event, void *junk);
92static void	acpi_identify(driver_t *driver, device_t parent);
93static int	acpi_probe(device_t dev);
94static int	acpi_attach(device_t dev);
95static int	acpi_suspend(device_t dev);
96static int	acpi_resume(device_t dev);
97static int	acpi_shutdown(device_t dev);
98static device_t	acpi_add_child(device_t bus, int order, const char *name,
99			int unit);
100static int	acpi_print_child(device_t bus, device_t child);
101static void	acpi_probe_nomatch(device_t bus, device_t child);
102static void	acpi_driver_added(device_t dev, driver_t *driver);
103static int	acpi_read_ivar(device_t dev, device_t child, int index,
104			uintptr_t *result);
105static int	acpi_write_ivar(device_t dev, device_t child, int index,
106			uintptr_t value);
107static struct resource_list *acpi_get_rlist(device_t dev, device_t child);
108static int	acpi_sysres_alloc(device_t dev);
109static struct resource_list_entry *acpi_sysres_find(device_t dev, int type,
110		    u_long addr);
111static struct resource *acpi_alloc_resource(device_t bus, device_t child,
112			int type, int *rid, u_long start, u_long end,
113			u_long count, u_int flags);
114static int	acpi_release_resource(device_t bus, device_t child, int type,
115			int rid, struct resource *r);
116static void	acpi_delete_resource(device_t bus, device_t child, int type,
117		    int rid);
118static uint32_t	acpi_isa_get_logicalid(device_t dev);
119static int	acpi_isa_get_compatid(device_t dev, uint32_t *cids, int count);
120static char	*acpi_device_id_probe(device_t bus, device_t dev, char **ids);
121static ACPI_STATUS acpi_device_eval_obj(device_t bus, device_t dev,
122		    ACPI_STRING pathname, ACPI_OBJECT_LIST *parameters,
123		    ACPI_BUFFER *ret);
124static int	acpi_device_pwr_for_sleep(device_t bus, device_t dev,
125		    int *dstate);
126static ACPI_STATUS acpi_device_scan_cb(ACPI_HANDLE h, UINT32 level,
127		    void *context, void **retval);
128static ACPI_STATUS acpi_device_scan_children(device_t bus, device_t dev,
129		    int max_depth, acpi_scan_cb_t user_fn, void *arg);
130static int	acpi_set_powerstate_method(device_t bus, device_t child,
131		    int state);
132static int	acpi_isa_pnp_probe(device_t bus, device_t child,
133		    struct isa_pnp_id *ids);
134static void	acpi_probe_children(device_t bus);
135static int	acpi_probe_order(ACPI_HANDLE handle, int *order);
136static ACPI_STATUS acpi_probe_child(ACPI_HANDLE handle, UINT32 level,
137		    void *context, void **status);
138static BOOLEAN	acpi_MatchHid(ACPI_HANDLE h, const char *hid);
139static void	acpi_shutdown_final(void *arg, int howto);
140static void	acpi_enable_fixed_events(struct acpi_softc *sc);
141static int	acpi_wake_sleep_prep(ACPI_HANDLE handle, int sstate);
142static int	acpi_wake_run_prep(ACPI_HANDLE handle, int sstate);
143static int	acpi_wake_prep_walk(int sstate);
144static int	acpi_wake_sysctl_walk(device_t dev);
145static int	acpi_wake_set_sysctl(SYSCTL_HANDLER_ARGS);
146static void	acpi_system_eventhandler_sleep(void *arg, int state);
147static void	acpi_system_eventhandler_wakeup(void *arg, int state);
148static int	acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS);
149static int	acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS);
150static int	acpi_pm_func(u_long cmd, void *arg, ...);
151static int	acpi_child_location_str_method(device_t acdev, device_t child,
152					       char *buf, size_t buflen);
153static int	acpi_child_pnpinfo_str_method(device_t acdev, device_t child,
154					      char *buf, size_t buflen);
155
156static device_method_t acpi_methods[] = {
157    /* Device interface */
158    DEVMETHOD(device_identify,		acpi_identify),
159    DEVMETHOD(device_probe,		acpi_probe),
160    DEVMETHOD(device_attach,		acpi_attach),
161    DEVMETHOD(device_shutdown,		acpi_shutdown),
162    DEVMETHOD(device_detach,		bus_generic_detach),
163    DEVMETHOD(device_suspend,		acpi_suspend),
164    DEVMETHOD(device_resume,		acpi_resume),
165
166    /* Bus interface */
167    DEVMETHOD(bus_add_child,		acpi_add_child),
168    DEVMETHOD(bus_print_child,		acpi_print_child),
169    DEVMETHOD(bus_probe_nomatch,	acpi_probe_nomatch),
170    DEVMETHOD(bus_driver_added,		acpi_driver_added),
171    DEVMETHOD(bus_read_ivar,		acpi_read_ivar),
172    DEVMETHOD(bus_write_ivar,		acpi_write_ivar),
173    DEVMETHOD(bus_get_resource_list,	acpi_get_rlist),
174    DEVMETHOD(bus_set_resource,		bus_generic_rl_set_resource),
175    DEVMETHOD(bus_get_resource,		bus_generic_rl_get_resource),
176    DEVMETHOD(bus_alloc_resource,	acpi_alloc_resource),
177    DEVMETHOD(bus_release_resource,	acpi_release_resource),
178    DEVMETHOD(bus_delete_resource,	acpi_delete_resource),
179    DEVMETHOD(bus_child_pnpinfo_str,	acpi_child_pnpinfo_str_method),
180    DEVMETHOD(bus_child_location_str,	acpi_child_location_str_method),
181    DEVMETHOD(bus_activate_resource,	bus_generic_activate_resource),
182    DEVMETHOD(bus_deactivate_resource,	bus_generic_deactivate_resource),
183    DEVMETHOD(bus_setup_intr,		bus_generic_setup_intr),
184    DEVMETHOD(bus_teardown_intr,	bus_generic_teardown_intr),
185
186    /* ACPI bus */
187    DEVMETHOD(acpi_id_probe,		acpi_device_id_probe),
188    DEVMETHOD(acpi_evaluate_object,	acpi_device_eval_obj),
189    DEVMETHOD(acpi_pwr_for_sleep,	acpi_device_pwr_for_sleep),
190    DEVMETHOD(acpi_scan_children,	acpi_device_scan_children),
191
192    /* PCI emulation */
193    DEVMETHOD(pci_set_powerstate,	acpi_set_powerstate_method),
194
195    /* ISA emulation */
196    DEVMETHOD(isa_pnp_probe,		acpi_isa_pnp_probe),
197
198    {0, 0}
199};
200
201static driver_t acpi_driver = {
202    "acpi",
203    acpi_methods,
204    sizeof(struct acpi_softc),
205};
206
207static devclass_t acpi_devclass;
208DRIVER_MODULE(acpi, nexus, acpi_driver, acpi_devclass, acpi_modevent, 0);
209MODULE_VERSION(acpi, 1);
210
211ACPI_SERIAL_DECL(acpi, "ACPI root bus");
212
213/* Local pools for managing system resources for ACPI child devices. */
214static struct rman acpi_rman_io, acpi_rman_mem;
215
216#define ACPI_MINIMUM_AWAKETIME	5
217
218static const char* sleep_state_names[] = {
219    "S0", "S1", "S2", "S3", "S4", "S5", "NONE"};
220
221SYSCTL_NODE(_debug, OID_AUTO, acpi, CTLFLAG_RD, NULL, "ACPI debugging");
222static char acpi_ca_version[12];
223SYSCTL_STRING(_debug_acpi, OID_AUTO, acpi_ca_version, CTLFLAG_RD,
224	      acpi_ca_version, 0, "Version of Intel ACPI-CA");
225
226/*
227 * Allow override of whether methods execute in parallel or not.
228 * Enable this for serial behavior, which fixes "AE_ALREADY_EXISTS"
229 * errors for AML that really can't handle parallel method execution.
230 * It is off by default since this breaks recursive methods and
231 * some IBMs use such code.
232 */
233static int acpi_serialize_methods;
234TUNABLE_INT("hw.acpi.serialize_methods", &acpi_serialize_methods);
235
236/* Power devices off and on in suspend and resume.  XXX Remove once tested. */
237static int acpi_do_powerstate = 1;
238TUNABLE_INT("debug.acpi.do_powerstate", &acpi_do_powerstate);
239SYSCTL_INT(_debug_acpi, OID_AUTO, do_powerstate, CTLFLAG_RW,
240    &acpi_do_powerstate, 1, "Turn off devices when suspending.");
241
242/* Allow users to override quirks. */
243TUNABLE_INT("debug.acpi.quirks", &acpi_quirks);
244
245/*
246 * ACPI can only be loaded as a module by the loader; activating it after
247 * system bootstrap time is not useful, and can be fatal to the system.
248 * It also cannot be unloaded, since the entire system bus heirarchy hangs
249 * off it.
250 */
251static int
252acpi_modevent(struct module *mod, int event, void *junk)
253{
254    switch (event) {
255    case MOD_LOAD:
256	if (!cold) {
257	    printf("The ACPI driver cannot be loaded after boot.\n");
258	    return (EPERM);
259	}
260	break;
261    case MOD_UNLOAD:
262	if (!cold && power_pm_get_type() == POWER_PM_TYPE_ACPI)
263	    return (EBUSY);
264	break;
265    default:
266	break;
267    }
268    return (0);
269}
270
271/*
272 * Perform early initialization.
273 */
274ACPI_STATUS
275acpi_Startup(void)
276{
277    static int started = 0;
278    int error, val;
279
280    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
281
282    /* Only run the startup code once.  The MADT driver also calls this. */
283    if (started)
284	return_VALUE (0);
285    started = 1;
286
287    /* Initialise the ACPI mutex */
288    mtx_init(&acpi_mutex, "ACPI global lock", NULL, MTX_DEF);
289
290    /*
291     * Set the globals from our tunables.  This is needed because ACPI-CA
292     * uses UINT8 for some values and we have no tunable_byte.
293     */
294    AcpiGbl_AllMethodsSerialized = acpi_serialize_methods;
295    AcpiGbl_EnableInterpreterSlack = TRUE;
296
297    /* Start up the ACPI CA subsystem. */
298    if (ACPI_FAILURE(error = AcpiInitializeSubsystem())) {
299	printf("ACPI: initialisation failed: %s\n", AcpiFormatException(error));
300	return_VALUE (error);
301    }
302
303    if (ACPI_FAILURE(error = AcpiLoadTables())) {
304	printf("ACPI: table load failed: %s\n", AcpiFormatException(error));
305	AcpiTerminate();
306	return_VALUE (error);
307    }
308
309    /* Set up any quirks we have for this system. */
310    if (acpi_quirks == 0)
311	acpi_table_quirks(&acpi_quirks);
312
313    /* If the user manually set the disabled hint to 0, force-enable ACPI. */
314    if (resource_int_value("acpi", 0, "disabled", &val) == 0 && val == 0)
315	acpi_quirks &= ~ACPI_Q_BROKEN;
316    if (acpi_quirks & ACPI_Q_BROKEN) {
317	printf("ACPI disabled by blacklist.  Contact your BIOS vendor.\n");
318	AcpiTerminate();
319	return_VALUE (AE_ERROR);
320    }
321
322    return_VALUE (AE_OK);
323}
324
325/*
326 * Detect ACPI, perform early initialisation
327 */
328static void
329acpi_identify(driver_t *driver, device_t parent)
330{
331    device_t	child;
332
333    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
334
335    if (!cold)
336	return_VOID;
337
338    /* Check that we haven't been disabled with a hint. */
339    if (resource_disabled("acpi", 0))
340	return_VOID;
341
342    /* Make sure we're not being doubly invoked. */
343    if (device_find_child(parent, "acpi", 0) != NULL)
344	return_VOID;
345
346    /* Initialize ACPI-CA. */
347    if (ACPI_FAILURE(acpi_Startup()))
348	return_VOID;
349
350    snprintf(acpi_ca_version, sizeof(acpi_ca_version), "%#x", ACPI_CA_VERSION);
351
352    /* Attach the actual ACPI device. */
353    if ((child = BUS_ADD_CHILD(parent, 0, "acpi", 0)) == NULL) {
354	device_printf(parent, "device_identify failed\n");
355	return_VOID;
356    }
357}
358
359/*
360 * Fetch some descriptive data from ACPI to put in our attach message.
361 */
362static int
363acpi_probe(device_t dev)
364{
365    ACPI_TABLE_HEADER	th;
366    char		buf[20];
367    int			error;
368    struct sbuf		sb;
369    ACPI_STATUS		status;
370
371    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
372
373    if (power_pm_get_type() != POWER_PM_TYPE_NONE &&
374	power_pm_get_type() != POWER_PM_TYPE_ACPI) {
375	device_printf(dev, "probe failed, other PM system enabled.\n");
376	return_VALUE (ENXIO);
377    }
378
379    if (ACPI_FAILURE(status = AcpiGetTableHeader(ACPI_TABLE_XSDT, 1, &th))) {
380	device_printf(dev, "couldn't get XSDT header: %s\n",
381		      AcpiFormatException(status));
382	error = ENXIO;
383    } else {
384	sbuf_new(&sb, buf, sizeof(buf), SBUF_FIXEDLEN);
385	sbuf_bcat(&sb, th.OemId, 6);
386	sbuf_trim(&sb);
387	sbuf_putc(&sb, ' ');
388	sbuf_bcat(&sb, th.OemTableId, 8);
389	sbuf_trim(&sb);
390	sbuf_finish(&sb);
391	device_set_desc_copy(dev, sbuf_data(&sb));
392	sbuf_delete(&sb);
393	error = 0;
394    }
395
396    return_VALUE (error);
397}
398
399static int
400acpi_attach(device_t dev)
401{
402    struct acpi_softc	*sc;
403    ACPI_STATUS		status;
404    int			error, state;
405    UINT32		flags;
406    UINT8		TypeA, TypeB;
407    char		*env;
408
409    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
410
411    sc = device_get_softc(dev);
412    sc->acpi_dev = dev;
413
414    /* Initialize resource manager. */
415    acpi_rman_io.rm_type = RMAN_ARRAY;
416    acpi_rman_io.rm_start = 0;
417    acpi_rman_io.rm_end = 0xffff;
418    acpi_rman_io.rm_descr = "I/O ports";
419    if (rman_init(&acpi_rman_io) != 0)
420	panic("acpi rman_init IO ports failed");
421    acpi_rman_mem.rm_type = RMAN_ARRAY;
422    acpi_rman_mem.rm_start = 0;
423    acpi_rman_mem.rm_end = ~0ul;
424    acpi_rman_mem.rm_descr = "I/O memory addresses";
425    if (rman_init(&acpi_rman_mem) != 0)
426	panic("acpi rman_init memory failed");
427
428    /* Install the default address space handlers. */
429    error = ENXIO;
430    status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
431		ACPI_ADR_SPACE_SYSTEM_MEMORY, ACPI_DEFAULT_HANDLER, NULL, NULL);
432    if (ACPI_FAILURE(status)) {
433	device_printf(dev, "Could not initialise SystemMemory handler: %s\n",
434		      AcpiFormatException(status));
435	goto out;
436    }
437    status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
438		ACPI_ADR_SPACE_SYSTEM_IO, ACPI_DEFAULT_HANDLER, NULL, NULL);
439    if (ACPI_FAILURE(status)) {
440	device_printf(dev, "Could not initialise SystemIO handler: %s\n",
441		      AcpiFormatException(status));
442	goto out;
443    }
444    status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
445		ACPI_ADR_SPACE_PCI_CONFIG, ACPI_DEFAULT_HANDLER, NULL, NULL);
446    if (ACPI_FAILURE(status)) {
447	device_printf(dev, "could not initialise PciConfig handler: %s\n",
448		      AcpiFormatException(status));
449	goto out;
450    }
451
452    /*
453     * Note that some systems (specifically, those with namespace evaluation
454     * issues that require the avoidance of parts of the namespace) must
455     * avoid running _INI and _STA on everything, as well as dodging the final
456     * object init pass.
457     *
458     * For these devices, we set ACPI_NO_DEVICE_INIT and ACPI_NO_OBJECT_INIT).
459     *
460     * XXX We should arrange for the object init pass after we have attached
461     *     all our child devices, but on many systems it works here.
462     */
463    flags = 0;
464    if (testenv("debug.acpi.avoid"))
465	flags = ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
466
467    /* Bring the hardware and basic handlers online. */
468    if (ACPI_FAILURE(status = AcpiEnableSubsystem(flags))) {
469	device_printf(dev, "Could not enable ACPI: %s\n",
470		      AcpiFormatException(status));
471	goto out;
472    }
473
474    /*
475     * Call the ECDT probe function to provide EC functionality before
476     * the namespace has been evaluated.
477     *
478     * XXX This happens before the sysresource devices have been probed and
479     * attached so its resources come from nexus0.  In practice, this isn't
480     * a problem but should be addressed eventually.
481     */
482    acpi_ec_ecdt_probe(dev);
483
484    /* Bring device objects and regions online. */
485    if (ACPI_FAILURE(status = AcpiInitializeObjects(flags))) {
486	device_printf(dev, "Could not initialize ACPI objects: %s\n",
487		      AcpiFormatException(status));
488	goto out;
489    }
490
491    /*
492     * Setup our sysctl tree.
493     *
494     * XXX: This doesn't check to make sure that none of these fail.
495     */
496    sysctl_ctx_init(&sc->acpi_sysctl_ctx);
497    sc->acpi_sysctl_tree = SYSCTL_ADD_NODE(&sc->acpi_sysctl_ctx,
498			       SYSCTL_STATIC_CHILDREN(_hw), OID_AUTO,
499			       device_get_name(dev), CTLFLAG_RD, 0, "");
500    SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
501	OID_AUTO, "supported_sleep_state", CTLTYPE_STRING | CTLFLAG_RD,
502	0, 0, acpi_supported_sleep_state_sysctl, "A", "");
503    SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
504	OID_AUTO, "power_button_state", CTLTYPE_STRING | CTLFLAG_RW,
505	&sc->acpi_power_button_sx, 0, acpi_sleep_state_sysctl, "A", "");
506    SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
507	OID_AUTO, "sleep_button_state", CTLTYPE_STRING | CTLFLAG_RW,
508	&sc->acpi_sleep_button_sx, 0, acpi_sleep_state_sysctl, "A", "");
509    SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
510	OID_AUTO, "lid_switch_state", CTLTYPE_STRING | CTLFLAG_RW,
511	&sc->acpi_lid_switch_sx, 0, acpi_sleep_state_sysctl, "A", "");
512    SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
513	OID_AUTO, "standby_state", CTLTYPE_STRING | CTLFLAG_RW,
514	&sc->acpi_standby_sx, 0, acpi_sleep_state_sysctl, "A", "");
515    SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
516	OID_AUTO, "suspend_state", CTLTYPE_STRING | CTLFLAG_RW,
517	&sc->acpi_suspend_sx, 0, acpi_sleep_state_sysctl, "A", "");
518    SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
519	OID_AUTO, "sleep_delay", CTLFLAG_RW, &sc->acpi_sleep_delay, 0,
520	"sleep delay");
521    SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
522	OID_AUTO, "s4bios", CTLFLAG_RW, &sc->acpi_s4bios, 0, "S4BIOS mode");
523    SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
524	OID_AUTO, "verbose", CTLFLAG_RW, &sc->acpi_verbose, 0, "verbose mode");
525
526    /*
527     * Default to 1 second before sleeping to give some machines time to
528     * stabilize.
529     */
530    sc->acpi_sleep_delay = 1;
531    if (bootverbose)
532	sc->acpi_verbose = 1;
533    if ((env = getenv("hw.acpi.verbose")) != NULL) {
534	if (strcmp(env, "0") != 0)
535	    sc->acpi_verbose = 1;
536	freeenv(env);
537    }
538
539    /* Only enable S4BIOS by default if the FACS says it is available. */
540    if (AcpiGbl_FACS->S4Bios_f != 0)
541	sc->acpi_s4bios = 1;
542
543    /*
544     * Dispatch the default sleep state to devices.  The lid switch is set
545     * to NONE by default to avoid surprising users.
546     */
547    sc->acpi_power_button_sx = ACPI_STATE_S5;
548    sc->acpi_lid_switch_sx = ACPI_S_STATES_MAX + 1;
549    sc->acpi_standby_sx = ACPI_STATE_S1;
550    sc->acpi_suspend_sx = ACPI_STATE_S3;
551
552    /* Pick the first valid sleep state for the sleep button default. */
553    sc->acpi_sleep_button_sx = ACPI_S_STATES_MAX + 1;
554    for (state = ACPI_STATE_S1; state < ACPI_STATE_S5; state++)
555	if (ACPI_SUCCESS(AcpiGetSleepTypeData(state, &TypeA, &TypeB))) {
556	    sc->acpi_sleep_button_sx = state;
557	    break;
558	}
559
560    acpi_enable_fixed_events(sc);
561
562    /*
563     * Scan the namespace and attach/initialise children.
564     */
565
566    /* Register our shutdown handler. */
567    EVENTHANDLER_REGISTER(shutdown_final, acpi_shutdown_final, sc,
568	SHUTDOWN_PRI_LAST);
569
570    /*
571     * Register our acpi event handlers.
572     * XXX should be configurable eg. via userland policy manager.
573     */
574    EVENTHANDLER_REGISTER(acpi_sleep_event, acpi_system_eventhandler_sleep,
575	sc, ACPI_EVENT_PRI_LAST);
576    EVENTHANDLER_REGISTER(acpi_wakeup_event, acpi_system_eventhandler_wakeup,
577	sc, ACPI_EVENT_PRI_LAST);
578
579    /* Flag our initial states. */
580    sc->acpi_enabled = 1;
581    sc->acpi_sstate = ACPI_STATE_S0;
582    sc->acpi_sleep_disabled = 0;
583
584    /* Create the control device */
585    sc->acpi_dev_t = make_dev(&acpi_cdevsw, 0, UID_ROOT, GID_WHEEL, 0644,
586			      "acpi");
587    sc->acpi_dev_t->si_drv1 = sc;
588
589    if ((error = acpi_machdep_init(dev)))
590	goto out;
591
592    /* Register ACPI again to pass the correct argument of pm_func. */
593    power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, sc);
594
595    if (!acpi_disabled("bus"))
596	acpi_probe_children(dev);
597
598    error = 0;
599
600 out:
601    return_VALUE (error);
602}
603
604static int
605acpi_suspend(device_t dev)
606{
607    device_t child, *devlist;
608    int error, i, numdevs, pstate;
609
610    GIANT_REQUIRED;
611
612    /* First give child devices a chance to suspend. */
613    error = bus_generic_suspend(dev);
614    if (error)
615	return (error);
616
617    /*
618     * Now, set them into the appropriate power state, usually D3.  If the
619     * device has an _SxD method for the next sleep state, use that power
620     * state instead.
621     */
622    device_get_children(dev, &devlist, &numdevs);
623    for (i = 0; i < numdevs; i++) {
624	/* If the device is not attached, we've powered it down elsewhere. */
625	child = devlist[i];
626	if (!device_is_attached(child))
627	    continue;
628
629	/*
630	 * Default to D3 for all sleep states.  The _SxD method is optional
631	 * so set the powerstate even if it's absent.
632	 */
633	pstate = PCI_POWERSTATE_D3;
634	error = acpi_device_pwr_for_sleep(device_get_parent(child),
635	    child, &pstate);
636	if ((error == 0 || error == ESRCH) && acpi_do_powerstate)
637	    pci_set_powerstate(child, pstate);
638    }
639    free(devlist, M_TEMP);
640    error = 0;
641
642    return (error);
643}
644
645static int
646acpi_resume(device_t dev)
647{
648    ACPI_HANDLE handle;
649    int i, numdevs;
650    device_t child, *devlist;
651
652    GIANT_REQUIRED;
653
654    /*
655     * Put all devices in D0 before resuming them.  Call _S0D on each one
656     * since some systems expect this.
657     */
658    device_get_children(dev, &devlist, &numdevs);
659    for (i = 0; i < numdevs; i++) {
660	child = devlist[i];
661	handle = acpi_get_handle(child);
662	if (handle)
663	    AcpiEvaluateObject(handle, "_S0D", NULL, NULL);
664	if (device_is_attached(child) && acpi_do_powerstate)
665	    pci_set_powerstate(child, PCI_POWERSTATE_D0);
666    }
667    free(devlist, M_TEMP);
668
669    return (bus_generic_resume(dev));
670}
671
672static int
673acpi_shutdown(device_t dev)
674{
675
676    GIANT_REQUIRED;
677
678    /* Allow children to shutdown first. */
679    bus_generic_shutdown(dev);
680
681    /*
682     * Enable any GPEs that are able to power-on the system (i.e., RTC).
683     * Also, disable any that are not valid for this state (most).
684     */
685    acpi_wake_prep_walk(ACPI_STATE_S5);
686
687    return (0);
688}
689
690/*
691 * Handle a new device being added
692 */
693static device_t
694acpi_add_child(device_t bus, int order, const char *name, int unit)
695{
696    struct acpi_device	*ad;
697    device_t		child;
698
699    if ((ad = malloc(sizeof(*ad), M_ACPIDEV, M_NOWAIT | M_ZERO)) == NULL)
700	return (NULL);
701
702    resource_list_init(&ad->ad_rl);
703
704    child = device_add_child_ordered(bus, order, name, unit);
705    if (child != NULL)
706	device_set_ivars(child, ad);
707    else
708	free(ad, M_ACPIDEV);
709    return (child);
710}
711
712static int
713acpi_print_child(device_t bus, device_t child)
714{
715    struct acpi_device	 *adev = device_get_ivars(child);
716    struct resource_list *rl = &adev->ad_rl;
717    int retval = 0;
718
719    retval += bus_print_child_header(bus, child);
720    retval += resource_list_print_type(rl, "port",  SYS_RES_IOPORT, "%#lx");
721    retval += resource_list_print_type(rl, "iomem", SYS_RES_MEMORY, "%#lx");
722    retval += resource_list_print_type(rl, "irq",   SYS_RES_IRQ,    "%ld");
723    retval += resource_list_print_type(rl, "drq",   SYS_RES_DRQ,    "%ld");
724    if (device_get_flags(child))
725	retval += printf(" flags %#x", device_get_flags(child));
726    retval += bus_print_child_footer(bus, child);
727
728    return (retval);
729}
730
731/*
732 * If this device is an ACPI child but no one claimed it, attempt
733 * to power it off.  We'll power it back up when a driver is added.
734 *
735 * XXX Disabled for now since many necessary devices (like fdc and
736 * ATA) don't claim the devices we created for them but still expect
737 * them to be powered up.
738 */
739static void
740acpi_probe_nomatch(device_t bus, device_t child)
741{
742
743    /* pci_set_powerstate(child, PCI_POWERSTATE_D3); */
744}
745
746/*
747 * If a new driver has a chance to probe a child, first power it up.
748 *
749 * XXX Disabled for now (see acpi_probe_nomatch for details).
750 */
751static void
752acpi_driver_added(device_t dev, driver_t *driver)
753{
754    device_t child, *devlist;
755    int i, numdevs;
756
757    DEVICE_IDENTIFY(driver, dev);
758    device_get_children(dev, &devlist, &numdevs);
759    for (i = 0; i < numdevs; i++) {
760	child = devlist[i];
761	if (device_get_state(child) == DS_NOTPRESENT) {
762	    /* pci_set_powerstate(child, PCI_POWERSTATE_D0); */
763	    if (device_probe_and_attach(child) != 0)
764		; /* pci_set_powerstate(child, PCI_POWERSTATE_D3); */
765	}
766    }
767    free(devlist, M_TEMP);
768}
769
770/* Location hint for devctl(8) */
771static int
772acpi_child_location_str_method(device_t cbdev, device_t child, char *buf,
773    size_t buflen)
774{
775    struct acpi_device *dinfo = device_get_ivars(child);
776
777    if (dinfo->ad_handle)
778	snprintf(buf, buflen, "handle=%s", acpi_name(dinfo->ad_handle));
779    else
780	snprintf(buf, buflen, "unknown");
781    return (0);
782}
783
784/* PnP information for devctl(8) */
785static int
786acpi_child_pnpinfo_str_method(device_t cbdev, device_t child, char *buf,
787    size_t buflen)
788{
789    ACPI_BUFFER adbuf = {ACPI_ALLOCATE_BUFFER, NULL};
790    ACPI_DEVICE_INFO *adinfo;
791    struct acpi_device *dinfo = device_get_ivars(child);
792    char *end;
793    int error;
794
795    error = AcpiGetObjectInfo(dinfo->ad_handle, &adbuf);
796    adinfo = (ACPI_DEVICE_INFO *) adbuf.Pointer;
797    if (error)
798	snprintf(buf, buflen, "unknown");
799    else
800	snprintf(buf, buflen, "_HID=%s _UID=%lu",
801		 (adinfo->Valid & ACPI_VALID_HID) ?
802		 adinfo->HardwareId.Value : "none",
803		 (adinfo->Valid & ACPI_VALID_UID) ?
804		 strtoul(adinfo->UniqueId.Value, &end, 10) : 0);
805    if (adinfo)
806	AcpiOsFree(adinfo);
807
808    return (0);
809}
810
811/*
812 * Handle per-device ivars
813 */
814static int
815acpi_read_ivar(device_t dev, device_t child, int index, uintptr_t *result)
816{
817    struct acpi_device	*ad;
818
819    if ((ad = device_get_ivars(child)) == NULL) {
820	printf("device has no ivars\n");
821	return (ENOENT);
822    }
823
824    /* ACPI and ISA compatibility ivars */
825    switch(index) {
826    case ACPI_IVAR_HANDLE:
827	*(ACPI_HANDLE *)result = ad->ad_handle;
828	break;
829    case ACPI_IVAR_MAGIC:
830	*(int *)result = ad->ad_magic;
831	break;
832    case ACPI_IVAR_PRIVATE:
833	*(void **)result = ad->ad_private;
834	break;
835    case ACPI_IVAR_FLAGS:
836	*(int *)result = ad->ad_flags;
837	break;
838    case ISA_IVAR_VENDORID:
839    case ISA_IVAR_SERIAL:
840    case ISA_IVAR_COMPATID:
841	*(int *)result = -1;
842	break;
843    case ISA_IVAR_LOGICALID:
844	*(int *)result = acpi_isa_get_logicalid(child);
845	break;
846    default:
847	return (ENOENT);
848    }
849
850    return (0);
851}
852
853static int
854acpi_write_ivar(device_t dev, device_t child, int index, uintptr_t value)
855{
856    struct acpi_device	*ad;
857
858    if ((ad = device_get_ivars(child)) == NULL) {
859	printf("device has no ivars\n");
860	return (ENOENT);
861    }
862
863    switch(index) {
864    case ACPI_IVAR_HANDLE:
865	ad->ad_handle = (ACPI_HANDLE)value;
866	break;
867    case ACPI_IVAR_MAGIC:
868	ad->ad_magic = (int)value;
869	break;
870    case ACPI_IVAR_PRIVATE:
871	ad->ad_private = (void *)value;
872	break;
873    case ACPI_IVAR_FLAGS:
874	ad->ad_flags = (int)value;
875	break;
876    default:
877	panic("bad ivar write request (%d)", index);
878	return (ENOENT);
879    }
880
881    return (0);
882}
883
884/*
885 * Handle child resource allocation/removal
886 */
887static struct resource_list *
888acpi_get_rlist(device_t dev, device_t child)
889{
890    struct acpi_device		*ad;
891
892    ad = device_get_ivars(child);
893    return (&ad->ad_rl);
894}
895
896/*
897 * Pre-allocate/manage all memory and IO resources.  Since rman can't handle
898 * duplicates, we merge any in the sysresource attach routine.
899 */
900static int
901acpi_sysres_alloc(device_t dev)
902{
903    struct resource *res;
904    struct resource_list *rl;
905    struct resource_list_entry *rle;
906    struct rman *rm;
907    char *sysres_ids[] = { "PNP0C01", "PNP0C02", NULL };
908    device_t *children;
909    int child_count, i;
910
911    /*
912     * Probe/attach any sysresource devices.  This would be unnecessary if we
913     * had multi-pass probe/attach.
914     */
915    if (device_get_children(dev, &children, &child_count) != 0)
916	return (ENXIO);
917    for (i = 0; i < child_count; i++) {
918	if (ACPI_ID_PROBE(dev, children[i], sysres_ids) != NULL)
919	    device_probe_and_attach(children[i]);
920    }
921    free(children, M_TEMP);
922
923    rl = BUS_GET_RESOURCE_LIST(device_get_parent(dev), dev);
924    STAILQ_FOREACH(rle, rl, link) {
925	if (rle->res != NULL) {
926	    device_printf(dev, "duplicate resource for %lx\n", rle->start);
927	    continue;
928	}
929
930	/* Only memory and IO resources are valid here. */
931	switch (rle->type) {
932	case SYS_RES_IOPORT:
933	    rm = &acpi_rman_io;
934	    break;
935	case SYS_RES_MEMORY:
936	    rm = &acpi_rman_mem;
937	    break;
938	default:
939	    continue;
940	}
941
942	/* Pre-allocate resource and add to our rman pool. */
943	res = BUS_ALLOC_RESOURCE(device_get_parent(dev), dev, rle->type,
944	    &rle->rid, rle->start, rle->start + rle->count - 1, rle->count, 0);
945	if (res != NULL) {
946	    rman_manage_region(rm, rman_get_start(res), rman_get_end(res));
947	    rle->res = res;
948	} else
949	    device_printf(dev, "reservation of %lx, %lx (%d) failed\n",
950		rle->start, rle->count, rle->type);
951    }
952    return (0);
953}
954
955/* Find if we manage a given resource. */
956static struct resource_list_entry *
957acpi_sysres_find(device_t dev, int type, u_long addr)
958{
959    struct resource_list *rl;
960    struct resource_list_entry *rle;
961
962    ACPI_SERIAL_ASSERT(acpi);
963
964    /* We only consider IO and memory resources for our pool. */
965    rle = NULL;
966    if (type != SYS_RES_IOPORT && type != SYS_RES_MEMORY)
967	goto out;
968
969    rl = BUS_GET_RESOURCE_LIST(device_get_parent(dev), dev);
970    STAILQ_FOREACH(rle, rl, link) {
971	if (type == rle->type && addr >= rle->start &&
972	    addr < rle->start + rle->count)
973	    break;
974    }
975
976out:
977    return (rle);
978}
979
980static struct resource *
981acpi_alloc_resource(device_t bus, device_t child, int type, int *rid,
982    u_long start, u_long end, u_long count, u_int flags)
983{
984    ACPI_RESOURCE ares;
985    struct acpi_device *ad = device_get_ivars(child);
986    struct resource_list *rl = &ad->ad_rl;
987    struct resource_list_entry *rle;
988    struct resource *res;
989    struct rman *rm;
990
991    res = NULL;
992    ACPI_SERIAL_BEGIN(acpi);
993
994    /*
995     * If this is an allocation of the "default" range for a given RID, and
996     * we know what the resources for this device are (i.e., they're on the
997     * child's resource list), use those start/end values.
998     */
999    if (bus == device_get_parent(child) && start == 0UL && end == ~0UL) {
1000	rle = resource_list_find(rl, type, *rid);
1001	if (rle == NULL)
1002	    goto out;
1003	start = rle->start;
1004	end = rle->end;
1005	count = rle->count;
1006    }
1007
1008    /* If we don't manage this address, pass the request up to the parent. */
1009    rle = acpi_sysres_find(bus, type, start);
1010    if (rle == NULL) {
1011	res = BUS_ALLOC_RESOURCE(device_get_parent(bus), child, type, rid,
1012	    start, end, count, flags);
1013    } else {
1014
1015	/* We only handle memory and IO resources through rman. */
1016	switch (type) {
1017	case SYS_RES_IOPORT:
1018	    rm = &acpi_rman_io;
1019	    break;
1020	case SYS_RES_MEMORY:
1021	    rm = &acpi_rman_mem;
1022	    break;
1023	default:
1024	    panic("acpi_alloc_resource: invalid res type %d", type);
1025	}
1026
1027	/* If we do know it, allocate it from the local pool. */
1028	res = rman_reserve_resource(rm, start, end, count, flags & ~RF_ACTIVE,
1029	    child);
1030	if (res == NULL)
1031	    goto out;
1032
1033	/* Copy the bus tag and handle from the pre-allocated resource. */
1034	rman_set_rid(res, *rid);
1035	rman_set_bustag(res, rman_get_bustag(rle->res));
1036	rman_set_bushandle(res, rman_get_start(res));
1037
1038	/* If requested, activate the resource using the parent's method. */
1039	if (flags & RF_ACTIVE)
1040	    if (bus_activate_resource(child, type, *rid, res) != 0) {
1041		rman_release_resource(res);
1042		res = NULL;
1043		goto out;
1044	    }
1045    }
1046
1047    if (res != NULL && device_get_parent(child) == bus)
1048	switch (type) {
1049	case SYS_RES_IRQ:
1050	    /*
1051	     * Since bus_config_intr() takes immediate effect, we cannot
1052	     * configure the interrupt associated with a device when we
1053	     * parse the resources but have to defer it until a driver
1054	     * actually allocates the interrupt via bus_alloc_resource().
1055	     *
1056	     * XXX: Should we handle the lookup failing?
1057	     */
1058	    if (ACPI_SUCCESS(acpi_lookup_irq_resource(child, *rid, res, &ares)))
1059		acpi_config_intr(child, &ares);
1060	    break;
1061	}
1062
1063out:
1064    ACPI_SERIAL_END(acpi);
1065    return (res);
1066}
1067
1068static int
1069acpi_release_resource(device_t bus, device_t child, int type, int rid,
1070    struct resource *r)
1071{
1072    int ret;
1073
1074    ACPI_SERIAL_BEGIN(acpi);
1075
1076    /*
1077     * If we know about this address, deactivate it and release it to the
1078     * local pool.  If we don't, pass this request up to the parent.
1079     */
1080    if (acpi_sysres_find(bus, type, rman_get_start(r)) == NULL) {
1081	if (rman_get_flags(r) & RF_ACTIVE) {
1082	    ret = bus_deactivate_resource(child, type, rid, r);
1083	    if (ret != 0)
1084		goto out;
1085	}
1086	ret = rman_release_resource(r);
1087    } else
1088	ret = BUS_RELEASE_RESOURCE(device_get_parent(bus), child, type, rid, r);
1089
1090out:
1091    ACPI_SERIAL_END(acpi);
1092    return (ret);
1093}
1094
1095static void
1096acpi_delete_resource(device_t bus, device_t child, int type, int rid)
1097{
1098    struct resource_list *rl;
1099
1100    rl = acpi_get_rlist(bus, child);
1101    resource_list_delete(rl, type, rid);
1102}
1103
1104/* Allocate an IO port or memory resource, given its GAS. */
1105int
1106acpi_bus_alloc_gas(device_t dev, int *type, int *rid, ACPI_GENERIC_ADDRESS *gas,
1107    struct resource **res)
1108{
1109    int error, res_type;
1110
1111    error = ENOMEM;
1112    if (type == NULL || rid == NULL || gas == NULL || res == NULL)
1113	return (EINVAL);
1114
1115    /* We only support memory and IO spaces. */
1116    switch (gas->AddressSpaceId) {
1117    case ACPI_ADR_SPACE_SYSTEM_MEMORY:
1118	res_type = SYS_RES_MEMORY;
1119	break;
1120    case ACPI_ADR_SPACE_SYSTEM_IO:
1121	res_type = SYS_RES_IOPORT;
1122	break;
1123    default:
1124	return (EOPNOTSUPP);
1125    }
1126
1127    /*
1128     * If the register width is less than 8, assume the BIOS author means
1129     * it is a bit field and just allocate a byte.
1130     */
1131    if (gas->RegisterBitWidth && gas->RegisterBitWidth < 8)
1132	gas->RegisterBitWidth = 8;
1133
1134    /* Validate the address after we're sure we support the space. */
1135    if (!ACPI_VALID_ADDRESS(gas->Address) || gas->RegisterBitWidth == 0)
1136	return (EINVAL);
1137
1138    bus_set_resource(dev, res_type, *rid, gas->Address,
1139	gas->RegisterBitWidth / 8);
1140    *res = bus_alloc_resource_any(dev, res_type, rid, RF_ACTIVE);
1141    if (*res != NULL) {
1142	*type = res_type;
1143	error = 0;
1144    } else
1145	bus_delete_resource(dev, res_type, *rid);
1146
1147    return (error);
1148}
1149
1150/* Probe _HID and _CID for compatible ISA PNP ids. */
1151static uint32_t
1152acpi_isa_get_logicalid(device_t dev)
1153{
1154    ACPI_DEVICE_INFO	*devinfo;
1155    ACPI_BUFFER		buf;
1156    ACPI_HANDLE		h;
1157    ACPI_STATUS		error;
1158    u_int32_t		pnpid;
1159
1160    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1161
1162    pnpid = 0;
1163    buf.Pointer = NULL;
1164    buf.Length = ACPI_ALLOCATE_BUFFER;
1165
1166    /* Fetch and validate the HID. */
1167    if ((h = acpi_get_handle(dev)) == NULL)
1168	goto out;
1169    error = AcpiGetObjectInfo(h, &buf);
1170    if (ACPI_FAILURE(error))
1171	goto out;
1172    devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1173
1174    if ((devinfo->Valid & ACPI_VALID_HID) != 0)
1175	pnpid = PNP_EISAID(devinfo->HardwareId.Value);
1176
1177out:
1178    if (buf.Pointer != NULL)
1179	AcpiOsFree(buf.Pointer);
1180    return_VALUE (pnpid);
1181}
1182
1183static int
1184acpi_isa_get_compatid(device_t dev, uint32_t *cids, int count)
1185{
1186    ACPI_DEVICE_INFO	*devinfo;
1187    ACPI_BUFFER		buf;
1188    ACPI_HANDLE		h;
1189    ACPI_STATUS		error;
1190    uint32_t		*pnpid;
1191    int			valid, i;
1192
1193    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1194
1195    pnpid = cids;
1196    valid = 0;
1197    buf.Pointer = NULL;
1198    buf.Length = ACPI_ALLOCATE_BUFFER;
1199
1200    /* Fetch and validate the CID */
1201    if ((h = acpi_get_handle(dev)) == NULL)
1202	goto out;
1203    error = AcpiGetObjectInfo(h, &buf);
1204    if (ACPI_FAILURE(error))
1205	goto out;
1206    devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1207    if ((devinfo->Valid & ACPI_VALID_CID) == 0)
1208	goto out;
1209
1210    if (devinfo->CompatibilityId.Count < count)
1211	count = devinfo->CompatibilityId.Count;
1212    for (i = 0; i < count; i++) {
1213	if (strncmp(devinfo->CompatibilityId.Id[i].Value, "PNP", 3) != 0)
1214	    continue;
1215	*pnpid++ = PNP_EISAID(devinfo->CompatibilityId.Id[i].Value);
1216	valid++;
1217    }
1218
1219out:
1220    if (buf.Pointer != NULL)
1221	AcpiOsFree(buf.Pointer);
1222    return_VALUE (valid);
1223}
1224
1225static char *
1226acpi_device_id_probe(device_t bus, device_t dev, char **ids)
1227{
1228    ACPI_HANDLE h;
1229    int i;
1230
1231    h = acpi_get_handle(dev);
1232    if (ids == NULL || h == NULL || acpi_get_type(dev) != ACPI_TYPE_DEVICE)
1233	return (NULL);
1234
1235    /* Try to match one of the array of IDs with a HID or CID. */
1236    for (i = 0; ids[i] != NULL; i++) {
1237	if (acpi_MatchHid(h, ids[i]))
1238	    return (ids[i]);
1239    }
1240    return (NULL);
1241}
1242
1243static ACPI_STATUS
1244acpi_device_eval_obj(device_t bus, device_t dev, ACPI_STRING pathname,
1245    ACPI_OBJECT_LIST *parameters, ACPI_BUFFER *ret)
1246{
1247    ACPI_HANDLE h;
1248
1249    if (dev == NULL)
1250	h = ACPI_ROOT_OBJECT;
1251    else if ((h = acpi_get_handle(dev)) == NULL)
1252	return (AE_BAD_PARAMETER);
1253    return (AcpiEvaluateObject(h, pathname, parameters, ret));
1254}
1255
1256static int
1257acpi_device_pwr_for_sleep(device_t bus, device_t dev, int *dstate)
1258{
1259    struct acpi_softc *sc;
1260    ACPI_HANDLE handle;
1261    ACPI_STATUS status;
1262    char sxd[8];
1263    int error;
1264
1265    sc = device_get_softc(bus);
1266    handle = acpi_get_handle(dev);
1267
1268    /*
1269     * XXX If we find these devices, don't try to power them down.
1270     * The serial and IRDA ports on my T23 hang the system when
1271     * set to D3 and it appears that such legacy devices may
1272     * need special handling in their drivers.
1273     */
1274    if (handle == NULL ||
1275	acpi_MatchHid(handle, "PNP0500") ||
1276	acpi_MatchHid(handle, "PNP0501") ||
1277	acpi_MatchHid(handle, "PNP0502") ||
1278	acpi_MatchHid(handle, "PNP0510") ||
1279	acpi_MatchHid(handle, "PNP0511"))
1280	return (ENXIO);
1281
1282    /*
1283     * Override next state with the value from _SxD, if present.  If no
1284     * dstate argument was provided, don't fetch the return value.
1285     */
1286    snprintf(sxd, sizeof(sxd), "_S%dD", sc->acpi_sstate);
1287    if (dstate)
1288	status = acpi_GetInteger(handle, sxd, dstate);
1289    else
1290	status = AcpiEvaluateObject(handle, sxd, NULL, NULL);
1291
1292    switch (status) {
1293    case AE_OK:
1294	error = 0;
1295	break;
1296    case AE_NOT_FOUND:
1297	error = ESRCH;
1298	break;
1299    default:
1300	error = ENXIO;
1301	break;
1302    }
1303
1304    return (error);
1305}
1306
1307/* Callback arg for our implementation of walking the namespace. */
1308struct acpi_device_scan_ctx {
1309    acpi_scan_cb_t	user_fn;
1310    void		*arg;
1311    ACPI_HANDLE		parent;
1312};
1313
1314static ACPI_STATUS
1315acpi_device_scan_cb(ACPI_HANDLE h, UINT32 level, void *arg, void **retval)
1316{
1317    struct acpi_device_scan_ctx *ctx;
1318    device_t dev, old_dev;
1319    ACPI_STATUS status;
1320    ACPI_OBJECT_TYPE type;
1321
1322    /*
1323     * Skip this device if we think we'll have trouble with it or it is
1324     * the parent where the scan began.
1325     */
1326    ctx = (struct acpi_device_scan_ctx *)arg;
1327    if (acpi_avoid(h) || h == ctx->parent)
1328	return (AE_OK);
1329
1330    /* If this is not a valid device type (e.g., a method), skip it. */
1331    if (ACPI_FAILURE(AcpiGetType(h, &type)))
1332	return (AE_OK);
1333    if (type != ACPI_TYPE_DEVICE && type != ACPI_TYPE_PROCESSOR &&
1334	type != ACPI_TYPE_THERMAL && type != ACPI_TYPE_POWER)
1335	return (AE_OK);
1336
1337    /*
1338     * Call the user function with the current device.  If it is unchanged
1339     * afterwards, return.  Otherwise, we update the handle to the new dev.
1340     */
1341    old_dev = acpi_get_device(h);
1342    dev = old_dev;
1343    status = ctx->user_fn(h, &dev, level, ctx->arg);
1344    if (ACPI_FAILURE(status) || old_dev == dev)
1345	return (status);
1346
1347    /* Remove the old child and its connection to the handle. */
1348    if (old_dev != NULL) {
1349	device_delete_child(device_get_parent(old_dev), old_dev);
1350	AcpiDetachData(h, acpi_fake_objhandler);
1351    }
1352
1353    /* Recreate the handle association if the user created a device. */
1354    if (dev != NULL)
1355	AcpiAttachData(h, acpi_fake_objhandler, dev);
1356
1357    return (AE_OK);
1358}
1359
1360static ACPI_STATUS
1361acpi_device_scan_children(device_t bus, device_t dev, int max_depth,
1362    acpi_scan_cb_t user_fn, void *arg)
1363{
1364    ACPI_HANDLE h;
1365    struct acpi_device_scan_ctx ctx;
1366
1367    if (acpi_disabled("children"))
1368	return (AE_OK);
1369
1370    if (dev == NULL)
1371	h = ACPI_ROOT_OBJECT;
1372    else if ((h = acpi_get_handle(dev)) == NULL)
1373	return (AE_BAD_PARAMETER);
1374    ctx.user_fn = user_fn;
1375    ctx.arg = arg;
1376    ctx.parent = h;
1377    return (AcpiWalkNamespace(ACPI_TYPE_ANY, h, max_depth,
1378	acpi_device_scan_cb, &ctx, NULL));
1379}
1380
1381/*
1382 * Even though ACPI devices are not PCI, we use the PCI approach for setting
1383 * device power states since it's close enough to ACPI.
1384 */
1385static int
1386acpi_set_powerstate_method(device_t bus, device_t child, int state)
1387{
1388    ACPI_HANDLE h;
1389    ACPI_STATUS status;
1390    int error;
1391
1392    error = 0;
1393    h = acpi_get_handle(child);
1394    if (state < ACPI_STATE_D0 || state > ACPI_STATE_D3)
1395	return (EINVAL);
1396    if (h == NULL)
1397	return (0);
1398
1399    /* Ignore errors if the power methods aren't present. */
1400    status = acpi_pwr_switch_consumer(h, state);
1401    if (ACPI_FAILURE(status) && status != AE_NOT_FOUND
1402	&& status != AE_BAD_PARAMETER)
1403	device_printf(bus, "failed to set ACPI power state D%d on %s: %s\n",
1404	    state, acpi_name(h), AcpiFormatException(status));
1405
1406    return (error);
1407}
1408
1409static int
1410acpi_isa_pnp_probe(device_t bus, device_t child, struct isa_pnp_id *ids)
1411{
1412    int			result, cid_count, i;
1413    uint32_t		lid, cids[8];
1414
1415    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1416
1417    /*
1418     * ISA-style drivers attached to ACPI may persist and
1419     * probe manually if we return ENOENT.  We never want
1420     * that to happen, so don't ever return it.
1421     */
1422    result = ENXIO;
1423
1424    /* Scan the supplied IDs for a match */
1425    lid = acpi_isa_get_logicalid(child);
1426    cid_count = acpi_isa_get_compatid(child, cids, 8);
1427    while (ids && ids->ip_id) {
1428	if (lid == ids->ip_id) {
1429	    result = 0;
1430	    goto out;
1431	}
1432	for (i = 0; i < cid_count; i++) {
1433	    if (cids[i] == ids->ip_id) {
1434		result = 0;
1435		goto out;
1436	    }
1437	}
1438	ids++;
1439    }
1440
1441 out:
1442    if (result == 0 && ids->ip_desc)
1443	device_set_desc(child, ids->ip_desc);
1444
1445    return_VALUE (result);
1446}
1447
1448/*
1449 * Scan all of the ACPI namespace and attach child devices.
1450 *
1451 * We should only expect to find devices in the \_PR, \_TZ, \_SI, and
1452 * \_SB scopes, and \_PR and \_TZ became obsolete in the ACPI 2.0 spec.
1453 * However, in violation of the spec, some systems place their PCI link
1454 * devices in \, so we have to walk the whole namespace.  We check the
1455 * type of namespace nodes, so this should be ok.
1456 */
1457static void
1458acpi_probe_children(device_t bus)
1459{
1460
1461    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1462
1463    /*
1464     * Scan the namespace and insert placeholders for all the devices that
1465     * we find.  We also probe/attach any early devices.
1466     *
1467     * Note that we use AcpiWalkNamespace rather than AcpiGetDevices because
1468     * we want to create nodes for all devices, not just those that are
1469     * currently present. (This assumes that we don't want to create/remove
1470     * devices as they appear, which might be smarter.)
1471     */
1472    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "namespace scan\n"));
1473    AcpiWalkNamespace(ACPI_TYPE_ANY, ACPI_ROOT_OBJECT, 100, acpi_probe_child,
1474	bus, NULL);
1475
1476    /* Pre-allocate resources for our rman from any sysresource devices. */
1477    acpi_sysres_alloc(bus);
1478
1479    /* Create any static children by calling device identify methods. */
1480    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "device identify routines\n"));
1481    bus_generic_probe(bus);
1482
1483    /* Probe/attach all children, created staticly and from the namespace. */
1484    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "first bus_generic_attach\n"));
1485    bus_generic_attach(bus);
1486
1487    /*
1488     * Some of these children may have attached others as part of their attach
1489     * process (eg. the root PCI bus driver), so rescan.
1490     */
1491    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "second bus_generic_attach\n"));
1492    bus_generic_attach(bus);
1493
1494    /* Attach wake sysctls. */
1495    acpi_wake_sysctl_walk(bus);
1496
1497    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "done attaching children\n"));
1498    return_VOID;
1499}
1500
1501/*
1502 * Determine the probe order for a given device and return non-zero if it
1503 * should be attached immediately.
1504 */
1505static int
1506acpi_probe_order(ACPI_HANDLE handle, int *order)
1507{
1508
1509    /*
1510     * 1. I/O port and memory system resource holders
1511     * 2. Embedded controllers (to handle early accesses)
1512     * 3. PCI Link Devices
1513     */
1514    if (acpi_MatchHid(handle, "PNP0C01") || acpi_MatchHid(handle, "PNP0C02"))
1515	*order = 1;
1516    else if (acpi_MatchHid(handle, "PNP0C09"))
1517	*order = 2;
1518    else if (acpi_MatchHid(handle, "PNP0C0F"))
1519	*order = 3;
1520    return (0);
1521}
1522
1523/*
1524 * Evaluate a child device and determine whether we might attach a device to
1525 * it.
1526 */
1527static ACPI_STATUS
1528acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
1529{
1530    ACPI_OBJECT_TYPE type;
1531    ACPI_HANDLE h;
1532    device_t bus, child;
1533    int order;
1534    char *handle_str, **search;
1535    static char *scopes[] = {"\\_PR_", "\\_TZ_", "\\_SI_", "\\_SB_", NULL};
1536
1537    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1538
1539    /* Skip this device if we think we'll have trouble with it. */
1540    if (acpi_avoid(handle))
1541	return_ACPI_STATUS (AE_OK);
1542
1543    bus = (device_t)context;
1544    if (ACPI_SUCCESS(AcpiGetType(handle, &type))) {
1545	switch (type) {
1546	case ACPI_TYPE_DEVICE:
1547	case ACPI_TYPE_PROCESSOR:
1548	case ACPI_TYPE_THERMAL:
1549	case ACPI_TYPE_POWER:
1550	    if (acpi_disabled("children"))
1551		break;
1552
1553	    /*
1554	     * Since we scan from \, be sure to skip system scope objects.
1555	     * At least \_SB and \_TZ are detected as devices (ACPI-CA bug?)
1556	     */
1557	    handle_str = acpi_name(handle);
1558	    for (search = scopes; *search != NULL; search++) {
1559		if (strcmp(handle_str, *search) == 0)
1560		    break;
1561	    }
1562	    if (*search != NULL)
1563		break;
1564
1565	    /*
1566	     * Create a placeholder device for this node.  Sort the placeholder
1567	     * so that the probe/attach passes will run breadth-first.  Orders
1568	     * less than 10 are reserved for special objects (i.e., system
1569	     * resources).  Larger values are used for all other devices.
1570	     */
1571	    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "scanning '%s'\n", handle_str));
1572	    order = (level + 1) * 10;
1573	    acpi_probe_order(handle, &order);
1574	    child = BUS_ADD_CHILD(bus, order, NULL, -1);
1575	    if (child == NULL)
1576		break;
1577
1578	    /* Associate the handle with the device_t and vice versa. */
1579	    acpi_set_handle(child, handle);
1580	    AcpiAttachData(handle, acpi_fake_objhandler, child);
1581
1582	    /*
1583	     * Check that the device is present.  If it's not present,
1584	     * leave it disabled (so that we have a device_t attached to
1585	     * the handle, but we don't probe it).
1586	     *
1587	     * XXX PCI link devices sometimes report "present" but not
1588	     * "functional" (i.e. if disabled).  Go ahead and probe them
1589	     * anyway since we may enable them later.
1590	     */
1591	    if (type == ACPI_TYPE_DEVICE && !acpi_DeviceIsPresent(child)) {
1592		/* Never disable PCI link devices. */
1593		if (acpi_MatchHid(handle, "PNP0C0F"))
1594		    break;
1595		/*
1596		 * Docking stations should remain enabled since the system
1597		 * may be undocked at boot.
1598		 */
1599		if (ACPI_SUCCESS(AcpiGetHandle(handle, "_DCK", &h)))
1600		    break;
1601
1602		device_disable(child);
1603		break;
1604	    }
1605
1606	    /*
1607	     * Get the device's resource settings and attach them.
1608	     * Note that if the device has _PRS but no _CRS, we need
1609	     * to decide when it's appropriate to try to configure the
1610	     * device.  Ignore the return value here; it's OK for the
1611	     * device not to have any resources.
1612	     */
1613	    acpi_parse_resources(child, handle, &acpi_res_parse_set, NULL);
1614	    break;
1615	}
1616    }
1617
1618    return_ACPI_STATUS (AE_OK);
1619}
1620
1621/*
1622 * AcpiAttachData() requires an object handler but never uses it.  This is a
1623 * placeholder object handler so we can store a device_t in an ACPI_HANDLE.
1624 */
1625void
1626acpi_fake_objhandler(ACPI_HANDLE h, UINT32 fn, void *data)
1627{
1628}
1629
1630static void
1631acpi_shutdown_final(void *arg, int howto)
1632{
1633    ACPI_STATUS	status;
1634
1635    /*
1636     * XXX Shutdown code should only run on the BSP (cpuid 0).
1637     * Some chipsets do not power off the system correctly if called from
1638     * an AP.
1639     */
1640    if ((howto & RB_POWEROFF) != 0) {
1641	status = AcpiEnterSleepStatePrep(ACPI_STATE_S5);
1642	if (ACPI_FAILURE(status)) {
1643	    printf("AcpiEnterSleepStatePrep failed - %s\n",
1644		   AcpiFormatException(status));
1645	    return;
1646	}
1647	printf("Powering system off using ACPI\n");
1648	ACPI_DISABLE_IRQS();
1649	status = AcpiEnterSleepState(ACPI_STATE_S5);
1650	if (ACPI_FAILURE(status)) {
1651	    printf("ACPI power-off failed - %s\n", AcpiFormatException(status));
1652	} else {
1653	    DELAY(1000000);
1654	    printf("ACPI power-off failed - timeout\n");
1655	}
1656    } else if ((howto & RB_AUTOBOOT) != 0 && AcpiGbl_FADT->ResetRegSup) {
1657	status = AcpiHwLowLevelWrite(
1658	    AcpiGbl_FADT->ResetRegister.RegisterBitWidth,
1659	    AcpiGbl_FADT->ResetValue, &AcpiGbl_FADT->ResetRegister);
1660	if (ACPI_FAILURE(status)) {
1661	    printf("ACPI reset failed - %s\n", AcpiFormatException(status));
1662	} else {
1663	    DELAY(1000000);
1664	    printf("ACPI reset failed - timeout\n");
1665	}
1666    } else if (panicstr == NULL) {
1667	printf("Shutting down ACPI\n");
1668	AcpiTerminate();
1669    }
1670}
1671
1672static void
1673acpi_enable_fixed_events(struct acpi_softc *sc)
1674{
1675    static int	first_time = 1;
1676
1677    /* Enable and clear fixed events and install handlers. */
1678    if (AcpiGbl_FADT != NULL && AcpiGbl_FADT->PwrButton == 0) {
1679	AcpiClearEvent(ACPI_EVENT_POWER_BUTTON);
1680	AcpiInstallFixedEventHandler(ACPI_EVENT_POWER_BUTTON,
1681				     acpi_event_power_button_sleep, sc);
1682	if (first_time)
1683	    device_printf(sc->acpi_dev, "Power Button (fixed)\n");
1684    }
1685    if (AcpiGbl_FADT != NULL && AcpiGbl_FADT->SleepButton == 0) {
1686	AcpiClearEvent(ACPI_EVENT_SLEEP_BUTTON);
1687	AcpiInstallFixedEventHandler(ACPI_EVENT_SLEEP_BUTTON,
1688				     acpi_event_sleep_button_sleep, sc);
1689	if (first_time)
1690	    device_printf(sc->acpi_dev, "Sleep Button (fixed)\n");
1691    }
1692
1693    first_time = 0;
1694}
1695
1696/*
1697 * Returns true if the device is actually present and should
1698 * be attached to.  This requires the present, enabled, UI-visible
1699 * and diagnostics-passed bits to be set.
1700 */
1701BOOLEAN
1702acpi_DeviceIsPresent(device_t dev)
1703{
1704    ACPI_DEVICE_INFO	*devinfo;
1705    ACPI_HANDLE		h;
1706    ACPI_BUFFER		buf;
1707    ACPI_STATUS		error;
1708    int			ret;
1709
1710    ret = FALSE;
1711    if ((h = acpi_get_handle(dev)) == NULL)
1712	return (FALSE);
1713    buf.Pointer = NULL;
1714    buf.Length = ACPI_ALLOCATE_BUFFER;
1715    error = AcpiGetObjectInfo(h, &buf);
1716    if (ACPI_FAILURE(error))
1717	return (FALSE);
1718    devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1719
1720    /* If no _STA method, must be present */
1721    if ((devinfo->Valid & ACPI_VALID_STA) == 0)
1722	ret = TRUE;
1723
1724    /* Return true for 'present' and 'functioning' */
1725    if (ACPI_DEVICE_PRESENT(devinfo->CurrentStatus))
1726	ret = TRUE;
1727
1728    AcpiOsFree(buf.Pointer);
1729    return (ret);
1730}
1731
1732/*
1733 * Returns true if the battery is actually present and inserted.
1734 */
1735BOOLEAN
1736acpi_BatteryIsPresent(device_t dev)
1737{
1738    ACPI_DEVICE_INFO	*devinfo;
1739    ACPI_HANDLE		h;
1740    ACPI_BUFFER		buf;
1741    ACPI_STATUS		error;
1742    int			ret;
1743
1744    ret = FALSE;
1745    if ((h = acpi_get_handle(dev)) == NULL)
1746	return (FALSE);
1747    buf.Pointer = NULL;
1748    buf.Length = ACPI_ALLOCATE_BUFFER;
1749    error = AcpiGetObjectInfo(h, &buf);
1750    if (ACPI_FAILURE(error))
1751	return (FALSE);
1752    devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1753
1754    /* If no _STA method, must be present */
1755    if ((devinfo->Valid & ACPI_VALID_STA) == 0)
1756	ret = TRUE;
1757
1758    /* Return true for 'present', 'battery present', and 'functioning' */
1759    if (ACPI_BATTERY_PRESENT(devinfo->CurrentStatus))
1760	ret = TRUE;
1761
1762    AcpiOsFree(buf.Pointer);
1763    return (ret);
1764}
1765
1766/*
1767 * Match a HID string against a handle
1768 */
1769static BOOLEAN
1770acpi_MatchHid(ACPI_HANDLE h, const char *hid)
1771{
1772    ACPI_DEVICE_INFO	*devinfo;
1773    ACPI_BUFFER		buf;
1774    ACPI_STATUS		error;
1775    int			ret, i;
1776
1777    ret = FALSE;
1778    if (hid == NULL || h == NULL)
1779	return (ret);
1780    buf.Pointer = NULL;
1781    buf.Length = ACPI_ALLOCATE_BUFFER;
1782    error = AcpiGetObjectInfo(h, &buf);
1783    if (ACPI_FAILURE(error))
1784	return (ret);
1785    devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1786
1787    if ((devinfo->Valid & ACPI_VALID_HID) != 0 &&
1788	strcmp(hid, devinfo->HardwareId.Value) == 0)
1789	    ret = TRUE;
1790    else if ((devinfo->Valid & ACPI_VALID_CID) != 0) {
1791	for (i = 0; i < devinfo->CompatibilityId.Count; i++) {
1792	    if (strcmp(hid, devinfo->CompatibilityId.Id[i].Value) == 0) {
1793		ret = TRUE;
1794		break;
1795	    }
1796	}
1797    }
1798
1799    AcpiOsFree(buf.Pointer);
1800    return (ret);
1801}
1802
1803/*
1804 * Return the handle of a named object within our scope, ie. that of (parent)
1805 * or one if its parents.
1806 */
1807ACPI_STATUS
1808acpi_GetHandleInScope(ACPI_HANDLE parent, char *path, ACPI_HANDLE *result)
1809{
1810    ACPI_HANDLE		r;
1811    ACPI_STATUS		status;
1812
1813    /* Walk back up the tree to the root */
1814    for (;;) {
1815	status = AcpiGetHandle(parent, path, &r);
1816	if (ACPI_SUCCESS(status)) {
1817	    *result = r;
1818	    return (AE_OK);
1819	}
1820	/* XXX Return error here? */
1821	if (status != AE_NOT_FOUND)
1822	    return (AE_OK);
1823	if (ACPI_FAILURE(AcpiGetParent(parent, &r)))
1824	    return (AE_NOT_FOUND);
1825	parent = r;
1826    }
1827}
1828
1829/* Find the difference between two PM tick counts. */
1830uint32_t
1831acpi_TimerDelta(uint32_t end, uint32_t start)
1832{
1833    uint32_t delta;
1834
1835    if (end >= start)
1836	delta = end - start;
1837    else if (AcpiGbl_FADT->TmrValExt == 0)
1838	delta = ((0x00FFFFFF - start) + end + 1) & 0x00FFFFFF;
1839    else
1840	delta = ((0xFFFFFFFF - start) + end + 1);
1841    return (delta);
1842}
1843
1844/*
1845 * Allocate a buffer with a preset data size.
1846 */
1847ACPI_BUFFER *
1848acpi_AllocBuffer(int size)
1849{
1850    ACPI_BUFFER	*buf;
1851
1852    if ((buf = malloc(size + sizeof(*buf), M_ACPIDEV, M_NOWAIT)) == NULL)
1853	return (NULL);
1854    buf->Length = size;
1855    buf->Pointer = (void *)(buf + 1);
1856    return (buf);
1857}
1858
1859ACPI_STATUS
1860acpi_SetInteger(ACPI_HANDLE handle, char *path, UINT32 number)
1861{
1862    ACPI_OBJECT arg1;
1863    ACPI_OBJECT_LIST args;
1864
1865    arg1.Type = ACPI_TYPE_INTEGER;
1866    arg1.Integer.Value = number;
1867    args.Count = 1;
1868    args.Pointer = &arg1;
1869
1870    return (AcpiEvaluateObject(handle, path, &args, NULL));
1871}
1872
1873/*
1874 * Evaluate a path that should return an integer.
1875 */
1876ACPI_STATUS
1877acpi_GetInteger(ACPI_HANDLE handle, char *path, UINT32 *number)
1878{
1879    ACPI_STATUS	status;
1880    ACPI_BUFFER	buf;
1881    ACPI_OBJECT	param;
1882
1883    if (handle == NULL)
1884	handle = ACPI_ROOT_OBJECT;
1885
1886    /*
1887     * Assume that what we've been pointed at is an Integer object, or
1888     * a method that will return an Integer.
1889     */
1890    buf.Pointer = &param;
1891    buf.Length = sizeof(param);
1892    status = AcpiEvaluateObject(handle, path, NULL, &buf);
1893    if (ACPI_SUCCESS(status)) {
1894	if (param.Type == ACPI_TYPE_INTEGER)
1895	    *number = param.Integer.Value;
1896	else
1897	    status = AE_TYPE;
1898    }
1899
1900    /*
1901     * In some applications, a method that's expected to return an Integer
1902     * may instead return a Buffer (probably to simplify some internal
1903     * arithmetic).  We'll try to fetch whatever it is, and if it's a Buffer,
1904     * convert it into an Integer as best we can.
1905     *
1906     * This is a hack.
1907     */
1908    if (status == AE_BUFFER_OVERFLOW) {
1909	if ((buf.Pointer = AcpiOsAllocate(buf.Length)) == NULL) {
1910	    status = AE_NO_MEMORY;
1911	} else {
1912	    status = AcpiEvaluateObject(handle, path, NULL, &buf);
1913	    if (ACPI_SUCCESS(status))
1914		status = acpi_ConvertBufferToInteger(&buf, number);
1915	    AcpiOsFree(buf.Pointer);
1916	}
1917    }
1918    return (status);
1919}
1920
1921ACPI_STATUS
1922acpi_ConvertBufferToInteger(ACPI_BUFFER *bufp, UINT32 *number)
1923{
1924    ACPI_OBJECT	*p;
1925    UINT8	*val;
1926    int		i;
1927
1928    p = (ACPI_OBJECT *)bufp->Pointer;
1929    if (p->Type == ACPI_TYPE_INTEGER) {
1930	*number = p->Integer.Value;
1931	return (AE_OK);
1932    }
1933    if (p->Type != ACPI_TYPE_BUFFER)
1934	return (AE_TYPE);
1935    if (p->Buffer.Length > sizeof(int))
1936	return (AE_BAD_DATA);
1937
1938    *number = 0;
1939    val = p->Buffer.Pointer;
1940    for (i = 0; i < p->Buffer.Length; i++)
1941	*number += val[i] << (i * 8);
1942    return (AE_OK);
1943}
1944
1945/*
1946 * Iterate over the elements of an a package object, calling the supplied
1947 * function for each element.
1948 *
1949 * XXX possible enhancement might be to abort traversal on error.
1950 */
1951ACPI_STATUS
1952acpi_ForeachPackageObject(ACPI_OBJECT *pkg,
1953	void (*func)(ACPI_OBJECT *comp, void *arg), void *arg)
1954{
1955    ACPI_OBJECT	*comp;
1956    int		i;
1957
1958    if (pkg == NULL || pkg->Type != ACPI_TYPE_PACKAGE)
1959	return (AE_BAD_PARAMETER);
1960
1961    /* Iterate over components */
1962    i = 0;
1963    comp = pkg->Package.Elements;
1964    for (; i < pkg->Package.Count; i++, comp++)
1965	func(comp, arg);
1966
1967    return (AE_OK);
1968}
1969
1970/*
1971 * Find the (index)th resource object in a set.
1972 */
1973ACPI_STATUS
1974acpi_FindIndexedResource(ACPI_BUFFER *buf, int index, ACPI_RESOURCE **resp)
1975{
1976    ACPI_RESOURCE	*rp;
1977    int			i;
1978
1979    rp = (ACPI_RESOURCE *)buf->Pointer;
1980    i = index;
1981    while (i-- > 0) {
1982	/* Range check */
1983	if (rp > (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
1984	    return (AE_BAD_PARAMETER);
1985
1986	/* Check for terminator */
1987	if (rp->Type == ACPI_RESOURCE_TYPE_END_TAG || rp->Length == 0)
1988	    return (AE_NOT_FOUND);
1989	rp = ACPI_NEXT_RESOURCE(rp);
1990    }
1991    if (resp != NULL)
1992	*resp = rp;
1993
1994    return (AE_OK);
1995}
1996
1997/*
1998 * Append an ACPI_RESOURCE to an ACPI_BUFFER.
1999 *
2000 * Given a pointer to an ACPI_RESOURCE structure, expand the ACPI_BUFFER
2001 * provided to contain it.  If the ACPI_BUFFER is empty, allocate a sensible
2002 * backing block.  If the ACPI_RESOURCE is NULL, return an empty set of
2003 * resources.
2004 */
2005#define ACPI_INITIAL_RESOURCE_BUFFER_SIZE	512
2006
2007ACPI_STATUS
2008acpi_AppendBufferResource(ACPI_BUFFER *buf, ACPI_RESOURCE *res)
2009{
2010    ACPI_RESOURCE	*rp;
2011    void		*newp;
2012
2013    /* Initialise the buffer if necessary. */
2014    if (buf->Pointer == NULL) {
2015	buf->Length = ACPI_INITIAL_RESOURCE_BUFFER_SIZE;
2016	if ((buf->Pointer = AcpiOsAllocate(buf->Length)) == NULL)
2017	    return (AE_NO_MEMORY);
2018	rp = (ACPI_RESOURCE *)buf->Pointer;
2019	rp->Type = ACPI_RESOURCE_TYPE_END_TAG;
2020	rp->Length = 0;
2021    }
2022    if (res == NULL)
2023	return (AE_OK);
2024
2025    /*
2026     * Scan the current buffer looking for the terminator.
2027     * This will either find the terminator or hit the end
2028     * of the buffer and return an error.
2029     */
2030    rp = (ACPI_RESOURCE *)buf->Pointer;
2031    for (;;) {
2032	/* Range check, don't go outside the buffer */
2033	if (rp >= (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
2034	    return (AE_BAD_PARAMETER);
2035	if (rp->Type == ACPI_RESOURCE_TYPE_END_TAG || rp->Length == 0)
2036	    break;
2037	rp = ACPI_NEXT_RESOURCE(rp);
2038    }
2039
2040    /*
2041     * Check the size of the buffer and expand if required.
2042     *
2043     * Required size is:
2044     *	size of existing resources before terminator +
2045     *	size of new resource and header +
2046     * 	size of terminator.
2047     *
2048     * Note that this loop should really only run once, unless
2049     * for some reason we are stuffing a *really* huge resource.
2050     */
2051    while ((((u_int8_t *)rp - (u_int8_t *)buf->Pointer) +
2052	    res->Length + ACPI_RS_SIZE_NO_DATA +
2053	    ACPI_RS_SIZE_MIN) >= buf->Length) {
2054	if ((newp = AcpiOsAllocate(buf->Length * 2)) == NULL)
2055	    return (AE_NO_MEMORY);
2056	bcopy(buf->Pointer, newp, buf->Length);
2057	rp = (ACPI_RESOURCE *)((u_int8_t *)newp +
2058			       ((u_int8_t *)rp - (u_int8_t *)buf->Pointer));
2059	AcpiOsFree(buf->Pointer);
2060	buf->Pointer = newp;
2061	buf->Length += buf->Length;
2062    }
2063
2064    /* Insert the new resource. */
2065    bcopy(res, rp, res->Length + ACPI_RS_SIZE_NO_DATA);
2066
2067    /* And add the terminator. */
2068    rp = ACPI_NEXT_RESOURCE(rp);
2069    rp->Type = ACPI_RESOURCE_TYPE_END_TAG;
2070    rp->Length = 0;
2071
2072    return (AE_OK);
2073}
2074
2075/*
2076 * Set interrupt model.
2077 */
2078ACPI_STATUS
2079acpi_SetIntrModel(int model)
2080{
2081
2082    return (acpi_SetInteger(ACPI_ROOT_OBJECT, "_PIC", model));
2083}
2084
2085static void
2086acpi_sleep_enable(void *arg)
2087{
2088
2089    ((struct acpi_softc *)arg)->acpi_sleep_disabled = 0;
2090}
2091
2092enum acpi_sleep_state {
2093    ACPI_SS_NONE,
2094    ACPI_SS_GPE_SET,
2095    ACPI_SS_DEV_SUSPEND,
2096    ACPI_SS_SLP_PREP,
2097    ACPI_SS_SLEPT,
2098};
2099
2100/*
2101 * Set the system sleep state
2102 *
2103 * Currently we support S1-S5 but S4 is only S4BIOS
2104 */
2105ACPI_STATUS
2106acpi_SetSleepState(struct acpi_softc *sc, int state)
2107{
2108    ACPI_STATUS	status;
2109    UINT8	TypeA;
2110    UINT8	TypeB;
2111    enum acpi_sleep_state slp_state;
2112
2113    ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
2114
2115    status = AE_OK;
2116    ACPI_LOCK(acpi);
2117    if (sc->acpi_sleep_disabled) {
2118	if (sc->acpi_sstate != ACPI_STATE_S0)
2119	    status = AE_ERROR;
2120	ACPI_UNLOCK(acpi);
2121	printf("acpi: suspend request ignored (not ready yet)\n");
2122	return (status);
2123    }
2124    sc->acpi_sleep_disabled = 1;
2125    ACPI_UNLOCK(acpi);
2126
2127    /*
2128     * Be sure to hold Giant across DEVICE_SUSPEND/RESUME since non-MPSAFE
2129     * drivers need this.
2130     */
2131    mtx_lock(&Giant);
2132    slp_state = ACPI_SS_NONE;
2133    switch (state) {
2134    case ACPI_STATE_S1:
2135    case ACPI_STATE_S2:
2136    case ACPI_STATE_S3:
2137    case ACPI_STATE_S4:
2138	status = AcpiGetSleepTypeData(state, &TypeA, &TypeB);
2139	if (status == AE_NOT_FOUND) {
2140	    device_printf(sc->acpi_dev,
2141			  "Sleep state S%d not supported by BIOS\n", state);
2142	    break;
2143	} else if (ACPI_FAILURE(status)) {
2144	    device_printf(sc->acpi_dev, "AcpiGetSleepTypeData failed - %s\n",
2145			  AcpiFormatException(status));
2146	    break;
2147	}
2148
2149	sc->acpi_sstate = state;
2150
2151	/* Enable any GPEs as appropriate and requested by the user. */
2152	acpi_wake_prep_walk(state);
2153	slp_state = ACPI_SS_GPE_SET;
2154
2155	/*
2156	 * Inform all devices that we are going to sleep.  If at least one
2157	 * device fails, DEVICE_SUSPEND() automatically resumes the tree.
2158	 *
2159	 * XXX Note that a better two-pass approach with a 'veto' pass
2160	 * followed by a "real thing" pass would be better, but the current
2161	 * bus interface does not provide for this.
2162	 */
2163	if (DEVICE_SUSPEND(root_bus) != 0) {
2164	    device_printf(sc->acpi_dev, "device_suspend failed\n");
2165	    break;
2166	}
2167	slp_state = ACPI_SS_DEV_SUSPEND;
2168
2169	status = AcpiEnterSleepStatePrep(state);
2170	if (ACPI_FAILURE(status)) {
2171	    device_printf(sc->acpi_dev, "AcpiEnterSleepStatePrep failed - %s\n",
2172			  AcpiFormatException(status));
2173	    break;
2174	}
2175	slp_state = ACPI_SS_SLP_PREP;
2176
2177	if (sc->acpi_sleep_delay > 0)
2178	    DELAY(sc->acpi_sleep_delay * 1000000);
2179
2180	if (state != ACPI_STATE_S1) {
2181	    acpi_sleep_machdep(sc, state);
2182
2183	    /* Re-enable ACPI hardware on wakeup from sleep state 4. */
2184	    if (state == ACPI_STATE_S4)
2185		AcpiEnable();
2186	} else {
2187	    ACPI_DISABLE_IRQS();
2188	    status = AcpiEnterSleepState(state);
2189	    if (ACPI_FAILURE(status)) {
2190		device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n",
2191			      AcpiFormatException(status));
2192		break;
2193	    }
2194	}
2195	slp_state = ACPI_SS_SLEPT;
2196	break;
2197    case ACPI_STATE_S5:
2198	/*
2199	 * Shut down cleanly and power off.  This will call us back through the
2200	 * shutdown handlers.
2201	 */
2202	shutdown_nice(RB_POWEROFF);
2203	break;
2204    case ACPI_STATE_S0:
2205    default:
2206	status = AE_BAD_PARAMETER;
2207	break;
2208    }
2209
2210    /*
2211     * Back out state according to how far along we got in the suspend
2212     * process.  This handles both the error and success cases.
2213     */
2214    if (slp_state >= ACPI_SS_GPE_SET) {
2215	acpi_wake_prep_walk(state);
2216	sc->acpi_sstate = ACPI_STATE_S0;
2217    }
2218    if (slp_state >= ACPI_SS_SLP_PREP)
2219	AcpiLeaveSleepState(state);
2220    if (slp_state >= ACPI_SS_DEV_SUSPEND)
2221	DEVICE_RESUME(root_bus);
2222    if (slp_state >= ACPI_SS_SLEPT)
2223	acpi_enable_fixed_events(sc);
2224
2225    /* Allow another sleep request after a while. */
2226    if (state != ACPI_STATE_S5)
2227	timeout(acpi_sleep_enable, (caddr_t)sc, hz * ACPI_MINIMUM_AWAKETIME);
2228
2229    mtx_unlock(&Giant);
2230    return_ACPI_STATUS (status);
2231}
2232
2233/* Initialize a device's wake GPE. */
2234int
2235acpi_wake_init(device_t dev, int type)
2236{
2237    struct acpi_prw_data prw;
2238
2239    /* Evaluate _PRW to find the GPE. */
2240    if (acpi_parse_prw(acpi_get_handle(dev), &prw) != 0)
2241	return (ENXIO);
2242
2243    /* Set the requested type for the GPE (runtime, wake, or both). */
2244    if (ACPI_FAILURE(AcpiSetGpeType(prw.gpe_handle, prw.gpe_bit, type))) {
2245	device_printf(dev, "set GPE type failed\n");
2246	return (ENXIO);
2247    }
2248
2249    return (0);
2250}
2251
2252/* Enable or disable the device's wake GPE. */
2253int
2254acpi_wake_set_enable(device_t dev, int enable)
2255{
2256    struct acpi_prw_data prw;
2257    ACPI_HANDLE handle;
2258    ACPI_STATUS status;
2259    int flags;
2260
2261    /* Make sure the device supports waking the system and get the GPE. */
2262    handle = acpi_get_handle(dev);
2263    if (acpi_parse_prw(handle, &prw) != 0)
2264	return (ENXIO);
2265
2266    flags = acpi_get_flags(dev);
2267    if (enable) {
2268	status = AcpiEnableGpe(prw.gpe_handle, prw.gpe_bit, ACPI_NOT_ISR);
2269	if (ACPI_FAILURE(status)) {
2270	    device_printf(dev, "enable wake failed\n");
2271	    return (ENXIO);
2272	}
2273	acpi_set_flags(dev, flags | ACPI_FLAG_WAKE_ENABLED);
2274    } else {
2275	status = AcpiDisableGpe(prw.gpe_handle, prw.gpe_bit, ACPI_NOT_ISR);
2276	if (ACPI_FAILURE(status)) {
2277	    device_printf(dev, "disable wake failed\n");
2278	    return (ENXIO);
2279	}
2280	acpi_set_flags(dev, flags & ~ACPI_FLAG_WAKE_ENABLED);
2281    }
2282
2283    return (0);
2284}
2285
2286static int
2287acpi_wake_sleep_prep(ACPI_HANDLE handle, int sstate)
2288{
2289    struct acpi_prw_data prw;
2290    device_t dev;
2291
2292    /* Check that this is a wake-capable device and get its GPE. */
2293    if (acpi_parse_prw(handle, &prw) != 0)
2294	return (ENXIO);
2295    dev = acpi_get_device(handle);
2296
2297    /*
2298     * The destination sleep state must be less than (i.e., higher power)
2299     * or equal to the value specified by _PRW.  If this GPE cannot be
2300     * enabled for the next sleep state, then disable it.  If it can and
2301     * the user requested it be enabled, turn on any required power resources
2302     * and set _PSW.
2303     */
2304    if (sstate > prw.lowest_wake) {
2305	AcpiDisableGpe(prw.gpe_handle, prw.gpe_bit, ACPI_NOT_ISR);
2306	if (bootverbose)
2307	    device_printf(dev, "wake_prep disabled wake for %s (S%d)\n",
2308		acpi_name(handle), sstate);
2309    } else if (dev && (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) != 0) {
2310	acpi_pwr_wake_enable(handle, 1);
2311	acpi_SetInteger(handle, "_PSW", 1);
2312	if (bootverbose)
2313	    device_printf(dev, "wake_prep enabled for %s (S%d)\n",
2314		acpi_name(handle), sstate);
2315    }
2316
2317    return (0);
2318}
2319
2320static int
2321acpi_wake_run_prep(ACPI_HANDLE handle, int sstate)
2322{
2323    struct acpi_prw_data prw;
2324    device_t dev;
2325
2326    /*
2327     * Check that this is a wake-capable device and get its GPE.  Return
2328     * now if the user didn't enable this device for wake.
2329     */
2330    if (acpi_parse_prw(handle, &prw) != 0)
2331	return (ENXIO);
2332    dev = acpi_get_device(handle);
2333    if (dev == NULL || (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) == 0)
2334	return (0);
2335
2336    /*
2337     * If this GPE couldn't be enabled for the previous sleep state, it was
2338     * disabled before going to sleep so re-enable it.  If it was enabled,
2339     * clear _PSW and turn off any power resources it used.
2340     */
2341    if (sstate > prw.lowest_wake) {
2342	AcpiEnableGpe(prw.gpe_handle, prw.gpe_bit, ACPI_NOT_ISR);
2343	if (bootverbose)
2344	    device_printf(dev, "run_prep re-enabled %s\n", acpi_name(handle));
2345    } else {
2346	acpi_SetInteger(handle, "_PSW", 0);
2347	acpi_pwr_wake_enable(handle, 0);
2348	if (bootverbose)
2349	    device_printf(dev, "run_prep cleaned up for %s\n",
2350		acpi_name(handle));
2351    }
2352
2353    return (0);
2354}
2355
2356static ACPI_STATUS
2357acpi_wake_prep(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
2358{
2359    int sstate;
2360
2361    /* If suspending, run the sleep prep function, otherwise wake. */
2362    sstate = *(int *)context;
2363    if (AcpiGbl_SystemAwakeAndRunning)
2364	acpi_wake_sleep_prep(handle, sstate);
2365    else
2366	acpi_wake_run_prep(handle, sstate);
2367    return (AE_OK);
2368}
2369
2370/* Walk the tree rooted at acpi0 to prep devices for suspend/resume. */
2371static int
2372acpi_wake_prep_walk(int sstate)
2373{
2374    ACPI_HANDLE sb_handle;
2375
2376    if (ACPI_SUCCESS(AcpiGetHandle(ACPI_ROOT_OBJECT, "\\_SB_", &sb_handle)))
2377	AcpiWalkNamespace(ACPI_TYPE_DEVICE, sb_handle, 100,
2378	    acpi_wake_prep, &sstate, NULL);
2379    return (0);
2380}
2381
2382/* Walk the tree rooted at acpi0 to attach per-device wake sysctls. */
2383static int
2384acpi_wake_sysctl_walk(device_t dev)
2385{
2386    int error, i, numdevs;
2387    device_t *devlist;
2388    device_t child;
2389    ACPI_STATUS status;
2390
2391    error = device_get_children(dev, &devlist, &numdevs);
2392    if (error != 0 || numdevs == 0) {
2393	if (numdevs == 0)
2394	    free(devlist, M_TEMP);
2395	return (error);
2396    }
2397    for (i = 0; i < numdevs; i++) {
2398	child = devlist[i];
2399	acpi_wake_sysctl_walk(child);
2400	if (!device_is_attached(child))
2401	    continue;
2402	status = AcpiEvaluateObject(acpi_get_handle(child), "_PRW", NULL, NULL);
2403	if (ACPI_SUCCESS(status)) {
2404	    SYSCTL_ADD_PROC(device_get_sysctl_ctx(child),
2405		SYSCTL_CHILDREN(device_get_sysctl_tree(child)), OID_AUTO,
2406		"wake", CTLTYPE_INT | CTLFLAG_RW, child, 0,
2407		acpi_wake_set_sysctl, "I", "Device set to wake the system");
2408	}
2409    }
2410    free(devlist, M_TEMP);
2411
2412    return (0);
2413}
2414
2415/* Enable or disable wake from userland. */
2416static int
2417acpi_wake_set_sysctl(SYSCTL_HANDLER_ARGS)
2418{
2419    int enable, error;
2420    device_t dev;
2421
2422    dev = (device_t)arg1;
2423    enable = (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) ? 1 : 0;
2424
2425    error = sysctl_handle_int(oidp, &enable, 0, req);
2426    if (error != 0 || req->newptr == NULL)
2427	return (error);
2428    if (enable != 0 && enable != 1)
2429	return (EINVAL);
2430
2431    return (acpi_wake_set_enable(dev, enable));
2432}
2433
2434/* Parse a device's _PRW into a structure. */
2435int
2436acpi_parse_prw(ACPI_HANDLE h, struct acpi_prw_data *prw)
2437{
2438    ACPI_STATUS			status;
2439    ACPI_BUFFER			prw_buffer;
2440    ACPI_OBJECT			*res, *res2;
2441    int				error, i, power_count;
2442
2443    if (h == NULL || prw == NULL)
2444	return (EINVAL);
2445
2446    /*
2447     * The _PRW object (7.2.9) is only required for devices that have the
2448     * ability to wake the system from a sleeping state.
2449     */
2450    error = EINVAL;
2451    prw_buffer.Pointer = NULL;
2452    prw_buffer.Length = ACPI_ALLOCATE_BUFFER;
2453    status = AcpiEvaluateObject(h, "_PRW", NULL, &prw_buffer);
2454    if (ACPI_FAILURE(status))
2455	return (ENOENT);
2456    res = (ACPI_OBJECT *)prw_buffer.Pointer;
2457    if (res == NULL)
2458	return (ENOENT);
2459    if (!ACPI_PKG_VALID(res, 2))
2460	goto out;
2461
2462    /*
2463     * Element 1 of the _PRW object:
2464     * The lowest power system sleeping state that can be entered while still
2465     * providing wake functionality.  The sleeping state being entered must
2466     * be less than (i.e., higher power) or equal to this value.
2467     */
2468    if (acpi_PkgInt32(res, 1, &prw->lowest_wake) != 0)
2469	goto out;
2470
2471    /*
2472     * Element 0 of the _PRW object:
2473     */
2474    switch (res->Package.Elements[0].Type) {
2475    case ACPI_TYPE_INTEGER:
2476	/*
2477	 * If the data type of this package element is numeric, then this
2478	 * _PRW package element is the bit index in the GPEx_EN, in the
2479	 * GPE blocks described in the FADT, of the enable bit that is
2480	 * enabled for the wake event.
2481	 */
2482	prw->gpe_handle = NULL;
2483	prw->gpe_bit = res->Package.Elements[0].Integer.Value;
2484	error = 0;
2485	break;
2486    case ACPI_TYPE_PACKAGE:
2487	/*
2488	 * If the data type of this package element is a package, then this
2489	 * _PRW package element is itself a package containing two
2490	 * elements.  The first is an object reference to the GPE Block
2491	 * device that contains the GPE that will be triggered by the wake
2492	 * event.  The second element is numeric and it contains the bit
2493	 * index in the GPEx_EN, in the GPE Block referenced by the
2494	 * first element in the package, of the enable bit that is enabled for
2495	 * the wake event.
2496	 *
2497	 * For example, if this field is a package then it is of the form:
2498	 * Package() {\_SB.PCI0.ISA.GPE, 2}
2499	 */
2500	res2 = &res->Package.Elements[0];
2501	if (!ACPI_PKG_VALID(res2, 2))
2502	    goto out;
2503	prw->gpe_handle = acpi_GetReference(NULL, &res2->Package.Elements[0]);
2504	if (prw->gpe_handle == NULL)
2505	    goto out;
2506	if (acpi_PkgInt32(res2, 1, &prw->gpe_bit) != 0)
2507	    goto out;
2508	error = 0;
2509	break;
2510    default:
2511	goto out;
2512    }
2513
2514    /* Elements 2 to N of the _PRW object are power resources. */
2515    power_count = res->Package.Count - 2;
2516    if (power_count > ACPI_PRW_MAX_POWERRES) {
2517	printf("ACPI device %s has too many power resources\n", acpi_name(h));
2518	power_count = 0;
2519    }
2520    prw->power_res_count = power_count;
2521    for (i = 0; i < power_count; i++)
2522	prw->power_res[i] = res->Package.Elements[i];
2523
2524out:
2525    if (prw_buffer.Pointer != NULL)
2526	AcpiOsFree(prw_buffer.Pointer);
2527    return (error);
2528}
2529
2530/*
2531 * ACPI Event Handlers
2532 */
2533
2534/* System Event Handlers (registered by EVENTHANDLER_REGISTER) */
2535
2536static void
2537acpi_system_eventhandler_sleep(void *arg, int state)
2538{
2539
2540    ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
2541
2542    if (state >= ACPI_STATE_S0 && state <= ACPI_S_STATES_MAX)
2543	acpi_SetSleepState((struct acpi_softc *)arg, state);
2544
2545    return_VOID;
2546}
2547
2548static void
2549acpi_system_eventhandler_wakeup(void *arg, int state)
2550{
2551
2552    ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
2553
2554    /* Currently, nothing to do for wakeup. */
2555
2556    return_VOID;
2557}
2558
2559/*
2560 * ACPICA Event Handlers (FixedEvent, also called from button notify handler)
2561 */
2562UINT32
2563acpi_event_power_button_sleep(void *context)
2564{
2565    struct acpi_softc	*sc = (struct acpi_softc *)context;
2566
2567    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2568
2569    EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_power_button_sx);
2570
2571    return_VALUE (ACPI_INTERRUPT_HANDLED);
2572}
2573
2574UINT32
2575acpi_event_power_button_wake(void *context)
2576{
2577    struct acpi_softc	*sc = (struct acpi_softc *)context;
2578
2579    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2580
2581    EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_power_button_sx);
2582
2583    return_VALUE (ACPI_INTERRUPT_HANDLED);
2584}
2585
2586UINT32
2587acpi_event_sleep_button_sleep(void *context)
2588{
2589    struct acpi_softc	*sc = (struct acpi_softc *)context;
2590
2591    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2592
2593    EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_sleep_button_sx);
2594
2595    return_VALUE (ACPI_INTERRUPT_HANDLED);
2596}
2597
2598UINT32
2599acpi_event_sleep_button_wake(void *context)
2600{
2601    struct acpi_softc	*sc = (struct acpi_softc *)context;
2602
2603    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2604
2605    EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_sleep_button_sx);
2606
2607    return_VALUE (ACPI_INTERRUPT_HANDLED);
2608}
2609
2610/*
2611 * XXX This static buffer is suboptimal.  There is no locking so only
2612 * use this for single-threaded callers.
2613 */
2614char *
2615acpi_name(ACPI_HANDLE handle)
2616{
2617    ACPI_BUFFER buf;
2618    static char data[256];
2619
2620    buf.Length = sizeof(data);
2621    buf.Pointer = data;
2622
2623    if (handle && ACPI_SUCCESS(AcpiGetName(handle, ACPI_FULL_PATHNAME, &buf)))
2624	return (data);
2625    return ("(unknown)");
2626}
2627
2628/*
2629 * Debugging/bug-avoidance.  Avoid trying to fetch info on various
2630 * parts of the namespace.
2631 */
2632int
2633acpi_avoid(ACPI_HANDLE handle)
2634{
2635    char	*cp, *env, *np;
2636    int		len;
2637
2638    np = acpi_name(handle);
2639    if (*np == '\\')
2640	np++;
2641    if ((env = getenv("debug.acpi.avoid")) == NULL)
2642	return (0);
2643
2644    /* Scan the avoid list checking for a match */
2645    cp = env;
2646    for (;;) {
2647	while (*cp != 0 && isspace(*cp))
2648	    cp++;
2649	if (*cp == 0)
2650	    break;
2651	len = 0;
2652	while (cp[len] != 0 && !isspace(cp[len]))
2653	    len++;
2654	if (!strncmp(cp, np, len)) {
2655	    freeenv(env);
2656	    return(1);
2657	}
2658	cp += len;
2659    }
2660    freeenv(env);
2661
2662    return (0);
2663}
2664
2665/*
2666 * Debugging/bug-avoidance.  Disable ACPI subsystem components.
2667 */
2668int
2669acpi_disabled(char *subsys)
2670{
2671    char	*cp, *env;
2672    int		len;
2673
2674    if ((env = getenv("debug.acpi.disabled")) == NULL)
2675	return (0);
2676    if (strcmp(env, "all") == 0) {
2677	freeenv(env);
2678	return (1);
2679    }
2680
2681    /* Scan the disable list, checking for a match. */
2682    cp = env;
2683    for (;;) {
2684	while (*cp != '\0' && isspace(*cp))
2685	    cp++;
2686	if (*cp == '\0')
2687	    break;
2688	len = 0;
2689	while (cp[len] != '\0' && !isspace(cp[len]))
2690	    len++;
2691	if (strncmp(cp, subsys, len) == 0) {
2692	    freeenv(env);
2693	    return (1);
2694	}
2695	cp += len;
2696    }
2697    freeenv(env);
2698
2699    return (0);
2700}
2701
2702/*
2703 * Control interface.
2704 *
2705 * We multiplex ioctls for all participating ACPI devices here.  Individual
2706 * drivers wanting to be accessible via /dev/acpi should use the
2707 * register/deregister interface to make their handlers visible.
2708 */
2709struct acpi_ioctl_hook
2710{
2711    TAILQ_ENTRY(acpi_ioctl_hook) link;
2712    u_long			 cmd;
2713    acpi_ioctl_fn		 fn;
2714    void			 *arg;
2715};
2716
2717static TAILQ_HEAD(,acpi_ioctl_hook)	acpi_ioctl_hooks;
2718static int				acpi_ioctl_hooks_initted;
2719
2720int
2721acpi_register_ioctl(u_long cmd, acpi_ioctl_fn fn, void *arg)
2722{
2723    struct acpi_ioctl_hook	*hp;
2724
2725    if ((hp = malloc(sizeof(*hp), M_ACPIDEV, M_NOWAIT)) == NULL)
2726	return (ENOMEM);
2727    hp->cmd = cmd;
2728    hp->fn = fn;
2729    hp->arg = arg;
2730
2731    ACPI_LOCK(acpi);
2732    if (acpi_ioctl_hooks_initted == 0) {
2733	TAILQ_INIT(&acpi_ioctl_hooks);
2734	acpi_ioctl_hooks_initted = 1;
2735    }
2736    TAILQ_INSERT_TAIL(&acpi_ioctl_hooks, hp, link);
2737    ACPI_UNLOCK(acpi);
2738
2739    return (0);
2740}
2741
2742void
2743acpi_deregister_ioctl(u_long cmd, acpi_ioctl_fn fn)
2744{
2745    struct acpi_ioctl_hook	*hp;
2746
2747    ACPI_LOCK(acpi);
2748    TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link)
2749	if (hp->cmd == cmd && hp->fn == fn)
2750	    break;
2751
2752    if (hp != NULL) {
2753	TAILQ_REMOVE(&acpi_ioctl_hooks, hp, link);
2754	free(hp, M_ACPIDEV);
2755    }
2756    ACPI_UNLOCK(acpi);
2757}
2758
2759static int
2760acpiopen(struct cdev *dev, int flag, int fmt, d_thread_t *td)
2761{
2762    return (0);
2763}
2764
2765static int
2766acpiclose(struct cdev *dev, int flag, int fmt, d_thread_t *td)
2767{
2768    return (0);
2769}
2770
2771static int
2772acpiioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag, d_thread_t *td)
2773{
2774    struct acpi_softc		*sc;
2775    struct acpi_ioctl_hook	*hp;
2776    int				error, state;
2777
2778    error = 0;
2779    hp = NULL;
2780    sc = dev->si_drv1;
2781
2782    /*
2783     * Scan the list of registered ioctls, looking for handlers.
2784     */
2785    ACPI_LOCK(acpi);
2786    if (acpi_ioctl_hooks_initted)
2787	TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link) {
2788	    if (hp->cmd == cmd)
2789		break;
2790	}
2791    ACPI_UNLOCK(acpi);
2792    if (hp)
2793	return (hp->fn(cmd, addr, hp->arg));
2794
2795    /*
2796     * Core ioctls are not permitted for non-writable user.
2797     * Currently, other ioctls just fetch information.
2798     * Not changing system behavior.
2799     */
2800    if ((flag & FWRITE) == 0)
2801	return (EPERM);
2802
2803    /* Core system ioctls. */
2804    switch (cmd) {
2805    case ACPIIO_SETSLPSTATE:
2806	error = EINVAL;
2807	state = *(int *)addr;
2808	if (state >= ACPI_STATE_S0 && state <= ACPI_S_STATES_MAX)
2809	    if (ACPI_SUCCESS(acpi_SetSleepState(sc, state)))
2810		error = 0;
2811	break;
2812    default:
2813	error = ENXIO;
2814	break;
2815    }
2816
2817    return (error);
2818}
2819
2820static int
2821acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
2822{
2823    int error;
2824    struct sbuf sb;
2825    UINT8 state, TypeA, TypeB;
2826
2827    sbuf_new(&sb, NULL, 32, SBUF_AUTOEXTEND);
2828    for (state = ACPI_STATE_S1; state < ACPI_S_STATES_MAX + 1; state++)
2829	if (ACPI_SUCCESS(AcpiGetSleepTypeData(state, &TypeA, &TypeB)))
2830	    sbuf_printf(&sb, "S%d ", state);
2831    sbuf_trim(&sb);
2832    sbuf_finish(&sb);
2833    error = sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
2834    sbuf_delete(&sb);
2835    return (error);
2836}
2837
2838static int
2839acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
2840{
2841    char sleep_state[10];
2842    int error;
2843    u_int new_state, old_state;
2844
2845    old_state = *(u_int *)oidp->oid_arg1;
2846    if (old_state > ACPI_S_STATES_MAX + 1)
2847	strlcpy(sleep_state, "unknown", sizeof(sleep_state));
2848    else
2849	strlcpy(sleep_state, sleep_state_names[old_state], sizeof(sleep_state));
2850    error = sysctl_handle_string(oidp, sleep_state, sizeof(sleep_state), req);
2851    if (error == 0 && req->newptr != NULL) {
2852	new_state = ACPI_STATE_S0;
2853	for (; new_state <= ACPI_S_STATES_MAX + 1; new_state++)
2854	    if (strcmp(sleep_state, sleep_state_names[new_state]) == 0)
2855		break;
2856	if (new_state <= ACPI_S_STATES_MAX + 1) {
2857	    if (new_state != old_state)
2858		*(u_int *)oidp->oid_arg1 = new_state;
2859	} else
2860	    error = EINVAL;
2861    }
2862
2863    return (error);
2864}
2865
2866/* Inform devctl(4) when we receive a Notify. */
2867void
2868acpi_UserNotify(const char *subsystem, ACPI_HANDLE h, uint8_t notify)
2869{
2870    char		notify_buf[16];
2871    ACPI_BUFFER		handle_buf;
2872    ACPI_STATUS		status;
2873
2874    if (subsystem == NULL)
2875	return;
2876
2877    handle_buf.Pointer = NULL;
2878    handle_buf.Length = ACPI_ALLOCATE_BUFFER;
2879    status = AcpiNsHandleToPathname(h, &handle_buf);
2880    if (ACPI_FAILURE(status))
2881	return;
2882    snprintf(notify_buf, sizeof(notify_buf), "notify=0x%02x", notify);
2883    devctl_notify("ACPI", subsystem, handle_buf.Pointer, notify_buf);
2884    AcpiOsFree(handle_buf.Pointer);
2885}
2886
2887#ifdef ACPI_DEBUG
2888/*
2889 * Support for parsing debug options from the kernel environment.
2890 *
2891 * Bits may be set in the AcpiDbgLayer and AcpiDbgLevel debug registers
2892 * by specifying the names of the bits in the debug.acpi.layer and
2893 * debug.acpi.level environment variables.  Bits may be unset by
2894 * prefixing the bit name with !.
2895 */
2896struct debugtag
2897{
2898    char	*name;
2899    UINT32	value;
2900};
2901
2902static struct debugtag	dbg_layer[] = {
2903    {"ACPI_UTILITIES",		ACPI_UTILITIES},
2904    {"ACPI_HARDWARE",		ACPI_HARDWARE},
2905    {"ACPI_EVENTS",		ACPI_EVENTS},
2906    {"ACPI_TABLES",		ACPI_TABLES},
2907    {"ACPI_NAMESPACE",		ACPI_NAMESPACE},
2908    {"ACPI_PARSER",		ACPI_PARSER},
2909    {"ACPI_DISPATCHER",		ACPI_DISPATCHER},
2910    {"ACPI_EXECUTER",		ACPI_EXECUTER},
2911    {"ACPI_RESOURCES",		ACPI_RESOURCES},
2912    {"ACPI_CA_DEBUGGER",	ACPI_CA_DEBUGGER},
2913    {"ACPI_OS_SERVICES",	ACPI_OS_SERVICES},
2914    {"ACPI_CA_DISASSEMBLER",	ACPI_CA_DISASSEMBLER},
2915    {"ACPI_ALL_COMPONENTS",	ACPI_ALL_COMPONENTS},
2916
2917    {"ACPI_AC_ADAPTER",		ACPI_AC_ADAPTER},
2918    {"ACPI_BATTERY",		ACPI_BATTERY},
2919    {"ACPI_BUS",		ACPI_BUS},
2920    {"ACPI_BUTTON",		ACPI_BUTTON},
2921    {"ACPI_EC", 		ACPI_EC},
2922    {"ACPI_FAN",		ACPI_FAN},
2923    {"ACPI_POWERRES",		ACPI_POWERRES},
2924    {"ACPI_PROCESSOR",		ACPI_PROCESSOR},
2925    {"ACPI_THERMAL",		ACPI_THERMAL},
2926    {"ACPI_TIMER",		ACPI_TIMER},
2927    {"ACPI_ALL_DRIVERS",	ACPI_ALL_DRIVERS},
2928    {NULL, 0}
2929};
2930
2931static struct debugtag dbg_level[] = {
2932    {"ACPI_LV_ERROR",		ACPI_LV_ERROR},
2933    {"ACPI_LV_WARN",		ACPI_LV_WARN},
2934    {"ACPI_LV_INIT",		ACPI_LV_INIT},
2935    {"ACPI_LV_DEBUG_OBJECT",	ACPI_LV_DEBUG_OBJECT},
2936    {"ACPI_LV_INFO",		ACPI_LV_INFO},
2937    {"ACPI_LV_ALL_EXCEPTIONS",	ACPI_LV_ALL_EXCEPTIONS},
2938
2939    /* Trace verbosity level 1 [Standard Trace Level] */
2940    {"ACPI_LV_INIT_NAMES",	ACPI_LV_INIT_NAMES},
2941    {"ACPI_LV_PARSE",		ACPI_LV_PARSE},
2942    {"ACPI_LV_LOAD",		ACPI_LV_LOAD},
2943    {"ACPI_LV_DISPATCH",	ACPI_LV_DISPATCH},
2944    {"ACPI_LV_EXEC",		ACPI_LV_EXEC},
2945    {"ACPI_LV_NAMES",		ACPI_LV_NAMES},
2946    {"ACPI_LV_OPREGION",	ACPI_LV_OPREGION},
2947    {"ACPI_LV_BFIELD",		ACPI_LV_BFIELD},
2948    {"ACPI_LV_TABLES",		ACPI_LV_TABLES},
2949    {"ACPI_LV_VALUES",		ACPI_LV_VALUES},
2950    {"ACPI_LV_OBJECTS",		ACPI_LV_OBJECTS},
2951    {"ACPI_LV_RESOURCES",	ACPI_LV_RESOURCES},
2952    {"ACPI_LV_USER_REQUESTS",	ACPI_LV_USER_REQUESTS},
2953    {"ACPI_LV_PACKAGE",		ACPI_LV_PACKAGE},
2954    {"ACPI_LV_VERBOSITY1",	ACPI_LV_VERBOSITY1},
2955
2956    /* Trace verbosity level 2 [Function tracing and memory allocation] */
2957    {"ACPI_LV_ALLOCATIONS",	ACPI_LV_ALLOCATIONS},
2958    {"ACPI_LV_FUNCTIONS",	ACPI_LV_FUNCTIONS},
2959    {"ACPI_LV_OPTIMIZATIONS",	ACPI_LV_OPTIMIZATIONS},
2960    {"ACPI_LV_VERBOSITY2",	ACPI_LV_VERBOSITY2},
2961    {"ACPI_LV_ALL",		ACPI_LV_ALL},
2962
2963    /* Trace verbosity level 3 [Threading, I/O, and Interrupts] */
2964    {"ACPI_LV_MUTEX",		ACPI_LV_MUTEX},
2965    {"ACPI_LV_THREADS",		ACPI_LV_THREADS},
2966    {"ACPI_LV_IO",		ACPI_LV_IO},
2967    {"ACPI_LV_INTERRUPTS",	ACPI_LV_INTERRUPTS},
2968    {"ACPI_LV_VERBOSITY3",	ACPI_LV_VERBOSITY3},
2969
2970    /* Exceptionally verbose output -- also used in the global "DebugLevel"  */
2971    {"ACPI_LV_AML_DISASSEMBLE",	ACPI_LV_AML_DISASSEMBLE},
2972    {"ACPI_LV_VERBOSE_INFO",	ACPI_LV_VERBOSE_INFO},
2973    {"ACPI_LV_FULL_TABLES",	ACPI_LV_FULL_TABLES},
2974    {"ACPI_LV_EVENTS",		ACPI_LV_EVENTS},
2975    {"ACPI_LV_VERBOSE",		ACPI_LV_VERBOSE},
2976    {NULL, 0}
2977};
2978
2979static void
2980acpi_parse_debug(char *cp, struct debugtag *tag, UINT32 *flag)
2981{
2982    char	*ep;
2983    int		i, l;
2984    int		set;
2985
2986    while (*cp) {
2987	if (isspace(*cp)) {
2988	    cp++;
2989	    continue;
2990	}
2991	ep = cp;
2992	while (*ep && !isspace(*ep))
2993	    ep++;
2994	if (*cp == '!') {
2995	    set = 0;
2996	    cp++;
2997	    if (cp == ep)
2998		continue;
2999	} else {
3000	    set = 1;
3001	}
3002	l = ep - cp;
3003	for (i = 0; tag[i].name != NULL; i++) {
3004	    if (!strncmp(cp, tag[i].name, l)) {
3005		if (set)
3006		    *flag |= tag[i].value;
3007		else
3008		    *flag &= ~tag[i].value;
3009	    }
3010	}
3011	cp = ep;
3012    }
3013}
3014
3015static void
3016acpi_set_debugging(void *junk)
3017{
3018    char	*layer, *level;
3019
3020    if (cold) {
3021	AcpiDbgLayer = 0;
3022	AcpiDbgLevel = 0;
3023    }
3024
3025    layer = getenv("debug.acpi.layer");
3026    level = getenv("debug.acpi.level");
3027    if (layer == NULL && level == NULL)
3028	return;
3029
3030    printf("ACPI set debug");
3031    if (layer != NULL) {
3032	if (strcmp("NONE", layer) != 0)
3033	    printf(" layer '%s'", layer);
3034	acpi_parse_debug(layer, &dbg_layer[0], &AcpiDbgLayer);
3035	freeenv(layer);
3036    }
3037    if (level != NULL) {
3038	if (strcmp("NONE", level) != 0)
3039	    printf(" level '%s'", level);
3040	acpi_parse_debug(level, &dbg_level[0], &AcpiDbgLevel);
3041	freeenv(level);
3042    }
3043    printf("\n");
3044}
3045
3046SYSINIT(acpi_debugging, SI_SUB_TUNABLES, SI_ORDER_ANY, acpi_set_debugging,
3047	NULL);
3048
3049static int
3050acpi_debug_sysctl(SYSCTL_HANDLER_ARGS)
3051{
3052    int		 error, *dbg;
3053    struct	 debugtag *tag;
3054    struct	 sbuf sb;
3055
3056    if (sbuf_new(&sb, NULL, 128, SBUF_AUTOEXTEND) == NULL)
3057	return (ENOMEM);
3058    if (strcmp(oidp->oid_arg1, "debug.acpi.layer") == 0) {
3059	tag = &dbg_layer[0];
3060	dbg = &AcpiDbgLayer;
3061    } else {
3062	tag = &dbg_level[0];
3063	dbg = &AcpiDbgLevel;
3064    }
3065
3066    /* Get old values if this is a get request. */
3067    ACPI_SERIAL_BEGIN(acpi);
3068    if (*dbg == 0) {
3069	sbuf_cpy(&sb, "NONE");
3070    } else if (req->newptr == NULL) {
3071	for (; tag->name != NULL; tag++) {
3072	    if ((*dbg & tag->value) == tag->value)
3073		sbuf_printf(&sb, "%s ", tag->name);
3074	}
3075    }
3076    sbuf_trim(&sb);
3077    sbuf_finish(&sb);
3078
3079    /* Copy out the old values to the user. */
3080    error = SYSCTL_OUT(req, sbuf_data(&sb), sbuf_len(&sb));
3081    sbuf_delete(&sb);
3082
3083    /* If the user is setting a string, parse it. */
3084    if (error == 0 && req->newptr != NULL) {
3085	*dbg = 0;
3086	setenv((char *)oidp->oid_arg1, (char *)req->newptr);
3087	acpi_set_debugging(NULL);
3088    }
3089    ACPI_SERIAL_END(acpi);
3090
3091    return (error);
3092}
3093
3094SYSCTL_PROC(_debug_acpi, OID_AUTO, layer, CTLFLAG_RW | CTLTYPE_STRING,
3095	    "debug.acpi.layer", 0, acpi_debug_sysctl, "A", "");
3096SYSCTL_PROC(_debug_acpi, OID_AUTO, level, CTLFLAG_RW | CTLTYPE_STRING,
3097	    "debug.acpi.level", 0, acpi_debug_sysctl, "A", "");
3098#endif /* ACPI_DEBUG */
3099
3100static int
3101acpi_pm_func(u_long cmd, void *arg, ...)
3102{
3103	int	state, acpi_state;
3104	int	error;
3105	struct	acpi_softc *sc;
3106	va_list	ap;
3107
3108	error = 0;
3109	switch (cmd) {
3110	case POWER_CMD_SUSPEND:
3111		sc = (struct acpi_softc *)arg;
3112		if (sc == NULL) {
3113			error = EINVAL;
3114			goto out;
3115		}
3116
3117		va_start(ap, arg);
3118		state = va_arg(ap, int);
3119		va_end(ap);
3120
3121		switch (state) {
3122		case POWER_SLEEP_STATE_STANDBY:
3123			acpi_state = sc->acpi_standby_sx;
3124			break;
3125		case POWER_SLEEP_STATE_SUSPEND:
3126			acpi_state = sc->acpi_suspend_sx;
3127			break;
3128		case POWER_SLEEP_STATE_HIBERNATE:
3129			acpi_state = ACPI_STATE_S4;
3130			break;
3131		default:
3132			error = EINVAL;
3133			goto out;
3134		}
3135
3136		acpi_SetSleepState(sc, acpi_state);
3137		break;
3138	default:
3139		error = EINVAL;
3140		goto out;
3141	}
3142
3143out:
3144	return (error);
3145}
3146
3147static void
3148acpi_pm_register(void *arg)
3149{
3150    if (!cold || resource_disabled("acpi", 0))
3151	return;
3152
3153    power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, NULL);
3154}
3155
3156SYSINIT(power, SI_SUB_KLD, SI_ORDER_ANY, acpi_pm_register, 0);
3157