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