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