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