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