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