xref: /netbsd-src/sys/dev/acpi/acpi.c (revision 4817a0b0b8fe9612e8ebe21a9bf2d97b95038a97)
1 /*	$NetBSD: acpi.c,v 1.222 2010/10/24 07:53:04 jruoho Exp $	*/
2 
3 /*-
4  * Copyright (c) 2003, 2007 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Charles M. Hannum of By Noon Software, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 /*
33  * Copyright (c) 2003 Wasabi Systems, Inc.
34  * All rights reserved.
35  *
36  * Written by Frank van der Linden for Wasabi Systems, Inc.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. All advertising materials mentioning features or use of this software
47  *    must display the following acknowledgement:
48  *      This product includes software developed for the NetBSD Project by
49  *      Wasabi Systems, Inc.
50  * 4. The name of Wasabi Systems, Inc. may not be used to endorse
51  *    or promote products derived from this software without specific prior
52  *    written permission.
53  *
54  * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``AS IS'' AND
55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
56  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
57  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL WASABI SYSTEMS, INC
58  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
59  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
60  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
61  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
62  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
63  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
64  * POSSIBILITY OF SUCH DAMAGE.
65  */
66 
67 /*
68  * Copyright 2001, 2003 Wasabi Systems, Inc.
69  * All rights reserved.
70  *
71  * Written by Jason R. Thorpe for Wasabi Systems, Inc.
72  *
73  * Redistribution and use in source and binary forms, with or without
74  * modification, are permitted provided that the following conditions
75  * are met:
76  * 1. Redistributions of source code must retain the above copyright
77  *    notice, this list of conditions and the following disclaimer.
78  * 2. Redistributions in binary form must reproduce the above copyright
79  *    notice, this list of conditions and the following disclaimer in the
80  *    documentation and/or other materials provided with the distribution.
81  * 3. All advertising materials mentioning features or use of this software
82  *    must display the following acknowledgement:
83  *	This product includes software developed for the NetBSD Project by
84  *	Wasabi Systems, Inc.
85  * 4. The name of Wasabi Systems, Inc. may not be used to endorse
86  *    or promote products derived from this software without specific prior
87  *    written permission.
88  *
89  * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``AS IS'' AND
90  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
91  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
92  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL WASABI SYSTEMS, INC
93  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
94  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
95  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
96  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
97  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
98  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
99  * POSSIBILITY OF SUCH DAMAGE.
100  */
101 
102 #include <sys/cdefs.h>
103 __KERNEL_RCSID(0, "$NetBSD: acpi.c,v 1.222 2010/10/24 07:53:04 jruoho Exp $");
104 
105 #include "opt_acpi.h"
106 #include "opt_pcifixup.h"
107 
108 #include <sys/param.h>
109 #include <sys/device.h>
110 #include <sys/kernel.h>
111 #include <sys/malloc.h>
112 #include <sys/module.h>
113 #include <sys/mutex.h>
114 #include <sys/sysctl.h>
115 #include <sys/systm.h>
116 #include <sys/timetc.h>
117 
118 #include <dev/acpi/acpireg.h>
119 #include <dev/acpi/acpivar.h>
120 #include <dev/acpi/acpi_osd.h>
121 #include <dev/acpi/acpi_pci.h>
122 #include <dev/acpi/acpi_power.h>
123 #include <dev/acpi/acpi_timer.h>
124 #include <dev/acpi/acpi_wakedev.h>
125 
126 #define _COMPONENT	ACPI_BUS_COMPONENT
127 ACPI_MODULE_NAME	("acpi")
128 
129 #if defined(ACPI_PCI_FIXUP)
130 #error The option ACPI_PCI_FIXUP has been obsoleted by PCI_INTR_FIXUP_DISABLED.  Please adjust your kernel configuration file.
131 #endif
132 
133 #ifdef PCI_INTR_FIXUP_DISABLED
134 #include <dev/pci/pcidevs.h>
135 #endif
136 
137 MALLOC_DECLARE(M_ACPI);
138 
139 #include <machine/acpi_machdep.h>
140 
141 #ifdef ACPI_DEBUGGER
142 #define	ACPI_DBGR_INIT		0x01
143 #define	ACPI_DBGR_TABLES	0x02
144 #define	ACPI_DBGR_ENABLE	0x04
145 #define	ACPI_DBGR_PROBE		0x08
146 #define	ACPI_DBGR_RUNNING	0x10
147 
148 static int acpi_dbgr = 0x00;
149 #endif
150 
151 /*
152  * This is a flag we set when the ACPI subsystem is active.  Machine
153  * dependent code may wish to skip other steps (such as attaching
154  * subsystems that ACPI supercedes) when ACPI is active.
155  */
156 int	acpi_active;
157 
158 int	acpi_force_load = 0;
159 int	acpi_suspended = 0;
160 int	acpi_verbose_loaded = 0;
161 
162 struct acpi_softc	*acpi_softc;
163 static uint64_t		 acpi_root_pointer;
164 extern kmutex_t		 acpi_interrupt_list_mtx;
165 extern struct		 cfdriver acpi_cd;
166 static ACPI_HANDLE	 acpi_scopes[4];
167 ACPI_TABLE_HEADER	*madt_header;
168 
169 /*
170  * This structure provides a context for the ACPI
171  * namespace walk performed in acpi_build_tree().
172  */
173 struct acpi_walkcontext {
174 	struct acpi_softc	*aw_sc;
175 	struct acpi_devnode	*aw_parent;
176 };
177 
178 /*
179  * Ignored HIDs.
180  */
181 static const char * const acpi_ignored_ids[] = {
182 #if defined(i386) || defined(x86_64)
183 	"PNP0000",	/* AT interrupt controller is handled internally */
184 	"PNP0200",	/* AT DMA controller is handled internally */
185 	"PNP0A??",	/* PCI Busses are handled internally */
186 	"PNP0B00",	/* AT RTC is handled internally */
187 	"PNP0C0F",	/* ACPI PCI link devices are handled internally */
188 #endif
189 #if defined(x86_64)
190 	"PNP0C04",	/* FPU is handled internally */
191 #endif
192 	NULL
193 };
194 
195 static int		acpi_match(device_t, cfdata_t, void *);
196 static int		acpi_submatch(device_t, cfdata_t, const int *, void *);
197 static void		acpi_attach(device_t, device_t, void *);
198 static int		acpi_detach(device_t, int);
199 static void		acpi_childdet(device_t, device_t);
200 static bool		acpi_suspend(device_t, const pmf_qual_t *);
201 static bool		acpi_resume(device_t, const pmf_qual_t *);
202 
203 static void		acpi_build_tree(struct acpi_softc *);
204 static ACPI_STATUS	acpi_make_devnode(ACPI_HANDLE, uint32_t,
205 					  void *, void **);
206 static ACPI_STATUS	acpi_make_devnode_post(ACPI_HANDLE, uint32_t,
207 					       void *, void **);
208 
209 #ifdef ACPI_ACTIVATE_DEV
210 static void		acpi_activate_device(ACPI_HANDLE, ACPI_DEVICE_INFO **);
211 static ACPI_STATUS	acpi_allocate_resources(ACPI_HANDLE);
212 #endif
213 
214 static int		acpi_rescan(device_t, const char *, const int *);
215 static void		acpi_rescan_nodes(struct acpi_softc *);
216 static void		acpi_rescan_capabilities(struct acpi_softc *);
217 static int		acpi_print(void *aux, const char *);
218 
219 static void		acpi_notify_handler(ACPI_HANDLE, uint32_t, void *);
220 
221 static void		acpi_register_fixed_button(struct acpi_softc *, int);
222 static void		acpi_deregister_fixed_button(struct acpi_softc *, int);
223 static uint32_t		acpi_fixed_button_handler(void *);
224 static void		acpi_fixed_button_pressed(void *);
225 
226 static void		acpi_sleep_init(struct acpi_softc *);
227 
228 static int		sysctl_hw_acpi_fixedstats(SYSCTLFN_PROTO);
229 static int		sysctl_hw_acpi_sleepstate(SYSCTLFN_PROTO);
230 static int		sysctl_hw_acpi_sleepstates(SYSCTLFN_PROTO);
231 
232 static bool		  acpi_is_scope(struct acpi_devnode *);
233 static ACPI_TABLE_HEADER *acpi_map_rsdt(void);
234 static void		  acpi_unmap_rsdt(ACPI_TABLE_HEADER *);
235 
236 void			acpi_print_verbose_stub(struct acpi_softc *);
237 void			acpi_print_dev_stub(const char *);
238 
239 void (*acpi_print_verbose)(struct acpi_softc *) = acpi_print_verbose_stub;
240 void (*acpi_print_dev)(const char *) = acpi_print_dev_stub;
241 
242 CFATTACH_DECL2_NEW(acpi, sizeof(struct acpi_softc),
243     acpi_match, acpi_attach, acpi_detach, NULL, acpi_rescan, acpi_childdet);
244 
245 /*
246  * Probe for ACPI support.
247  *
248  * This is called by the machine-dependent ACPI front-end.
249  * Note: this is not an autoconfiguration interface function.
250  */
251 int
252 acpi_probe(void)
253 {
254 	ACPI_TABLE_HEADER *rsdt;
255 	const char *func;
256 	static int once;
257 	bool initialized;
258 	ACPI_STATUS rv;
259 
260 	if (once != 0)
261 		panic("%s: already probed", __func__);
262 
263 	once = 1;
264 	func = NULL;
265 	acpi_softc = NULL;
266 	initialized = false;
267 
268 	mutex_init(&acpi_interrupt_list_mtx, MUTEX_DEFAULT, IPL_NONE);
269 
270 	/*
271 	 * Start up ACPICA.
272 	 */
273 #ifdef ACPI_DEBUGGER
274 	if (acpi_dbgr & ACPI_DBGR_INIT)
275 		acpi_osd_debugger();
276 #endif
277 
278 	CTASSERT(TRUE == true);
279 	CTASSERT(FALSE == false);
280 
281 	AcpiGbl_AllMethodsSerialized = false;
282 	AcpiGbl_EnableInterpreterSlack = true;
283 
284 	rv = AcpiInitializeSubsystem();
285 
286 	if (ACPI_SUCCESS(rv))
287 		initialized = true;
288 	else {
289 		func = "AcpiInitializeSubsystem()";
290 		goto fail;
291 	}
292 
293 	/*
294 	 * Allocate space for RSDT/XSDT and DSDT,
295 	 * but allow resizing if more tables exist.
296 	 */
297 	rv = AcpiInitializeTables(NULL, 2, true);
298 
299 	if (ACPI_FAILURE(rv)) {
300 		func = "AcpiInitializeTables()";
301 		goto fail;
302 	}
303 
304 #ifdef ACPI_DEBUGGER
305 	if (acpi_dbgr & ACPI_DBGR_TABLES)
306 		acpi_osd_debugger();
307 #endif
308 
309 	rv = AcpiLoadTables();
310 
311 	if (ACPI_FAILURE(rv)) {
312 		func = "AcpiLoadTables()";
313 		goto fail;
314 	}
315 
316 	rsdt = acpi_map_rsdt();
317 
318 	if (rsdt == NULL) {
319 		func = "acpi_map_rsdt()";
320 		rv = AE_ERROR;
321 		goto fail;
322 	}
323 
324 	if (acpi_force_load == 0 && (acpi_find_quirks() & ACPI_QUIRK_BROKEN)) {
325 		aprint_normal("ACPI: BIOS is listed as broken:\n");
326 		aprint_normal("ACPI: X/RSDT: OemId <%6.6s,%8.8s,%08x>, "
327 		       "AslId <%4.4s,%08x>\n",
328 			rsdt->OemId, rsdt->OemTableId,
329 		        rsdt->OemRevision,
330 			rsdt->AslCompilerId,
331 		        rsdt->AslCompilerRevision);
332 		aprint_normal("ACPI: Not used. Set acpi_force_load to use.\n");
333 		acpi_unmap_rsdt(rsdt);
334 		AcpiTerminate();
335 		return 0;
336 	}
337 	if (acpi_force_load == 0 && (acpi_find_quirks() & ACPI_QUIRK_OLDBIOS)) {
338 		aprint_normal("ACPI: BIOS is too old (%s). Set acpi_force_load to use.\n",
339 		    pmf_get_platform("firmware-date"));
340 		acpi_unmap_rsdt(rsdt);
341 		AcpiTerminate();
342 		return 0;
343 	}
344 
345 	acpi_unmap_rsdt(rsdt);
346 
347 	rv = AcpiEnableSubsystem(~(ACPI_NO_HARDWARE_INIT|ACPI_NO_ACPI_ENABLE));
348 
349 	if (ACPI_FAILURE(rv)) {
350 		func = "AcpiEnableSubsystem()";
351 		goto fail;
352 	}
353 
354 	/*
355 	 * Looks like we have ACPI!
356 	 */
357 	return 1;
358 
359 fail:
360 	KASSERT(rv != AE_OK);
361 	KASSERT(func != NULL);
362 
363 	aprint_error("%s: failed to probe ACPI: %s\n",
364 	    func, AcpiFormatException(rv));
365 
366 	if (initialized != false)
367 		(void)AcpiTerminate();
368 
369 	return 0;
370 }
371 
372 void
373 acpi_disable(void)
374 {
375 
376 	if (acpi_softc == NULL)
377 		return;
378 
379 	KASSERT(acpi_active != 0);
380 
381 	if (AcpiGbl_FADT.SmiCommand != 0)
382 		AcpiDisable();
383 }
384 
385 int
386 acpi_check(device_t parent, const char *ifattr)
387 {
388 	return (config_search_ia(acpi_submatch, parent, ifattr, NULL) != NULL);
389 }
390 
391 /*
392  * Autoconfiguration.
393  */
394 static int
395 acpi_match(device_t parent, cfdata_t match, void *aux)
396 {
397 	/*
398 	 * XXX: Nada; MD code has called acpi_probe().
399 	 */
400 	return 1;
401 }
402 
403 static int
404 acpi_submatch(device_t parent, cfdata_t cf, const int *locs, void *aux)
405 {
406 	struct cfattach *ca;
407 
408 	ca = config_cfattach_lookup(cf->cf_name, cf->cf_atname);
409 
410 	return (ca == &acpi_ca);
411 }
412 
413 static void
414 acpi_attach(device_t parent, device_t self, void *aux)
415 {
416 	struct acpi_softc *sc = device_private(self);
417 	struct acpibus_attach_args *aa = aux;
418 	ACPI_TABLE_HEADER *rsdt;
419 	ACPI_STATUS rv;
420 
421 	aprint_naive("\n");
422 	aprint_normal(": Intel ACPICA %08x\n", ACPI_CA_VERSION);
423 
424 	if (acpi_softc != NULL)
425 		panic("%s: already attached", __func__);
426 
427 	rsdt = acpi_map_rsdt();
428 
429 	if (rsdt == NULL)
430 		aprint_error_dev(self, "X/RSDT: Not found\n");
431 	else {
432 		aprint_verbose_dev(self,
433 		    "X/RSDT: OemId <%6.6s,%8.8s,%08x>, AslId <%4.4s,%08x>\n",
434 		    rsdt->OemId, rsdt->OemTableId,
435 		    rsdt->OemRevision,
436 		    rsdt->AslCompilerId, rsdt->AslCompilerRevision);
437 	}
438 
439 	acpi_unmap_rsdt(rsdt);
440 
441 	sc->sc_dev = self;
442 	sc->sc_root = NULL;
443 
444 	sc->sc_sleepstate = ACPI_STATE_S0;
445 	sc->sc_quirks = acpi_find_quirks();
446 
447 	sysmon_power_settype("acpi");
448 
449 	sc->sc_iot = aa->aa_iot;
450 	sc->sc_memt = aa->aa_memt;
451 	sc->sc_pc = aa->aa_pc;
452 	sc->sc_pciflags = aa->aa_pciflags;
453 	sc->sc_ic = aa->aa_ic;
454 
455 	SIMPLEQ_INIT(&sc->ad_head);
456 
457 	acpi_softc = sc;
458 
459 	if (pmf_device_register(self, acpi_suspend, acpi_resume) != true)
460 		aprint_error_dev(self, "couldn't establish power handler\n");
461 
462 	/*
463 	 * Bring ACPI on-line.
464 	 */
465 #ifdef ACPI_DEBUGGER
466 	if (acpi_dbgr & ACPI_DBGR_ENABLE)
467 		acpi_osd_debugger();
468 #endif
469 
470 #define ACPI_ENABLE_PHASE1 \
471     (ACPI_NO_HANDLER_INIT | ACPI_NO_EVENT_INIT)
472 #define ACPI_ENABLE_PHASE2 \
473     (ACPI_NO_HARDWARE_INIT | ACPI_NO_ACPI_ENABLE | \
474      ACPI_NO_ADDRESS_SPACE_INIT)
475 
476 	rv = AcpiEnableSubsystem(ACPI_ENABLE_PHASE1);
477 
478 	if (ACPI_FAILURE(rv))
479 		goto fail;
480 
481 	acpi_md_callback();
482 
483 	rv = AcpiEnableSubsystem(ACPI_ENABLE_PHASE2);
484 
485 	if (ACPI_FAILURE(rv))
486 		goto fail;
487 
488 	/*
489 	 * Early EC handler initialization if ECDT table is available.
490 	 */
491 	config_found_ia(self, "acpiecdtbus", aa, NULL);
492 
493 	rv = AcpiInitializeObjects(ACPI_FULL_INITIALIZATION);
494 
495 	if (ACPI_FAILURE(rv))
496 		goto fail;
497 
498 	/*
499 	 * Install global notify handlers.
500 	 */
501 	rv = AcpiInstallNotifyHandler(ACPI_ROOT_OBJECT,
502 	    ACPI_SYSTEM_NOTIFY, acpi_notify_handler, NULL);
503 
504 	if (ACPI_FAILURE(rv))
505 		goto fail;
506 
507 	rv = AcpiInstallNotifyHandler(ACPI_ROOT_OBJECT,
508 	    ACPI_DEVICE_NOTIFY, acpi_notify_handler, NULL);
509 
510 	if (ACPI_FAILURE(rv))
511 		goto fail;
512 
513 	acpi_active = 1;
514 
515 	/* Show SCI interrupt. */
516 	aprint_verbose_dev(self, "SCI interrupting at int %u\n",
517 	    AcpiGbl_FADT.SciInterrupt);
518 
519 	/*
520 	 * Install fixed-event handlers.
521 	 */
522 	acpi_register_fixed_button(sc, ACPI_EVENT_POWER_BUTTON);
523 	acpi_register_fixed_button(sc, ACPI_EVENT_SLEEP_BUTTON);
524 
525 	acpitimer_init(sc);
526 
527 #ifdef ACPI_DEBUGGER
528 	if (acpi_dbgr & ACPI_DBGR_PROBE)
529 		acpi_osd_debugger();
530 #endif
531 
532 	/*
533 	 * Scan the namespace and build our device tree.
534 	 */
535 	acpi_build_tree(sc);
536 	acpi_sleep_init(sc);
537 
538 #ifdef ACPI_DEBUGGER
539 	if (acpi_dbgr & ACPI_DBGR_RUNNING)
540 		acpi_osd_debugger();
541 #endif
542 
543 #ifdef ACPI_DEBUG
544 	acpi_debug_init();
545 #endif
546 
547 	/*
548 	 * Print debug information.
549 	 */
550 	acpi_print_verbose(sc);
551 
552 	return;
553 
554 fail:
555 	aprint_error("%s: failed to initialize ACPI: %s\n",
556 	    __func__, AcpiFormatException(rv));
557 }
558 
559 /*
560  * XXX: This is incomplete.
561  */
562 static int
563 acpi_detach(device_t self, int flags)
564 {
565 	struct acpi_softc *sc = device_private(self);
566 	ACPI_STATUS rv;
567 	int rc;
568 
569 	rv = AcpiRemoveNotifyHandler(ACPI_ROOT_OBJECT,
570 	    ACPI_SYSTEM_NOTIFY, acpi_notify_handler);
571 
572 	if (ACPI_FAILURE(rv))
573 		return EBUSY;
574 
575 	rv = AcpiRemoveNotifyHandler(ACPI_ROOT_OBJECT,
576 	    ACPI_DEVICE_NOTIFY, acpi_notify_handler);
577 
578 	if (ACPI_FAILURE(rv))
579 		return EBUSY;
580 
581 	if ((rc = config_detach_children(self, flags)) != 0)
582 		return rc;
583 
584 	if ((rc = acpitimer_detach()) != 0)
585 		return rc;
586 
587 	acpi_deregister_fixed_button(sc, ACPI_EVENT_POWER_BUTTON);
588 	acpi_deregister_fixed_button(sc, ACPI_EVENT_SLEEP_BUTTON);
589 
590 	pmf_device_deregister(self);
591 
592 	acpi_softc = NULL;
593 
594 	return 0;
595 }
596 
597 /*
598  * XXX: Need to reclaim any resources? Yes.
599  */
600 static void
601 acpi_childdet(device_t self, device_t child)
602 {
603 	struct acpi_softc *sc = device_private(self);
604 	struct acpi_devnode *ad;
605 
606 	if (sc->sc_apmbus == child)
607 		sc->sc_apmbus = NULL;
608 
609 	SIMPLEQ_FOREACH(ad, &sc->ad_head, ad_list) {
610 
611 		if (ad->ad_device == child)
612 			ad->ad_device = NULL;
613 	}
614 }
615 
616 static bool
617 acpi_suspend(device_t dv, const pmf_qual_t *qual)
618 {
619 
620 	acpi_suspended = 1;
621 
622 	return true;
623 }
624 
625 static bool
626 acpi_resume(device_t dv, const pmf_qual_t *qual)
627 {
628 
629 	acpi_suspended = 0;
630 
631 	return true;
632 }
633 
634 /*
635  * Namespace scan.
636  */
637 static void
638 acpi_build_tree(struct acpi_softc *sc)
639 {
640 	struct acpi_walkcontext awc;
641 
642 	/*
643 	 * Get the root scope handles.
644 	 */
645 	KASSERT(__arraycount(acpi_scopes) == 4);
646 
647 	(void)AcpiGetHandle(ACPI_ROOT_OBJECT, "\\_PR_", &acpi_scopes[0]);
648 	(void)AcpiGetHandle(ACPI_ROOT_OBJECT, "\\_SB_", &acpi_scopes[1]);
649 	(void)AcpiGetHandle(ACPI_ROOT_OBJECT, "\\_SI_", &acpi_scopes[2]);
650 	(void)AcpiGetHandle(ACPI_ROOT_OBJECT, "\\_TZ_", &acpi_scopes[3]);
651 
652 	/*
653 	 * Make the root node.
654 	 */
655 	awc.aw_sc = sc;
656 	awc.aw_parent = NULL;
657 
658 	(void)acpi_make_devnode(ACPI_ROOT_OBJECT, 0, &awc, NULL);
659 
660 	KASSERT(sc->sc_root == NULL);
661 	KASSERT(awc.aw_parent != NULL);
662 
663 	sc->sc_root = awc.aw_parent;
664 
665 	/*
666 	 * Build the internal namespace.
667 	 */
668 	(void)AcpiWalkNamespace(ACPI_TYPE_ANY, ACPI_ROOT_OBJECT, UINT32_MAX,
669 	    acpi_make_devnode, acpi_make_devnode_post, &awc, NULL);
670 
671 	/*
672 	 * Scan the internal namespace.
673 	 */
674 	(void)acpi_pcidev_scan(sc->sc_root);
675 	(void)acpi_rescan(sc->sc_dev, NULL, NULL);
676 
677 	acpi_rescan_capabilities(sc);
678 }
679 
680 static ACPI_STATUS
681 acpi_make_devnode(ACPI_HANDLE handle, uint32_t level,
682     void *context, void **status)
683 {
684 	struct acpi_walkcontext *awc = context;
685 	struct acpi_softc *sc = awc->aw_sc;
686 	struct acpi_devnode *ad;
687 	ACPI_DEVICE_INFO *devinfo;
688 	ACPI_OBJECT_TYPE type;
689 	ACPI_NAME_UNION *anu;
690 	ACPI_STATUS rv;
691 	int clear, i;
692 
693 	rv = AcpiGetObjectInfo(handle, &devinfo);
694 
695 	if (ACPI_FAILURE(rv))
696 		return AE_OK;	/* Do not terminate the walk. */
697 
698 	type = devinfo->Type;
699 
700 	switch (type) {
701 
702 	case ACPI_TYPE_DEVICE:
703 
704 #ifdef ACPI_ACTIVATE_DEV
705 		acpi_activate_device(handle, &devinfo);
706 #endif
707 
708 	case ACPI_TYPE_PROCESSOR:
709 	case ACPI_TYPE_THERMAL:
710 	case ACPI_TYPE_POWER:
711 
712 		ad = malloc(sizeof(*ad), M_ACPI, M_NOWAIT | M_ZERO);
713 
714 		if (ad == NULL)
715 			return AE_NO_MEMORY;
716 
717 		ad->ad_device = NULL;
718 		ad->ad_notify = NULL;
719 		ad->ad_pciinfo = NULL;
720 
721 		ad->ad_type = type;
722 		ad->ad_handle = handle;
723 		ad->ad_devinfo = devinfo;
724 
725 		ad->ad_root = sc->sc_dev;
726 		ad->ad_parent = awc->aw_parent;
727 
728 		anu = (ACPI_NAME_UNION *)&devinfo->Name;
729 		ad->ad_name[4] = '\0';
730 
731 		for (i = 3, clear = 0; i >= 0; i--) {
732 
733 			if (clear == 0 && anu->Ascii[i] == '_')
734 				ad->ad_name[i] = '\0';
735 			else {
736 				ad->ad_name[i] = anu->Ascii[i];
737 				clear = 1;
738 			}
739 		}
740 
741 		if (ad->ad_name[0] == '\0')
742 			ad->ad_name[0] = '_';
743 
744 		SIMPLEQ_INIT(&ad->ad_child_head);
745 		SIMPLEQ_INSERT_TAIL(&sc->ad_head, ad, ad_list);
746 
747 		acpi_set_node(ad);
748 
749 		if (ad->ad_parent != NULL) {
750 
751 			SIMPLEQ_INSERT_TAIL(&ad->ad_parent->ad_child_head,
752 			    ad, ad_child_list);
753 		}
754 
755 		awc->aw_parent = ad;
756 	}
757 
758 	return AE_OK;
759 }
760 
761 static ACPI_STATUS
762 acpi_make_devnode_post(ACPI_HANDLE handle, uint32_t level,
763     void *context, void **status)
764 {
765 	struct acpi_walkcontext *awc = context;
766 
767 	KASSERT(awc != NULL);
768 	KASSERT(awc->aw_parent != NULL);
769 
770 	if (handle == awc->aw_parent->ad_handle)
771 		awc->aw_parent = awc->aw_parent->ad_parent;
772 
773 	return AE_OK;
774 }
775 
776 #ifdef ACPI_ACTIVATE_DEV
777 static void
778 acpi_activate_device(ACPI_HANDLE handle, ACPI_DEVICE_INFO **di)
779 {
780 	static const int valid = ACPI_VALID_STA | ACPI_VALID_HID;
781 	ACPI_DEVICE_INFO *newdi;
782 	ACPI_STATUS rv;
783 	uint32_t old;
784 
785 	/*
786 	 * If the device is valid and present,
787 	 * but not enabled, try to activate it.
788 	 */
789 	if (((*di)->Valid & valid) != valid)
790 		return;
791 
792 	old = (*di)->CurrentStatus;
793 
794 	if ((old & (ACPI_STA_DEVICE_PRESENT | ACPI_STA_DEVICE_ENABLED)) !=
795 	    ACPI_STA_DEVICE_PRESENT)
796 		return;
797 
798 	rv = acpi_allocate_resources(handle);
799 
800 	if (ACPI_FAILURE(rv))
801 		goto fail;
802 
803 	rv = AcpiGetObjectInfo(handle, &newdi);
804 
805 	if (ACPI_FAILURE(rv))
806 		goto fail;
807 
808 	ACPI_FREE(*di);
809 	*di = newdi;
810 
811 	aprint_verbose_dev(acpi_softc->sc_dev,
812 	    "%s activated, STA 0x%08X -> STA 0x%08X\n",
813 	    (*di)->HardwareId.String, old, (*di)->CurrentStatus);
814 
815 	return;
816 
817 fail:
818 	aprint_error_dev(acpi_softc->sc_dev, "failed to "
819 	    "activate %s\n", (*di)->HardwareId.String);
820 }
821 
822 /*
823  * XXX: This very incomplete.
824  */
825 ACPI_STATUS
826 acpi_allocate_resources(ACPI_HANDLE handle)
827 {
828 	ACPI_BUFFER bufp, bufc, bufn;
829 	ACPI_RESOURCE *resp, *resc, *resn;
830 	ACPI_RESOURCE_IRQ *irq;
831 	ACPI_RESOURCE_EXTENDED_IRQ *xirq;
832 	ACPI_STATUS rv;
833 	uint delta;
834 
835 	rv = acpi_get(handle, &bufp, AcpiGetPossibleResources);
836 	if (ACPI_FAILURE(rv))
837 		goto out;
838 	rv = acpi_get(handle, &bufc, AcpiGetCurrentResources);
839 	if (ACPI_FAILURE(rv)) {
840 		goto out1;
841 	}
842 
843 	bufn.Length = 1000;
844 	bufn.Pointer = resn = malloc(bufn.Length, M_ACPI, M_WAITOK);
845 	resp = bufp.Pointer;
846 	resc = bufc.Pointer;
847 	while (resc->Type != ACPI_RESOURCE_TYPE_END_TAG &&
848 	       resp->Type != ACPI_RESOURCE_TYPE_END_TAG) {
849 		while (resc->Type != resp->Type && resp->Type != ACPI_RESOURCE_TYPE_END_TAG)
850 			resp = ACPI_NEXT_RESOURCE(resp);
851 		if (resp->Type == ACPI_RESOURCE_TYPE_END_TAG)
852 			break;
853 		/* Found identical Id */
854 		resn->Type = resc->Type;
855 		switch (resc->Type) {
856 		case ACPI_RESOURCE_TYPE_IRQ:
857 			memcpy(&resn->Data, &resp->Data,
858 			       sizeof(ACPI_RESOURCE_IRQ));
859 			irq = (ACPI_RESOURCE_IRQ *)&resn->Data;
860 			irq->Interrupts[0] =
861 			    ((ACPI_RESOURCE_IRQ *)&resp->Data)->
862 			        Interrupts[irq->InterruptCount-1];
863 			irq->InterruptCount = 1;
864 			resn->Length = ACPI_RS_SIZE(ACPI_RESOURCE_IRQ);
865 			break;
866 		case ACPI_RESOURCE_TYPE_EXTENDED_IRQ:
867 			memcpy(&resn->Data, &resp->Data,
868 			       sizeof(ACPI_RESOURCE_EXTENDED_IRQ));
869 			xirq = (ACPI_RESOURCE_EXTENDED_IRQ *)&resn->Data;
870 #if 0
871 			/*
872 			 * XXX:	Not duplicating the interrupt logic above
873 			 *	because its not clear what it accomplishes.
874 			 */
875 			xirq->Interrupts[0] =
876 			    ((ACPI_RESOURCE_EXT_IRQ *)&resp->Data)->
877 			    Interrupts[irq->NumberOfInterrupts-1];
878 			xirq->NumberOfInterrupts = 1;
879 #endif
880 			resn->Length = ACPI_RS_SIZE(ACPI_RESOURCE_EXTENDED_IRQ);
881 			break;
882 		case ACPI_RESOURCE_TYPE_IO:
883 			memcpy(&resn->Data, &resp->Data,
884 			       sizeof(ACPI_RESOURCE_IO));
885 			resn->Length = resp->Length;
886 			break;
887 		default:
888 			aprint_error_dev(acpi_softc->sc_dev,
889 			    "%s: invalid type %u\n", __func__, resc->Type);
890 			rv = AE_BAD_DATA;
891 			goto out2;
892 		}
893 		resc = ACPI_NEXT_RESOURCE(resc);
894 		resn = ACPI_NEXT_RESOURCE(resn);
895 		resp = ACPI_NEXT_RESOURCE(resp);
896 		delta = (uint8_t *)resn - (uint8_t *)bufn.Pointer;
897 		if (delta >=
898 		    bufn.Length-ACPI_RS_SIZE(ACPI_RESOURCE_DATA)) {
899 			bufn.Length *= 2;
900 			bufn.Pointer = realloc(bufn.Pointer, bufn.Length,
901 					       M_ACPI, M_WAITOK);
902 			resn = (ACPI_RESOURCE *)((uint8_t *)bufn.Pointer +
903 			    delta);
904 		}
905 	}
906 
907 	if (resc->Type != ACPI_RESOURCE_TYPE_END_TAG) {
908 		aprint_error_dev(acpi_softc->sc_dev,
909 		    "%s: resc not exhausted\n", __func__);
910 		rv = AE_BAD_DATA;
911 		goto out3;
912 	}
913 
914 	resn->Type = ACPI_RESOURCE_TYPE_END_TAG;
915 	rv = AcpiSetCurrentResources(handle, &bufn);
916 
917 	if (ACPI_FAILURE(rv))
918 		aprint_error_dev(acpi_softc->sc_dev, "%s: failed to set "
919 		    "resources: %s\n", __func__, AcpiFormatException(rv));
920 
921 out3:
922 	free(bufn.Pointer, M_ACPI);
923 out2:
924 	ACPI_FREE(bufc.Pointer);
925 out1:
926 	ACPI_FREE(bufp.Pointer);
927 out:
928 	return rv;
929 }
930 #endif /* ACPI_ACTIVATE_DEV */
931 
932 /*
933  * Device attachment.
934  */
935 static int
936 acpi_rescan(device_t self, const char *ifattr, const int *locators)
937 {
938 	struct acpi_softc *sc = device_private(self);
939 
940 	if (ifattr_match(ifattr, "acpinodebus"))
941 		acpi_rescan_nodes(sc);
942 
943 	if (ifattr_match(ifattr, "acpiapmbus") && sc->sc_apmbus == NULL)
944 		sc->sc_apmbus = config_found_ia(sc->sc_dev,
945 		    "acpiapmbus", NULL, NULL);
946 
947 	return 0;
948 }
949 
950 static void
951 acpi_rescan_nodes(struct acpi_softc *sc)
952 {
953 	struct acpi_attach_args aa;
954 	struct acpi_devnode *ad;
955 	ACPI_DEVICE_INFO *di;
956 
957 	SIMPLEQ_FOREACH(ad, &sc->ad_head, ad_list) {
958 
959 		if (ad->ad_device != NULL)
960 			continue;
961 
962 		/*
963 		 * There is a bug in ACPICA: it defines the type
964 		 * of the scopes incorrectly for its own reasons.
965 		 */
966 		if (acpi_is_scope(ad) != false)
967 			continue;
968 
969 		di = ad->ad_devinfo;
970 
971 		/*
972 		 * We only attach devices which are present, enabled, and
973 		 * functioning properly. However, if a device is enabled,
974 		 * it is decoding resources and we should claim these,
975 		 * if possible. This requires changes to bus_space(9).
976 		 * Note: there is a possible race condition, because _STA
977 		 * may have changed since di->CurrentStatus was set.
978 		 */
979 		if (di->Type == ACPI_TYPE_DEVICE) {
980 
981 			if ((di->Valid & ACPI_VALID_STA) != 0 &&
982 			    (di->CurrentStatus & ACPI_STA_OK) != ACPI_STA_OK)
983 				continue;
984 		}
985 
986 		/*
987 		 * Handled internally.
988 		 */
989 		if (di->Type == ACPI_TYPE_POWER)
990 			continue;
991 
992 		/*
993 		 * Skip ignored HIDs.
994 		 */
995 		if (acpi_match_hid(di, acpi_ignored_ids))
996 			continue;
997 
998 		aa.aa_node = ad;
999 		aa.aa_iot = sc->sc_iot;
1000 		aa.aa_memt = sc->sc_memt;
1001 		aa.aa_pc = sc->sc_pc;
1002 		aa.aa_pciflags = sc->sc_pciflags;
1003 		aa.aa_ic = sc->sc_ic;
1004 
1005 		ad->ad_device = config_found_ia(sc->sc_dev,
1006 		    "acpinodebus", &aa, acpi_print);
1007 	}
1008 }
1009 
1010 static void
1011 acpi_rescan_capabilities(struct acpi_softc *sc)
1012 {
1013 	struct acpi_devnode *ad;
1014 	ACPI_HANDLE tmp;
1015 	ACPI_STATUS rv;
1016 
1017 	SIMPLEQ_FOREACH(ad, &sc->ad_head, ad_list) {
1018 
1019 		if (ad->ad_devinfo->Type != ACPI_TYPE_DEVICE)
1020 			continue;
1021 
1022 		/*
1023 		 * Scan power resource capabilities.
1024 		 *
1025 		 * If any power states are supported,
1026 		 * at least _PR0 and _PR3 must be present.
1027 		 */
1028 		rv = AcpiGetHandle(ad->ad_handle, "_PR0", &tmp);
1029 
1030 		if (ACPI_SUCCESS(rv)) {
1031 			ad->ad_flags |= ACPI_DEVICE_POWER;
1032 			acpi_power_add(ad);
1033 		}
1034 
1035 		/*
1036 		 * Scan wake-up capabilities.
1037 		 */
1038 		rv = AcpiGetHandle(ad->ad_handle, "_PRW", &tmp);
1039 
1040 		if (ACPI_SUCCESS(rv)) {
1041 			ad->ad_flags |= ACPI_DEVICE_WAKEUP;
1042 			acpi_wakedev_add(ad);
1043 		}
1044 	}
1045 }
1046 
1047 static int
1048 acpi_print(void *aux, const char *pnp)
1049 {
1050 	struct acpi_attach_args *aa = aux;
1051 	ACPI_STATUS rv;
1052 
1053 	if (pnp) {
1054 		if (aa->aa_node->ad_devinfo->Valid & ACPI_VALID_HID) {
1055 			char *pnpstr =
1056 			    aa->aa_node->ad_devinfo->HardwareId.String;
1057 			ACPI_BUFFER buf;
1058 
1059 			aprint_normal("%s (%s) ", aa->aa_node->ad_name,
1060 			    pnpstr);
1061 
1062 			rv = acpi_eval_struct(aa->aa_node->ad_handle,
1063 			    "_STR", &buf);
1064 			if (ACPI_SUCCESS(rv)) {
1065 				ACPI_OBJECT *obj = buf.Pointer;
1066 				switch (obj->Type) {
1067 				case ACPI_TYPE_STRING:
1068 					aprint_normal("[%s] ", obj->String.Pointer);
1069 					break;
1070 				case ACPI_TYPE_BUFFER:
1071 					aprint_normal("buffer %p ", obj->Buffer.Pointer);
1072 					break;
1073 				default:
1074 					aprint_normal("type %u ",obj->Type);
1075 					break;
1076 				}
1077 				ACPI_FREE(buf.Pointer);
1078 			}
1079 			else
1080 				acpi_print_dev(pnpstr);
1081 
1082 			aprint_normal("at %s", pnp);
1083 		} else if (aa->aa_node->ad_devinfo->Type != ACPI_TYPE_DEVICE) {
1084 			aprint_normal("%s (ACPI Object Type '%s' "
1085 			    "[0x%02x]) ", aa->aa_node->ad_name,
1086 			     AcpiUtGetTypeName(aa->aa_node->ad_devinfo->Type),
1087 			     aa->aa_node->ad_devinfo->Type);
1088 			aprint_normal("at %s", pnp);
1089 		} else
1090 			return 0;
1091 	} else {
1092 		aprint_normal(" (%s", aa->aa_node->ad_name);
1093 		if (aa->aa_node->ad_devinfo->Valid & ACPI_VALID_HID) {
1094 			aprint_normal(", %s", aa->aa_node->ad_devinfo->HardwareId.String);
1095 			if (aa->aa_node->ad_devinfo->Valid & ACPI_VALID_UID) {
1096 				const char *uid;
1097 
1098 				uid = aa->aa_node->ad_devinfo->UniqueId.String;
1099 				if (uid[0] == '\0')
1100 					uid = "<null>";
1101 				aprint_normal("-%s", uid);
1102 			}
1103 		}
1104 		aprint_normal(")");
1105 	}
1106 
1107 	return UNCONF;
1108 }
1109 
1110 /*
1111  * Notify.
1112  */
1113 static void
1114 acpi_notify_handler(ACPI_HANDLE handle, uint32_t event, void *aux)
1115 {
1116 	struct acpi_softc *sc = acpi_softc;
1117 	struct acpi_devnode *ad;
1118 
1119 	KASSERT(sc != NULL);
1120 	KASSERT(aux == NULL);
1121 	KASSERT(acpi_active != 0);
1122 
1123 	if (acpi_suspended != 0)
1124 		return;
1125 
1126 	/*
1127 	 *  System: 0x00 - 0x7F.
1128 	 *  Device: 0x80 - 0xFF.
1129 	 */
1130 	switch (event) {
1131 
1132 	case ACPI_NOTIFY_BUS_CHECK:
1133 	case ACPI_NOTIFY_DEVICE_CHECK:
1134 	case ACPI_NOTIFY_DEVICE_WAKE:
1135 	case ACPI_NOTIFY_EJECT_REQUEST:
1136 	case ACPI_NOTIFY_DEVICE_CHECK_LIGHT:
1137 	case ACPI_NOTIFY_FREQUENCY_MISMATCH:
1138 	case ACPI_NOTIFY_BUS_MODE_MISMATCH:
1139 	case ACPI_NOTIFY_POWER_FAULT:
1140 	case ACPI_NOTIFY_CAPABILITIES_CHECK:
1141 	case ACPI_NOTIFY_DEVICE_PLD_CHECK:
1142 	case ACPI_NOTIFY_RESERVED:
1143 	case ACPI_NOTIFY_LOCALITY_UPDATE:
1144 		break;
1145 	}
1146 
1147 	ACPI_DEBUG_PRINT((ACPI_DB_INFO, "notification 0x%02X for "
1148 		"%s (%p)\n", event, acpi_name(handle), handle));
1149 
1150 	/*
1151 	 * We deliver notifications only to drivers
1152 	 * that have been succesfully attached and
1153 	 * that have registered a handler with us.
1154 	 * The opaque pointer is always the device_t.
1155 	 */
1156 	SIMPLEQ_FOREACH(ad, &sc->ad_head, ad_list) {
1157 
1158 		if (ad->ad_device == NULL)
1159 			continue;
1160 
1161 		if (ad->ad_notify == NULL)
1162 			continue;
1163 
1164 		if (ad->ad_handle != handle)
1165 			continue;
1166 
1167 		(*ad->ad_notify)(ad->ad_handle, event, ad->ad_device);
1168 
1169 		return;
1170 	}
1171 
1172 	aprint_debug_dev(sc->sc_dev, "unhandled notify 0x%02X "
1173 	    "for %s (%p)\n", event, acpi_name(handle), handle);
1174 }
1175 
1176 bool
1177 acpi_register_notify(struct acpi_devnode *ad, ACPI_NOTIFY_HANDLER notify)
1178 {
1179 	struct acpi_softc *sc = acpi_softc;
1180 
1181 	KASSERT(sc != NULL);
1182 	KASSERT(acpi_active != 0);
1183 
1184 	if (acpi_suspended != 0)
1185 		goto fail;
1186 
1187 	if (ad == NULL || notify == NULL)
1188 		goto fail;
1189 
1190 	ad->ad_notify = notify;
1191 
1192 	return true;
1193 
1194 fail:
1195 	aprint_error_dev(sc->sc_dev, "failed to register notify "
1196 	    "handler for %s (%p)\n", ad->ad_name, ad->ad_handle);
1197 
1198 	return false;
1199 }
1200 
1201 void
1202 acpi_deregister_notify(struct acpi_devnode *ad)
1203 {
1204 
1205 	ad->ad_notify = NULL;
1206 }
1207 
1208 /*
1209  * Fixed buttons.
1210  */
1211 static void
1212 acpi_register_fixed_button(struct acpi_softc *sc, int event)
1213 {
1214 	struct sysmon_pswitch *smpsw;
1215 	ACPI_STATUS rv;
1216 	int type;
1217 
1218 	switch (event) {
1219 
1220 	case ACPI_EVENT_POWER_BUTTON:
1221 
1222 		if ((AcpiGbl_FADT.Flags & ACPI_FADT_POWER_BUTTON) != 0)
1223 			return;
1224 
1225 		type = PSWITCH_TYPE_POWER;
1226 		smpsw = &sc->sc_smpsw_power;
1227 		break;
1228 
1229 	case ACPI_EVENT_SLEEP_BUTTON:
1230 
1231 		if ((AcpiGbl_FADT.Flags & ACPI_FADT_SLEEP_BUTTON) != 0)
1232 			return;
1233 
1234 		type = PSWITCH_TYPE_SLEEP;
1235 		smpsw = &sc->sc_smpsw_sleep;
1236 		break;
1237 
1238 	default:
1239 		rv = AE_TYPE;
1240 		goto fail;
1241 	}
1242 
1243 	smpsw->smpsw_type = type;
1244 	smpsw->smpsw_name = device_xname(sc->sc_dev);
1245 
1246 	if (sysmon_pswitch_register(smpsw) != 0) {
1247 		rv = AE_ERROR;
1248 		goto fail;
1249 	}
1250 
1251 	rv = AcpiInstallFixedEventHandler(event,
1252 	    acpi_fixed_button_handler, smpsw);
1253 
1254 	if (ACPI_FAILURE(rv)) {
1255 		sysmon_pswitch_unregister(smpsw);
1256 		goto fail;
1257 	}
1258 
1259 	aprint_debug_dev(sc->sc_dev, "fixed %s button present\n",
1260 	    (type != ACPI_EVENT_SLEEP_BUTTON) ? "power" : "sleep");
1261 
1262 	return;
1263 
1264 fail:
1265 	aprint_error_dev(sc->sc_dev, "failed to register "
1266 	    "fixed event: %s\n", AcpiFormatException(rv));
1267 }
1268 
1269 static void
1270 acpi_deregister_fixed_button(struct acpi_softc *sc, int event)
1271 {
1272 	struct sysmon_pswitch *smpsw;
1273 	ACPI_STATUS rv;
1274 
1275 	switch (event) {
1276 
1277 	case ACPI_EVENT_POWER_BUTTON:
1278 		smpsw = &sc->sc_smpsw_power;
1279 
1280 		if ((AcpiGbl_FADT.Flags & ACPI_FADT_POWER_BUTTON) != 0) {
1281 			KASSERT(smpsw->smpsw_type != PSWITCH_TYPE_POWER);
1282 			return;
1283 		}
1284 
1285 		break;
1286 
1287 	case ACPI_EVENT_SLEEP_BUTTON:
1288 		smpsw = &sc->sc_smpsw_sleep;
1289 
1290 		if ((AcpiGbl_FADT.Flags & ACPI_FADT_SLEEP_BUTTON) != 0) {
1291 			KASSERT(smpsw->smpsw_type != PSWITCH_TYPE_SLEEP);
1292 			return;
1293 		}
1294 
1295 		break;
1296 
1297 	default:
1298 		rv = AE_TYPE;
1299 		goto fail;
1300 	}
1301 
1302 	rv = AcpiRemoveFixedEventHandler(event, acpi_fixed_button_handler);
1303 
1304 	if (ACPI_SUCCESS(rv)) {
1305 		sysmon_pswitch_unregister(smpsw);
1306 		return;
1307 	}
1308 
1309 fail:
1310 	aprint_error_dev(sc->sc_dev, "failed to deregister "
1311 	    "fixed event: %s\n", AcpiFormatException(rv));
1312 }
1313 
1314 static uint32_t
1315 acpi_fixed_button_handler(void *context)
1316 {
1317 	static const int handler = OSL_NOTIFY_HANDLER;
1318 	struct sysmon_pswitch *smpsw = context;
1319 
1320 	(void)AcpiOsExecute(handler, acpi_fixed_button_pressed, smpsw);
1321 
1322 	return ACPI_INTERRUPT_HANDLED;
1323 }
1324 
1325 static void
1326 acpi_fixed_button_pressed(void *context)
1327 {
1328 	struct sysmon_pswitch *smpsw = context;
1329 
1330 	ACPI_DEBUG_PRINT((ACPI_DB_INFO, "%s fixed button pressed\n",
1331 		(smpsw->smpsw_type != ACPI_EVENT_SLEEP_BUTTON) ?
1332 		"power" : "sleep"));
1333 
1334 	sysmon_pswitch_event(smpsw, PSWITCH_EVENT_PRESSED);
1335 }
1336 
1337 /*
1338  * Sleep.
1339  */
1340 static void
1341 acpi_sleep_init(struct acpi_softc *sc)
1342 {
1343 	uint8_t a, b, i;
1344 	ACPI_STATUS rv;
1345 
1346 	CTASSERT(ACPI_STATE_S0 == 0 && ACPI_STATE_S1 == 1);
1347 	CTASSERT(ACPI_STATE_S2 == 2 && ACPI_STATE_S3 == 3);
1348 	CTASSERT(ACPI_STATE_S4 == 4 && ACPI_STATE_S5 == 5);
1349 
1350 	/*
1351 	 * Evaluate supported sleep states.
1352 	 */
1353 	for (i = ACPI_STATE_S0; i <= ACPI_STATE_S5; i++) {
1354 
1355 		rv = AcpiGetSleepTypeData(i, &a, &b);
1356 
1357 		if (ACPI_SUCCESS(rv))
1358 			sc->sc_sleepstates |= __BIT(i);
1359 	}
1360 }
1361 
1362 void
1363 acpi_enter_sleep_state(int state)
1364 {
1365 	struct acpi_softc *sc = acpi_softc;
1366 	ACPI_STATUS rv;
1367 	int err;
1368 
1369 	if (acpi_softc == NULL)
1370 		return;
1371 
1372 	if (state == sc->sc_sleepstate)
1373 		return;
1374 
1375 	if (state < ACPI_STATE_S0 || state > ACPI_STATE_S5)
1376 		return;
1377 
1378 	aprint_normal_dev(sc->sc_dev, "entering state S%d\n", state);
1379 
1380 	switch (state) {
1381 
1382 	case ACPI_STATE_S0:
1383 		sc->sc_sleepstate = ACPI_STATE_S0;
1384 		return;
1385 
1386 	case ACPI_STATE_S1:
1387 	case ACPI_STATE_S2:
1388 	case ACPI_STATE_S3:
1389 	case ACPI_STATE_S4:
1390 
1391 		if ((sc->sc_sleepstates & __BIT(state)) == 0) {
1392 			aprint_error_dev(sc->sc_dev, "sleep state "
1393 			    "S%d is not available\n", state);
1394 			return;
1395 		}
1396 
1397 		/*
1398 		 * Evaluate the _TTS method. This should be done before
1399 		 * pmf_system_suspend(9) and the evaluation of _PTS.
1400 		 * We should also re-evaluate this once we return to
1401 		 * S0 or if we abort the sleep state transition in the
1402 		 * middle (see ACPI 3.0, section 7.3.6). In reality,
1403 		 * however, the _TTS method is seldom seen in the field.
1404 		 */
1405 		rv = acpi_eval_set_integer(NULL, "\\_TTS", state);
1406 
1407 		if (ACPI_SUCCESS(rv))
1408 			aprint_debug_dev(sc->sc_dev, "evaluated _TTS\n");
1409 
1410 		if (state != ACPI_STATE_S1 &&
1411 		    pmf_system_suspend(PMF_Q_NONE) != true) {
1412 			aprint_error_dev(sc->sc_dev, "aborting suspend\n");
1413 			break;
1414 		}
1415 
1416 		/*
1417 		 * This will evaluate the  _PTS and _SST methods,
1418 		 * but unlike the documentation claims, not _GTS,
1419 		 * which is evaluated in AcpiEnterSleepState().
1420 		 * This must be called with interrupts enabled.
1421 		 */
1422 		rv = AcpiEnterSleepStatePrep(state);
1423 
1424 		if (ACPI_FAILURE(rv)) {
1425 			aprint_error_dev(sc->sc_dev, "failed to prepare "
1426 			    "S%d: %s\n", state, AcpiFormatException(rv));
1427 			break;
1428 		}
1429 
1430 		/*
1431 		 * After the _PTS method has been evaluated, we can
1432 		 * enable wake and evaluate _PSW (ACPI 4.0, p. 284).
1433 		 */
1434 		acpi_wakedev_commit(sc, state);
1435 
1436 		sc->sc_sleepstate = state;
1437 
1438 		if (state == ACPI_STATE_S1) {
1439 
1440 			/* Just enter the state. */
1441 			acpi_md_OsDisableInterrupt();
1442 			rv = AcpiEnterSleepState(state);
1443 
1444 			if (ACPI_FAILURE(rv))
1445 				aprint_error_dev(sc->sc_dev, "failed to "
1446 				    "enter S1: %s\n", AcpiFormatException(rv));
1447 
1448 			(void)AcpiLeaveSleepState(state);
1449 
1450 		} else {
1451 
1452 			err = acpi_md_sleep(state);
1453 
1454 			if (state == ACPI_STATE_S4)
1455 				AcpiEnable();
1456 
1457 			pmf_system_bus_resume(PMF_Q_NONE);
1458 			(void)AcpiLeaveSleepState(state);
1459 			pmf_system_resume(PMF_Q_NONE);
1460 		}
1461 
1462 		break;
1463 
1464 	case ACPI_STATE_S5:
1465 
1466 		(void)acpi_eval_set_integer(NULL, "\\_TTS", ACPI_STATE_S5);
1467 
1468 		rv = AcpiEnterSleepStatePrep(ACPI_STATE_S5);
1469 
1470 		if (ACPI_FAILURE(rv)) {
1471 			aprint_error_dev(sc->sc_dev, "failed to prepare "
1472 			    "S%d: %s\n", state, AcpiFormatException(rv));
1473 			break;
1474 		}
1475 
1476 		DELAY(1000000);
1477 
1478 		sc->sc_sleepstate = state;
1479 		acpi_md_OsDisableInterrupt();
1480 
1481 		(void)AcpiEnterSleepState(ACPI_STATE_S5);
1482 
1483 		aprint_error_dev(sc->sc_dev, "WARNING: powerdown failed!\n");
1484 
1485 		break;
1486 	}
1487 
1488 	sc->sc_sleepstate = ACPI_STATE_S0;
1489 
1490 	(void)acpi_eval_set_integer(NULL, "\\_TTS", ACPI_STATE_S0);
1491 }
1492 
1493 /*
1494  * Sysctl.
1495  */
1496 SYSCTL_SETUP(sysctl_acpi_setup, "sysctl hw.acpi subtree setup")
1497 {
1498 	const struct sysctlnode *mnode, *rnode;
1499 	int err;
1500 
1501 	err = sysctl_createv(clog, 0, NULL, &rnode,
1502 	    CTLFLAG_PERMANENT, CTLTYPE_NODE, "hw",
1503 	    NULL, NULL, 0, NULL, 0,
1504 	    CTL_HW, CTL_EOL);
1505 
1506 	if (err != 0)
1507 		return;
1508 
1509 	err = sysctl_createv(clog, 0, &rnode, &rnode,
1510 	    CTLFLAG_PERMANENT, CTLTYPE_NODE,
1511 	    "acpi", SYSCTL_DESCR("ACPI subsystem parameters"),
1512 	    NULL, 0, NULL, 0,
1513 	    CTL_CREATE, CTL_EOL);
1514 
1515 	if (err != 0)
1516 		return;
1517 
1518 	(void)sysctl_createv(NULL, 0, &rnode, NULL,
1519 	    CTLFLAG_PERMANENT | CTLFLAG_READONLY, CTLTYPE_QUAD,
1520 	    "root", SYSCTL_DESCR("ACPI root pointer"),
1521 	    NULL, 0, &acpi_root_pointer, sizeof(acpi_root_pointer),
1522 	    CTL_CREATE, CTL_EOL);
1523 
1524 	(void)sysctl_createv(NULL, 0, &rnode, NULL,
1525 	    CTLFLAG_PERMANENT | CTLFLAG_READONLY, CTLTYPE_STRING,
1526 	    "supported_states", SYSCTL_DESCR("Supported system states"),
1527 	    sysctl_hw_acpi_sleepstates, 0, NULL, 0,
1528 	    CTL_CREATE, CTL_EOL);
1529 
1530 	err = sysctl_createv(NULL, 0, NULL, &mnode,
1531 	    CTLFLAG_PERMANENT, CTLTYPE_NODE, "machdep",
1532 	    NULL, NULL, 0, NULL, 0,
1533 	    CTL_MACHDEP, CTL_EOL);
1534 
1535 	if (err == 0) {
1536 
1537 		(void)sysctl_createv(NULL, 0, &mnode, NULL,
1538 		    CTLFLAG_PERMANENT | CTLFLAG_READWRITE, CTLTYPE_INT,
1539 		    "sleep_state", SYSCTL_DESCR("System sleep state"),
1540 		    sysctl_hw_acpi_sleepstate, 0, NULL, 0,
1541 		    CTL_CREATE, CTL_EOL);
1542 	}
1543 
1544 	err = sysctl_createv(clog, 0, &rnode, &rnode,
1545 	    CTLFLAG_PERMANENT, CTLTYPE_NODE,
1546 	    "stat", SYSCTL_DESCR("ACPI statistics"),
1547 	    NULL, 0, NULL, 0,
1548 	    CTL_CREATE, CTL_EOL);
1549 
1550 	if (err != 0)
1551 		return;
1552 
1553 	(void)sysctl_createv(clog, 0, &rnode, NULL,
1554 	    CTLFLAG_PERMANENT | CTLFLAG_READONLY, CTLTYPE_QUAD,
1555 	    "gpe", SYSCTL_DESCR("Number of dispatched GPEs"),
1556 	    NULL, 0, &AcpiGpeCount, sizeof(AcpiGpeCount),
1557 	    CTL_CREATE, CTL_EOL);
1558 
1559 	(void)sysctl_createv(clog, 0, &rnode, NULL,
1560 	    CTLFLAG_PERMANENT | CTLFLAG_READONLY, CTLTYPE_QUAD,
1561 	    "sci", SYSCTL_DESCR("Number of SCI interrupts"),
1562 	    NULL, 0, &AcpiSciCount, sizeof(AcpiSciCount),
1563 	    CTL_CREATE, CTL_EOL);
1564 
1565 	(void)sysctl_createv(clog, 0, &rnode, NULL,
1566 	    CTLFLAG_PERMANENT | CTLFLAG_READONLY, CTLTYPE_QUAD,
1567 	    "fixed", SYSCTL_DESCR("Number of fixed events"),
1568 	    sysctl_hw_acpi_fixedstats, 0, NULL, 0,
1569 	    CTL_CREATE, CTL_EOL);
1570 
1571 	(void)sysctl_createv(clog, 0, &rnode, NULL,
1572 	    CTLFLAG_PERMANENT | CTLFLAG_READONLY, CTLTYPE_QUAD,
1573 	    "method", SYSCTL_DESCR("Number of methods executed"),
1574 	    NULL, 0, &AcpiMethodCount, sizeof(AcpiMethodCount),
1575 	    CTL_CREATE, CTL_EOL);
1576 
1577 	CTASSERT(sizeof(AcpiGpeCount) == sizeof(uint64_t));
1578 	CTASSERT(sizeof(AcpiSciCount) == sizeof(uint64_t));
1579 }
1580 
1581 static int
1582 sysctl_hw_acpi_fixedstats(SYSCTLFN_ARGS)
1583 {
1584 	struct sysctlnode node;
1585 	uint64_t t;
1586 	int err, i;
1587 
1588 	for (i = t = 0; i < __arraycount(AcpiFixedEventCount); i++)
1589 		t += AcpiFixedEventCount[i];
1590 
1591 	node = *rnode;
1592 	node.sysctl_data = &t;
1593 
1594 	err = sysctl_lookup(SYSCTLFN_CALL(&node));
1595 
1596 	if (err || newp == NULL)
1597 		return err;
1598 
1599 	return 0;
1600 }
1601 
1602 static int
1603 sysctl_hw_acpi_sleepstate(SYSCTLFN_ARGS)
1604 {
1605 	struct acpi_softc *sc = acpi_softc;
1606 	struct sysctlnode node;
1607 	int err, t;
1608 
1609 	if (acpi_softc == NULL)
1610 		return ENOSYS;
1611 
1612 	node = *rnode;
1613 	t = sc->sc_sleepstate;
1614 	node.sysctl_data = &t;
1615 
1616 	err = sysctl_lookup(SYSCTLFN_CALL(&node));
1617 
1618 	if (err || newp == NULL)
1619 		return err;
1620 
1621 	if (t < ACPI_STATE_S0 || t > ACPI_STATE_S5)
1622 		return EINVAL;
1623 
1624 	acpi_enter_sleep_state(t);
1625 
1626 	return 0;
1627 }
1628 
1629 static int
1630 sysctl_hw_acpi_sleepstates(SYSCTLFN_ARGS)
1631 {
1632 	struct acpi_softc *sc = acpi_softc;
1633 	struct sysctlnode node;
1634 	char t[3 * 6 + 1];
1635 	int err;
1636 
1637 	if (acpi_softc == NULL)
1638 		return ENOSYS;
1639 
1640 	(void)memset(t, '\0', sizeof(t));
1641 
1642 	(void)snprintf(t, sizeof(t), "%s%s%s%s%s%s",
1643 	    ((sc->sc_sleepstates & __BIT(0)) != 0) ? "S0 " : "",
1644 	    ((sc->sc_sleepstates & __BIT(1)) != 0) ? "S1 " : "",
1645 	    ((sc->sc_sleepstates & __BIT(2)) != 0) ? "S2 " : "",
1646 	    ((sc->sc_sleepstates & __BIT(3)) != 0) ? "S3 " : "",
1647 	    ((sc->sc_sleepstates & __BIT(4)) != 0) ? "S4 " : "",
1648 	    ((sc->sc_sleepstates & __BIT(5)) != 0) ? "S5 " : "");
1649 
1650 	node = *rnode;
1651 	node.sysctl_data = &t;
1652 
1653 	err = sysctl_lookup(SYSCTLFN_CALL(&node));
1654 
1655 	if (err || newp == NULL)
1656 		return err;
1657 
1658 	return 0;
1659 }
1660 
1661 /*
1662  * Tables.
1663  */
1664 ACPI_PHYSICAL_ADDRESS
1665 acpi_OsGetRootPointer(void)
1666 {
1667 	ACPI_PHYSICAL_ADDRESS PhysicalAddress;
1668 
1669 	/*
1670 	 * We let MD code handle this since there are multiple ways to do it:
1671 	 *
1672 	 *	IA-32: Use AcpiFindRootPointer() to locate the RSDP.
1673 	 *
1674 	 *	IA-64: Use the EFI.
1675 	 */
1676 	PhysicalAddress = acpi_md_OsGetRootPointer();
1677 
1678 	if (acpi_root_pointer == 0)
1679 		acpi_root_pointer = PhysicalAddress;
1680 
1681 	return PhysicalAddress;
1682 }
1683 
1684 static ACPI_TABLE_HEADER *
1685 acpi_map_rsdt(void)
1686 {
1687 	ACPI_PHYSICAL_ADDRESS paddr;
1688 	ACPI_TABLE_RSDP *rsdp;
1689 
1690 	paddr = AcpiOsGetRootPointer();
1691 
1692 	if (paddr == 0)
1693 		return NULL;
1694 
1695 	rsdp = AcpiOsMapMemory(paddr, sizeof(ACPI_TABLE_RSDP));
1696 
1697 	if (rsdp == NULL)
1698 		return NULL;
1699 
1700 	if (rsdp->Revision > 1 && rsdp->XsdtPhysicalAddress)
1701 		paddr = rsdp->XsdtPhysicalAddress;
1702 	else
1703 		paddr = rsdp->RsdtPhysicalAddress;
1704 
1705 	AcpiOsUnmapMemory(rsdp, sizeof(ACPI_TABLE_RSDP));
1706 
1707 	return AcpiOsMapMemory(paddr, sizeof(ACPI_TABLE_HEADER));
1708 }
1709 
1710 static void
1711 acpi_unmap_rsdt(ACPI_TABLE_HEADER *rsdt)
1712 {
1713 
1714 	if (rsdt == NULL)
1715 		return;
1716 
1717 	AcpiOsUnmapMemory(rsdt, sizeof(ACPI_TABLE_HEADER));
1718 }
1719 
1720 /*
1721  * XXX: Refactor to be a generic function that maps tables.
1722  */
1723 ACPI_STATUS
1724 acpi_madt_map(void)
1725 {
1726 	ACPI_STATUS  rv;
1727 
1728 	if (madt_header != NULL)
1729 		return AE_ALREADY_EXISTS;
1730 
1731 	rv = AcpiGetTable(ACPI_SIG_MADT, 1, &madt_header);
1732 
1733 	if (ACPI_FAILURE(rv))
1734 		return rv;
1735 
1736 	return AE_OK;
1737 }
1738 
1739 void
1740 acpi_madt_unmap(void)
1741 {
1742 	madt_header = NULL;
1743 }
1744 
1745 /*
1746  * XXX: Refactor to be a generic function that walks tables.
1747  */
1748 void
1749 acpi_madt_walk(ACPI_STATUS (*func)(ACPI_SUBTABLE_HEADER *, void *), void *aux)
1750 {
1751 	ACPI_SUBTABLE_HEADER *hdrp;
1752 	char *madtend, *where;
1753 
1754 	madtend = (char *)madt_header + madt_header->Length;
1755 	where = (char *)madt_header + sizeof (ACPI_TABLE_MADT);
1756 
1757 	while (where < madtend) {
1758 
1759 		hdrp = (ACPI_SUBTABLE_HEADER *)where;
1760 
1761 		if (ACPI_FAILURE(func(hdrp, aux)))
1762 			break;
1763 
1764 		where += hdrp->Length;
1765 	}
1766 }
1767 
1768 /*
1769  * Miscellaneous.
1770  */
1771 static bool
1772 acpi_is_scope(struct acpi_devnode *ad)
1773 {
1774 	int i;
1775 
1776 	/*
1777 	 * Return true if the node is a root scope.
1778 	 */
1779 	if (ad->ad_parent == NULL)
1780 		return false;
1781 
1782 	if (ad->ad_parent->ad_handle != ACPI_ROOT_OBJECT)
1783 		return false;
1784 
1785 	for (i = 0; i < __arraycount(acpi_scopes); i++) {
1786 
1787 		if (acpi_scopes[i] == NULL)
1788 			continue;
1789 
1790 		if (ad->ad_handle == acpi_scopes[i])
1791 			return true;
1792 	}
1793 
1794 	return false;
1795 }
1796 
1797 /*
1798  * ACPIVERBOSE.
1799  */
1800 void
1801 acpi_load_verbose(void)
1802 {
1803 
1804 	if (acpi_verbose_loaded == 0)
1805 		module_autoload("acpiverbose", MODULE_CLASS_MISC);
1806 }
1807 
1808 void
1809 acpi_print_verbose_stub(struct acpi_softc *sc)
1810 {
1811 
1812 	acpi_load_verbose();
1813 
1814 	if (acpi_verbose_loaded != 0)
1815 		acpi_print_verbose(sc);
1816 }
1817 
1818 void
1819 acpi_print_dev_stub(const char *pnpstr)
1820 {
1821 
1822 	acpi_load_verbose();
1823 
1824 	if (acpi_verbose_loaded != 0)
1825 		acpi_print_dev(pnpstr);
1826 }
1827