acpi.c revision 231161
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 231161 2012-02-07 20:54:44Z jkim $");
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/sched.h>
50#include <sys/smp.h>
51#include <sys/timetc.h>
52
53#if defined(__i386__) || defined(__amd64__)
54#include <machine/pci_cfgreg.h>
55#endif
56#include <machine/resource.h>
57#include <machine/bus.h>
58#include <sys/rman.h>
59#include <isa/isavar.h>
60#include <isa/pnpvar.h>
61
62#include <contrib/dev/acpica/include/acpi.h>
63#include <contrib/dev/acpica/include/accommon.h>
64#include <contrib/dev/acpica/include/acnamesp.h>
65
66#include <dev/acpica/acpivar.h>
67#include <dev/acpica/acpiio.h>
68
69#include <vm/vm_param.h>
70
71static MALLOC_DEFINE(M_ACPIDEV, "acpidev", "ACPI devices");
72
73/* Hooks for the ACPI CA debugging infrastructure */
74#define _COMPONENT	ACPI_BUS
75ACPI_MODULE_NAME("ACPI")
76
77static d_open_t		acpiopen;
78static d_close_t	acpiclose;
79static d_ioctl_t	acpiioctl;
80
81static struct cdevsw acpi_cdevsw = {
82	.d_version =	D_VERSION,
83	.d_open =	acpiopen,
84	.d_close =	acpiclose,
85	.d_ioctl =	acpiioctl,
86	.d_name =	"acpi",
87};
88
89struct acpi_interface {
90	ACPI_STRING	*data;
91	int		num;
92};
93
94/* Global mutex for locking access to the ACPI subsystem. */
95struct mtx	acpi_mutex;
96
97/* Bitmap of device quirks. */
98int		acpi_quirks;
99
100/* Supported sleep states. */
101static BOOLEAN	acpi_sleep_states[ACPI_S_STATE_COUNT];
102
103static int	acpi_modevent(struct module *mod, int event, void *junk);
104static int	acpi_probe(device_t dev);
105static int	acpi_attach(device_t dev);
106static int	acpi_suspend(device_t dev);
107static int	acpi_resume(device_t dev);
108static int	acpi_shutdown(device_t dev);
109static device_t	acpi_add_child(device_t bus, u_int order, const char *name,
110			int unit);
111static int	acpi_print_child(device_t bus, device_t child);
112static void	acpi_probe_nomatch(device_t bus, device_t child);
113static void	acpi_driver_added(device_t dev, driver_t *driver);
114static int	acpi_read_ivar(device_t dev, device_t child, int index,
115			uintptr_t *result);
116static int	acpi_write_ivar(device_t dev, device_t child, int index,
117			uintptr_t value);
118static struct resource_list *acpi_get_rlist(device_t dev, device_t child);
119static void	acpi_reserve_resources(device_t dev);
120static int	acpi_sysres_alloc(device_t dev);
121static int	acpi_set_resource(device_t dev, device_t child, int type,
122			int rid, u_long start, u_long count);
123static struct resource *acpi_alloc_resource(device_t bus, device_t child,
124			int type, int *rid, u_long start, u_long end,
125			u_long count, u_int flags);
126static int	acpi_adjust_resource(device_t bus, device_t child, int type,
127			struct resource *r, u_long start, u_long end);
128static int	acpi_release_resource(device_t bus, device_t child, int type,
129			int rid, struct resource *r);
130static void	acpi_delete_resource(device_t bus, device_t child, int type,
131		    int rid);
132static uint32_t	acpi_isa_get_logicalid(device_t dev);
133static int	acpi_isa_get_compatid(device_t dev, uint32_t *cids, int count);
134static char	*acpi_device_id_probe(device_t bus, device_t dev, char **ids);
135static ACPI_STATUS acpi_device_eval_obj(device_t bus, device_t dev,
136		    ACPI_STRING pathname, ACPI_OBJECT_LIST *parameters,
137		    ACPI_BUFFER *ret);
138static ACPI_STATUS acpi_device_scan_cb(ACPI_HANDLE h, UINT32 level,
139		    void *context, void **retval);
140static ACPI_STATUS acpi_device_scan_children(device_t bus, device_t dev,
141		    int max_depth, acpi_scan_cb_t user_fn, void *arg);
142static int	acpi_set_powerstate(device_t child, int state);
143static int	acpi_isa_pnp_probe(device_t bus, device_t child,
144		    struct isa_pnp_id *ids);
145static void	acpi_probe_children(device_t bus);
146static void	acpi_probe_order(ACPI_HANDLE handle, int *order);
147static ACPI_STATUS acpi_probe_child(ACPI_HANDLE handle, UINT32 level,
148		    void *context, void **status);
149static void	acpi_sleep_enable(void *arg);
150static ACPI_STATUS acpi_sleep_disable(struct acpi_softc *sc);
151static ACPI_STATUS acpi_EnterSleepState(struct acpi_softc *sc, int state);
152static void	acpi_shutdown_final(void *arg, int howto);
153static void	acpi_enable_fixed_events(struct acpi_softc *sc);
154static BOOLEAN	acpi_has_hid(ACPI_HANDLE handle);
155static int	acpi_wake_sleep_prep(ACPI_HANDLE handle, int sstate);
156static int	acpi_wake_run_prep(ACPI_HANDLE handle, int sstate);
157static int	acpi_wake_prep_walk(int sstate);
158static int	acpi_wake_sysctl_walk(device_t dev);
159static int	acpi_wake_set_sysctl(SYSCTL_HANDLER_ARGS);
160static void	acpi_system_eventhandler_sleep(void *arg, int state);
161static void	acpi_system_eventhandler_wakeup(void *arg, int state);
162static int	acpi_sname2sstate(const char *sname);
163static const char *acpi_sstate2sname(int sstate);
164static int	acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS);
165static int	acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS);
166static int	acpi_debug_objects_sysctl(SYSCTL_HANDLER_ARGS);
167static int	acpi_pm_func(u_long cmd, void *arg, ...);
168static int	acpi_child_location_str_method(device_t acdev, device_t child,
169					       char *buf, size_t buflen);
170static int	acpi_child_pnpinfo_str_method(device_t acdev, device_t child,
171					      char *buf, size_t buflen);
172#if defined(__i386__) || defined(__amd64__)
173static void	acpi_enable_pcie(void);
174#endif
175static void	acpi_hint_device_unit(device_t acdev, device_t child,
176		    const char *name, int *unitp);
177static void	acpi_reset_interfaces(device_t dev);
178
179static device_method_t acpi_methods[] = {
180    /* Device interface */
181    DEVMETHOD(device_probe,		acpi_probe),
182    DEVMETHOD(device_attach,		acpi_attach),
183    DEVMETHOD(device_shutdown,		acpi_shutdown),
184    DEVMETHOD(device_detach,		bus_generic_detach),
185    DEVMETHOD(device_suspend,		acpi_suspend),
186    DEVMETHOD(device_resume,		acpi_resume),
187
188    /* Bus interface */
189    DEVMETHOD(bus_add_child,		acpi_add_child),
190    DEVMETHOD(bus_print_child,		acpi_print_child),
191    DEVMETHOD(bus_probe_nomatch,	acpi_probe_nomatch),
192    DEVMETHOD(bus_driver_added,		acpi_driver_added),
193    DEVMETHOD(bus_read_ivar,		acpi_read_ivar),
194    DEVMETHOD(bus_write_ivar,		acpi_write_ivar),
195    DEVMETHOD(bus_get_resource_list,	acpi_get_rlist),
196    DEVMETHOD(bus_set_resource,		acpi_set_resource),
197    DEVMETHOD(bus_get_resource,		bus_generic_rl_get_resource),
198    DEVMETHOD(bus_alloc_resource,	acpi_alloc_resource),
199    DEVMETHOD(bus_adjust_resource,	acpi_adjust_resource),
200    DEVMETHOD(bus_release_resource,	acpi_release_resource),
201    DEVMETHOD(bus_delete_resource,	acpi_delete_resource),
202    DEVMETHOD(bus_child_pnpinfo_str,	acpi_child_pnpinfo_str_method),
203    DEVMETHOD(bus_child_location_str,	acpi_child_location_str_method),
204    DEVMETHOD(bus_activate_resource,	bus_generic_activate_resource),
205    DEVMETHOD(bus_deactivate_resource,	bus_generic_deactivate_resource),
206    DEVMETHOD(bus_setup_intr,		bus_generic_setup_intr),
207    DEVMETHOD(bus_teardown_intr,	bus_generic_teardown_intr),
208    DEVMETHOD(bus_hint_device_unit,	acpi_hint_device_unit),
209
210    /* ACPI bus */
211    DEVMETHOD(acpi_id_probe,		acpi_device_id_probe),
212    DEVMETHOD(acpi_evaluate_object,	acpi_device_eval_obj),
213    DEVMETHOD(acpi_pwr_for_sleep,	acpi_device_pwr_for_sleep),
214    DEVMETHOD(acpi_scan_children,	acpi_device_scan_children),
215
216    /* ISA emulation */
217    DEVMETHOD(isa_pnp_probe,		acpi_isa_pnp_probe),
218
219    {0, 0}
220};
221
222static driver_t acpi_driver = {
223    "acpi",
224    acpi_methods,
225    sizeof(struct acpi_softc),
226};
227
228static devclass_t acpi_devclass;
229DRIVER_MODULE(acpi, nexus, acpi_driver, acpi_devclass, acpi_modevent, 0);
230MODULE_VERSION(acpi, 1);
231
232ACPI_SERIAL_DECL(acpi, "ACPI root bus");
233
234/* Local pools for managing system resources for ACPI child devices. */
235static struct rman acpi_rman_io, acpi_rman_mem;
236
237#define ACPI_MINIMUM_AWAKETIME	5
238
239/* Holds the description of the acpi0 device. */
240static char acpi_desc[ACPI_OEM_ID_SIZE + ACPI_OEM_TABLE_ID_SIZE + 2];
241
242SYSCTL_NODE(_debug, OID_AUTO, acpi, CTLFLAG_RD, NULL, "ACPI debugging");
243static char acpi_ca_version[12];
244SYSCTL_STRING(_debug_acpi, OID_AUTO, acpi_ca_version, CTLFLAG_RD,
245	      acpi_ca_version, 0, "Version of Intel ACPI-CA");
246
247/*
248 * Allow overriding _OSI methods.
249 */
250static char acpi_install_interface[256];
251TUNABLE_STR("hw.acpi.install_interface", acpi_install_interface,
252    sizeof(acpi_install_interface));
253static char acpi_remove_interface[256];
254TUNABLE_STR("hw.acpi.remove_interface", acpi_remove_interface,
255    sizeof(acpi_remove_interface));
256
257/*
258 * Allow override of whether methods execute in parallel or not.
259 * Enable this for serial behavior, which fixes "AE_ALREADY_EXISTS"
260 * errors for AML that really can't handle parallel method execution.
261 * It is off by default since this breaks recursive methods and
262 * some IBMs use such code.
263 */
264static int acpi_serialize_methods;
265TUNABLE_INT("hw.acpi.serialize_methods", &acpi_serialize_methods);
266
267/* Allow users to dump Debug objects without ACPI debugger. */
268static int acpi_debug_objects;
269TUNABLE_INT("debug.acpi.enable_debug_objects", &acpi_debug_objects);
270SYSCTL_PROC(_debug_acpi, OID_AUTO, enable_debug_objects,
271    CTLFLAG_RW | CTLTYPE_INT, NULL, 0, acpi_debug_objects_sysctl, "I",
272    "Enable Debug objects");
273
274/* Allow the interpreter to ignore common mistakes in BIOS. */
275static int acpi_interpreter_slack = 1;
276TUNABLE_INT("debug.acpi.interpreter_slack", &acpi_interpreter_slack);
277SYSCTL_INT(_debug_acpi, OID_AUTO, interpreter_slack, CTLFLAG_RDTUN,
278    &acpi_interpreter_slack, 1, "Turn on interpreter slack mode.");
279
280/* Reset system clock while resuming.  XXX Remove once tested. */
281static int acpi_reset_clock = 1;
282TUNABLE_INT("debug.acpi.reset_clock", &acpi_reset_clock);
283SYSCTL_INT(_debug_acpi, OID_AUTO, reset_clock, CTLFLAG_RW,
284    &acpi_reset_clock, 1, "Reset system clock while resuming.");
285
286/* Allow users to override quirks. */
287TUNABLE_INT("debug.acpi.quirks", &acpi_quirks);
288
289static int acpi_susp_bounce;
290SYSCTL_INT(_debug_acpi, OID_AUTO, suspend_bounce, CTLFLAG_RW,
291    &acpi_susp_bounce, 0, "Don't actually suspend, just test devices.");
292
293/*
294 * ACPI can only be loaded as a module by the loader; activating it after
295 * system bootstrap time is not useful, and can be fatal to the system.
296 * It also cannot be unloaded, since the entire system bus hierarchy hangs
297 * off it.
298 */
299static int
300acpi_modevent(struct module *mod, int event, void *junk)
301{
302    switch (event) {
303    case MOD_LOAD:
304	if (!cold) {
305	    printf("The ACPI driver cannot be loaded after boot.\n");
306	    return (EPERM);
307	}
308	break;
309    case MOD_UNLOAD:
310	if (!cold && power_pm_get_type() == POWER_PM_TYPE_ACPI)
311	    return (EBUSY);
312	break;
313    default:
314	break;
315    }
316    return (0);
317}
318
319/*
320 * Perform early initialization.
321 */
322ACPI_STATUS
323acpi_Startup(void)
324{
325    static int started = 0;
326    ACPI_STATUS status;
327    int val;
328
329    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
330
331    /* Only run the startup code once.  The MADT driver also calls this. */
332    if (started)
333	return_VALUE (AE_OK);
334    started = 1;
335
336    /*
337     * Pre-allocate space for RSDT/XSDT and DSDT tables and allow resizing
338     * if more tables exist.
339     */
340    if (ACPI_FAILURE(status = AcpiInitializeTables(NULL, 2, TRUE))) {
341	printf("ACPI: Table initialisation failed: %s\n",
342	    AcpiFormatException(status));
343	return_VALUE (status);
344    }
345
346    /* Set up any quirks we have for this system. */
347    if (acpi_quirks == ACPI_Q_OK)
348	acpi_table_quirks(&acpi_quirks);
349
350    /* If the user manually set the disabled hint to 0, force-enable ACPI. */
351    if (resource_int_value("acpi", 0, "disabled", &val) == 0 && val == 0)
352	acpi_quirks &= ~ACPI_Q_BROKEN;
353    if (acpi_quirks & ACPI_Q_BROKEN) {
354	printf("ACPI disabled by blacklist.  Contact your BIOS vendor.\n");
355	status = AE_SUPPORT;
356    }
357
358    return_VALUE (status);
359}
360
361/*
362 * Detect ACPI and perform early initialisation.
363 */
364int
365acpi_identify(void)
366{
367    ACPI_TABLE_RSDP	*rsdp;
368    ACPI_TABLE_HEADER	*rsdt;
369    ACPI_PHYSICAL_ADDRESS paddr;
370    struct sbuf		sb;
371
372    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
373
374    if (!cold)
375	return (ENXIO);
376
377    /* Check that we haven't been disabled with a hint. */
378    if (resource_disabled("acpi", 0))
379	return (ENXIO);
380
381    /* Check for other PM systems. */
382    if (power_pm_get_type() != POWER_PM_TYPE_NONE &&
383	power_pm_get_type() != POWER_PM_TYPE_ACPI) {
384	printf("ACPI identify failed, other PM system enabled.\n");
385	return (ENXIO);
386    }
387
388    /* Initialize root tables. */
389    if (ACPI_FAILURE(acpi_Startup())) {
390	printf("ACPI: Try disabling either ACPI or apic support.\n");
391	return (ENXIO);
392    }
393
394    if ((paddr = AcpiOsGetRootPointer()) == 0 ||
395	(rsdp = AcpiOsMapMemory(paddr, sizeof(ACPI_TABLE_RSDP))) == NULL)
396	return (ENXIO);
397    if (rsdp->Revision > 1 && rsdp->XsdtPhysicalAddress != 0)
398	paddr = (ACPI_PHYSICAL_ADDRESS)rsdp->XsdtPhysicalAddress;
399    else
400	paddr = (ACPI_PHYSICAL_ADDRESS)rsdp->RsdtPhysicalAddress;
401    AcpiOsUnmapMemory(rsdp, sizeof(ACPI_TABLE_RSDP));
402
403    if ((rsdt = AcpiOsMapMemory(paddr, sizeof(ACPI_TABLE_HEADER))) == NULL)
404	return (ENXIO);
405    sbuf_new(&sb, acpi_desc, sizeof(acpi_desc), SBUF_FIXEDLEN);
406    sbuf_bcat(&sb, rsdt->OemId, ACPI_OEM_ID_SIZE);
407    sbuf_trim(&sb);
408    sbuf_putc(&sb, ' ');
409    sbuf_bcat(&sb, rsdt->OemTableId, ACPI_OEM_TABLE_ID_SIZE);
410    sbuf_trim(&sb);
411    sbuf_finish(&sb);
412    sbuf_delete(&sb);
413    AcpiOsUnmapMemory(rsdt, sizeof(ACPI_TABLE_HEADER));
414
415    snprintf(acpi_ca_version, sizeof(acpi_ca_version), "%x", ACPI_CA_VERSION);
416
417    return (0);
418}
419
420/*
421 * Fetch some descriptive data from ACPI to put in our attach message.
422 */
423static int
424acpi_probe(device_t dev)
425{
426
427    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
428
429    device_set_desc(dev, acpi_desc);
430
431    return_VALUE (0);
432}
433
434static int
435acpi_attach(device_t dev)
436{
437    struct acpi_softc	*sc;
438    ACPI_STATUS		status;
439    int			error, state;
440    UINT32		flags;
441    UINT8		TypeA, TypeB;
442    char		*env;
443
444    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
445
446    sc = device_get_softc(dev);
447    sc->acpi_dev = dev;
448    callout_init(&sc->susp_force_to, TRUE);
449
450    error = ENXIO;
451
452    /* Initialize resource manager. */
453    acpi_rman_io.rm_type = RMAN_ARRAY;
454    acpi_rman_io.rm_start = 0;
455    acpi_rman_io.rm_end = 0xffff;
456    acpi_rman_io.rm_descr = "ACPI I/O ports";
457    if (rman_init(&acpi_rman_io) != 0)
458	panic("acpi rman_init IO ports failed");
459    acpi_rman_mem.rm_type = RMAN_ARRAY;
460    acpi_rman_mem.rm_start = 0;
461    acpi_rman_mem.rm_end = ~0ul;
462    acpi_rman_mem.rm_descr = "ACPI I/O memory addresses";
463    if (rman_init(&acpi_rman_mem) != 0)
464	panic("acpi rman_init memory failed");
465
466    /* Initialise the ACPI mutex */
467    mtx_init(&acpi_mutex, "ACPI global lock", NULL, MTX_DEF);
468
469    /*
470     * Set the globals from our tunables.  This is needed because ACPI-CA
471     * uses UINT8 for some values and we have no tunable_byte.
472     */
473    AcpiGbl_AllMethodsSerialized = acpi_serialize_methods ? TRUE : FALSE;
474    AcpiGbl_EnableInterpreterSlack = acpi_interpreter_slack ? TRUE : FALSE;
475    AcpiGbl_EnableAmlDebugObject = acpi_debug_objects ? TRUE : FALSE;
476
477#ifndef ACPI_DEBUG
478    /*
479     * Disable all debugging layers and levels.
480     */
481    AcpiDbgLayer = 0;
482    AcpiDbgLevel = 0;
483#endif
484
485    /* Start up the ACPI CA subsystem. */
486    status = AcpiInitializeSubsystem();
487    if (ACPI_FAILURE(status)) {
488	device_printf(dev, "Could not initialize Subsystem: %s\n",
489		      AcpiFormatException(status));
490	goto out;
491    }
492
493    /* Override OS interfaces if the user requested. */
494    acpi_reset_interfaces(dev);
495
496    /* Load ACPI name space. */
497    status = AcpiLoadTables();
498    if (ACPI_FAILURE(status)) {
499	device_printf(dev, "Could not load Namespace: %s\n",
500		      AcpiFormatException(status));
501	goto out;
502    }
503
504#if defined(__i386__) || defined(__amd64__)
505    /* Handle MCFG table if present. */
506    acpi_enable_pcie();
507#endif
508
509    /*
510     * Note that some systems (specifically, those with namespace evaluation
511     * issues that require the avoidance of parts of the namespace) must
512     * avoid running _INI and _STA on everything, as well as dodging the final
513     * object init pass.
514     *
515     * For these devices, we set ACPI_NO_DEVICE_INIT and ACPI_NO_OBJECT_INIT).
516     *
517     * XXX We should arrange for the object init pass after we have attached
518     *     all our child devices, but on many systems it works here.
519     */
520    flags = 0;
521    if (testenv("debug.acpi.avoid"))
522	flags = ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
523
524    /* Bring the hardware and basic handlers online. */
525    if (ACPI_FAILURE(status = AcpiEnableSubsystem(flags))) {
526	device_printf(dev, "Could not enable ACPI: %s\n",
527		      AcpiFormatException(status));
528	goto out;
529    }
530
531    /*
532     * Call the ECDT probe function to provide EC functionality before
533     * the namespace has been evaluated.
534     *
535     * XXX This happens before the sysresource devices have been probed and
536     * attached so its resources come from nexus0.  In practice, this isn't
537     * a problem but should be addressed eventually.
538     */
539    acpi_ec_ecdt_probe(dev);
540
541    /* Bring device objects and regions online. */
542    if (ACPI_FAILURE(status = AcpiInitializeObjects(flags))) {
543	device_printf(dev, "Could not initialize ACPI objects: %s\n",
544		      AcpiFormatException(status));
545	goto out;
546    }
547
548    /*
549     * Setup our sysctl tree.
550     *
551     * XXX: This doesn't check to make sure that none of these fail.
552     */
553    sysctl_ctx_init(&sc->acpi_sysctl_ctx);
554    sc->acpi_sysctl_tree = SYSCTL_ADD_NODE(&sc->acpi_sysctl_ctx,
555			       SYSCTL_STATIC_CHILDREN(_hw), OID_AUTO,
556			       device_get_name(dev), CTLFLAG_RD, 0, "");
557    SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
558	OID_AUTO, "supported_sleep_state", CTLTYPE_STRING | CTLFLAG_RD,
559	0, 0, acpi_supported_sleep_state_sysctl, "A", "");
560    SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
561	OID_AUTO, "power_button_state", CTLTYPE_STRING | CTLFLAG_RW,
562	&sc->acpi_power_button_sx, 0, acpi_sleep_state_sysctl, "A", "");
563    SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
564	OID_AUTO, "sleep_button_state", CTLTYPE_STRING | CTLFLAG_RW,
565	&sc->acpi_sleep_button_sx, 0, acpi_sleep_state_sysctl, "A", "");
566    SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
567	OID_AUTO, "lid_switch_state", CTLTYPE_STRING | CTLFLAG_RW,
568	&sc->acpi_lid_switch_sx, 0, acpi_sleep_state_sysctl, "A", "");
569    SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
570	OID_AUTO, "standby_state", CTLTYPE_STRING | CTLFLAG_RW,
571	&sc->acpi_standby_sx, 0, acpi_sleep_state_sysctl, "A", "");
572    SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
573	OID_AUTO, "suspend_state", CTLTYPE_STRING | CTLFLAG_RW,
574	&sc->acpi_suspend_sx, 0, acpi_sleep_state_sysctl, "A", "");
575    SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
576	OID_AUTO, "sleep_delay", CTLFLAG_RW, &sc->acpi_sleep_delay, 0,
577	"sleep delay in seconds");
578    SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
579	OID_AUTO, "s4bios", CTLFLAG_RW, &sc->acpi_s4bios, 0, "S4BIOS mode");
580    SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
581	OID_AUTO, "verbose", CTLFLAG_RW, &sc->acpi_verbose, 0, "verbose mode");
582    SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
583	OID_AUTO, "disable_on_reboot", CTLFLAG_RW,
584	&sc->acpi_do_disable, 0, "Disable ACPI when rebooting/halting system");
585    SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
586	OID_AUTO, "handle_reboot", CTLFLAG_RW,
587	&sc->acpi_handle_reboot, 0, "Use ACPI Reset Register to reboot");
588
589    /*
590     * Default to 1 second before sleeping to give some machines time to
591     * stabilize.
592     */
593    sc->acpi_sleep_delay = 1;
594    if (bootverbose)
595	sc->acpi_verbose = 1;
596    if ((env = getenv("hw.acpi.verbose")) != NULL) {
597	if (strcmp(env, "0") != 0)
598	    sc->acpi_verbose = 1;
599	freeenv(env);
600    }
601
602    /* Only enable reboot by default if the FADT says it is available. */
603    if (AcpiGbl_FADT.Flags & ACPI_FADT_RESET_REGISTER)
604	sc->acpi_handle_reboot = 1;
605
606    /* Only enable S4BIOS by default if the FACS says it is available. */
607    if (AcpiGbl_FACS->Flags & ACPI_FACS_S4_BIOS_PRESENT)
608	sc->acpi_s4bios = 1;
609
610    /* Probe all supported sleep states. */
611    acpi_sleep_states[ACPI_STATE_S0] = TRUE;
612    for (state = ACPI_STATE_S1; state < ACPI_S_STATE_COUNT; state++)
613	if (ACPI_SUCCESS(AcpiGetSleepTypeData(state, &TypeA, &TypeB)))
614	    acpi_sleep_states[state] = TRUE;
615
616    /*
617     * Dispatch the default sleep state to devices.  The lid switch is set
618     * to UNKNOWN by default to avoid surprising users.
619     */
620    sc->acpi_power_button_sx = acpi_sleep_states[ACPI_STATE_S5] ?
621	ACPI_STATE_S5 : ACPI_STATE_UNKNOWN;
622    sc->acpi_lid_switch_sx = ACPI_STATE_UNKNOWN;
623    sc->acpi_standby_sx = acpi_sleep_states[ACPI_STATE_S1] ?
624	ACPI_STATE_S1 : ACPI_STATE_UNKNOWN;
625    sc->acpi_suspend_sx = acpi_sleep_states[ACPI_STATE_S3] ?
626	ACPI_STATE_S3 : ACPI_STATE_UNKNOWN;
627
628    /* Pick the first valid sleep state for the sleep button default. */
629    sc->acpi_sleep_button_sx = ACPI_STATE_UNKNOWN;
630    for (state = ACPI_STATE_S1; state <= ACPI_STATE_S4; state++)
631	if (acpi_sleep_states[state]) {
632	    sc->acpi_sleep_button_sx = state;
633	    break;
634	}
635
636    acpi_enable_fixed_events(sc);
637
638    /*
639     * Scan the namespace and attach/initialise children.
640     */
641
642    /* Register our shutdown handler. */
643    EVENTHANDLER_REGISTER(shutdown_final, acpi_shutdown_final, sc,
644	SHUTDOWN_PRI_LAST);
645
646    /*
647     * Register our acpi event handlers.
648     * XXX should be configurable eg. via userland policy manager.
649     */
650    EVENTHANDLER_REGISTER(acpi_sleep_event, acpi_system_eventhandler_sleep,
651	sc, ACPI_EVENT_PRI_LAST);
652    EVENTHANDLER_REGISTER(acpi_wakeup_event, acpi_system_eventhandler_wakeup,
653	sc, ACPI_EVENT_PRI_LAST);
654
655    /* Flag our initial states. */
656    sc->acpi_enabled = TRUE;
657    sc->acpi_sstate = ACPI_STATE_S0;
658    sc->acpi_sleep_disabled = TRUE;
659
660    /* Create the control device */
661    sc->acpi_dev_t = make_dev(&acpi_cdevsw, 0, UID_ROOT, GID_WHEEL, 0644,
662			      "acpi");
663    sc->acpi_dev_t->si_drv1 = sc;
664
665    if ((error = acpi_machdep_init(dev)))
666	goto out;
667
668    /* Register ACPI again to pass the correct argument of pm_func. */
669    power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, sc);
670
671    if (!acpi_disabled("bus"))
672	acpi_probe_children(dev);
673
674    /* Update all GPEs and enable runtime GPEs. */
675    status = AcpiUpdateAllGpes();
676    if (ACPI_FAILURE(status))
677	device_printf(dev, "Could not update all GPEs: %s\n",
678	    AcpiFormatException(status));
679
680    /* Allow sleep request after a while. */
681    timeout(acpi_sleep_enable, sc, hz * ACPI_MINIMUM_AWAKETIME);
682
683    error = 0;
684
685 out:
686    return_VALUE (error);
687}
688
689static void
690acpi_set_power_children(device_t dev, int state)
691{
692	device_t child, parent;
693	device_t *devlist;
694	struct pci_devinfo *dinfo;
695	int dstate, i, numdevs;
696
697	if (device_get_children(dev, &devlist, &numdevs) != 0)
698		return;
699
700	/*
701	 * Retrieve and set D-state for the sleep state if _SxD is present.
702	 * Skip children who aren't attached since they are handled separately.
703	 */
704	parent = device_get_parent(dev);
705	for (i = 0; i < numdevs; i++) {
706		child = devlist[i];
707		dinfo = device_get_ivars(child);
708		dstate = state;
709		if (device_is_attached(child) &&
710		    acpi_device_pwr_for_sleep(parent, dev, &dstate) == 0)
711			acpi_set_powerstate(child, dstate);
712	}
713	free(devlist, M_TEMP);
714}
715
716static int
717acpi_suspend(device_t dev)
718{
719    int error;
720
721    GIANT_REQUIRED;
722
723    error = bus_generic_suspend(dev);
724    if (error == 0)
725	acpi_set_power_children(dev, ACPI_STATE_D3);
726
727    return (error);
728}
729
730static int
731acpi_resume(device_t dev)
732{
733
734    GIANT_REQUIRED;
735
736    acpi_set_power_children(dev, ACPI_STATE_D0);
737
738    return (bus_generic_resume(dev));
739}
740
741static int
742acpi_shutdown(device_t dev)
743{
744
745    GIANT_REQUIRED;
746
747    /* Allow children to shutdown first. */
748    bus_generic_shutdown(dev);
749
750    /*
751     * Enable any GPEs that are able to power-on the system (i.e., RTC).
752     * Also, disable any that are not valid for this state (most).
753     */
754    acpi_wake_prep_walk(ACPI_STATE_S5);
755
756    return (0);
757}
758
759/*
760 * Handle a new device being added
761 */
762static device_t
763acpi_add_child(device_t bus, u_int order, const char *name, int unit)
764{
765    struct acpi_device	*ad;
766    device_t		child;
767
768    if ((ad = malloc(sizeof(*ad), M_ACPIDEV, M_NOWAIT | M_ZERO)) == NULL)
769	return (NULL);
770
771    resource_list_init(&ad->ad_rl);
772
773    child = device_add_child_ordered(bus, order, name, unit);
774    if (child != NULL)
775	device_set_ivars(child, ad);
776    else
777	free(ad, M_ACPIDEV);
778    return (child);
779}
780
781static int
782acpi_print_child(device_t bus, device_t child)
783{
784    struct acpi_device	 *adev = device_get_ivars(child);
785    struct resource_list *rl = &adev->ad_rl;
786    int retval = 0;
787
788    retval += bus_print_child_header(bus, child);
789    retval += resource_list_print_type(rl, "port",  SYS_RES_IOPORT, "%#lx");
790    retval += resource_list_print_type(rl, "iomem", SYS_RES_MEMORY, "%#lx");
791    retval += resource_list_print_type(rl, "irq",   SYS_RES_IRQ,    "%ld");
792    retval += resource_list_print_type(rl, "drq",   SYS_RES_DRQ,    "%ld");
793    if (device_get_flags(child))
794	retval += printf(" flags %#x", device_get_flags(child));
795    retval += bus_print_child_footer(bus, child);
796
797    return (retval);
798}
799
800/*
801 * If this device is an ACPI child but no one claimed it, attempt
802 * to power it off.  We'll power it back up when a driver is added.
803 *
804 * XXX Disabled for now since many necessary devices (like fdc and
805 * ATA) don't claim the devices we created for them but still expect
806 * them to be powered up.
807 */
808static void
809acpi_probe_nomatch(device_t bus, device_t child)
810{
811#ifdef ACPI_ENABLE_POWERDOWN_NODRIVER
812    acpi_set_powerstate(child, ACPI_STATE_D3);
813#endif
814}
815
816/*
817 * If a new driver has a chance to probe a child, first power it up.
818 *
819 * XXX Disabled for now (see acpi_probe_nomatch for details).
820 */
821static void
822acpi_driver_added(device_t dev, driver_t *driver)
823{
824    device_t child, *devlist;
825    int i, numdevs;
826
827    DEVICE_IDENTIFY(driver, dev);
828    if (device_get_children(dev, &devlist, &numdevs))
829	    return;
830    for (i = 0; i < numdevs; i++) {
831	child = devlist[i];
832	if (device_get_state(child) == DS_NOTPRESENT) {
833#ifdef ACPI_ENABLE_POWERDOWN_NODRIVER
834	    acpi_set_powerstate(child, ACPI_STATE_D0);
835	    if (device_probe_and_attach(child) != 0)
836		acpi_set_powerstate(child, ACPI_STATE_D3);
837#else
838	    device_probe_and_attach(child);
839#endif
840	}
841    }
842    free(devlist, M_TEMP);
843}
844
845/* Location hint for devctl(8) */
846static int
847acpi_child_location_str_method(device_t cbdev, device_t child, char *buf,
848    size_t buflen)
849{
850    struct acpi_device *dinfo = device_get_ivars(child);
851
852    if (dinfo->ad_handle)
853	snprintf(buf, buflen, "handle=%s", acpi_name(dinfo->ad_handle));
854    else
855	snprintf(buf, buflen, "unknown");
856    return (0);
857}
858
859/* PnP information for devctl(8) */
860static int
861acpi_child_pnpinfo_str_method(device_t cbdev, device_t child, char *buf,
862    size_t buflen)
863{
864    struct acpi_device *dinfo = device_get_ivars(child);
865    ACPI_DEVICE_INFO *adinfo;
866
867    if (ACPI_FAILURE(AcpiGetObjectInfo(dinfo->ad_handle, &adinfo))) {
868	snprintf(buf, buflen, "unknown");
869	return (0);
870    }
871
872    snprintf(buf, buflen, "_HID=%s _UID=%lu",
873	(adinfo->Valid & ACPI_VALID_HID) ?
874	adinfo->HardwareId.String : "none",
875	(adinfo->Valid & ACPI_VALID_UID) ?
876	strtoul(adinfo->UniqueId.String, NULL, 10) : 0UL);
877    AcpiOsFree(adinfo);
878
879    return (0);
880}
881
882/*
883 * Handle per-device ivars
884 */
885static int
886acpi_read_ivar(device_t dev, device_t child, int index, uintptr_t *result)
887{
888    struct acpi_device	*ad;
889
890    if ((ad = device_get_ivars(child)) == NULL) {
891	device_printf(child, "device has no ivars\n");
892	return (ENOENT);
893    }
894
895    /* ACPI and ISA compatibility ivars */
896    switch(index) {
897    case ACPI_IVAR_HANDLE:
898	*(ACPI_HANDLE *)result = ad->ad_handle;
899	break;
900    case ACPI_IVAR_PRIVATE:
901	*(void **)result = ad->ad_private;
902	break;
903    case ACPI_IVAR_FLAGS:
904	*(int *)result = ad->ad_flags;
905	break;
906    case ISA_IVAR_VENDORID:
907    case ISA_IVAR_SERIAL:
908    case ISA_IVAR_COMPATID:
909	*(int *)result = -1;
910	break;
911    case ISA_IVAR_LOGICALID:
912	*(int *)result = acpi_isa_get_logicalid(child);
913	break;
914    default:
915	return (ENOENT);
916    }
917
918    return (0);
919}
920
921static int
922acpi_write_ivar(device_t dev, device_t child, int index, uintptr_t value)
923{
924    struct acpi_device	*ad;
925
926    if ((ad = device_get_ivars(child)) == NULL) {
927	device_printf(child, "device has no ivars\n");
928	return (ENOENT);
929    }
930
931    switch(index) {
932    case ACPI_IVAR_HANDLE:
933	ad->ad_handle = (ACPI_HANDLE)value;
934	break;
935    case ACPI_IVAR_PRIVATE:
936	ad->ad_private = (void *)value;
937	break;
938    case ACPI_IVAR_FLAGS:
939	ad->ad_flags = (int)value;
940	break;
941    default:
942	panic("bad ivar write request (%d)", index);
943	return (ENOENT);
944    }
945
946    return (0);
947}
948
949/*
950 * Handle child resource allocation/removal
951 */
952static struct resource_list *
953acpi_get_rlist(device_t dev, device_t child)
954{
955    struct acpi_device		*ad;
956
957    ad = device_get_ivars(child);
958    return (&ad->ad_rl);
959}
960
961static int
962acpi_match_resource_hint(device_t dev, int type, long value)
963{
964    struct acpi_device *ad = device_get_ivars(dev);
965    struct resource_list *rl = &ad->ad_rl;
966    struct resource_list_entry *rle;
967
968    STAILQ_FOREACH(rle, rl, link) {
969	if (rle->type != type)
970	    continue;
971	if (rle->start <= value && rle->end >= value)
972	    return (1);
973    }
974    return (0);
975}
976
977/*
978 * Wire device unit numbers based on resource matches in hints.
979 */
980static void
981acpi_hint_device_unit(device_t acdev, device_t child, const char *name,
982    int *unitp)
983{
984    const char *s;
985    long value;
986    int line, matches, unit;
987
988    /*
989     * Iterate over all the hints for the devices with the specified
990     * name to see if one's resources are a subset of this device.
991     */
992    line = 0;
993    for (;;) {
994	if (resource_find_dev(&line, name, &unit, "at", NULL) != 0)
995	    break;
996
997	/* Must have an "at" for acpi or isa. */
998	resource_string_value(name, unit, "at", &s);
999	if (!(strcmp(s, "acpi0") == 0 || strcmp(s, "acpi") == 0 ||
1000	    strcmp(s, "isa0") == 0 || strcmp(s, "isa") == 0))
1001	    continue;
1002
1003	/*
1004	 * Check for matching resources.  We must have at least one match.
1005	 * Since I/O and memory resources cannot be shared, if we get a
1006	 * match on either of those, ignore any mismatches in IRQs or DRQs.
1007	 *
1008	 * XXX: We may want to revisit this to be more lenient and wire
1009	 * as long as it gets one match.
1010	 */
1011	matches = 0;
1012	if (resource_long_value(name, unit, "port", &value) == 0) {
1013	    /*
1014	     * Floppy drive controllers are notorious for having a
1015	     * wide variety of resources not all of which include the
1016	     * first port that is specified by the hint (typically
1017	     * 0x3f0) (see the comment above fdc_isa_alloc_resources()
1018	     * in fdc_isa.c).  However, they do all seem to include
1019	     * port + 2 (e.g. 0x3f2) so for a floppy device, look for
1020	     * 'value + 2' in the port resources instead of the hint
1021	     * value.
1022	     */
1023	    if (strcmp(name, "fdc") == 0)
1024		value += 2;
1025	    if (acpi_match_resource_hint(child, SYS_RES_IOPORT, value))
1026		matches++;
1027	    else
1028		continue;
1029	}
1030	if (resource_long_value(name, unit, "maddr", &value) == 0) {
1031	    if (acpi_match_resource_hint(child, SYS_RES_MEMORY, value))
1032		matches++;
1033	    else
1034		continue;
1035	}
1036	if (matches > 0)
1037	    goto matched;
1038	if (resource_long_value(name, unit, "irq", &value) == 0) {
1039	    if (acpi_match_resource_hint(child, SYS_RES_IRQ, value))
1040		matches++;
1041	    else
1042		continue;
1043	}
1044	if (resource_long_value(name, unit, "drq", &value) == 0) {
1045	    if (acpi_match_resource_hint(child, SYS_RES_DRQ, value))
1046		matches++;
1047	    else
1048		continue;
1049	}
1050
1051    matched:
1052	if (matches > 0) {
1053	    /* We have a winner! */
1054	    *unitp = unit;
1055	    break;
1056	}
1057    }
1058}
1059
1060/*
1061 * Pre-allocate/manage all memory and IO resources.  Since rman can't handle
1062 * duplicates, we merge any in the sysresource attach routine.
1063 */
1064static int
1065acpi_sysres_alloc(device_t dev)
1066{
1067    struct resource *res;
1068    struct resource_list *rl;
1069    struct resource_list_entry *rle;
1070    struct rman *rm;
1071    char *sysres_ids[] = { "PNP0C01", "PNP0C02", NULL };
1072    device_t *children;
1073    int child_count, i;
1074
1075    /*
1076     * Probe/attach any sysresource devices.  This would be unnecessary if we
1077     * had multi-pass probe/attach.
1078     */
1079    if (device_get_children(dev, &children, &child_count) != 0)
1080	return (ENXIO);
1081    for (i = 0; i < child_count; i++) {
1082	if (ACPI_ID_PROBE(dev, children[i], sysres_ids) != NULL)
1083	    device_probe_and_attach(children[i]);
1084    }
1085    free(children, M_TEMP);
1086
1087    rl = BUS_GET_RESOURCE_LIST(device_get_parent(dev), dev);
1088    STAILQ_FOREACH(rle, rl, link) {
1089	if (rle->res != NULL) {
1090	    device_printf(dev, "duplicate resource for %lx\n", rle->start);
1091	    continue;
1092	}
1093
1094	/* Only memory and IO resources are valid here. */
1095	switch (rle->type) {
1096	case SYS_RES_IOPORT:
1097	    rm = &acpi_rman_io;
1098	    break;
1099	case SYS_RES_MEMORY:
1100	    rm = &acpi_rman_mem;
1101	    break;
1102	default:
1103	    continue;
1104	}
1105
1106	/* Pre-allocate resource and add to our rman pool. */
1107	res = BUS_ALLOC_RESOURCE(device_get_parent(dev), dev, rle->type,
1108	    &rle->rid, rle->start, rle->start + rle->count - 1, rle->count, 0);
1109	if (res != NULL) {
1110	    rman_manage_region(rm, rman_get_start(res), rman_get_end(res));
1111	    rle->res = res;
1112	} else
1113	    device_printf(dev, "reservation of %lx, %lx (%d) failed\n",
1114		rle->start, rle->count, rle->type);
1115    }
1116    return (0);
1117}
1118
1119static char *pcilink_ids[] = { "PNP0C0F", NULL };
1120static char *sysres_ids[] = { "PNP0C01", "PNP0C02", NULL };
1121
1122/*
1123 * Reserve declared resources for devices found during attach once system
1124 * resources have been allocated.
1125 */
1126static void
1127acpi_reserve_resources(device_t dev)
1128{
1129    struct resource_list_entry *rle;
1130    struct resource_list *rl;
1131    struct acpi_device *ad;
1132    struct acpi_softc *sc;
1133    device_t *children;
1134    int child_count, i;
1135
1136    sc = device_get_softc(dev);
1137    if (device_get_children(dev, &children, &child_count) != 0)
1138	return;
1139    for (i = 0; i < child_count; i++) {
1140	ad = device_get_ivars(children[i]);
1141	rl = &ad->ad_rl;
1142
1143	/* Don't reserve system resources. */
1144	if (ACPI_ID_PROBE(dev, children[i], sysres_ids) != NULL)
1145	    continue;
1146
1147	STAILQ_FOREACH(rle, rl, link) {
1148	    /*
1149	     * Don't reserve IRQ resources.  There are many sticky things
1150	     * to get right otherwise (e.g. IRQs for psm, atkbd, and HPET
1151	     * when using legacy routing).
1152	     */
1153	    if (rle->type == SYS_RES_IRQ)
1154		continue;
1155
1156	    /*
1157	     * Don't reserve the resource if it is already allocated.
1158	     * The acpi_ec(4) driver can allocate its resources early
1159	     * if ECDT is present.
1160	     */
1161	    if (rle->res != NULL)
1162		continue;
1163
1164	    /*
1165	     * Try to reserve the resource from our parent.  If this
1166	     * fails because the resource is a system resource, just
1167	     * let it be.  The resource range is already reserved so
1168	     * that other devices will not use it.  If the driver
1169	     * needs to allocate the resource, then
1170	     * acpi_alloc_resource() will sub-alloc from the system
1171	     * resource.
1172	     */
1173	    resource_list_reserve(rl, dev, children[i], rle->type, &rle->rid,
1174		rle->start, rle->end, rle->count, 0);
1175	}
1176    }
1177    free(children, M_TEMP);
1178    sc->acpi_resources_reserved = 1;
1179}
1180
1181static int
1182acpi_set_resource(device_t dev, device_t child, int type, int rid,
1183    u_long start, u_long count)
1184{
1185    struct acpi_softc *sc = device_get_softc(dev);
1186    struct acpi_device *ad = device_get_ivars(child);
1187    struct resource_list *rl = &ad->ad_rl;
1188    u_long end;
1189
1190    /* Ignore IRQ resources for PCI link devices. */
1191    if (type == SYS_RES_IRQ && ACPI_ID_PROBE(dev, child, pcilink_ids) != NULL)
1192	return (0);
1193
1194    /* If the resource is already allocated, fail. */
1195    if (resource_list_busy(rl, type, rid))
1196	return (EBUSY);
1197
1198    /* If the resource is already reserved, release it. */
1199    if (resource_list_reserved(rl, type, rid))
1200	resource_list_unreserve(rl, dev, child, type, rid);
1201
1202    /* Add the resource. */
1203    end = (start + count - 1);
1204    resource_list_add(rl, type, rid, start, end, count);
1205
1206    /* Don't reserve resources until the system resources are allocated. */
1207    if (!sc->acpi_resources_reserved)
1208	return (0);
1209
1210    /* Don't reserve system resources. */
1211    if (ACPI_ID_PROBE(dev, child, sysres_ids) != NULL)
1212	return (0);
1213
1214    /*
1215     * Don't reserve IRQ resources.  There are many sticky things to
1216     * get right otherwise (e.g. IRQs for psm, atkbd, and HPET when
1217     * using legacy routing).
1218     */
1219    if (type == SYS_RES_IRQ)
1220	return (0);
1221
1222    /*
1223     * Reserve the resource.
1224     *
1225     * XXX: Ignores failure for now.  Failure here is probably a
1226     * BIOS/firmware bug?
1227     */
1228    resource_list_reserve(rl, dev, child, type, &rid, start, end, count, 0);
1229    return (0);
1230}
1231
1232static struct resource *
1233acpi_alloc_resource(device_t bus, device_t child, int type, int *rid,
1234    u_long start, u_long end, u_long count, u_int flags)
1235{
1236    ACPI_RESOURCE ares;
1237    struct acpi_device *ad;
1238    struct resource_list_entry *rle;
1239    struct resource_list *rl;
1240    struct resource *res;
1241    int isdefault = (start == 0UL && end == ~0UL);
1242
1243    /*
1244     * First attempt at allocating the resource.  For direct children,
1245     * use resource_list_alloc() to handle reserved resources.  For
1246     * other devices, pass the request up to our parent.
1247     */
1248    if (bus == device_get_parent(child)) {
1249	ad = device_get_ivars(child);
1250	rl = &ad->ad_rl;
1251
1252	/*
1253	 * Simulate the behavior of the ISA bus for direct children
1254	 * devices.  That is, if a non-default range is specified for
1255	 * a resource that doesn't exist, use bus_set_resource() to
1256	 * add the resource before allocating it.  Note that these
1257	 * resources will not be reserved.
1258	 */
1259	if (!isdefault && resource_list_find(rl, type, *rid) == NULL)
1260		resource_list_add(rl, type, *rid, start, end, count);
1261	res = resource_list_alloc(rl, bus, child, type, rid, start, end, count,
1262	    flags);
1263	if (res != NULL && type == SYS_RES_IRQ) {
1264	    /*
1265	     * Since bus_config_intr() takes immediate effect, we cannot
1266	     * configure the interrupt associated with a device when we
1267	     * parse the resources but have to defer it until a driver
1268	     * actually allocates the interrupt via bus_alloc_resource().
1269	     *
1270	     * XXX: Should we handle the lookup failing?
1271	     */
1272	    if (ACPI_SUCCESS(acpi_lookup_irq_resource(child, *rid, res, &ares)))
1273		acpi_config_intr(child, &ares);
1274	}
1275
1276	/*
1277	 * If this is an allocation of the "default" range for a given
1278	 * RID, fetch the exact bounds for this resource from the
1279	 * resource list entry to try to allocate the range from the
1280	 * system resource regions.
1281	 */
1282	if (res == NULL && isdefault) {
1283	    rle = resource_list_find(rl, type, *rid);
1284	    if (rle != NULL) {
1285		start = rle->start;
1286		end = rle->end;
1287		count = rle->count;
1288	    }
1289	}
1290    } else
1291	res = BUS_ALLOC_RESOURCE(device_get_parent(bus), child, type, rid,
1292	    start, end, count, flags);
1293
1294    /*
1295     * If the first attempt failed and this is an allocation of a
1296     * specific range, try to satisfy the request via a suballocation
1297     * from our system resource regions.
1298     */
1299    if (res == NULL && start + count - 1 == end)
1300	res = acpi_alloc_sysres(child, type, rid, start, end, count, flags);
1301    return (res);
1302}
1303
1304/*
1305 * Attempt to allocate a specific resource range from the system
1306 * resource ranges.  Note that we only handle memory and I/O port
1307 * system resources.
1308 */
1309struct resource *
1310acpi_alloc_sysres(device_t child, int type, int *rid, u_long start, u_long end,
1311    u_long count, u_int flags)
1312{
1313    struct rman *rm;
1314    struct resource *res;
1315
1316    switch (type) {
1317    case SYS_RES_IOPORT:
1318	rm = &acpi_rman_io;
1319	break;
1320    case SYS_RES_MEMORY:
1321	rm = &acpi_rman_mem;
1322	break;
1323    default:
1324	return (NULL);
1325    }
1326
1327    KASSERT(start + count - 1 == end, ("wildcard resource range"));
1328    res = rman_reserve_resource(rm, start, end, count, flags & ~RF_ACTIVE,
1329	child);
1330    if (res == NULL)
1331	return (NULL);
1332
1333    rman_set_rid(res, *rid);
1334
1335    /* If requested, activate the resource using the parent's method. */
1336    if (flags & RF_ACTIVE)
1337	if (bus_activate_resource(child, type, *rid, res) != 0) {
1338	    rman_release_resource(res);
1339	    return (NULL);
1340	}
1341
1342    return (res);
1343}
1344
1345static int
1346acpi_is_resource_managed(int type, struct resource *r)
1347{
1348
1349    /* We only handle memory and IO resources through rman. */
1350    switch (type) {
1351    case SYS_RES_IOPORT:
1352	return (rman_is_region_manager(r, &acpi_rman_io));
1353    case SYS_RES_MEMORY:
1354	return (rman_is_region_manager(r, &acpi_rman_mem));
1355    }
1356    return (0);
1357}
1358
1359static int
1360acpi_adjust_resource(device_t bus, device_t child, int type, struct resource *r,
1361    u_long start, u_long end)
1362{
1363
1364    if (acpi_is_resource_managed(type, r))
1365	return (rman_adjust_resource(r, start, end));
1366    return (bus_generic_adjust_resource(bus, child, type, r, start, end));
1367}
1368
1369static int
1370acpi_release_resource(device_t bus, device_t child, int type, int rid,
1371    struct resource *r)
1372{
1373    int ret;
1374
1375    /*
1376     * If this resource belongs to one of our internal managers,
1377     * deactivate it and release it to the local pool.
1378     */
1379    if (acpi_is_resource_managed(type, r)) {
1380	if (rman_get_flags(r) & RF_ACTIVE) {
1381	    ret = bus_deactivate_resource(child, type, rid, r);
1382	    if (ret != 0)
1383		return (ret);
1384	}
1385	return (rman_release_resource(r));
1386    }
1387
1388    return (bus_generic_rl_release_resource(bus, child, type, rid, r));
1389}
1390
1391static void
1392acpi_delete_resource(device_t bus, device_t child, int type, int rid)
1393{
1394    struct resource_list *rl;
1395
1396    rl = acpi_get_rlist(bus, child);
1397    if (resource_list_busy(rl, type, rid)) {
1398	device_printf(bus, "delete_resource: Resource still owned by child"
1399	    " (type=%d, rid=%d)\n", type, rid);
1400	return;
1401    }
1402    resource_list_unreserve(rl, bus, child, type, rid);
1403    resource_list_delete(rl, type, rid);
1404}
1405
1406/* Allocate an IO port or memory resource, given its GAS. */
1407int
1408acpi_bus_alloc_gas(device_t dev, int *type, int *rid, ACPI_GENERIC_ADDRESS *gas,
1409    struct resource **res, u_int flags)
1410{
1411    int error, res_type;
1412
1413    error = ENOMEM;
1414    if (type == NULL || rid == NULL || gas == NULL || res == NULL)
1415	return (EINVAL);
1416
1417    /* We only support memory and IO spaces. */
1418    switch (gas->SpaceId) {
1419    case ACPI_ADR_SPACE_SYSTEM_MEMORY:
1420	res_type = SYS_RES_MEMORY;
1421	break;
1422    case ACPI_ADR_SPACE_SYSTEM_IO:
1423	res_type = SYS_RES_IOPORT;
1424	break;
1425    default:
1426	return (EOPNOTSUPP);
1427    }
1428
1429    /*
1430     * If the register width is less than 8, assume the BIOS author means
1431     * it is a bit field and just allocate a byte.
1432     */
1433    if (gas->BitWidth && gas->BitWidth < 8)
1434	gas->BitWidth = 8;
1435
1436    /* Validate the address after we're sure we support the space. */
1437    if (gas->Address == 0 || gas->BitWidth == 0)
1438	return (EINVAL);
1439
1440    bus_set_resource(dev, res_type, *rid, gas->Address,
1441	gas->BitWidth / 8);
1442    *res = bus_alloc_resource_any(dev, res_type, rid, RF_ACTIVE | flags);
1443    if (*res != NULL) {
1444	*type = res_type;
1445	error = 0;
1446    } else
1447	bus_delete_resource(dev, res_type, *rid);
1448
1449    return (error);
1450}
1451
1452/* Probe _HID and _CID for compatible ISA PNP ids. */
1453static uint32_t
1454acpi_isa_get_logicalid(device_t dev)
1455{
1456    ACPI_DEVICE_INFO	*devinfo;
1457    ACPI_HANDLE		h;
1458    uint32_t		pnpid;
1459
1460    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1461
1462    /* Fetch and validate the HID. */
1463    if ((h = acpi_get_handle(dev)) == NULL ||
1464	ACPI_FAILURE(AcpiGetObjectInfo(h, &devinfo)))
1465	return_VALUE (0);
1466
1467    pnpid = (devinfo->Valid & ACPI_VALID_HID) != 0 &&
1468	devinfo->HardwareId.Length >= ACPI_EISAID_STRING_SIZE ?
1469	PNP_EISAID(devinfo->HardwareId.String) : 0;
1470    AcpiOsFree(devinfo);
1471
1472    return_VALUE (pnpid);
1473}
1474
1475static int
1476acpi_isa_get_compatid(device_t dev, uint32_t *cids, int count)
1477{
1478    ACPI_DEVICE_INFO	*devinfo;
1479    ACPI_DEVICE_ID	*ids;
1480    ACPI_HANDLE		h;
1481    uint32_t		*pnpid;
1482    int			i, valid;
1483
1484    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1485
1486    pnpid = cids;
1487
1488    /* Fetch and validate the CID */
1489    if ((h = acpi_get_handle(dev)) == NULL ||
1490	ACPI_FAILURE(AcpiGetObjectInfo(h, &devinfo)))
1491	return_VALUE (0);
1492
1493    if ((devinfo->Valid & ACPI_VALID_CID) == 0) {
1494	AcpiOsFree(devinfo);
1495	return_VALUE (0);
1496    }
1497
1498    if (devinfo->CompatibleIdList.Count < count)
1499	count = devinfo->CompatibleIdList.Count;
1500    ids = devinfo->CompatibleIdList.Ids;
1501    for (i = 0, valid = 0; i < count; i++)
1502	if (ids[i].Length >= ACPI_EISAID_STRING_SIZE &&
1503	    strncmp(ids[i].String, "PNP", 3) == 0) {
1504	    *pnpid++ = PNP_EISAID(ids[i].String);
1505	    valid++;
1506	}
1507    AcpiOsFree(devinfo);
1508
1509    return_VALUE (valid);
1510}
1511
1512static char *
1513acpi_device_id_probe(device_t bus, device_t dev, char **ids)
1514{
1515    ACPI_HANDLE h;
1516    ACPI_OBJECT_TYPE t;
1517    int i;
1518
1519    h = acpi_get_handle(dev);
1520    if (ids == NULL || h == NULL)
1521	return (NULL);
1522    t = acpi_get_type(dev);
1523    if (t != ACPI_TYPE_DEVICE && t != ACPI_TYPE_PROCESSOR)
1524	return (NULL);
1525
1526    /* Try to match one of the array of IDs with a HID or CID. */
1527    for (i = 0; ids[i] != NULL; i++) {
1528	if (acpi_MatchHid(h, ids[i]))
1529	    return (ids[i]);
1530    }
1531    return (NULL);
1532}
1533
1534static ACPI_STATUS
1535acpi_device_eval_obj(device_t bus, device_t dev, ACPI_STRING pathname,
1536    ACPI_OBJECT_LIST *parameters, ACPI_BUFFER *ret)
1537{
1538    ACPI_HANDLE h;
1539
1540    if (dev == NULL)
1541	h = ACPI_ROOT_OBJECT;
1542    else if ((h = acpi_get_handle(dev)) == NULL)
1543	return (AE_BAD_PARAMETER);
1544    return (AcpiEvaluateObject(h, pathname, parameters, ret));
1545}
1546
1547int
1548acpi_device_pwr_for_sleep(device_t bus, device_t dev, int *dstate)
1549{
1550    struct acpi_softc *sc;
1551    ACPI_HANDLE handle;
1552    ACPI_STATUS status;
1553    char sxd[8];
1554
1555    handle = acpi_get_handle(dev);
1556
1557    /*
1558     * XXX If we find these devices, don't try to power them down.
1559     * The serial and IRDA ports on my T23 hang the system when
1560     * set to D3 and it appears that such legacy devices may
1561     * need special handling in their drivers.
1562     */
1563    if (dstate == NULL || handle == NULL ||
1564	acpi_MatchHid(handle, "PNP0500") ||
1565	acpi_MatchHid(handle, "PNP0501") ||
1566	acpi_MatchHid(handle, "PNP0502") ||
1567	acpi_MatchHid(handle, "PNP0510") ||
1568	acpi_MatchHid(handle, "PNP0511"))
1569	return (ENXIO);
1570
1571    /*
1572     * Override next state with the value from _SxD, if present.
1573     * Note illegal _S0D is evaluated because some systems expect this.
1574     */
1575    sc = device_get_softc(bus);
1576    snprintf(sxd, sizeof(sxd), "_S%dD", sc->acpi_sstate);
1577    status = acpi_GetInteger(handle, sxd, dstate);
1578    if (ACPI_FAILURE(status) && status != AE_NOT_FOUND) {
1579	    device_printf(dev, "failed to get %s on %s: %s\n", sxd,
1580		acpi_name(handle), AcpiFormatException(status));
1581	    return (ENXIO);
1582    }
1583
1584    return (0);
1585}
1586
1587/* Callback arg for our implementation of walking the namespace. */
1588struct acpi_device_scan_ctx {
1589    acpi_scan_cb_t	user_fn;
1590    void		*arg;
1591    ACPI_HANDLE		parent;
1592};
1593
1594static ACPI_STATUS
1595acpi_device_scan_cb(ACPI_HANDLE h, UINT32 level, void *arg, void **retval)
1596{
1597    struct acpi_device_scan_ctx *ctx;
1598    device_t dev, old_dev;
1599    ACPI_STATUS status;
1600    ACPI_OBJECT_TYPE type;
1601
1602    /*
1603     * Skip this device if we think we'll have trouble with it or it is
1604     * the parent where the scan began.
1605     */
1606    ctx = (struct acpi_device_scan_ctx *)arg;
1607    if (acpi_avoid(h) || h == ctx->parent)
1608	return (AE_OK);
1609
1610    /* If this is not a valid device type (e.g., a method), skip it. */
1611    if (ACPI_FAILURE(AcpiGetType(h, &type)))
1612	return (AE_OK);
1613    if (type != ACPI_TYPE_DEVICE && type != ACPI_TYPE_PROCESSOR &&
1614	type != ACPI_TYPE_THERMAL && type != ACPI_TYPE_POWER)
1615	return (AE_OK);
1616
1617    /*
1618     * Call the user function with the current device.  If it is unchanged
1619     * afterwards, return.  Otherwise, we update the handle to the new dev.
1620     */
1621    old_dev = acpi_get_device(h);
1622    dev = old_dev;
1623    status = ctx->user_fn(h, &dev, level, ctx->arg);
1624    if (ACPI_FAILURE(status) || old_dev == dev)
1625	return (status);
1626
1627    /* Remove the old child and its connection to the handle. */
1628    if (old_dev != NULL) {
1629	device_delete_child(device_get_parent(old_dev), old_dev);
1630	AcpiDetachData(h, acpi_fake_objhandler);
1631    }
1632
1633    /* Recreate the handle association if the user created a device. */
1634    if (dev != NULL)
1635	AcpiAttachData(h, acpi_fake_objhandler, dev);
1636
1637    return (AE_OK);
1638}
1639
1640static ACPI_STATUS
1641acpi_device_scan_children(device_t bus, device_t dev, int max_depth,
1642    acpi_scan_cb_t user_fn, void *arg)
1643{
1644    ACPI_HANDLE h;
1645    struct acpi_device_scan_ctx ctx;
1646
1647    if (acpi_disabled("children"))
1648	return (AE_OK);
1649
1650    if (dev == NULL)
1651	h = ACPI_ROOT_OBJECT;
1652    else if ((h = acpi_get_handle(dev)) == NULL)
1653	return (AE_BAD_PARAMETER);
1654    ctx.user_fn = user_fn;
1655    ctx.arg = arg;
1656    ctx.parent = h;
1657    return (AcpiWalkNamespace(ACPI_TYPE_ANY, h, max_depth,
1658	acpi_device_scan_cb, NULL, &ctx, NULL));
1659}
1660
1661/*
1662 * Even though ACPI devices are not PCI, we use the PCI approach for setting
1663 * device power states since it's close enough to ACPI.
1664 */
1665static int
1666acpi_set_powerstate(device_t child, int state)
1667{
1668    ACPI_HANDLE h;
1669    ACPI_STATUS status;
1670
1671    h = acpi_get_handle(child);
1672    if (state < ACPI_STATE_D0 || state > ACPI_D_STATES_MAX)
1673	return (EINVAL);
1674    if (h == NULL)
1675	return (0);
1676
1677    /* Ignore errors if the power methods aren't present. */
1678    status = acpi_pwr_switch_consumer(h, state);
1679    if (ACPI_SUCCESS(status)) {
1680	if (bootverbose)
1681	    device_printf(child, "set ACPI power state D%d on %s\n",
1682		state, acpi_name(h));
1683    } else if (status != AE_NOT_FOUND)
1684	device_printf(child,
1685	    "failed to set ACPI power state D%d on %s: %s\n", state,
1686	    acpi_name(h), AcpiFormatException(status));
1687
1688    return (0);
1689}
1690
1691static int
1692acpi_isa_pnp_probe(device_t bus, device_t child, struct isa_pnp_id *ids)
1693{
1694    int			result, cid_count, i;
1695    uint32_t		lid, cids[8];
1696
1697    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1698
1699    /*
1700     * ISA-style drivers attached to ACPI may persist and
1701     * probe manually if we return ENOENT.  We never want
1702     * that to happen, so don't ever return it.
1703     */
1704    result = ENXIO;
1705
1706    /* Scan the supplied IDs for a match */
1707    lid = acpi_isa_get_logicalid(child);
1708    cid_count = acpi_isa_get_compatid(child, cids, 8);
1709    while (ids && ids->ip_id) {
1710	if (lid == ids->ip_id) {
1711	    result = 0;
1712	    goto out;
1713	}
1714	for (i = 0; i < cid_count; i++) {
1715	    if (cids[i] == ids->ip_id) {
1716		result = 0;
1717		goto out;
1718	    }
1719	}
1720	ids++;
1721    }
1722
1723 out:
1724    if (result == 0 && ids->ip_desc)
1725	device_set_desc(child, ids->ip_desc);
1726
1727    return_VALUE (result);
1728}
1729
1730#if defined(__i386__) || defined(__amd64__)
1731/*
1732 * Look for a MCFG table.  If it is present, use the settings for
1733 * domain (segment) 0 to setup PCI config space access via the memory
1734 * map.
1735 */
1736static void
1737acpi_enable_pcie(void)
1738{
1739	ACPI_TABLE_HEADER *hdr;
1740	ACPI_MCFG_ALLOCATION *alloc, *end;
1741	ACPI_STATUS status;
1742
1743	status = AcpiGetTable(ACPI_SIG_MCFG, 1, &hdr);
1744	if (ACPI_FAILURE(status))
1745		return;
1746
1747	end = (ACPI_MCFG_ALLOCATION *)((char *)hdr + hdr->Length);
1748	alloc = (ACPI_MCFG_ALLOCATION *)((ACPI_TABLE_MCFG *)hdr + 1);
1749	while (alloc < end) {
1750		if (alloc->PciSegment == 0) {
1751			pcie_cfgregopen(alloc->Address, alloc->StartBusNumber,
1752			    alloc->EndBusNumber);
1753			return;
1754		}
1755		alloc++;
1756	}
1757}
1758#endif
1759
1760/*
1761 * Scan all of the ACPI namespace and attach child devices.
1762 *
1763 * We should only expect to find devices in the \_PR, \_TZ, \_SI, and
1764 * \_SB scopes, and \_PR and \_TZ became obsolete in the ACPI 2.0 spec.
1765 * However, in violation of the spec, some systems place their PCI link
1766 * devices in \, so we have to walk the whole namespace.  We check the
1767 * type of namespace nodes, so this should be ok.
1768 */
1769static void
1770acpi_probe_children(device_t bus)
1771{
1772
1773    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1774
1775    /*
1776     * Scan the namespace and insert placeholders for all the devices that
1777     * we find.  We also probe/attach any early devices.
1778     *
1779     * Note that we use AcpiWalkNamespace rather than AcpiGetDevices because
1780     * we want to create nodes for all devices, not just those that are
1781     * currently present. (This assumes that we don't want to create/remove
1782     * devices as they appear, which might be smarter.)
1783     */
1784    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "namespace scan\n"));
1785    AcpiWalkNamespace(ACPI_TYPE_ANY, ACPI_ROOT_OBJECT, 100, acpi_probe_child,
1786	NULL, bus, NULL);
1787
1788    /* Pre-allocate resources for our rman from any sysresource devices. */
1789    acpi_sysres_alloc(bus);
1790
1791    /* Reserve resources already allocated to children. */
1792    acpi_reserve_resources(bus);
1793
1794    /* Create any static children by calling device identify methods. */
1795    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "device identify routines\n"));
1796    bus_generic_probe(bus);
1797
1798    /* Probe/attach all children, created statically and from the namespace. */
1799    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "acpi bus_generic_attach\n"));
1800    bus_generic_attach(bus);
1801
1802    /* Attach wake sysctls. */
1803    acpi_wake_sysctl_walk(bus);
1804
1805    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "done attaching children\n"));
1806    return_VOID;
1807}
1808
1809/*
1810 * Determine the probe order for a given device.
1811 */
1812static void
1813acpi_probe_order(ACPI_HANDLE handle, int *order)
1814{
1815	ACPI_OBJECT_TYPE type;
1816
1817	/*
1818	 * 0. CPUs
1819	 * 1. I/O port and memory system resource holders
1820	 * 2. Clocks and timers (to handle early accesses)
1821	 * 3. Embedded controllers (to handle early accesses)
1822	 * 4. PCI Link Devices
1823	 */
1824	AcpiGetType(handle, &type);
1825	if (type == ACPI_TYPE_PROCESSOR)
1826		*order = 0;
1827	else if (acpi_MatchHid(handle, "PNP0C01") ||
1828	    acpi_MatchHid(handle, "PNP0C02"))
1829		*order = 1;
1830	else if (acpi_MatchHid(handle, "PNP0100") ||
1831	    acpi_MatchHid(handle, "PNP0103") ||
1832	    acpi_MatchHid(handle, "PNP0B00"))
1833		*order = 2;
1834	else if (acpi_MatchHid(handle, "PNP0C09"))
1835		*order = 3;
1836	else if (acpi_MatchHid(handle, "PNP0C0F"))
1837		*order = 4;
1838}
1839
1840/*
1841 * Evaluate a child device and determine whether we might attach a device to
1842 * it.
1843 */
1844static ACPI_STATUS
1845acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
1846{
1847    struct acpi_prw_data prw;
1848    ACPI_OBJECT_TYPE type;
1849    ACPI_HANDLE h;
1850    device_t bus, child;
1851    char *handle_str;
1852    int order;
1853
1854    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1855
1856    if (acpi_disabled("children"))
1857	return_ACPI_STATUS (AE_OK);
1858
1859    /* Skip this device if we think we'll have trouble with it. */
1860    if (acpi_avoid(handle))
1861	return_ACPI_STATUS (AE_OK);
1862
1863    bus = (device_t)context;
1864    if (ACPI_SUCCESS(AcpiGetType(handle, &type))) {
1865	handle_str = acpi_name(handle);
1866	switch (type) {
1867	case ACPI_TYPE_DEVICE:
1868	    /*
1869	     * Since we scan from \, be sure to skip system scope objects.
1870	     * \_SB_ and \_TZ_ are defined in ACPICA as devices to work around
1871	     * BIOS bugs.  For example, \_SB_ is to allow \_SB_._INI to be run
1872	     * during the intialization and \_TZ_ is to support Notify() on it.
1873	     */
1874	    if (strcmp(handle_str, "\\_SB_") == 0 ||
1875		strcmp(handle_str, "\\_TZ_") == 0)
1876		break;
1877	    if (acpi_parse_prw(handle, &prw) == 0)
1878		AcpiSetupGpeForWake(handle, prw.gpe_handle, prw.gpe_bit);
1879
1880	    /*
1881	     * Ignore devices that do not have a _HID or _CID.  They should
1882	     * be discovered by other buses (e.g. the PCI bus driver).
1883	     */
1884	    if (!acpi_has_hid(handle))
1885		break;
1886	    /* FALLTHROUGH */
1887	case ACPI_TYPE_PROCESSOR:
1888	case ACPI_TYPE_THERMAL:
1889	case ACPI_TYPE_POWER:
1890	    /*
1891	     * Create a placeholder device for this node.  Sort the
1892	     * placeholder so that the probe/attach passes will run
1893	     * breadth-first.  Orders less than ACPI_DEV_BASE_ORDER
1894	     * are reserved for special objects (i.e., system
1895	     * resources).
1896	     */
1897	    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "scanning '%s'\n", handle_str));
1898	    order = level * 10 + ACPI_DEV_BASE_ORDER;
1899	    acpi_probe_order(handle, &order);
1900	    child = BUS_ADD_CHILD(bus, order, NULL, -1);
1901	    if (child == NULL)
1902		break;
1903
1904	    /* Associate the handle with the device_t and vice versa. */
1905	    acpi_set_handle(child, handle);
1906	    AcpiAttachData(handle, acpi_fake_objhandler, child);
1907
1908	    /*
1909	     * Check that the device is present.  If it's not present,
1910	     * leave it disabled (so that we have a device_t attached to
1911	     * the handle, but we don't probe it).
1912	     *
1913	     * XXX PCI link devices sometimes report "present" but not
1914	     * "functional" (i.e. if disabled).  Go ahead and probe them
1915	     * anyway since we may enable them later.
1916	     */
1917	    if (type == ACPI_TYPE_DEVICE && !acpi_DeviceIsPresent(child)) {
1918		/* Never disable PCI link devices. */
1919		if (acpi_MatchHid(handle, "PNP0C0F"))
1920		    break;
1921		/*
1922		 * Docking stations should remain enabled since the system
1923		 * may be undocked at boot.
1924		 */
1925		if (ACPI_SUCCESS(AcpiGetHandle(handle, "_DCK", &h)))
1926		    break;
1927
1928		device_disable(child);
1929		break;
1930	    }
1931
1932	    /*
1933	     * Get the device's resource settings and attach them.
1934	     * Note that if the device has _PRS but no _CRS, we need
1935	     * to decide when it's appropriate to try to configure the
1936	     * device.  Ignore the return value here; it's OK for the
1937	     * device not to have any resources.
1938	     */
1939	    acpi_parse_resources(child, handle, &acpi_res_parse_set, NULL);
1940	    break;
1941	}
1942    }
1943
1944    return_ACPI_STATUS (AE_OK);
1945}
1946
1947/*
1948 * AcpiAttachData() requires an object handler but never uses it.  This is a
1949 * placeholder object handler so we can store a device_t in an ACPI_HANDLE.
1950 */
1951void
1952acpi_fake_objhandler(ACPI_HANDLE h, void *data)
1953{
1954}
1955
1956static void
1957acpi_shutdown_final(void *arg, int howto)
1958{
1959    struct acpi_softc *sc = (struct acpi_softc *)arg;
1960    ACPI_STATUS status;
1961
1962    /*
1963     * XXX Shutdown code should only run on the BSP (cpuid 0).
1964     * Some chipsets do not power off the system correctly if called from
1965     * an AP.
1966     */
1967    if ((howto & RB_POWEROFF) != 0) {
1968	status = AcpiEnterSleepStatePrep(ACPI_STATE_S5);
1969	if (ACPI_FAILURE(status)) {
1970	    device_printf(sc->acpi_dev, "AcpiEnterSleepStatePrep failed - %s\n",
1971		AcpiFormatException(status));
1972	    return;
1973	}
1974	device_printf(sc->acpi_dev, "Powering system off\n");
1975	ACPI_DISABLE_IRQS();
1976	status = AcpiEnterSleepState(ACPI_STATE_S5);
1977	if (ACPI_FAILURE(status))
1978	    device_printf(sc->acpi_dev, "power-off failed - %s\n",
1979		AcpiFormatException(status));
1980	else {
1981	    DELAY(1000000);
1982	    device_printf(sc->acpi_dev, "power-off failed - timeout\n");
1983	}
1984    } else if ((howto & RB_HALT) == 0 && sc->acpi_handle_reboot) {
1985	/* Reboot using the reset register. */
1986	status = AcpiReset();
1987	if (ACPI_SUCCESS(status)) {
1988	    DELAY(1000000);
1989	    device_printf(sc->acpi_dev, "reset failed - timeout\n");
1990	} else if (status != AE_NOT_EXIST)
1991	    device_printf(sc->acpi_dev, "reset failed - %s\n",
1992		AcpiFormatException(status));
1993    } else if (sc->acpi_do_disable && panicstr == NULL) {
1994	/*
1995	 * Only disable ACPI if the user requested.  On some systems, writing
1996	 * the disable value to SMI_CMD hangs the system.
1997	 */
1998	device_printf(sc->acpi_dev, "Shutting down\n");
1999	AcpiTerminate();
2000    }
2001}
2002
2003static void
2004acpi_enable_fixed_events(struct acpi_softc *sc)
2005{
2006    static int	first_time = 1;
2007
2008    /* Enable and clear fixed events and install handlers. */
2009    if ((AcpiGbl_FADT.Flags & ACPI_FADT_POWER_BUTTON) == 0) {
2010	AcpiClearEvent(ACPI_EVENT_POWER_BUTTON);
2011	AcpiInstallFixedEventHandler(ACPI_EVENT_POWER_BUTTON,
2012				     acpi_event_power_button_sleep, sc);
2013	if (first_time)
2014	    device_printf(sc->acpi_dev, "Power Button (fixed)\n");
2015    }
2016    if ((AcpiGbl_FADT.Flags & ACPI_FADT_SLEEP_BUTTON) == 0) {
2017	AcpiClearEvent(ACPI_EVENT_SLEEP_BUTTON);
2018	AcpiInstallFixedEventHandler(ACPI_EVENT_SLEEP_BUTTON,
2019				     acpi_event_sleep_button_sleep, sc);
2020	if (first_time)
2021	    device_printf(sc->acpi_dev, "Sleep Button (fixed)\n");
2022    }
2023
2024    first_time = 0;
2025}
2026
2027/*
2028 * Returns true if the device is actually present and should
2029 * be attached to.  This requires the present, enabled, UI-visible
2030 * and diagnostics-passed bits to be set.
2031 */
2032BOOLEAN
2033acpi_DeviceIsPresent(device_t dev)
2034{
2035    ACPI_DEVICE_INFO	*devinfo;
2036    ACPI_HANDLE		h;
2037    BOOLEAN		present;
2038
2039    if ((h = acpi_get_handle(dev)) == NULL ||
2040	ACPI_FAILURE(AcpiGetObjectInfo(h, &devinfo)))
2041	return (FALSE);
2042
2043    /* If no _STA method, must be present */
2044    present = (devinfo->Valid & ACPI_VALID_STA) == 0 ||
2045	ACPI_DEVICE_PRESENT(devinfo->CurrentStatus) ? TRUE : FALSE;
2046
2047    AcpiOsFree(devinfo);
2048    return (present);
2049}
2050
2051/*
2052 * Returns true if the battery is actually present and inserted.
2053 */
2054BOOLEAN
2055acpi_BatteryIsPresent(device_t dev)
2056{
2057    ACPI_DEVICE_INFO	*devinfo;
2058    ACPI_HANDLE		h;
2059    BOOLEAN		present;
2060
2061    if ((h = acpi_get_handle(dev)) == NULL ||
2062	ACPI_FAILURE(AcpiGetObjectInfo(h, &devinfo)))
2063	return (FALSE);
2064
2065    /* If no _STA method, must be present */
2066    present = (devinfo->Valid & ACPI_VALID_STA) == 0 ||
2067	ACPI_BATTERY_PRESENT(devinfo->CurrentStatus) ? TRUE : FALSE;
2068
2069    AcpiOsFree(devinfo);
2070    return (present);
2071}
2072
2073/*
2074 * Returns true if a device has at least one valid device ID.
2075 */
2076static BOOLEAN
2077acpi_has_hid(ACPI_HANDLE h)
2078{
2079    ACPI_DEVICE_INFO	*devinfo;
2080    BOOLEAN		ret;
2081
2082    if (h == NULL ||
2083	ACPI_FAILURE(AcpiGetObjectInfo(h, &devinfo)))
2084	return (FALSE);
2085
2086    ret = FALSE;
2087    if ((devinfo->Valid & ACPI_VALID_HID) != 0)
2088	ret = TRUE;
2089    else if ((devinfo->Valid & ACPI_VALID_CID) != 0)
2090	if (devinfo->CompatibleIdList.Count > 0)
2091	    ret = TRUE;
2092
2093    AcpiOsFree(devinfo);
2094    return (ret);
2095}
2096
2097/*
2098 * Match a HID string against a handle
2099 */
2100BOOLEAN
2101acpi_MatchHid(ACPI_HANDLE h, const char *hid)
2102{
2103    ACPI_DEVICE_INFO	*devinfo;
2104    BOOLEAN		ret;
2105    int			i;
2106
2107    if (hid == NULL || h == NULL ||
2108	ACPI_FAILURE(AcpiGetObjectInfo(h, &devinfo)))
2109	return (FALSE);
2110
2111    ret = FALSE;
2112    if ((devinfo->Valid & ACPI_VALID_HID) != 0 &&
2113	strcmp(hid, devinfo->HardwareId.String) == 0)
2114	    ret = TRUE;
2115    else if ((devinfo->Valid & ACPI_VALID_CID) != 0)
2116	for (i = 0; i < devinfo->CompatibleIdList.Count; i++) {
2117	    if (strcmp(hid, devinfo->CompatibleIdList.Ids[i].String) == 0) {
2118		ret = TRUE;
2119		break;
2120	    }
2121	}
2122
2123    AcpiOsFree(devinfo);
2124    return (ret);
2125}
2126
2127/*
2128 * Return the handle of a named object within our scope, ie. that of (parent)
2129 * or one if its parents.
2130 */
2131ACPI_STATUS
2132acpi_GetHandleInScope(ACPI_HANDLE parent, char *path, ACPI_HANDLE *result)
2133{
2134    ACPI_HANDLE		r;
2135    ACPI_STATUS		status;
2136
2137    /* Walk back up the tree to the root */
2138    for (;;) {
2139	status = AcpiGetHandle(parent, path, &r);
2140	if (ACPI_SUCCESS(status)) {
2141	    *result = r;
2142	    return (AE_OK);
2143	}
2144	/* XXX Return error here? */
2145	if (status != AE_NOT_FOUND)
2146	    return (AE_OK);
2147	if (ACPI_FAILURE(AcpiGetParent(parent, &r)))
2148	    return (AE_NOT_FOUND);
2149	parent = r;
2150    }
2151}
2152
2153/*
2154 * Allocate a buffer with a preset data size.
2155 */
2156ACPI_BUFFER *
2157acpi_AllocBuffer(int size)
2158{
2159    ACPI_BUFFER	*buf;
2160
2161    if ((buf = malloc(size + sizeof(*buf), M_ACPIDEV, M_NOWAIT)) == NULL)
2162	return (NULL);
2163    buf->Length = size;
2164    buf->Pointer = (void *)(buf + 1);
2165    return (buf);
2166}
2167
2168ACPI_STATUS
2169acpi_SetInteger(ACPI_HANDLE handle, char *path, UINT32 number)
2170{
2171    ACPI_OBJECT arg1;
2172    ACPI_OBJECT_LIST args;
2173
2174    arg1.Type = ACPI_TYPE_INTEGER;
2175    arg1.Integer.Value = number;
2176    args.Count = 1;
2177    args.Pointer = &arg1;
2178
2179    return (AcpiEvaluateObject(handle, path, &args, NULL));
2180}
2181
2182/*
2183 * Evaluate a path that should return an integer.
2184 */
2185ACPI_STATUS
2186acpi_GetInteger(ACPI_HANDLE handle, char *path, UINT32 *number)
2187{
2188    ACPI_STATUS	status;
2189    ACPI_BUFFER	buf;
2190    ACPI_OBJECT	param;
2191
2192    if (handle == NULL)
2193	handle = ACPI_ROOT_OBJECT;
2194
2195    /*
2196     * Assume that what we've been pointed at is an Integer object, or
2197     * a method that will return an Integer.
2198     */
2199    buf.Pointer = &param;
2200    buf.Length = sizeof(param);
2201    status = AcpiEvaluateObject(handle, path, NULL, &buf);
2202    if (ACPI_SUCCESS(status)) {
2203	if (param.Type == ACPI_TYPE_INTEGER)
2204	    *number = param.Integer.Value;
2205	else
2206	    status = AE_TYPE;
2207    }
2208
2209    /*
2210     * In some applications, a method that's expected to return an Integer
2211     * may instead return a Buffer (probably to simplify some internal
2212     * arithmetic).  We'll try to fetch whatever it is, and if it's a Buffer,
2213     * convert it into an Integer as best we can.
2214     *
2215     * This is a hack.
2216     */
2217    if (status == AE_BUFFER_OVERFLOW) {
2218	if ((buf.Pointer = AcpiOsAllocate(buf.Length)) == NULL) {
2219	    status = AE_NO_MEMORY;
2220	} else {
2221	    status = AcpiEvaluateObject(handle, path, NULL, &buf);
2222	    if (ACPI_SUCCESS(status))
2223		status = acpi_ConvertBufferToInteger(&buf, number);
2224	    AcpiOsFree(buf.Pointer);
2225	}
2226    }
2227    return (status);
2228}
2229
2230ACPI_STATUS
2231acpi_ConvertBufferToInteger(ACPI_BUFFER *bufp, UINT32 *number)
2232{
2233    ACPI_OBJECT	*p;
2234    UINT8	*val;
2235    int		i;
2236
2237    p = (ACPI_OBJECT *)bufp->Pointer;
2238    if (p->Type == ACPI_TYPE_INTEGER) {
2239	*number = p->Integer.Value;
2240	return (AE_OK);
2241    }
2242    if (p->Type != ACPI_TYPE_BUFFER)
2243	return (AE_TYPE);
2244    if (p->Buffer.Length > sizeof(int))
2245	return (AE_BAD_DATA);
2246
2247    *number = 0;
2248    val = p->Buffer.Pointer;
2249    for (i = 0; i < p->Buffer.Length; i++)
2250	*number += val[i] << (i * 8);
2251    return (AE_OK);
2252}
2253
2254/*
2255 * Iterate over the elements of an a package object, calling the supplied
2256 * function for each element.
2257 *
2258 * XXX possible enhancement might be to abort traversal on error.
2259 */
2260ACPI_STATUS
2261acpi_ForeachPackageObject(ACPI_OBJECT *pkg,
2262	void (*func)(ACPI_OBJECT *comp, void *arg), void *arg)
2263{
2264    ACPI_OBJECT	*comp;
2265    int		i;
2266
2267    if (pkg == NULL || pkg->Type != ACPI_TYPE_PACKAGE)
2268	return (AE_BAD_PARAMETER);
2269
2270    /* Iterate over components */
2271    i = 0;
2272    comp = pkg->Package.Elements;
2273    for (; i < pkg->Package.Count; i++, comp++)
2274	func(comp, arg);
2275
2276    return (AE_OK);
2277}
2278
2279/*
2280 * Find the (index)th resource object in a set.
2281 */
2282ACPI_STATUS
2283acpi_FindIndexedResource(ACPI_BUFFER *buf, int index, ACPI_RESOURCE **resp)
2284{
2285    ACPI_RESOURCE	*rp;
2286    int			i;
2287
2288    rp = (ACPI_RESOURCE *)buf->Pointer;
2289    i = index;
2290    while (i-- > 0) {
2291	/* Range check */
2292	if (rp > (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
2293	    return (AE_BAD_PARAMETER);
2294
2295	/* Check for terminator */
2296	if (rp->Type == ACPI_RESOURCE_TYPE_END_TAG || rp->Length == 0)
2297	    return (AE_NOT_FOUND);
2298	rp = ACPI_NEXT_RESOURCE(rp);
2299    }
2300    if (resp != NULL)
2301	*resp = rp;
2302
2303    return (AE_OK);
2304}
2305
2306/*
2307 * Append an ACPI_RESOURCE to an ACPI_BUFFER.
2308 *
2309 * Given a pointer to an ACPI_RESOURCE structure, expand the ACPI_BUFFER
2310 * provided to contain it.  If the ACPI_BUFFER is empty, allocate a sensible
2311 * backing block.  If the ACPI_RESOURCE is NULL, return an empty set of
2312 * resources.
2313 */
2314#define ACPI_INITIAL_RESOURCE_BUFFER_SIZE	512
2315
2316ACPI_STATUS
2317acpi_AppendBufferResource(ACPI_BUFFER *buf, ACPI_RESOURCE *res)
2318{
2319    ACPI_RESOURCE	*rp;
2320    void		*newp;
2321
2322    /* Initialise the buffer if necessary. */
2323    if (buf->Pointer == NULL) {
2324	buf->Length = ACPI_INITIAL_RESOURCE_BUFFER_SIZE;
2325	if ((buf->Pointer = AcpiOsAllocate(buf->Length)) == NULL)
2326	    return (AE_NO_MEMORY);
2327	rp = (ACPI_RESOURCE *)buf->Pointer;
2328	rp->Type = ACPI_RESOURCE_TYPE_END_TAG;
2329	rp->Length = 0;
2330    }
2331    if (res == NULL)
2332	return (AE_OK);
2333
2334    /*
2335     * Scan the current buffer looking for the terminator.
2336     * This will either find the terminator or hit the end
2337     * of the buffer and return an error.
2338     */
2339    rp = (ACPI_RESOURCE *)buf->Pointer;
2340    for (;;) {
2341	/* Range check, don't go outside the buffer */
2342	if (rp >= (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
2343	    return (AE_BAD_PARAMETER);
2344	if (rp->Type == ACPI_RESOURCE_TYPE_END_TAG || rp->Length == 0)
2345	    break;
2346	rp = ACPI_NEXT_RESOURCE(rp);
2347    }
2348
2349    /*
2350     * Check the size of the buffer and expand if required.
2351     *
2352     * Required size is:
2353     *	size of existing resources before terminator +
2354     *	size of new resource and header +
2355     * 	size of terminator.
2356     *
2357     * Note that this loop should really only run once, unless
2358     * for some reason we are stuffing a *really* huge resource.
2359     */
2360    while ((((u_int8_t *)rp - (u_int8_t *)buf->Pointer) +
2361	    res->Length + ACPI_RS_SIZE_NO_DATA +
2362	    ACPI_RS_SIZE_MIN) >= buf->Length) {
2363	if ((newp = AcpiOsAllocate(buf->Length * 2)) == NULL)
2364	    return (AE_NO_MEMORY);
2365	bcopy(buf->Pointer, newp, buf->Length);
2366	rp = (ACPI_RESOURCE *)((u_int8_t *)newp +
2367			       ((u_int8_t *)rp - (u_int8_t *)buf->Pointer));
2368	AcpiOsFree(buf->Pointer);
2369	buf->Pointer = newp;
2370	buf->Length += buf->Length;
2371    }
2372
2373    /* Insert the new resource. */
2374    bcopy(res, rp, res->Length + ACPI_RS_SIZE_NO_DATA);
2375
2376    /* And add the terminator. */
2377    rp = ACPI_NEXT_RESOURCE(rp);
2378    rp->Type = ACPI_RESOURCE_TYPE_END_TAG;
2379    rp->Length = 0;
2380
2381    return (AE_OK);
2382}
2383
2384/*
2385 * Set interrupt model.
2386 */
2387ACPI_STATUS
2388acpi_SetIntrModel(int model)
2389{
2390
2391    return (acpi_SetInteger(ACPI_ROOT_OBJECT, "_PIC", model));
2392}
2393
2394/*
2395 * Walk subtables of a table and call a callback routine for each
2396 * subtable.  The caller should provide the first subtable and a
2397 * pointer to the end of the table.  This can be used to walk tables
2398 * such as MADT and SRAT that use subtable entries.
2399 */
2400void
2401acpi_walk_subtables(void *first, void *end, acpi_subtable_handler *handler,
2402    void *arg)
2403{
2404    ACPI_SUBTABLE_HEADER *entry;
2405
2406    for (entry = first; (void *)entry < end; ) {
2407	/* Avoid an infinite loop if we hit a bogus entry. */
2408	if (entry->Length < sizeof(ACPI_SUBTABLE_HEADER))
2409	    return;
2410
2411	handler(entry, arg);
2412	entry = ACPI_ADD_PTR(ACPI_SUBTABLE_HEADER, entry, entry->Length);
2413    }
2414}
2415
2416/*
2417 * DEPRECATED.  This interface has serious deficiencies and will be
2418 * removed.
2419 *
2420 * Immediately enter the sleep state.  In the old model, acpiconf(8) ran
2421 * rc.suspend and rc.resume so we don't have to notify devd(8) to do this.
2422 */
2423ACPI_STATUS
2424acpi_SetSleepState(struct acpi_softc *sc, int state)
2425{
2426    static int once;
2427
2428    if (!once) {
2429	device_printf(sc->acpi_dev,
2430"warning: acpi_SetSleepState() deprecated, need to update your software\n");
2431	once = 1;
2432    }
2433    return (acpi_EnterSleepState(sc, state));
2434}
2435
2436#if defined(__amd64__) || defined(__i386__)
2437static void
2438acpi_sleep_force(void *arg)
2439{
2440    struct acpi_softc *sc = (struct acpi_softc *)arg;
2441
2442    device_printf(sc->acpi_dev,
2443	"suspend request timed out, forcing sleep now\n");
2444    if (ACPI_FAILURE(acpi_EnterSleepState(sc, sc->acpi_next_sstate)))
2445	device_printf(sc->acpi_dev, "force sleep state S%d failed\n",
2446	    sc->acpi_next_sstate);
2447}
2448#endif
2449
2450/*
2451 * Request that the system enter the given suspend state.  All /dev/apm
2452 * devices and devd(8) will be notified.  Userland then has a chance to
2453 * save state and acknowledge the request.  The system sleeps once all
2454 * acks are in.
2455 */
2456int
2457acpi_ReqSleepState(struct acpi_softc *sc, int state)
2458{
2459#if defined(__amd64__) || defined(__i386__)
2460    struct apm_clone_data *clone;
2461    ACPI_STATUS status;
2462
2463    if (state < ACPI_STATE_S1 || state > ACPI_S_STATES_MAX)
2464	return (EINVAL);
2465    if (!acpi_sleep_states[state])
2466	return (EOPNOTSUPP);
2467
2468    ACPI_LOCK(acpi);
2469
2470    /* If a suspend request is already in progress, just return. */
2471    if (sc->acpi_next_sstate != 0) {
2472    	ACPI_UNLOCK(acpi);
2473	return (0);
2474    }
2475
2476    /* S5 (soft-off) should be entered directly with no waiting. */
2477    if (state == ACPI_STATE_S5) {
2478    	ACPI_UNLOCK(acpi);
2479	status = acpi_EnterSleepState(sc, state);
2480	return (ACPI_SUCCESS(status) ? 0 : ENXIO);
2481    }
2482
2483    /* Record the pending state and notify all apm devices. */
2484    sc->acpi_next_sstate = state;
2485    STAILQ_FOREACH(clone, &sc->apm_cdevs, entries) {
2486	clone->notify_status = APM_EV_NONE;
2487	if ((clone->flags & ACPI_EVF_DEVD) == 0) {
2488	    selwakeuppri(&clone->sel_read, PZERO);
2489	    KNOTE_LOCKED(&clone->sel_read.si_note, 0);
2490	}
2491    }
2492
2493    /* If devd(8) is not running, immediately enter the sleep state. */
2494    if (!devctl_process_running()) {
2495	ACPI_UNLOCK(acpi);
2496	status = acpi_EnterSleepState(sc, state);
2497	return (ACPI_SUCCESS(status) ? 0 : ENXIO);
2498    }
2499
2500    /*
2501     * Set a timeout to fire if userland doesn't ack the suspend request
2502     * in time.  This way we still eventually go to sleep if we were
2503     * overheating or running low on battery, even if userland is hung.
2504     * We cancel this timeout once all userland acks are in or the
2505     * suspend request is aborted.
2506     */
2507    callout_reset(&sc->susp_force_to, 10 * hz, acpi_sleep_force, sc);
2508    ACPI_UNLOCK(acpi);
2509
2510    /* Now notify devd(8) also. */
2511    acpi_UserNotify("Suspend", ACPI_ROOT_OBJECT, state);
2512
2513    return (0);
2514#else
2515    /* This platform does not support acpi suspend/resume. */
2516    return (EOPNOTSUPP);
2517#endif
2518}
2519
2520/*
2521 * Acknowledge (or reject) a pending sleep state.  The caller has
2522 * prepared for suspend and is now ready for it to proceed.  If the
2523 * error argument is non-zero, it indicates suspend should be cancelled
2524 * and gives an errno value describing why.  Once all votes are in,
2525 * we suspend the system.
2526 */
2527int
2528acpi_AckSleepState(struct apm_clone_data *clone, int error)
2529{
2530#if defined(__amd64__) || defined(__i386__)
2531    struct acpi_softc *sc;
2532    int ret, sleeping;
2533
2534    /* If no pending sleep state, return an error. */
2535    ACPI_LOCK(acpi);
2536    sc = clone->acpi_sc;
2537    if (sc->acpi_next_sstate == 0) {
2538    	ACPI_UNLOCK(acpi);
2539	return (ENXIO);
2540    }
2541
2542    /* Caller wants to abort suspend process. */
2543    if (error) {
2544	sc->acpi_next_sstate = 0;
2545	callout_stop(&sc->susp_force_to);
2546	device_printf(sc->acpi_dev,
2547	    "listener on %s cancelled the pending suspend\n",
2548	    devtoname(clone->cdev));
2549    	ACPI_UNLOCK(acpi);
2550	return (0);
2551    }
2552
2553    /*
2554     * Mark this device as acking the suspend request.  Then, walk through
2555     * all devices, seeing if they agree yet.  We only count devices that
2556     * are writable since read-only devices couldn't ack the request.
2557     */
2558    sleeping = TRUE;
2559    clone->notify_status = APM_EV_ACKED;
2560    STAILQ_FOREACH(clone, &sc->apm_cdevs, entries) {
2561	if ((clone->flags & ACPI_EVF_WRITE) != 0 &&
2562	    clone->notify_status != APM_EV_ACKED) {
2563	    sleeping = FALSE;
2564	    break;
2565	}
2566    }
2567
2568    /* If all devices have voted "yes", we will suspend now. */
2569    if (sleeping)
2570	callout_stop(&sc->susp_force_to);
2571    ACPI_UNLOCK(acpi);
2572    ret = 0;
2573    if (sleeping) {
2574	if (ACPI_FAILURE(acpi_EnterSleepState(sc, sc->acpi_next_sstate)))
2575		ret = ENODEV;
2576    }
2577    return (ret);
2578#else
2579    /* This platform does not support acpi suspend/resume. */
2580    return (EOPNOTSUPP);
2581#endif
2582}
2583
2584static void
2585acpi_sleep_enable(void *arg)
2586{
2587    struct acpi_softc	*sc = (struct acpi_softc *)arg;
2588
2589    /* Reschedule if the system is not fully up and running. */
2590    if (!AcpiGbl_SystemAwakeAndRunning) {
2591	timeout(acpi_sleep_enable, sc, hz * ACPI_MINIMUM_AWAKETIME);
2592	return;
2593    }
2594
2595    ACPI_LOCK(acpi);
2596    sc->acpi_sleep_disabled = FALSE;
2597    ACPI_UNLOCK(acpi);
2598}
2599
2600static ACPI_STATUS
2601acpi_sleep_disable(struct acpi_softc *sc)
2602{
2603    ACPI_STATUS		status;
2604
2605    /* Fail if the system is not fully up and running. */
2606    if (!AcpiGbl_SystemAwakeAndRunning)
2607	return (AE_ERROR);
2608
2609    ACPI_LOCK(acpi);
2610    status = sc->acpi_sleep_disabled ? AE_ERROR : AE_OK;
2611    sc->acpi_sleep_disabled = TRUE;
2612    ACPI_UNLOCK(acpi);
2613
2614    return (status);
2615}
2616
2617enum acpi_sleep_state {
2618    ACPI_SS_NONE,
2619    ACPI_SS_GPE_SET,
2620    ACPI_SS_DEV_SUSPEND,
2621    ACPI_SS_SLP_PREP,
2622    ACPI_SS_SLEPT,
2623};
2624
2625/*
2626 * Enter the desired system sleep state.
2627 *
2628 * Currently we support S1-S5 but S4 is only S4BIOS
2629 */
2630static ACPI_STATUS
2631acpi_EnterSleepState(struct acpi_softc *sc, int state)
2632{
2633    ACPI_STATUS	status;
2634    enum acpi_sleep_state slp_state;
2635
2636    ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
2637
2638    if (state < ACPI_STATE_S1 || state > ACPI_S_STATES_MAX)
2639	return_ACPI_STATUS (AE_BAD_PARAMETER);
2640    if (!acpi_sleep_states[state]) {
2641	device_printf(sc->acpi_dev, "Sleep state S%d not supported by BIOS\n",
2642	    state);
2643	return (AE_SUPPORT);
2644    }
2645
2646    /* Re-entry once we're suspending is not allowed. */
2647    status = acpi_sleep_disable(sc);
2648    if (ACPI_FAILURE(status)) {
2649	device_printf(sc->acpi_dev,
2650	    "suspend request ignored (not ready yet)\n");
2651	return (status);
2652    }
2653
2654    if (state == ACPI_STATE_S5) {
2655	/*
2656	 * Shut down cleanly and power off.  This will call us back through the
2657	 * shutdown handlers.
2658	 */
2659	shutdown_nice(RB_POWEROFF);
2660	return_ACPI_STATUS (AE_OK);
2661    }
2662
2663    EVENTHANDLER_INVOKE(power_suspend);
2664
2665    if (smp_started) {
2666	thread_lock(curthread);
2667	sched_bind(curthread, 0);
2668	thread_unlock(curthread);
2669    }
2670
2671    /*
2672     * Be sure to hold Giant across DEVICE_SUSPEND/RESUME since non-MPSAFE
2673     * drivers need this.
2674     */
2675    mtx_lock(&Giant);
2676
2677    slp_state = ACPI_SS_NONE;
2678
2679    sc->acpi_sstate = state;
2680
2681    /* Enable any GPEs as appropriate and requested by the user. */
2682    acpi_wake_prep_walk(state);
2683    slp_state = ACPI_SS_GPE_SET;
2684
2685    /*
2686     * Inform all devices that we are going to sleep.  If at least one
2687     * device fails, DEVICE_SUSPEND() automatically resumes the tree.
2688     *
2689     * XXX Note that a better two-pass approach with a 'veto' pass
2690     * followed by a "real thing" pass would be better, but the current
2691     * bus interface does not provide for this.
2692     */
2693    if (DEVICE_SUSPEND(root_bus) != 0) {
2694	device_printf(sc->acpi_dev, "device_suspend failed\n");
2695	goto backout;
2696    }
2697    slp_state = ACPI_SS_DEV_SUSPEND;
2698
2699    /* If testing device suspend only, back out of everything here. */
2700    if (acpi_susp_bounce)
2701	goto backout;
2702
2703    status = AcpiEnterSleepStatePrep(state);
2704    if (ACPI_FAILURE(status)) {
2705	device_printf(sc->acpi_dev, "AcpiEnterSleepStatePrep failed - %s\n",
2706		      AcpiFormatException(status));
2707	goto backout;
2708    }
2709    slp_state = ACPI_SS_SLP_PREP;
2710
2711    if (sc->acpi_sleep_delay > 0)
2712	DELAY(sc->acpi_sleep_delay * 1000000);
2713
2714    if (state != ACPI_STATE_S1) {
2715	acpi_sleep_machdep(sc, state);
2716
2717	/* Re-enable ACPI hardware on wakeup from sleep state 4. */
2718	if (state == ACPI_STATE_S4)
2719	    AcpiEnable();
2720    } else {
2721	ACPI_DISABLE_IRQS();
2722	status = AcpiEnterSleepState(state);
2723	if (ACPI_FAILURE(status)) {
2724	    device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n",
2725			  AcpiFormatException(status));
2726	    goto backout;
2727	}
2728    }
2729    slp_state = ACPI_SS_SLEPT;
2730
2731    /*
2732     * Back out state according to how far along we got in the suspend
2733     * process.  This handles both the error and success cases.
2734     */
2735backout:
2736    if (slp_state >= ACPI_SS_GPE_SET) {
2737	acpi_wake_prep_walk(state);
2738	sc->acpi_sstate = ACPI_STATE_S0;
2739    }
2740    if (slp_state >= ACPI_SS_SLP_PREP)
2741	AcpiLeaveSleepState(state);
2742    if (slp_state >= ACPI_SS_DEV_SUSPEND)
2743	DEVICE_RESUME(root_bus);
2744    if (slp_state >= ACPI_SS_SLEPT)
2745	acpi_enable_fixed_events(sc);
2746    sc->acpi_next_sstate = 0;
2747
2748    mtx_unlock(&Giant);
2749
2750    if (smp_started) {
2751	thread_lock(curthread);
2752	sched_unbind(curthread);
2753	thread_unlock(curthread);
2754    }
2755
2756    EVENTHANDLER_INVOKE(power_resume);
2757
2758    /* Allow another sleep request after a while. */
2759    timeout(acpi_sleep_enable, sc, hz * ACPI_MINIMUM_AWAKETIME);
2760
2761    /* Run /etc/rc.resume after we are back. */
2762    if (devctl_process_running())
2763	acpi_UserNotify("Resume", ACPI_ROOT_OBJECT, state);
2764
2765    return_ACPI_STATUS (status);
2766}
2767
2768void
2769acpi_resync_clock(struct acpi_softc *sc)
2770{
2771
2772    if (!acpi_reset_clock)
2773	return;
2774
2775    /*
2776     * Warm up timecounter again and reset system clock.
2777     */
2778    (void)timecounter->tc_get_timecount(timecounter);
2779    (void)timecounter->tc_get_timecount(timecounter);
2780    inittodr(time_second + sc->acpi_sleep_delay);
2781}
2782
2783/* Enable or disable the device's wake GPE. */
2784int
2785acpi_wake_set_enable(device_t dev, int enable)
2786{
2787    struct acpi_prw_data prw;
2788    ACPI_STATUS status;
2789    int flags;
2790
2791    /* Make sure the device supports waking the system and get the GPE. */
2792    if (acpi_parse_prw(acpi_get_handle(dev), &prw) != 0)
2793	return (ENXIO);
2794
2795    flags = acpi_get_flags(dev);
2796    if (enable) {
2797	status = AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit,
2798	    ACPI_GPE_ENABLE);
2799	if (ACPI_FAILURE(status)) {
2800	    device_printf(dev, "enable wake failed\n");
2801	    return (ENXIO);
2802	}
2803	acpi_set_flags(dev, flags | ACPI_FLAG_WAKE_ENABLED);
2804    } else {
2805	status = AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit,
2806	    ACPI_GPE_DISABLE);
2807	if (ACPI_FAILURE(status)) {
2808	    device_printf(dev, "disable wake failed\n");
2809	    return (ENXIO);
2810	}
2811	acpi_set_flags(dev, flags & ~ACPI_FLAG_WAKE_ENABLED);
2812    }
2813
2814    return (0);
2815}
2816
2817static int
2818acpi_wake_sleep_prep(ACPI_HANDLE handle, int sstate)
2819{
2820    struct acpi_prw_data prw;
2821    device_t dev;
2822
2823    /* Check that this is a wake-capable device and get its GPE. */
2824    if (acpi_parse_prw(handle, &prw) != 0)
2825	return (ENXIO);
2826    dev = acpi_get_device(handle);
2827
2828    /*
2829     * The destination sleep state must be less than (i.e., higher power)
2830     * or equal to the value specified by _PRW.  If this GPE cannot be
2831     * enabled for the next sleep state, then disable it.  If it can and
2832     * the user requested it be enabled, turn on any required power resources
2833     * and set _PSW.
2834     */
2835    if (sstate > prw.lowest_wake) {
2836	AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit, ACPI_GPE_DISABLE);
2837	if (bootverbose)
2838	    device_printf(dev, "wake_prep disabled wake for %s (S%d)\n",
2839		acpi_name(handle), sstate);
2840    } else if (dev && (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) != 0) {
2841	acpi_pwr_wake_enable(handle, 1);
2842	acpi_SetInteger(handle, "_PSW", 1);
2843	if (bootverbose)
2844	    device_printf(dev, "wake_prep enabled for %s (S%d)\n",
2845		acpi_name(handle), sstate);
2846    }
2847
2848    return (0);
2849}
2850
2851static int
2852acpi_wake_run_prep(ACPI_HANDLE handle, int sstate)
2853{
2854    struct acpi_prw_data prw;
2855    device_t dev;
2856
2857    /*
2858     * Check that this is a wake-capable device and get its GPE.  Return
2859     * now if the user didn't enable this device for wake.
2860     */
2861    if (acpi_parse_prw(handle, &prw) != 0)
2862	return (ENXIO);
2863    dev = acpi_get_device(handle);
2864    if (dev == NULL || (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) == 0)
2865	return (0);
2866
2867    /*
2868     * If this GPE couldn't be enabled for the previous sleep state, it was
2869     * disabled before going to sleep so re-enable it.  If it was enabled,
2870     * clear _PSW and turn off any power resources it used.
2871     */
2872    if (sstate > prw.lowest_wake) {
2873	AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit, ACPI_GPE_ENABLE);
2874	if (bootverbose)
2875	    device_printf(dev, "run_prep re-enabled %s\n", acpi_name(handle));
2876    } else {
2877	acpi_SetInteger(handle, "_PSW", 0);
2878	acpi_pwr_wake_enable(handle, 0);
2879	if (bootverbose)
2880	    device_printf(dev, "run_prep cleaned up for %s\n",
2881		acpi_name(handle));
2882    }
2883
2884    return (0);
2885}
2886
2887static ACPI_STATUS
2888acpi_wake_prep(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
2889{
2890    int sstate;
2891
2892    /* If suspending, run the sleep prep function, otherwise wake. */
2893    sstate = *(int *)context;
2894    if (AcpiGbl_SystemAwakeAndRunning)
2895	acpi_wake_sleep_prep(handle, sstate);
2896    else
2897	acpi_wake_run_prep(handle, sstate);
2898    return (AE_OK);
2899}
2900
2901/* Walk the tree rooted at acpi0 to prep devices for suspend/resume. */
2902static int
2903acpi_wake_prep_walk(int sstate)
2904{
2905    ACPI_HANDLE sb_handle;
2906
2907    if (ACPI_SUCCESS(AcpiGetHandle(ACPI_ROOT_OBJECT, "\\_SB_", &sb_handle)))
2908	AcpiWalkNamespace(ACPI_TYPE_DEVICE, sb_handle, 100,
2909	    acpi_wake_prep, NULL, &sstate, NULL);
2910    return (0);
2911}
2912
2913/* Walk the tree rooted at acpi0 to attach per-device wake sysctls. */
2914static int
2915acpi_wake_sysctl_walk(device_t dev)
2916{
2917    int error, i, numdevs;
2918    device_t *devlist;
2919    device_t child;
2920    ACPI_STATUS status;
2921
2922    error = device_get_children(dev, &devlist, &numdevs);
2923    if (error != 0 || numdevs == 0) {
2924	if (numdevs == 0)
2925	    free(devlist, M_TEMP);
2926	return (error);
2927    }
2928    for (i = 0; i < numdevs; i++) {
2929	child = devlist[i];
2930	acpi_wake_sysctl_walk(child);
2931	if (!device_is_attached(child))
2932	    continue;
2933	status = AcpiEvaluateObject(acpi_get_handle(child), "_PRW", NULL, NULL);
2934	if (ACPI_SUCCESS(status)) {
2935	    SYSCTL_ADD_PROC(device_get_sysctl_ctx(child),
2936		SYSCTL_CHILDREN(device_get_sysctl_tree(child)), OID_AUTO,
2937		"wake", CTLTYPE_INT | CTLFLAG_RW, child, 0,
2938		acpi_wake_set_sysctl, "I", "Device set to wake the system");
2939	}
2940    }
2941    free(devlist, M_TEMP);
2942
2943    return (0);
2944}
2945
2946/* Enable or disable wake from userland. */
2947static int
2948acpi_wake_set_sysctl(SYSCTL_HANDLER_ARGS)
2949{
2950    int enable, error;
2951    device_t dev;
2952
2953    dev = (device_t)arg1;
2954    enable = (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) ? 1 : 0;
2955
2956    error = sysctl_handle_int(oidp, &enable, 0, req);
2957    if (error != 0 || req->newptr == NULL)
2958	return (error);
2959    if (enable != 0 && enable != 1)
2960	return (EINVAL);
2961
2962    return (acpi_wake_set_enable(dev, enable));
2963}
2964
2965/* Parse a device's _PRW into a structure. */
2966int
2967acpi_parse_prw(ACPI_HANDLE h, struct acpi_prw_data *prw)
2968{
2969    ACPI_STATUS			status;
2970    ACPI_BUFFER			prw_buffer;
2971    ACPI_OBJECT			*res, *res2;
2972    int				error, i, power_count;
2973
2974    if (h == NULL || prw == NULL)
2975	return (EINVAL);
2976
2977    /*
2978     * The _PRW object (7.2.9) is only required for devices that have the
2979     * ability to wake the system from a sleeping state.
2980     */
2981    error = EINVAL;
2982    prw_buffer.Pointer = NULL;
2983    prw_buffer.Length = ACPI_ALLOCATE_BUFFER;
2984    status = AcpiEvaluateObject(h, "_PRW", NULL, &prw_buffer);
2985    if (ACPI_FAILURE(status))
2986	return (ENOENT);
2987    res = (ACPI_OBJECT *)prw_buffer.Pointer;
2988    if (res == NULL)
2989	return (ENOENT);
2990    if (!ACPI_PKG_VALID(res, 2))
2991	goto out;
2992
2993    /*
2994     * Element 1 of the _PRW object:
2995     * The lowest power system sleeping state that can be entered while still
2996     * providing wake functionality.  The sleeping state being entered must
2997     * be less than (i.e., higher power) or equal to this value.
2998     */
2999    if (acpi_PkgInt32(res, 1, &prw->lowest_wake) != 0)
3000	goto out;
3001
3002    /*
3003     * Element 0 of the _PRW object:
3004     */
3005    switch (res->Package.Elements[0].Type) {
3006    case ACPI_TYPE_INTEGER:
3007	/*
3008	 * If the data type of this package element is numeric, then this
3009	 * _PRW package element is the bit index in the GPEx_EN, in the
3010	 * GPE blocks described in the FADT, of the enable bit that is
3011	 * enabled for the wake event.
3012	 */
3013	prw->gpe_handle = NULL;
3014	prw->gpe_bit = res->Package.Elements[0].Integer.Value;
3015	error = 0;
3016	break;
3017    case ACPI_TYPE_PACKAGE:
3018	/*
3019	 * If the data type of this package element is a package, then this
3020	 * _PRW package element is itself a package containing two
3021	 * elements.  The first is an object reference to the GPE Block
3022	 * device that contains the GPE that will be triggered by the wake
3023	 * event.  The second element is numeric and it contains the bit
3024	 * index in the GPEx_EN, in the GPE Block referenced by the
3025	 * first element in the package, of the enable bit that is enabled for
3026	 * the wake event.
3027	 *
3028	 * For example, if this field is a package then it is of the form:
3029	 * Package() {\_SB.PCI0.ISA.GPE, 2}
3030	 */
3031	res2 = &res->Package.Elements[0];
3032	if (!ACPI_PKG_VALID(res2, 2))
3033	    goto out;
3034	prw->gpe_handle = acpi_GetReference(NULL, &res2->Package.Elements[0]);
3035	if (prw->gpe_handle == NULL)
3036	    goto out;
3037	if (acpi_PkgInt32(res2, 1, &prw->gpe_bit) != 0)
3038	    goto out;
3039	error = 0;
3040	break;
3041    default:
3042	goto out;
3043    }
3044
3045    /* Elements 2 to N of the _PRW object are power resources. */
3046    power_count = res->Package.Count - 2;
3047    if (power_count > ACPI_PRW_MAX_POWERRES) {
3048	printf("ACPI device %s has too many power resources\n", acpi_name(h));
3049	power_count = 0;
3050    }
3051    prw->power_res_count = power_count;
3052    for (i = 0; i < power_count; i++)
3053	prw->power_res[i] = res->Package.Elements[i];
3054
3055out:
3056    if (prw_buffer.Pointer != NULL)
3057	AcpiOsFree(prw_buffer.Pointer);
3058    return (error);
3059}
3060
3061/*
3062 * ACPI Event Handlers
3063 */
3064
3065/* System Event Handlers (registered by EVENTHANDLER_REGISTER) */
3066
3067static void
3068acpi_system_eventhandler_sleep(void *arg, int state)
3069{
3070    struct acpi_softc *sc = (struct acpi_softc *)arg;
3071    int ret;
3072
3073    ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
3074
3075    /* Check if button action is disabled or unknown. */
3076    if (state == ACPI_STATE_UNKNOWN)
3077	return;
3078
3079    /* Request that the system prepare to enter the given suspend state. */
3080    ret = acpi_ReqSleepState(sc, state);
3081    if (ret != 0)
3082	device_printf(sc->acpi_dev,
3083	    "request to enter state S%d failed (err %d)\n", state, ret);
3084
3085    return_VOID;
3086}
3087
3088static void
3089acpi_system_eventhandler_wakeup(void *arg, int state)
3090{
3091
3092    ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
3093
3094    /* Currently, nothing to do for wakeup. */
3095
3096    return_VOID;
3097}
3098
3099/*
3100 * ACPICA Event Handlers (FixedEvent, also called from button notify handler)
3101 */
3102static void
3103acpi_invoke_sleep_eventhandler(void *context)
3104{
3105
3106    EVENTHANDLER_INVOKE(acpi_sleep_event, *(int *)context);
3107}
3108
3109static void
3110acpi_invoke_wake_eventhandler(void *context)
3111{
3112
3113    EVENTHANDLER_INVOKE(acpi_wakeup_event, *(int *)context);
3114}
3115
3116UINT32
3117acpi_event_power_button_sleep(void *context)
3118{
3119    struct acpi_softc	*sc = (struct acpi_softc *)context;
3120
3121    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
3122
3123    if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
3124	acpi_invoke_sleep_eventhandler, &sc->acpi_power_button_sx)))
3125	return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
3126    return_VALUE (ACPI_INTERRUPT_HANDLED);
3127}
3128
3129UINT32
3130acpi_event_power_button_wake(void *context)
3131{
3132    struct acpi_softc	*sc = (struct acpi_softc *)context;
3133
3134    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
3135
3136    if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
3137	acpi_invoke_wake_eventhandler, &sc->acpi_power_button_sx)))
3138	return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
3139    return_VALUE (ACPI_INTERRUPT_HANDLED);
3140}
3141
3142UINT32
3143acpi_event_sleep_button_sleep(void *context)
3144{
3145    struct acpi_softc	*sc = (struct acpi_softc *)context;
3146
3147    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
3148
3149    if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
3150	acpi_invoke_sleep_eventhandler, &sc->acpi_sleep_button_sx)))
3151	return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
3152    return_VALUE (ACPI_INTERRUPT_HANDLED);
3153}
3154
3155UINT32
3156acpi_event_sleep_button_wake(void *context)
3157{
3158    struct acpi_softc	*sc = (struct acpi_softc *)context;
3159
3160    ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
3161
3162    if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
3163	acpi_invoke_wake_eventhandler, &sc->acpi_sleep_button_sx)))
3164	return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
3165    return_VALUE (ACPI_INTERRUPT_HANDLED);
3166}
3167
3168/*
3169 * XXX This static buffer is suboptimal.  There is no locking so only
3170 * use this for single-threaded callers.
3171 */
3172char *
3173acpi_name(ACPI_HANDLE handle)
3174{
3175    ACPI_BUFFER buf;
3176    static char data[256];
3177
3178    buf.Length = sizeof(data);
3179    buf.Pointer = data;
3180
3181    if (handle && ACPI_SUCCESS(AcpiGetName(handle, ACPI_FULL_PATHNAME, &buf)))
3182	return (data);
3183    return ("(unknown)");
3184}
3185
3186/*
3187 * Debugging/bug-avoidance.  Avoid trying to fetch info on various
3188 * parts of the namespace.
3189 */
3190int
3191acpi_avoid(ACPI_HANDLE handle)
3192{
3193    char	*cp, *env, *np;
3194    int		len;
3195
3196    np = acpi_name(handle);
3197    if (*np == '\\')
3198	np++;
3199    if ((env = getenv("debug.acpi.avoid")) == NULL)
3200	return (0);
3201
3202    /* Scan the avoid list checking for a match */
3203    cp = env;
3204    for (;;) {
3205	while (*cp != 0 && isspace(*cp))
3206	    cp++;
3207	if (*cp == 0)
3208	    break;
3209	len = 0;
3210	while (cp[len] != 0 && !isspace(cp[len]))
3211	    len++;
3212	if (!strncmp(cp, np, len)) {
3213	    freeenv(env);
3214	    return(1);
3215	}
3216	cp += len;
3217    }
3218    freeenv(env);
3219
3220    return (0);
3221}
3222
3223/*
3224 * Debugging/bug-avoidance.  Disable ACPI subsystem components.
3225 */
3226int
3227acpi_disabled(char *subsys)
3228{
3229    char	*cp, *env;
3230    int		len;
3231
3232    if ((env = getenv("debug.acpi.disabled")) == NULL)
3233	return (0);
3234    if (strcmp(env, "all") == 0) {
3235	freeenv(env);
3236	return (1);
3237    }
3238
3239    /* Scan the disable list, checking for a match. */
3240    cp = env;
3241    for (;;) {
3242	while (*cp != '\0' && isspace(*cp))
3243	    cp++;
3244	if (*cp == '\0')
3245	    break;
3246	len = 0;
3247	while (cp[len] != '\0' && !isspace(cp[len]))
3248	    len++;
3249	if (strncmp(cp, subsys, len) == 0) {
3250	    freeenv(env);
3251	    return (1);
3252	}
3253	cp += len;
3254    }
3255    freeenv(env);
3256
3257    return (0);
3258}
3259
3260/*
3261 * Control interface.
3262 *
3263 * We multiplex ioctls for all participating ACPI devices here.  Individual
3264 * drivers wanting to be accessible via /dev/acpi should use the
3265 * register/deregister interface to make their handlers visible.
3266 */
3267struct acpi_ioctl_hook
3268{
3269    TAILQ_ENTRY(acpi_ioctl_hook) link;
3270    u_long			 cmd;
3271    acpi_ioctl_fn		 fn;
3272    void			 *arg;
3273};
3274
3275static TAILQ_HEAD(,acpi_ioctl_hook)	acpi_ioctl_hooks;
3276static int				acpi_ioctl_hooks_initted;
3277
3278int
3279acpi_register_ioctl(u_long cmd, acpi_ioctl_fn fn, void *arg)
3280{
3281    struct acpi_ioctl_hook	*hp;
3282
3283    if ((hp = malloc(sizeof(*hp), M_ACPIDEV, M_NOWAIT)) == NULL)
3284	return (ENOMEM);
3285    hp->cmd = cmd;
3286    hp->fn = fn;
3287    hp->arg = arg;
3288
3289    ACPI_LOCK(acpi);
3290    if (acpi_ioctl_hooks_initted == 0) {
3291	TAILQ_INIT(&acpi_ioctl_hooks);
3292	acpi_ioctl_hooks_initted = 1;
3293    }
3294    TAILQ_INSERT_TAIL(&acpi_ioctl_hooks, hp, link);
3295    ACPI_UNLOCK(acpi);
3296
3297    return (0);
3298}
3299
3300void
3301acpi_deregister_ioctl(u_long cmd, acpi_ioctl_fn fn)
3302{
3303    struct acpi_ioctl_hook	*hp;
3304
3305    ACPI_LOCK(acpi);
3306    TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link)
3307	if (hp->cmd == cmd && hp->fn == fn)
3308	    break;
3309
3310    if (hp != NULL) {
3311	TAILQ_REMOVE(&acpi_ioctl_hooks, hp, link);
3312	free(hp, M_ACPIDEV);
3313    }
3314    ACPI_UNLOCK(acpi);
3315}
3316
3317static int
3318acpiopen(struct cdev *dev, int flag, int fmt, struct thread *td)
3319{
3320    return (0);
3321}
3322
3323static int
3324acpiclose(struct cdev *dev, int flag, int fmt, struct thread *td)
3325{
3326    return (0);
3327}
3328
3329static int
3330acpiioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
3331{
3332    struct acpi_softc		*sc;
3333    struct acpi_ioctl_hook	*hp;
3334    int				error, state;
3335
3336    error = 0;
3337    hp = NULL;
3338    sc = dev->si_drv1;
3339
3340    /*
3341     * Scan the list of registered ioctls, looking for handlers.
3342     */
3343    ACPI_LOCK(acpi);
3344    if (acpi_ioctl_hooks_initted)
3345	TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link) {
3346	    if (hp->cmd == cmd)
3347		break;
3348	}
3349    ACPI_UNLOCK(acpi);
3350    if (hp)
3351	return (hp->fn(cmd, addr, hp->arg));
3352
3353    /*
3354     * Core ioctls are not permitted for non-writable user.
3355     * Currently, other ioctls just fetch information.
3356     * Not changing system behavior.
3357     */
3358    if ((flag & FWRITE) == 0)
3359	return (EPERM);
3360
3361    /* Core system ioctls. */
3362    switch (cmd) {
3363    case ACPIIO_REQSLPSTATE:
3364	state = *(int *)addr;
3365	if (state != ACPI_STATE_S5)
3366	    return (acpi_ReqSleepState(sc, state));
3367	device_printf(sc->acpi_dev, "power off via acpi ioctl not supported\n");
3368	error = EOPNOTSUPP;
3369	break;
3370    case ACPIIO_ACKSLPSTATE:
3371	error = *(int *)addr;
3372	error = acpi_AckSleepState(sc->acpi_clone, error);
3373	break;
3374    case ACPIIO_SETSLPSTATE:	/* DEPRECATED */
3375	state = *(int *)addr;
3376	if (state < ACPI_STATE_S0 || state > ACPI_S_STATES_MAX)
3377	    return (EINVAL);
3378	if (!acpi_sleep_states[state])
3379	    return (EOPNOTSUPP);
3380	if (ACPI_FAILURE(acpi_SetSleepState(sc, state)))
3381	    error = ENXIO;
3382	break;
3383    default:
3384	error = ENXIO;
3385	break;
3386    }
3387
3388    return (error);
3389}
3390
3391static int
3392acpi_sname2sstate(const char *sname)
3393{
3394    int sstate;
3395
3396    if (toupper(sname[0]) == 'S') {
3397	sstate = sname[1] - '0';
3398	if (sstate >= ACPI_STATE_S0 && sstate <= ACPI_STATE_S5 &&
3399	    sname[2] == '\0')
3400	    return (sstate);
3401    } else if (strcasecmp(sname, "NONE") == 0)
3402	return (ACPI_STATE_UNKNOWN);
3403    return (-1);
3404}
3405
3406static const char *
3407acpi_sstate2sname(int sstate)
3408{
3409    static const char *snames[] = { "S0", "S1", "S2", "S3", "S4", "S5" };
3410
3411    if (sstate >= ACPI_STATE_S0 && sstate <= ACPI_STATE_S5)
3412	return (snames[sstate]);
3413    else if (sstate == ACPI_STATE_UNKNOWN)
3414	return ("NONE");
3415    return (NULL);
3416}
3417
3418static int
3419acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
3420{
3421    int error;
3422    struct sbuf sb;
3423    UINT8 state;
3424
3425    sbuf_new(&sb, NULL, 32, SBUF_AUTOEXTEND);
3426    for (state = ACPI_STATE_S1; state < ACPI_S_STATE_COUNT; state++)
3427	if (acpi_sleep_states[state])
3428	    sbuf_printf(&sb, "%s ", acpi_sstate2sname(state));
3429    sbuf_trim(&sb);
3430    sbuf_finish(&sb);
3431    error = sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
3432    sbuf_delete(&sb);
3433    return (error);
3434}
3435
3436static int
3437acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
3438{
3439    char sleep_state[10];
3440    int error, new_state, old_state;
3441
3442    old_state = *(int *)oidp->oid_arg1;
3443    strlcpy(sleep_state, acpi_sstate2sname(old_state), sizeof(sleep_state));
3444    error = sysctl_handle_string(oidp, sleep_state, sizeof(sleep_state), req);
3445    if (error == 0 && req->newptr != NULL) {
3446	new_state = acpi_sname2sstate(sleep_state);
3447	if (new_state < ACPI_STATE_S1)
3448	    return (EINVAL);
3449	if (new_state < ACPI_S_STATE_COUNT && !acpi_sleep_states[new_state])
3450	    return (EOPNOTSUPP);
3451	if (new_state != old_state)
3452	    *(int *)oidp->oid_arg1 = new_state;
3453    }
3454    return (error);
3455}
3456
3457/* Inform devctl(4) when we receive a Notify. */
3458void
3459acpi_UserNotify(const char *subsystem, ACPI_HANDLE h, uint8_t notify)
3460{
3461    char		notify_buf[16];
3462    ACPI_BUFFER		handle_buf;
3463    ACPI_STATUS		status;
3464
3465    if (subsystem == NULL)
3466	return;
3467
3468    handle_buf.Pointer = NULL;
3469    handle_buf.Length = ACPI_ALLOCATE_BUFFER;
3470    status = AcpiNsHandleToPathname(h, &handle_buf);
3471    if (ACPI_FAILURE(status))
3472	return;
3473    snprintf(notify_buf, sizeof(notify_buf), "notify=0x%02x", notify);
3474    devctl_notify("ACPI", subsystem, handle_buf.Pointer, notify_buf);
3475    AcpiOsFree(handle_buf.Pointer);
3476}
3477
3478#ifdef ACPI_DEBUG
3479/*
3480 * Support for parsing debug options from the kernel environment.
3481 *
3482 * Bits may be set in the AcpiDbgLayer and AcpiDbgLevel debug registers
3483 * by specifying the names of the bits in the debug.acpi.layer and
3484 * debug.acpi.level environment variables.  Bits may be unset by
3485 * prefixing the bit name with !.
3486 */
3487struct debugtag
3488{
3489    char	*name;
3490    UINT32	value;
3491};
3492
3493static struct debugtag	dbg_layer[] = {
3494    {"ACPI_UTILITIES",		ACPI_UTILITIES},
3495    {"ACPI_HARDWARE",		ACPI_HARDWARE},
3496    {"ACPI_EVENTS",		ACPI_EVENTS},
3497    {"ACPI_TABLES",		ACPI_TABLES},
3498    {"ACPI_NAMESPACE",		ACPI_NAMESPACE},
3499    {"ACPI_PARSER",		ACPI_PARSER},
3500    {"ACPI_DISPATCHER",		ACPI_DISPATCHER},
3501    {"ACPI_EXECUTER",		ACPI_EXECUTER},
3502    {"ACPI_RESOURCES",		ACPI_RESOURCES},
3503    {"ACPI_CA_DEBUGGER",	ACPI_CA_DEBUGGER},
3504    {"ACPI_OS_SERVICES",	ACPI_OS_SERVICES},
3505    {"ACPI_CA_DISASSEMBLER",	ACPI_CA_DISASSEMBLER},
3506    {"ACPI_ALL_COMPONENTS",	ACPI_ALL_COMPONENTS},
3507
3508    {"ACPI_AC_ADAPTER",		ACPI_AC_ADAPTER},
3509    {"ACPI_BATTERY",		ACPI_BATTERY},
3510    {"ACPI_BUS",		ACPI_BUS},
3511    {"ACPI_BUTTON",		ACPI_BUTTON},
3512    {"ACPI_EC", 		ACPI_EC},
3513    {"ACPI_FAN",		ACPI_FAN},
3514    {"ACPI_POWERRES",		ACPI_POWERRES},
3515    {"ACPI_PROCESSOR",		ACPI_PROCESSOR},
3516    {"ACPI_THERMAL",		ACPI_THERMAL},
3517    {"ACPI_TIMER",		ACPI_TIMER},
3518    {"ACPI_ALL_DRIVERS",	ACPI_ALL_DRIVERS},
3519    {NULL, 0}
3520};
3521
3522static struct debugtag dbg_level[] = {
3523    {"ACPI_LV_INIT",		ACPI_LV_INIT},
3524    {"ACPI_LV_DEBUG_OBJECT",	ACPI_LV_DEBUG_OBJECT},
3525    {"ACPI_LV_INFO",		ACPI_LV_INFO},
3526    {"ACPI_LV_ALL_EXCEPTIONS",	ACPI_LV_ALL_EXCEPTIONS},
3527
3528    /* Trace verbosity level 1 [Standard Trace Level] */
3529    {"ACPI_LV_INIT_NAMES",	ACPI_LV_INIT_NAMES},
3530    {"ACPI_LV_PARSE",		ACPI_LV_PARSE},
3531    {"ACPI_LV_LOAD",		ACPI_LV_LOAD},
3532    {"ACPI_LV_DISPATCH",	ACPI_LV_DISPATCH},
3533    {"ACPI_LV_EXEC",		ACPI_LV_EXEC},
3534    {"ACPI_LV_NAMES",		ACPI_LV_NAMES},
3535    {"ACPI_LV_OPREGION",	ACPI_LV_OPREGION},
3536    {"ACPI_LV_BFIELD",		ACPI_LV_BFIELD},
3537    {"ACPI_LV_TABLES",		ACPI_LV_TABLES},
3538    {"ACPI_LV_VALUES",		ACPI_LV_VALUES},
3539    {"ACPI_LV_OBJECTS",		ACPI_LV_OBJECTS},
3540    {"ACPI_LV_RESOURCES",	ACPI_LV_RESOURCES},
3541    {"ACPI_LV_USER_REQUESTS",	ACPI_LV_USER_REQUESTS},
3542    {"ACPI_LV_PACKAGE",		ACPI_LV_PACKAGE},
3543    {"ACPI_LV_VERBOSITY1",	ACPI_LV_VERBOSITY1},
3544
3545    /* Trace verbosity level 2 [Function tracing and memory allocation] */
3546    {"ACPI_LV_ALLOCATIONS",	ACPI_LV_ALLOCATIONS},
3547    {"ACPI_LV_FUNCTIONS",	ACPI_LV_FUNCTIONS},
3548    {"ACPI_LV_OPTIMIZATIONS",	ACPI_LV_OPTIMIZATIONS},
3549    {"ACPI_LV_VERBOSITY2",	ACPI_LV_VERBOSITY2},
3550    {"ACPI_LV_ALL",		ACPI_LV_ALL},
3551
3552    /* Trace verbosity level 3 [Threading, I/O, and Interrupts] */
3553    {"ACPI_LV_MUTEX",		ACPI_LV_MUTEX},
3554    {"ACPI_LV_THREADS",		ACPI_LV_THREADS},
3555    {"ACPI_LV_IO",		ACPI_LV_IO},
3556    {"ACPI_LV_INTERRUPTS",	ACPI_LV_INTERRUPTS},
3557    {"ACPI_LV_VERBOSITY3",	ACPI_LV_VERBOSITY3},
3558
3559    /* Exceptionally verbose output -- also used in the global "DebugLevel"  */
3560    {"ACPI_LV_AML_DISASSEMBLE",	ACPI_LV_AML_DISASSEMBLE},
3561    {"ACPI_LV_VERBOSE_INFO",	ACPI_LV_VERBOSE_INFO},
3562    {"ACPI_LV_FULL_TABLES",	ACPI_LV_FULL_TABLES},
3563    {"ACPI_LV_EVENTS",		ACPI_LV_EVENTS},
3564    {"ACPI_LV_VERBOSE",		ACPI_LV_VERBOSE},
3565    {NULL, 0}
3566};
3567
3568static void
3569acpi_parse_debug(char *cp, struct debugtag *tag, UINT32 *flag)
3570{
3571    char	*ep;
3572    int		i, l;
3573    int		set;
3574
3575    while (*cp) {
3576	if (isspace(*cp)) {
3577	    cp++;
3578	    continue;
3579	}
3580	ep = cp;
3581	while (*ep && !isspace(*ep))
3582	    ep++;
3583	if (*cp == '!') {
3584	    set = 0;
3585	    cp++;
3586	    if (cp == ep)
3587		continue;
3588	} else {
3589	    set = 1;
3590	}
3591	l = ep - cp;
3592	for (i = 0; tag[i].name != NULL; i++) {
3593	    if (!strncmp(cp, tag[i].name, l)) {
3594		if (set)
3595		    *flag |= tag[i].value;
3596		else
3597		    *flag &= ~tag[i].value;
3598	    }
3599	}
3600	cp = ep;
3601    }
3602}
3603
3604static void
3605acpi_set_debugging(void *junk)
3606{
3607    char	*layer, *level;
3608
3609    if (cold) {
3610	AcpiDbgLayer = 0;
3611	AcpiDbgLevel = 0;
3612    }
3613
3614    layer = getenv("debug.acpi.layer");
3615    level = getenv("debug.acpi.level");
3616    if (layer == NULL && level == NULL)
3617	return;
3618
3619    printf("ACPI set debug");
3620    if (layer != NULL) {
3621	if (strcmp("NONE", layer) != 0)
3622	    printf(" layer '%s'", layer);
3623	acpi_parse_debug(layer, &dbg_layer[0], &AcpiDbgLayer);
3624	freeenv(layer);
3625    }
3626    if (level != NULL) {
3627	if (strcmp("NONE", level) != 0)
3628	    printf(" level '%s'", level);
3629	acpi_parse_debug(level, &dbg_level[0], &AcpiDbgLevel);
3630	freeenv(level);
3631    }
3632    printf("\n");
3633}
3634
3635SYSINIT(acpi_debugging, SI_SUB_TUNABLES, SI_ORDER_ANY, acpi_set_debugging,
3636	NULL);
3637
3638static int
3639acpi_debug_sysctl(SYSCTL_HANDLER_ARGS)
3640{
3641    int		 error, *dbg;
3642    struct	 debugtag *tag;
3643    struct	 sbuf sb;
3644
3645    if (sbuf_new(&sb, NULL, 128, SBUF_AUTOEXTEND) == NULL)
3646	return (ENOMEM);
3647    if (strcmp(oidp->oid_arg1, "debug.acpi.layer") == 0) {
3648	tag = &dbg_layer[0];
3649	dbg = &AcpiDbgLayer;
3650    } else {
3651	tag = &dbg_level[0];
3652	dbg = &AcpiDbgLevel;
3653    }
3654
3655    /* Get old values if this is a get request. */
3656    ACPI_SERIAL_BEGIN(acpi);
3657    if (*dbg == 0) {
3658	sbuf_cpy(&sb, "NONE");
3659    } else if (req->newptr == NULL) {
3660	for (; tag->name != NULL; tag++) {
3661	    if ((*dbg & tag->value) == tag->value)
3662		sbuf_printf(&sb, "%s ", tag->name);
3663	}
3664    }
3665    sbuf_trim(&sb);
3666    sbuf_finish(&sb);
3667
3668    /* Copy out the old values to the user. */
3669    error = SYSCTL_OUT(req, sbuf_data(&sb), sbuf_len(&sb));
3670    sbuf_delete(&sb);
3671
3672    /* If the user is setting a string, parse it. */
3673    if (error == 0 && req->newptr != NULL) {
3674	*dbg = 0;
3675	setenv((char *)oidp->oid_arg1, (char *)req->newptr);
3676	acpi_set_debugging(NULL);
3677    }
3678    ACPI_SERIAL_END(acpi);
3679
3680    return (error);
3681}
3682
3683SYSCTL_PROC(_debug_acpi, OID_AUTO, layer, CTLFLAG_RW | CTLTYPE_STRING,
3684	    "debug.acpi.layer", 0, acpi_debug_sysctl, "A", "");
3685SYSCTL_PROC(_debug_acpi, OID_AUTO, level, CTLFLAG_RW | CTLTYPE_STRING,
3686	    "debug.acpi.level", 0, acpi_debug_sysctl, "A", "");
3687#endif /* ACPI_DEBUG */
3688
3689static int
3690acpi_debug_objects_sysctl(SYSCTL_HANDLER_ARGS)
3691{
3692	int	error;
3693	int	old;
3694
3695	old = acpi_debug_objects;
3696	error = sysctl_handle_int(oidp, &acpi_debug_objects, 0, req);
3697	if (error != 0 || req->newptr == NULL)
3698		return (error);
3699	if (old == acpi_debug_objects || (old && acpi_debug_objects))
3700		return (0);
3701
3702	ACPI_SERIAL_BEGIN(acpi);
3703	AcpiGbl_EnableAmlDebugObject = acpi_debug_objects ? TRUE : FALSE;
3704	ACPI_SERIAL_END(acpi);
3705
3706	return (0);
3707}
3708
3709static int
3710acpi_parse_interfaces(char *str, struct acpi_interface *iface)
3711{
3712	char *p;
3713	size_t len;
3714	int i, j;
3715
3716	p = str;
3717	while (isspace(*p) || *p == ',')
3718		p++;
3719	len = strlen(p);
3720	if (len == 0)
3721		return (0);
3722	p = strdup(p, M_TEMP);
3723	for (i = 0; i < len; i++)
3724		if (p[i] == ',')
3725			p[i] = '\0';
3726	i = j = 0;
3727	while (i < len)
3728		if (isspace(p[i]) || p[i] == '\0')
3729			i++;
3730		else {
3731			i += strlen(p + i) + 1;
3732			j++;
3733		}
3734	if (j == 0) {
3735		free(p, M_TEMP);
3736		return (0);
3737	}
3738	iface->data = malloc(sizeof(*iface->data) * j, M_TEMP, M_WAITOK);
3739	iface->num = j;
3740	i = j = 0;
3741	while (i < len)
3742		if (isspace(p[i]) || p[i] == '\0')
3743			i++;
3744		else {
3745			iface->data[j] = p + i;
3746			i += strlen(p + i) + 1;
3747			j++;
3748		}
3749
3750	return (j);
3751}
3752
3753static void
3754acpi_free_interfaces(struct acpi_interface *iface)
3755{
3756
3757	free(iface->data[0], M_TEMP);
3758	free(iface->data, M_TEMP);
3759}
3760
3761static void
3762acpi_reset_interfaces(device_t dev)
3763{
3764	struct acpi_interface list;
3765	ACPI_STATUS status;
3766	int i;
3767
3768	if (acpi_parse_interfaces(acpi_install_interface, &list) > 0) {
3769		for (i = 0; i < list.num; i++) {
3770			status = AcpiInstallInterface(list.data[i]);
3771			if (ACPI_FAILURE(status))
3772				device_printf(dev,
3773				    "failed to install _OSI(\"%s\"): %s\n",
3774				    list.data[i], AcpiFormatException(status));
3775			else if (bootverbose)
3776				device_printf(dev, "installed _OSI(\"%s\")\n",
3777				    list.data[i]);
3778		}
3779		acpi_free_interfaces(&list);
3780	}
3781	if (acpi_parse_interfaces(acpi_remove_interface, &list) > 0) {
3782		for (i = 0; i < list.num; i++) {
3783			status = AcpiRemoveInterface(list.data[i]);
3784			if (ACPI_FAILURE(status))
3785				device_printf(dev,
3786				    "failed to remove _OSI(\"%s\"): %s\n",
3787				    list.data[i], AcpiFormatException(status));
3788			else if (bootverbose)
3789				device_printf(dev, "removed _OSI(\"%s\")\n",
3790				    list.data[i]);
3791		}
3792		acpi_free_interfaces(&list);
3793	}
3794}
3795
3796static int
3797acpi_pm_func(u_long cmd, void *arg, ...)
3798{
3799	int	state, acpi_state;
3800	int	error;
3801	struct	acpi_softc *sc;
3802	va_list	ap;
3803
3804	error = 0;
3805	switch (cmd) {
3806	case POWER_CMD_SUSPEND:
3807		sc = (struct acpi_softc *)arg;
3808		if (sc == NULL) {
3809			error = EINVAL;
3810			goto out;
3811		}
3812
3813		va_start(ap, arg);
3814		state = va_arg(ap, int);
3815		va_end(ap);
3816
3817		switch (state) {
3818		case POWER_SLEEP_STATE_STANDBY:
3819			acpi_state = sc->acpi_standby_sx;
3820			break;
3821		case POWER_SLEEP_STATE_SUSPEND:
3822			acpi_state = sc->acpi_suspend_sx;
3823			break;
3824		case POWER_SLEEP_STATE_HIBERNATE:
3825			acpi_state = ACPI_STATE_S4;
3826			break;
3827		default:
3828			error = EINVAL;
3829			goto out;
3830		}
3831
3832		if (ACPI_FAILURE(acpi_EnterSleepState(sc, acpi_state)))
3833			error = ENXIO;
3834		break;
3835	default:
3836		error = EINVAL;
3837		goto out;
3838	}
3839
3840out:
3841	return (error);
3842}
3843
3844static void
3845acpi_pm_register(void *arg)
3846{
3847    if (!cold || resource_disabled("acpi", 0))
3848	return;
3849
3850    power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, NULL);
3851}
3852
3853SYSINIT(power, SI_SUB_KLD, SI_ORDER_ANY, acpi_pm_register, 0);
3854