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