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