acpi.c revision 83169
1133094Ssimon/*-
2133094Ssimon * Copyright (c) 2000 Takanori Watanabe <takawata@jp.freebsd.org>
3133094Ssimon * Copyright (c) 2000 Mitsuru IWASAKI <iwasaki@jp.freebsd.org>
4133094Ssimon * Copyright (c) 2000, 2001 Michael Smith
5133094Ssimon * Copyright (c) 2000 BSDi
6133094Ssimon * All rights reserved.
7133094Ssimon *
8133094Ssimon * Redistribution and use in source and binary forms, with or without
9133094Ssimon * modification, are permitted provided that the following conditions
10133094Ssimon * are met:
11133094Ssimon * 1. Redistributions of source code must retain the above copyright
12133094Ssimon *    notice, this list of conditions and the following disclaimer.
13133094Ssimon * 2. Redistributions in binary form must reproduce the above copyright
14133094Ssimon *    notice, this list of conditions and the following disclaimer in the
15133094Ssimon *    documentation and/or other materials provided with the distribution.
16133094Ssimon *
17133094Ssimon * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18133094Ssimon * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19133094Ssimon * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20133094Ssimon * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21133094Ssimon * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22133094Ssimon * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23133094Ssimon * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24133094Ssimon * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25133094Ssimon * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26133094Ssimon * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27133094Ssimon * SUCH DAMAGE.
28133094Ssimon *
29133094Ssimon *	$FreeBSD: head/sys/dev/acpica/acpi.c 83169 2001-09-06 23:16:55Z jhb $
30133094Ssimon */
31133094Ssimon
32133094Ssimon#include "opt_acpi.h"
33133094Ssimon#include <sys/param.h>
34133094Ssimon#include <sys/kernel.h>
35133094Ssimon#include <sys/proc.h>
36133094Ssimon#include <sys/lock.h>
37133094Ssimon#include <sys/malloc.h>
38134652Sbrueffer#include <sys/mutex.h>
39133094Ssimon#include <sys/bus.h>
40133094Ssimon#include <sys/conf.h>
41133094Ssimon#include <sys/ioccom.h>
42133094Ssimon#include <sys/reboot.h>
43135126Sbrueffer#include <sys/sysctl.h>
44133094Ssimon#include <sys/ctype.h>
45133343Ssimon
46134264Ssimon#include <machine/clock.h>
47134401Ssimon#include <machine/resource.h>
48135126Sbrueffer
49133094Ssimon#include <isa/isavar.h>
50134316Sbrueffer
51133094Ssimon#include "acpi.h"
52139404Sbrueffer
53133343Ssimon#include <dev/acpica/acpivar.h>
54135126Sbrueffer#include <dev/acpica/acpiio.h>
55133094Ssimon
56135560SpeterMALLOC_DEFINE(M_ACPIDEV, "acpidev", "ACPI devices");
57133094Ssimon
58133094Ssimon/*
59134826Ssimon * Hooks for the ACPI CA debugging infrastructure
60135126Sbrueffer */
61133094Ssimon#define _COMPONENT	ACPI_BUS
62135126SbruefferMODULE_NAME("ACPI")
63135126Sbrueffer
64135336Sbrueffer/*
65134786Sbrueffer * Character device
66135104Sbrueffer */
67134786Sbrueffer
68134772Ssimonstatic d_open_t		acpiopen;
69133094Ssimonstatic d_close_t	acpiclose;
70135143Sbruefferstatic d_ioctl_t	acpiioctl;
71133778Ssimon
72135120Ssimon#define CDEV_MAJOR 152
73137927Sbruefferstatic struct cdevsw acpi_cdevsw = {
74133343Ssimon    acpiopen,
75134772Ssimon    acpiclose,
76135126Sbrueffer    noread,
77133343Ssimon    nowrite,
78134218Sbrueffer    acpiioctl,
79135126Sbrueffer    nopoll,
80134273Sbrueffer    nommap,
81135143Sbrueffer    nostrategy,
82135126Sbrueffer    "acpi",
83135126Sbrueffer    CDEV_MAJOR,
84133094Ssimon    nodump,
85134047Ssimon    nopsize,
86133457Ssimon    0
87138967Sbrueffer};
88135143Sbrueffer
89135081Sbruefferstatic const char* sleep_state_names[] = {
90133343Ssimon    "S0", "S1", "S2", "S3", "S4", "S5", "S4B" };
91133343Ssimon
92141288Sbrueffer/* this has to be static, as the softc is gone when we need it */
93135143Sbruefferstatic int acpi_off_state = ACPI_STATE_S5;
94134316Sbrueffer
95135120Ssimonstruct mtx	acpi_mutex;
96135126Sbrueffer
97135126Sbruefferstatic int	acpi_modevent(struct module *mod, int event, void *junk);
98135126Sbruefferstatic void	acpi_identify(driver_t *driver, device_t parent);
99138872Ssimonstatic int	acpi_probe(device_t dev);
100134256Sbruefferstatic int	acpi_attach(device_t dev);
101134786Sbruefferstatic device_t	acpi_add_child(device_t bus, int order, const char *name, int unit);
102134757Sbruefferstatic int	acpi_print_resources(struct resource_list *rl, const char *name, int type,
103134414Ssimon				     const char *format);
104138846Ssimonstatic int	acpi_print_child(device_t bus, device_t child);
105134414Ssimonstatic int	acpi_read_ivar(device_t dev, device_t child, int index, uintptr_t *result);
106134414Ssimonstatic int	acpi_write_ivar(device_t dev, device_t child, int index, uintptr_t value);
107135082Ssimonstatic int	acpi_set_resource(device_t dev, device_t child, int type, int rid, u_long start,
108134414Ssimon				  u_long count);
109134414Ssimonstatic int	acpi_get_resource(device_t dev, device_t child, int type, int rid, u_long *startp,
110134414Ssimon				  u_long *countp);
111135533Ssimonstatic struct resource *acpi_alloc_resource(device_t bus, device_t child, int type, int *rid,
112135082Ssimon					    u_long start, u_long end, u_long count, u_int flags);
113138133Ssimonstatic int	acpi_release_resource(device_t bus, device_t child, int type, int rid, struct resource *r);
114138850Ssimonstatic int	acpi_isa_pnp_probe(device_t bus, device_t child, struct isa_pnp_id *ids);
115138850Ssimon
116142347Sbruefferstatic void	acpi_probe_children(device_t bus);
117134414Ssimonstatic ACPI_STATUS acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status);
118134673Sbrueffer
119133343Ssimonstatic void	acpi_shutdown_pre_sync(void *arg, int howto);
120134701Sbruefferstatic void	acpi_shutdown_final(void *arg, int howto);
121134701Sbrueffer
122133778Ssimonstatic void	acpi_enable_fixed_events(struct acpi_softc *sc);
123134652Sbrueffer
124134652Sbruefferstatic void	acpi_system_eventhandler_sleep(void *arg, int state);
125135126Sbruefferstatic void	acpi_system_eventhandler_wakeup(void *arg, int state);
126134730Sbruefferstatic int	acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS);
127135120Ssimon
128135103Ssimonstatic device_method_t acpi_methods[] = {
129134864Sbrueffer    /* Device interface */
130133094Ssimon    DEVMETHOD(device_identify,		acpi_identify),
131134730Sbrueffer    DEVMETHOD(device_probe,		acpi_probe),
132134830Ssimon    DEVMETHOD(device_attach,		acpi_attach),
133135829Ssimon    DEVMETHOD(device_shutdown,		bus_generic_shutdown),
134138985Sbrueffer    DEVMETHOD(device_suspend,		bus_generic_suspend),
135134047Ssimon    DEVMETHOD(device_resume,		bus_generic_resume),
136134730Sbrueffer
137135829Ssimon    /* Bus interface */
138134047Ssimon    DEVMETHOD(bus_add_child,		acpi_add_child),
139135114Ssimon    DEVMETHOD(bus_print_child,		acpi_print_child),
140134876Sbrueffer    DEVMETHOD(bus_read_ivar,		acpi_read_ivar),
141135057Ssimon    DEVMETHOD(bus_write_ivar,		acpi_write_ivar),
142138872Ssimon    DEVMETHOD(bus_set_resource,		acpi_set_resource),
143133778Ssimon    DEVMETHOD(bus_get_resource,		acpi_get_resource),
144135126Sbrueffer    DEVMETHOD(bus_alloc_resource,	acpi_alloc_resource),
145134730Sbrueffer    DEVMETHOD(bus_release_resource,	acpi_release_resource),
146133094Ssimon    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
158static driver_t acpi_driver = {
159    "acpi",
160    acpi_methods,
161    sizeof(struct acpi_softc),
162};
163
164devclass_t acpi_devclass;
165DRIVER_MODULE(acpi, nexus, acpi_driver, acpi_devclass, acpi_modevent, 0);
166MODULE_VERSION(acpi, 100);
167
168SYSCTL_INT(_debug, OID_AUTO, acpi_debug_layer, CTLFLAG_RW, &AcpiDbgLayer, 0, "");
169SYSCTL_INT(_debug, OID_AUTO, acpi_debug_level, CTLFLAG_RW, &AcpiDbgLevel, 0, "");
170static int acpi_ca_version = ACPI_CA_VERSION;
171SYSCTL_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 */
178static int
179acpi_modevent(struct module *mod, int event, void *junk)
180{
181    switch(event) {
182    case MOD_LOAD:
183	if (!cold)
184	    return(EPERM);
185	break;
186    case MOD_UNLOAD:
187	return(EBUSY);
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 ENABLE_DEBUGGER
203    char			*debugpoint = getenv("debug.acpi.debugger");
204#endif
205
206    FUNCTION_TRACE(__func__);
207
208    if(!cold){
209	    printf("Don't load this driver from userland!!\n");
210	    return ;
211    }
212
213    /*
214     * Make sure we're not being doubly invoked.
215     */
216    if (device_find_child(parent, "acpi", 0) != NULL)
217	return_VOID;
218
219    /* initialise the ACPI mutex */
220    mtx_init(&acpi_mutex, "ACPI global lock", MTX_DEF);
221
222    /*
223     * Start up the ACPI CA subsystem.
224     */
225#ifdef ENABLE_DEBUGGER
226    if (debugpoint && !strcmp(debugpoint, "init"))
227	acpi_EnterDebugger();
228#endif
229    if ((error = AcpiInitializeSubsystem()) != AE_OK) {
230	printf("ACPI: initialisation failed: %s\n", AcpiFormatException(error));
231	return_VOID;
232    }
233#ifdef ENABLE_DEBUGGER
234    if (debugpoint && !strcmp(debugpoint, "tables"))
235	acpi_EnterDebugger();
236#endif
237    if ((error = AcpiLoadTables()) != AE_OK) {
238	printf("ACPI: table load failed: %s\n", AcpiFormatException(error));
239	return_VOID;
240    }
241
242    /*
243     * Attach the actual ACPI device.
244     */
245    if ((child = BUS_ADD_CHILD(parent, 0, "acpi", 0)) == NULL) {
246	    device_printf(parent, "ACPI: could not attach\n");
247	    return_VOID;
248    }
249}
250
251/*
252 * Fetch some descriptive data from ACPI to put in our attach message
253 */
254static int
255acpi_probe(device_t dev)
256{
257    ACPI_TABLE_HEADER	th;
258    char		buf[20];
259    ACPI_STATUS		status;
260    int			error;
261
262    FUNCTION_TRACE(__func__);
263    ACPI_LOCK;
264
265    if ((status = AcpiGetTableHeader(ACPI_TABLE_XSDT, 1, &th)) != AE_OK) {
266	device_printf(dev, "couldn't get XSDT header: %s\n", AcpiFormatException(status));
267	error = ENXIO;
268    } else {
269	sprintf(buf, "%.6s %.8s", th.OemId, th.OemTableId);
270	device_set_desc_copy(dev, buf);
271	error = 0;
272    }
273    ACPI_UNLOCK;
274    return_VALUE(error);
275}
276
277static int
278acpi_attach(device_t dev)
279{
280    struct acpi_softc	*sc;
281    ACPI_STATUS		status;
282    int			error;
283#ifdef ENABLE_DEBUGGER
284    char		*debugpoint = getenv("debug.acpi.debugger");
285#endif
286
287    FUNCTION_TRACE(__func__);
288    ACPI_LOCK;
289    sc = device_get_softc(dev);
290    bzero(sc, sizeof(*sc));
291    sc->acpi_dev = dev;
292
293    acpi_install_wakeup_handler(sc);
294
295#ifdef ENABLE_DEBUGGER
296    if (debugpoint && !strcmp(debugpoint, "spaces"))
297	acpi_EnterDebugger();
298#endif
299
300    /*
301     * Install the default address space handlers.
302     */
303    error = ENXIO;
304    if ((status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
305						ACPI_ADR_SPACE_SYSTEM_MEMORY,
306						ACPI_DEFAULT_HANDLER,
307						NULL, NULL)) != AE_OK) {
308	device_printf(dev, "could not initialise SystemMemory handler: %s\n", AcpiFormatException(status));
309	goto out;
310    }
311    if ((status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
312						ACPI_ADR_SPACE_SYSTEM_IO,
313						ACPI_DEFAULT_HANDLER,
314						NULL, NULL)) != AE_OK) {
315	device_printf(dev, "could not initialise SystemIO handler: %s\n", AcpiFormatException(status));
316	goto out;
317    }
318    if ((status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT,
319						ACPI_ADR_SPACE_PCI_CONFIG,
320						ACPI_DEFAULT_HANDLER,
321						NULL, NULL)) != AE_OK) {
322	device_printf(dev, "could not initialise PciConfig handler: %s\n", AcpiFormatException(status));
323	goto out;
324    }
325
326    /*
327     * Bring ACPI fully online.
328     *
329     * Note that we request that device _STA and _INI methods not be run (ACPI_NO_DEVICE_INIT)
330     * and the final object initialisation pass be skipped (ACPI_NO_OBJECT_INIT).
331     *
332     * XXX We need to arrange for the object init pass after we have attached all our
333     *     child devices.
334     */
335#ifdef ENABLE_DEBUGGER
336    if (debugpoint && !strcmp(debugpoint, "enable"))
337	acpi_EnterDebugger();
338#endif
339    if ((status = AcpiEnableSubsystem(ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT)) != AE_OK) {
340	device_printf(dev, "could not enable ACPI: %s\n", AcpiFormatException(status));
341	goto out;
342    }
343
344    /*
345     * Setup our sysctl tree.
346     *
347     * XXX: This doesn't check to make sure that none of these fail.
348     */
349    sysctl_ctx_init(&sc->acpi_sysctl_ctx);
350    sc->acpi_sysctl_tree = SYSCTL_ADD_NODE(&sc->acpi_sysctl_ctx,
351			       SYSCTL_STATIC_CHILDREN(_hw), OID_AUTO,
352			       device_get_name(dev), CTLFLAG_RD, 0, "");
353    SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
354	OID_AUTO, "power_button_state", CTLTYPE_STRING | CTLFLAG_RW,
355	&sc->acpi_power_button_sx, 0, acpi_sleep_state_sysctl, "A", "");
356    SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
357	OID_AUTO, "sleep_button_state", CTLTYPE_STRING | CTLFLAG_RW,
358	&sc->acpi_sleep_button_sx, 0, acpi_sleep_state_sysctl, "A", "");
359    SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
360	OID_AUTO, "lid_switch_state", CTLTYPE_STRING | CTLFLAG_RW,
361	&sc->acpi_lid_switch_sx, 0, acpi_sleep_state_sysctl, "A", "");
362
363    /*
364     * Dispatch the default sleep state to devices.
365     * TBD: should be configured from userland policy manager.
366     */
367    sc->acpi_power_button_sx = ACPI_POWER_BUTTON_DEFAULT_SX;
368    sc->acpi_sleep_button_sx = ACPI_SLEEP_BUTTON_DEFAULT_SX;
369    sc->acpi_lid_switch_sx = ACPI_LID_SWITCH_DEFAULT_SX;
370
371    acpi_enable_fixed_events(sc);
372
373    /*
374     * Scan the namespace and attach/initialise children.
375     */
376#ifdef ENABLE_DEBUGGER
377    if (debugpoint && !strcmp(debugpoint, "probe"))
378	acpi_EnterDebugger();
379#endif
380    if (!acpi_disabled("bus"))
381	acpi_probe_children(dev);
382
383    /*
384     * Register our shutdown handlers
385     */
386    EVENTHANDLER_REGISTER(shutdown_pre_sync, acpi_shutdown_pre_sync, sc, SHUTDOWN_PRI_LAST);
387    EVENTHANDLER_REGISTER(shutdown_final, acpi_shutdown_final, sc, SHUTDOWN_PRI_LAST);
388
389    /*
390     * Register our acpi event handlers.
391     * XXX should be configurable eg. via userland policy manager.
392     */
393    EVENTHANDLER_REGISTER(acpi_sleep_event, acpi_system_eventhandler_sleep, sc, ACPI_EVENT_PRI_LAST);
394    EVENTHANDLER_REGISTER(acpi_wakeup_event, acpi_system_eventhandler_wakeup, sc, ACPI_EVENT_PRI_LAST);
395
396    /*
397     * Flag our initial states.
398     */
399    sc->acpi_enabled = 1;
400    sc->acpi_sstate = ACPI_STATE_S0;
401
402    /*
403     * Create the control device
404     */
405    sc->acpi_dev_t = make_dev(&acpi_cdevsw, 0, 0, 5, 0660, "acpi");
406    sc->acpi_dev_t->si_drv1 = sc;
407
408#ifdef ENABLE_DEBUGGER
409    if (debugpoint && !strcmp(debugpoint, "running"))
410	acpi_EnterDebugger();
411#endif
412    error = 0;
413
414 out:
415    ACPI_UNLOCK;
416    return_VALUE(error);
417}
418
419/*
420 * Handle a new device being added
421 */
422static device_t
423acpi_add_child(device_t bus, int order, const char *name, int unit)
424{
425    struct acpi_device	*ad;
426    device_t		child;
427
428    if ((ad = malloc(sizeof(*ad), M_ACPIDEV, M_NOWAIT)) == NULL)
429	return(NULL);
430    bzero(ad, sizeof(*ad));
431
432    resource_list_init(&ad->ad_rl);
433
434    child = device_add_child_ordered(bus, order, name, unit);
435    if (child != NULL)
436	device_set_ivars(child, ad);
437    return(child);
438}
439
440/*
441 * Print child device resource usage
442 */
443static int
444acpi_print_resources(struct resource_list *rl, const char *name, int type, const char *format)
445{
446    struct resource_list_entry	*rle;
447    int				printed, retval;
448
449    printed = 0;
450    retval = 0;
451
452    if (!SLIST_FIRST(rl))
453	return(0);
454
455    /* Yes, this is kinda cheating */
456    SLIST_FOREACH(rle, rl, link) {
457	if (rle->type == type) {
458	    if (printed == 0)
459		retval += printf(" %s ", name);
460	    else if (printed > 0)
461		retval += printf(",");
462	    printed++;
463	    retval += printf(format, rle->start);
464	    if (rle->count > 1) {
465		retval += printf("-");
466		retval += printf(format, rle->start +
467				 rle->count - 1);
468	    }
469	}
470    }
471    return(retval);
472}
473
474static int
475acpi_print_child(device_t bus, device_t child)
476{
477    struct acpi_device		*adev = device_get_ivars(child);
478    struct resource_list	*rl = &adev->ad_rl;
479    int retval = 0;
480
481    retval += bus_print_child_header(bus, child);
482    retval += acpi_print_resources(rl, "port",  SYS_RES_IOPORT, "%#lx");
483    retval += acpi_print_resources(rl, "iomem", SYS_RES_MEMORY, "%#lx");
484    retval += acpi_print_resources(rl, "irq",   SYS_RES_IRQ,    "%ld");
485    retval += bus_print_child_footer(bus, child);
486
487    return(retval);
488}
489
490
491/*
492 * Handle per-device ivars
493 */
494static int
495acpi_read_ivar(device_t dev, device_t child, int index, uintptr_t *result)
496{
497    struct acpi_device	*ad;
498
499    if ((ad = device_get_ivars(child)) == NULL) {
500	printf("device has no ivars\n");
501	return(ENOENT);
502    }
503
504    switch(index) {
505	/* ACPI ivars */
506    case ACPI_IVAR_HANDLE:
507	*(ACPI_HANDLE *)result = ad->ad_handle;
508	break;
509    case ACPI_IVAR_MAGIC:
510	*(int *)result = ad->ad_magic;
511	break;
512    case ACPI_IVAR_PRIVATE:
513	*(void **)result = ad->ad_private;
514	break;
515
516    default:
517	panic("bad ivar read request (%d)\n", index);
518	return(ENOENT);
519    }
520    return(0);
521}
522
523static int
524acpi_write_ivar(device_t dev, device_t child, int index, uintptr_t value)
525{
526    struct acpi_device	*ad;
527
528    if ((ad = device_get_ivars(child)) == NULL) {
529	printf("device has no ivars\n");
530	return(ENOENT);
531    }
532
533    switch(index) {
534	/* ACPI ivars */
535    case ACPI_IVAR_HANDLE:
536	ad->ad_handle = (ACPI_HANDLE)value;
537	break;
538    case ACPI_IVAR_MAGIC:
539	ad->ad_magic = (int )value;
540	break;
541    case ACPI_IVAR_PRIVATE:
542	ad->ad_private = (void *)value;
543	break;
544
545    default:
546	panic("bad ivar write request (%d)\n", index);
547	return(ENOENT);
548    }
549    return(0);
550}
551
552/*
553 * Handle child resource allocation/removal
554 */
555static int
556acpi_set_resource(device_t dev, device_t child, int type, int rid, u_long start, u_long count)
557{
558    struct acpi_device		*ad = device_get_ivars(child);
559    struct resource_list	*rl = &ad->ad_rl;
560
561    resource_list_add(rl, type, rid, start, start + count -1, count);
562
563    return(0);
564}
565
566static int
567acpi_get_resource(device_t dev, device_t child, int type, int rid, u_long *startp, u_long *countp)
568{
569    struct acpi_device		*ad = device_get_ivars(child);
570    struct resource_list	*rl = &ad->ad_rl;
571    struct resource_list_entry	*rle;
572
573    rle = resource_list_find(rl, type, rid);
574    if (!rle)
575	return(ENOENT);
576
577    if (startp)
578	*startp = rle->start;
579    if (countp)
580	*countp = rle->count;
581
582    return(0);
583}
584
585static struct resource *
586acpi_alloc_resource(device_t bus, device_t child, int type, int *rid,
587		    u_long start, u_long end, u_long count, u_int flags)
588{
589    struct acpi_device *ad = device_get_ivars(child);
590    struct resource_list *rl = &ad->ad_rl;
591
592    return(resource_list_alloc(rl, bus, child, type, rid, start, end, count, flags));
593}
594
595static int
596acpi_release_resource(device_t bus, device_t child, int type, int rid, struct resource *r)
597{
598    struct acpi_device *ad = device_get_ivars(child);
599    struct resource_list *rl = &ad->ad_rl;
600
601    return(resource_list_release(rl, bus, child, type, rid, r));
602}
603
604/*
605 * Handle ISA-like devices probing for a PnP ID to match.
606 */
607#define PNP_EISAID(s)				\
608	((((s[0] - '@') & 0x1f) << 2)		\
609	 | (((s[1] - '@') & 0x18) >> 3)		\
610	 | (((s[1] - '@') & 0x07) << 13)	\
611	 | (((s[2] - '@') & 0x1f) << 8)		\
612	 | (PNP_HEXTONUM(s[4]) << 16)		\
613	 | (PNP_HEXTONUM(s[3]) << 20)		\
614	 | (PNP_HEXTONUM(s[6]) << 24)		\
615	 | (PNP_HEXTONUM(s[5]) << 28))
616
617int
618acpi_isa_pnp_probe(device_t bus, device_t child, struct isa_pnp_id *ids)
619{
620    ACPI_HANDLE		h;
621    ACPI_DEVICE_INFO	devinfo;
622    ACPI_STATUS		error;
623    u_int32_t		pnpid;
624    int			result;
625
626    FUNCTION_TRACE(__func__);
627
628    /*
629     * ISA-style drivers attached to ACPI may persist and
630     * probe manually if we return ENOENT.  We never want
631     * that to happen, so don't ever return it.
632     */
633    result = ENXIO;
634    ACPI_LOCK;
635
636    /* fetch and validate the HID */
637    if ((h = acpi_get_handle(child)) == NULL)
638	goto out;
639    if ((error = AcpiGetObjectInfo(h, &devinfo)) != AE_OK)
640	goto out;
641    if (!(devinfo.Valid & ACPI_VALID_HID))
642	goto out;
643
644    /* scan the supplied IDs for a match */
645    pnpid = PNP_EISAID(devinfo.HardwareId);
646    while (ids && ids->ip_id) {
647	if (pnpid == ids->ip_id) {
648	    result = 0;
649	    goto out;
650	}
651	ids++;
652    }
653 out:
654    ACPI_UNLOCK;
655    return_VALUE(result);
656}
657
658/*
659 * Scan relevant portions of the ACPI namespace and attach child devices.
660 *
661 * Note that we only expect to find devices in the \_PR_, \_TZ_, \_SI_ and \_SB_ scopes,
662 * and \_PR_ and \_TZ_ become obsolete in the ACPI 2.0 spec.
663 */
664static void
665acpi_probe_children(device_t bus)
666{
667    ACPI_HANDLE		parent;
668    static char		*scopes[] = {"\\_PR_", "\\_TZ_", "\\_SI", "\\_SB_", NULL};
669    int			i;
670
671    FUNCTION_TRACE(__func__);
672    ACPI_ASSERTLOCK;
673
674    /*
675     * Create any static children by calling device identify methods.
676     */
677    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "device identify routines\n"));
678    bus_generic_probe(bus);
679
680    /*
681     * Scan the namespace and insert placeholders for all the devices that
682     * we find.
683     *
684     * Note that we use AcpiWalkNamespace rather than AcpiGetDevices because
685     * we want to create nodes for all devices, not just those that are currently
686     * present. (This assumes that we don't want to create/remove devices as they
687     * appear, which might be smarter.)
688     */
689    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "namespace scan\n"));
690    for (i = 0; scopes[i] != NULL; i++)
691	if ((AcpiGetHandle(ACPI_ROOT_OBJECT, scopes[i], &parent)) == AE_OK)
692	    AcpiWalkNamespace(ACPI_TYPE_ANY, parent, 100, acpi_probe_child, bus, NULL);
693
694    /*
695     * Scan all of the child devices we have created and let them probe/attach.
696     */
697    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "first bus_generic_attach\n"));
698    bus_generic_attach(bus);
699
700    /*
701     * Some of these children may have attached others as part of their attach
702     * process (eg. the root PCI bus driver), so rescan.
703     */
704    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "second bus_generic_attach\n"));
705    bus_generic_attach(bus);
706
707    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "done attaching children\n"));
708    return_VOID;
709}
710
711/*
712 * Evaluate a child device and determine whether we might attach a device to
713 * it.
714 */
715static ACPI_STATUS
716acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
717{
718    ACPI_OBJECT_TYPE	type;
719    device_t		child, bus = (device_t)context;
720
721    FUNCTION_TRACE(__func__);
722
723    /*
724     * Skip this device if we think we'll have trouble with it.
725     */
726    if (acpi_avoid(handle))
727	return_ACPI_STATUS(AE_OK);
728
729    if (AcpiGetType(handle, &type) == AE_OK) {
730	switch(type) {
731	case ACPI_TYPE_DEVICE:
732	case ACPI_TYPE_PROCESSOR:
733	case ACPI_TYPE_THERMAL:
734	case ACPI_TYPE_POWER:
735	    if (acpi_disabled("children"))
736		break;
737	    /*
738	     * Create a placeholder device for this node.  Sort the placeholder
739	     * so that the probe/attach passes will run breadth-first.
740	     */
741	    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "scanning '%s'\n", acpi_name(handle)));
742	    child = BUS_ADD_CHILD(bus, level * 10, NULL, -1);
743	    if (child == NULL)
744		break;
745	    acpi_set_handle(child, handle);
746
747	    /*
748	     * Get the device's resource settings and attach them.
749	     * Note that if the device has _PRS but no _CRS, we need
750	     * to decide when it's appropriate to try to configure the
751	     * device.  Ignore the return value here; it's OK for the
752	     * device not to have any resources.
753	     */
754	    acpi_parse_resources(child, handle, &acpi_res_parse_set);
755
756	    /* if we're debugging, probe/attach now rather than later */
757	    DEBUG_EXEC(device_probe_and_attach(child));
758	    break;
759	}
760    }
761    return_ACPI_STATUS(AE_OK);
762}
763
764static void
765acpi_shutdown_pre_sync(void *arg, int howto)
766{
767
768    ACPI_ASSERTLOCK;
769
770    /*
771     * Disable all ACPI events before soft off, otherwise the system
772     * will be turned on again on some laptops.
773     *
774     * XXX this should probably be restricted to masking some events just
775     *     before powering down, since we may still need ACPI during the
776     *     shutdown process.
777     */
778    acpi_Disable((struct acpi_softc *)arg);
779}
780
781static void
782acpi_shutdown_final(void *arg, int howto)
783{
784    ACPI_STATUS	status;
785
786    ACPI_ASSERTLOCK;
787
788    if (howto & RB_POWEROFF) {
789	printf("Power system off using ACPI...\n");
790	if ((status = AcpiEnterSleepState(acpi_off_state)) != AE_OK) {
791	    printf("ACPI power-off failed - %s\n", AcpiFormatException(status));
792	} else {
793	    DELAY(1000000);
794	    printf("ACPI power-off failed - timeout\n");
795	}
796    }
797}
798
799static void
800acpi_enable_fixed_events(struct acpi_softc *sc)
801{
802    static int	first_time = 1;
803#define MSGFORMAT "%s button is handled as a fixed feature programming model.\n"
804
805    ACPI_ASSERTLOCK;
806
807    /* Enable and clear fixed events and install handlers. */
808    if ((AcpiGbl_FADT != NULL) && (AcpiGbl_FADT->PwrButton == 0)) {
809	AcpiEnableEvent(ACPI_EVENT_POWER_BUTTON, ACPI_EVENT_FIXED);
810	AcpiClearEvent(ACPI_EVENT_POWER_BUTTON, ACPI_EVENT_FIXED);
811	AcpiInstallFixedEventHandler(ACPI_EVENT_POWER_BUTTON,
812				     acpi_eventhandler_power_button_for_sleep, sc);
813	if (first_time) {
814	    device_printf(sc->acpi_dev, MSGFORMAT, "power");
815	}
816    }
817    if ((AcpiGbl_FADT != NULL) && (AcpiGbl_FADT->SleepButton == 0)) {
818	AcpiEnableEvent(ACPI_EVENT_SLEEP_BUTTON, ACPI_EVENT_FIXED);
819	AcpiClearEvent(ACPI_EVENT_SLEEP_BUTTON, ACPI_EVENT_FIXED);
820	AcpiInstallFixedEventHandler(ACPI_EVENT_SLEEP_BUTTON,
821				     acpi_eventhandler_sleep_button_for_sleep, sc);
822	if (first_time) {
823	    device_printf(sc->acpi_dev, MSGFORMAT, "sleep");
824	}
825    }
826
827    first_time = 0;
828}
829
830/*
831 * Returns true if the device is actually present and should
832 * be attached to.  This requires the present, enabled, UI-visible
833 * and diagnostics-passed bits to be set.
834 */
835BOOLEAN
836acpi_DeviceIsPresent(device_t dev)
837{
838    ACPI_HANDLE		h;
839    ACPI_DEVICE_INFO	devinfo;
840    ACPI_STATUS		error;
841
842    ACPI_ASSERTLOCK;
843
844    if ((h = acpi_get_handle(dev)) == NULL)
845	return(FALSE);
846    if ((error = AcpiGetObjectInfo(h, &devinfo)) != AE_OK)
847	return(FALSE);
848    /* XXX 0xf is probably not appropriate */
849    if ((devinfo.Valid & ACPI_VALID_HID) && (devinfo.CurrentStatus & 0xf))
850	return(TRUE);
851    return(FALSE);
852}
853
854/*
855 * Match a HID string against a device
856 */
857BOOLEAN
858acpi_MatchHid(device_t dev, char *hid)
859{
860    ACPI_HANDLE		h;
861    ACPI_DEVICE_INFO	devinfo;
862    ACPI_STATUS		error;
863
864    ACPI_ASSERTLOCK;
865
866    if (hid == NULL)
867	return(FALSE);
868    if ((h = acpi_get_handle(dev)) == NULL)
869	return(FALSE);
870    if ((error = AcpiGetObjectInfo(h, &devinfo)) != AE_OK)
871	return(FALSE);
872    if ((devinfo.Valid & ACPI_VALID_HID) && !strcmp(hid, devinfo.HardwareId))
873	return(TRUE);
874    return(FALSE);
875}
876
877/*
878 * Return the handle of a named object within our scope, ie. that of (parent)
879 * or one if its parents.
880 */
881ACPI_STATUS
882acpi_GetHandleInScope(ACPI_HANDLE parent, char *path, ACPI_HANDLE *result)
883{
884    ACPI_HANDLE		r;
885    ACPI_STATUS		status;
886
887    ACPI_ASSERTLOCK;
888
889    /* walk back up the tree to the root */
890    for (;;) {
891	status = AcpiGetHandle(parent, path, &r);
892	if (status == AE_OK) {
893	    *result = r;
894	    return(AE_OK);
895	}
896	if (status != AE_NOT_FOUND)
897	    return(AE_OK);
898	if (AcpiGetParent(parent, &r) != AE_OK)
899	    return(AE_NOT_FOUND);
900	parent = r;
901    }
902}
903
904/*
905 * Allocate a buffer with a preset data size.
906 */
907ACPI_BUFFER *
908acpi_AllocBuffer(int size)
909{
910    ACPI_BUFFER	*buf;
911
912    if ((buf = malloc(size + sizeof(*buf), M_ACPIDEV, M_NOWAIT)) == NULL)
913	return(NULL);
914    buf->Length = size;
915    buf->Pointer = (void *)(buf + 1);
916    return(buf);
917}
918
919/*
920 * Perform the tedious double-get procedure required for fetching something into
921 * an ACPI_BUFFER that has not been initialised.
922 */
923ACPI_STATUS
924acpi_GetIntoBuffer(ACPI_HANDLE handle, ACPI_STATUS (*func)(ACPI_HANDLE, ACPI_BUFFER *), ACPI_BUFFER *buf)
925{
926    ACPI_STATUS	status;
927
928    ACPI_ASSERTLOCK;
929
930    buf->Length = 0;
931    buf->Pointer = NULL;
932
933    if ((status = func(handle, buf)) != AE_BUFFER_OVERFLOW)
934	return(status);
935    if ((buf->Pointer = AcpiOsCallocate(buf->Length)) == NULL)
936	return(AE_NO_MEMORY);
937    return(func(handle, buf));
938}
939
940/*
941 * Perform the tedious double-get procedure required for fetching a table into
942 * an ACPI_BUFFER that has not been initialised.
943 */
944ACPI_STATUS
945acpi_GetTableIntoBuffer(ACPI_TABLE_TYPE table, UINT32 instance, ACPI_BUFFER *buf)
946{
947    ACPI_STATUS	status;
948
949    ACPI_ASSERTLOCK;
950
951    buf->Length = 0;
952    buf->Pointer = NULL;
953
954    if ((status = AcpiGetTable(table, instance, buf)) != AE_BUFFER_OVERFLOW)
955	return(status);
956    if ((buf->Pointer = AcpiOsCallocate(buf->Length)) == NULL)
957	return(AE_NO_MEMORY);
958    return(AcpiGetTable(table, instance, buf));
959}
960
961/*
962 * Perform the tedious double-evaluate procedure for evaluating something into
963 * an ACPI_BUFFER that has not been initialised.  Note that this evaluates
964 * twice, so avoid applying this to things that may have side-effects.
965 *
966 * This is like AcpiEvaluateObject with automatic buffer allocation.
967 */
968ACPI_STATUS
969acpi_EvaluateIntoBuffer(ACPI_HANDLE object, ACPI_STRING pathname, ACPI_OBJECT_LIST *params,
970			ACPI_BUFFER *buf)
971{
972    ACPI_STATUS	status;
973
974    ACPI_ASSERTLOCK;
975
976    buf->Length = 0;
977    buf->Pointer = NULL;
978
979    if ((status = AcpiEvaluateObject(object, pathname, params, buf)) != AE_BUFFER_OVERFLOW)
980	return(status);
981    if ((buf->Pointer = AcpiOsCallocate(buf->Length)) == NULL)
982	return(AE_NO_MEMORY);
983    return(AcpiEvaluateObject(object, pathname, params, buf));
984}
985
986/*
987 * Evaluate a path that should return an integer.
988 */
989ACPI_STATUS
990acpi_EvaluateInteger(ACPI_HANDLE handle, char *path, int *number)
991{
992    ACPI_STATUS	error;
993    ACPI_BUFFER	buf;
994    ACPI_OBJECT	param, *p;
995    int		i;
996
997    ACPI_ASSERTLOCK;
998
999    if (handle == NULL)
1000	handle = ACPI_ROOT_OBJECT;
1001
1002    /*
1003     * Assume that what we've been pointed at is an Integer object, or
1004     * a method that will return an Integer.
1005     */
1006    buf.Pointer = &param;
1007    buf.Length = sizeof(param);
1008    if ((error = AcpiEvaluateObject(handle, path, NULL, &buf)) == AE_OK) {
1009	if (param.Type == ACPI_TYPE_INTEGER) {
1010	    *number = param.Integer.Value;
1011	} else {
1012	    error = AE_TYPE;
1013	}
1014    }
1015
1016    /*
1017     * In some applications, a method that's expected to return an Integer
1018     * may instead return a Buffer (probably to simplify some internal
1019     * arithmetic).  We'll try to fetch whatever it is, and if it's a Buffer,
1020     * convert it into an Integer as best we can.
1021     *
1022     * This is a hack.
1023     */
1024    if (error == AE_BUFFER_OVERFLOW) {
1025	if ((buf.Pointer = AcpiOsCallocate(buf.Length)) == NULL) {
1026	    error = AE_NO_MEMORY;
1027	} else {
1028	    if ((error = AcpiEvaluateObject(handle, path, NULL, &buf)) == AE_OK) {
1029		p = (ACPI_OBJECT *)buf.Pointer;
1030		if (p->Type != ACPI_TYPE_BUFFER) {
1031		    error = AE_TYPE;
1032		} else {
1033		    if (p->Buffer.Length > sizeof(int)) {
1034			error = AE_BAD_DATA;
1035		    } else {
1036			*number = 0;
1037			for (i = 0; i < p->Buffer.Length; i++)
1038			    *number += (*(p->Buffer.Pointer + i) << (i * 8));
1039		    }
1040		}
1041	    }
1042	}
1043	AcpiOsFree(buf.Pointer);
1044    }
1045    return(error);
1046}
1047
1048/*
1049 * Iterate over the elements of an a package object, calling the supplied
1050 * function for each element.
1051 *
1052 * XXX possible enhancement might be to abort traversal on error.
1053 */
1054ACPI_STATUS
1055acpi_ForeachPackageObject(ACPI_OBJECT *pkg, void (* func)(ACPI_OBJECT *comp, void *arg), void *arg)
1056{
1057    ACPI_OBJECT	*comp;
1058    int		i;
1059
1060    if ((pkg == NULL) || (pkg->Type != ACPI_TYPE_PACKAGE))
1061	return(AE_BAD_PARAMETER);
1062
1063    /* iterate over components */
1064    for (i = 0, comp = pkg->Package.Elements; i < pkg->Package.Count; i++, comp++)
1065	func(comp, arg);
1066
1067    return(AE_OK);
1068}
1069
1070/*
1071 * Find the (index)th resource object in a set.
1072 */
1073ACPI_STATUS
1074acpi_FindIndexedResource(ACPI_BUFFER *buf, int index, ACPI_RESOURCE **resp)
1075{
1076    ACPI_RESOURCE	*rp;
1077    int			i;
1078
1079    rp = (ACPI_RESOURCE *)buf->Pointer;
1080    i = index;
1081    while (i-- > 0) {
1082	/* range check */
1083	if (rp > (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
1084	    return(AE_BAD_PARAMETER);
1085	/* check for terminator */
1086	if ((rp->Id == ACPI_RSTYPE_END_TAG) ||
1087	    (rp->Length == 0))
1088	    return(AE_NOT_FOUND);
1089	rp = ACPI_RESOURCE_NEXT(rp);
1090    }
1091    if (resp != NULL)
1092	*resp = rp;
1093    return(AE_OK);
1094}
1095
1096/*
1097 * Append an ACPI_RESOURCE to an ACPI_BUFFER.
1098 *
1099 * Given a pointer to an ACPI_RESOURCE structure, expand the ACPI_BUFFER
1100 * provided to contain it.  If the ACPI_BUFFER is empty, allocate a sensible
1101 * backing block.  If the ACPI_RESOURCE is NULL, return an empty set of
1102 * resources.
1103 */
1104#define ACPI_INITIAL_RESOURCE_BUFFER_SIZE	512
1105
1106ACPI_STATUS
1107acpi_AppendBufferResource(ACPI_BUFFER *buf, ACPI_RESOURCE *res)
1108{
1109    ACPI_RESOURCE	*rp;
1110    void		*newp;
1111
1112    /*
1113     * Initialise the buffer if necessary.
1114     */
1115    if (buf->Pointer == NULL) {
1116	buf->Length = ACPI_INITIAL_RESOURCE_BUFFER_SIZE;
1117	if ((buf->Pointer = AcpiOsAllocate(buf->Length)) == NULL)
1118	    return(AE_NO_MEMORY);
1119	rp = (ACPI_RESOURCE *)buf->Pointer;
1120	rp->Id = ACPI_RSTYPE_END_TAG;
1121	rp->Length = 0;
1122    }
1123    if (res == NULL)
1124	return(AE_OK);
1125
1126    /*
1127     * Scan the current buffer looking for the terminator.
1128     * This will either find the terminator or hit the end
1129     * of the buffer and return an error.
1130     */
1131    rp = (ACPI_RESOURCE *)buf->Pointer;
1132    for (;;) {
1133	/* range check, don't go outside the buffer */
1134	if (rp >= (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
1135	    return(AE_BAD_PARAMETER);
1136	if ((rp->Id == ACPI_RSTYPE_END_TAG) ||
1137	    (rp->Length == 0)) {
1138	    break;
1139	}
1140	rp = ACPI_RESOURCE_NEXT(rp);
1141    }
1142
1143    /*
1144     * Check the size of the buffer and expand if required.
1145     *
1146     * Required size is:
1147     *	size of existing resources before terminator +
1148     *	size of new resource and header +
1149     * 	size of terminator.
1150     *
1151     * Note that this loop should really only run once, unless
1152     * for some reason we are stuffing a *really* huge resource.
1153     */
1154    while ((((u_int8_t *)rp - (u_int8_t *)buf->Pointer) +
1155	    res->Length + ACPI_RESOURCE_LENGTH_NO_DATA +
1156	    ACPI_RESOURCE_LENGTH) >= buf->Length) {
1157	if ((newp = AcpiOsAllocate(buf->Length * 2)) == NULL)
1158	    return(AE_NO_MEMORY);
1159	bcopy(buf->Pointer, newp, buf->Length);
1160        rp = (ACPI_RESOURCE *)((u_int8_t *)newp +
1161			       ((u_int8_t *)rp - (u_int8_t *)buf->Pointer));
1162	AcpiOsFree(buf->Pointer);
1163	buf->Pointer = newp;
1164	buf->Length += buf->Length;
1165    }
1166
1167    /*
1168     * Insert the new resource.
1169     */
1170    bcopy(res, rp, res->Length + ACPI_RESOURCE_LENGTH_NO_DATA);
1171
1172    /*
1173     * And add the terminator.
1174     */
1175    rp = ACPI_RESOURCE_NEXT(rp);
1176    rp->Id = ACPI_RSTYPE_END_TAG;
1177    rp->Length = 0;
1178
1179    return(AE_OK);
1180}
1181
1182
1183/*
1184 * Set the system sleep state
1185 *
1186 * Currently we only support S1 and S5
1187 */
1188ACPI_STATUS
1189acpi_SetSleepState(struct acpi_softc *sc, int state)
1190{
1191    ACPI_STATUS	status = AE_OK;
1192    UINT16	Count;
1193    UINT8	TypeA;
1194    UINT8	TypeB;
1195
1196    FUNCTION_TRACE_U32(__func__, state);
1197    ACPI_ASSERTLOCK;
1198
1199    switch (state) {
1200    case ACPI_STATE_S0:	/* XXX only for testing */
1201	status = AcpiEnterSleepState((UINT8)state);
1202	if (status != AE_OK) {
1203	    device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n", AcpiFormatException(status));
1204	}
1205	break;
1206
1207    case ACPI_STATE_S1:
1208    case ACPI_STATE_S2:
1209    case ACPI_STATE_S3:
1210    case ACPI_STATE_S4:
1211	status = AcpiHwObtainSleepTypeRegisterData((UINT8)state, &TypeA, &TypeB);
1212	if (status != AE_OK) {
1213	    device_printf(sc->acpi_dev, "AcpiHwObtainSleepTypeRegisterData failed - %s\n", AcpiFormatException(status));
1214	    break;
1215	}
1216
1217	/*
1218	 * Inform all devices that we are going to sleep.
1219	 */
1220	if (DEVICE_SUSPEND(root_bus) != 0) {
1221	    /*
1222	     * Re-wake the system.
1223	     *
1224	     * XXX note that a better two-pass approach with a 'veto' pass
1225	     *     followed by a "real thing" pass would be better, but the
1226	     *     current bus interface does not provide for this.
1227	     */
1228	    DEVICE_RESUME(root_bus);
1229	    return_ACPI_STATUS(AE_ERROR);
1230	}
1231	sc->acpi_sstate = state;
1232
1233	if (state != ACPI_STATE_S1) {
1234	    acpi_sleep_machdep(sc, state);
1235
1236	    /* AcpiEnterSleepState() maybe incompleted, unlock here. */
1237	    AcpiUtReleaseMutex(ACPI_MTX_HARDWARE);
1238
1239	    /* Re-enable ACPI hardware on wakeup from sleep state 4. */
1240	    if (state >= ACPI_STATE_S4) {
1241		acpi_Disable(sc);
1242		acpi_Enable(sc);
1243	    }
1244	} else {
1245	    status = AcpiEnterSleepState((UINT8)state);
1246	    if (status != AE_OK) {
1247		device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n", AcpiFormatException(status));
1248		break;
1249	    }
1250	    /* wait for the WAK_STS bit */
1251	    Count = 0;
1252	    while (!(AcpiHwRegisterBitAccess(ACPI_READ, ACPI_MTX_LOCK, WAK_STS))) {
1253		AcpiOsSleep(0, 1);
1254		/*
1255		 * Some BIOSes don't set WAK_STS at all,
1256		 * give up waiting for wakeup if we time out.
1257		 */
1258		if (Count > 1000) {
1259		    break;	/* giving up */
1260		}
1261		Count++;
1262	    }
1263	}
1264	AcpiLeaveSleepState((UINT8)state);
1265	DEVICE_RESUME(root_bus);
1266	sc->acpi_sstate = ACPI_STATE_S0;
1267	acpi_enable_fixed_events(sc);
1268	break;
1269
1270    case ACPI_STATE_S5:
1271	/*
1272	 * Shut down cleanly and power off.  This will call us back through the
1273	 * shutdown handlers.
1274	 */
1275	shutdown_nice(RB_POWEROFF);
1276	break;
1277
1278    default:
1279	status = AE_BAD_PARAMETER;
1280	break;
1281    }
1282    return_ACPI_STATUS(status);
1283}
1284
1285/*
1286 * Enable/Disable ACPI
1287 */
1288ACPI_STATUS
1289acpi_Enable(struct acpi_softc *sc)
1290{
1291    ACPI_STATUS	status;
1292    u_int32_t	flags;
1293
1294    FUNCTION_TRACE(__func__);
1295    ACPI_ASSERTLOCK;
1296
1297    flags = ACPI_NO_ADDRESS_SPACE_INIT | ACPI_NO_HARDWARE_INIT |
1298            ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
1299    if (!sc->acpi_enabled) {
1300	status = AcpiEnableSubsystem(flags);
1301    } else {
1302	status = AE_OK;
1303    }
1304    if (status == AE_OK)
1305	sc->acpi_enabled = 1;
1306    return_ACPI_STATUS(status);
1307}
1308
1309ACPI_STATUS
1310acpi_Disable(struct acpi_softc *sc)
1311{
1312    ACPI_STATUS	status;
1313
1314    FUNCTION_TRACE(__func__);
1315    ACPI_ASSERTLOCK;
1316
1317    if (sc->acpi_enabled) {
1318	status = AcpiDisable();
1319    } else {
1320	status = AE_OK;
1321    }
1322    if (status == AE_OK)
1323	sc->acpi_enabled = 0;
1324    return_ACPI_STATUS(status);
1325}
1326
1327/*
1328 * ACPI Event Handlers
1329 */
1330
1331/* System Event Handlers (registered by EVENTHANDLER_REGISTER) */
1332
1333static void
1334acpi_system_eventhandler_sleep(void *arg, int state)
1335{
1336    FUNCTION_TRACE_U32(__func__, state);
1337
1338    ACPI_LOCK;
1339    if (state >= ACPI_STATE_S0 && state <= ACPI_S_STATES_MAX)
1340	acpi_SetSleepState((struct acpi_softc *)arg, state);
1341    ACPI_UNLOCK;
1342    return_VOID;
1343}
1344
1345static void
1346acpi_system_eventhandler_wakeup(void *arg, int state)
1347{
1348    FUNCTION_TRACE_U32(__func__, state);
1349
1350    /* Well, what to do? :-) */
1351
1352    ACPI_LOCK;
1353    ACPI_UNLOCK;
1354
1355    return_VOID;
1356}
1357
1358/*
1359 * ACPICA Event Handlers (FixedEvent, also called from button notify handler)
1360 */
1361UINT32
1362acpi_eventhandler_power_button_for_sleep(void *context)
1363{
1364    struct acpi_softc	*sc = (struct acpi_softc *)context;
1365
1366    FUNCTION_TRACE(__func__);
1367
1368    EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_power_button_sx);
1369
1370    return_VALUE(INTERRUPT_HANDLED);
1371}
1372
1373UINT32
1374acpi_eventhandler_power_button_for_wakeup(void *context)
1375{
1376    struct acpi_softc	*sc = (struct acpi_softc *)context;
1377
1378    FUNCTION_TRACE(__func__);
1379
1380    EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_power_button_sx);
1381
1382    return_VALUE(INTERRUPT_HANDLED);
1383}
1384
1385UINT32
1386acpi_eventhandler_sleep_button_for_sleep(void *context)
1387{
1388    struct acpi_softc	*sc = (struct acpi_softc *)context;
1389
1390    FUNCTION_TRACE(__func__);
1391
1392    EVENTHANDLER_INVOKE(acpi_sleep_event, sc->acpi_sleep_button_sx);
1393
1394    return_VALUE(INTERRUPT_HANDLED);
1395}
1396
1397UINT32
1398acpi_eventhandler_sleep_button_for_wakeup(void *context)
1399{
1400    struct acpi_softc	*sc = (struct acpi_softc *)context;
1401
1402    FUNCTION_TRACE(__func__);
1403
1404    EVENTHANDLER_INVOKE(acpi_wakeup_event, sc->acpi_sleep_button_sx);
1405
1406    return_VALUE(INTERRUPT_HANDLED);
1407}
1408
1409/*
1410 * XXX This is kinda ugly, and should not be here.
1411 */
1412struct acpi_staticbuf {
1413    ACPI_BUFFER	buffer;
1414    char	data[512];
1415};
1416
1417char *
1418acpi_name(ACPI_HANDLE handle)
1419{
1420    static struct acpi_staticbuf	buf;
1421
1422    ACPI_ASSERTLOCK;
1423
1424    buf.buffer.Length = 512;
1425    buf.buffer.Pointer = &buf.data[0];
1426
1427    if (AcpiGetName(handle, ACPI_FULL_PATHNAME, &buf.buffer) == AE_OK)
1428	return(buf.buffer.Pointer);
1429    return("(unknown path)");
1430}
1431
1432/*
1433 * Debugging/bug-avoidance.  Avoid trying to fetch info on various
1434 * parts of the namespace.
1435 */
1436int
1437acpi_avoid(ACPI_HANDLE handle)
1438{
1439    char	*cp, *np;
1440    int		len;
1441
1442    np = acpi_name(handle);
1443    if (*np == '\\')
1444	np++;
1445    if ((cp = getenv("debug.acpi.avoid")) == NULL)
1446	return(0);
1447
1448    /* scan the avoid list checking for a match */
1449    for (;;) {
1450	while ((*cp != 0) && isspace(*cp))
1451	    cp++;
1452	if (*cp == 0)
1453	    break;
1454	len = 0;
1455	while ((cp[len] != 0) && !isspace(cp[len]))
1456	    len++;
1457	if (!strncmp(cp, np, len))
1458	    return(1);
1459	cp += len;
1460    }
1461    return(0);
1462}
1463
1464/*
1465 * Debugging/bug-avoidance.  Disable ACPI subsystem components.
1466 */
1467int
1468acpi_disabled(char *subsys)
1469{
1470    char	*cp;
1471    int		len;
1472
1473    if ((cp = getenv("debug.acpi.disable")) == NULL)
1474	return(0);
1475    if (!strcmp(cp, "all"))
1476	return(1);
1477
1478    /* scan the disable list checking for a match */
1479    for (;;) {
1480	while ((*cp != 0) && isspace(*cp))
1481	    cp++;
1482	if (*cp == 0)
1483	    break;
1484	len = 0;
1485	while ((cp[len] != 0) && !isspace(cp[len]))
1486	    len++;
1487	if (!strncmp(cp, subsys, len))
1488	    return(1);
1489	cp += len;
1490    }
1491    return(0);
1492}
1493
1494/*
1495 * Control interface.
1496 *
1497 * We multiplex ioctls for all participating ACPI devices here.  Individual
1498 * drivers wanting to be accessible via /dev/acpi should use the register/deregister
1499 * interface to make their handlers visible.
1500 */
1501struct acpi_ioctl_hook
1502{
1503    TAILQ_ENTRY(acpi_ioctl_hook)	link;
1504    u_long				cmd;
1505    int					(* fn)(u_long cmd, caddr_t addr, void *arg);
1506    void				*arg;
1507};
1508
1509static TAILQ_HEAD(,acpi_ioctl_hook)	acpi_ioctl_hooks;
1510static int				acpi_ioctl_hooks_initted;
1511
1512/*
1513 * Register an ioctl handler.
1514 */
1515int
1516acpi_register_ioctl(u_long cmd, int (* fn)(u_long cmd, caddr_t addr, void *arg), void *arg)
1517{
1518    struct acpi_ioctl_hook	*hp;
1519
1520    if ((hp = malloc(sizeof(*hp), M_ACPIDEV, M_NOWAIT)) == NULL)
1521	return(ENOMEM);
1522    hp->cmd = cmd;
1523    hp->fn = fn;
1524    hp->arg = arg;
1525    if (acpi_ioctl_hooks_initted == 0) {
1526	TAILQ_INIT(&acpi_ioctl_hooks);
1527	acpi_ioctl_hooks_initted = 1;
1528    }
1529    TAILQ_INSERT_TAIL(&acpi_ioctl_hooks, hp, link);
1530    return(0);
1531}
1532
1533/*
1534 * Deregister an ioctl handler.
1535 */
1536void
1537acpi_deregister_ioctl(u_long cmd, int (* fn)(u_long cmd, caddr_t addr, void *arg))
1538{
1539    struct acpi_ioctl_hook	*hp;
1540
1541    TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link)
1542	if ((hp->cmd == cmd) && (hp->fn == fn))
1543	    break;
1544
1545    if (hp != NULL) {
1546	TAILQ_REMOVE(&acpi_ioctl_hooks, hp, link);
1547	free(hp, M_ACPIDEV);
1548    }
1549}
1550
1551static int
1552acpiopen(dev_t dev, int flag, int fmt, struct proc *p)
1553{
1554    return(0);
1555}
1556
1557static int
1558acpiclose(dev_t dev, int flag, int fmt, struct proc *p)
1559{
1560    return(0);
1561}
1562
1563static int
1564acpiioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct proc *p)
1565{
1566    struct acpi_softc		*sc;
1567    struct acpi_ioctl_hook	*hp;
1568    int				error, xerror, state;
1569
1570    ACPI_LOCK;
1571
1572    error = state = 0;
1573    sc = dev->si_drv1;
1574
1575    /*
1576     * Scan the list of registered ioctls, looking for handlers.
1577     */
1578    if (acpi_ioctl_hooks_initted) {
1579	TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link) {
1580	    if (hp->cmd == cmd) {
1581		xerror = hp->fn(cmd, addr, hp->arg);
1582		if (xerror != 0)
1583		    error = xerror;
1584		goto out;
1585	    }
1586	}
1587    }
1588
1589    /*
1590     * Core system ioctls.
1591     */
1592    switch (cmd) {
1593    case ACPIIO_ENABLE:
1594	if (ACPI_FAILURE(acpi_Enable(sc)))
1595	    error = ENXIO;
1596	break;
1597
1598    case ACPIIO_DISABLE:
1599	if (ACPI_FAILURE(acpi_Disable(sc)))
1600	    error = ENXIO;
1601	break;
1602
1603    case ACPIIO_SETSLPSTATE:
1604	if (!sc->acpi_enabled) {
1605	    error = ENXIO;
1606	    break;
1607	}
1608	state = *(int *)addr;
1609	if (state >= ACPI_STATE_S0  && state <= ACPI_S_STATES_MAX) {
1610	    acpi_SetSleepState(sc, state);
1611	} else {
1612	    error = EINVAL;
1613	}
1614	break;
1615
1616    default:
1617	if (error == 0)
1618	    error = EINVAL;
1619	break;
1620    }
1621
1622out:
1623    ACPI_UNLOCK;
1624    return(error);
1625}
1626
1627static int
1628acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
1629{
1630    char sleep_state[10];
1631    int error;
1632    u_int new_state, old_state;
1633
1634    old_state = *(u_int *)oidp->oid_arg1;
1635    if (old_state > ACPI_S_STATES_MAX) {
1636	strcpy(sleep_state, "unknown");
1637    } else {
1638	strncpy(sleep_state, sleep_state_names[old_state],
1639		sizeof(sleep_state_names[old_state]));
1640    }
1641    error = sysctl_handle_string(oidp, sleep_state, sizeof(sleep_state), req);
1642    if (error == 0 && req->newptr != NULL) {
1643	for (new_state = ACPI_STATE_S0; new_state <= ACPI_S_STATES_MAX; new_state++) {
1644	    if (strncmp(sleep_state, sleep_state_names[new_state],
1645			sizeof(sleep_state)) == 0)
1646		break;
1647	}
1648	if ((new_state != old_state) && (new_state <= ACPI_S_STATES_MAX)) {
1649	    *(u_int *)oidp->oid_arg1 = new_state;
1650	} else {
1651	    error = EINVAL;
1652	}
1653    }
1654    return(error);
1655}
1656
1657#ifdef ACPI_DEBUG
1658/*
1659 * Support for parsing debug options from the kernel environment.
1660 *
1661 * Bits may be set in the AcpiDbgLayer and AcpiDbgLevel debug registers
1662 * by specifying the names of the bits in the debug.acpi.layer and
1663 * debug.acpi.level environment variables.  Bits may be unset by
1664 * prefixing the bit name with !.
1665 */
1666struct debugtag
1667{
1668    char	*name;
1669    UINT32	value;
1670};
1671
1672static struct debugtag	dbg_layer[] = {
1673    {"ACPI_UTILITIES",		ACPI_UTILITIES},
1674    {"ACPI_HARDWARE",		ACPI_HARDWARE},
1675    {"ACPI_EVENTS",		ACPI_EVENTS},
1676    {"ACPI_TABLES",		ACPI_TABLES},
1677    {"ACPI_NAMESPACE",		ACPI_NAMESPACE},
1678    {"ACPI_PARSER",		ACPI_PARSER},
1679    {"ACPI_DISPATCHER",		ACPI_DISPATCHER},
1680    {"ACPI_EXECUTER",		ACPI_EXECUTER},
1681    {"ACPI_RESOURCES",		ACPI_RESOURCES},
1682    {"ACPI_DEBUGGER",		ACPI_DEBUGGER},
1683    {"ACPI_OS_SERVICES",	ACPI_OS_SERVICES},
1684
1685    {"ACPI_BUS",		ACPI_BUS},
1686    {"ACPI_SYSTEM",		ACPI_SYSTEM},
1687    {"ACPI_POWER",		ACPI_POWER},
1688    {"ACPI_EC", 		ACPI_EC},
1689    {"ACPI_AC_ADAPTER",		ACPI_AC_ADAPTER},
1690    {"ACPI_BATTERY",		ACPI_BATTERY},
1691    {"ACPI_BUTTON",		ACPI_BUTTON},
1692    {"ACPI_PROCESSOR",		ACPI_PROCESSOR},
1693    {"ACPI_THERMAL",		ACPI_THERMAL},
1694    {"ACPI_FAN",		ACPI_FAN},
1695
1696    {"ACPI_ALL_COMPONENTS",	ACPI_ALL_COMPONENTS},
1697    {NULL, 0}
1698};
1699
1700static struct debugtag dbg_level[] = {
1701    {"ACPI_LV_OK",		ACPI_LV_OK},
1702    {"ACPI_LV_INFO",		ACPI_LV_INFO},
1703    {"ACPI_LV_WARN",		ACPI_LV_WARN},
1704    {"ACPI_LV_ERROR",		ACPI_LV_ERROR},
1705    {"ACPI_LV_FATAL",		ACPI_LV_FATAL},
1706    {"ACPI_LV_DEBUG_OBJECT",	ACPI_LV_DEBUG_OBJECT},
1707    {"ACPI_LV_ALL_EXCEPTIONS",	ACPI_LV_ALL_EXCEPTIONS},
1708    {"ACPI_LV_THREADS",		ACPI_LV_THREADS},
1709    {"ACPI_LV_PARSE",		ACPI_LV_PARSE},
1710    {"ACPI_LV_DISPATCH",	ACPI_LV_DISPATCH},
1711    {"ACPI_LV_LOAD",		ACPI_LV_LOAD},
1712    {"ACPI_LV_EXEC",		ACPI_LV_EXEC},
1713    {"ACPI_LV_NAMES",		ACPI_LV_NAMES},
1714    {"ACPI_LV_OPREGION",	ACPI_LV_OPREGION},
1715    {"ACPI_LV_BFIELD",		ACPI_LV_BFIELD},
1716    {"ACPI_LV_TRASH",		ACPI_LV_TRASH},
1717    {"ACPI_LV_TABLES",		ACPI_LV_TABLES},
1718    {"ACPI_LV_FUNCTIONS",	ACPI_LV_FUNCTIONS},
1719    {"ACPI_LV_VALUES",		ACPI_LV_VALUES},
1720    {"ACPI_LV_OBJECTS",		ACPI_LV_OBJECTS},
1721    {"ACPI_LV_ALLOCATIONS",	ACPI_LV_ALLOCATIONS},
1722    {"ACPI_LV_RESOURCES",	ACPI_LV_RESOURCES},
1723    {"ACPI_LV_IO",		ACPI_LV_IO},
1724    {"ACPI_LV_INTERRUPTS",	ACPI_LV_INTERRUPTS},
1725    {"ACPI_LV_USER_REQUESTS",	ACPI_LV_USER_REQUESTS},
1726    {"ACPI_LV_PACKAGE",		ACPI_LV_PACKAGE},
1727    {"ACPI_LV_MUTEX",		ACPI_LV_MUTEX},
1728    {"ACPI_LV_INIT",		ACPI_LV_INIT},
1729    {"ACPI_LV_ALL",		ACPI_LV_ALL},
1730    {"ACPI_DB_AML_DISASSEMBLE",	ACPI_DB_AML_DISASSEMBLE},
1731    {"ACPI_DB_VERBOSE_INFO",	ACPI_DB_VERBOSE_INFO},
1732    {"ACPI_DB_FULL_TABLES",	ACPI_DB_FULL_TABLES},
1733    {"ACPI_DB_EVENTS",		ACPI_DB_EVENTS},
1734    {"ACPI_DB_VERBOSE",		ACPI_DB_VERBOSE},
1735    {NULL, 0}
1736};
1737
1738static void
1739acpi_parse_debug(char *cp, struct debugtag *tag, UINT32 *flag)
1740{
1741    char	*ep;
1742    int		i, l;
1743    int		set;
1744
1745    while (*cp) {
1746	if (isspace(*cp)) {
1747	    cp++;
1748	    continue;
1749	}
1750	ep = cp;
1751	while (*ep && !isspace(*ep))
1752	    ep++;
1753	if (*cp == '!') {
1754	    set = 0;
1755	    cp++;
1756	    if (cp == ep)
1757		continue;
1758	} else {
1759	    set = 1;
1760	}
1761	l = ep - cp;
1762	for (i = 0; tag[i].name != NULL; i++) {
1763	    if (!strncmp(cp, tag[i].name, l)) {
1764		if (set) {
1765		    *flag |= tag[i].value;
1766		} else {
1767		    *flag &= ~tag[i].value;
1768		}
1769		printf("ACPI_DEBUG: set '%s'\n", tag[i].name);
1770	    }
1771	}
1772	cp = ep;
1773    }
1774}
1775
1776static void
1777acpi_set_debugging(void *junk)
1778{
1779    char	*cp;
1780
1781    AcpiDbgLayer = 0;
1782    AcpiDbgLevel = 0;
1783    if ((cp = getenv("debug.acpi.layer")) != NULL)
1784	acpi_parse_debug(cp, &dbg_layer[0], &AcpiDbgLayer);
1785    if ((cp = getenv("debug.acpi.level")) != NULL)
1786	acpi_parse_debug(cp, &dbg_level[0], &AcpiDbgLevel);
1787
1788    printf("ACPI debug layer 0x%x  debug level 0x%x\n", AcpiDbgLayer, AcpiDbgLevel);
1789}
1790SYSINIT(acpi_debugging, SI_SUB_TUNABLES, SI_ORDER_ANY, acpi_set_debugging, NULL);
1791#endif
1792