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