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