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