code:
/* $OpenBSD: acpibtn.c,v 1.41 2015/01/27 19:40:14 kettenis Exp $ */
/*
 * Copyright (c) 2005 Marco Peereboom <marco@openbsd.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <sys/param.h>
#include <sys/signalvar.h>
#include <sys/systm.h>
#include <sys/device.h>
#include <sys/malloc.h>

#include <machine/bus.h>
#include <machine/apmvar.h>

#include <dev/acpi/acpireg.h>
#include <dev/acpi/acpivar.h>
#include <dev/acpi/acpidev.h>
#include <dev/acpi/amltypes.h>
#include <dev/acpi/dsdt.h>

#include <sys/sensors.h>

int	acpibtn_match(struct device *, void *, void *);
void	acpibtn_attach(struct device *, struct device *, void *);
int	acpibtn_notify(struct aml_node *, int, void *);

struct acpibtn_softc {
	struct device		sc_dev;

	bus_space_tag_t		sc_iot;
	bus_space_handle_t	sc_ioh;

	struct acpi_softc	*sc_acpi;
	struct aml_node		*sc_devnode;

	struct ksensor		sc_sens;
	struct ksensordev	sc_sensdev;

	int			sc_btn_type;
#define	ACPIBTN_UNKNOWN	0
#define ACPIBTN_LID	1
#define ACPIBTN_POWER	2
#define ACPIBTN_SLEEP	3
};

int	acpibtn_setpsw(struct acpibtn_softc *, int);

struct acpi_lid {
	struct acpibtn_softc	*abl_softc;
	SLIST_ENTRY(acpi_lid)	abl_link;
};
SLIST_HEAD(acpi_lid_head, acpi_lid) acpibtn_lids =
    SLIST_HEAD_INITIALIZER(acpibtn_lids);

struct cfattach acpibtn_ca = {
	sizeof(struct acpibtn_softc), acpibtn_match, acpibtn_attach
};

struct cfdriver acpibtn_cd = {
	NULL, "acpibtn", DV_DULL
};

const char *acpibtn_hids[] = { ACPI_DEV_LD, ACPI_DEV_PBD, ACPI_DEV_SBD, 0 };

/*
 * acpibtn_numopenlids
 *
 * Return the number of _LID devices that are in the "open" state.
 * Used to determine if we should go back to sleep/hibernate if we
 * woke up with the all the lids still closed for some reason. If
 * the machine has no lids, returns -1.
 */
int
acpibtn_numopenlids(void)
{
	struct acpi_lid *lid;
	int64_t val;
	int ct = 0;

	/* If we have no lids ... */
	if (SLIST_EMPTY(&acpibtn_lids))
		return (-1);

	/*
	 * Determine how many lids are open. Assumes _LID evals to
	 * non-0 or 0, for on / off (which is what the spec says).
	 */
	SLIST_FOREACH(lid, &acpibtn_lids, abl_link)
		if (!aml_evalinteger(lid->abl_softc->sc_acpi,
		    lid->abl_softc->sc_devnode, "_LID", 0, NULL, &val) &&
		    val != 0)
			ct++;
	return (ct);
}

int
acpibtn_setpsw(struct acpibtn_softc *sc, int psw)
{
	struct aml_value	val;

	bzero(&val, sizeof val);
	val.type = AML_OBJTYPE_INTEGER;
	val.v_integer = psw;
	val.length = 1;

	return (aml_evalname(sc->sc_acpi, sc->sc_devnode, "_PSW", 1, &val,
	    NULL));
}

void
acpibtn_disable_psw(void)
{
	struct acpi_lid *lid;

	/* disable _LID for wakeup */
	SLIST_FOREACH(lid, &acpibtn_lids, abl_link)
		acpibtn_setpsw(lid->abl_softc, 0);
}

void
acpibtn_enable_psw(void)
{
	struct acpi_lid		*lid;

	/* enable _LID for wakeup */
	SLIST_FOREACH(lid, &acpibtn_lids, abl_link)
		acpibtn_setpsw(lid->abl_softc, 1);
}

int
acpibtn_match(struct device *parent, void *match, void *aux)
{
	struct acpi_attach_args	*aa = aux;
	struct cfdata		*cf = match;

	/* sanity */
	return (acpi_matchhids(aa, acpibtn_hids, cf->cf_driver->cd_name));
}

void
acpibtn_attach(struct device *parent, struct device *self, void *aux)
{
	struct acpibtn_softc	*sc = (struct acpibtn_softc *)self;
	struct acpi_attach_args *aa = aux;
	struct acpi_lid		*lid;
	int64_t			lid_open;
	int64_t			st;

	sc->sc_acpi = (struct acpi_softc *)parent;
	sc->sc_devnode = aa->aaa_node;

	printf(": %s\n", sc->sc_devnode->name);

	if (aml_evalinteger(sc->sc_acpi, sc->sc_devnode, "_STA", 0, NULL, &st))
		st = STA_PRESENT | STA_ENABLED | STA_DEV_OK;
	if ((st & (STA_PRESENT | STA_ENABLED | STA_DEV_OK)) !=
	    (STA_PRESENT | STA_ENABLED | STA_DEV_OK))
		return;

	if (!strcmp(aa->aaa_dev, ACPI_DEV_LD)) {
		sc->sc_btn_type = ACPIBTN_LID;

		/* Set PSW (if present) to disable wake on this LID */
		(void)acpibtn_setpsw(sc, 0);
		lid = malloc(sizeof(*lid), M_DEVBUF, M_WAITOK | M_ZERO);
		lid->abl_softc = sc;
		SLIST_INSERT_HEAD(&acpibtn_lids, lid, abl_link);
	} else if (!strcmp(aa->aaa_dev, ACPI_DEV_PBD))
		sc->sc_btn_type = ACPIBTN_POWER;
	else if (!strcmp(aa->aaa_dev, ACPI_DEV_SBD))
		sc->sc_btn_type = ACPIBTN_SLEEP;

	if (sc->sc_btn_type == ACPIBTN_LID) {
		strlcpy(sc->sc_sensdev.xname, DEVNAME(sc),
		    sizeof(sc->sc_sensdev.xname));
		strlcpy(sc->sc_sens.desc, "lid open",
		    sizeof(sc->sc_sens.desc));
		sc->sc_sens.type = SENSOR_INDICATOR;
		sensor_attach(&sc->sc_sensdev, &sc->sc_sens);
		sensordev_install(&sc->sc_sensdev);

		aml_evalinteger(sc->sc_acpi, sc->sc_devnode,
		    "_LID", 0, NULL, &lid_open);
		sc->sc_sens.value = lid_open;
	}

	aml_register_notify(sc->sc_devnode, aa->aaa_dev, acpibtn_notify,
	    sc, ACPIDEV_NOPOLL);
}

int
acpibtn_notify(struct aml_node *node, int notify_type, void *arg)
{
	struct acpibtn_softc	*sc = arg;
#ifndef SMALL_KERNEL
	extern int lid_suspend;
	int64_t lid;
#endif

	dnprintf(10, "acpibtn_notify: %.2x %s\n", notify_type,
	    sc->sc_devnode->name);

	switch (sc->sc_btn_type) {
	case ACPIBTN_LID:
#ifndef SMALL_KERNEL
		/*
		 * Notification of 0x80 for lid opens or closes.  We
		 * need to check the current status by calling the
		 * _LID method.  0 means the lid is closed and we
		 * should go to sleep.
		 */
		if (aml_evalinteger(sc->sc_acpi, sc->sc_devnode,
		    "_LID", 0, NULL, &lid))
			return (0);
		sc->sc_sens.value = lid;
		if (lid_suspend == 0)
			break;
		if (lid == 0)
			goto sleep;
#endif /* SMALL_KERNEL */
		break;
	case ACPIBTN_SLEEP:
#ifndef SMALL_KERNEL
		switch (notify_type) {
		case 0x02:
			/* "something" has been taken care of by the system */
			break;
		case 0x80:
sleep:
			/* Request to go to sleep */
			if (acpi_record_event(sc->sc_acpi, APM_USER_SUSPEND_REQ))
				acpi_addtask(sc->sc_acpi, acpi_sleep_task,
				    sc->sc_acpi, ACPI_STATE_S3);
			break;
		}
#endif /* SMALL_KERNEL */
		break;
	case ACPIBTN_POWER:
		if (notify_type == 0x80)
			acpi_addtask(sc->sc_acpi, acpi_powerdown_task,
			    sc->sc_acpi, 0);
		break;
	default:
		printf("%s: spurious acpi button interrupt %i\n", DEVNAME(sc),
		    sc->sc_btn_type);
		break;
	}

	return (0);
}


code:
/* $OpenBSD: acpicpu.c,v 1.68 2015/08/04 22:25:54 guenther Exp $ */
/*
 * Copyright (c) 2005 Marco Peereboom <marco@openbsd.org>
 * Copyright (c) 2015 Philip Guenther <guenther@openbsd.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <sys/param.h>
#include <sys/kernel.h>		/* for tick */
#include <sys/signalvar.h>
#include <sys/sysctl.h>
#include <sys/systm.h>
#include <sys/device.h>
#include <sys/malloc.h>
#include <sys/queue.h>
#include <sys/atomic.h>

#include <machine/bus.h>
#include <machine/cpu.h>
#include <machine/cpufunc.h>
#include <machine/specialreg.h>

#include <dev/acpi/acpireg.h>
#include <dev/acpi/acpivar.h>
#include <dev/acpi/acpidev.h>
#include <dev/acpi/amltypes.h>
#include <dev/acpi/dsdt.h>

#include <sys/sensors.h>

int	acpicpu_match(struct device *, void *, void *);
void	acpicpu_attach(struct device *, struct device *, void *);
int	acpicpu_notify(struct aml_node *, int, void *);
void	acpicpu_setperf(int);
void	acpicpu_setperf_ppc_change(struct acpicpu_pss *, int);

#define ACPI_STATE_C0		0x00
#define ACPI_STATE_C1		0x01
#define ACPI_STATE_C2		0x02
#define ACPI_STATE_C3		0x03

#define ACPI_PDC_REVID		0x1
#define ACPI_PDC_SMP		0xa
#define ACPI_PDC_MSR		0x1

/* _PDC/_OSC Intel capabilities flags */
#define ACPI_PDC_P_FFH		0x0001
#define ACPI_PDC_C_C1_HALT	0x0002
#define ACPI_PDC_T_FFH		0x0004
#define ACPI_PDC_SMP_C1PT	0x0008
#define ACPI_PDC_SMP_C2C3	0x0010
#define ACPI_PDC_SMP_P_SWCOORD	0x0020
#define ACPI_PDC_SMP_C_SWCOORD	0x0040
#define ACPI_PDC_SMP_T_SWCOORD	0x0080
#define ACPI_PDC_C_C1_FFH	0x0100
#define ACPI_PDC_C_C2C3_FFH	0x0200
/* reserved			0x0400 */
#define ACPI_PDC_P_HWCOORD	0x0800
#define ACPI_PDC_PPC_NOTIFY	0x1000

#define CST_METH_HALT		0
#define CST_METH_IO_HALT	1
#define CST_METH_MWAIT		2
#define CST_METH_GAS_IO		3

/* flags on Intel's FFH mwait method */
#define CST_FLAG_MWAIT_HW_COORD		0x1
#define CST_FLAG_MWAIT_BM_AVOIDANCE	0x2
#define CST_FLAG_FALLBACK		0x4000	/* fallback for broken _CST */
#define CST_FLAG_SKIP			0x8000	/* state is worse choice */

#define FLAGS_MWAIT_ONLY	0x02
#define FLAGS_BMCHECK		0x04
#define FLAGS_NOTHROTTLE	0x08
#define FLAGS_NOPSS		0x10
#define FLAGS_NOPCT		0x20

#define CPU_THT_EN		(1L << 4)
#define CPU_MAXSTATE(sc)	(1L << (sc)->sc_duty_wid)
#define CPU_STATE(sc,pct)	((pct * CPU_MAXSTATE(sc) / 100) << (sc)->sc_duty_off)
#define CPU_STATEMASK(sc)	((CPU_MAXSTATE(sc) - 1) << (sc)->sc_duty_off)

#define ACPI_MAX_C2_LATENCY	100
#define ACPI_MAX_C3_LATENCY	1000

/* Make sure throttling bits are valid,a=addr,o=offset,w=width */
#define valid_throttle(o,w,a)	(a && w && (o+w)<=31 && (o>4 || (o+w)<=4))

struct acpi_cstate
{
	SLIST_ENTRY(acpi_cstate) link;

	u_short		state;
	short		method;		/* CST_METH_* */
	u_short		flags;		/* CST_FLAG_* */
	u_short		latency;
	int		power;
	u_int64_t	address;	/* or mwait hint */
};

unsigned long cst_stats[4] = { 0 };

struct acpicpu_softc {
	struct device		sc_dev;
	int			sc_cpu;

	int			sc_duty_wid;
	int			sc_duty_off;
	u_int32_t		sc_pblk_addr;
	int			sc_pblk_len;
	int			sc_flags;
	unsigned long		sc_prev_sleep;
	unsigned long		sc_last_itime;

	struct cpu_info		*sc_ci;
	SLIST_HEAD(,acpi_cstate) sc_cstates;

	bus_space_tag_t		sc_iot;
	bus_space_handle_t	sc_ioh;

	struct acpi_softc	*sc_acpi;
	struct aml_node		*sc_devnode;

	int			sc_pss_len;
	int			sc_ppc;
	int			sc_level;
	struct acpicpu_pss	*sc_pss;

	struct acpicpu_pct	sc_pct;
	/* save compensation for pct access for lying bios' */
	u_int32_t		sc_pct_stat_as;
	u_int32_t		sc_pct_ctrl_as;
	u_int32_t		sc_pct_stat_len;
	u_int32_t		sc_pct_ctrl_len;
	/*
	 * XXX: _PPC Change listener
	 * PPC changes can occur when for example a machine is disconnected
	 * from AC power and can no loger support the highest frequency or
	 * voltage when driven from the battery.
	 * Should probably be reimplemented as a list for now we assume only
	 * one listener
	 */
	void			(*sc_notify)(struct acpicpu_pss *, int);
};

void	acpicpu_add_cstatepkg(struct aml_value *, void *);
void	acpicpu_add_cdeppkg(struct aml_value *, void *);
int	acpicpu_getppc(struct acpicpu_softc *);
int	acpicpu_getpct(struct acpicpu_softc *);
int	acpicpu_getpss(struct acpicpu_softc *);
int	acpicpu_getcst(struct acpicpu_softc *);
void	acpicpu_getcst_from_fadt(struct acpicpu_softc *);
void	acpicpu_print_one_cst(struct acpi_cstate *_cx);
void	acpicpu_print_cst(struct acpicpu_softc *_sc);
void	acpicpu_add_cstate(struct acpicpu_softc *_sc, int _state, int _method,
	    int _flags, int _latency, int _power, u_int64_t _address);
void	acpicpu_set_pdc(struct acpicpu_softc *);
void	acpicpu_idle(void);

#if 0
void    acpicpu_set_throttle(struct acpicpu_softc *, int);
struct acpi_cstate *acpicpu_find_cstate(struct acpicpu_softc *, int);
#endif

struct cfattach acpicpu_ca = {
	sizeof(struct acpicpu_softc), acpicpu_match, acpicpu_attach
};

struct cfdriver acpicpu_cd = {
	NULL, "acpicpu", DV_DULL
};

extern int setperf_prio;

struct acpicpu_softc *acpicpu_sc[MAXCPUS];

#if 0
void
acpicpu_set_throttle(struct acpicpu_softc *sc, int level)
{
	uint32_t pbval;

	if (sc->sc_flags & FLAGS_NOTHROTTLE)
		return;

	/* Disable throttling control */
	pbval = inl(sc->sc_pblk_addr);
	outl(sc->sc_pblk_addr, pbval & ~CPU_THT_EN);
	if (level < 100) {
		pbval &= ~CPU_STATEMASK(sc);
		pbval |= CPU_STATE(sc, level);
		outl(sc->sc_pblk_addr, pbval & ~CPU_THT_EN);
		outl(sc->sc_pblk_addr, pbval | CPU_THT_EN);
	}
}

struct acpi_cstate *
acpicpu_find_cstate(struct acpicpu_softc *sc, int state)
{
	struct acpi_cstate	*cx;

	SLIST_FOREACH(cx, &sc->sc_cstates, link)
		if (cx->state == state)
			return cx;
	return (NULL);
}
#endif

void
acpicpu_set_pdc(struct acpicpu_softc *sc)
{
	struct aml_value cmd, osc_cmd[4];
	struct aml_value res;
	uint32_t cap;
	uint32_t buf[3];

	/* 4077A616-290C-47BE-9EBD-D87058713953 */
	static uint8_t cpu_oscuuid[16] = { 0x16, 0xA6, 0x77, 0x40, 0x0C, 0x29,
					   0xBE, 0x47, 0x9E, 0xBD, 0xD8, 0x70,
					   0x58, 0x71, 0x39, 0x53 };
	cap = ACPI_PDC_C_C1_HALT | ACPI_PDC_P_FFH | ACPI_PDC_C_C1_FFH
	    | ACPI_PDC_C_C2C3_FFH | ACPI_PDC_SMP_P_SWCOORD | ACPI_PDC_SMP_C2C3
	    | ACPI_PDC_SMP_C1PT;

	if (aml_searchname(sc->sc_devnode, "_OSC")) {
		/* Query _OSC */
		memset(&osc_cmd, 0, sizeof(cmd) * 4);
		osc_cmd[0].type = AML_OBJTYPE_BUFFER;
		osc_cmd[0].v_buffer = (uint8_t *)&cpu_oscuuid;
		osc_cmd[0].length = sizeof(cpu_oscuuid);

		osc_cmd[1].type = AML_OBJTYPE_INTEGER;
		osc_cmd[1].v_integer = 1;
		osc_cmd[1].length = 1;

		osc_cmd[2].type = AML_OBJTYPE_INTEGER;
		osc_cmd[2].v_integer = 2;
		osc_cmd[2].length = 1;

		buf[0] = 1;
		buf[1] = cap;
		osc_cmd[3].type = AML_OBJTYPE_BUFFER;
		osc_cmd[3].v_buffer = (int8_t *)&buf;
		osc_cmd[3].length = sizeof(buf);

		aml_evalname(sc->sc_acpi, sc->sc_devnode, "_OSC",
		    4, osc_cmd, &res);

		if (res.type != AML_OBJTYPE_BUFFER || res.length < 8) {
			printf(": unable to query capabilities\n");
			return;
		}

		/* Evaluate _OSC */
		memset(&osc_cmd, 0, sizeof(cmd) * 4);
		osc_cmd[0].type = AML_OBJTYPE_BUFFER;
		osc_cmd[0].v_buffer = (uint8_t *)&cpu_oscuuid;
		osc_cmd[0].length = sizeof(cpu_oscuuid);

		osc_cmd[1].type = AML_OBJTYPE_INTEGER;
		osc_cmd[1].v_integer = 1;
		osc_cmd[1].length = 1;

		osc_cmd[2].type = AML_OBJTYPE_INTEGER;
		osc_cmd[2].v_integer = 2;
		osc_cmd[2].length = 1;

		buf[0] = 0;
		buf[1] = (*(uint32_t *)&res.v_buffer[4]) & cap;
		osc_cmd[3].type = AML_OBJTYPE_BUFFER;
		osc_cmd[3].v_buffer = (int8_t *)&buf;
		osc_cmd[3].length = sizeof(buf);

		aml_evalname(sc->sc_acpi, sc->sc_devnode, "_OSC",
		    4, osc_cmd, &res);
	} else {
		/* Evaluate _PDC */
		memset(&cmd, 0, sizeof(cmd));
		cmd.type = AML_OBJTYPE_BUFFER;
		cmd.v_buffer = (uint8_t *)&buf;
		cmd.length = sizeof(buf);

		buf[0] = ACPI_PDC_REVID;
		buf[1] = 1;
		buf[2] = cap;

		aml_evalname(sc->sc_acpi, sc->sc_devnode, "_PDC",
		    1, &cmd, &res);
	}
}

/*
 * sanity check mwait hints against what cpuid told us
 */
static int
check_mwait_hints(int state, int hints)
{
	int cstate;
	int substate;
	int num_substates;

	if (cpu_mwait_size == 0)
		return (0);
	cstate = ((hints >> 4) & 0xf) + 1;
	if (cstate == 16)
		cstate = 0;
	else if (cstate > 7) {
		/* out of range of test against CPUID; just trust'em */
		return (1);
	}
	substate = hints & 0xf;
	num_substates = (cpu_mwait_states >> (4 * cstate)) & 0xf;
	if (substate >= num_substates) {
		printf("\nC%d: state %d: substate %d >= num %d",
		    state, cstate, substate, num_substates);
		return (0);
	}
	return (1);
}

void
acpicpu_add_cstate(struct acpicpu_softc *sc, int state, int method,
    int flags, int latency, int power, u_int64_t address)
{
	struct acpi_cstate	*cx;

	dnprintf(10," C%d: latency:.%4x power:%.4x addr:%.16llx\n",
	    state, latency, power, address);

	/* add a new state, or overwrite the fallback C1 state? */
	if (state != ACPI_STATE_C1 ||
	    (cx = SLIST_FIRST(&sc->sc_cstates)) == NULL ||
	    (cx->flags & CST_FLAG_FALLBACK) == 0) {
		cx = malloc(sizeof(*cx), M_DEVBUF, M_WAITOK);
		SLIST_INSERT_HEAD(&sc->sc_cstates, cx, link);
	}

	cx->state = state;
	cx->method = method;
	cx->flags = flags;
	cx->latency = latency;
	cx->power = power;
	cx->address = address;
}

/* Found a _CST object, add new cstate for each entry */
void
acpicpu_add_cstatepkg(struct aml_value *val, void *arg)
{
	struct acpicpu_softc	*sc = arg;
	u_int64_t addr;
	struct acpi_grd *grd;
	int state, method, flags;

#if defined(ACPI_DEBUG) && !defined(SMALL_KERNEL)
	aml_showvalue(val, 0);
#endif
	if (val->type != AML_OBJTYPE_PACKAGE || val->length != 4)
		return;

	/* range and sanity checks */
	state = val->v_package[1]->v_integer;
	if (state < 0 || state > 4)
		return;
	if (val->v_package[0]->type != AML_OBJTYPE_BUFFER) {
		printf("\nC%d: unexpected ACPI object type %d",
		    state, val->v_package[0]->type);
		return;
	}
	grd = (struct acpi_grd *)val->v_package[0]->v_buffer;
	if (val->v_package[0]->length != sizeof(*grd) + 2 ||
	    grd->grd_descriptor != LR_GENREGISTER ||
	    grd->grd_length != sizeof(grd->grd_gas) ||
	    val->v_package[0]->v_buffer[sizeof(*grd)] != SR_TAG(SR_ENDTAG,1)) {
		printf("\nC%d: bogo buffer", state);
		return;
	}

	flags = 0;
	switch (grd->grd_gas.address_space_id) {
	case GAS_FUNCTIONAL_FIXED:
		if (grd->grd_gas.register_bit_width == 0) {
			method = CST_METH_HALT;
			addr = 0;
		} else if (grd->grd_gas.register_bit_width == 1) {
			/* vendor == Intel */
			switch (grd->grd_gas.register_bit_offset) {
			case 0x1:
				method = CST_METH_IO_HALT;
				addr = grd->grd_gas.address;

				/* i386 and amd64 I/O space is 16bits */
				if (addr > 0xffff) {
					printf("\nC%d: bogo I/O addr %llx",
					    state, addr);
					return;
				}
				break;
			case 0x2:
				addr = grd->grd_gas.address;
				if (!check_mwait_hints(state, addr))
					return;
				method = CST_METH_MWAIT;
				flags = grd->grd_gas.access_size;
				break;
			default:
				printf("\nC%d: unknown FFH class %d",
				    state, grd->grd_gas.register_bit_offset);
				return;
			}
		} else {
			printf("\nC%d: unknown FFH vendor %d",
			    state, grd->grd_gas.register_bit_width);
			return;
		}
		break;

	case GAS_SYSTEM_IOSPACE:
		addr = grd->grd_gas.address;
		if (grd->grd_gas.register_bit_width != 8 ||
		    grd->grd_gas.register_bit_offset != 0) {
			printf("\nC%d: unhandled %s spec: %d/%d", state,
			    "I/O", grd->grd_gas.register_bit_width,
			    grd->grd_gas.register_bit_offset);
			return;
		}
		method = CST_METH_GAS_IO;
		break;

	default:
		/* dump the GAS for analysis */
		{
			int i;
			printf("\nC%d: unhandled GAS:", state);
			for (i = 0; i < sizeof(grd->grd_gas); i++)
				printf(" %#x", ((u_char *)&grd->grd_gas)[i]);

		}
		return;
	}

	acpicpu_add_cstate(sc, state, method, flags,
	    val->v_package[2]->v_integer, val->v_package[3]->v_integer, addr);
}

/* Found a _CSD object, print the dependency  */
void
acpicpu_add_cdeppkg(struct aml_value *val, void *arg)
{
#if 1 || defined(ACPI_DEBUG) && !defined(SMALL_KERNEL)
	aml_showvalue(val, 0);
#endif
	if (val->type != AML_OBJTYPE_PACKAGE || val->length < 6 ||
	    val->length != val->v_package[0]->v_integer) {
		printf("bogus CSD\n");
		return;
	}

	printf("\nCSD r=%lld d=%lld c=%llx n=%lld i=%lli\n",
	    val->v_package[1]->v_integer,
	    val->v_package[2]->v_integer,
	    val->v_package[3]->v_integer,
	    val->v_package[4]->v_integer,
	    val->v_package[5]->v_integer);
}

int
acpicpu_getcst(struct acpicpu_softc *sc)
{
	struct aml_value	res;
	struct acpi_cstate	*cx, *next_cx;
	int			use_nonmwait;

	/* delete the existing list */
	while ((cx = SLIST_FIRST(&sc->sc_cstates)) != NULL) {
		SLIST_REMOVE_HEAD(&sc->sc_cstates, link);
		free(cx, M_DEVBUF, sizeof(*cx));
	}

	/* provide a fallback C1-via-halt in case _CST's C1 is bogus */
	acpicpu_add_cstate(sc, ACPI_STATE_C1, CST_METH_HALT,
	    CST_FLAG_FALLBACK, 1, -1, 0);

	if (aml_evalname(sc->sc_acpi, sc->sc_devnode, "_CST", 0, NULL, &res))
		return (1);

	aml_foreachpkg(&res, 1, acpicpu_add_cstatepkg, sc);
	aml_freevalue(&res);

	/* only have fallback state?  then no _CST objects were understood */
	cx = SLIST_FIRST(&sc->sc_cstates);
	if (cx->flags & CST_FLAG_FALLBACK)
		return (1);

	/*
	 * Scan the list for states that are neither lower power nor
	 * lower latency than the next state; mark them to be skipped.
	 * Also skip states >=C2 if the CPU's LAPIC timer stops in deep
	 * states (i.e., it doesn't have the 'ARAT' bit set).
	 * Also keep track if all the states we'll use use mwait.
	 */
	use_nonmwait = 0;
	while ((next_cx = SLIST_NEXT(cx, link)) != NULL) {
		if ((next_cx->power != -1 &&
		    cx->power >= next_cx->power &&
		    cx->latency >= next_cx->latency) ||
		    (cx->state > 1 &&
		    (sc->sc_ci->ci_feature_tpmflags & TPM_ARAT) == 0))
			cx->flags |= CST_FLAG_SKIP;
		else if (cx->method != CST_METH_MWAIT)
			use_nonmwait = 1;
		cx = next_cx;
	}
	if (use_nonmwait)
		sc->sc_flags &= ~FLAGS_MWAIT_ONLY;
	else
		sc->sc_flags |= FLAGS_MWAIT_ONLY;

	if (!aml_evalname(sc->sc_acpi, sc->sc_devnode, "_CSD", 0, NULL, &res)) {
		aml_foreachpkg(&res, 1, acpicpu_add_cdeppkg, sc);
		aml_freevalue(&res);
	}

	return (0);
}

/*
 * old-style fixed C-state info in the FADT.
 * Note that this has extra restrictions on values and flags.
 */
void
acpicpu_getcst_from_fadt(struct acpicpu_softc *sc)
{
	struct acpi_fadt	*fadt = sc->sc_acpi->sc_fadt;
	int flags;

	/* FADT has to set flag to do C2 and higher on MP */
	if ((fadt->flags & FADT_P_LVL2_UP) == 0 && ncpus > 1)
		return;

	/* skip these C2 and C3 states if the CPU doesn't have ARAT */
	flags = (sc->sc_ci->ci_feature_tpmflags & TPM_ARAT)
	    ? 0 : CST_FLAG_SKIP;

	/* Some systems don't export a full PBLK; reduce functionality */
	if (sc->sc_pblk_len >= 5 && fadt->p_lvl2_lat <= ACPI_MAX_C2_LATENCY) {
		acpicpu_add_cstate(sc, ACPI_STATE_C2, CST_METH_GAS_IO, flags,
		    fadt->p_lvl2_lat, -1, sc->sc_pblk_addr + 4);
	}
	if (sc->sc_pblk_len >= 6 && fadt->p_lvl3_lat <= ACPI_MAX_C3_LATENCY)
		acpicpu_add_cstate(sc, ACPI_STATE_C3, CST_METH_GAS_IO, flags,
		    fadt->p_lvl3_lat, -1, sc->sc_pblk_addr + 5);
}

void
acpicpu_print_one_cst(struct acpi_cstate *cx)
{
	const char *meth = "";
	int show_addr = 0;

	switch (cx->method) {
	case CST_METH_IO_HALT:
		show_addr = 1;
		/* fallthrough */
	case CST_METH_HALT:
		meth = " halt";
		break;

	case CST_METH_MWAIT:
		meth = " mwait";
		show_addr = cx->address != 0;
		break;

	case CST_METH_GAS_IO:
		meth = " io";
		show_addr = 1;
		break;

	}

	printf(" %sC%d(", (cx->flags & CST_FLAG_SKIP ? "!" : ""), cx->state);
	if (cx->power != -1)
		printf("%d", cx->power);
	printf("@%d%s", cx->latency, meth);
	if (cx->flags & ~CST_FLAG_SKIP) {
		if (cx->flags & CST_FLAG_FALLBACK)
			printf("!");
		else
			printf(".%x", (cx->flags & ~CST_FLAG_SKIP));
	}
	if (show_addr)
		printf("@0x%llx", cx->address);
	printf(")");
}

void
acpicpu_print_cst(struct acpicpu_softc *sc)
{
	struct acpi_cstate	*cx;
	int i;

	if (!SLIST_EMPTY(&sc->sc_cstates)) {
		printf(":");

		i = 0;
		SLIST_FOREACH(cx, &sc->sc_cstates, link) {
			if (i++)
				printf(",");
			acpicpu_print_one_cst(cx);
		}
	}
}

int
acpicpu_match(struct device *parent, void *match, void *aux)
{
	struct acpi_attach_args	*aa = aux;
	struct cfdata		*cf = match;

	/* sanity */
	if (aa->aaa_name == NULL ||
	    strcmp(aa->aaa_name, cf->cf_driver->cd_name) != 0 ||
	    aa->aaa_table != NULL)
		return (0);

	return (1);
}

void
acpicpu_attach(struct device *parent, struct device *self, void *aux)
{
	struct acpicpu_softc	*sc = (struct acpicpu_softc *)self;
	struct acpi_attach_args *aa = aux;
	struct aml_value	res;
	int			i;
	u_int32_t		status = 0;
	CPU_INFO_ITERATOR	cii;
	struct cpu_info		*ci;

	sc->sc_acpi = (struct acpi_softc *)parent;
	sc->sc_devnode = aa->aaa_node;
	acpicpu_sc[sc->sc_dev.dv_unit] = sc;

	SLIST_INIT(&sc->sc_cstates);

	sc->sc_pss = NULL;

	if (aml_evalnode(sc->sc_acpi, sc->sc_devnode, 0, NULL, &res) == 0) {
		if (res.type == AML_OBJTYPE_PROCESSOR) {
			sc->sc_cpu = res.v_processor.proc_id;
			sc->sc_pblk_addr = res.v_processor.proc_addr;
			sc->sc_pblk_len = res.v_processor.proc_len;
		}
		aml_freevalue(&res);
	}
	sc->sc_duty_off = sc->sc_acpi->sc_fadt->duty_offset;
	sc->sc_duty_wid = sc->sc_acpi->sc_fadt->duty_width;

	/* link in the matching cpu_info */
	CPU_INFO_FOREACH(cii, ci)
		if (ci->ci_cpuid == sc->sc_dev.dv_unit) {
			ci->ci_acpicpudev = self;
			sc->sc_ci = ci;
			break;
		}
	if (ci == NULL)
		printf("unable to find cpu %d\n", sc->sc_dev.dv_unit);
	sc->sc_prev_sleep = 1000000;

	acpicpu_set_pdc(sc);

	if (!valid_throttle(sc->sc_duty_off, sc->sc_duty_wid, sc->sc_pblk_addr))
		sc->sc_flags |= FLAGS_NOTHROTTLE;
#ifdef ACPI_DEBUG
	printf(": %s: ", sc->sc_devnode->name);
	printf("\n: hdr:%x pblk:%x,%x duty:%x,%x pstate:%x "
	       "(%ld throttling states)\n", sc->sc_acpi->sc_fadt->hdr_revision,
		sc->sc_pblk_addr, sc->sc_pblk_len, sc->sc_duty_off,
		sc->sc_duty_wid, sc->sc_acpi->sc_fadt->pstate_cnt,
		CPU_MAXSTATE(sc));
#endif

	/* Get C-States from _CST or FADT */
	if (acpicpu_getcst(sc) || SLIST_EMPTY(&sc->sc_cstates))
		acpicpu_getcst_from_fadt(sc);
	else {
		/* Notify BIOS we use _CST objects */
		if (sc->sc_acpi->sc_fadt->cst_cnt) {
			acpi_write_pmreg(sc->sc_acpi, ACPIREG_SMICMD, 0,
			    sc->sc_acpi->sc_fadt->cst_cnt);
		}
	}
	if (!SLIST_EMPTY(&sc->sc_cstates)) {
		extern u_int32_t acpi_force_bm;

		cpu_idle_cycle_fcn = &acpicpu_idle;

		/*
		 * C3 (and maybe C2?) needs BM_RLD to be set to
		 * wake the system
		 */
		if (SLIST_FIRST(&sc->sc_cstates)->state > 1 && acpi_force_bm == 0) {
			uint16_t en = acpi_read_pmreg(sc->sc_acpi,
			    ACPIREG_PM1_CNT, 0);
			if ((en & ACPI_PM1_BM_RLD) == 0) {
				acpi_write_pmreg(sc->sc_acpi, ACPIREG_PM1_CNT,
				    0, en | ACPI_PM1_BM_RLD);
				acpi_force_bm = ACPI_PM1_BM_RLD;
			}
		}
	}

	if (acpicpu_getpss(sc)) {
		sc->sc_flags |= FLAGS_NOPSS;
	} else {
#ifdef ACPI_DEBUG
		for (i = 0; i < sc->sc_pss_len; i++) {
			dnprintf(20, "%d %d %d %d %d %d\n",
			    sc->sc_pss[i].pss_core_freq,
			    sc->sc_pss[i].pss_power,
			    sc->sc_pss[i].pss_trans_latency,
			    sc->sc_pss[i].pss_bus_latency,
			    sc->sc_pss[i].pss_ctrl,
			    sc->sc_pss[i].pss_status);
		}
		dnprintf(20, "\n");
#endif
		if (sc->sc_pss_len == 0) {
			/* this should never happen */
			printf("%s: invalid _PSS length\n", DEVNAME(sc));
			sc->sc_flags |= FLAGS_NOPSS;
		}

		acpicpu_getppc(sc);
		if (acpicpu_getpct(sc))
			sc->sc_flags |= FLAGS_NOPCT;
		else if (sc->sc_pss_len > 0) {
			/* Notify BIOS we are handling p-states */
			if (sc->sc_acpi->sc_fadt->pstate_cnt) {
				acpi_write_pmreg(sc->sc_acpi, ACPIREG_SMICMD,
				    0, sc->sc_acpi->sc_fadt->pstate_cnt);
			}

			aml_register_notify(sc->sc_devnode, NULL,
			    acpicpu_notify, sc, ACPIDEV_NOPOLL);

			acpi_gasio(sc->sc_acpi, ACPI_IOREAD,
			    sc->sc_pct.pct_status.grd_gas.address_space_id,
			    sc->sc_pct.pct_status.grd_gas.address,
			    sc->sc_pct_stat_as, sc->sc_pct_stat_as, &status);
			sc->sc_level = (100 / sc->sc_pss_len) *
			    (sc->sc_pss_len - status);
			dnprintf(20, "%s: cpu index %d, percentage %d\n",
			    DEVNAME(sc), status, sc->sc_level);
			if (setperf_prio < 30) {
				cpu_setperf = acpicpu_setperf;
				acpicpu_set_notify(acpicpu_setperf_ppc_change);
				setperf_prio = 30;
				acpi_hasprocfvs = 1;
			}
		}
	}

	/*
	 * Nicely enumerate what power management capabilities
	 * ACPI CPU provides.
	 */
	acpicpu_print_cst(sc);
	if (!(sc->sc_flags & (FLAGS_NOPSS | FLAGS_NOPCT)) ||
	    !(sc->sc_flags & FLAGS_NOPSS)) {
		printf("%c ", SLIST_EMPTY(&sc->sc_cstates) ? ':' : ',');

		/*
		 * If acpicpu is itself providing the capability to transition
		 * states, enumerate them in the fashion that est and powernow
		 * would.
		 */
		if (!(sc->sc_flags & (FLAGS_NOPSS | FLAGS_NOPCT))) {
			printf("FVS, ");
			for (i = 0; i < sc->sc_pss_len - 1; i++)
				printf("%d, ", sc->sc_pss[i].pss_core_freq);
			printf("%d MHz", sc->sc_pss[i].pss_core_freq);
		} else
			printf("PSS");
	}

	printf("\n");
}

int
acpicpu_getppc(struct acpicpu_softc *sc)
{
	struct aml_value	res;

	sc->sc_ppc = 0;

	if (aml_evalname(sc->sc_acpi, sc->sc_devnode, "_PPC", 0, NULL, &res)) {
		dnprintf(10, "%s: no _PPC\n", DEVNAME(sc));
		return (1);
	}

	sc->sc_ppc = aml_val2int(&res);
	dnprintf(10, "%s: _PPC: %d\n", DEVNAME(sc), sc->sc_ppc);
	aml_freevalue(&res);

	return (0);
}

int
acpicpu_getpct(struct acpicpu_softc *sc)
{
	struct aml_value	res;
	int			rv = 1;

	if (aml_evalname(sc->sc_acpi, sc->sc_devnode, "_PCT", 0, NULL, &res)) {
		dnprintf(20, "%s: no _PCT\n", DEVNAME(sc));
		return (1);
	}

	if (res.length != 2) {
		dnprintf(20, "%s: %s: invalid _PCT length\n", DEVNAME(sc),
		    sc->sc_devnode->name);
		return (1);
	}

	memcpy(&sc->sc_pct.pct_ctrl, res.v_package[0]->v_buffer,
	    sizeof sc->sc_pct.pct_ctrl);
	if (sc->sc_pct.pct_ctrl.grd_gas.address_space_id ==
	    GAS_FUNCTIONAL_FIXED) {
		dnprintf(20, "CTRL GASIO is functional fixed hardware.\n");
		goto ffh;
	}

	memcpy(&sc->sc_pct.pct_status, res.v_package[1]->v_buffer,
	    sizeof sc->sc_pct.pct_status);
	if (sc->sc_pct.pct_status.grd_gas.address_space_id ==
	    GAS_FUNCTIONAL_FIXED) {
		dnprintf(20, "CTRL GASIO is functional fixed hardware.\n");
		goto ffh;
	}

	dnprintf(10, "_PCT(ctrl)  : %02x %04x %02x %02x %02x %02x %016llx\n",
	    sc->sc_pct.pct_ctrl.grd_descriptor,
	    sc->sc_pct.pct_ctrl.grd_length,
	    sc->sc_pct.pct_ctrl.grd_gas.address_space_id,
	    sc->sc_pct.pct_ctrl.grd_gas.register_bit_width,
	    sc->sc_pct.pct_ctrl.grd_gas.register_bit_offset,
	    sc->sc_pct.pct_ctrl.grd_gas.access_size,
	    sc->sc_pct.pct_ctrl.grd_gas.address);

	dnprintf(10, "_PCT(status): %02x %04x %02x %02x %02x %02x %016llx\n",
	    sc->sc_pct.pct_status.grd_descriptor,
	    sc->sc_pct.pct_status.grd_length,
	    sc->sc_pct.pct_status.grd_gas.address_space_id,
	    sc->sc_pct.pct_status.grd_gas.register_bit_width,
	    sc->sc_pct.pct_status.grd_gas.register_bit_offset,
	    sc->sc_pct.pct_status.grd_gas.access_size,
	    sc->sc_pct.pct_status.grd_gas.address);

	/* if not set assume single 32 bit access */
	sc->sc_pct_stat_as = sc->sc_pct.pct_status.grd_gas.register_bit_width
	    / 8;
	if (sc->sc_pct_stat_as == 0)
		sc->sc_pct_stat_as = 4;
	sc->sc_pct_ctrl_as = sc->sc_pct.pct_ctrl.grd_gas.register_bit_width / 8;
	if (sc->sc_pct_ctrl_as == 0)
		sc->sc_pct_ctrl_as = 4;
	sc->sc_pct_stat_len = sc->sc_pct.pct_status.grd_gas.access_size;
	if (sc->sc_pct_stat_len == 0)
		sc->sc_pct_stat_len = sc->sc_pct_stat_as;
	sc->sc_pct_ctrl_len = sc->sc_pct.pct_ctrl.grd_gas.access_size;
	if (sc->sc_pct_ctrl_len == 0)
		sc->sc_pct_ctrl_len = sc->sc_pct_ctrl_as;

	rv = 0;
ffh:
	aml_freevalue(&res);
	return (rv);
}

int
acpicpu_getpss(struct acpicpu_softc *sc)
{
	struct aml_value	res;
	int			i, c, cf;

	if (aml_evalname(sc->sc_acpi, sc->sc_devnode, "_PSS", 0, NULL, &res)) {
		dprintf("%s: no _PSS\n", DEVNAME(sc));
		return (1);
	}

	if (sc->sc_pss)
		free(sc->sc_pss, M_DEVBUF, 0);

	sc->sc_pss = mallocarray(res.length, sizeof(*sc->sc_pss), M_DEVBUF,
	    M_WAITOK | M_ZERO);

	c = 0;
	for (i = 0; i < res.length; i++) {
		cf = aml_val2int(res.v_package[i]->v_package[0]);

		/* This heuristic comes from FreeBSDs
		 * dev/acpica/acpi_perf.c to weed out invalid PSS entries.
		 */
		if (cf == sc->sc_pss[c].pss_core_freq) {
			printf("%s: struck PSS entry, core frequency equals "
			    " last\n", sc->sc_dev.dv_xname);
			continue;
		}

		if (cf == 0xFFFF || cf == 0x9999 || cf == 99999 || cf == 0) {
			printf("%s: struck PSS entry, inappropriate core "
			    "frequency value\n", sc->sc_dev.dv_xname);
			continue;
		}

		sc->sc_pss[c].pss_core_freq = cf;
		sc->sc_pss[c].pss_power = aml_val2int(
		    res.v_package[i]->v_package[1]);
		sc->sc_pss[c].pss_trans_latency = aml_val2int(
		    res.v_package[i]->v_package[2]);
		sc->sc_pss[c].pss_bus_latency = aml_val2int(
		    res.v_package[i]->v_package[3]);
		sc->sc_pss[c].pss_ctrl = aml_val2int(
		    res.v_package[i]->v_package[4]);
		sc->sc_pss[c].pss_status = aml_val2int(
		    res.v_package[i]->v_package[5]);
		c++;
	}
	sc->sc_pss_len = c;

	aml_freevalue(&res);

	return (0);
}

int
acpicpu_fetch_pss(struct acpicpu_pss **pss)
{
	struct acpicpu_softc	*sc;

	/*
	 * XXX: According to the ACPI spec in an SMP system all processors
	 * are supposed to support the same states. For now we pray
	 * the bios ensures this...
	 */

	sc = acpicpu_sc[0];
	if (!sc)
		return 0;
	*pss = sc->sc_pss;

	return (sc->sc_pss_len);
}

int
acpicpu_notify(struct aml_node *node, int notify_type, void *arg)
{
	struct acpicpu_softc	*sc = arg;

	dnprintf(10, "acpicpu_notify: %.2x %s\n", notify_type,
	    sc->sc_devnode->name);

	switch (notify_type) {
	case 0x80:	/* _PPC changed, retrieve new values */
		acpicpu_getppc(sc);
		acpicpu_getpss(sc);
		if (sc->sc_notify)
			sc->sc_notify(sc->sc_pss, sc->sc_pss_len);
		break;

	case 0x81:	/* _CST changed, retrieve new values */
		acpicpu_getcst(sc);
		printf("%s: notify", DEVNAME(sc));
		acpicpu_print_cst(sc);
		printf("\n");
		break;

	default:
		printf("%s: unhandled cpu event %x\n", DEVNAME(sc),
		    notify_type);
		break;
	}

	return (0);
}

void
acpicpu_set_notify(void (*func)(struct acpicpu_pss *, int))
{
	struct acpicpu_softc    *sc;

	sc = acpicpu_sc[0];
	if (sc != NULL)
		sc->sc_notify = func;
}

void
acpicpu_setperf_ppc_change(struct acpicpu_pss *pss, int npss)
{
	struct acpicpu_softc    *sc;

	sc = acpicpu_sc[0];

	if (sc != NULL)
		cpu_setperf(sc->sc_level);
}

void
acpicpu_setperf(int level)
{
	struct acpicpu_softc	*sc;
	struct acpicpu_pss	*pss = NULL;
	int			idx, len;
	u_int32_t		status = 0;

	sc = acpicpu_sc[cpu_number()];

	dnprintf(10, "%s: acpicpu setperf level %d\n",
	    sc->sc_devnode->name, level);

	if (level < 0 || level > 100) {
		dnprintf(10, "%s: acpicpu setperf illegal percentage\n",
		    sc->sc_devnode->name);
		return;
	}

	/*
	 * XXX this should be handled more gracefully and it needs to also do
	 * the duty cycle method instead of pss exclusively
	 */
	if (sc->sc_flags & FLAGS_NOPSS || sc->sc_flags & FLAGS_NOPCT) {
		dnprintf(10, "%s: acpicpu no _PSS or _PCT\n",
		    sc->sc_devnode->name);
		return;
	}

	if (sc->sc_ppc)
		len = sc->sc_ppc;
	else
		len = sc->sc_pss_len;
	idx = (len - 1) - (level / (100 / len));
	if (idx < 0)
		idx = 0;

	if (sc->sc_ppc)
		idx += sc->sc_pss_len - sc->sc_ppc;

	if (idx > sc->sc_pss_len)
		idx = sc->sc_pss_len - 1;

	dnprintf(10, "%s: acpicpu setperf index %d pss_len %d ppc %d\n",
	    sc->sc_devnode->name, idx, sc->sc_pss_len, sc->sc_ppc);

	pss = &sc->sc_pss[idx];

#ifdef ACPI_DEBUG
	/* keep this for now since we will need this for debug in the field */
	printf("0 status: %x %llx %u %u ctrl: %x %llx %u %u\n",
	    sc->sc_pct.pct_status.grd_gas.address_space_id,
	    sc->sc_pct.pct_status.grd_gas.address,
	    sc->sc_pct_stat_as, sc->sc_pct_stat_len,
	    sc->sc_pct.pct_ctrl.grd_gas.address_space_id,
	    sc->sc_pct.pct_ctrl.grd_gas.address,
	    sc->sc_pct_ctrl_as, sc->sc_pct_ctrl_len);
#endif
	acpi_gasio(sc->sc_acpi, ACPI_IOREAD,
	    sc->sc_pct.pct_status.grd_gas.address_space_id,
	    sc->sc_pct.pct_status.grd_gas.address, sc->sc_pct_stat_as,
	    sc->sc_pct_stat_len, &status);
	dnprintf(20, "1 status: %u <- %u\n", status, pss->pss_status);

	/* Are we already at the requested frequency? */
	if (status == pss->pss_status)
		return;

	acpi_gasio(sc->sc_acpi, ACPI_IOWRITE,
	    sc->sc_pct.pct_ctrl.grd_gas.address_space_id,
	    sc->sc_pct.pct_ctrl.grd_gas.address, sc->sc_pct_ctrl_as,
	    sc->sc_pct_ctrl_len, &pss->pss_ctrl);
	dnprintf(20, "pss_ctrl: %x\n", pss->pss_ctrl);

	acpi_gasio(sc->sc_acpi, ACPI_IOREAD,
	    sc->sc_pct.pct_status.grd_gas.address_space_id,
	    sc->sc_pct.pct_status.grd_gas.address, sc->sc_pct_stat_as,
	    sc->sc_pct_stat_as, &status);
	dnprintf(20, "2 status: %d\n", status);

	/* Did the transition succeed? */
	 if (status == pss->pss_status) {
		cpuspeed = pss->pss_core_freq;
		sc->sc_level = level;
	} else
		printf("%s: acpicpu setperf failed to alter frequency\n",
		    sc->sc_devnode->name);
}

void
acpicpu_idle(void)
{
	struct cpu_info *ci = curcpu();
	struct acpicpu_softc *sc = (struct acpicpu_softc *)ci->ci_acpicpudev;
	struct acpi_cstate *best, *cx;
	unsigned long itime;

	if (sc == NULL) {
		__asm volatile("sti");
		panic("null acpicpu");
	}

	/* possibly update the MWAIT_ONLY flag in cpu_info */
	if (sc->sc_flags & FLAGS_MWAIT_ONLY) {
		if ((ci->ci_mwait & MWAIT_ONLY) == 0)
			atomic_setbits_int(&ci->ci_mwait, MWAIT_ONLY);
	} else if (ci->ci_mwait & MWAIT_ONLY)
		atomic_clearbits_int(&ci->ci_mwait, MWAIT_ONLY);

	/*
	 * Find the first state with a latency we'll accept, ignoring
	 * states marked skippable
	 */
	best = cx = SLIST_FIRST(&sc->sc_cstates);
	while ((cx->flags & CST_FLAG_SKIP) ||
	    cx->latency * 3 > sc->sc_prev_sleep) {
		if ((cx = SLIST_NEXT(cx, link)) == NULL)
			break;
		best = cx;
	}

	if (best->state >= 3 &&
	    (best->flags & CST_FLAG_MWAIT_BM_AVOIDANCE) &&
	    acpi_read_pmreg(acpi_softc, ACPIREG_PM1_STS, 0) & ACPI_PM1_BM_STS) {
		/* clear it and back off */
		acpi_write_pmreg(acpi_softc, ACPIREG_PM1_STS, 0,
		    ACPI_PM1_BM_STS);
		while ((cx = SLIST_NEXT(cx, link)) != NULL) {
			if (cx->flags & CST_FLAG_SKIP)
				continue;
			if (cx->state < 3 ||
			    (cx->flags & CST_FLAG_MWAIT_BM_AVOIDANCE) == 0)
				break;
		}
		best = cx;
	}

	atomic_inc_long(&cst_stats[best->state]);

	itime = tick / 2;
	switch (best->method) {
	default:
	case CST_METH_HALT:
		__asm volatile("sti; hlt");
		break;

	case CST_METH_IO_HALT:
		inb((u_short)best->address);
		__asm volatile("sti; hlt");
		break;

	case CST_METH_MWAIT:
		{
		struct timeval start, stop;
		unsigned int hints;

#ifdef __LP64__
		if ((read_rflags() & PSL_I) == 0)
			panic("idle with interrupts blocked!");
#else
		if ((read_eflags() & PSL_I) == 0)
			panic("idle with interrupts blocked!");
#endif

		/* something already queued? */
		if (ci->ci_schedstate.spc_whichqs != 0)
			return;

		/*
		 * About to idle; setting the MWAIT_IN_IDLE bit tells
		 * cpu_unidle() that it can't be a no-op and tells cpu_kick()
		 * that it doesn't need to use an IPI.  We also set the
		 * MWAIT_KEEP_IDLING bit: those routines clear it to stop
		 * the mwait.  Once they're set, we do a final check of the
		 * queue, in case another cpu called setrunqueue() and added
		 * something to the queue and called cpu_unidle() between
		 * the check in sched_idle() and here.
		 */
		hints = (unsigned)best->address;
		microuptime(&start);
		atomic_setbits_int(&ci->ci_mwait, MWAIT_IDLING);
		if (ci->ci_schedstate.spc_whichqs == 0) {
			/* intel errata AAI65: cflush before monitor */
			if (ci->ci_cflushsz != 0) {
				membar_sync();
				clflush((unsigned long)&ci->ci_mwait);
				membar_sync();
			}

			monitor(&ci->ci_mwait, 0, 0);
			if ((ci->ci_mwait & MWAIT_IDLING) == MWAIT_IDLING)
				mwait(0, hints);
		}

		microuptime(&stop);
		timersub(&stop, &start, &stop);
		itime = stop.tv_sec * 1000000 + stop.tv_usec;

		/* done idling; let cpu_kick() know that an IPI is required */
		atomic_clearbits_int(&ci->ci_mwait, MWAIT_IDLING);
		break;
		}

	case CST_METH_GAS_IO:
		inb((u_short)best->address);
		/* something harmless to give system time to change state */
		acpi_read_pmreg(acpi_softc, ACPIREG_PM1_STS, 0);
		break;

	}

	sc->sc_last_itime = itime;
	itime >>= 1;
	sc->sc_prev_sleep = (sc->sc_prev_sleep + (sc->sc_prev_sleep >> 1)
	    + itime) >> 1;
}

license: unknown


code:
/* $OpenBSD: acpidebug.c,v 1.30 2015/03/14 03:38:46 jsg Exp $ */
/*
 * Copyright (c) 2006 Marco Peereboom <marco@openbsd.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <machine/db_machdep.h>
#include <ddb/db_output.h>
#include <ddb/db_extern.h>
#include <ddb/db_lex.h>

#include <machine/bus.h>
#include <sys/malloc.h>

#include <dev/acpi/acpireg.h>
#include <dev/acpi/acpivar.h>
#include <dev/acpi/amltypes.h>
#include <dev/acpi/acpidebug.h>
#include <dev/acpi/dsdt.h>

#ifdef DDB

extern int aml_pc(uint8_t *);

extern const char *aml_mnem(int opcode, uint8_t *);
extern const char *aml_nodename(struct aml_node *);
extern void aml_disasm(struct aml_scope *scope, int lvl,
    void (*dbprintf)(void *, const char *, ...),
    void *arg);

const char		*db_aml_objtype(struct aml_value *);
const char		*db_opregion(int);
int			db_parse_name(void);
void			db_aml_dump(int, u_int8_t *);
void			db_aml_showvalue(struct aml_value *);
void			db_aml_walktree(struct aml_node *);
void			db_disprint(void *, const char *, ...);

const char		*db_aml_fieldacc(int);
const char		*db_aml_fieldlock(int);
const char		*db_aml_fieldupdate(int);

extern struct aml_node	aml_root;

/* name of scope for lexer */
char			scope[80];

const char *
db_opregion(int id)
{
	switch (id) {
	case 0:
		return "SystemMemory";
	case 1:
		return "SystemIO";
	case 2:
		return "PCIConfig";
	case 3:
		return "Embedded";
	case 4:
		return "SMBus";
	case 5:
		return "CMOS";
	case 6:
		return "PCIBAR";
	}
	return "";
}
void
db_aml_dump(int len, u_int8_t *buf)
{
	int		idx;

	db_printf("{ ");
	for (idx = 0; idx < len; idx++)
		db_printf("%s0x%.2x", idx ? ", " : "", buf[idx]);
	db_printf(" }\n");
}

void
db_aml_showvalue(struct aml_value *value)
{
	int		idx;

	if (value == NULL)
		return;

	if (value->node)
		db_printf("[%s] ", aml_nodename(value->node));

	switch (value->type) {
	case AML_OBJTYPE_OBJREF:
		db_printf("refof: %x {\n", value->v_objref.index);
		db_aml_showvalue(value->v_objref.ref);
		db_printf("}\n");
		break;
	case AML_OBJTYPE_NAMEREF:
		db_printf("nameref: %s\n", value->v_nameref);
		break;
	case AML_OBJTYPE_INTEGER:
		db_printf("integer: %llx\n", value->v_integer);
		break;
	case AML_OBJTYPE_STRING:
		db_printf("string: %s\n", value->v_string);
		break;
	case AML_OBJTYPE_PACKAGE:
		db_printf("package: %d {\n", value->length);
		for (idx = 0; idx < value->length; idx++)
			db_aml_showvalue(value->v_package[idx]);
		db_printf("}\n");
		break;
	case AML_OBJTYPE_BUFFER:
		db_printf("buffer: %d ", value->length);
		db_aml_dump(value->length, value->v_buffer);
		break;
	case AML_OBJTYPE_DEBUGOBJ:
		db_printf("debug");
		break;
	case AML_OBJTYPE_MUTEX:
		db_printf("mutex : %llx\n", value->v_integer);
		break;
	case AML_OBJTYPE_DEVICE:
		db_printf("device\n");
		break;
	case AML_OBJTYPE_EVENT:
		db_printf("event\n");
		break;
	case AML_OBJTYPE_PROCESSOR:
		db_printf("cpu: %x,%x,%x\n",
		    value->v_processor.proc_id,
		    value->v_processor.proc_addr,
		    value->v_processor.proc_len);
		break;
	case AML_OBJTYPE_METHOD:
		db_printf("method: args=%d, serialized=%d, synclevel=%d\n",
		    AML_METHOD_ARGCOUNT(value->v_method.flags),
		    AML_METHOD_SERIALIZED(value->v_method.flags),
		    AML_METHOD_SYNCLEVEL(value->v_method.flags));
		break;
	case AML_OBJTYPE_FIELDUNIT:
		db_printf("%s: access=%x,lock=%x,update=%x pos=%.4x "
		    "len=%.4x\n",
		    aml_mnem(value->v_field.type, NULL),
		    AML_FIELD_ACCESS(value->v_field.flags),
		    AML_FIELD_LOCK(value->v_field.flags),
		    AML_FIELD_UPDATE(value->v_field.flags),
		    value->v_field.bitpos,
		    value->v_field.bitlen);
		if (value->v_field.ref2)
			db_printf("  index: %.3x %s\n",
			    value->v_field.ref3,
			    aml_nodename(value->v_field.ref2->node));
		if (value->v_field.ref1)
			db_printf("  data: %s\n",
			    aml_nodename(value->v_field.ref1->node));
		break;
	case AML_OBJTYPE_BUFFERFIELD:
		db_printf("%s: pos=%.4x len=%.4x\n",
		    aml_mnem(value->v_field.type, NULL),
		    value->v_field.bitpos,
		    value->v_field.bitlen);
		db_printf("  buffer: %s\n",
		    aml_nodename(value->v_field.ref1->node));
		break;
	case AML_OBJTYPE_OPREGION:
		db_printf("opregion: %s,0x%llx,0x%x\n",
		    db_opregion(value->v_opregion.iospace),
		    value->v_opregion.iobase,
		    value->v_opregion.iolen);
		break;
	default:
		db_printf("unknown: %d\n", value->type);
		break;
	}
}

const char *
db_aml_objtype(struct aml_value *val)
{
	if (val == NULL)
		return "nil";

	switch (val->type) {
	case AML_OBJTYPE_INTEGER:
		return "integer";
	case AML_OBJTYPE_STRING:
		return "string";
	case AML_OBJTYPE_BUFFER:
		return "buffer";
	case AML_OBJTYPE_PACKAGE:
		return "package";
	case AML_OBJTYPE_DEVICE:
		return "device";
	case AML_OBJTYPE_EVENT:
		return "event";
	case AML_OBJTYPE_METHOD:
		return "method";
	case AML_OBJTYPE_MUTEX:
		return "mutex";
	case AML_OBJTYPE_OPREGION:
		return "opregion";
	case AML_OBJTYPE_POWERRSRC:
		return "powerrsrc";
	case AML_OBJTYPE_PROCESSOR:
		return "processor";
	case AML_OBJTYPE_THERMZONE:
		return "thermzone";
	case AML_OBJTYPE_DDBHANDLE:
		return "ddbhandle";
	case AML_OBJTYPE_DEBUGOBJ:
		return "debugobj";
	case AML_OBJTYPE_NAMEREF:
		return "nameref";
	case AML_OBJTYPE_OBJREF:
		return "refof";
	case AML_OBJTYPE_FIELDUNIT:
	case AML_OBJTYPE_BUFFERFIELD:
		return aml_mnem(val->v_field.type, NULL);
	}

	return ("");
}

void
db_aml_walktree(struct aml_node *node)
{
	while (node) {
		db_aml_showvalue(node->value);
		db_aml_walktree(SIMPLEQ_FIRST(&node->son));
		node = SIMPLEQ_NEXT(node, sib);
	}
}

int
db_parse_name(void)
{
	int		t, rv = 1;

	memset(scope, 0, sizeof scope);
	do {
		t = db_read_token();
		if (t == tIDENT) {
			if (strlcat(scope, db_tok_string, sizeof scope) >=
			    sizeof scope) {
				printf("Input too long\n");
				goto error;
			}
			t = db_read_token();
			if (t == tDOT)
				if (strlcat(scope, ".", sizeof scope) >=
				    sizeof scope) {
					printf("Input too long 2\n");
					goto error;
				}
		}
	} while (t != tEOL);

	if (!strlen(scope)) {
		db_printf("Invalid input\n");
		goto error;
	}

	rv = 0;
error:
	/* get rid of the rest of input */
	db_flush_lex();
	return (rv);
}

/* ddb interface */
void
db_acpi_showval(db_expr_t addr, int haddr, db_expr_t count, char *modif)
{
	struct aml_node *node;

	if (db_parse_name())
		return;

	node = aml_searchname(&aml_root, scope);
	if (node)
		db_aml_showvalue(node->value);
	else
		db_printf("Not a valid value\n");
}

void db_disprint(void *arg, const char *fmt, ...)
{
	va_list ap;

	va_start(ap,fmt);
	db_vprintf(fmt, ap);
	va_end(ap);
}

void
db_acpi_disasm(db_expr_t addr, int haddr, db_expr_t count, char *modif)
{
	struct aml_node *node;

	if (db_parse_name())
		return;

	node = aml_searchname(&aml_root, scope);
	if (node && node->value && node->value->type == AML_OBJTYPE_METHOD) {
		struct aml_scope ns;

		memset(&ns, 0, sizeof(ns));
		ns.pos   = node->value->v_method.start;
		ns.end   = node->value->v_method.end;
		ns.node  = node;
		while (ns.pos < ns.end)
			aml_disasm(&ns, 0, db_disprint, 0);
	}
	else
		db_printf("Not a valid method\n");
}

void
db_acpi_tree(db_expr_t addr, int haddr, db_expr_t count, char *modif)
{
	db_aml_walktree(&aml_root);
}

void
db_acpi_trace(db_expr_t addr, int haddr, db_expr_t count, char *modif)
{
	struct aml_scope *root;
	struct aml_value *sp;
	int idx;
	extern struct aml_scope *aml_lastscope;

	for (root=aml_lastscope; root && root->pos; root=root->parent) {
		db_printf("%.4x Called: %s\n", aml_pc(root->pos),
		    aml_nodename(root->node));
		for (idx = 0; idx< AML_MAX_ARG; idx++) {
			sp = aml_getstack(root, AMLOP_ARG0 + idx);
			if (sp && sp->type) {
				db_printf("  arg%d: ", idx);
				db_aml_showvalue(sp);
		}
			}
		for (idx = 0; idx < AML_MAX_LOCAL; idx++) {
			sp = aml_getstack(root, AMLOP_LOCAL0 + idx);
			if (sp && sp->type) {
				db_printf("  local%d: ", idx);
				db_aml_showvalue(sp);
		}
	}
	}
}

#endif /* DDB */


code:
/* $OpenBSD: acpidebug.h,v 1.4 2006/10/24 19:01:48 jordan Exp $ */
/*
 * Copyright (c) 2006 Marco Peereboom <marco@openbsd.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

void db_acpi_showval(db_expr_t, int, db_expr_t, char *);
void db_acpi_disasm(db_expr_t, int, db_expr_t, char *);
void db_acpi_tree(db_expr_t, int, db_expr_t, char *);
void db_acpi_trace(db_expr_t, int, db_expr_t, char *);


code:
/* $OpenBSD: acpidev.h,v 1.37 2015/08/04 04:20:35 mlarkin Exp $ */
/*
 * Copyright (c) 2005 Marco Peereboom <marco@openbsd.org>
 * Copyright (c) 2005 Thorsten Lockert <tholo@sigmasoft.com>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#ifndef __DEV_ACPI_ACPIDEV_H__
#define __DEV_ACPI_ACPIDEV_H__

#include <sys/sensors.h>
#include <sys/rwlock.h>
#include <dev/acpi/acpireg.h>

#define DEVNAME(s)  ((s)->sc_dev.dv_xname)

#define ACPIDEV_NOPOLL		0
#define ACPIDEV_POLL		1

/*
 * _BIF (Battery InFormation)
 * Arguments: none
 * Results  : package _BIF (Battery InFormation)
 * Package {
 * 	// ASCIIZ is ASCII character string terminated with a 0x00.
 * 	Power Unit			//DWORD
 * 	Design Capacity			//DWORD
 * 	Last Full Charge Capacity	//DWORD
 * 	Battery Technology		//DWORD
 * 	Design Voltage			//DWORD
 * 	Design Capacity of Warning	//DWORD
 * 	Design Capacity of Low		//DWORD
 * 	Battery Capacity Granularity 1	//DWORD
 * 	Battery Capacity Granularity 2	//DWORD
 * 	Model Number			//ASCIIZ
 * 	Serial Number			//ASCIIZ
 * 	Battery Type			//ASCIIZ
 * 	OEM Information			//ASCIIZ
 * }
 */
struct acpibat_bif {
	u_int32_t	bif_power_unit;
#define BIF_POWER_MW		0x00
#define BIF_POWER_MA		0x01
	u_int32_t	bif_capacity;
#define BIF_UNKNOWN		0xffffffff
	u_int32_t	bif_last_capacity;
	u_int32_t	bif_technology;
#define BIF_TECH_PRIMARY	0x00
#define BIF_TECH_SECONDARY	0x01
	u_int32_t	bif_voltage;
	u_int32_t	bif_warning;
	u_int32_t	bif_low;
	u_int32_t	bif_cap_granu1;
	u_int32_t	bif_cap_granu2;
	char		bif_model[20];
	char		bif_serial[20];
	char		bif_type[20];
	char		bif_oem[20];
};

/*
 * _OSC Definition for Control Method Battery
 * Arguments: none
 * Results  : DWORD flags
 */
#define CMB_OSC_UUID		"f18fc78b-0f15-4978-b793-53f833a1d35b"
#define   CMB_OSC_GRANULARITY	0x01
#define   CMB_OSC_WAKE_ON_LOW	0x02

/*
 * _BST (Battery STatus)
 * Arguments: none
 * Results  : package _BST (Battery STatus)
 * Package {
 * 	Battery State			//DWORD
 * 	Battery Present Rate		//DWORD
 * 	Battery Remaining Capacity	//DWORD
 * 	Battery Present Voltage		//DWORD
 * }
 *
 * Per the spec section 10.2.2.3
 * Remaining Battery Percentage[%] = (Battery Remaining Capacity [=0 ~ 100] /
 *     Last Full Charged Capacity[=100]) * 100
 *
 * Remaining Battery Life [h] = Battery Remaining Capacity [mAh/mWh] /
 *     Battery Present Rate [=0xFFFFFFFF] = unknown
 */
struct acpibat_bst {
	u_int32_t	bst_state;
#define BST_DISCHARGE		0x01
#define BST_CHARGE		0x02
#define BST_CRITICAL		0x04
	u_int32_t	bst_rate;
#define BST_UNKNOWN		0xffffffff
	u_int32_t	bst_capacity;
	u_int32_t	bst_voltage;
};

/*
 * _BTP (Battery Trip Point)
 * Arguments: DWORD level
 * Results  : none
 */
#define BTP_CLEAR_TRIP_POINT	0x00

/*
 * _BTM (Battery TiMe)
 * Arguments: DWORD rate of discharge
 * Results  : DWORD time in seconds or error/unknown
 */
#define BTM_CURRENT_RATE	0x00

#define BTM_RATE_TOO_LARGE	0x00
#define BTM_CRITICAL		0x00
#define BTM_UNKNOWN		0xffffffff

/*
 * _BMD (Battery Maintenance Data)
 * Arguments: none
 * Results  : package _BMD (Battery Maintenance Data)
 * Package {
 * 	Status Flags		//DWORD
 * 	Capability Flags	//DWORD
 * 	Recalibrate Count	//DWORD
 * 	Quick Recalibrate Time	//DWORD
 * 	Slow Recalibrate Time	//DWORD
 * }
 */
struct acpibat_bmd {
	u_int32_t	bmd_status;
#define BMD_AML_CALIBRATE_CYCLE	0x01
#define BMD_CHARGING_DISABLED	0x02
#define BMD_DISCHARGE_WHILE_AC	0x04
#define BMD_RECALIBRATE_BAT	0x08
#define BMD_GOTO_STANDBY_SPEED	0x10
	u_int32_t	bmd_capability;
#define BMD_CB_AML_CALIBRATION	0x01
#define BMD_CB_DISABLE_CHARGER	0x02
#define BMD_CB_DISCH_WHILE_AC	0x04
#define BMD_CB_AFFECT_ALL_BATT	0x08
#define BMD_CB_FULL_CHRG_FIRST	0x10
	u_int32_t	bmd_recalibrate_count;
#define BMD_ONLY_CALIB_IF_ST3	0x00	/* only recal when status bit 3 set */
	u_int32_t	bmd_quick_recalibrate_time;
#define BMD_UNKNOWN		0xffffffff
	u_int32_t	bmd_slow_recalibrate_time;
};

/*
 * _BMC (Battery Maintenance Control)
 * Arguments: DWORD flags
 * Results  : none
 */
#define BMC_AML_CALIBRATE	0x01
#define BMC_DISABLE_CHARGING	0x02
#define BMC_ALLOW_AC_DISCHARGE	0x04

/* AC device */
/*
 * _PSR (Power Source)
 * Arguments: none
 * Results  : DWORD status
 */
#define PSR_OFFLINE		0x00
#define PSR_ONLINE		0x01

/*
 * _PCL (Power Consumer List)
 * Arguments: none
 * Results  : LIST of Power Class pointers
 */

/* hpet device */
#define	HPET_REG_SIZE		1024

#define	HPET_CAPABILITIES	0x000
#define	HPET_CONFIGURATION	0x010
#define	HPET_INTERRUPT_STATUS	0x020
#define	HPET_MAIN_COUNTER	0x0F0
#define	HPET_TIMER0_CONFIG	0x100
#define	HPET_TIMER0_COMPARE	0x108
#define	HPET_TIMER0_INTERRUPT	0x110
#define	HPET_TIMER1_CONFIG	((0x20 * 1) + HPET_TIMER0_CONFIG)
#define	HPET_TIMER1_COMPARE	((0x20 * 1) + HPET_TIMER0_COMPARE)
#define	HPET_TIMER1_INTERRUPT	((0x20 * 1) + HPET_TIMER0_INTERRUPT)
#define	HPET_TIMER2_CONFIG	((0x20 * 2) + HPET_TIMER0_CONFIG)
#define	HPET_TIMER2_COMPARE	((0x20 * 2) + HPET_TIMER0_COMPARE)
#define	HPET_TIMER2_INTERRUPT	((0x20 * 2) + HPET_TIMER0_INTERRUPT)

#define STA_PRESENT   (1L << 0)
#define STA_ENABLED   (1L << 1)
#define STA_SHOW_UI   (1L << 2)
#define STA_DEV_OK    (1L << 3)
#define STA_BATTERY   (1L << 4)

/*
 * _PSS (Performance Supported States)
 * Arguments: none
 * Results  : package _PSS (Performance Supported States)
 * Package {
 *	CoreFreq		//DWORD
 *	Power			//DWORD
 *	TransitionLatency	//DWORD
 *	BusMasterLatency	//DWORD
 *	Control			//DWORD
 * 	Status			//DWORD
 * }
 */
struct acpicpu_pss {
	u_int32_t	pss_core_freq;
	u_int32_t	pss_power;
	u_int32_t	pss_trans_latency;
	u_int32_t	pss_bus_latency;
	u_int32_t	pss_ctrl;
	u_int32_t	pss_status;
};

int acpicpu_fetch_pss(struct acpicpu_pss **);
void acpicpu_set_notify(void (*)(struct acpicpu_pss *, int));
/*
 * XXX this is returned in a buffer and is not a "natural" type.
 *
 * GRD (Generic Register Descriptor )
 *
 */
struct acpi_grd {
	u_int8_t	grd_descriptor;
	u_int16_t	grd_length;
	struct acpi_gas	grd_gas;
} __packed;

/*
 * _PCT (Performance Control )
 * Arguments: none
 * Results  : package _PCT (Performance Control)
 * Package {
 *	Perf_Ctrl_register	//Register
 *	Perf_Status_register	//Register
 * }
 */
struct acpicpu_pct {
	struct acpi_grd	pct_ctrl;
	struct acpi_grd	pct_status;
};

/* softc for fake apm devices */
struct acpiac_softc {
	struct device		sc_dev;

	struct acpi_softc	*sc_acpi;
	struct aml_node		*sc_devnode;

	int			sc_ac_stat;

	struct ksensor		sc_sens[1];
	struct ksensordev	sc_sensdev;
};

struct acpibat_softc {
	struct device		sc_dev;

	struct acpi_softc	*sc_acpi;
	struct aml_node		*sc_devnode;

	struct acpibat_bif	sc_bif;
	struct acpibat_bst	sc_bst;
	volatile int		sc_bat_present;

	struct ksensor		sc_sens[9];
	struct ksensordev	sc_sensdev;
};

TAILQ_HEAD(aml_nodelisth, aml_nodelist);

struct acpidock_softc {
	struct device		sc_dev;

	struct acpi_softc	*sc_acpi;
	struct aml_node		*sc_devnode;

	struct aml_nodelisth	sc_deps_h;
	struct aml_nodelist	*sc_deps;

	struct ksensor		sc_sens;
	struct ksensordev	sc_sensdev;

	int			sc_docked;
	int			sc_sta;

#define ACPIDOCK_STATUS_UNKNOWN		-1
#define ACPIDOCK_STATUS_UNDOCKED	0
#define ACPIDOCK_STATUS_DOCKED		1
};

#define ACPIDOCK_EVENT_INSERT	0
#define ACPIDOCK_EVENT_DEVCHECK 1
#define	ACPIDOCK_EVENT_EJECT	3

#define ACPIEC_MAX_EVENTS	256

struct acpiec_event {
	struct aml_node *event;
};

struct acpiec_softc {
	struct device		sc_dev;

	int			sc_ecbusy;

	/* command/status register */
	bus_space_tag_t		sc_cmd_bt;
	bus_space_handle_t	sc_cmd_bh;

	/* data register */
	bus_space_tag_t		sc_data_bt;
	bus_space_handle_t	sc_data_bh;

	struct acpi_softc	*sc_acpi;
	struct aml_node		*sc_devnode;
	u_int32_t		sc_gpe;
	struct acpiec_event	sc_events[ACPIEC_MAX_EVENTS];
	int			sc_gotsci;
	int			sc_glk;
};

void		acpibtn_disable_psw(void);
void		acpibtn_enable_psw(void);
int		acpibtn_numopenlids(void);
#endif /* __DEV_ACPI_ACPIDEV_H__ */


code:
/* $OpenBSD: acpidock.c,v 1.44 2015/03/14 03:38:46 jsg Exp $ */
/*
 * Copyright (c) 2006,2007 Michael Knudsen <mk@openbsd.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/device.h>
#include <sys/malloc.h>
#include <sys/sensors.h>

#include <machine/bus.h>

#include <dev/acpi/acpivar.h>
#include <dev/acpi/acpidev.h>
#include <dev/acpi/amltypes.h>
#include <dev/acpi/dsdt.h>

struct aml_nodelist {
	struct aml_node *node;
	TAILQ_ENTRY(aml_nodelist) entries;
};

int	acpidock_match(struct device *, void *, void *);
void	acpidock_attach(struct device *, struct device *, void *);

struct cfattach acpidock_ca = {
	sizeof(struct acpidock_softc), acpidock_match, acpidock_attach
};

struct cfdriver acpidock_cd = {
	NULL, "acpidock", DV_DULL
};

int	acpidock_docklock(struct acpidock_softc *, int);
int	acpidock_dockctl(struct acpidock_softc *, int);
int	acpidock_eject(struct acpidock_softc *, struct aml_node *);
int	acpidock_notify(struct aml_node *, int, void *);
int	acpidock_status(struct acpidock_softc *);
int	acpidock_walkchildren(struct aml_node *, void *);

int	acpidock_foundejd(struct aml_node *, void *);

int
acpidock_match(struct device *parent, void *match, void *aux)
{
	struct acpi_attach_args	 *aaa = aux;
	struct cfdata		 *cf = match;

	/* sanity */
	if (aaa->aaa_name == NULL ||
	    strcmp(aaa->aaa_name, cf->cf_driver->cd_name) != 0 ||
	    aaa->aaa_table != NULL)
		return (0);

	return (1);
}

void
acpidock_attach(struct device *parent, struct device *self, void *aux)
{
	struct acpidock_softc	*sc = (struct acpidock_softc *)self;
	struct acpi_attach_args *aa = aux;
	extern struct aml_node	aml_root;

	sc->sc_acpi = (struct acpi_softc *)parent;
	sc->sc_devnode = aa->aaa_node;

	printf(": %s", sc->sc_devnode->name);

	acpidock_status(sc);
	if (sc->sc_docked == ACPIDOCK_STATUS_DOCKED) {
		acpidock_docklock(sc, 1);
		acpidock_dockctl(sc, 1);
	}

	acpidock_status(sc);
	printf("%s docked (%d)\n",
	    sc->sc_docked == ACPIDOCK_STATUS_DOCKED ? "" : " not",
	    sc->sc_sta);

	strlcpy(sc->sc_sensdev.xname, DEVNAME(sc),
	    sizeof(sc->sc_sensdev.xname));
	if (sc->sc_docked)
		strlcpy(sc->sc_sens.desc, "docked",
		    sizeof(sc->sc_sens.desc));
	else
		strlcpy(sc->sc_sens.desc, "not docked",
		    sizeof(sc->sc_sens.desc));

	sc->sc_sens.type = SENSOR_INDICATOR;
	sc->sc_sens.value = sc->sc_docked == ACPIDOCK_STATUS_DOCKED;
	sc->sc_sens.status = sc->sc_docked ? SENSOR_S_OK : SENSOR_S_UNKNOWN;
	sensor_attach(&sc->sc_sensdev, &sc->sc_sens);
	sensordev_install(&sc->sc_sensdev);

	TAILQ_INIT(&sc->sc_deps_h);
	aml_find_node(&aml_root, "_EJD", acpidock_foundejd, sc);

	aml_register_notify(sc->sc_devnode, aa->aaa_dev,
	    acpidock_notify, sc, ACPIDEV_NOPOLL);
}

int
acpidock_status(struct acpidock_softc *sc)
{
	int64_t			sta;
	int			rv;

	if (aml_evalinteger(sc->sc_acpi, sc->sc_devnode, "_STA", 0, NULL,
	    &sta) != 0) {
		sta = 0;
		rv = 0;
	} else
		rv = 1;

	sc->sc_sta = sta;
	sc->sc_docked = sc->sc_sta & STA_PRESENT;

	return (rv);
}

int
acpidock_docklock(struct acpidock_softc *sc, int lock)
{
	struct aml_value	cmd;
	struct aml_value	res;
	int			rv;

	memset(&cmd, 0, sizeof cmd);
	cmd.v_integer = lock;
	cmd.type = AML_OBJTYPE_INTEGER;
	if (aml_evalname(sc->sc_acpi, sc->sc_devnode, "_LCK", 1, &cmd,
	    &res) != 0) {
		dnprintf(20, "%s: _LCK %d failed\n", DEVNAME(sc), lock);
		rv = 0;
	} else {
		dnprintf(20, "%s: _LCK %d successful\n", DEVNAME(sc), lock);
		rv = 1;
	}

	aml_freevalue(&res);

	return (rv);
}

int
acpidock_dockctl(struct acpidock_softc *sc, int dock)
{
	struct aml_value	cmd;
	struct aml_value	res;
	int			rv;

	memset(&cmd, 0, sizeof cmd);
	cmd.v_integer = dock;
	cmd.type = AML_OBJTYPE_INTEGER;
	if (aml_evalname(sc->sc_acpi, sc->sc_devnode, "_DCK", 1, &cmd,
	    &res) != 0) {
		dnprintf(15, "%s: _DCK %d failed\n", DEVNAME(sc), dock);
		rv = 0;
	} else {
		dnprintf(15, "%s: _DCK %d successful\n", DEVNAME(sc), dock);
		rv = 1;
	}

	aml_freevalue(&res);

	return (rv);
}

int
acpidock_eject(struct acpidock_softc *sc, struct aml_node *node)
{
	struct aml_value	cmd;
	struct aml_value	res;
	int			rv;

	if (node != sc->sc_devnode)
		aml_notify(node, 3);

	memset(&cmd, 0, sizeof cmd);
	cmd.v_integer = 1;
	cmd.type = AML_OBJTYPE_INTEGER;
	if (aml_evalname(sc->sc_acpi, node, "_EJ0", 1, &cmd,
	    &res) != 0) {
		dnprintf(15, "%s: _EJ0 failed\n", DEVNAME(sc));
		rv = 0;
	} else {
		dnprintf(15, "%s: _EJ0 successful\n", DEVNAME(sc));
		rv = 1;
	}

	aml_freevalue(&res);

	return (rv);
}

int
acpidock_notify(struct aml_node *node, int notify_type, void *arg)
{
	struct acpidock_softc	*sc = arg;
	struct aml_nodelist	*n;

	dnprintf(5, "%s: acpidock_notify: notify %d\n", DEVNAME(sc),
	    notify_type);

	switch (notify_type) {
	case ACPIDOCK_EVENT_INSERT:
		acpidock_docklock(sc, 1);
		acpidock_dockctl(sc, 1);

		TAILQ_FOREACH_REVERSE(n, &sc->sc_deps_h, aml_nodelisth, entries)
			aml_notify(n->node, 0x00);
		break;

	case ACPIDOCK_EVENT_EJECT:
	case ACPIDOCK_EVENT_DEVCHECK:
		/* ACPI Spec says eject button press generates
		 * a Notify(Device, 1); */
		TAILQ_FOREACH(n, &sc->sc_deps_h, entries)
			acpidock_eject(sc, n->node);
		acpidock_dockctl(sc, 0);
		acpidock_docklock(sc, 0);

		/* now actually undock */
		acpidock_eject(sc, sc->sc_devnode);
		break;
	}

	acpidock_status(sc);
	sc->sc_sens.value = sc->sc_docked == ACPIDOCK_STATUS_DOCKED;
	sc->sc_sens.status = sc->sc_docked ? SENSOR_S_OK : SENSOR_S_UNKNOWN;
	if (sc->sc_docked)
		strlcpy(sc->sc_sens.desc, "docked",
		    sizeof(sc->sc_sens.desc));
	else
		strlcpy(sc->sc_sens.desc, "not docked",
		    sizeof(sc->sc_sens.desc));

	printf("%s: %s\n",
	    DEVNAME(sc), sc->sc_docked == ACPIDOCK_STATUS_DOCKED ?
	    "docked" : "undocked");

	return (0);
}

int
acpidock_walkchildren(struct aml_node *node, void *arg)
{
	struct acpidock_softc	*sc = arg;
	struct aml_nodelist	*n;

	if (node && node->value && node->value->type == AML_OBJTYPE_DEVICE) {
		n = malloc(sizeof *n, M_DEVBUF, M_WAITOK | M_ZERO);
		n->node = node;
		dnprintf(10,"%s depends on", aml_nodename(node));
		dnprintf(10,"%s\n", aml_nodename(sc->sc_devnode));
		TAILQ_INSERT_TAIL(&sc->sc_deps_h, n, entries);
	}

	return (0);
}

int
acpidock_foundejd(struct aml_node *node, void *arg)
{
	struct acpidock_softc	*sc = (struct acpidock_softc *)arg;
	struct aml_value	res;
	struct aml_node		*dock;
	extern struct aml_node	aml_root;

	dnprintf(15, "%s: %s", DEVNAME(sc), node->name);

	if (aml_evalnode(sc->sc_acpi, node, 0, NULL, &res) == -1)
		printf(": error\n");
	else {
		dock = aml_searchname(&aml_root, res.v_string);

		if (dock == sc->sc_devnode)
			/* Add all children devices of Device containing _EJD */
			aml_walknodes(node->parent, AML_WALK_POST,
			    acpidock_walkchildren, sc);
		aml_freevalue(&res);
	}

	return (0);
}


code:
/* $OpenBSD: acpiec.c,v 1.52 2015/03/14 03:38:46 jsg Exp $ */
/*
 * Copyright (c) 2006 Can Erkin Acar <canacar@openbsd.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <sys/param.h>
#include <sys/signalvar.h>
#include <sys/systm.h>
#include <sys/device.h>

#include <machine/bus.h>

#include <dev/acpi/acpireg.h>
#include <dev/acpi/acpivar.h>
#include <dev/acpi/acpidev.h>
#include <dev/acpi/amltypes.h>
#include <dev/acpi/dsdt.h>

#include <sys/sensors.h>

int		acpiec_match(struct device *, void *, void *);
void		acpiec_attach(struct device *, struct device *, void *);

u_int8_t	acpiec_status(struct acpiec_softc *);
u_int8_t	acpiec_read_data(struct acpiec_softc *);
void		acpiec_write_cmd(struct acpiec_softc *, u_int8_t);
void		acpiec_write_data(struct acpiec_softc *, u_int8_t);
void		acpiec_burst_enable(struct acpiec_softc *sc);
void		acpiec_burst_disable(struct acpiec_softc *sc);

u_int8_t	acpiec_read_1(struct acpiec_softc *, u_int8_t);
void		acpiec_write_1(struct acpiec_softc *, u_int8_t, u_int8_t);

void		acpiec_read(struct acpiec_softc *, u_int8_t, int, u_int8_t *);
void		acpiec_write(struct acpiec_softc *, u_int8_t, int, u_int8_t *);

int		acpiec_getcrs(struct acpiec_softc *,
		    struct acpi_attach_args *);
int		acpiec_getregister(const u_int8_t *, int, int *, bus_size_t *);

void		acpiec_wait(struct acpiec_softc *, u_int8_t, u_int8_t);
void		acpiec_sci_event(struct acpiec_softc *);

void		acpiec_get_events(struct acpiec_softc *);

int		acpiec_gpehandler(struct acpi_softc *, int, void *);

void		acpiec_lock(struct acpiec_softc *);
void		acpiec_unlock(struct acpiec_softc *);

/* EC Status bits */
#define		EC_STAT_SMI_EVT	0x40	/* SMI event pending */
#define		EC_STAT_SCI_EVT	0x20	/* SCI event pending */
#define		EC_STAT_BURST	0x10	/* Controller in burst mode */
#define		EC_STAT_CMD	0x08	/* data is command */
#define		EC_STAT_IBF	0x02	/* input buffer full */
#define		EC_STAT_OBF	0x01	/* output buffer full */

/* EC Commands */
#define		EC_CMD_RD	0x80	/* Read */
#define		EC_CMD_WR	0x81	/* Write */
#define		EC_CMD_BE	0x82	/* Burst Enable */
#define		EC_CMD_BD	0x83	/* Burst Disable */
#define		EC_CMD_QR	0x84	/* Query */

#define		REG_TYPE_EC	3

int	acpiec_reg(struct acpiec_softc *);

struct cfattach acpiec_ca = {
	sizeof(struct acpiec_softc), acpiec_match, acpiec_attach
};

struct cfdriver acpiec_cd = {
	NULL, "acpiec", DV_DULL
};

const char *acpiec_hids[] = { ACPI_DEV_ECD, 0 };

void
acpiec_wait(struct acpiec_softc *sc, u_int8_t mask, u_int8_t val)
{
	static int acpiecnowait;
	u_int8_t		stat;

	dnprintf(40, "%s: EC wait_ns for: %b == %02x\n",
	    DEVNAME(sc), (int)mask,
	    "\20\x8IGN\x7SMI\x6SCI\05BURST\04CMD\03IGN\02IBF\01OBF", (int)val);

	while (((stat = acpiec_status(sc)) & mask) != val) {
		if (stat & EC_STAT_SCI_EVT)
			sc->sc_gotsci = 1;
		if (cold || (stat & EC_STAT_BURST))
			delay(1);
		else
			tsleep(&acpiecnowait, PWAIT, "acpiec", 1);
	}

	dnprintf(40, "%s: EC wait_ns, stat: %b\n", DEVNAME(sc), (int)stat,
	    "\20\x8IGN\x7SMI\x6SCI\05BURST\04CMD\03IGN\02IBF\01OBF");
}

u_int8_t
acpiec_status(struct acpiec_softc *sc)
{
	return (bus_space_read_1(sc->sc_cmd_bt, sc->sc_cmd_bh, 0));
}

void
acpiec_write_data(struct acpiec_softc *sc, u_int8_t val)
{
	acpiec_wait(sc, EC_STAT_IBF, 0);
	dnprintf(40, "acpiec: write_data -- %d\n", (int)val);
	bus_space_write_1(sc->sc_data_bt, sc->sc_data_bh, 0, val);
}

void
acpiec_write_cmd(struct acpiec_softc *sc, u_int8_t val)
{
	acpiec_wait(sc, EC_STAT_IBF, 0);
	dnprintf(40, "acpiec: write_cmd -- %d\n", (int)val);
	bus_space_write_1(sc->sc_cmd_bt, sc->sc_cmd_bh, 0, val);
}

u_int8_t
acpiec_read_data(struct acpiec_softc *sc)
{
	u_int8_t		val;

	acpiec_wait(sc, EC_STAT_OBF, EC_STAT_OBF);
	val = bus_space_read_1(sc->sc_data_bt, sc->sc_data_bh, 0);

	dnprintf(40, "acpiec: read_data %d\n", (int)val);

	return (val);
}

void
acpiec_sci_event(struct acpiec_softc *sc)
{
	u_int8_t		evt;

	sc->sc_gotsci = 0;

	acpiec_wait(sc, EC_STAT_IBF, 0);
	bus_space_write_1(sc->sc_cmd_bt, sc->sc_cmd_bh, 0, EC_CMD_QR);

	acpiec_wait(sc, EC_STAT_OBF, EC_STAT_OBF);
	evt = bus_space_read_1(sc->sc_data_bt, sc->sc_data_bh, 0);

	if (evt) {
		dnprintf(10, "%s: sci_event: 0x%02x\n", DEVNAME(sc), (int)evt);
		aml_evalnode(sc->sc_acpi, sc->sc_events[evt].event, 0, NULL,
		    NULL);
	}
}

u_int8_t
acpiec_read_1(struct acpiec_softc *sc, u_int8_t addr)
{
	u_int8_t		val;

	if ((acpiec_status(sc) & EC_STAT_SCI_EVT) == EC_STAT_SCI_EVT)
		sc->sc_gotsci = 1;

	acpiec_write_cmd(sc, EC_CMD_RD);
	acpiec_write_data(sc, addr);

	val = acpiec_read_data(sc);

	return (val);
}

void
acpiec_write_1(struct acpiec_softc *sc, u_int8_t addr, u_int8_t data)
{
	if ((acpiec_status(sc) & EC_STAT_SCI_EVT) == EC_STAT_SCI_EVT)
		sc->sc_gotsci = 1;

	acpiec_write_cmd(sc, EC_CMD_WR);
	acpiec_write_data(sc, addr);
	acpiec_write_data(sc, data);
}

void
acpiec_burst_enable(struct acpiec_softc *sc)
{
	acpiec_write_cmd(sc, EC_CMD_BE);
	acpiec_read_data(sc);
}

void
acpiec_burst_disable(struct acpiec_softc *sc)
{
	if ((acpiec_status(sc) & EC_STAT_BURST) == EC_STAT_BURST)
		acpiec_write_cmd(sc, EC_CMD_BD);
}

void
acpiec_read(struct acpiec_softc *sc, u_int8_t addr, int len, u_int8_t *buffer)
{
	int			reg;

	/*
	 * this works because everything runs in the acpi thread context.
	 * at some point add a lock to deal with concurrency so that a
	 * transaction does not get interrupted.
	 */
	dnprintf(20, "%s: read %d, %d\n", DEVNAME(sc), (int)addr, len);
	sc->sc_ecbusy = 1;
	acpiec_burst_enable(sc);
	for (reg = 0; reg < len; reg++)
		buffer[reg] = acpiec_read_1(sc, addr + reg);
	acpiec_burst_disable(sc);
	sc->sc_ecbusy = 0;
}

void
acpiec_write(struct acpiec_softc *sc, u_int8_t addr, int len, u_int8_t *buffer)
{
	int			reg;

	/*
	 * this works because everything runs in the acpi thread context.
	 * at some point add a lock to deal with concurrency so that a
	 * transaction does not get interrupted.
	 */
	dnprintf(20, "%s: write %d, %d\n", DEVNAME(sc), (int)addr, len);
	sc->sc_ecbusy = 1;
	acpiec_burst_enable(sc);
	for (reg = 0; reg < len; reg++)
		acpiec_write_1(sc, addr + reg, buffer[reg]);
	acpiec_burst_disable(sc);
	sc->sc_ecbusy = 0;
}

int
acpiec_match(struct device *parent, void *match, void *aux)
{
	struct acpi_attach_args	*aa = aux;
	struct cfdata		*cf = match;
	struct acpi_ecdt	*ecdt = aa->aaa_table;
	struct acpi_softc	*acpisc = (struct acpi_softc *)parent;

	/* Check for early ECDT table attach */
	if (ecdt &&
	    !memcmp(ecdt->hdr.signature, ECDT_SIG, sizeof(ECDT_SIG) - 1))
		return (1);
	if (acpisc->sc_ec)
		return (0);

	/* sanity */
	return (acpi_matchhids(aa, acpiec_hids, cf->cf_driver->cd_name));
}

void
acpiec_attach(struct device *parent, struct device *self, void *aux)
{
	struct acpiec_softc	*sc = (struct acpiec_softc *)self;
	struct acpi_attach_args *aa = aux;
	struct aml_value res;
	int64_t st;

	sc->sc_acpi = (struct acpi_softc *)parent;
	sc->sc_devnode = aa->aaa_node;

	if (aml_evalinteger(sc->sc_acpi, sc->sc_devnode, "_STA", 0, NULL, &st))
		st = STA_PRESENT | STA_ENABLED | STA_DEV_OK;
	if ((st & STA_PRESENT) == 0) {
		printf(": not present\n");
		return;
	}

	if (acpiec_getcrs(sc, aa)) {
		printf(": Failed to read resource settings\n");
		return;
	}

	sc->sc_acpi->sc_ec = sc;

	if (acpiec_reg(sc)) {
		printf(": Failed to register address space\n");
		return;
	}

	acpiec_get_events(sc);

	dnprintf(10, "%s: GPE: %d\n", DEVNAME(sc), sc->sc_gpe);

#ifndef SMALL_KERNEL
	acpi_set_gpehandler(sc->sc_acpi, sc->sc_gpe, acpiec_gpehandler,
	    sc, 1);
#endif

	if (aml_evalname(sc->sc_acpi, sc->sc_devnode, "_GLK", 0, NULL, &res))
		sc->sc_glk = 0;
	else if (res.type != AML_OBJTYPE_INTEGER)
		sc->sc_glk = 0;
	else
		sc->sc_glk = res.v_integer ? 1 : 0;

	printf("\n");
}

void
acpiec_get_events(struct acpiec_softc *sc)
{
	int			idx;
	char			name[16];

	memset(sc->sc_events, 0, sizeof(sc->sc_events));
	for (idx = 0; idx < ACPIEC_MAX_EVENTS; idx++) {
		snprintf(name, sizeof(name), "_Q%02X", idx);
		sc->sc_events[idx].event = aml_searchname(sc->sc_devnode, name);
		if (sc->sc_events[idx].event != NULL)
			dnprintf(10, "%s: Found event %s\n", DEVNAME(sc), name);
	}
}

int
acpiec_gpehandler(struct acpi_softc *acpi_sc, int gpe, void *arg)
{
	struct acpiec_softc	*sc = arg;
	u_int8_t		mask, stat, en;
	int			s;

	KASSERT(sc->sc_ecbusy == 0);
	dnprintf(10, "ACPIEC: got gpe\n");

	do {
		if (sc->sc_gotsci)
			acpiec_sci_event(sc);

		stat = acpiec_status(sc);
		dnprintf(40, "%s: EC interrupt, stat: %b\n",
		    DEVNAME(sc), (int)stat,
		    "\20\x8IGN\x7SMI\x6SCI\05BURST\04CMD\03IGN\02IBF\01OBF");

		if (stat & EC_STAT_SCI_EVT)
			sc->sc_gotsci = 1;
		else
			sc->sc_gotsci = 0;
	} while (sc->sc_gotsci);

	/* Unmask the GPE which was blocked at interrupt time */
	s = spltty();
	mask = (1L << (gpe & 7));
	en = acpi_read_pmreg(acpi_sc, ACPIREG_GPE_EN, gpe>>3);
	acpi_write_pmreg(acpi_sc, ACPIREG_GPE_EN, gpe>>3, en | mask);
	splx(s);

	return (0);
}

/* parse the resource buffer to get a 'register' value */
int
acpiec_getregister(const u_int8_t *buf, int size, int *type, bus_size_t *addr)
{
	int			len, hlen;

#define RES_TYPE_MASK 0x80
#define RES_LENGTH_MASK 0x07
#define RES_TYPE_IOPORT	0x47
#define RES_TYPE_ENDTAG	0x79

	if (size <= 0)
		return (0);

	if (*buf & RES_TYPE_MASK) {
		/* large resource */
		if (size < 3)
			return (1);
		len = (int)buf[1] + 256 * (int)buf[2];
		hlen = 3;
	} else {
		/* small resource */
		len = buf[0] & RES_LENGTH_MASK;
		hlen = 1;
	}

	/* XXX todo: decode other types */
	if (*buf != RES_TYPE_IOPORT)
		return (0);

	if (size < hlen + len)
		return (0);

	/* XXX validate? */
	*type = GAS_SYSTEM_IOSPACE;
	*addr = (int)buf[2] + 256 * (int)buf[3];

	return (hlen + len);
}

int
acpiec_getcrs(struct acpiec_softc *sc, struct acpi_attach_args *aa)
{
	struct aml_value	res;
	bus_size_t		ec_sc, ec_data;
	int			dtype, ctype;
	char			*buf;
	int			size, ret;
	int64_t			gpe;
	struct acpi_ecdt	*ecdt = aa->aaa_table;
	extern struct aml_node	aml_root;

	/* Check if this is ECDT initialization */
	if (ecdt) {
		/* Get GPE, Data and Control segments */
		sc->sc_gpe = ecdt->gpe_bit;

		ctype = ecdt->ec_control.address_space_id;
		ec_sc = ecdt->ec_control.address;

		dtype = ecdt->ec_data.address_space_id;
		ec_data = ecdt->ec_data.address;

		/* Get devnode from header */
		sc->sc_devnode = aml_searchname(&aml_root, ecdt->ec_id);

		goto ecdtdone;
	}

	if (aml_evalinteger(sc->sc_acpi, sc->sc_devnode, "_GPE", 0, NULL, &gpe)) {
		dnprintf(10, "%s: no _GPE\n", DEVNAME(sc));
		return (1);
	}

	sc->sc_gpe = gpe;

	if (aml_evalname(sc->sc_acpi, sc->sc_devnode, "_CRS", 0, NULL, &res)) {
		dnprintf(10, "%s: no _CRS\n", DEVNAME(sc));
		return (1);
	}

	/* Parse CRS to get control and data registers */

	if (res.type != AML_OBJTYPE_BUFFER) {
		dnprintf(10, "%s: unknown _CRS type %d\n",
		    DEVNAME(sc), res.type);
		aml_freevalue(&res);
		return (1);
	}

	size = res.length;
	buf = res.v_buffer;

	ret = acpiec_getregister(buf, size, &dtype, &ec_data);
	if (ret <= 0) {
		dnprintf(10, "%s: failed to read DATA from _CRS\n",
		    DEVNAME(sc));
		aml_freevalue(&res);
		return (1);
	}

	buf += ret;
	size -= ret;

	ret = acpiec_getregister(buf, size, &ctype, &ec_sc);
	if (ret <= 0) {
		dnprintf(10, "%s: failed to read S/C from _CRS\n",
		    DEVNAME(sc));
		aml_freevalue(&res);
		return (1);
	}

	buf += ret;
	size -= ret;

	if (size != 2 || *buf != RES_TYPE_ENDTAG) {
		dnprintf(10, "%s: no _CRS end tag\n", DEVNAME(sc));
		aml_freevalue(&res);
		return (1);
	}
	aml_freevalue(&res);

	/* XXX: todo - validate _CRS checksum? */
ecdtdone:

	dnprintf(10, "%s: Data: 0x%lx, S/C: 0x%lx\n",
	    DEVNAME(sc), ec_data, ec_sc);

	if (ctype == GAS_SYSTEM_IOSPACE)
		sc->sc_cmd_bt = aa->aaa_iot;
	else
		sc->sc_cmd_bt = aa->aaa_memt;

	if (bus_space_map(sc->sc_cmd_bt, ec_sc, 1, 0, &sc->sc_cmd_bh)) {
		dnprintf(10, "%s: failed to map S/C reg.\n", DEVNAME(sc));
		return (1);
	}

	if (dtype == GAS_SYSTEM_IOSPACE)
		sc->sc_data_bt = aa->aaa_iot;
	else
		sc->sc_data_bt = aa->aaa_memt;

	if (bus_space_map(sc->sc_data_bt, ec_data, 1, 0, &sc->sc_data_bh)) {
		dnprintf(10, "%s: failed to map DATA reg.\n", DEVNAME(sc));
		bus_space_unmap(sc->sc_cmd_bt, sc->sc_cmd_bh, 1);
		return (1);
	}

	return (0);
}

int
acpiec_reg(struct acpiec_softc *sc)
{
	struct aml_value arg[2];
	struct aml_node *node;

	memset(&arg, 0, sizeof(arg));
	arg[0].type = AML_OBJTYPE_INTEGER;
	arg[0].v_integer = REG_TYPE_EC;
	arg[1].type = AML_OBJTYPE_INTEGER;
	arg[1].v_integer = 1;

	node = aml_searchname(sc->sc_devnode, "_REG");
	if (node && aml_evalnode(sc->sc_acpi, node, 2, arg, NULL)) {
		dnprintf(10, "%s: eval method _REG failed\n", DEVNAME(sc));
		printf("acpiec _REG failed, broken BIOS\n");
	}

	return (0);
}

void
acpiec_lock(struct acpiec_softc *sc)
{
	KASSERT(sc->sc_ecbusy == 0);

	sc->sc_ecbusy = 1;

	if (sc->sc_glk) {
		acpi_glk_enter();
	}
}

void
acpiec_unlock(struct acpiec_softc *sc)
{
	KASSERT(sc->sc_ecbusy == 1);

	if (sc->sc_glk) {
		acpi_glk_leave();
	}

	sc->sc_ecbusy = 0;
}


code:
/* $OpenBSD: acpihpet.c,v 1.19 2015/08/04 22:22:28 deraadt Exp $ */
/*
 * Copyright (c) 2005 Thorsten Lockert <tholo@sigmasoft.com>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/device.h>
#include <sys/timetc.h>

#include <machine/bus.h>

#include <dev/acpi/acpireg.h>
#include <dev/acpi/acpivar.h>
#include <dev/acpi/acpidev.h>

int acpihpet_attached;

int acpihpet_match(struct device *, void *, void *);
void acpihpet_attach(struct device *, struct device *, void *);
int acpihpet_activate(struct device *, int);

u_int acpihpet_gettime(struct timecounter *tc);

u_int64_t	acpihpet_r(bus_space_tag_t _iot, bus_space_handle_t _ioh,
		    bus_size_t _ioa);
void		acpihpet_w(bus_space_tag_t _iot, bus_space_handle_t _ioh,
		    bus_size_t _ioa, u_int64_t _val);

static struct timecounter hpet_timecounter = {
	acpihpet_gettime,	/* get_timecount */
	0,			/* no poll_pps */
	0xffffffff,		/* counter_mask (24 bits) */
	0,			/* frequency */
	0,			/* name */
	1000			/* quality */
};

#define HPET_TIMERS	3
struct hpet_regs {
	u_int64_t	configuration;
	u_int64_t	interrupt_status;
	u_int64_t	main_counter;
	struct {	/* timers */
		u_int64_t config;
		u_int64_t compare;
		u_int64_t interrupt;
	} timers[HPET_TIMERS];
};

struct acpihpet_softc {
	struct device		sc_dev;

	bus_space_tag_t		sc_iot;
	bus_space_handle_t	sc_ioh;

	u_int32_t		sc_conf;
	struct hpet_regs	sc_save;
};

struct cfattach acpihpet_ca = {
	sizeof(struct acpihpet_softc), acpihpet_match, acpihpet_attach,
	NULL, acpihpet_activate
};

struct cfdriver acpihpet_cd = {
	NULL, "acpihpet", DV_DULL
};

u_int64_t
acpihpet_r(bus_space_tag_t iot, bus_space_handle_t ioh, bus_size_t ioa)
{
	u_int64_t val;

	val = bus_space_read_4(iot, ioh, ioa + 4);
	val = val << 32;
	val |= bus_space_read_4(iot, ioh, ioa);
	return (val);
}

void
acpihpet_w(bus_space_tag_t iot, bus_space_handle_t ioh, bus_size_t ioa,
    u_int64_t val)
{
	bus_space_write_4(iot, ioh, ioa + 4, val >> 32);
	bus_space_write_4(iot, ioh, ioa, val & 0xffffffff);
}

int
acpihpet_activate(struct device *self, int act)
{
	struct acpihpet_softc *sc = (struct acpihpet_softc *) self;

	switch (act) {
	case DVACT_SUSPEND:
		/* stop, then save */
		bus_space_write_4(sc->sc_iot, sc->sc_ioh,
		    HPET_CONFIGURATION, sc->sc_conf);

		sc->sc_save.configuration = acpihpet_r(sc->sc_iot,
		    sc->sc_ioh, HPET_CONFIGURATION);
		sc->sc_save.interrupt_status = acpihpet_r(sc->sc_iot,
		    sc->sc_ioh, HPET_INTERRUPT_STATUS);
		sc->sc_save.main_counter = acpihpet_r(sc->sc_iot,
		    sc->sc_ioh, HPET_MAIN_COUNTER);
		sc->sc_save.timers[0].config = acpihpet_r(sc->sc_iot,
		    sc->sc_ioh, HPET_TIMER0_CONFIG);
		sc->sc_save.timers[0].interrupt = acpihpet_r(sc->sc_iot,
		    sc->sc_ioh, HPET_TIMER0_INTERRUPT);
		sc->sc_save.timers[0].compare = acpihpet_r(sc->sc_iot,
		    sc->sc_ioh, HPET_TIMER0_COMPARE);
		sc->sc_save.timers[1].config = acpihpet_r(sc->sc_iot,
		    sc->sc_ioh, HPET_TIMER1_CONFIG);
		sc->sc_save.timers[1].interrupt = acpihpet_r(sc->sc_iot,
		    sc->sc_ioh, HPET_TIMER1_INTERRUPT);
		sc->sc_save.timers[1].compare = acpihpet_r(sc->sc_iot,
		    sc->sc_ioh, HPET_TIMER1_COMPARE);
		sc->sc_save.timers[2].config = acpihpet_r(sc->sc_iot,
		    sc->sc_ioh, HPET_TIMER2_CONFIG);
		sc->sc_save.timers[2].interrupt = acpihpet_r(sc->sc_iot,
		    sc->sc_ioh, HPET_TIMER2_INTERRUPT);
		sc->sc_save.timers[2].compare = acpihpet_r(sc->sc_iot,
		    sc->sc_ioh, HPET_TIMER2_COMPARE);
		break;
	case DVACT_RESUME:
		/* stop, restore, then restart */
		bus_space_write_4(sc->sc_iot, sc->sc_ioh,
		    HPET_CONFIGURATION, sc->sc_conf);

		acpihpet_w(sc->sc_iot, sc->sc_ioh,
		    HPET_CONFIGURATION, sc->sc_save.configuration);
		acpihpet_w(sc->sc_iot, sc->sc_ioh,
		    HPET_INTERRUPT_STATUS, sc->sc_save.interrupt_status);
		acpihpet_w(sc->sc_iot, sc->sc_ioh,
		    HPET_MAIN_COUNTER, sc->sc_save.main_counter);
		acpihpet_w(sc->sc_iot, sc->sc_ioh,
		    HPET_TIMER0_CONFIG, sc->sc_save.timers[0].config);
		acpihpet_w(sc->sc_iot, sc->sc_ioh,
		    HPET_TIMER0_INTERRUPT, sc->sc_save.timers[0].interrupt);
		acpihpet_w(sc->sc_iot, sc->sc_ioh,
		    HPET_TIMER0_COMPARE, sc->sc_save.timers[0].compare);
		acpihpet_w(sc->sc_iot, sc->sc_ioh,
		    HPET_TIMER1_CONFIG, sc->sc_save.timers[1].config);
		acpihpet_w(sc->sc_iot, sc->sc_ioh,
		    HPET_TIMER1_INTERRUPT, sc->sc_save.timers[1].interrupt);
		acpihpet_w(sc->sc_iot, sc->sc_ioh,
		    HPET_TIMER1_COMPARE, sc->sc_save.timers[1].compare);
		acpihpet_w(sc->sc_iot, sc->sc_ioh,
		    HPET_TIMER2_CONFIG, sc->sc_save.timers[2].config);
		acpihpet_w(sc->sc_iot, sc->sc_ioh,
		    HPET_TIMER2_INTERRUPT, sc->sc_save.timers[2].interrupt);
		acpihpet_w(sc->sc_iot, sc->sc_ioh,
		    HPET_TIMER2_COMPARE, sc->sc_save.timers[2].compare);
		bus_space_write_4(sc->sc_iot, sc->sc_ioh,
		    HPET_CONFIGURATION, sc->sc_conf | 1);
		break;
	}

	return 0;
}

int
acpihpet_match(struct device *parent, void *match, void *aux)
{
	struct acpi_attach_args *aaa = aux;
	struct acpi_table_header *hdr;

	/*
	 * If we do not have a table, it is not us; attach only once
	 */
	if (acpihpet_attached || aaa->aaa_table == NULL)
		return (0);

	/*
	 * If it is an HPET table, we can attach
	 */
	hdr = (struct acpi_table_header *)aaa->aaa_table;
	if (memcmp(hdr->signature, HPET_SIG, sizeof(HPET_SIG) - 1) != 0)
		return (0);

	return (1);
}

void
acpihpet_attach(struct device *parent, struct device *self, void *aux)
{
	struct acpihpet_softc *sc = (struct acpihpet_softc *) self;
	struct acpi_softc *psc = (struct acpi_softc *)parent;
	struct acpi_attach_args *aaa = aux;
	struct acpi_hpet *hpet = (struct acpi_hpet *)aaa->aaa_table;
	u_int64_t period, freq;	/* timer period in femtoseconds (10^-15) */
	u_int32_t v1, v2;
	int timeout;

	if (acpi_map_address(psc, &hpet->base_address, 0, HPET_REG_SIZE,
	    &sc->sc_ioh, &sc->sc_iot))	{
		printf(": can't map i/o space\n");
		return;
	}

	/*
	 * Revisions 0x30 through 0x3a of the AMD SB700, with spread
	 * spectrum enabled, have an SMM based HPET emulation that's
	 * subtly broken.  The hardware is initialized upon first
	 * access of the configuration register.  Initialization takes
	 * some time during which the configuration register returns
	 * 0xffffffff.
	 */
	timeout = 1000;
	do {
		if (bus_space_read_4(sc->sc_iot, sc->sc_ioh,
		    HPET_CONFIGURATION) != 0xffffffff)
			break;
	} while(--timeout > 0);

	if (timeout == 0) {
		printf(": disabled\n");
		return;
	}

	/* enable hpet */
	sc->sc_conf = bus_space_read_4(sc->sc_iot, sc->sc_ioh,
	    HPET_CONFIGURATION) & ~1;
	bus_space_write_4(sc->sc_iot, sc->sc_ioh, HPET_CONFIGURATION,
	    sc->sc_conf | 1);

	/* make sure hpet is working */
	v1 = bus_space_read_4(sc->sc_iot, sc->sc_ioh, HPET_MAIN_COUNTER);
	delay(1);
	v2 = bus_space_read_4(sc->sc_iot, sc->sc_ioh, HPET_MAIN_COUNTER);
	if (v1 == v2) {
		printf(": counter not incrementing\n");
		bus_space_write_4(sc->sc_iot, sc->sc_ioh,
		    HPET_CONFIGURATION, sc->sc_conf);
		return;
	}

	period = bus_space_read_4(sc->sc_iot, sc->sc_ioh,
	    HPET_CAPABILITIES + sizeof(u_int32_t));
	if (period == 0) {
		printf(": invalid period\n");
		bus_space_write_4(sc->sc_iot, sc->sc_ioh,
		    HPET_CONFIGURATION, sc->sc_conf);
		return;
	}
	freq =  1000000000000000ull / period;
	printf(": %lld Hz\n", freq);

	hpet_timecounter.tc_frequency = (u_int32_t)freq;
	hpet_timecounter.tc_priv = sc;
	hpet_timecounter.tc_name = sc->sc_dev.dv_xname;
	tc_init(&hpet_timecounter);
	acpihpet_attached++;
}

u_int
acpihpet_gettime(struct timecounter *tc)
{
	struct acpihpet_softc *sc = tc->tc_priv;

	return (bus_space_read_4(sc->sc_iot, sc->sc_ioh, HPET_MAIN_COUNTER));
}


code:
/* $OpenBSD: acpimadt.c,v 1.32 2015/06/26 18:12:23 guenther Exp $ */
/*
 * Copyright (c) 2006 Mark Kettenis <kettenis@openbsd.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/device.h>
#include <sys/malloc.h>

#include <machine/apicvar.h>
#include <machine/cpuvar.h>
#include <machine/bus.h>

#include <dev/acpi/acpireg.h>
#include <dev/acpi/acpivar.h>
#include <dev/acpi/acpidev.h>
#include <dev/acpi/amltypes.h>
#include <dev/acpi/dsdt.h>

#include <machine/i8259.h>
#include <machine/i82093reg.h>
#include <machine/i82093var.h>
#include <machine/i82489reg.h>
#include <machine/i82489var.h>

#include <machine/mpbiosvar.h>

#include "ioapic.h"

u_int8_t acpi_lapic_flags[LAPIC_MAP_SIZE];

int acpimadt_match(struct device *, void *, void *);
void acpimadt_attach(struct device *, struct device *, void *);

struct cfattach acpimadt_ca = {
	sizeof(struct device), acpimadt_match, acpimadt_attach
};

struct cfdriver acpimadt_cd = {
	NULL, "acpimadt", DV_DULL
};

int acpimadt_validate(struct acpi_madt *);
int acpimadt_cfg_intr(int, u_int32_t *);
int acpimadt_print(void *, const char *);

int
acpimadt_match(struct device *parent, void *match, void *aux)
{
	struct acpi_attach_args *aaa = aux;
	struct acpi_table_header *hdr;

	/*
	 * If we do not have a table, it is not us
	 */
	if (aaa->aaa_table == NULL)
		return (0);

	/*
	 * If it is an MADT table, we can attach
	 */
	hdr = (struct acpi_table_header *)aaa->aaa_table;
	if (memcmp(hdr->signature, MADT_SIG, sizeof(MADT_SIG) - 1) != 0)
		return (0);

	return (1);
}

int
acpimadt_validate(struct acpi_madt *madt)
{
	caddr_t addr = (caddr_t)(madt + 1);

	while (addr < (caddr_t)madt + madt->hdr.length) {
		union acpi_madt_entry *entry = (union acpi_madt_entry *)addr;
		u_int8_t length = entry->madt_lapic.length;

		if (length < 2)
			return (0);

		if (addr + length > (caddr_t)madt + madt->hdr.length)
			return (0);

		switch (entry->madt_lapic.apic_type) {
		case ACPI_MADT_LAPIC:
			if (length != sizeof(entry->madt_lapic))
				return (0);
			break;
		case ACPI_MADT_IOAPIC:
			if (length != sizeof(entry->madt_ioapic))
				return (0);
			break;
		case ACPI_MADT_OVERRIDE:
			if (length != sizeof(entry->madt_override))
				return (0);
			break;
		case ACPI_MADT_NMI:
			if (length != sizeof(entry->madt_nmi))
				return (0);
			break;
		case ACPI_MADT_LAPIC_NMI:
			if (length != sizeof(entry->madt_lapic_nmi))
				return (0);
			break;
		case ACPI_MADT_LAPIC_OVERRIDE:
			if (length != sizeof(entry->madt_lapic_override))
				return (0);
			break;
		case ACPI_MADT_IO_SAPIC:
			if (length != sizeof(entry->madt_io_sapic))
				return (0);
			break;
		case ACPI_MADT_LOCAL_SAPIC:
			if (length != sizeof(entry->madt_local_sapic))
				return (0);
			break;
		case ACPI_MADT_PLATFORM_INT:
			if (length != sizeof(entry->madt_platform_int))
				return (0);
			break;
		case ACPI_MADT_X2APIC:
			if (length != sizeof(entry->madt_x2apic))
				return (0);
			break;
		case ACPI_MADT_X2APIC_NMI:
			if (length != sizeof(entry->madt_x2apic_nmi))
				return (0);
			break;
		}

		addr += length;
	}

	return (1);
}

struct mp_bus acpimadt_busses[256];
struct mp_bus acpimadt_isa_bus;

int
acpimadt_cfg_intr(int flags, u_int32_t *redir)
{
	int mpspo = (flags >> MPS_INTPO_SHIFT) & MPS_INTPO_MASK;
	int mpstrig = (flags >> MPS_INTTR_SHIFT) & MPS_INTTR_MASK;

	*redir &= ~IOAPIC_REDLO_DEL_MASK;
	switch (mpspo) {
	case MPS_INTPO_DEF:
	case MPS_INTPO_ACTHI:
		*redir &= ~IOAPIC_REDLO_ACTLO;
		break;
	case MPS_INTPO_ACTLO:
		*redir |= IOAPIC_REDLO_ACTLO;
		break;
	default:
		return (0);
	}

	*redir |= (IOAPIC_REDLO_DEL_LOPRI << IOAPIC_REDLO_DEL_SHIFT);

	switch (mpstrig) {
	case MPS_INTTR_LEVEL:
		*redir |= IOAPIC_REDLO_LEVEL;
		break;
	case MPS_INTTR_DEF:
	case MPS_INTTR_EDGE:
		*redir &= ~IOAPIC_REDLO_LEVEL;
		break;
	default:
		return (0);
	}

	return (1);
}

static u_int8_t lapic_map[256];

void
acpimadt_attach(struct device *parent, struct device *self, void *aux)
{
	struct acpi_softc *acpi_sc = (struct acpi_softc *)parent;
	struct device *mainbus = parent->dv_parent->dv_parent;
	struct acpi_attach_args *aaa = aux;
	struct acpi_madt *madt = (struct acpi_madt *)aaa->aaa_table;
	caddr_t addr = (caddr_t)(madt + 1);
	struct aml_value arg;
	struct mp_intr_map *map;
	struct ioapic_softc *apic;
	int nlapic_nmis = 0;
	int pin;

	/* Do some sanity checks before committing to run in APIC mode. */
	if (!acpimadt_validate(madt)) {
		printf(": invalid, skipping\n");
		return;
	}

	printf(" addr 0x%x", madt->local_apic_address);
	if (madt->flags & ACPI_APIC_PCAT_COMPAT)
		printf(": PC-AT compat");
	printf("\n");

	/* Tell the BIOS we will be using APIC mode. */
	memset(&arg, 0, sizeof(arg));
	arg.type = AML_OBJTYPE_INTEGER;
	arg.v_integer = 1;

	aml_evalname(acpi_sc, NULL, "\\_PIC", 1, &arg, NULL);

	mp_busses = acpimadt_busses;
	mp_nbusses = nitems(acpimadt_busses);
	mp_isa_bus = &acpimadt_isa_bus;

	lapic_boot_init(madt->local_apic_address);

	/* 1st pass, get CPUs and IOAPICs */
	while (addr < (caddr_t)madt + madt->hdr.length) {
		union acpi_madt_entry *entry = (union acpi_madt_entry *)addr;
		struct cpu_attach_args caa;
		struct apic_attach_args aaa;

		switch (entry->madt_lapic.apic_type) {
		case ACPI_MADT_LAPIC:
			dprintf("%s: LAPIC: acpi_proc_id %x, apic_id %x, flags 0x%x\n",
			    self->dv_xname, entry->madt_lapic.acpi_proc_id,
			    entry->madt_lapic.apic_id,
			    entry->madt_lapic.flags);

			if ((entry->madt_lapic.flags & ACPI_PROC_ENABLE) == 0)
				break;

			lapic_map[entry->madt_lapic.acpi_proc_id] =
			    entry->madt_lapic.apic_id;
			acpi_lapic_flags[entry->madt_lapic.acpi_proc_id] =
			    entry->madt_lapic.flags;

			memset(&caa, 0, sizeof(struct cpu_attach_args));
			if (lapic_cpu_number() == entry->madt_lapic.apic_id)
				caa.cpu_role = CPU_ROLE_BP;
			else {
				caa.cpu_role = CPU_ROLE_AP;
				ncpusfound++;
			}
			caa.caa_name = "cpu";
			caa.cpu_number = entry->madt_lapic.apic_id;
#ifdef MULTIPROCESSOR
			caa.cpu_func = &mp_cpu_funcs;
#endif
#ifdef __i386__
			/*
			 * XXX utterly wrong.  These are the
			 * cpu_feature/cpu_id from the BSP cpu, now
			 * being given to another cpu.  This is
			 * bullshit.
			 */
			extern int cpu_id, cpu_feature;
			caa.cpu_signature = cpu_id;
			caa.feature_flags = cpu_feature;
#endif

			config_found(mainbus, &caa, acpimadt_print);
			break;
		case ACPI_MADT_IOAPIC:
			dprintf("%s: IOAPIC: acpi_ioapic_id %x, address 0x%x, global_int_base 0x%x\n",
			    self->dv_xname, entry->madt_ioapic.acpi_ioapic_id,
			    entry->madt_ioapic.address,
			    entry->madt_ioapic.global_int_base);

			memset(&aaa, 0, sizeof(struct apic_attach_args));
			aaa.aaa_name = "ioapic";
			aaa.apic_id = entry->madt_ioapic.acpi_ioapic_id;
			aaa.apic_address = entry->madt_ioapic.address;
			aaa.apic_vecbase = entry->madt_ioapic.global_int_base;

			config_found(mainbus, &aaa, acpimadt_print);
			break;
		case ACPI_MADT_LAPIC_NMI:
			nlapic_nmis++;
			break;
		}
		addr += entry->madt_lapic.length;
	}

	mp_intrs = mallocarray(nlapic_nmis, sizeof(struct mp_intr_map),
	    M_DEVBUF, M_NOWAIT);
	if (mp_intrs == NULL)
		return;

	/* 2nd pass, get interrupt overrides */
	addr = (caddr_t)(madt + 1);
	while (addr < (caddr_t)madt + madt->hdr.length) {
		union acpi_madt_entry *entry = (union acpi_madt_entry *)addr;

		switch (entry->madt_lapic.apic_type) {
		case ACPI_MADT_LAPIC:
		case ACPI_MADT_IOAPIC:
			break;

		case ACPI_MADT_OVERRIDE:
			dprintf("%s: OVERRIDE: bus %x, source %x, global_int %x, flags %x\n",
			    self->dv_xname, entry->madt_override.bus,
			    entry->madt_override.source,
			    entry->madt_override.global_int,
			    entry->madt_override.flags);

			pin = entry->madt_override.global_int;
			apic = ioapic_find_bybase(pin);

			map = malloc(sizeof(*map), M_DEVBUF, M_NOWAIT | M_ZERO);
			if (map == NULL)
				return;

			map->ioapic = apic;
			map->ioapic_pin = pin - apic->sc_apic_vecbase;
			map->bus_pin = entry->madt_override.source;
			map->flags = entry->madt_override.flags;

			if (!acpimadt_cfg_intr(entry->madt_override.flags, &map->redir)) {
				printf("%s: bogus override for pin %d\n",
				    self->dv_xname, pin);
				free(map, M_DEVBUF, 0);
				break;
			}

			map->ioapic_ih = APIC_INT_VIA_APIC |
			    ((apic->sc_apicid << APIC_INT_APIC_SHIFT) |
			    (pin << APIC_INT_PIN_SHIFT));

			apic->sc_pins[pin].ip_map = map;

			map->next = mp_isa_bus->mb_intrs;
			mp_isa_bus->mb_intrs = map;
			break;

		case ACPI_MADT_LAPIC_NMI:
			dprintf("%s: LAPIC_NMI: acpi_proc_id %x, local_apic_lint %x, flags %x\n",
			    self->dv_xname, entry->madt_lapic_nmi.acpi_proc_id,
			    entry->madt_lapic_nmi.local_apic_lint,
			    entry->madt_lapic_nmi.flags);

			pin = entry->madt_lapic_nmi.local_apic_lint;

			map = &mp_intrs[mp_nintrs++];
			memset(map, 0, sizeof *map);
			map->cpu_id = lapic_map[entry->madt_lapic_nmi.acpi_proc_id];
			map->ioapic_pin = pin;
			map->flags = entry->madt_lapic_nmi.flags;

			if ((pin != 0 && pin != 1) ||
			    !acpimadt_cfg_intr(entry->madt_lapic_nmi.flags, &map->redir)) {
				printf("%s: bogus nmi for apid %d\n",
				    self->dv_xname, map->cpu_id);
				mp_nintrs--;
				break;
			}

			map->redir &= ~IOAPIC_REDLO_DEL_MASK;
			map->redir |= (IOAPIC_REDLO_DEL_NMI << IOAPIC_REDLO_DEL_SHIFT);
			break;

		case ACPI_MADT_X2APIC:
		case ACPI_MADT_X2APIC_NMI:
			break;

		default:
			printf("%s: unknown apic structure type %x\n",
			    self->dv_xname, entry->madt_lapic.apic_type);
		}

		addr += entry->madt_lapic.length;
	}

	/*
	 * ISA interrupts are supposed to be identity mapped unless
	 * there is an override, in which case we will already have a
	 * mapping for the interrupt.
	 */
	for (pin = 0; pin < ICU_LEN; pin++) {
		/* Skip if we already have a mapping for this interrupt. */
		for (map = mp_isa_bus->mb_intrs; map != NULL; map = map->next)
			if (map->bus_pin == pin)
				break;
		if (map != NULL)
			continue;

		apic = ioapic_find_bybase(pin);

		map = malloc(sizeof(*map), M_DEVBUF, M_NOWAIT | M_ZERO);
		if (map == NULL)
			return;

		map->ioapic = apic;
		map->ioapic_pin = pin;
		map->bus_pin = pin;
		map->redir = (IOAPIC_REDLO_DEL_LOPRI << IOAPIC_REDLO_DEL_SHIFT);

		map->ioapic_ih = APIC_INT_VIA_APIC |
		    ((apic->sc_apicid << APIC_INT_APIC_SHIFT) |
		    (pin << APIC_INT_PIN_SHIFT));

		apic->sc_pins[pin].ip_map = map;

		map->next = mp_isa_bus->mb_intrs;
		mp_isa_bus->mb_intrs = map;
	}
}

int
acpimadt_print(void *aux, const char *pnp)
{
	struct apic_attach_args *aaa = aux;

	if (pnp)
		printf("%s at %s:", aaa->aaa_name, pnp);

	return (UNCONF);
}