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