xref: /freebsd/sys/dev/acpica/acpi.c (revision dba6dd177bdee890cf445fbe21a5dccefd5de18e)
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  *	$FreeBSD$
30  */
31 
32 #include "opt_acpi.h"
33 #include <sys/param.h>
34 #include <sys/kernel.h>
35 #include <sys/proc.h>
36 #include <sys/fcntl.h>
37 #include <sys/malloc.h>
38 #include <sys/bus.h>
39 #include <sys/conf.h>
40 #include <sys/ioccom.h>
41 #include <sys/reboot.h>
42 #include <sys/sysctl.h>
43 #include <sys/ctype.h>
44 #include <sys/linker.h>
45 #include <sys/power.h>
46 #include <sys/sbuf.h>
47 #include <sys/smp.h>
48 
49 #include <machine/clock.h>
50 #include <machine/resource.h>
51 #include <machine/bus.h>
52 #include <sys/rman.h>
53 #include <isa/isavar.h>
54 
55 #include "acpi.h"
56 #include <dev/acpica/acpivar.h>
57 #include <dev/acpica/acpiio.h>
58 #include <contrib/dev/acpica/acnamesp.h>
59 
60 MALLOC_DEFINE(M_ACPIDEV, "acpidev", "ACPI devices");
61 
62 /* Hooks for the ACPI CA debugging infrastructure */
63 #define _COMPONENT	ACPI_BUS
64 ACPI_MODULE_NAME("ACPI")
65 
66 static d_open_t		acpiopen;
67 static d_close_t	acpiclose;
68 static d_ioctl_t	acpiioctl;
69 
70 static struct cdevsw acpi_cdevsw = {
71 	.d_version =	D_VERSION,
72 	.d_flags =	D_NEEDGIANT,
73 	.d_open =	acpiopen,
74 	.d_close =	acpiclose,
75 	.d_ioctl =	acpiioctl,
76 	.d_name =	"acpi",
77 };
78 
79 #if __FreeBSD_version >= 500000
80 struct mtx	acpi_mutex;
81 #endif
82 
83 struct acpi_quirks {
84     char	*OemId;
85     uint32_t	OemRevision;
86     char	*value;
87 };
88 
89 #define ACPI_OEM_REV_ANY	0
90 
91 static struct acpi_quirks acpi_quirks_table[] = {
92 #ifdef notyet
93     /* Bad PCI routing table.  Used on some SuperMicro boards. */
94     { "PTLTD ", 0x06040000, "pci_link" },
95 #endif
96 
97     { NULL, 0, NULL }
98 };
99 
100 static int	acpi_modevent(struct module *mod, int event, void *junk);
101 static void	acpi_identify(driver_t *driver, device_t parent);
102 static int	acpi_probe(device_t dev);
103 static int	acpi_attach(device_t dev);
104 static void	acpi_quirks_set(void);
105 static device_t	acpi_add_child(device_t bus, int order, const char *name,
106 			int unit);
107 static int	acpi_print_child(device_t bus, device_t child);
108 static int	acpi_read_ivar(device_t dev, device_t child, int index,
109 			uintptr_t *result);
110 static int	acpi_write_ivar(device_t dev, device_t child, int index,
111 			uintptr_t value);
112 static int	acpi_set_resource(device_t dev, device_t child, int type,
113 			int rid, u_long start, u_long count);
114 static int	acpi_get_resource(device_t dev, device_t child, int type,
115 			int rid, u_long *startp, u_long *countp);
116 static struct resource *acpi_alloc_resource(device_t bus, device_t child,
117 			int type, int *rid, u_long start, u_long end,
118 			u_long count, u_int flags);
119 static int	acpi_release_resource(device_t bus, device_t child, int type,
120 			int rid, struct resource *r);
121 static uint32_t	acpi_isa_get_logicalid(device_t dev);
122 static int	acpi_isa_get_compatid(device_t dev, uint32_t *cids, int count);
123 static int	acpi_isa_pnp_probe(device_t bus, device_t child,
124 			struct isa_pnp_id *ids);
125 static void	acpi_probe_children(device_t bus);
126 static ACPI_STATUS acpi_probe_child(ACPI_HANDLE handle, UINT32 level,
127 			void *context, void **status);
128 static void	acpi_shutdown_pre_sync(void *arg, int howto);
129 static void	acpi_shutdown_final(void *arg, int howto);
130 static void	acpi_shutdown_poweroff(void *arg);
131 static void	acpi_enable_fixed_events(struct acpi_softc *sc);
132 static void	acpi_system_eventhandler_sleep(void *arg, int state);
133 static void	acpi_system_eventhandler_wakeup(void *arg, int state);
134 static int	acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS);
135 static int	acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS);
136 static int	acpi_pm_func(u_long cmd, void *arg, ...);
137 static int	acpi_child_location_str_method(device_t acdev, device_t child,
138 					       char *buf, size_t buflen);
139 static int	acpi_child_pnpinfo_str_method(device_t acdev, device_t child,
140 					      char *buf, size_t buflen);
141 
142 static device_method_t acpi_methods[] = {
143     /* Device interface */
144     DEVMETHOD(device_identify,		acpi_identify),
145     DEVMETHOD(device_probe,		acpi_probe),
146     DEVMETHOD(device_attach,		acpi_attach),
147     DEVMETHOD(device_detach,		bus_generic_detach),
148     DEVMETHOD(device_shutdown,		bus_generic_shutdown),
149     DEVMETHOD(device_suspend,		bus_generic_suspend),
150     DEVMETHOD(device_resume,		bus_generic_resume),
151 
152     /* Bus interface */
153     DEVMETHOD(bus_add_child,		acpi_add_child),
154     DEVMETHOD(bus_print_child,		acpi_print_child),
155     DEVMETHOD(bus_read_ivar,		acpi_read_ivar),
156     DEVMETHOD(bus_write_ivar,		acpi_write_ivar),
157     DEVMETHOD(bus_set_resource,		acpi_set_resource),
158     DEVMETHOD(bus_get_resource,		acpi_get_resource),
159     DEVMETHOD(bus_alloc_resource,	acpi_alloc_resource),
160     DEVMETHOD(bus_release_resource,	acpi_release_resource),
161     DEVMETHOD(bus_child_pnpinfo_str,	acpi_child_pnpinfo_str_method),
162     DEVMETHOD(bus_child_location_str,	acpi_child_location_str_method),
163     DEVMETHOD(bus_driver_added,		bus_generic_driver_added),
164     DEVMETHOD(bus_activate_resource,	bus_generic_activate_resource),
165     DEVMETHOD(bus_deactivate_resource,	bus_generic_deactivate_resource),
166     DEVMETHOD(bus_setup_intr,		bus_generic_setup_intr),
167     DEVMETHOD(bus_teardown_intr,	bus_generic_teardown_intr),
168 
169     /* ISA emulation */
170     DEVMETHOD(isa_pnp_probe,		acpi_isa_pnp_probe),
171 
172     {0, 0}
173 };
174 
175 static driver_t acpi_driver = {
176     "acpi",
177     acpi_methods,
178     sizeof(struct acpi_softc),
179 };
180 
181 static devclass_t acpi_devclass;
182 DRIVER_MODULE(acpi, nexus, acpi_driver, acpi_devclass, acpi_modevent, 0);
183 MODULE_VERSION(acpi, 1);
184 
185 static const char* sleep_state_names[] = {
186     "S0", "S1", "S2", "S3", "S4", "S5", "NONE"};
187 
188 SYSCTL_NODE(_debug, OID_AUTO, acpi, CTLFLAG_RW, NULL, "ACPI debugging");
189 static char acpi_ca_version[12];
190 SYSCTL_STRING(_debug_acpi, OID_AUTO, acpi_ca_version, CTLFLAG_RD,
191 	      acpi_ca_version, 0, "Version of Intel ACPI-CA");
192 
193 /*
194  * Allow override of whether methods execute in parallel or not.
195  * Enable this for serial behavior, which fixes "AE_ALREADY_EXISTS"
196  * errors for AML that really can't handle parallel method execution.
197  * It is off by default since this breaks recursive methods and
198  * some IBMs use such code.
199  */
200 static int acpi_serialize_methods;
201 TUNABLE_INT("hw.acpi.serialize_methods", &acpi_serialize_methods);
202 
203 /*
204  * ACPI can only be loaded as a module by the loader; activating it after
205  * system bootstrap time is not useful, and can be fatal to the system.
206  * It also cannot be unloaded, since the entire system bus heirarchy hangs
207  * off it.
208  */
209 static int
210 acpi_modevent(struct module *mod, int event, void *junk)
211 {
212     switch(event) {
213     case MOD_LOAD:
214 	if (!cold) {
215 	    printf("The ACPI driver cannot be loaded after boot.\n");
216 	    return (EPERM);
217 	}
218 	break;
219     case MOD_UNLOAD:
220 	if (!cold && power_pm_get_type() == POWER_PM_TYPE_ACPI)
221 	    return (EBUSY);
222 	break;
223     default:
224 	break;
225     }
226     return (0);
227 }
228 
229 /*
230  * Perform early initialization.
231  */
232 ACPI_STATUS
233 acpi_Startup(void)
234 {
235 #ifdef ACPI_DEBUGGER
236     char *debugpoint;
237 #endif
238     static int error, started = 0;
239 
240     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
241 
242     if (started)
243 	return_VALUE (error);
244     started = 1;
245 
246 #if __FreeBSD_version >= 500000
247     /* Initialise the ACPI mutex */
248     mtx_init(&acpi_mutex, "ACPI global lock", NULL, MTX_DEF);
249 #endif
250 
251     /*
252      * Set the globals from our tunables.  This is needed because ACPI-CA
253      * uses UINT8 for some values and we have no tunable_byte.
254      */
255     AcpiGbl_AllMethodsSerialized = (UINT8)acpi_serialize_methods;
256 
257     /* Start up the ACPI CA subsystem. */
258 #ifdef ACPI_DEBUGGER
259     debugpoint = getenv("debug.acpi.debugger");
260     if (debugpoint) {
261 	if (!strcmp(debugpoint, "init"))
262 	    acpi_EnterDebugger();
263 	freeenv(debugpoint);
264     }
265 #endif
266     if (ACPI_FAILURE(error = AcpiInitializeSubsystem())) {
267 	printf("ACPI: initialisation failed: %s\n", AcpiFormatException(error));
268 	return_VALUE (error);
269     }
270 #ifdef ACPI_DEBUGGER
271     debugpoint = getenv("debug.acpi.debugger");
272     if (debugpoint) {
273 	if (!strcmp(debugpoint, "tables"))
274 	    acpi_EnterDebugger();
275 	freeenv(debugpoint);
276     }
277 #endif
278 
279     if (ACPI_FAILURE(error = AcpiLoadTables())) {
280 	printf("ACPI: table load failed: %s\n", AcpiFormatException(error));
281 	return_VALUE(error);
282     }
283 
284     /* Set up any quirks we have for this XSDT. */
285     acpi_quirks_set();
286     if (acpi_disabled("acpi"))
287 	return_VALUE (AE_ERROR);
288 
289     return_VALUE (AE_OK);
290 }
291 
292 /*
293  * Detect ACPI, perform early initialisation
294  */
295 static void
296 acpi_identify(driver_t *driver, device_t parent)
297 {
298     device_t	child;
299 
300     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
301 
302     if (!cold)
303 	return_VOID;
304 
305     /* Check that we haven't been disabled with a hint. */
306     if (resource_disabled("acpi", 0))
307 	return_VOID;
308 
309     /* Make sure we're not being doubly invoked. */
310     if (device_find_child(parent, "acpi", 0) != NULL)
311 	return_VOID;
312 
313     /* Initialize ACPI-CA. */
314     if (ACPI_FAILURE(acpi_Startup()))
315 	return_VOID;
316 
317     snprintf(acpi_ca_version, sizeof(acpi_ca_version), "%#x", ACPI_CA_VERSION);
318 
319     /* Attach the actual ACPI device. */
320     if ((child = BUS_ADD_CHILD(parent, 0, "acpi", 0)) == NULL) {
321 	device_printf(parent, "ACPI: could not attach\n");
322 	return_VOID;
323     }
324 }
325 
326 /*
327  * Fetch some descriptive data from ACPI to put in our attach message
328  */
329 static int
330 acpi_probe(device_t dev)
331 {
332     ACPI_TABLE_HEADER	th;
333     char		buf[20];
334     int			error;
335     struct sbuf		sb;
336     ACPI_STATUS		status;
337     ACPI_LOCK_DECL;
338 
339     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
340 
341     if (power_pm_get_type() != POWER_PM_TYPE_NONE &&
342 	power_pm_get_type() != POWER_PM_TYPE_ACPI) {
343 
344 	device_printf(dev, "Other PM system enabled.\n");
345 	return_VALUE(ENXIO);
346     }
347 
348     ACPI_LOCK;
349 
350     if (ACPI_FAILURE(status = AcpiGetTableHeader(ACPI_TABLE_XSDT, 1, &th))) {
351 	device_printf(dev, "couldn't get XSDT header: %s\n",
352 		      AcpiFormatException(status));
353 	error = ENXIO;
354     } else {
355 	sbuf_new(&sb, buf, sizeof(buf), SBUF_FIXEDLEN);
356 	sbuf_bcat(&sb, th.OemId, 6);
357 	sbuf_trim(&sb);
358 	sbuf_putc(&sb, ' ');
359 	sbuf_bcat(&sb, th.OemTableId, 8);
360 	sbuf_trim(&sb);
361 	sbuf_finish(&sb);
362 	device_set_desc_copy(dev, sbuf_data(&sb));
363 	sbuf_delete(&sb);
364 	error = 0;
365     }
366     ACPI_UNLOCK;
367     return_VALUE(error);
368 }
369 
370 static int
371 acpi_attach(device_t dev)
372 {
373     struct acpi_softc	*sc;
374     ACPI_STATUS		status;
375     int			error, state;
376     UINT32		flags;
377     UINT8		TypeA, TypeB;
378     char		*env;
379 #ifdef ACPI_DEBUGGER
380     char		*debugpoint;
381 #endif
382     ACPI_LOCK_DECL;
383 
384     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
385     ACPI_LOCK;
386     sc = device_get_softc(dev);
387     bzero(sc, sizeof(*sc));
388     sc->acpi_dev = dev;
389 
390 #ifdef ACPI_DEBUGGER
391     debugpoint = getenv("debug.acpi.debugger");
392     if (debugpoint) {
393 	if (!strcmp(debugpoint, "spaces"))
394 	    acpi_EnterDebugger();
395 	freeenv(debugpoint);
396     }
397 #endif
398 
399     /* Install the default address space handlers. */
400     error = ENXIO;
401     status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
402 		ACPI_ADR_SPACE_SYSTEM_MEMORY, ACPI_DEFAULT_HANDLER, NULL, NULL);
403     if (ACPI_FAILURE(status)) {
404 	device_printf(dev, "Could not initialise SystemMemory handler: %s\n",
405 		      AcpiFormatException(status));
406 	goto out;
407     }
408     status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
409 		ACPI_ADR_SPACE_SYSTEM_IO, ACPI_DEFAULT_HANDLER, NULL, NULL);
410     if (ACPI_FAILURE(status)) {
411 	device_printf(dev, "Could not initialise SystemIO handler: %s\n",
412 		      AcpiFormatException(status));
413 	goto out;
414     }
415     status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
416 		ACPI_ADR_SPACE_PCI_CONFIG, ACPI_DEFAULT_HANDLER, NULL, NULL);
417     if (ACPI_FAILURE(status)) {
418 	device_printf(dev, "could not initialise PciConfig handler: %s\n",
419 		      AcpiFormatException(status));
420 	goto out;
421     }
422 
423     /*
424      * Bring ACPI fully online.
425      *
426      * Note that some systems (specifically, those with namespace evaluation
427      * issues that require the avoidance of parts of the namespace) must
428      * avoid running _INI and _STA on everything, as well as dodging the final
429      * object init pass.
430      *
431      * For these devices, we set ACPI_NO_DEVICE_INIT and ACPI_NO_OBJECT_INIT).
432      *
433      * XXX We should arrange for the object init pass after we have attached
434      *     all our child devices, but on many systems it works here.
435      */
436 #ifdef ACPI_DEBUGGER
437     debugpoint = getenv("debug.acpi.debugger");
438     if (debugpoint) {
439 	if (!strcmp(debugpoint, "enable"))
440 	    acpi_EnterDebugger();
441 	freeenv(debugpoint);
442     }
443 #endif
444     flags = 0;
445     if (testenv("debug.acpi.avoid"))
446 	flags = ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
447     if (ACPI_FAILURE(status = AcpiEnableSubsystem(flags))) {
448 	device_printf(dev, "Could not enable ACPI: %s\n",
449 		      AcpiFormatException(status));
450 	goto out;
451     }
452 
453     /*
454      * Call the ECDT probe function to provide EC functionality before
455      * the namespace has been evaluated.
456      */
457     acpi_ec_ecdt_probe(dev);
458 
459     if (ACPI_FAILURE(status = AcpiInitializeObjects(flags))) {
460 	device_printf(dev, "Could not initialize ACPI objects: %s\n",
461 		      AcpiFormatException(status));
462 	goto out;
463     }
464 
465     /*
466      * Setup our sysctl tree.
467      *
468      * XXX: This doesn't check to make sure that none of these fail.
469      */
470     sysctl_ctx_init(&sc->acpi_sysctl_ctx);
471     sc->acpi_sysctl_tree = SYSCTL_ADD_NODE(&sc->acpi_sysctl_ctx,
472 			       SYSCTL_STATIC_CHILDREN(_hw), OID_AUTO,
473 			       device_get_name(dev), CTLFLAG_RD, 0, "");
474     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
475 	OID_AUTO, "supported_sleep_state", CTLTYPE_STRING | CTLFLAG_RD,
476 	0, 0, acpi_supported_sleep_state_sysctl, "A", "");
477     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
478 	OID_AUTO, "power_button_state", CTLTYPE_STRING | CTLFLAG_RW,
479 	&sc->acpi_power_button_sx, 0, acpi_sleep_state_sysctl, "A", "");
480     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
481 	OID_AUTO, "sleep_button_state", CTLTYPE_STRING | CTLFLAG_RW,
482 	&sc->acpi_sleep_button_sx, 0, acpi_sleep_state_sysctl, "A", "");
483     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
484 	OID_AUTO, "lid_switch_state", CTLTYPE_STRING | CTLFLAG_RW,
485 	&sc->acpi_lid_switch_sx, 0, acpi_sleep_state_sysctl, "A", "");
486     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
487 	OID_AUTO, "standby_state", CTLTYPE_STRING | CTLFLAG_RW,
488 	&sc->acpi_standby_sx, 0, acpi_sleep_state_sysctl, "A", "");
489     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
490 	OID_AUTO, "suspend_state", CTLTYPE_STRING | CTLFLAG_RW,
491 	&sc->acpi_suspend_sx, 0, acpi_sleep_state_sysctl, "A", "");
492     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
493 	OID_AUTO, "sleep_delay", CTLFLAG_RD | CTLFLAG_RW,
494 	&sc->acpi_sleep_delay, 0, "sleep delay");
495     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
496 	OID_AUTO, "s4bios", CTLFLAG_RD | CTLFLAG_RW,
497 	&sc->acpi_s4bios, 0, "S4BIOS mode");
498     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
499 	OID_AUTO, "verbose", CTLFLAG_RD | CTLFLAG_RW,
500 	&sc->acpi_verbose, 0, "verbose mode");
501     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
502 	OID_AUTO, "disable_on_poweroff", CTLFLAG_RD | CTLFLAG_RW,
503 	&sc->acpi_disable_on_poweroff, 0, "ACPI subsystem disable on poweroff");
504 
505     /*
506      * Default to 5 seconds before sleeping to give some machines time to
507      * stabilize.
508      */
509     sc->acpi_sleep_delay = 5;
510     sc->acpi_disable_on_poweroff = 1;
511     if (bootverbose)
512 	sc->acpi_verbose = 1;
513     if ((env = getenv("hw.acpi.verbose")) && strcmp(env, "0")) {
514 	sc->acpi_verbose = 1;
515 	freeenv(env);
516     }
517 
518     /* Only enable S4BIOS by default if the FACS says it is available. */
519     if (AcpiGbl_FACS->S4Bios_f != 0)
520 	    sc->acpi_s4bios = 1;
521 
522     /*
523      * Dispatch the default sleep state to devices.  The lid switch is set
524      * to NONE by default to avoid surprising users.
525      */
526     sc->acpi_power_button_sx = ACPI_STATE_S5;
527     sc->acpi_lid_switch_sx = ACPI_S_STATES_MAX + 1;
528     sc->acpi_standby_sx = ACPI_STATE_S1;
529     sc->acpi_suspend_sx = ACPI_STATE_S3;
530 
531     /* Pick the first valid sleep state for the sleep button default. */
532     sc->acpi_sleep_button_sx = ACPI_S_STATES_MAX + 1;
533     for (state = ACPI_STATE_S1; state < ACPI_STATE_S5; state++)
534 	if (ACPI_SUCCESS(AcpiGetSleepTypeData(state, &TypeA, &TypeB))) {
535 	    sc->acpi_sleep_button_sx = state;
536 	    break;
537 	}
538 
539     acpi_enable_fixed_events(sc);
540 
541     /*
542      * Scan the namespace and attach/initialise children.
543      */
544 #ifdef ACPI_DEBUGGER
545     debugpoint = getenv("debug.acpi.debugger");
546     if (debugpoint) {
547 	if (!strcmp(debugpoint, "probe"))
548 	    acpi_EnterDebugger();
549 	freeenv(debugpoint);
550     }
551 #endif
552 
553     /* Register our shutdown handlers */
554     EVENTHANDLER_REGISTER(shutdown_pre_sync, acpi_shutdown_pre_sync, sc,
555 	SHUTDOWN_PRI_LAST);
556     EVENTHANDLER_REGISTER(shutdown_final, acpi_shutdown_final, sc,
557 	SHUTDOWN_PRI_LAST);
558 
559     /*
560      * Register our acpi event handlers.
561      * XXX should be configurable eg. via userland policy manager.
562      */
563     EVENTHANDLER_REGISTER(acpi_sleep_event, acpi_system_eventhandler_sleep,
564 	sc, ACPI_EVENT_PRI_LAST);
565     EVENTHANDLER_REGISTER(acpi_wakeup_event, acpi_system_eventhandler_wakeup,
566 	sc, ACPI_EVENT_PRI_LAST);
567 
568     /* Flag our initial states. */
569     sc->acpi_enabled = 1;
570     sc->acpi_sstate = ACPI_STATE_S0;
571     sc->acpi_sleep_disabled = 0;
572 
573     /* Create the control device */
574     sc->acpi_dev_t = make_dev(&acpi_cdevsw, 0, UID_ROOT, GID_WHEEL, 0644,
575 			      "acpi");
576     sc->acpi_dev_t->si_drv1 = sc;
577 
578 #ifdef ACPI_DEBUGGER
579     debugpoint = getenv("debug.acpi.debugger");
580     if (debugpoint) {
581 	if (strcmp(debugpoint, "running") == 0)
582 	    acpi_EnterDebugger();
583 	freeenv(debugpoint);
584     }
585 #endif
586 
587 #ifdef ACPI_USE_THREADS
588     if ((error = acpi_task_thread_init()))
589 	goto out;
590 #endif
591 
592     if ((error = acpi_machdep_init(dev)))
593 	goto out;
594 
595     /* Register ACPI again to pass the correct argument of pm_func. */
596     power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, sc);
597 
598     if (!acpi_disabled("bus"))
599 	acpi_probe_children(dev);
600 
601     error = 0;
602 
603  out:
604     ACPI_UNLOCK;
605     return_VALUE (error);
606 }
607 
608 static void
609 acpi_quirks_set()
610 {
611     XSDT_DESCRIPTOR *xsdt;
612     struct acpi_quirks *quirk;
613     char *env, *tmp;
614     int len;
615 
616     /*
617      * If the user loaded a custom table or disabled "quirks", leave
618      * the settings alone.
619      */
620     len = 0;
621     if ((env = getenv("acpi_dsdt_load")) != NULL) {
622 	/* XXX No strcasecmp but this is good enough. */
623 	if (*env == 'Y' || *env == 'y')
624 	    goto out;
625 	freeenv(env);
626     }
627     if ((env = getenv("debug.acpi.disabled")) != NULL) {
628 	if (strstr("quirks", env) != NULL)
629 	    goto out;
630 	len = strlen(env);
631     }
632 
633     /*
634      * Search through our quirk table and concatenate the disabled
635      * values with whatever we find.
636      */
637     xsdt = AcpiGbl_XSDT;
638     for (quirk = acpi_quirks_table; quirk->OemId; quirk++) {
639 	if (!strncmp(xsdt->OemId, quirk->OemId, strlen(quirk->OemId)) &&
640 	    (xsdt->OemRevision == quirk->OemRevision ||
641 	    quirk->OemRevision == ACPI_OEM_REV_ANY)) {
642 		len += strlen(quirk->value) + 2;
643 		if ((tmp = malloc(len, M_TEMP, M_NOWAIT)) == NULL)
644 		    goto out;
645 		sprintf(tmp, "%s %s", env ? env : "", quirk->value);
646 		setenv("debug.acpi.disabled", tmp);
647 		free(tmp, M_TEMP);
648 		break;
649 	}
650     }
651 
652 out:
653     if (env)
654 	freeenv(env);
655 }
656 
657 /*
658  * Handle a new device being added
659  */
660 static device_t
661 acpi_add_child(device_t bus, int order, const char *name, int unit)
662 {
663     struct acpi_device	*ad;
664     device_t		child;
665 
666     if ((ad = malloc(sizeof(*ad), M_ACPIDEV, M_NOWAIT | M_ZERO)) == NULL)
667 	return (NULL);
668 
669     resource_list_init(&ad->ad_rl);
670 
671     child = device_add_child_ordered(bus, order, name, unit);
672     if (child != NULL)
673 	device_set_ivars(child, ad);
674     return (child);
675 }
676 
677 static int
678 acpi_print_child(device_t bus, device_t child)
679 {
680     struct acpi_device	 *adev = device_get_ivars(child);
681     struct resource_list *rl = &adev->ad_rl;
682     int retval = 0;
683 
684     retval += bus_print_child_header(bus, child);
685     retval += resource_list_print_type(rl, "port",  SYS_RES_IOPORT, "%#lx");
686     retval += resource_list_print_type(rl, "iomem", SYS_RES_MEMORY, "%#lx");
687     retval += resource_list_print_type(rl, "irq",   SYS_RES_IRQ,    "%ld");
688     retval += resource_list_print_type(rl, "drq",   SYS_RES_DRQ,    "%ld");
689     retval += bus_print_child_footer(bus, child);
690 
691     return (retval);
692 }
693 
694 /* Location hint for devctl(8) */
695 static int
696 acpi_child_location_str_method(device_t cbdev, device_t child, char *buf,
697     size_t buflen)
698 {
699     struct acpi_device *dinfo = device_get_ivars(child);
700 
701     if (dinfo->ad_handle)
702 	snprintf(buf, buflen, "path=%s", acpi_name(dinfo->ad_handle));
703     else
704 	snprintf(buf, buflen, "magic=unknown");
705     return (0);
706 }
707 
708 /* PnP information for devctl(8) */
709 static int
710 acpi_child_pnpinfo_str_method(device_t cbdev, device_t child, char *buf,
711     size_t buflen)
712 {
713     ACPI_BUFFER adbuf = {ACPI_ALLOCATE_BUFFER, NULL};
714     ACPI_DEVICE_INFO *adinfo;
715     struct acpi_device *dinfo = device_get_ivars(child);
716     char *end;
717     int error;
718 
719     error = AcpiGetObjectInfo(dinfo->ad_handle, &adbuf);
720     adinfo = (ACPI_DEVICE_INFO *) adbuf.Pointer;
721 
722     if (error)
723 	snprintf(buf, buflen, "Unknown");
724     else
725 	snprintf(buf, buflen, "_HID=%s _UID=%lu",
726 		 (adinfo->Valid & ACPI_VALID_HID) ?
727 		 adinfo->HardwareId.Value : "UNKNOWN",
728 		 (adinfo->Valid & ACPI_VALID_UID) ?
729 		 strtoul(adinfo->UniqueId.Value, &end, 10) : 0);
730 
731     if (adinfo)
732 	AcpiOsFree(adinfo);
733 
734     return (0);
735 }
736 
737 /*
738  * Handle per-device ivars
739  */
740 static int
741 acpi_read_ivar(device_t dev, device_t child, int index, uintptr_t *result)
742 {
743     struct acpi_device	*ad;
744 
745     if ((ad = device_get_ivars(child)) == NULL) {
746 	printf("device has no ivars\n");
747 	return (ENOENT);
748     }
749 
750     /* ACPI and ISA compatibility ivars */
751     switch(index) {
752     case ACPI_IVAR_HANDLE:
753 	*(ACPI_HANDLE *)result = ad->ad_handle;
754 	break;
755     case ACPI_IVAR_MAGIC:
756 	*(int *)result = ad->ad_magic;
757 	break;
758     case ACPI_IVAR_PRIVATE:
759 	*(void **)result = ad->ad_private;
760 	break;
761     case ISA_IVAR_VENDORID:
762     case ISA_IVAR_SERIAL:
763     case ISA_IVAR_COMPATID:
764 	*(int *)result = -1;
765 	break;
766     case ISA_IVAR_LOGICALID:
767 	*(int *)result = acpi_isa_get_logicalid(child);
768 	break;
769     default:
770 	return (ENOENT);
771     }
772 
773     return (0);
774 }
775 
776 static int
777 acpi_write_ivar(device_t dev, device_t child, int index, uintptr_t value)
778 {
779     struct acpi_device	*ad;
780 
781     if ((ad = device_get_ivars(child)) == NULL) {
782 	printf("device has no ivars\n");
783 	return (ENOENT);
784     }
785 
786     switch(index) {
787     case ACPI_IVAR_HANDLE:
788 	ad->ad_handle = (ACPI_HANDLE)value;
789 	break;
790     case ACPI_IVAR_MAGIC:
791 	ad->ad_magic = (int)value;
792 	break;
793     case ACPI_IVAR_PRIVATE:
794 	ad->ad_private = (void *)value;
795 	break;
796     default:
797 	panic("bad ivar write request (%d)", index);
798 	return (ENOENT);
799     }
800 
801     return (0);
802 }
803 
804 /*
805  * Handle child resource allocation/removal
806  */
807 static int
808 acpi_set_resource(device_t dev, device_t child, int type, int rid,
809 		  u_long start, u_long count)
810 {
811     struct acpi_device		*ad = device_get_ivars(child);
812     struct resource_list	*rl = &ad->ad_rl;
813 
814     resource_list_add(rl, type, rid, start, start + count -1, count);
815 
816     return(0);
817 }
818 
819 static int
820 acpi_get_resource(device_t dev, device_t child, int type, int rid,
821 		  u_long *startp, u_long *countp)
822 {
823     struct acpi_device		*ad = device_get_ivars(child);
824     struct resource_list	*rl = &ad->ad_rl;
825     struct resource_list_entry	*rle;
826 
827     rle = resource_list_find(rl, type, rid);
828     if (!rle)
829 	return(ENOENT);
830 
831     if (startp)
832 	*startp = rle->start;
833     if (countp)
834 	*countp = rle->count;
835 
836     return (0);
837 }
838 
839 static struct resource *
840 acpi_alloc_resource(device_t bus, device_t child, int type, int *rid,
841 		    u_long start, u_long end, u_long count, u_int flags)
842 {
843     struct acpi_device *ad = device_get_ivars(child);
844     struct resource_list *rl = &ad->ad_rl;
845 
846     return (resource_list_alloc(rl, bus, child, type, rid, start, end, count,
847 	    flags));
848 }
849 
850 static int
851 acpi_release_resource(device_t bus, device_t child, int type, int rid, struct resource *r)
852 {
853     struct acpi_device *ad = device_get_ivars(child);
854     struct resource_list *rl = &ad->ad_rl;
855 
856     return (resource_list_release(rl, bus, child, type, rid, r));
857 }
858 
859 /* Allocate an IO port or memory resource, given its GAS. */
860 struct resource *
861 acpi_bus_alloc_gas(device_t dev, int *rid, ACPI_GENERIC_ADDRESS *gas)
862 {
863     int type;
864 
865     if (gas == NULL || !ACPI_VALID_ADDRESS(gas->Address) ||
866 	gas->RegisterBitWidth < 8)
867 	return (NULL);
868 
869     switch (gas->AddressSpaceId) {
870     case ACPI_ADR_SPACE_SYSTEM_MEMORY:
871 	type = SYS_RES_MEMORY;
872 	break;
873     case ACPI_ADR_SPACE_SYSTEM_IO:
874 	type = SYS_RES_IOPORT;
875 	break;
876     default:
877 	return (NULL);
878     }
879 
880     bus_set_resource(dev, type, *rid, gas->Address, gas->RegisterBitWidth / 8);
881     return (bus_alloc_resource_any(dev, type, rid, RF_ACTIVE));
882 }
883 
884 /*
885  * Handle ISA-like devices probing for a PnP ID to match.
886  */
887 #define PNP_EISAID(s)				\
888 	((((s[0] - '@') & 0x1f) << 2)		\
889 	 | (((s[1] - '@') & 0x18) >> 3)		\
890 	 | (((s[1] - '@') & 0x07) << 13)	\
891 	 | (((s[2] - '@') & 0x1f) << 8)		\
892 	 | (PNP_HEXTONUM(s[4]) << 16)		\
893 	 | (PNP_HEXTONUM(s[3]) << 20)		\
894 	 | (PNP_HEXTONUM(s[6]) << 24)		\
895 	 | (PNP_HEXTONUM(s[5]) << 28))
896 
897 static uint32_t
898 acpi_isa_get_logicalid(device_t dev)
899 {
900     ACPI_DEVICE_INFO	*devinfo;
901     ACPI_BUFFER		buf;
902     ACPI_HANDLE		h;
903     ACPI_STATUS		error;
904     u_int32_t		pnpid;
905     ACPI_LOCK_DECL;
906 
907     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
908 
909     pnpid = 0;
910     buf.Pointer = NULL;
911     buf.Length = ACPI_ALLOCATE_BUFFER;
912 
913     ACPI_LOCK;
914 
915     /* Fetch and validate the HID. */
916     if ((h = acpi_get_handle(dev)) == NULL)
917 	goto out;
918     error = AcpiGetObjectInfo(h, &buf);
919     if (ACPI_FAILURE(error))
920 	goto out;
921     devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
922 
923     if ((devinfo->Valid & ACPI_VALID_HID) != 0)
924 	pnpid = PNP_EISAID(devinfo->HardwareId.Value);
925 
926 out:
927     if (buf.Pointer != NULL)
928 	AcpiOsFree(buf.Pointer);
929     ACPI_UNLOCK;
930     return_VALUE (pnpid);
931 }
932 
933 static int
934 acpi_isa_get_compatid(device_t dev, uint32_t *cids, int count)
935 {
936     ACPI_DEVICE_INFO	*devinfo;
937     ACPI_BUFFER		buf;
938     ACPI_HANDLE		h;
939     ACPI_STATUS		error;
940     uint32_t		*pnpid;
941     int			valid, i;
942     ACPI_LOCK_DECL;
943 
944     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
945 
946     pnpid = cids;
947     valid = 0;
948     buf.Pointer = NULL;
949     buf.Length = ACPI_ALLOCATE_BUFFER;
950 
951     ACPI_LOCK;
952 
953     /* Fetch and validate the CID */
954     if ((h = acpi_get_handle(dev)) == NULL)
955 	goto out;
956     error = AcpiGetObjectInfo(h, &buf);
957     if (ACPI_FAILURE(error))
958 	goto out;
959     devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
960     if ((devinfo->Valid & ACPI_VALID_CID) == 0)
961 	goto out;
962 
963     if (devinfo->CompatibilityId.Count < count)
964 	count = devinfo->CompatibilityId.Count;
965     for (i = 0; i < count; i++) {
966 	if (strncmp(devinfo->CompatibilityId.Id[i].Value, "PNP", 3) != 0)
967 	    continue;
968 	*pnpid++ = PNP_EISAID(devinfo->CompatibilityId.Id[i].Value);
969 	valid++;
970     }
971 
972 out:
973     if (buf.Pointer != NULL)
974 	AcpiOsFree(buf.Pointer);
975     ACPI_UNLOCK;
976     return_VALUE (valid);
977 }
978 
979 static int
980 acpi_isa_pnp_probe(device_t bus, device_t child, struct isa_pnp_id *ids)
981 {
982     int			result, cid_count, i;
983     uint32_t		lid, cids[8];
984 
985     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
986 
987     /*
988      * ISA-style drivers attached to ACPI may persist and
989      * probe manually if we return ENOENT.  We never want
990      * that to happen, so don't ever return it.
991      */
992     result = ENXIO;
993 
994     /* Scan the supplied IDs for a match */
995     lid = acpi_isa_get_logicalid(child);
996     cid_count = acpi_isa_get_compatid(child, cids, 8);
997     while (ids && ids->ip_id) {
998 	if (lid == ids->ip_id) {
999 	    result = 0;
1000 	    goto out;
1001 	}
1002 	for (i = 0; i < cid_count; i++) {
1003 	    if (cids[i] == ids->ip_id) {
1004 		result = 0;
1005 		goto out;
1006 	    }
1007 	}
1008 	ids++;
1009     }
1010 
1011  out:
1012     return_VALUE (result);
1013 }
1014 
1015 /*
1016  * Scan relevant portions of the ACPI namespace and attach child devices.
1017  *
1018  * Note that we only expect to find devices in the \_PR_, \_TZ_, \_SI_ and
1019  * \_SB_ scopes, and \_PR_ and \_TZ_ become obsolete in the ACPI 2.0 spec.
1020  */
1021 static void
1022 acpi_probe_children(device_t bus)
1023 {
1024     ACPI_HANDLE	parent;
1025     ACPI_STATUS	status;
1026     static char	*scopes[] = {"\\_PR_", "\\_TZ_", "\\_SI", "\\_SB_", NULL};
1027     int		i;
1028 
1029     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1030     ACPI_ASSERTLOCK;
1031 
1032     /* Create any static children by calling device identify methods. */
1033     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "device identify routines\n"));
1034     bus_generic_probe(bus);
1035 
1036     /*
1037      * Scan the namespace and insert placeholders for all the devices that
1038      * we find.
1039      *
1040      * Note that we use AcpiWalkNamespace rather than AcpiGetDevices because
1041      * we want to create nodes for all devices, not just those that are
1042      * currently present. (This assumes that we don't want to create/remove
1043      * devices as they appear, which might be smarter.)
1044      */
1045     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "namespace scan\n"));
1046     for (i = 0; scopes[i] != NULL; i++) {
1047 	status = AcpiGetHandle(ACPI_ROOT_OBJECT, scopes[i], &parent);
1048 	if (ACPI_SUCCESS(status)) {
1049 	    AcpiWalkNamespace(ACPI_TYPE_ANY, parent, 100, acpi_probe_child,
1050 			      bus, NULL);
1051 	}
1052     }
1053 
1054     /*
1055      * Scan all of the child devices we have created and let them probe/attach.
1056      */
1057     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "first bus_generic_attach\n"));
1058     bus_generic_attach(bus);
1059 
1060     /*
1061      * Some of these children may have attached others as part of their attach
1062      * process (eg. the root PCI bus driver), so rescan.
1063      */
1064     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "second bus_generic_attach\n"));
1065     bus_generic_attach(bus);
1066 
1067     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "done attaching children\n"));
1068     return_VOID;
1069 }
1070 
1071 /*
1072  * Evaluate a child device and determine whether we might attach a device to
1073  * it.
1074  */
1075 static ACPI_STATUS
1076 acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
1077 {
1078     ACPI_OBJECT_TYPE	type;
1079     device_t		child, bus = (device_t)context;
1080 
1081     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1082 
1083     /* Skip this device if we think we'll have trouble with it. */
1084     if (acpi_avoid(handle))
1085 	return_ACPI_STATUS (AE_OK);
1086 
1087     if (ACPI_SUCCESS(AcpiGetType(handle, &type))) {
1088 	switch(type) {
1089 	case ACPI_TYPE_DEVICE:
1090 	case ACPI_TYPE_PROCESSOR:
1091 	case ACPI_TYPE_THERMAL:
1092 	case ACPI_TYPE_POWER:
1093 	    if (acpi_disabled("children"))
1094 		break;
1095 
1096 	    /*
1097 	     * Create a placeholder device for this node.  Sort the placeholder
1098 	     * so that the probe/attach passes will run breadth-first.
1099 	     */
1100 	    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "scanning '%s'\n",
1101 			     acpi_name(handle)));
1102 	    child = BUS_ADD_CHILD(bus, level * 10, NULL, -1);
1103 	    if (child == NULL)
1104 		break;
1105 	    acpi_set_handle(child, handle);
1106 
1107 	    /*
1108 	     * Check that the device is present.  If it's not present,
1109 	     * leave it disabled (so that we have a device_t attached to
1110 	     * the handle, but we don't probe it).
1111 	     */
1112 	    if (type == ACPI_TYPE_DEVICE && !acpi_DeviceIsPresent(child)) {
1113 		device_disable(child);
1114 		break;
1115 	    }
1116 
1117 	    /*
1118 	     * Get the device's resource settings and attach them.
1119 	     * Note that if the device has _PRS but no _CRS, we need
1120 	     * to decide when it's appropriate to try to configure the
1121 	     * device.  Ignore the return value here; it's OK for the
1122 	     * device not to have any resources.
1123 	     */
1124 	    acpi_parse_resources(child, handle, &acpi_res_parse_set, NULL);
1125 
1126 	    /* If we're debugging, probe/attach now rather than later */
1127 	    ACPI_DEBUG_EXEC(device_probe_and_attach(child));
1128 	    break;
1129 	}
1130     }
1131 
1132     return_ACPI_STATUS (AE_OK);
1133 }
1134 
1135 static void
1136 acpi_shutdown_pre_sync(void *arg, int howto)
1137 {
1138     struct acpi_softc *sc = arg;
1139 
1140     ACPI_ASSERTLOCK;
1141 
1142     /*
1143      * Disable all ACPI events before soft off, otherwise the system
1144      * will be turned on again on some laptops.
1145      *
1146      * XXX this should probably be restricted to masking some events just
1147      *     before powering down, since we may still need ACPI during the
1148      *     shutdown process.
1149      */
1150     if (sc->acpi_disable_on_poweroff)
1151 	acpi_Disable(sc);
1152 }
1153 
1154 static void
1155 acpi_shutdown_final(void *arg, int howto)
1156 {
1157     ACPI_STATUS	status;
1158     ACPI_ASSERTLOCK;
1159 
1160     /*
1161      * If powering off, run the actual shutdown code on each processor.
1162      * It will only perform the shutdown on the BSP.  Some chipsets do
1163      * not power off the system correctly if called from an AP.
1164      */
1165     if ((howto & RB_POWEROFF) != 0) {
1166 	status = AcpiEnterSleepStatePrep(ACPI_STATE_S5);
1167 	if (ACPI_FAILURE(status)) {
1168 	    printf("AcpiEnterSleepStatePrep failed - %s\n",
1169 		   AcpiFormatException(status));
1170 	    return;
1171 	}
1172 	printf("Powering system off using ACPI\n");
1173 	smp_rendezvous(NULL, acpi_shutdown_poweroff, NULL, NULL);
1174     } else {
1175 	printf("Shutting down ACPI\n");
1176 	AcpiTerminate();
1177     }
1178 }
1179 
1180 /*
1181  * Since this function may be called with locks held or in an unknown
1182  * context, it cannot allocate memory, acquire locks, sleep, etc.
1183  */
1184 static void
1185 acpi_shutdown_poweroff(void *arg)
1186 {
1187     ACPI_STATUS	status;
1188 
1189     ACPI_ASSERTLOCK;
1190 
1191     /* Only attempt to power off if this is the BSP (cpuid 0). */
1192     if (PCPU_GET(cpuid) != 0)
1193 	return;
1194 
1195     ACPI_DISABLE_IRQS();
1196     status = AcpiEnterSleepState(ACPI_STATE_S5);
1197     if (ACPI_FAILURE(status)) {
1198 	printf("ACPI power-off failed - %s\n", AcpiFormatException(status));
1199     } else {
1200 	DELAY(1000000);
1201 	printf("ACPI power-off failed - timeout\n");
1202     }
1203 }
1204 
1205 static void
1206 acpi_enable_fixed_events(struct acpi_softc *sc)
1207 {
1208     static int	first_time = 1;
1209 
1210     ACPI_ASSERTLOCK;
1211 
1212     /* Enable and clear fixed events and install handlers. */
1213     if (AcpiGbl_FADT != NULL && AcpiGbl_FADT->PwrButton == 0) {
1214 	AcpiClearEvent(ACPI_EVENT_POWER_BUTTON);
1215 	AcpiInstallFixedEventHandler(ACPI_EVENT_POWER_BUTTON,
1216 				     acpi_event_power_button_sleep, sc);
1217 	if (first_time)
1218 	    device_printf(sc->acpi_dev, "Power Button (fixed)\n");
1219     }
1220     if (AcpiGbl_FADT != NULL && AcpiGbl_FADT->SleepButton == 0) {
1221 	AcpiClearEvent(ACPI_EVENT_SLEEP_BUTTON);
1222 	AcpiInstallFixedEventHandler(ACPI_EVENT_SLEEP_BUTTON,
1223 				     acpi_event_sleep_button_sleep, sc);
1224 	if (first_time)
1225 	    device_printf(sc->acpi_dev, "Sleep Button (fixed)\n");
1226     }
1227 
1228     first_time = 0;
1229 }
1230 
1231 /*
1232  * Returns true if the device is actually present and should
1233  * be attached to.  This requires the present, enabled, UI-visible
1234  * and diagnostics-passed bits to be set.
1235  */
1236 BOOLEAN
1237 acpi_DeviceIsPresent(device_t dev)
1238 {
1239     ACPI_DEVICE_INFO	*devinfo;
1240     ACPI_HANDLE		h;
1241     ACPI_BUFFER		buf;
1242     ACPI_STATUS		error;
1243     int			ret;
1244 
1245     ACPI_ASSERTLOCK;
1246 
1247     ret = FALSE;
1248     if ((h = acpi_get_handle(dev)) == NULL)
1249 	return (FALSE);
1250     buf.Pointer = NULL;
1251     buf.Length = ACPI_ALLOCATE_BUFFER;
1252     error = AcpiGetObjectInfo(h, &buf);
1253     if (ACPI_FAILURE(error))
1254 	return (FALSE);
1255     devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1256 
1257     /* If no _STA method, must be present */
1258     if ((devinfo->Valid & ACPI_VALID_STA) == 0)
1259 	ret = TRUE;
1260 
1261     /* Return true for 'present' and 'functioning' */
1262     if ((devinfo->CurrentStatus & 0x9) == 0x9)
1263 	ret = TRUE;
1264 
1265     AcpiOsFree(buf.Pointer);
1266     return (ret);
1267 }
1268 
1269 /*
1270  * Returns true if the battery is actually present and inserted.
1271  */
1272 BOOLEAN
1273 acpi_BatteryIsPresent(device_t dev)
1274 {
1275     ACPI_DEVICE_INFO	*devinfo;
1276     ACPI_HANDLE		h;
1277     ACPI_BUFFER		buf;
1278     ACPI_STATUS		error;
1279     int			ret;
1280 
1281     ACPI_ASSERTLOCK;
1282 
1283     ret = FALSE;
1284     if ((h = acpi_get_handle(dev)) == NULL)
1285 	return (FALSE);
1286     buf.Pointer = NULL;
1287     buf.Length = ACPI_ALLOCATE_BUFFER;
1288     error = AcpiGetObjectInfo(h, &buf);
1289     if (ACPI_FAILURE(error))
1290 	return (FALSE);
1291     devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1292 
1293     /* If no _STA method, must be present */
1294     if ((devinfo->Valid & ACPI_VALID_STA) == 0)
1295 	ret = TRUE;
1296 
1297     /* Return true for 'present' and 'functioning' */
1298     if ((devinfo->CurrentStatus & 0x19) == 0x19)
1299 	ret = TRUE;
1300 
1301     AcpiOsFree(buf.Pointer);
1302     return (ret);
1303 }
1304 
1305 /*
1306  * Match a HID string against a device
1307  */
1308 BOOLEAN
1309 acpi_MatchHid(device_t dev, char *hid)
1310 {
1311     ACPI_DEVICE_INFO	*devinfo;
1312     ACPI_HANDLE		h;
1313     ACPI_BUFFER		buf;
1314     ACPI_STATUS		error;
1315     int			ret, i;
1316 
1317     ACPI_ASSERTLOCK;
1318 
1319     ret = FALSE;
1320     if (hid == NULL)
1321 	return (FALSE);
1322     if ((h = acpi_get_handle(dev)) == NULL)
1323 	return (FALSE);
1324     buf.Pointer = NULL;
1325     buf.Length = ACPI_ALLOCATE_BUFFER;
1326     error = AcpiGetObjectInfo(h, &buf);
1327     if (ACPI_FAILURE(error))
1328 	return (FALSE);
1329     devinfo = (ACPI_DEVICE_INFO *)buf.Pointer;
1330 
1331     if ((devinfo->Valid & ACPI_VALID_HID) != 0 &&
1332 	strcmp(hid, devinfo->HardwareId.Value) == 0)
1333 	    ret = TRUE;
1334     else if ((devinfo->Valid & ACPI_VALID_CID) != 0) {
1335 	for (i = 0; i < devinfo->CompatibilityId.Count; i++) {
1336 	    if (strcmp(hid, devinfo->CompatibilityId.Id[i].Value) == 0) {
1337 		ret = TRUE;
1338 		break;
1339 	    }
1340 	}
1341     }
1342 
1343     AcpiOsFree(buf.Pointer);
1344     return (ret);
1345 }
1346 
1347 /*
1348  * Return the handle of a named object within our scope, ie. that of (parent)
1349  * or one if its parents.
1350  */
1351 ACPI_STATUS
1352 acpi_GetHandleInScope(ACPI_HANDLE parent, char *path, ACPI_HANDLE *result)
1353 {
1354     ACPI_HANDLE		r;
1355     ACPI_STATUS		status;
1356 
1357     ACPI_ASSERTLOCK;
1358 
1359     /* Walk back up the tree to the root */
1360     for (;;) {
1361 	status = AcpiGetHandle(parent, path, &r);
1362 	if (ACPI_SUCCESS(status)) {
1363 	    *result = r;
1364 	    return (AE_OK);
1365 	}
1366 	if (status != AE_NOT_FOUND)
1367 	    return (AE_OK);
1368 	if (ACPI_FAILURE(AcpiGetParent(parent, &r)))
1369 	    return (AE_NOT_FOUND);
1370 	parent = r;
1371     }
1372 }
1373 
1374 /* Find the difference between two PM tick counts. */
1375 uint32_t
1376 acpi_TimerDelta(uint32_t end, uint32_t start)
1377 {
1378     uint32_t delta;
1379 
1380     if (end >= start)
1381 	delta = end - start;
1382     else if (AcpiGbl_FADT->TmrValExt == 0)
1383 	delta = ((0x00FFFFFF - start) + end + 1) & 0x00FFFFFF;
1384     else
1385 	delta = ((0xFFFFFFFF - start) + end + 1);
1386     return (delta);
1387 }
1388 
1389 /*
1390  * Allocate a buffer with a preset data size.
1391  */
1392 ACPI_BUFFER *
1393 acpi_AllocBuffer(int size)
1394 {
1395     ACPI_BUFFER	*buf;
1396 
1397     if ((buf = malloc(size + sizeof(*buf), M_ACPIDEV, M_NOWAIT)) == NULL)
1398 	return (NULL);
1399     buf->Length = size;
1400     buf->Pointer = (void *)(buf + 1);
1401     return (buf);
1402 }
1403 
1404 ACPI_STATUS
1405 acpi_SetInteger(ACPI_HANDLE handle, char *path, UINT32 number)
1406 {
1407     ACPI_OBJECT arg1;
1408     ACPI_OBJECT_LIST args;
1409 
1410     ACPI_ASSERTLOCK;
1411 
1412     arg1.Type = ACPI_TYPE_INTEGER;
1413     arg1.Integer.Value = number;
1414     args.Count = 1;
1415     args.Pointer = &arg1;
1416 
1417     return (AcpiEvaluateObject(handle, path, &args, NULL));
1418 }
1419 
1420 /*
1421  * Evaluate a path that should return an integer.
1422  */
1423 ACPI_STATUS
1424 acpi_GetInteger(ACPI_HANDLE handle, char *path, UINT32 *number)
1425 {
1426     ACPI_STATUS	status;
1427     ACPI_BUFFER	buf;
1428     ACPI_OBJECT	param;
1429 
1430     ACPI_ASSERTLOCK;
1431 
1432     if (handle == NULL)
1433 	handle = ACPI_ROOT_OBJECT;
1434 
1435     /*
1436      * Assume that what we've been pointed at is an Integer object, or
1437      * a method that will return an Integer.
1438      */
1439     buf.Pointer = &param;
1440     buf.Length = sizeof(param);
1441     status = AcpiEvaluateObject(handle, path, NULL, &buf);
1442     if (ACPI_SUCCESS(status)) {
1443 	if (param.Type == ACPI_TYPE_INTEGER)
1444 	    *number = param.Integer.Value;
1445 	else
1446 	    status = AE_TYPE;
1447     }
1448 
1449     /*
1450      * In some applications, a method that's expected to return an Integer
1451      * may instead return a Buffer (probably to simplify some internal
1452      * arithmetic).  We'll try to fetch whatever it is, and if it's a Buffer,
1453      * convert it into an Integer as best we can.
1454      *
1455      * This is a hack.
1456      */
1457     if (status == AE_BUFFER_OVERFLOW) {
1458 	if ((buf.Pointer = AcpiOsAllocate(buf.Length)) == NULL) {
1459 	    status = AE_NO_MEMORY;
1460 	} else {
1461 	    status = AcpiEvaluateObject(handle, path, NULL, &buf);
1462 	    if (ACPI_SUCCESS(status))
1463 		status = acpi_ConvertBufferToInteger(&buf, number);
1464 	    AcpiOsFree(buf.Pointer);
1465 	}
1466     }
1467     return (status);
1468 }
1469 
1470 ACPI_STATUS
1471 acpi_ConvertBufferToInteger(ACPI_BUFFER *bufp, UINT32 *number)
1472 {
1473     ACPI_OBJECT	*p;
1474     UINT8	*val;
1475     int		i;
1476 
1477     p = (ACPI_OBJECT *)bufp->Pointer;
1478     if (p->Type == ACPI_TYPE_INTEGER) {
1479 	*number = p->Integer.Value;
1480 	return (AE_OK);
1481     }
1482     if (p->Type != ACPI_TYPE_BUFFER)
1483 	return (AE_TYPE);
1484     if (p->Buffer.Length > sizeof(int))
1485 	return (AE_BAD_DATA);
1486 
1487     *number = 0;
1488     val = p->Buffer.Pointer;
1489     for (i = 0; i < p->Buffer.Length; i++)
1490 	*number += val[i] << (i * 8);
1491     return (AE_OK);
1492 }
1493 
1494 /*
1495  * Iterate over the elements of an a package object, calling the supplied
1496  * function for each element.
1497  *
1498  * XXX possible enhancement might be to abort traversal on error.
1499  */
1500 ACPI_STATUS
1501 acpi_ForeachPackageObject(ACPI_OBJECT *pkg,
1502 	void (*func)(ACPI_OBJECT *comp, void *arg), void *arg)
1503 {
1504     ACPI_OBJECT	*comp;
1505     int		i;
1506 
1507     if (pkg == NULL || pkg->Type != ACPI_TYPE_PACKAGE)
1508 	return (AE_BAD_PARAMETER);
1509 
1510     /* Iterate over components */
1511     i = 0;
1512     comp = pkg->Package.Elements;
1513     for (; i < pkg->Package.Count; i++, comp++)
1514 	func(comp, arg);
1515 
1516     return (AE_OK);
1517 }
1518 
1519 /*
1520  * Find the (index)th resource object in a set.
1521  */
1522 ACPI_STATUS
1523 acpi_FindIndexedResource(ACPI_BUFFER *buf, int index, ACPI_RESOURCE **resp)
1524 {
1525     ACPI_RESOURCE	*rp;
1526     int			i;
1527 
1528     rp = (ACPI_RESOURCE *)buf->Pointer;
1529     i = index;
1530     while (i-- > 0) {
1531 	/* Range check */
1532 	if (rp > (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
1533 	    return (AE_BAD_PARAMETER);
1534 
1535 	/* Check for terminator */
1536 	if (rp->Id == ACPI_RSTYPE_END_TAG || rp->Length == 0)
1537 	    return (AE_NOT_FOUND);
1538 	rp = ACPI_NEXT_RESOURCE(rp);
1539     }
1540     if (resp != NULL)
1541 	*resp = rp;
1542 
1543     return (AE_OK);
1544 }
1545 
1546 /*
1547  * Append an ACPI_RESOURCE to an ACPI_BUFFER.
1548  *
1549  * Given a pointer to an ACPI_RESOURCE structure, expand the ACPI_BUFFER
1550  * provided to contain it.  If the ACPI_BUFFER is empty, allocate a sensible
1551  * backing block.  If the ACPI_RESOURCE is NULL, return an empty set of
1552  * resources.
1553  */
1554 #define ACPI_INITIAL_RESOURCE_BUFFER_SIZE	512
1555 
1556 ACPI_STATUS
1557 acpi_AppendBufferResource(ACPI_BUFFER *buf, ACPI_RESOURCE *res)
1558 {
1559     ACPI_RESOURCE	*rp;
1560     void		*newp;
1561 
1562     /* Initialise the buffer if necessary. */
1563     if (buf->Pointer == NULL) {
1564 	buf->Length = ACPI_INITIAL_RESOURCE_BUFFER_SIZE;
1565 	if ((buf->Pointer = AcpiOsAllocate(buf->Length)) == NULL)
1566 	    return (AE_NO_MEMORY);
1567 	rp = (ACPI_RESOURCE *)buf->Pointer;
1568 	rp->Id = ACPI_RSTYPE_END_TAG;
1569 	rp->Length = 0;
1570     }
1571     if (res == NULL)
1572 	return (AE_OK);
1573 
1574     /*
1575      * Scan the current buffer looking for the terminator.
1576      * This will either find the terminator or hit the end
1577      * of the buffer and return an error.
1578      */
1579     rp = (ACPI_RESOURCE *)buf->Pointer;
1580     for (;;) {
1581 	/* Range check, don't go outside the buffer */
1582 	if (rp >= (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
1583 	    return (AE_BAD_PARAMETER);
1584 	if (rp->Id == ACPI_RSTYPE_END_TAG || rp->Length == 0)
1585 	    break;
1586 	rp = ACPI_NEXT_RESOURCE(rp);
1587     }
1588 
1589     /*
1590      * Check the size of the buffer and expand if required.
1591      *
1592      * Required size is:
1593      *	size of existing resources before terminator +
1594      *	size of new resource and header +
1595      * 	size of terminator.
1596      *
1597      * Note that this loop should really only run once, unless
1598      * for some reason we are stuffing a *really* huge resource.
1599      */
1600     while ((((u_int8_t *)rp - (u_int8_t *)buf->Pointer) +
1601 	    res->Length + ACPI_RESOURCE_LENGTH_NO_DATA +
1602 	    ACPI_RESOURCE_LENGTH) >= buf->Length) {
1603 	if ((newp = AcpiOsAllocate(buf->Length * 2)) == NULL)
1604 	    return (AE_NO_MEMORY);
1605 	bcopy(buf->Pointer, newp, buf->Length);
1606 	rp = (ACPI_RESOURCE *)((u_int8_t *)newp +
1607 			       ((u_int8_t *)rp - (u_int8_t *)buf->Pointer));
1608 	AcpiOsFree(buf->Pointer);
1609 	buf->Pointer = newp;
1610 	buf->Length += buf->Length;
1611     }
1612 
1613     /* Insert the new resource. */
1614     bcopy(res, rp, res->Length + ACPI_RESOURCE_LENGTH_NO_DATA);
1615 
1616     /* And add the terminator. */
1617     rp = ACPI_NEXT_RESOURCE(rp);
1618     rp->Id = ACPI_RSTYPE_END_TAG;
1619     rp->Length = 0;
1620 
1621     return (AE_OK);
1622 }
1623 
1624 /*
1625  * Set interrupt model.
1626  */
1627 ACPI_STATUS
1628 acpi_SetIntrModel(int model)
1629 {
1630 
1631     return (acpi_SetInteger(ACPI_ROOT_OBJECT, "_PIC", model));
1632 }
1633 
1634 #define ACPI_MINIMUM_AWAKETIME	5
1635 
1636 static void
1637 acpi_sleep_enable(void *arg)
1638 {
1639     ((struct acpi_softc *)arg)->acpi_sleep_disabled = 0;
1640 }
1641 
1642 /*
1643  * Set the system sleep state
1644  *
1645  * Currently we support S1-S5 but S4 is only S4BIOS
1646  */
1647 ACPI_STATUS
1648 acpi_SetSleepState(struct acpi_softc *sc, int state)
1649 {
1650     ACPI_STATUS	status = AE_OK;
1651     UINT8	TypeA;
1652     UINT8	TypeB;
1653 
1654     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
1655     ACPI_ASSERTLOCK;
1656 
1657     /* Avoid reentry if already attempting to suspend. */
1658     if (sc->acpi_sstate != ACPI_STATE_S0)
1659 	return_ACPI_STATUS (AE_BAD_PARAMETER);
1660 
1661     /* We recently woke up so don't suspend again for a while. */
1662     if (sc->acpi_sleep_disabled)
1663 	return_ACPI_STATUS (AE_OK);
1664 
1665     switch (state) {
1666     case ACPI_STATE_S1:
1667     case ACPI_STATE_S2:
1668     case ACPI_STATE_S3:
1669     case ACPI_STATE_S4:
1670 	status = AcpiGetSleepTypeData((UINT8)state, &TypeA, &TypeB);
1671 	if (status == AE_NOT_FOUND) {
1672 	    device_printf(sc->acpi_dev,
1673 			  "Sleep state S%d not supported by BIOS\n", state);
1674 	    break;
1675 	} else if (ACPI_FAILURE(status)) {
1676 	    device_printf(sc->acpi_dev, "AcpiGetSleepTypeData failed - %s\n",
1677 			  AcpiFormatException(status));
1678 	    break;
1679 	}
1680 
1681 	sc->acpi_sstate = state;
1682 	sc->acpi_sleep_disabled = 1;
1683 
1684 	/* Inform all devices that we are going to sleep. */
1685 	if (DEVICE_SUSPEND(root_bus) != 0) {
1686 	    /*
1687 	     * Re-wake the system.
1688 	     *
1689 	     * XXX note that a better two-pass approach with a 'veto' pass
1690 	     *     followed by a "real thing" pass would be better, but the
1691 	     *     current bus interface does not provide for this.
1692 	     */
1693 	    DEVICE_RESUME(root_bus);
1694 	    return_ACPI_STATUS (AE_ERROR);
1695 	}
1696 
1697 	status = AcpiEnterSleepStatePrep(state);
1698 	if (ACPI_FAILURE(status)) {
1699 	    device_printf(sc->acpi_dev, "AcpiEnterSleepStatePrep failed - %s\n",
1700 			  AcpiFormatException(status));
1701 	    break;
1702 	}
1703 
1704 	if (sc->acpi_sleep_delay > 0)
1705 	    DELAY(sc->acpi_sleep_delay * 1000000);
1706 
1707 	if (state != ACPI_STATE_S1) {
1708 	    acpi_sleep_machdep(sc, state);
1709 
1710 	    /* AcpiEnterSleepState() may be incomplete, unlock if locked. */
1711 	    if (AcpiGbl_MutexInfo[ACPI_MTX_HARDWARE].OwnerId !=
1712 		ACPI_MUTEX_NOT_ACQUIRED) {
1713 
1714 		AcpiUtReleaseMutex(ACPI_MTX_HARDWARE);
1715 	    }
1716 
1717 	    /* Re-enable ACPI hardware on wakeup from sleep state 4. */
1718 	    if (state == ACPI_STATE_S4)
1719 		AcpiEnable();
1720 	} else {
1721 	    status = AcpiEnterSleepState((UINT8)state);
1722 	    if (ACPI_FAILURE(status)) {
1723 		device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n",
1724 			      AcpiFormatException(status));
1725 		break;
1726 	    }
1727 	}
1728 	AcpiLeaveSleepState((UINT8)state);
1729 	DEVICE_RESUME(root_bus);
1730 	sc->acpi_sstate = ACPI_STATE_S0;
1731 	acpi_enable_fixed_events(sc);
1732 	break;
1733     case ACPI_STATE_S5:
1734 	/*
1735 	 * Shut down cleanly and power off.  This will call us back through the
1736 	 * shutdown handlers.
1737 	 */
1738 	shutdown_nice(RB_POWEROFF);
1739 	break;
1740     case ACPI_STATE_S0:
1741     default:
1742 	status = AE_BAD_PARAMETER;
1743 	break;
1744     }
1745 
1746     /* Disable a second sleep request for a short period */
1747     if (sc->acpi_sleep_disabled)
1748 	timeout(acpi_sleep_enable, (caddr_t)sc, hz * ACPI_MINIMUM_AWAKETIME);
1749 
1750     return_ACPI_STATUS (status);
1751 }
1752 
1753 /*
1754  * Enable/Disable ACPI
1755  */
1756 ACPI_STATUS
1757 acpi_Enable(struct acpi_softc *sc)
1758 {
1759     ACPI_STATUS	status;
1760     u_int32_t	flags;
1761 
1762     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1763     ACPI_ASSERTLOCK;
1764 
1765     flags = ACPI_NO_ADDRESS_SPACE_INIT | ACPI_NO_HARDWARE_INIT |
1766 	    ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
1767     if (!sc->acpi_enabled)
1768 	status = AcpiEnableSubsystem(flags);
1769     else
1770 	status = AE_OK;
1771 
1772     if (status == AE_OK)
1773 	sc->acpi_enabled = 1;
1774 
1775     return_ACPI_STATUS (status);
1776 }
1777 
1778 ACPI_STATUS
1779 acpi_Disable(struct acpi_softc *sc)
1780 {
1781     ACPI_STATUS	status;
1782 
1783     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1784     ACPI_ASSERTLOCK;
1785 
1786     if (sc->acpi_enabled)
1787 	status = AcpiDisable();
1788     else
1789 	status = AE_OK;
1790 
1791     if (status == AE_OK)
1792 	sc->acpi_enabled = 0;
1793 
1794     return_ACPI_STATUS (status);
1795 }
1796 
1797 /*
1798  * ACPI Event Handlers
1799  */
1800 
1801 /* System Event Handlers (registered by EVENTHANDLER_REGISTER) */
1802 
1803 static void
1804 acpi_system_eventhandler_sleep(void *arg, int state)
1805 {
1806     ACPI_LOCK_DECL;
1807     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
1808 
1809     ACPI_LOCK;
1810     if (state >= ACPI_STATE_S0 && state <= ACPI_S_STATES_MAX)
1811 	acpi_SetSleepState((struct acpi_softc *)arg, state);
1812     ACPI_UNLOCK;
1813     return_VOID;
1814 }
1815 
1816 static void
1817 acpi_system_eventhandler_wakeup(void *arg, int state)
1818 {
1819     ACPI_LOCK_DECL;
1820     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
1821 
1822     /* Well, what to do? :-) */
1823 
1824     ACPI_LOCK;
1825     ACPI_UNLOCK;
1826 
1827     return_VOID;
1828 }
1829 
1830 /*
1831  * ACPICA Event Handlers (FixedEvent, also called from button notify handler)
1832  */
1833 UINT32
1834 acpi_event_power_button_sleep(void *context)
1835 {
1836     struct acpi_softc	*sc = (struct acpi_softc *)context;
1837 
1838     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1839 
1840     EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_power_button_sx);
1841 
1842     return_VALUE (ACPI_INTERRUPT_HANDLED);
1843 }
1844 
1845 UINT32
1846 acpi_event_power_button_wake(void *context)
1847 {
1848     struct acpi_softc	*sc = (struct acpi_softc *)context;
1849 
1850     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1851 
1852     EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_power_button_sx);
1853 
1854     return_VALUE (ACPI_INTERRUPT_HANDLED);
1855 }
1856 
1857 UINT32
1858 acpi_event_sleep_button_sleep(void *context)
1859 {
1860     struct acpi_softc	*sc = (struct acpi_softc *)context;
1861 
1862     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1863 
1864     EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_sleep_button_sx);
1865 
1866     return_VALUE (ACPI_INTERRUPT_HANDLED);
1867 }
1868 
1869 UINT32
1870 acpi_event_sleep_button_wake(void *context)
1871 {
1872     struct acpi_softc	*sc = (struct acpi_softc *)context;
1873 
1874     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1875 
1876     EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_sleep_button_sx);
1877 
1878     return_VALUE (ACPI_INTERRUPT_HANDLED);
1879 }
1880 
1881 /*
1882  * XXX This is kinda ugly, and should not be here.
1883  */
1884 struct acpi_staticbuf {
1885     ACPI_BUFFER	buffer;
1886     char	data[512];
1887 };
1888 
1889 char *
1890 acpi_name(ACPI_HANDLE handle)
1891 {
1892     static struct acpi_staticbuf	buf;
1893 
1894     ACPI_ASSERTLOCK;
1895 
1896     buf.buffer.Length = 512;
1897     buf.buffer.Pointer = &buf.data[0];
1898 
1899     if (ACPI_SUCCESS(AcpiGetName(handle, ACPI_FULL_PATHNAME, &buf.buffer)))
1900 	return (buf.buffer.Pointer);
1901 
1902     return ("(unknown path)");
1903 }
1904 
1905 /*
1906  * Debugging/bug-avoidance.  Avoid trying to fetch info on various
1907  * parts of the namespace.
1908  */
1909 int
1910 acpi_avoid(ACPI_HANDLE handle)
1911 {
1912     char	*cp, *env, *np;
1913     int		len;
1914 
1915     np = acpi_name(handle);
1916     if (*np == '\\')
1917 	np++;
1918     if ((env = getenv("debug.acpi.avoid")) == NULL)
1919 	return (0);
1920 
1921     /* Scan the avoid list checking for a match */
1922     cp = env;
1923     for (;;) {
1924 	while ((*cp != 0) && isspace(*cp))
1925 	    cp++;
1926 	if (*cp == 0)
1927 	    break;
1928 	len = 0;
1929 	while ((cp[len] != 0) && !isspace(cp[len]))
1930 	    len++;
1931 	if (!strncmp(cp, np, len)) {
1932 	    freeenv(env);
1933 	    return(1);
1934 	}
1935 	cp += len;
1936     }
1937     freeenv(env);
1938 
1939     return (0);
1940 }
1941 
1942 /*
1943  * Debugging/bug-avoidance.  Disable ACPI subsystem components.
1944  */
1945 int
1946 acpi_disabled(char *subsys)
1947 {
1948     char	*cp, *env;
1949     int		len;
1950 
1951     if ((env = getenv("debug.acpi.disabled")) == NULL)
1952 	return (0);
1953     if (strcmp(env, "all") == 0) {
1954 	freeenv(env);
1955 	return (1);
1956     }
1957 
1958     /* Scan the disable list, checking for a match. */
1959     cp = env;
1960     for (;;) {
1961 	while (*cp != '\0' && isspace(*cp))
1962 	    cp++;
1963 	if (*cp == '\0')
1964 	    break;
1965 	len = 0;
1966 	while (cp[len] != '\0' && !isspace(cp[len]))
1967 	    len++;
1968 	if (strncmp(cp, subsys, len) == 0) {
1969 	    freeenv(env);
1970 	    return (1);
1971 	}
1972 	cp += len;
1973     }
1974     freeenv(env);
1975 
1976     return (0);
1977 }
1978 
1979 /*
1980  * Device wake capability enable/disable.
1981  */
1982 void
1983 acpi_device_enable_wake_capability(ACPI_HANDLE h, int enable)
1984 {
1985     /*
1986      * TBD: All Power Resources referenced by elements 2 through N
1987      *      of the _PRW object are put into the ON state.
1988      */
1989 
1990     (void)acpi_SetInteger(h, "_PSW", enable);
1991 }
1992 
1993 void
1994 acpi_device_enable_wake_event(ACPI_HANDLE h)
1995 {
1996     struct acpi_softc		*sc;
1997     uint32_t			gpe_bit, lowest_wake;
1998     ACPI_HANDLE			handle;
1999     ACPI_STATUS			status;
2000     ACPI_BUFFER			prw_buffer;
2001     ACPI_OBJECT			*res, *res2;
2002 
2003     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2004 
2005     sc = devclass_get_softc(acpi_devclass, 0);
2006     if (sc == NULL)
2007 	return;
2008 
2009     /*
2010      * The _PRW object (7.2.9) is only required for devices that have the
2011      * ability to wake the system from a sleeping state.
2012      */
2013     prw_buffer.Pointer = NULL;
2014     prw_buffer.Length = ACPI_ALLOCATE_BUFFER;
2015     status = AcpiEvaluateObject(h, "_PRW", NULL, &prw_buffer);
2016     if (ACPI_FAILURE(status))
2017 	return;
2018     res = (ACPI_OBJECT *)prw_buffer.Pointer;
2019     if (res == NULL)
2020 	return;
2021     if (!ACPI_PKG_VALID(res, 2))
2022 	goto out;
2023 
2024     /*
2025      * Element 1 of the _PRW object:
2026      * The lowest power system sleeping state that can be entered while still
2027      * providing wake functionality.  The sleeping state being entered must
2028      * be less than (i.e., higher power) or equal to this value.
2029      */
2030     if (acpi_PkgInt32(res, 1, &lowest_wake) != 0)
2031 	goto out;
2032     if (sc->acpi_sstate > lowest_wake)
2033 	goto out;
2034 
2035     /*
2036      * Element 0 of the _PRW object:
2037      */
2038     switch (res->Package.Elements[0].Type) {
2039     case ACPI_TYPE_INTEGER:
2040 	/*
2041 	 * If the data type of this package element is numeric, then this
2042 	 * _PRW package element is the bit index in the GPEx_EN, in the
2043 	 * GPE blocks described in the FADT, of the enable bit that is
2044 	 * enabled for the wake event.
2045 	 */
2046 	gpe_bit = res->Package.Elements[0].Integer.Value;
2047 	status = AcpiSetGpeType(NULL, gpe_bit, ACPI_GPE_TYPE_WAKE_RUN);
2048 	if (ACPI_FAILURE(status)) {
2049 	    printf("wake enable: AcpiSetGpeType failed for %u\n",
2050 		   gpe_bit);
2051 	    goto out;
2052 	}
2053 	status = AcpiEnableGpe(NULL, gpe_bit, ACPI_NOT_ISR);
2054 	if (ACPI_FAILURE(status))
2055 	    printf("wake enable: AcpiEnableGpe failed for %u\n",
2056 		   gpe_bit);
2057 	break;
2058     case ACPI_TYPE_PACKAGE:
2059 	/*
2060 	 * If the data type of this package element is a package, then this
2061 	 * _PRW package element is itself a package containing two
2062 	 * elements.  The first is an object reference to the GPE Block
2063 	 * device that contains the GPE that will be triggered by the wake
2064 	 * event.  The second element is numeric and it contains the bit
2065 	 * index in the GPEx_EN, in the GPE Block referenced by the
2066 	 * first element in the package, of the enable bit that is enabled for
2067 	 * the wake event.
2068 	 *
2069 	 * For example, if this field is a package then it is of the form:
2070 	 * Package() {\_SB.PCI0.ISA.GPE, 2}
2071 	 */
2072 	res2 = &res->Package.Elements[0];
2073 	if (!ACPI_PKG_VALID(res2, 2))
2074 	    goto out;
2075 	handle = acpi_GetReference(NULL, &res2->Package.Elements[0]);
2076 	if (handle == NULL || acpi_PkgInt32(res2, 1, &gpe_bit) != 0)
2077 	    goto out;
2078 	status = AcpiSetGpeType(handle, gpe_bit, ACPI_GPE_TYPE_WAKE_RUN);
2079 	if (ACPI_FAILURE(status)) {
2080 	    printf("wake enable: AcpiSetGpeType failed for %u\n",
2081 		   gpe_bit);
2082 	    goto out;
2083 	}
2084 	status = AcpiEnableGpe(handle, gpe_bit, ACPI_NOT_ISR);
2085 	if (ACPI_FAILURE(status))
2086 	    printf("wake enable: AcpiEnableGpe (package) failed for %u\n",
2087 		   gpe_bit);
2088 	break;
2089     default:
2090 	break;
2091     }
2092 
2093 out:
2094     if (prw_buffer.Pointer != NULL)
2095 	AcpiOsFree(prw_buffer.Pointer);
2096 }
2097 
2098 /*
2099  * Control interface.
2100  *
2101  * We multiplex ioctls for all participating ACPI devices here.  Individual
2102  * drivers wanting to be accessible via /dev/acpi should use the
2103  * register/deregister interface to make their handlers visible.
2104  */
2105 struct acpi_ioctl_hook
2106 {
2107     TAILQ_ENTRY(acpi_ioctl_hook) link;
2108     u_long			 cmd;
2109     acpi_ioctl_fn		 fn;
2110     void			 *arg;
2111 };
2112 
2113 static TAILQ_HEAD(,acpi_ioctl_hook)	acpi_ioctl_hooks;
2114 static int				acpi_ioctl_hooks_initted;
2115 
2116 /*
2117  * Register an ioctl handler.
2118  */
2119 int
2120 acpi_register_ioctl(u_long cmd, acpi_ioctl_fn fn, void *arg)
2121 {
2122     struct acpi_ioctl_hook	*hp;
2123 
2124     if ((hp = malloc(sizeof(*hp), M_ACPIDEV, M_NOWAIT)) == NULL)
2125 	return (ENOMEM);
2126     hp->cmd = cmd;
2127     hp->fn = fn;
2128     hp->arg = arg;
2129     if (acpi_ioctl_hooks_initted == 0) {
2130 	TAILQ_INIT(&acpi_ioctl_hooks);
2131 	acpi_ioctl_hooks_initted = 1;
2132     }
2133     TAILQ_INSERT_TAIL(&acpi_ioctl_hooks, hp, link);
2134     return (0);
2135 }
2136 
2137 /*
2138  * Deregister an ioctl handler.
2139  */
2140 void
2141 acpi_deregister_ioctl(u_long cmd, acpi_ioctl_fn fn)
2142 {
2143     struct acpi_ioctl_hook	*hp;
2144 
2145     TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link)
2146 	if ((hp->cmd == cmd) && (hp->fn == fn))
2147 	    break;
2148 
2149     if (hp != NULL) {
2150 	TAILQ_REMOVE(&acpi_ioctl_hooks, hp, link);
2151 	free(hp, M_ACPIDEV);
2152     }
2153 }
2154 
2155 static int
2156 acpiopen(dev_t dev, int flag, int fmt, d_thread_t *td)
2157 {
2158     return (0);
2159 }
2160 
2161 static int
2162 acpiclose(dev_t dev, int flag, int fmt, d_thread_t *td)
2163 {
2164     return (0);
2165 }
2166 
2167 static int
2168 acpiioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, d_thread_t *td)
2169 {
2170     struct acpi_softc		*sc;
2171     struct acpi_ioctl_hook	*hp;
2172     int				error, xerror, state;
2173     ACPI_LOCK_DECL;
2174 
2175     ACPI_LOCK;
2176 
2177     error = state = 0;
2178     sc = dev->si_drv1;
2179 
2180     /*
2181      * Scan the list of registered ioctls, looking for handlers.
2182      */
2183     if (acpi_ioctl_hooks_initted) {
2184 	TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link) {
2185 	    if (hp->cmd == cmd) {
2186 		xerror = hp->fn(cmd, addr, hp->arg);
2187 		if (xerror != 0)
2188 		    error = xerror;
2189 		goto out;
2190 	    }
2191 	}
2192     }
2193 
2194     /*
2195      * Core ioctls are not permitted for non-writable user.
2196      * Currently, other ioctls just fetch information.
2197      * Not changing system behavior.
2198      */
2199     if((flag & FWRITE) == 0)
2200 	return (EPERM);
2201 
2202     /* Core system ioctls. */
2203     switch (cmd) {
2204     case ACPIIO_ENABLE:
2205 	if (ACPI_FAILURE(acpi_Enable(sc)))
2206 	    error = ENXIO;
2207 	break;
2208     case ACPIIO_DISABLE:
2209 	if (ACPI_FAILURE(acpi_Disable(sc)))
2210 	    error = ENXIO;
2211 	break;
2212     case ACPIIO_SETSLPSTATE:
2213 	if (!sc->acpi_enabled) {
2214 	    error = ENXIO;
2215 	    break;
2216 	}
2217 	state = *(int *)addr;
2218 	if (state >= ACPI_STATE_S0  && state <= ACPI_S_STATES_MAX) {
2219 	    if (ACPI_FAILURE(acpi_SetSleepState(sc, state)))
2220 		error = EINVAL;
2221 	} else {
2222 	    error = EINVAL;
2223 	}
2224 	break;
2225     default:
2226 	if (error == 0)
2227 	    error = EINVAL;
2228 	break;
2229     }
2230 
2231 out:
2232     ACPI_UNLOCK;
2233     return (error);
2234 }
2235 
2236 static int
2237 acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
2238 {
2239     char sleep_state[4];
2240     char buf[16];
2241     int error;
2242     UINT8 state, TypeA, TypeB;
2243 
2244     buf[0] = '\0';
2245     for (state = ACPI_STATE_S1; state < ACPI_S_STATES_MAX + 1; state++) {
2246 	if (ACPI_SUCCESS(AcpiGetSleepTypeData(state, &TypeA, &TypeB))) {
2247 	    sprintf(sleep_state, "S%d ", state);
2248 	    strcat(buf, sleep_state);
2249 	}
2250     }
2251     error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
2252     return (error);
2253 }
2254 
2255 static int
2256 acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
2257 {
2258     char sleep_state[10];
2259     int error;
2260     u_int new_state, old_state;
2261 
2262     old_state = *(u_int *)oidp->oid_arg1;
2263     if (old_state > ACPI_S_STATES_MAX + 1) {
2264 	strcpy(sleep_state, "unknown");
2265     } else {
2266 	bzero(sleep_state, sizeof(sleep_state));
2267 	strncpy(sleep_state, sleep_state_names[old_state],
2268 		sizeof(sleep_state_names[old_state]));
2269     }
2270     error = sysctl_handle_string(oidp, sleep_state, sizeof(sleep_state), req);
2271     if (error == 0 && req->newptr != NULL) {
2272 	new_state = ACPI_STATE_S0;
2273 	for (; new_state <= ACPI_S_STATES_MAX + 1; new_state++) {
2274 	    if (strncmp(sleep_state, sleep_state_names[new_state],
2275 			sizeof(sleep_state)) == 0)
2276 		break;
2277 	}
2278 	if (new_state <= ACPI_S_STATES_MAX + 1) {
2279 	    if (new_state != old_state)
2280 		*(u_int *)oidp->oid_arg1 = new_state;
2281 	} else {
2282 	    error = EINVAL;
2283 	}
2284     }
2285 
2286     return (error);
2287 }
2288 
2289 /* Inform devctl(4) when we receive a Notify. */
2290 void
2291 acpi_UserNotify(const char *subsystem, ACPI_HANDLE h, uint8_t notify)
2292 {
2293     char		notify_buf[16];
2294     ACPI_BUFFER		handle_buf;
2295     ACPI_STATUS		status;
2296 
2297     if (subsystem == NULL)
2298 	return;
2299 
2300     handle_buf.Pointer = NULL;
2301     handle_buf.Length = ACPI_ALLOCATE_BUFFER;
2302     status = AcpiNsHandleToPathname(h, &handle_buf);
2303     if (ACPI_FAILURE(status))
2304 	return;
2305     snprintf(notify_buf, sizeof(notify_buf), "notify=0x%02x", notify);
2306     devctl_notify("ACPI", subsystem, handle_buf.Pointer, notify_buf);
2307     AcpiOsFree(handle_buf.Pointer);
2308 }
2309 
2310 #ifdef ACPI_DEBUG
2311 /*
2312  * Support for parsing debug options from the kernel environment.
2313  *
2314  * Bits may be set in the AcpiDbgLayer and AcpiDbgLevel debug registers
2315  * by specifying the names of the bits in the debug.acpi.layer and
2316  * debug.acpi.level environment variables.  Bits may be unset by
2317  * prefixing the bit name with !.
2318  */
2319 struct debugtag
2320 {
2321     char	*name;
2322     UINT32	value;
2323 };
2324 
2325 static struct debugtag	dbg_layer[] = {
2326     {"ACPI_UTILITIES",		ACPI_UTILITIES},
2327     {"ACPI_HARDWARE",		ACPI_HARDWARE},
2328     {"ACPI_EVENTS",		ACPI_EVENTS},
2329     {"ACPI_TABLES",		ACPI_TABLES},
2330     {"ACPI_NAMESPACE",		ACPI_NAMESPACE},
2331     {"ACPI_PARSER",		ACPI_PARSER},
2332     {"ACPI_DISPATCHER",		ACPI_DISPATCHER},
2333     {"ACPI_EXECUTER",		ACPI_EXECUTER},
2334     {"ACPI_RESOURCES",		ACPI_RESOURCES},
2335     {"ACPI_CA_DEBUGGER",	ACPI_CA_DEBUGGER},
2336     {"ACPI_OS_SERVICES",	ACPI_OS_SERVICES},
2337     {"ACPI_CA_DISASSEMBLER",	ACPI_CA_DISASSEMBLER},
2338     {"ACPI_ALL_COMPONENTS",	ACPI_ALL_COMPONENTS},
2339 
2340     {"ACPI_AC_ADAPTER",		ACPI_AC_ADAPTER},
2341     {"ACPI_BATTERY",		ACPI_BATTERY},
2342     {"ACPI_BUS",		ACPI_BUS},
2343     {"ACPI_BUTTON",		ACPI_BUTTON},
2344     {"ACPI_EC", 		ACPI_EC},
2345     {"ACPI_FAN",		ACPI_FAN},
2346     {"ACPI_POWERRES",		ACPI_POWERRES},
2347     {"ACPI_PROCESSOR",		ACPI_PROCESSOR},
2348     {"ACPI_THERMAL",		ACPI_THERMAL},
2349     {"ACPI_TIMER",		ACPI_TIMER},
2350     {"ACPI_ALL_DRIVERS",	ACPI_ALL_DRIVERS},
2351     {NULL, 0}
2352 };
2353 
2354 static struct debugtag dbg_level[] = {
2355     {"ACPI_LV_ERROR",		ACPI_LV_ERROR},
2356     {"ACPI_LV_WARN",		ACPI_LV_WARN},
2357     {"ACPI_LV_INIT",		ACPI_LV_INIT},
2358     {"ACPI_LV_DEBUG_OBJECT",	ACPI_LV_DEBUG_OBJECT},
2359     {"ACPI_LV_INFO",		ACPI_LV_INFO},
2360     {"ACPI_LV_ALL_EXCEPTIONS",	ACPI_LV_ALL_EXCEPTIONS},
2361 
2362     /* Trace verbosity level 1 [Standard Trace Level] */
2363     {"ACPI_LV_INIT_NAMES",	ACPI_LV_INIT_NAMES},
2364     {"ACPI_LV_PARSE",		ACPI_LV_PARSE},
2365     {"ACPI_LV_LOAD",		ACPI_LV_LOAD},
2366     {"ACPI_LV_DISPATCH",	ACPI_LV_DISPATCH},
2367     {"ACPI_LV_EXEC",		ACPI_LV_EXEC},
2368     {"ACPI_LV_NAMES",		ACPI_LV_NAMES},
2369     {"ACPI_LV_OPREGION",	ACPI_LV_OPREGION},
2370     {"ACPI_LV_BFIELD",		ACPI_LV_BFIELD},
2371     {"ACPI_LV_TABLES",		ACPI_LV_TABLES},
2372     {"ACPI_LV_VALUES",		ACPI_LV_VALUES},
2373     {"ACPI_LV_OBJECTS",		ACPI_LV_OBJECTS},
2374     {"ACPI_LV_RESOURCES",	ACPI_LV_RESOURCES},
2375     {"ACPI_LV_USER_REQUESTS",	ACPI_LV_USER_REQUESTS},
2376     {"ACPI_LV_PACKAGE",		ACPI_LV_PACKAGE},
2377     {"ACPI_LV_VERBOSITY1",	ACPI_LV_VERBOSITY1},
2378 
2379     /* Trace verbosity level 2 [Function tracing and memory allocation] */
2380     {"ACPI_LV_ALLOCATIONS",	ACPI_LV_ALLOCATIONS},
2381     {"ACPI_LV_FUNCTIONS",	ACPI_LV_FUNCTIONS},
2382     {"ACPI_LV_OPTIMIZATIONS",	ACPI_LV_OPTIMIZATIONS},
2383     {"ACPI_LV_VERBOSITY2",	ACPI_LV_VERBOSITY2},
2384     {"ACPI_LV_ALL",		ACPI_LV_ALL},
2385 
2386     /* Trace verbosity level 3 [Threading, I/O, and Interrupts] */
2387     {"ACPI_LV_MUTEX",		ACPI_LV_MUTEX},
2388     {"ACPI_LV_THREADS",		ACPI_LV_THREADS},
2389     {"ACPI_LV_IO",		ACPI_LV_IO},
2390     {"ACPI_LV_INTERRUPTS",	ACPI_LV_INTERRUPTS},
2391     {"ACPI_LV_VERBOSITY3",	ACPI_LV_VERBOSITY3},
2392 
2393     /* Exceptionally verbose output -- also used in the global "DebugLevel"  */
2394     {"ACPI_LV_AML_DISASSEMBLE",	ACPI_LV_AML_DISASSEMBLE},
2395     {"ACPI_LV_VERBOSE_INFO",	ACPI_LV_VERBOSE_INFO},
2396     {"ACPI_LV_FULL_TABLES",	ACPI_LV_FULL_TABLES},
2397     {"ACPI_LV_EVENTS",		ACPI_LV_EVENTS},
2398     {"ACPI_LV_VERBOSE",		ACPI_LV_VERBOSE},
2399     {NULL, 0}
2400 };
2401 
2402 static void
2403 acpi_parse_debug(char *cp, struct debugtag *tag, UINT32 *flag)
2404 {
2405     char	*ep;
2406     int		i, l;
2407     int		set;
2408 
2409     while (*cp) {
2410 	if (isspace(*cp)) {
2411 	    cp++;
2412 	    continue;
2413 	}
2414 	ep = cp;
2415 	while (*ep && !isspace(*ep))
2416 	    ep++;
2417 	if (*cp == '!') {
2418 	    set = 0;
2419 	    cp++;
2420 	    if (cp == ep)
2421 		continue;
2422 	} else {
2423 	    set = 1;
2424 	}
2425 	l = ep - cp;
2426 	for (i = 0; tag[i].name != NULL; i++) {
2427 	    if (!strncmp(cp, tag[i].name, l)) {
2428 		if (set)
2429 		    *flag |= tag[i].value;
2430 		else
2431 		    *flag &= ~tag[i].value;
2432 	    }
2433 	}
2434 	cp = ep;
2435     }
2436 }
2437 
2438 static void
2439 acpi_set_debugging(void *junk)
2440 {
2441     char	*layer, *level;
2442 
2443     if (cold) {
2444 	AcpiDbgLayer = 0;
2445 	AcpiDbgLevel = 0;
2446     }
2447 
2448     layer = getenv("debug.acpi.layer");
2449     level = getenv("debug.acpi.level");
2450     if (layer == NULL && level == NULL)
2451 	return;
2452 
2453     printf("ACPI set debug");
2454     if (layer != NULL) {
2455 	if (strcmp("NONE", layer) != 0)
2456 	    printf(" layer '%s'", layer);
2457 	acpi_parse_debug(layer, &dbg_layer[0], &AcpiDbgLayer);
2458 	freeenv(layer);
2459     }
2460     if (level != NULL) {
2461 	if (strcmp("NONE", level) != 0)
2462 	    printf(" level '%s'", level);
2463 	acpi_parse_debug(level, &dbg_level[0], &AcpiDbgLevel);
2464 	freeenv(level);
2465     }
2466     printf("\n");
2467 }
2468 SYSINIT(acpi_debugging, SI_SUB_TUNABLES, SI_ORDER_ANY, acpi_set_debugging,
2469 	NULL);
2470 
2471 static int
2472 acpi_debug_sysctl(SYSCTL_HANDLER_ARGS)
2473 {
2474     int		 error, *dbg;
2475     struct	 debugtag *tag;
2476     struct	 sbuf sb;
2477 
2478     if (sbuf_new(&sb, NULL, 128, SBUF_AUTOEXTEND) == NULL)
2479 	return (ENOMEM);
2480     if (strcmp(oidp->oid_arg1, "debug.acpi.layer") == 0) {
2481 	tag = &dbg_layer[0];
2482 	dbg = &AcpiDbgLayer;
2483     } else {
2484 	tag = &dbg_level[0];
2485 	dbg = &AcpiDbgLevel;
2486     }
2487 
2488     /* Get old values if this is a get request. */
2489     if (*dbg == 0) {
2490 	sbuf_cpy(&sb, "NONE");
2491     } else if (req->newptr == NULL) {
2492 	for (; tag->name != NULL; tag++) {
2493 	    if ((*dbg & tag->value) == tag->value)
2494 		sbuf_printf(&sb, "%s ", tag->name);
2495 	}
2496     }
2497     sbuf_trim(&sb);
2498     sbuf_finish(&sb);
2499 
2500     /* Copy out the old values to the user. */
2501     error = SYSCTL_OUT(req, sbuf_data(&sb), sbuf_len(&sb));
2502     sbuf_delete(&sb);
2503 
2504     /* If the user is setting a string, parse it. */
2505     if (error == 0 && req->newptr != NULL) {
2506 	*dbg = 0;
2507 	setenv((char *)oidp->oid_arg1, (char *)req->newptr);
2508 	acpi_set_debugging(NULL);
2509     }
2510 
2511     return (error);
2512 }
2513 SYSCTL_PROC(_debug_acpi, OID_AUTO, layer, CTLFLAG_RW | CTLTYPE_STRING,
2514 	    "debug.acpi.layer", 0, acpi_debug_sysctl, "A", "");
2515 SYSCTL_PROC(_debug_acpi, OID_AUTO, level, CTLFLAG_RW | CTLTYPE_STRING,
2516 	    "debug.acpi.level", 0, acpi_debug_sysctl, "A", "");
2517 #endif
2518 
2519 static int
2520 acpi_pm_func(u_long cmd, void *arg, ...)
2521 {
2522 	int	state, acpi_state;
2523 	int	error;
2524 	struct	acpi_softc *sc;
2525 	va_list	ap;
2526 
2527 	error = 0;
2528 	switch (cmd) {
2529 	case POWER_CMD_SUSPEND:
2530 		sc = (struct acpi_softc *)arg;
2531 		if (sc == NULL) {
2532 			error = EINVAL;
2533 			goto out;
2534 		}
2535 
2536 		va_start(ap, arg);
2537 		state = va_arg(ap, int);
2538 		va_end(ap);
2539 
2540 		switch (state) {
2541 		case POWER_SLEEP_STATE_STANDBY:
2542 			acpi_state = sc->acpi_standby_sx;
2543 			break;
2544 		case POWER_SLEEP_STATE_SUSPEND:
2545 			acpi_state = sc->acpi_suspend_sx;
2546 			break;
2547 		case POWER_SLEEP_STATE_HIBERNATE:
2548 			acpi_state = ACPI_STATE_S4;
2549 			break;
2550 		default:
2551 			error = EINVAL;
2552 			goto out;
2553 		}
2554 
2555 		acpi_SetSleepState(sc, acpi_state);
2556 		break;
2557 	default:
2558 		error = EINVAL;
2559 		goto out;
2560 	}
2561 
2562 out:
2563 	return (error);
2564 }
2565 
2566 static void
2567 acpi_pm_register(void *arg)
2568 {
2569     if (!cold || resource_disabled("acpi", 0))
2570 	return;
2571 
2572     power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, NULL);
2573 }
2574 
2575 SYSINIT(power, SI_SUB_KLD, SI_ORDER_ANY, acpi_pm_register, 0);
2576