code:
/*	$OpenBSD: aacreg.h,v 1.11 2009/03/06 07:28:10 grange Exp $	*/

/*-
 * Copyright (c) 2000 Michael Smith
 * Copyright (c) 2000-2001 Scott Long
 * Copyright (c) 2000 BSDi
 * Copyright (c) 2001 Adaptec, Inc.
 * Copyright (c) 2000 Niklas Hallqvist
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	$FreeBSD$
 */

/*
 * Data structures defining the interface between the driver and the Adaptec
 * 'FSA' adapters.  Note that many field names and comments here are taken
 * verbatim from the Adaptec driver source in order to make comparing the
 * two slightly easier.
 */

/*
 * Misc. magic numbers.
 */
#define AAC_MAX_CONTAINERS	64
#define AAC_BLOCK_SIZE		512

/*
 * Communications interface.
 *
 * Where datastructure layouts are closely parallel to the Adaptec sample code,
 * retain their naming conventions (for now) to aid in cross-referencing.
 */

/*
 * We establish 4 command queues and matching response queues.  Queues must
 * be 16-byte aligned, and are sized as follows:
 */
#define AAC_HOST_NORM_CMD_ENTRIES	8	/* command adapter->host,
						 * normal priority */
#define AAC_HOST_HIGH_CMD_ENTRIES	4	/* command adapter->host,
						 * high priority */
#define AAC_ADAP_NORM_CMD_ENTRIES	512	/* command host->adapter,
						 * normal priority */
#define AAC_ADAP_HIGH_CMD_ENTRIES	4	/* command host->adapter,
						 * high priority */
#define AAC_HOST_NORM_RESP_ENTRIES	512	/* response, adapter->host,
						 * normal priority */
#define AAC_HOST_HIGH_RESP_ENTRIES	4	/* response, adapter->host,
						 * high priority */
#define AAC_ADAP_NORM_RESP_ENTRIES	8	/* response, host->adapter,
						 * normal priority */
#define AAC_ADAP_HIGH_RESP_ENTRIES	4	/* response, host->adapter,
						 * high priority */

#define AAC_TOTALQ_LENGTH	(AAC_HOST_HIGH_CMD_ENTRIES +	\
				 AAC_HOST_NORM_CMD_ENTRIES +	\
				 AAC_ADAP_HIGH_CMD_ENTRIES +	\
				 AAC_ADAP_NORM_CMD_ENTRIES +	\
				 AAC_HOST_HIGH_RESP_ENTRIES +	\
				 AAC_HOST_NORM_RESP_ENTRIES +	\
				 AAC_ADAP_HIGH_RESP_ENTRIES +	\
				 AAC_ADAP_NORM_RESP_ENTRIES)
#define AAC_QUEUE_COUNT		8
#define AAC_QUEUE_ALIGN		16

struct aac_queue_entry {
	u_int32_t	aq_fib_size;	/* FIB size in bytes */
	u_int32_t	aq_fib_addr;	/* receiver-space address of the FIB */
} __packed;

#define AAC_PRODUCER_INDEX	0
#define AAC_CONSUMER_INDEX	1

/*
 * Table of queue indices and queues used to communicate with the
 * controller.  This structure must be aligned to AAC_QUEUE_ALIGN
 */
struct aac_queue_table {
	/* queue consumer/producer indexes (layout mandated by adapter) */
	u_int32_t			qt_qindex[AAC_QUEUE_COUNT][2];

	/* queue entry structures (layout mandated by adapter) */
	struct aac_queue_entry qt_HostNormCmdQueue [AAC_HOST_NORM_CMD_ENTRIES];
	struct aac_queue_entry qt_HostHighCmdQueue [AAC_HOST_HIGH_CMD_ENTRIES];
	struct aac_queue_entry qt_AdapNormCmdQueue [AAC_ADAP_NORM_CMD_ENTRIES];
	struct aac_queue_entry qt_AdapHighCmdQueue [AAC_ADAP_HIGH_CMD_ENTRIES];
	struct aac_queue_entry qt_HostNormRespQueue[AAC_HOST_NORM_RESP_ENTRIES];
	struct aac_queue_entry qt_HostHighRespQueue[AAC_HOST_HIGH_RESP_ENTRIES];
	struct aac_queue_entry qt_AdapNormRespQueue[AAC_ADAP_NORM_RESP_ENTRIES];
	struct aac_queue_entry qt_AdapHighRespQueue[AAC_ADAP_HIGH_RESP_ENTRIES];
} __packed;

/*
 * Queue names
 *
 * Note that we base these at 0 in order to use them as array indices.  Adaptec
 * used base 1 for some unknown reason, and sorted them in a different order.
 */
#define AAC_HOST_NORM_CMD_QUEUE		0
#define AAC_HOST_HIGH_CMD_QUEUE		1
#define AAC_ADAP_NORM_CMD_QUEUE		2
#define AAC_ADAP_HIGH_CMD_QUEUE		3
#define AAC_HOST_NORM_RESP_QUEUE	4
#define AAC_HOST_HIGH_RESP_QUEUE	5
#define AAC_ADAP_NORM_RESP_QUEUE	6
#define AAC_ADAP_HIGH_RESP_QUEUE	7

/*
 * List structure used to chain FIBs (used by the adapter - we hang FIBs off
 * our private command structure and don't touch these)
 */
struct aac_fib_list_entry {
	u_int32_t	Flink;
	u_int32_t	Blink;
} __packed;

/*
 * FIB (FSA Interface Block?); this is the datastructure passed between the host
 * and adapter.
 */
struct aac_fib_header {
	u_int32_t		XferState;
	u_int16_t		Command;
	u_int8_t		StructType;
	u_int8_t		Flags;
	u_int16_t		Size;
	u_int16_t		SenderSize;
	u_int32_t		SenderFibAddress;
	u_int32_t		ReceiverFibAddress;
	u_int32_t		SenderData;
	union {
		struct {
			u_int32_t	ReceiverTimeStart;
			u_int32_t	ReceiverTimeDone;
		} _s;
		struct aac_fib_list_entry FibLinks;
	} _u;
} __packed;

#define AAC_FIB_DATASIZE	(512 - sizeof(struct aac_fib_header))

struct aac_fib {
	struct aac_fib_header	Header;
	u_int8_t			data[AAC_FIB_DATASIZE];
} __packed;

/*
 * FIB commands
 */
typedef enum {
	TestCommandResponse =		1,
	TestAdapterCommand =		2,

	/* lowlevel and comm commands */
	LastTestCommand =		100,
	ReinitHostNormCommandQueue =	101,
	ReinitHostHighCommandQueue =	102,
	ReinitHostHighRespQueue =	103,
	ReinitHostNormRespQueue =	104,
	ReinitAdapNormCommandQueue =	105,
	ReinitAdapHighCommandQueue =	107,
	ReinitAdapHighRespQueue =	108,
	ReinitAdapNormRespQueue =	109,
	InterfaceShutdown =		110,
	DmaCommandFib =			120,
	StartProfile =			121,
	TermProfile =			122,
	SpeedTest =			123,
	TakeABreakPt =			124,
	RequestPerfData =		125,
	SetInterruptDefTimer=		126,
	SetInterruptDefCount=		127,
	GetInterruptDefStatus=		128,
	LastCommCommand =		129,

	/* filesystem commands */
	NuFileSystem =			300,
	UFS =				301,
	HostFileSystem =		302,
	LastFileSystemCommand =		303,

	/* Container Commands */
	ContainerCommand =		500,
	ContainerCommand64 =		501,

	/* Cluster Commands */
	ClusterCommand =		550,

	/* Scsi Port commands (scsi passthrough) */
	ScsiPortCommand =		600,

	/* misc house keeping and generic adapter initiated commands */
	AifRequest =			700,
	CheckRevision =			701,
	FsaHostShutdown =		702,
	RequestAdapterInfo =		703,
	IsAdapterPaused =		704,
	SendHostTime =			705,
	LastMiscCommand =		706
} AAC_FibCommands;

/*
 * FIB types
 */
#define AAC_FIBTYPE_TFIB	1
#define AAC_FIBTYPE_TQE		2
#define AAC_FIBTYPE_TCTPERF	3

/*
 * FIB transfer state
 */
#define AAC_FIBSTATE_HOSTOWNED		(1<<0)	/* owned by the host */
#define AAC_FIBSTATE_ADAPTEROWNED	(1<<1)	/* owned by the adapter */
#define AAC_FIBSTATE_INITIALISED	(1<<2)	/* initialised */
#define AAC_FIBSTATE_EMPTY		(1<<3)	/* empty */
#define AAC_FIBSTATE_FROMPOOL		(1<<4)	/* allocated from pool */
#define AAC_FIBSTATE_FROMHOST		(1<<5)	/* sent from the host */
#define AAC_FIBSTATE_FROMADAP		(1<<6)	/* sent from the adapter */
#define AAC_FIBSTATE_REXPECTED		(1<<7)	/* response is expected */
#define AAC_FIBSTATE_RNOTEXPECTED	(1<<8)	/* response is not expected */
#define AAC_FIBSTATE_DONEADAP		(1<<9)	/* processed by the adapter */
#define AAC_FIBSTATE_DONEHOST		(1<<10)	/* processed by the host */
#define AAC_FIBSTATE_HIGH		(1<<11)	/* high priority */
#define AAC_FIBSTATE_NORM		(1<<12)	/* normal priority */
#define AAC_FIBSTATE_ASYNC		(1<<13)
#define AAC_FIBSTATE_ASYNCIO		(1<<13)	/* to be removed */
#define AAC_FIBSTATE_PAGEFILEIO		(1<<14)	/* to be removed */
#define AAC_FIBSTATE_SHUTDOWN		(1<<15)
#define AAC_FIBSTATE_LAZYWRITE		(1<<16)	/* to be removed */
#define AAC_FIBSTATE_ADAPMICROFIB	(1<<17)
#define AAC_FIBSTATE_BIOSFIB		(1<<18)
#define AAC_FIBSTATE_FAST_RESPONSE	(1<<19)	/* fast response capable */
#define AAC_FIBSTATE_APIFIB		(1<<20)

/*
 * FIB error values
 */
#define AAC_ERROR_NORMAL			0x00
#define AAC_ERROR_PENDING			0x01
#define AAC_ERROR_FATAL				0x02
#define AAC_ERROR_INVALID_QUEUE			0x03
#define AAC_ERROR_NOENTRIES			0x04
#define AAC_ERROR_SENDFAILED			0x05
#define AAC_ERROR_INVALID_QUEUE_PRIORITY	0x06
#define AAC_ERROR_FIB_ALLOCATION_FAILED		0x07
#define AAC_ERROR_FIB_DEALLOCATION_FAILED	0x08

/*
 * Adapter Init Structure: this is passed to the adapter with the
 * AAC_MONKER_INITSTRUCT command to point it at our control structures.
 */
struct aac_adapter_init {
	u_int32_t	InitStructRevision;
#define AAC_INIT_STRUCT_REVISION		3
	u_int32_t	MiniPortRevision;
#define AAC_INIT_STRUCT_MINIPORT_REVISION	1
	u_int32_t	FilesystemRevision;
	u_int32_t	CommHeaderAddress;
	u_int32_t	FastIoCommAreaAddress;
	u_int32_t	AdapterFibsPhysicalAddress;
	u_int32_t 	AdapterFibsVirtualAddress;
	u_int32_t	AdapterFibsSize;
	u_int32_t	AdapterFibAlign;
	u_int32_t	PrintfBufferAddress;
	u_int32_t	PrintfBufferSize;
#define	AAC_PAGE_SIZE				4096
	u_int32_t	HostPhysMemPages;
	u_int32_t	HostElapsedSeconds;
} __packed;

/*
 * Shared data types
 */
/*
 * Container types
 */
typedef enum {
	CT_NONE = 0,
	CT_VOLUME,
	CT_MIRROR,
	CT_STRIPE,
	CT_RAID5,
	CT_SSRW,
	CT_SSRO,
	CT_MORPH,
	CT_PASSTHRU,
	CT_RAID4,
	CT_RAID10,                  /* stripe of mirror */
	CT_RAID00,                  /* stripe of stripe */
	CT_VOLUME_OF_MIRRORS,       /* volume of mirror */
	CT_PSEUDO_RAID3,            /* really raid4 */
	CT_RAID50,		    /* stripe of raid5 */
} AAC_FSAVolType;

/*
 * Host-addressable object types
 */
typedef enum {
	FT_REG = 1,     /* regular file */
	FT_DIR,         /* directory */
	FT_BLK,         /* "block" device - reserved */
	FT_CHR,         /* "character special" device - reserved */
	FT_LNK,         /* symbolic link */
	FT_SOCK,        /* socket */
	FT_FIFO,        /* fifo */
	FT_FILESYS,     /* ADAPTEC's "FSA"(tm) filesystem */
	FT_DRIVE,       /* physical disk - addressable in scsi by b/t/l */
	FT_SLICE,       /* virtual disk - raw volume - slice */
	FT_PARTITION,   /* FSA partition - carved out of a slice - building
			 * block for containers */
	FT_VOLUME,      /* Container - Volume Set */
	FT_STRIPE,      /* Container - Stripe Set */
	FT_MIRROR,      /* Container - Mirror Set */
	FT_RAID5,       /* Container - Raid 5 Set */
	FT_DATABASE     /* Storage object with "foreign" content manager */
} AAC_FType;

/*
 * Host-side scatter/gather list for 32-bit commands.
 */
struct aac_sg_entry {
	u_int32_t	SgAddress;
	u_int32_t	SgByteCount;
} __packed;

struct aac_sg_entry64 {
	u_int64_t	SgAddress;
	u_int32_t	SgByteCount;
} __packed;

struct aac_sg_table {
	u_int32_t		SgCount;
	struct aac_sg_entry	SgEntry[0];
} __packed;

/*
 * Host-side scatter/gather list for 64-bit commands.
 */
struct aac_sg_table64 {
	u_int32_t	SgCount;
	struct aac_sg_entry64	SgEntry64[0];
} __packed;

/*
 * Container creation data
 */
struct aac_container_creation {
	u_int8_t	ViaBuildNumber;
	u_int8_t	MicroSecond;
	u_int8_t	Via;		/* 1 = FSU, 2 = API, etc. */
	u_int8_t	YearsSince1900;
	u_int32_t	Month:4;	/* 1-12 */
	u_int32_t	Day:6;		/* 1-32 */
	u_int32_t	Hour:6;		/* 0-23 */
	u_int32_t	Minute:6;	/* 0-59 */
	u_int32_t	Second:6;	/* 0-59 */
	u_int64_t	ViaAdapterSerialNumber;
} __packed;

/*
 * Revision number handling
 */

typedef enum {
	RevApplication = 1,
	RevDkiCli,
	RevNetService,
	RevApi,
	RevFileSysDriver,
	RevMiniportDriver,
	RevAdapterSW,
	RevMonitor,
	RevRemoteApi
} RevComponent;

struct FsaRevision {
	union {
		struct {
			u_int8_t	dash;
			u_int8_t	type;
			u_int8_t	minor;
			u_int8_t	major;
		} comp;
		u_int32_t	ul;
	} external;
	u_int32_t	buildNumber;
}  __packed;

/*
 * Adapter Information
 */

typedef enum {
	CPU_NTSIM = 1,
	CPU_I960,
	CPU_ARM,
	CPU_SPARC,
	CPU_POWERPC,
	CPU_ALPHA,
	CPU_P7,
	CPU_I960_RX,
	CPU_MIPS,
	CPU_XSCALE,
	CPU__last
} AAC_CpuType;

typedef enum {
	CPUI960_JX = 1,
	CPUI960_CX,
	CPUI960_HX,
	CPUI960_RX,
	CPUARM_SA110,
	CPUARM_xxx,
	CPUMPC_824x,
	CPUPPC_xxx,
	CPUI960_302,
	CPU_XSCALE_80321,
	CPU_MIPS_4KC,
	CPU_MIPS_5KC,
	CPUSUBTYPE__last
} AAC_CpuSubType;

typedef enum {
	PLAT_NTSIM = 1,
	PLAT_V3ADU,
	PLAT_CYCLONE,
	PLAT_CYCLONE_HD,
	PLAT_BATBOARD,
	PLAT_BATBOARD_HD,
	PLAT_YOLO,
	PLAT_COBRA,
	PLAT_ANAHEIM,
	PLAT_JALAPENO,
	PLAT_QUEENS,
	PLAT_JALAPENO_DELL,
	PLAT_POBLANO,
	PLAT_POBLANO_OPAL,
	PLAT_POBLANO_SL0,
	PLAT_POBLANO_SL1,
	PLAT_POBLANO_SL2,
	PLAT_POBLANO_XXX,
	PLAT_JALAPENO_P2,
	PLAT_HABANERO,
	PLAT__last
} AAC_Platform;

typedef enum {
	OEM_FLAVOR_ADAPTEC = 1,
	OEM_FLAVOR_DELL,
	OEM_FLAVOR_HP,
	OEM_FLAVOR_IBM,
	OEM_FLAVOR_CPQ,
	OEM_FLAVOR_BRAND_X,
	OEM_FLAVOR_BRAND_Y,
	OEM_FLAVOR_BRAND_Z,
	OEM_FLAVOR__last
} AAC_OemFlavor;

/*
 * XXX the aac-2622 with no battery present reports PLATFORM_BAT_OPT_PRESENT
 */
typedef enum
{
	PLATFORM_BAT_REQ_PRESENT = 1,	/* BATTERY REQUIRED AND PRESENT */
	PLATFORM_BAT_REQ_NOTPRESENT,	/* BATTERY REQUIRED AND NOT PRESENT */
	PLATFORM_BAT_OPT_PRESENT,	/* BATTERY OPTIONAL AND PRESENT */
	PLATFORM_BAT_OPT_NOTPRESENT,	/* BATTERY OPTIONAL AND NOT PRESENT */
	PLATFORM_BAT_NOT_SUPPORTED	/* BATTERY NOT SUPPORTED */
} AAC_BatteryPlatform;

/*
 * options supported by this board
 * there has to be a one to one mapping of these defines and the ones in
 * fsaapi.h, search for FSA_SUPPORT_SNAPSHOT
 */
#define AAC_SUPPORTED_SNAPSHOT		0x01
#define AAC_SUPPORTED_CLUSTERS		0x02
#define AAC_SUPPORTED_WRITE_CACHE	0x04
#define AAC_SUPPORTED_64BIT_DATA	0x08
#define AAC_SUPPORTED_HOST_TIME_FIB	0x10
#define AAC_SUPPORTED_RAID50		0x20
#define AAC_SUPPORTED_4GB_WINDOW	0x40
#define AAC_SUPPORTED_SCSI_UPGRADEABLE	0x80
#define AAC_SUPPORTED_SOFT_ERR_REPORT	0x100
#define AAC_SUPPORTED_NOT_RECONDITION	0x200
#define AAC_SUPPORTED_SGMAP_HOST64	0x400
#define AAC_SUPPORTED_ALARM		0x800
#define AAC_SUPPORTED_NONDASD		0x1000

/*
 * Structure used to respond to a RequestAdapterInfo fib.
 */
struct aac_adapter_info {
	AAC_Platform		PlatformBase;    /* adapter type */
	AAC_CpuType		CpuArchitecture; /* adapter CPU type */
	AAC_CpuSubType		CpuVariant;      /* adapter CPU subtype */
	u_int32_t		ClockSpeed;      /* adapter CPU clockspeed */
	u_int32_t		ExecutionMem;    /* adapter Execution Memory
						  * size */
	u_int32_t		BufferMem;       /* adapter Data Memory */
	u_int32_t		TotalMem;        /* adapter Total Memory */
	struct FsaRevision	KernelRevision;  /* adapter Kernel Software
						  * Revision */
	struct FsaRevision	MonitorRevision; /* adapter Monitor/Diagnostic
						  * Software Revision */
	struct FsaRevision	HardwareRevision;/* TBD */
	struct FsaRevision	BIOSRevision;    /* adapter BIOS Revision */
	u_int32_t		ClusteringEnabled;
	u_int32_t		ClusterChannelMask;
	u_int64_t		SerialNumber;
	AAC_BatteryPlatform	batteryPlatform;
	u_int32_t		SupportedOptions; /* supported features of this
						   * controller */
	AAC_OemFlavor	OemVariant;
} __packed;

/*
 * Monitor/Kernel interface.
 */

/*
 * Synchronous commands to the monitor/kernel.
 */
#define AAC_MONKER_INITSTRUCT	0x05
#define AAC_MONKER_SYNCFIB	0x0c
#define AAC_MONKER_GETKERNVER	0x11
#define AAC_MONKER_GETINFO	0x19

/*
 *  Adapter Status Register
 *
 *  Phase Staus mailbox is 32bits:
 *  <31:16> = Phase Status
 *  <15:0>  = Phase
 *
 *  The adapter reports its present state through the phase.  Only
 *  a single phase should be ever be set.  Each phase can have multiple
 *  phase status bits to provide more detailed information about the
 *  state of the adapter.
 */
#define AAC_SELF_TEST_FAILED	0x00000004
#define AAC_UP_AND_RUNNING	0x00000080
#define AAC_KERNEL_PANIC	0x00000100

/*
 * Data types relating to control and monitoring of the NVRAM/WriteCache
 * subsystem.
 */

#define AAC_NFILESYS	24	/* maximum number of filesystems */

/*
 * NVRAM/Write Cache subsystem states
 */
typedef enum {
	NVSTATUS_DISABLED = 0,	/* present, clean, not being used */
	NVSTATUS_ENABLED,	/* present, possibly dirty, ready for use */
	NVSTATUS_ERROR,		/* present, dirty, contains dirty data */
	NVSTATUS_BATTERY,	/* present, bad or low battery, may contain
				 * dirty data */
	NVSTATUS_UNKNOWN	/* for bad/missing device */
} AAC_NVSTATUS;

/*
 * NVRAM/Write Cache subsystem battery component states
 *
 */
typedef enum {
	NVBATTSTATUS_NONE = 0,	/* battery has no power or is not present */
	NVBATTSTATUS_LOW,	/* battery is low on power */
	NVBATTSTATUS_OK,	/* battery is okay - normal operation possible
				 * only in this state */
	NVBATTSTATUS_RECONDITIONING	/* no battery present - reconditioning
					 * in process */
} AAC_NVBATTSTATUS;

/*
 * Battery transition type
 */
typedef enum {
	NVBATT_TRANSITION_NONE = 0,	/* battery now has no power or is not
					 * present */
	NVBATT_TRANSITION_LOW,		/* battery is now low on power */
	NVBATT_TRANSITION_OK		/* battery is now okay - normal
					 * operation possible only in this
					 * state */
} AAC_NVBATT_TRANSITION;

/*
 * NVRAM Info structure returned for NVRAM_GetInfo call
 */
struct aac_nvramdevinfo {
	u_int32_t	NV_Enabled;	/* write caching enabled */
	u_int32_t	NV_Error;	/* device in error state */
	u_int32_t	NV_NDirty;	/* count of dirty NVRAM buffers */
	u_int32_t	NV_NActive;	/* count of NVRAM buffers being
					 * written */
} __packed;

struct aac_nvraminfo {
	AAC_NVSTATUS		NV_Status;	/* nvram subsystem status */
	AAC_NVBATTSTATUS	NV_BattStatus;	/* battery status */
	u_int32_t		NV_Size;	/* size of WriteCache NVRAM in
						 * bytes */
	u_int32_t		NV_BufSize;	/* size of NVRAM buffers in
						 * bytes */
	u_int32_t		NV_NBufs;	/* number of NVRAM buffers */
	u_int32_t		NV_NDirty;	/* Num dirty NVRAM buffers */
	u_int32_t		NV_NClean;	/* Num clean NVRAM buffers */
	u_int32_t		NV_NActive;	/* Num NVRAM buffers being
						 * written */
	u_int32_t		NV_NBrokered;	/* Num brokered NVRAM buffers */
	struct aac_nvramdevinfo	NV_DevInfo[AAC_NFILESYS];	/* per device
								 * info */
	u_int32_t		NV_BattNeedsReconditioning;	/* boolean */
	u_int32_t		NV_TotalSize;	/* size of all non-volatile
						 * memories in bytes */
} __packed;

/*
 * Data types relating to adapter-initiated FIBs
 *
 * Based on types and structures in <aifstruc.h>
 */

/*
 * Progress Reports
 */
typedef enum {
	AifJobStsSuccess = 1,
	AifJobStsFinished,
	AifJobStsAborted,
	AifJobStsFailed,
	AifJobStsLastReportMarker = 100,	/* All prior mean last report */
	AifJobStsSuspended,
	AifJobStsRunning
} AAC_AifJobStatus;

typedef enum {
	AifJobScsiMin = 1,		/* Minimum value for Scsi operation */
	AifJobScsiZero,			/* SCSI device clear operation */
	AifJobScsiVerify,		/* SCSI device Verify operation NO
					 * REPAIR */
	AifJobScsiExercise,		/* SCSI device Exercise operation */
	AifJobScsiVerifyRepair,		/* SCSI device Verify operation WITH
					 * repair */
	AifJobScsiMax = 99,		/* Max Scsi value */
	AifJobCtrMin,			/* Min Ctr op value */
	AifJobCtrZero,			/* Container clear operation */
	AifJobCtrCopy,			/* Container copy operation */
	AifJobCtrCreateMirror,		/* Container Create Mirror operation */
	AifJobCtrMergeMirror,		/* Container Merge Mirror operation */
	AifJobCtrScrubMirror,		/* Container Scrub Mirror operation */
	AifJobCtrRebuildRaid5,		/* Container Rebuild Raid5 operation */
	AifJobCtrScrubRaid5,		/* Container Scrub Raid5 operation */
	AifJobCtrMorph,			/* Container morph operation */
	AifJobCtrPartCopy,		/* Container Partition copy operation */
	AifJobCtrRebuildMirror,		/* Container Rebuild Mirror operation */
	AifJobCtrCrazyCache,		/* crazy cache */
	AifJobCtrMax = 199,		/* Max Ctr type operation */
	AifJobFsMin,			/* Min Fs type operation */
	AifJobFsCreate,			/* File System Create operation */
	AifJobFsVerify,			/* File System Verify operation */
	AifJobFsExtend,			/* File System Extend operation */
	AifJobFsMax = 299,		/* Max Fs type operation */
	AifJobApiFormatNTFS,		/* Format a drive to NTFS */
	AifJobApiFormatFAT,		/* Format a drive to FAT */
	AifJobApiUpdateSnapshot,	/* update the read/write half of a
					 * snapshot */
	AifJobApiFormatFAT32,		/* Format a drive to FAT32 */
	AifJobApiMax = 399,		/* Max API type operation */
	AifJobCtlContinuousCtrVerify,	/* Adapter operation */
	AifJobCtlMax = 499		/* Max Adapter type operation */
} AAC_AifJobType;

struct aac_AifContainers {
	u_int32_t	src;		/* from/master */
	u_int32_t	dst;		/* to/slave */
} __packed;

union aac_AifJobClient {
	struct aac_AifContainers	container;	/* For Container and
							 * filesystem progress
							 * ops; */
	int32_t				scsi_dh;	/* For SCSI progress
							 * ops */
};

struct aac_AifJobDesc {
	u_int32_t		jobID;		/* DO NOT FILL IN! Will be
						 * filled in by AIF */
	AAC_AifJobType		type;		/* Operation that is being
						 * performed */
	union aac_AifJobClient	client;		/* Details */
} __packed;

struct aac_AifJobProgressReport {
	struct aac_AifJobDesc	jd;
	AAC_AifJobStatus	status;
	u_int32_t		finalTick;
	u_int32_t		currentTick;
	u_int32_t		jobSpecificData1;
	u_int32_t		jobSpecificData2;
} __packed;

/*
 * Event Notification
 */
typedef enum {
	/* General application notifies start here */
	AifEnGeneric = 1,		/* Generic notification */
	AifEnTaskComplete,		/* Task has completed */
	AifEnConfigChange,		/* Adapter config change occurred */
	AifEnContainerChange,		/* Adapter specific container
					 * configuration change */
	AifEnDeviceFailure,		/* SCSI device failed */
	AifEnMirrorFailover,		/* Mirror failover started */
	AifEnContainerEvent,		/* Significant container event */
	AifEnFileSystemChange,		/* File system changed */
	AifEnConfigPause,		/* Container pause event */
	AifEnConfigResume,		/* Container resume event */
	AifEnFailoverChange,		/* Failover space assignment changed */
	AifEnRAID5RebuildDone,		/* RAID5 rebuild finished */
	AifEnEnclosureManagement,	/* Enclosure management event */
	AifEnBatteryEvent,		/* Significant NV battery event */
	AifEnAddContainer,		/* A new container was created. */
	AifEnDeleteContainer,		/* A container was deleted. */
	AifEnSMARTEvent, 	       	/* SMART Event */
	AifEnBatteryNeedsRecond,	/* The battery needs reconditioning */
	AifEnClusterEvent,		/* Some cluster event */
	AifEnDiskSetEvent,		/* A disk set event occured. */
	AifDriverNotifyStart=199,	/* Notifies for host driver go here */
	/* Host driver notifications start here */
	AifDenMorphComplete, 		/* A morph operation completed */
	AifDenVolumeExtendComplete 	/* Volume expand operation completed */
} AAC_AifEventNotifyType;

struct aac_AifEnsGeneric {
	char	text[132];		/* Generic text */
} __packed;

struct aac_AifEnsDeviceFailure {
	u_int32_t	deviceHandle;	/* SCSI device handle */
} __packed;

struct aac_AifEnsMirrorFailover {
	u_int32_t	container;	/* Container with failed element */
	u_int32_t	failedSlice;	/* Old slice which failed */
	u_int32_t	creatingSlice;	/* New slice used for auto-create */
} __packed;

struct aac_AifEnsContainerChange {
	u_int32_t	container[2];	/* container that changed, -1 if no
					 * container */
} __packed;

struct aac_AifEnsContainerEvent {
	u_int32_t	container;	/* container number  */
	u_int32_t	eventType;	/* event type */
} __packed;

struct aac_AifEnsEnclosureEvent {
	u_int32_t	empID;		/* enclosure management proc number  */
	u_int32_t	unitID;		/* unitId, fan id, power supply id,
					 * slot id, tempsensor id.  */
	u_int32_t	eventType;	/* event type */
} __packed;

struct aac_AifEnsBatteryEvent {
	AAC_NVBATT_TRANSITION	transition_type;	/* eg from low to ok */
	AAC_NVBATTSTATUS	current_state;		/* current batt state */
	AAC_NVBATTSTATUS	prior_state;		/* prev batt state */
} __packed;

struct aac_AifEnsDiskSetEvent {
	u_int32_t	eventType;
	u_int64_t	DsNum;
	u_int64_t	CreatorId;
} __packed;

typedef enum {
	CLUSTER_NULL_EVENT = 0,
	CLUSTER_PARTNER_NAME_EVENT,	/* change in partner hostname or
					 * adaptername from NULL to non-NULL */
	/* (partner's agent may be up) */
	CLUSTER_PARTNER_NULL_NAME_EVENT	/* change in partner hostname or
					 * adaptername from non-null to NULL */
	/* (partner has rebooted) */
} AAC_ClusterAifEvent;

struct aac_AifEnsClusterEvent {
	AAC_ClusterAifEvent	eventType;
} __packed;

struct aac_AifEventNotify {
	AAC_AifEventNotifyType	type;
	union {
		struct aac_AifEnsGeneric		EG;
		struct aac_AifEnsDeviceFailure		EDF;
		struct aac_AifEnsMirrorFailover		EMF;
		struct aac_AifEnsContainerChange	ECC;
		struct aac_AifEnsContainerEvent		ECE;
		struct aac_AifEnsEnclosureEvent		EEE;
		struct aac_AifEnsBatteryEvent		EBE;
		struct aac_AifEnsDiskSetEvent		EDS;
/*		struct aac_AifEnsSMARTEvent		ES;*/
		struct aac_AifEnsClusterEvent		ECLE;
	} data;
} __packed;

/*
 * Adapter Initiated FIB command structures. Start with the adapter
 * initiated FIBs that really come from the adapter, and get responded
 * to by the host.
 */
#define AAC_AIF_REPORT_MAX_SIZE 64

typedef enum {
	AifCmdEventNotify = 1,	/* Notify of event */
	AifCmdJobProgress,	/* Progress report */
	AifCmdAPIReport,	/* Report from other user of API */
	AifCmdDriverNotify,	/* Notify host driver of event */
	AifReqJobList = 100,	/* Gets back complete job list */
	AifReqJobsForCtr,	/* Gets back jobs for specific container */
	AifReqJobsForScsi,	/* Gets back jobs for specific SCSI device */
	AifReqJobReport,	/* Gets back a specific job report or list */
	AifReqTerminateJob,	/* Terminates job */
	AifReqSuspendJob,	/* Suspends a job */
	AifReqResumeJob,	/* Resumes a job */
	AifReqSendAPIReport,	/* API generic report requests */
	AifReqAPIJobStart,	/* Start a job from the API */
	AifReqAPIJobUpdate,	/* Update a job report from the API */
	AifReqAPIJobFinish	/* Finish a job from the API */
} AAC_AifCommand;

struct aac_aif_command {
	AAC_AifCommand	command;	/* Tell host what type of
					 * notify this is */
	u_int32_t	seqNumber;	/* To allow ordering of
					 * reports (if necessary) */
	union {
		struct aac_AifEventNotify	EN;	/* Event notify */
		struct aac_AifJobProgressReport	PR[1];	/* Progress report */
		u_int8_t			AR[AAC_AIF_REPORT_MAX_SIZE];
		u_int8_t			data[AAC_FIB_DATASIZE - 8];
	} data;
} __packed;

/*
 * Filesystem commands/data
 *
 * The adapter has a very complex filesystem interface, most of which we ignore.
 * (And which seems not to be implemented, anyway.)
 */

/*
 * FSA commands
 * (not used?)
 */
typedef enum {
	Null = 0,
	GetAttributes,
	SetAttributes,
	Lookup,
	ReadLink,
	Read,
	Write,
	Create,
	MakeDirectory,
	SymbolicLink,
	MakeNode,
	Removex,
	RemoveDirectory,
	Rename,
	Link,
	ReadDirectory,
	ReadDirectoryPlus,
	FileSystemStatus,
	FileSystemInfo,
	PathConfigure,
	Commit,
	Mount,
	UnMount,
	Newfs,
	FsCheck,
	FsSync,
	SimReadWrite,
	SetFileSystemStatus,
	BlockRead,
	BlockWrite,
	NvramIoctl,
	FsSyncWait,
	ClearArchiveBit,
	SetAcl,
	GetAcl,
	AssignAcl,
	FaultInsertion,
	CrazyCache
} AAC_FSACommand;

/*
 * Command status values
 */
typedef enum {
	ST_OK = 0,
	ST_PERM = 1,
	ST_NOENT = 2,
	ST_IO = 5,
	ST_NXIO = 6,
	ST_E2BIG = 7,
	ST_ACCES = 13,
	ST_EXIST = 17,
	ST_XDEV = 18,
	ST_NODEV = 19,
	ST_NOTDIR = 20,
	ST_ISDIR = 21,
	ST_INVAL = 22,
	ST_FBIG = 27,
	ST_NOSPC = 28,
	ST_ROFS = 30,
	ST_MLINK = 31,
	ST_WOULDBLOCK = 35,
	ST_NAMETOOLONG = 63,
	ST_NOTEMPTY = 66,
	ST_DQUOT = 69,
	ST_STALE = 70,
	ST_REMOTE = 71,
	ST_BADHANDLE = 10001,
	ST_NOT_SYNC = 10002,
	ST_BAD_COOKIE = 10003,
	ST_NOTSUPP = 10004,
	ST_TOOSMALL = 10005,
	ST_SERVERFAULT = 10006,
	ST_BADTYPE = 10007,
	ST_JUKEBOX = 10008,
	ST_NOTMOUNTED = 10009,
	ST_MAINTMODE = 10010,
	ST_STALEACL = 10011
} AAC_FSAStatus;

/*
 * Volume manager commands
 */
typedef enum _VM_COMMANDS {
	VM_Null = 0,
	VM_NameServe,
	VM_ContainerConfig,
	VM_Ioctl,
	VM_FilesystemIoctl,
	VM_CloseAll,
	VM_CtBlockRead,
	VM_CtBlockWrite,
	VM_SliceBlockRead,	 /* raw access to configured storage objects */
	VM_SliceBlockWrite,
	VM_DriveBlockRead,	 /* raw access to physical devices */
	VM_DriveBlockWrite,
	VM_EnclosureMgt,	 /* enclosure management */
	VM_Unused,		 /* used to be diskset management */
	VM_CtBlockVerify,
	VM_CtPerf,		 /* performance test */
	VM_CtBlockRead64,
	VM_CtBlockWrite64,
	VM_CtBlockVerify64,
	VM_CtHostRead64,
	VM_CtHostWrite64,
} AAC_VMCommand;

/*
 * "mountable object"
 */
struct aac_mntobj {
	u_int32_t			ObjectId;
	char				FileSystemName[16];
	struct aac_container_creation	CreateInfo;
	u_int32_t			Capacity;
	u_int32_t			VolType;
	u_int32_t			ObjType;
	u_int32_t			ContentState;
#define FSCS_READONLY		0x0002		/* XXX need more information
						 * than this */
	union {
		u_int32_t	pad[8];
	} ObjExtension;
	u_int32_t			AlterEgoId;
} __packed;

struct aac_mntinfo {
	u_int32_t		Command;
	u_int32_t		MntType;
	u_int32_t		MntCount;
} __packed;

struct aac_mntinforesp {
	u_int32_t		Status;
	u_int32_t		MntType;
	u_int32_t		MntRespCount;
	struct aac_mntobj	MntTable[1];
} __packed;

/*
 * Container shutdown command.
 */
struct aac_closecommand {
	u_int32_t	Command;
	u_int32_t	ContainerId;
} __packed;

/*
 * Container Config Command
 */
#define CT_GET_SCSI_METHOD	64
struct aac_ctcfg {
	u_int32_t		Command;
	u_int32_t		cmd;
	u_int32_t		param;
} __packed;

struct aac_ctcfg_resp {
	u_int32_t		Status;
	u_int32_t		resp;
	u_int32_t		param;
} __packed;

/*
 * 'Ioctl' commads
 */
#define AAC_SCSI_MAX_PORTS	10
#define AAC_BUS_NO_EXIST	0
#define AAC_BUS_VALID		1
#define AAC_BUS_FAULTED		2
#define AAC_BUS_DISABLED	3
#define GetBusInfo		0x9

struct aac_getbusinf {
	u_int32_t		ProbeComplete;
	u_int32_t		BusCount;
	u_int32_t		TargetsPerBus;
	u_int8_t		InitiatorBusId[AAC_SCSI_MAX_PORTS];
	u_int8_t		BusValid[AAC_SCSI_MAX_PORTS];
} __packed;

struct aac_vmioctl {
	u_int32_t		Command;
	u_int32_t		ObjType;
	u_int32_t		MethId;
	u_int32_t		ObjId;
	u_int32_t		IoctlCmd;
	u_int32_t		IoctlBuf[1];	/* Placeholder? */
} __packed;

struct aac_vmi_businf_resp {
	u_int32_t		Status;
	u_int32_t		ObjType;
	u_int32_t		MethId;
	u_int32_t		ObjId;
	u_int32_t		IoctlCmd;
	struct aac_getbusinf	BusInf;
} __packed;

#define AAC_BTL_TO_HANDLE(b, t, l) \
    (((b & 0x3f) << 7) | ((l & 0x7) << 4) | (t & 0xf))
#define GetDeviceProbeInfo 0x5

struct aac_vmi_devinfo_resp {
	u_int32_t		Status;
	u_int32_t		ObjType;
	u_int32_t		MethId;
	u_int32_t		ObjId;
	u_int32_t		IoctlCmd;
	u_int8_t		VendorId[8];
	u_int8_t		ProductId[16];
	u_int8_t		ProductRev[4];
	u_int32_t		Inquiry7;
	u_int32_t		align1;
	u_int32_t		Inquiry0;
	u_int32_t		align2;
	u_int32_t		Inquiry1;
	u_int32_t		align3;
	u_int32_t		reserved[2];
	u_int8_t		VendorSpecific[20];
	u_int32_t		Smart:1;
	u_int32_t		AAC_Managed:1;
	u_int32_t		align4;
	u_int32_t		reserved2:6;
	u_int32_t		Bus;
	u_int32_t		Target;
	u_int32_t		Lun;
	u_int32_t		ultraEnable:1,
				disconnectEnable:1,
				fast20EnabledW:1,
				scamDevice:1,
				scamTolerant:1,
				setForSync:1,
				setForWide:1,
				syncDevice:1,
				wideDevice:1,
				reserved1:7,
				ScsiRate:8,
				ScsiOffset:8;
}; /* Do not pack */

#define ResetBus 0x16
struct aac_resetbus {
	u_int32_t		BusNumber;
};

/*
 * Write 'stability' options.
 */
typedef enum {
	CSTABLE = 1,
	CUNSTABLE
} AAC_CacheLevel;

/*
 * Commit level response for a write request.
 */
typedef enum {
	CMFILE_SYNC_NVRAM = 1,
	CMDATA_SYNC_NVRAM,
	CMFILE_SYNC,
	CMDATA_SYNC,
	CMUNSTABLE
} AAC_CommitLevel;

/*
 * Block read/write operations.
 * These structures are packed into the 'data' area in the FIB.
 */

struct aac_blockread {
	u_int32_t		Command;	/* not FSACommand! */
	u_int32_t		ContainerId;
	u_int32_t		BlockNumber;
	u_int32_t		ByteCount;
	struct aac_sg_table	SgMap;		/* variable size */
} __packed;

struct aac_blockread64 {
	u_int32_t		Command;
	u_int16_t		ContainerId;
	u_int16_t		SectorCount;
	u_int32_t		BlockNumber;
	u_int16_t		Pad;
	u_int16_t		Flags;
	struct aac_sg_table64	SgMap64;
} __packed;

struct aac_blockread_response {
	u_int32_t		Status;
	u_int32_t		ByteCount;
} __packed;

struct aac_blockwrite {
	u_int32_t		Command;	/* not FSACommand! */
	u_int32_t		ContainerId;
	u_int32_t		BlockNumber;
	u_int32_t		ByteCount;
	u_int32_t		Stable;
	struct aac_sg_table	SgMap;		/* variable size */
} __packed;

struct aac_blockwrite64 {
	u_int32_t		Command;	/* not FSACommand! */
	u_int16_t		ContainerId;
	u_int16_t		SectorCount;
	u_int32_t		BlockNumber;
	u_int16_t		Pad;
	u_int16_t		Flags;
	struct aac_sg_table64	SgMap64;	/* variable size */
} __packed;

struct aac_blockwrite_response {
	u_int32_t		Status;
	u_int32_t		ByteCount;
	u_int32_t		Committed;
} __packed;

/*
 * Container shutdown command.
 */
struct aac_close_command {
	u_int32_t		Command;
	u_int32_t		ContainerId;
};

/*
 * SCSI Passthrough structures
 */
struct aac_srb32 {
	u_int32_t		function;
	u_int32_t		bus;
	u_int32_t		target;
	u_int32_t		lun;
	u_int32_t		timeout;
	u_int32_t		flags;
	u_int32_t		data_len;
	u_int32_t		retry_limit;
	u_int32_t		cdb_len;
	u_int8_t		cdb[16];
	struct aac_sg_table	sg_map32;
};

enum {
	AAC_SRB_FUNC_EXECUTE_SCSI	= 0x00,
	AAC_SRB_FUNC_CLAIM_DEVICE,
	AAC_SRB_FUNC_IO_CONTROL,
	AAC_SRB_FUNC_RECEIVE_EVENT,
	AAC_SRB_FUNC_RELEASE_QUEUE,
	AAC_SRB_FUNC_ATTACH_DEVICE,
	AAC_SRB_FUNC_RELEASE_DEVICE,
	AAC_SRB_FUNC_SHUTDOWN,
	AAC_SRB_FUNC_FLUSH,
	AAC_SRB_FUNC_ABORT_COMMAND	= 0x10,
	AAC_SRB_FUNC_RELEASE_RECOVERY,
	AAC_SRB_FUNC_RESET_BUS,
	AAC_SRB_FUNC_RESET_DEVICE,
	AAC_SRB_FUNC_TERMINATE_IO,
	AAC_SRB_FUNC_FLUSH_QUEUE,
	AAC_SRB_FUNC_REMOVE_DEVICE,
	AAC_SRB_FUNC_DOMAIN_VALIDATION
};

#define AAC_SRB_FLAGS_NO_DATA_XFER		0x0000
#define	AAC_SRB_FLAGS_DISABLE_DISCONNECT	0x0004
#define	AAC_SRB_FLAGS_DISABLE_SYNC_TRANSFER	0x0008
#define AAC_SRB_FLAGS_BYPASS_FROZEN_QUEUE	0x0010
#define	AAC_SRB_FLAGS_DISABLE_AUTOSENSE		0x0020
#define	AAC_SRB_FLAGS_DATA_IN			0x0040
#define AAC_SRB_FLAGS_DATA_OUT			0x0080
#define	AAC_SRB_FLAGS_UNSPECIFIED_DIRECTION \
			(AAC_SRB_FLAGS_DATA_IN | AAC_SRB_FLAGS_DATA_OUT)

#define AAC_HOST_SENSE_DATA_MAX			30

struct aac_srb_response {
	u_int32_t	fib_status;
	u_int32_t	srb_status;
	u_int32_t	scsi_status;
	u_int32_t	data_len;
	u_int32_t	sense_len;
	u_int8_t	sense[AAC_HOST_SENSE_DATA_MAX];
};

enum {
	AAC_SRB_STS_PENDING			= 0x00,
	AAC_SRB_STS_SUCCESS,
	AAC_SRB_STS_ABORTED,
	AAC_SRB_STS_ABORT_FAILED,
	AAC_SRB_STS_ERROR,
	AAC_SRB_STS_BUSY,
	AAC_SRB_STS_INVALID_REQUEST,
	AAC_SRB_STS_INVALID_PATH_ID,
	AAC_SRB_STS_NO_DEVICE,
	AAC_SRB_STS_TIMEOUT,
	AAC_SRB_STS_SELECTION_TIMEOUT,
	AAC_SRB_STS_COMMAND_TIMEOUT,
	AAC_SRB_STS_MESSAGE_REJECTED		= 0x0D,
	AAC_SRB_STS_BUS_RESET,
	AAC_SRB_STS_PARITY_ERROR,
	AAC_SRB_STS_REQUEST_SENSE_FAILED,
	AAC_SRB_STS_NO_HBA,
	AAC_SRB_STS_DATA_OVERRUN,
	AAC_SRB_STS_UNEXPECTED_BUS_FREE,
	AAC_SRB_STS_PHASE_SEQUENCE_FAILURE,
	AAC_SRB_STS_BAD_SRB_BLOCK_LENGTH,
	AAC_SRB_STS_REQUEST_FLUSHED,
	AAC_SRB_STS_INVALID_LUN			= 0x20,
	AAC_SRB_STS_INVALID_TARGET_ID,
	AAC_SRB_STS_BAD_FUNCTION,
	AAC_SRB_STS_ERROR_RECOVERY
};

/*
 * Register set for adapters based on the Falcon bridge and PPC core
 */

#define AAC_FA_DOORBELL0_CLEAR		0x00
#define AAC_FA_DOORBELL1_CLEAR		0x02
#define AAC_FA_DOORBELL0		0x04
#define AAC_FA_DOORBELL1		0x06
#define AAC_FA_MASK0_CLEAR		0x08
#define AAC_FA_MASK1_CLEAR		0x0a
#define	AAC_FA_MASK0			0x0c
#define AAC_FA_MASK1			0x0e
#define AAC_FA_MAILBOX			0x10
#define	AAC_FA_FWSTATUS			0x2c	/* Mailbox 7 */
#define	AAC_FA_INTSRC			0x900

#define AAC_FA_HACK(sc)	(void)AAC_GETREG4(sc, AAC_FA_INTSRC)

/*
 * Register definitions for the Adaptec AAC-364 'Jalapeno I/II' adapters, based
 * on the SA110 'StrongArm'.
 */

#define AAC_REGSIZE			0x2000

#define AAC_SA_DOORBELL0_CLEAR		0x98	/* doorbell 0 (adapter->host) */
#define AAC_SA_DOORBELL0_SET		0x9c
#define AAC_SA_DOORBELL0		0x9c
#define AAC_SA_MASK0_CLEAR		0xa0
#define AAC_SA_MASK0_SET		0xa4

#define AAC_SA_DOORBELL1_CLEAR		0x9a	/* doorbell 1 (host->adapter) */
#define AAC_SA_DOORBELL1_SET		0x9e
#define AAC_SA_DOORBELL1		0x9e
#define AAC_SA_MASK1_CLEAR		0xa2
#define AAC_SA_MASK1_SET		0xa6

#define AAC_SA_MAILBOX			0xa8	/* mailbox (20 bytes) */
#define AAC_SA_FWSTATUS			0xc4

/*
 * Register definitions for the Adaptec 'Pablano' adapters, based on the i960Rx,
 * and other related adapters.
 */

#define AAC_RX_IDBR		0x20	/* inbound doorbell register */
#define AAC_RX_IISR		0x24	/* inbound interrupt status register */
#define AAC_RX_IIMR		0x28	/* inbound interrupt mask register */
#define AAC_RX_ODBR		0x2c	/* outbound doorbell register */
#define AAC_RX_OISR		0x30	/* outbound interrupt status register */
#define AAC_RX_OIMR		0x34	/* outbound interrupt mask register */

#define AAC_RX_MAILBOX		0x50	/* mailbox (20 bytes) */
#define AAC_RX_FWSTATUS		0x6c

/*
 * Register definitions for the Adaptec 'Rocket' RAID-On-Chip adapters.
 * Unsurprisingly, it's quite similar to the i960!
 */

#define AAC_RKT_IDBR		0x20	/* inbound doorbell register */
#define AAC_RKT_IISR		0x24	/* inbound interrupt status register */
#define AAC_RKT_IIMR		0x28	/* inbound interrupt mask register */
#define AAC_RKT_ODBR		0x2c	/* outbound doorbell register */
#define AAC_RKT_OISR		0x30	/* outbound interrupt status register */
#define AAC_RKT_OIMR		0x34	/* outbound interrupt mask register */

#define AAC_RKT_MAILBOX		0x1000	/* mailbox */
#define AAC_RKT_FWSTATUS	0x101c	/* Firmware Status (mailbox 7) */

/*
 * Common bit definitions for the doorbell registers.
 */

/*
 * Status bits in the doorbell registers.
 */
#define AAC_DB_SYNC_COMMAND	(1<<0)	/* send/completed synchronous FIB */
#define AAC_DB_COMMAND_READY	(1<<1)	/* posted one or more commands */
#define AAC_DB_RESPONSE_READY	(1<<2)	/* one or more commands complete */
#define AAC_DB_COMMAND_NOT_FULL	(1<<3)	/* command queue not full */
#define AAC_DB_RESPONSE_NOT_FULL (1<<4)	/* response queue not full */

/*
 * The adapter can request the host print a message by setting the
 * DB_PRINTF flag in DOORBELL0.  The driver responds by collecting the
 * message from the printf buffer, clearing the DB_PRINTF flag in
 * DOORBELL0 and setting it in DOORBELL1.
 * (ODBR and IDBR respectively for the i960Rx adapters)
 */
#define AAC_DB_PRINTF		(1<<5)	/* adapter requests host printf */
#define AAC_PRINTF_DONE		(1<<5)	/* Host completed printf processing */

/*
 * Mask containing the interrupt bits we care about.  We don't anticipate (or
 * want) interrupts not in this mask.
 */
#define AAC_DB_INTERRUPTS	(AAC_DB_COMMAND_READY  |	\
				 AAC_DB_RESPONSE_READY |	\
				 AAC_DB_PRINTF)


code:
/*	$OpenBSD: aacvar.h,v 1.12 2014/01/17 22:51:10 dlg Exp $	*/

/*-
 * Copyright (c) 2000 Michael Smith
 * Copyright (c) 2000 BSDi
 * Copyright (c) 2000 Niklas Hallqvist
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	$FreeBSD: /c/ncvs/src/sys/dev/aac/aacvar.h,v 1.1 2000/09/13 03:20:34 msmith Exp $
 */

/*
 * This driver would not have rewritten for OpenBSD if it was not for the
 * hardware donation from Nocom.  I want to thank them for their support.
 * Of course, credit should go to Mike Smith for the original work he did
 * in the FreeBSD driver where I found lots of inspiration.
 * - Niklas Hallqvist
 */

/* compatibility */
#define time_second (mono_time.tv_sec)

/* Debugging */
// #define AAC_DEBUG 0x0

#ifdef AAC_DEBUG
#define AAC_DPRINTF(mask, args) if (aac_debug & (mask)) printf args
#define AAC_D_INTR	0x001
#define AAC_D_MISC	0x002
#define AAC_D_CMD	0x004
#define AAC_D_QUEUE	0x008
#define AAC_D_IO	0x010
#define AAC_D_IOCTL	0x020
#define AAC_D_LOCK	0x040
#define AAC_D_THREAD	0x080
#define AAC_D_FIB	0x100
extern int aac_debug;

#define AAC_PRINT_FIB(sc, fib)  do { \
	if (aac_debug & AAC_D_FIB) \
		aac_print_fib((sc), (fib), __func__); \
} while (0)
#else
#define AAC_DPRINTF(mask, args)
#define AAC_PRINT_FIB(sc, fib)
#endif

struct aac_code_lookup {
	char	*string;
	u_int32_t code;
};

struct aac_softc;

/*
 * We allocate a small set of FIBs for the adapter to use to send us messages.
 */
#define AAC_ADAPTER_FIBS	8

/*
 * FIBs are allocated in page-size chunks and can grow up to the 512
 * limit imposed by the hardware.
 */
#define AAC_FIB_COUNT		(PAGE_SIZE/sizeof(struct aac_fib))
#define AAC_MAX_FIBS		512
#define AAC_FIBMAP_SIZE		(PAGE_SIZE)

/*
 * The controller reports status events in AIFs.  We hang on to a number of
 * these in order to pass them out to user-space management tools.
 */
#define AAC_AIFQ_LENGTH		64

/*
 * Firmware messages are passed in the printf buffer.
 */
#define AAC_PRINTF_BUFSIZE	256

/*
 * We wait this many seconds for the adapter to come ready if it is still
 * booting.
 */
#define AAC_BOOT_TIMEOUT	(3 * 60)

/*
 * Timeout for immediate commands.
 */
#define AAC_IMMEDIATE_TIMEOUT	30

/*
 * Timeout for normal commands
 */
#define AAC_CMD_TIMEOUT		30		/* seconds */

/*
 * Rate at which we periodically check for timed out commands and kick the
 * controller.
 */
#define AAC_PERIODIC_INTERVAL	20		/* seconds */

/*
 * Wait this long for a lost interrupt to get detected.
 */
#define AAC_WATCH_TIMEOUT	10000		/* 10000 * 1ms = 10s */

/*
 * Delay 20ms after the qnotify in sync operations.  Experimentally deduced.
 */
#define AAC_SYNC_DELAY 20000

/*
 * The firmware interface allows for a 16-bit s/g list length.  We limit
 * ourselves to a reasonable maximum and ensure alignment.
 */
#define AAC_MAXSGENTRIES	64	/* max S/G entries, limit 65535 */

/*
 * We gather a number of adapter-visible items into a single structure.
 *
 * The ordering of this structure may be important; we copy the Linux driver:
 *
 * Adapter FIBs
 * Init struct
 * Queue headers (Comm Area)
 * Printf buffer
 *
 * In addition, we add:
 * Sync Fib
 */
struct aac_common {
	/* fibs for the controller to send us messages */
	struct aac_fib ac_fibs[AAC_ADAPTER_FIBS];

	/* the init structure */
	struct aac_adapter_init	ac_init;

	/* arena within which the queue structures are kept */
	u_int8_t ac_qbuf[sizeof(struct aac_queue_table) + AAC_QUEUE_ALIGN];

	/* buffer for text messages from the controller */
	char	ac_printf[AAC_PRINTF_BUFSIZE];

	/* fib for synchronous commands */
	struct aac_fib ac_sync_fib;
};
#define AAC_COMMON_ALLOCSIZE (8192 + sizeof(struct aac_common))

/*
 * Interface operations
 */
struct aac_interface {
	int	(*aif_get_fwstatus)(struct aac_softc *);
	void	(*aif_qnotify)(struct aac_softc *, int);
	int	(*aif_get_istatus)(struct aac_softc *);
	void	(*aif_set_istatus)(struct aac_softc *, int);
	void	(*aif_set_mailbox)(struct aac_softc *, u_int32_t,
	    u_int32_t, u_int32_t, u_int32_t, u_int32_t);
	int	(*aif_get_mailbox)(struct aac_softc *, int mb);
	void	(*aif_set_interrupts)(struct aac_softc *, int);
};
extern struct aac_interface aac_fa_interface;
extern struct aac_interface aac_sa_interface;
extern struct aac_interface aac_rx_interface;
extern struct aac_interface aac_rkt_interface;

#define AAC_GET_FWSTATUS(sc)		((sc)->aac_if.aif_get_fwstatus(sc))
#define AAC_QNOTIFY(sc, qbit) \
	((sc)->aac_if.aif_qnotify((sc), (qbit)))
#define AAC_GET_ISTATUS(sc)		((sc)->aac_if.aif_get_istatus(sc))
#define AAC_CLEAR_ISTATUS(sc, mask) \
	((sc)->aac_if.aif_set_istatus((sc), (mask)))
#define AAC_SET_MAILBOX(sc, command, arg0, arg1, arg2, arg3) \
	do {								\
		((sc)->aac_if.aif_set_mailbox((sc), (command), (arg0),	\
		    (arg1), (arg2), (arg3)));				\
	} while(0)
#define AAC_GET_MAILBOX(sc, mb) \
	((sc)->aac_if.aif_get_mailbox(sc, (mb)))
#define	AAC_MASK_INTERRUPTS(sc)	\
	((sc)->aac_if.aif_set_interrupts((sc), 0))
#define AAC_UNMASK_INTERRUPTS(sc) \
	((sc)->aac_if.aif_set_interrupts((sc), 1))

#define AAC_SETREG4(sc, reg, val) \
	bus_space_write_4((sc)->aac_memt, (sc)->aac_memh, (reg), (val))
#define AAC_GETREG4(sc, reg) \
	bus_space_read_4((sc)->aac_memt, (sc)->aac_memh, (reg))
#define AAC_SETREG2(sc, reg, val) \
	bus_space_write_2((sc)->aac_memt, (sc)->aac_memh, (reg), (val))
#define AAC_GETREG2(sc, reg) \
	bus_space_read_2((sc)->aac_memt, (sc)->aac_memh, (reg))
#define AAC_SETREG1(sc, reg, val) \
	bus_space_write_1((sc)->aac_memt, (sc)->aac_memh, (reg), (val))
#define AAC_GETREG1(sc, reg) \
	bus_space_read_1((sc)->aac_memt, (sc)->aac_memh, (reg))

/* Define the OS version specific locks */
typedef struct rwlock aac_lock_t;
#define AAC_LOCK_INIT(l, s)	do { \
    rw_init((l), "aaclock"); \
    AAC_DPRINTF(AAC_D_LOCK, ("%s: init lock @%s: %d\n", \
	        sc->aac_dev.dv_xname, __FUNCTION__, __LINE__)); \
} while (0)

#define AAC_LOCK_ACQUIRE(l) do { \
    AAC_DPRINTF(AAC_D_LOCK, ("%s: lock @%s: %d\n", \
	        sc->aac_dev.dv_xname, __FUNCTION__, __LINE__)); \
    rw_enter_write((l)); \
} while (0)

#define AAC_LOCK_RELEASE(l) do { \
    rw_exit_write((l)); \
    AAC_DPRINTF(AAC_D_LOCK, ("%s: unlock @%s: %d\n", \
	        sc->aac_dev.dv_xname, __FUNCTION__, __LINE__)); \
} while (0)

/*
 * Per-container data structure
 */
struct aac_container
{
	struct aac_mntobj co_mntobj;
	int				co_found;
	TAILQ_ENTRY(aac_container)	co_link;
};

/*
 * A command contol block, one for each corresponding command index of the
 * controller.
 */
struct aac_command
{
	TAILQ_ENTRY(aac_command) cm_link;	/* list linkage */

	struct aac_softc	*cm_sc;		/* controller that owns us */

	struct aac_fib 		*cm_fib;	/* FIB for this command */
	bus_addr_t		cm_fibphys;	/* bus address of the FIB */
	void			*cm_data;
	size_t			cm_datalen;
	bus_dmamap_t		cm_datamap;
	struct aac_sg_table	*cm_sgtable;	/* pointer to s/g table */

	u_int			cm_flags;
#define AAC_CMD_MAPPED		(1<<0)	/* command has had its data mapped */
#define AAC_CMD_DATAIN		(1<<1)	/* command involves data moving
					 * from controller to host */
#define AAC_CMD_DATAOUT		(1<<2)	/* command involves data moving
					 * from host to controller */
#define AAC_CMD_COMPLETED	(1<<3)	/* command has been completed */
#define AAC_CMD_TIMEDOUT	(1<<4)	/* command taken too long */
#define AAC_ON_AACQ_FREE	(1<<5)
#define AAC_ON_AACQ_READY	(1<<6)
#define AAC_ON_AACQ_BUSY	(1<<7)
#define AAC_ON_AACQ_BIO		(1<<8)
#define AAC_ON_AACQ_MASK	((1<<5)|(1<<6)|(1<<7)|(1<<8))
#define AAC_QUEUE_FRZN		(1<<9)	/* Freeze the processing of
					 * commands on the queue. */
#define AAC_ACF_WATCHDOG 	(1<<10)

	void			(*cm_complete)(struct aac_command *);
	void			*cm_private;
	u_int32_t		cm_blkno;
	u_int32_t		cm_bcount;
	time_t			cm_timestamp;	/* command creation time */
	int			cm_queue;
	int			cm_index;
};

struct aac_fibmap {
	TAILQ_ENTRY(aac_fibmap) fm_link;	/* list linkage */
	struct aac_fib		*aac_fibs;
	bus_dmamap_t		aac_fibmap;
 	bus_dma_segment_t	aac_seg;
	int			aac_nsegs;
	struct aac_command	*aac_commands;
};

/*
 * Command queue statistics
 */
#define AACQ_FREE       0
#define AACQ_BIO        1
#define AACQ_READY      2
#define AACQ_BUSY       3
#define AACQ_COUNT      4       /* total number of queues */

struct aac_qstat {
        u_int32_t       q_length;
        u_int32_t       q_max;
};

/*
 * Per-controller structure.
 */
struct aac_softc
{
	struct device aac_dev;
	void   *aac_ih;
	struct	scsi_link aac_link;	/* Virtual SCSI bus for cache devs */

	bus_space_tag_t aac_memt;
	bus_space_handle_t aac_memh;
	bus_dma_tag_t aac_dmat;		/* parent DMA tag */

	/* controller features, limits and status */
	int	aac_state;
#define AAC_STATE_SUSPEND	(1<<0)
#define	AAC_STATE_OPEN		(1<<1)
#define AAC_STATE_INTERRUPTS_ON	(1<<2)
#define AAC_STATE_AIF_SLEEPER	(1<<3)
	struct FsaRevision aac_revision;

	int	aac_hwif;	/* controller hardware interface */
#define AAC_HWIF_I960RX		0
#define AAC_HWIF_STRONGARM	1
#define AAC_HWIF_FALCON		2
#define AAC_HWIF_RKT		3
#define AAC_HWIF_UNKNOWN	-1

	struct aac_common *aac_common;
	bus_dmamap_t		aac_common_map;
	u_int32_t aac_common_busaddr;
	struct aac_interface aac_if;

	/* command/fib resources */
	TAILQ_HEAD(,aac_fibmap)	aac_fibmap_tqh;
	u_int			total_fibs;
	struct aac_command	*aac_commands;
	struct scsi_iopool	aac_iopool;

	/* command management */
	struct mutex		 aac_free_mtx;
	TAILQ_HEAD(,aac_command) aac_free;	/* command structures
						 * available for reuse */
	TAILQ_HEAD(,aac_command) aac_ready;	/* commands on hold for
						 * controller resources */
	TAILQ_HEAD(,aac_command) aac_busy;
	TAILQ_HEAD(,aac_command) aac_bio;

	/* command management */
	struct aac_queue_table *aac_queues;
	struct aac_queue_entry *aac_qentries[AAC_QUEUE_COUNT];

	struct aac_qstat	aac_qstat[AACQ_COUNT];	/* queue statistics */

	/* connected containters */
	TAILQ_HEAD(,aac_container)	aac_container_tqh;
	aac_lock_t		aac_container_lock;

	/* Protect the sync fib */
#define AAC_SYNC_LOCK_FORCE	(1 << 0)
	aac_lock_t		aac_sync_lock;

	aac_lock_t		aac_io_lock;

	struct {
		u_int8_t hd_present;
		u_int8_t hd_is_logdrv;
		u_int8_t hd_is_arraydrv;
		u_int8_t hd_is_master;
		u_int8_t hd_is_parity;
		u_int8_t hd_is_hotfix;
		u_int8_t hd_master_no;
		u_int8_t hd_lock;
		u_int8_t hd_heads;
		u_int8_t hd_secs;
		u_int16_t hd_devtype;
		u_int32_t hd_size;
		u_int8_t hd_ldr_no;
		u_int8_t hd_rw_attribs;
		u_int32_t hd_start_sec;
	} aac_hdr[AAC_MAX_CONTAINERS];
	int			aac_container_count;

	/* management interface */
	aac_lock_t		aac_aifq_lock;
	struct aac_aif_command	aac_aifq[AAC_AIFQ_LENGTH];
	int			aac_aifq_head;
	int			aac_aifq_tail;
	struct selinfo		aac_select;
	struct proc		*aifthread;
	int			aifflags;
#define AAC_AIFFLAGS_RUNNING	(1 << 0)
#define AAC_AIFFLAGS_AIF	(1 << 1)
#define	AAC_AIFFLAGS_EXIT	(1 << 2)
#define AAC_AIFFLAGS_EXITED	(1 << 3)
#define	AAC_AIFFLAGS_COMPLETE	(1 << 4)
#define AAC_AIFFLAGS_PRINTF	(1 << 5)
#define AAC_AIFFLAGS_PENDING	(AAC_AIFFLAGS_AIF | AAC_AIFFLAGS_COMPLETE | \
				 AAC_AIFFLAGS_PRINTF)

	u_int32_t		flags;
#define AAC_FLAGS_PERC2QC	(1 << 0)
#define	AAC_FLAGS_ENABLE_CAM	(1 << 1)	/* No SCSI passthrough */
#define	AAC_FLAGS_CAM_NORESET	(1 << 2)	/* Fake SCSI resets */
#define	AAC_FLAGS_CAM_PASSONLY	(1 << 3)	/* Only create pass devices */
#define	AAC_FLAGS_SG_64BIT	(1 << 4)	/* Use 64-bit S/G addresses */
#define	AAC_FLAGS_4GB_WINDOW	(1 << 5)	/* Device can access host mem
						 * 2GB-4GB range */
#define	AAC_FLAGS_NO4GB		(1 << 6)	/* Can't access host mem >2GB*/
#define	AAC_FLAGS_256FIBS	(1 << 7)	/* Can only do 256 commands */
#define	AAC_FLAGS_BROKEN_MEMMAP (1 << 8)	/* Broken HostPhysMemPages */

	u_int32_t		supported_options;
	int			aac_max_fibs;
	void			*aac_sdh;
};

int	aac_attach(struct aac_softc *);
int	aac_intr(void *);

/* These all require correctly aligned buffers */
static __inline__ void aac_enc16(u_int8_t *, u_int16_t);
static __inline__ void aac_enc32(u_int8_t *, u_int32_t);
static __inline__ u_int16_t aac_dec16(u_int8_t *);
static __inline__ u_int32_t aac_dec32(u_int8_t *);

static __inline__ void
aac_enc16(addr, value)
	u_int8_t *addr;
	u_int16_t value;
{
	*(u_int16_t *)addr = htole16(value);
}

static __inline__ void
aac_enc32(addr, value)
	u_int8_t *addr;
	u_int32_t value;
{
	*(u_int32_t *)addr = htole32(value);
}

static __inline__ u_int16_t
aac_dec16(addr)
	u_int8_t *addr;
{
	return letoh16(*(u_int16_t *)addr);
}

static __inline__ u_int32_t
aac_dec32(addr)
	u_int8_t *addr;
{
	return letoh32(*(u_int32_t *)addr);
}

/* Declarations copied from aac.c */
#ifdef AAC_DEBUG
void aac_print_fib(struct aac_softc *, struct aac_fib *, const char *);
void aac_print_aif(struct aac_softc *, struct aac_aif_command *);
#endif
void aac_handle_aif(struct aac_softc *, struct aac_fib *);

/*
 * Queue primitives for driver queues.
 */
#define AACQ_ADD(sc, qname)					\
	do {							\
		struct aac_qstat *qs;				\
								\
		qs = &(sc)->aac_qstat[qname];			\
								\
		qs->q_length++;					\
		if (qs->q_length > qs->q_max)			\
			qs->q_max = qs->q_length;		\
	} while (0)

#define AACQ_REMOVE(sc, qname)    (sc)->aac_qstat[qname].q_length--
#define AACQ_INIT(sc, qname)				\
	do {						\
		sc->aac_qstat[qname].q_length = 0;	\
		sc->aac_qstat[qname].q_max = 0;		\
	} while (0)

#define AACQ_COMMAND_QUEUE(name, index)					\
static __inline void							\
aac_initq_ ## name (struct aac_softc *sc)				\
{									\
	TAILQ_INIT(&sc->aac_ ## name);					\
	AACQ_INIT(sc, index);						\
}									\
static __inline void							\
aac_enqueue_ ## name (struct aac_command *cm)				\
{									\
	AAC_DPRINTF(AAC_D_CMD, (": enqueue " #name));			\
	if ((cm->cm_flags & AAC_ON_AACQ_MASK) != 0) {			\
		printf("command %p is on another queue, flags = %#x\n",	\
		       cm, cm->cm_flags);				\
		panic("command is on another queue");			\
	}								\
	TAILQ_INSERT_TAIL(&cm->cm_sc->aac_ ## name, cm, cm_link);	\
	cm->cm_flags |= AAC_ON_ ## index;				\
	AACQ_ADD(cm->cm_sc, index);					\
}									\
static __inline void							\
aac_requeue_ ## name (struct aac_command *cm)				\
{									\
	AAC_DPRINTF(AAC_D_CMD, (": requeue " #name));			\
	if ((cm->cm_flags & AAC_ON_AACQ_MASK) != 0) {			\
		printf("command %p is on another queue, flags = %#x\n",	\
		       cm, cm->cm_flags);				\
		panic("command is on another queue");			\
	}								\
	TAILQ_INSERT_HEAD(&cm->cm_sc->aac_ ## name, cm, cm_link);	\
	cm->cm_flags |= AAC_ON_ ## index;				\
	AACQ_ADD(cm->cm_sc, index);					\
}									\
static __inline struct aac_command *					\
aac_dequeue_ ## name (struct aac_softc *sc)				\
{									\
	struct aac_command *cm;						\
									\
	if ((cm = TAILQ_FIRST(&sc->aac_ ## name)) != NULL) {		\
		AAC_DPRINTF(AAC_D_CMD, (": dequeue " #name));		\
		if ((cm->cm_flags & AAC_ON_ ## index) == 0) {		\
			printf("dequeue - command %p not in queue, flags = %#x, "	\
		       	       "bit = %#x\n", cm, cm->cm_flags,		\
			       AAC_ON_ ## index);			\
			panic("command not in queue");			\
		}							\
		TAILQ_REMOVE(&sc->aac_ ## name, cm, cm_link);		\
		cm->cm_flags &= ~AAC_ON_ ## index;			\
		AACQ_REMOVE(sc, index);					\
	}								\
	return(cm);							\
}									\
static __inline void							\
aac_remove_ ## name (struct aac_command *cm)				\
{									\
	AAC_DPRINTF(AAC_D_CMD, (": remove " #name));			\
	if ((cm->cm_flags & AAC_ON_ ## index) == 0) {			\
		printf("remove - command %p not in queue, flags = %#x, "		\
		       "bit = %#x\n", cm, cm->cm_flags, 		\
		       AAC_ON_ ## index);				\
		panic("command not in queue");				\
	}								\
	TAILQ_REMOVE(&cm->cm_sc->aac_ ## name, cm, cm_link);		\
	cm->cm_flags &= ~AAC_ON_ ## index;				\
	AACQ_REMOVE(cm->cm_sc, index);					\
}									\
struct hack

AACQ_COMMAND_QUEUE(free, AACQ_FREE);
AACQ_COMMAND_QUEUE(ready, AACQ_READY);
AACQ_COMMAND_QUEUE(busy, AACQ_BUSY);
AACQ_COMMAND_QUEUE(bio, AACQ_BIO);

static __inline void
aac_print_printf(struct aac_softc *sc)
{
	/*
	 * XXX We have the ability to read the length of the printf string
	 * from out of the mailboxes.
	 */
	printf("** %s: %.*s", sc->aac_dev.dv_xname, AAC_PRINTF_BUFSIZE,
	       sc->aac_common->ac_printf);
	sc->aac_common->ac_printf[0] = 0;
	AAC_QNOTIFY(sc, AAC_DB_PRINTF);
}

license: unknown


code:
/*	$OpenBSD: ac97.c,v 1.80 2015/05/11 06:46:21 ratchov Exp $	*/

/*
 * Copyright (c) 1999, 2000 Constantine Sapuntzakis
 *
 * Author:	Constantine Sapuntzakis <csapuntz@stanford.edu>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote
 *    products derived from this software without specific prior written
 *    permission.
 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.  */

/* Partially inspired by FreeBSD's sys/dev/pcm/ac97.c. It came with
   the following copyright */

/*
 * Copyright (c) 1999 Cameron Grant <gandalf@vilnya.demon.co.uk>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * $FreeBSD$
 */

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

#include <sys/audioio.h>
#include <dev/audio_if.h>
#include <dev/ic/ac97.h>

/* default parameters; supported by all ac97 codecs */
const struct audio_params ac97_audio_default = {
	48000,		/* sample_rate */
	AUDIO_ENCODING_SLINEAR_LE, /* encoding */
	16,		/* precision */
	2,		/* bps */
	1,		/* msb */
	2		/* channels */
};

const struct audio_mixer_enum ac97_on_off = {
	2,
	{ { { AudioNoff } , 0 },
	{ { AudioNon }  , 1 } }
};

const struct audio_mixer_enum ac97_mic_select = {
	2,
	{ { { AudioNmicrophone "0" }, 0 },
	{ { AudioNmicrophone "1" }, 1 } }
};

const struct audio_mixer_enum ac97_mono_select = {
	2,
	{ { { AudioNmixerout }, 0 },
	{ { AudioNmicrophone }, 1 } }
};

const struct audio_mixer_enum ac97_source = {
	8,
	{ { { AudioNmicrophone } , 0 },
	{ { AudioNcd }, 1 },
	{ { "video" }, 2 },
	{ { AudioNaux }, 3 },
	{ { AudioNline }, 4 },
	{ { AudioNmixerout }, 5 },
	{ { AudioNmixerout AudioNmono }, 6 },
	{ { "phone" }, 7 }}
};

/*
 * Due to different values for each source that uses these structures,
 * the ac97_query_devinfo function sets delta in mixer_devinfo_t using
 * ac97_source_info.bits.
 */
const struct audio_mixer_value ac97_volume_stereo = {
	{ AudioNvolume },
	2
};

const struct audio_mixer_value ac97_volume_mono = {
	{ AudioNvolume },
	1
};

#define AudioNspdif	"spdif"

#define WRAP(a)  &a, sizeof(a)

const struct ac97_source_info {
	char *class;
	char *device;
	char *qualifier;
	int  type;

	const void *info;
	int16_t info_size;

	u_int8_t  reg;
	u_int16_t default_value;
	u_int8_t  bits:3;
	u_int8_t  ofs:4;
	u_int8_t  mute:1;
	u_int8_t  polarity:1;		/* Does 0 == MAX or MIN */
	enum {
		CHECK_NONE = 0,
		CHECK_SURROUND,
		CHECK_CENTER,
		CHECK_LFE,
		CHECK_HEADPHONES,
		CHECK_TONE,
		CHECK_MIC,
		CHECK_LOUDNESS,
		CHECK_3D,
		CHECK_SPDIF
	} req_feature;

	int16_t  prev;
	int16_t  next;
	int16_t  mixer_class;
} source_info[] = {
	{ AudioCinputs,		NULL,		NULL,
	  AUDIO_MIXER_CLASS, },
	{ AudioCoutputs,	NULL,		NULL,
	  AUDIO_MIXER_CLASS, },
	{ AudioCrecord,		NULL,		NULL,
	  AUDIO_MIXER_CLASS, },
	/* Stereo master volume*/
	{ AudioCoutputs,	AudioNmaster,	NULL,
	  AUDIO_MIXER_VALUE, WRAP(ac97_volume_stereo),
	  AC97_REG_MASTER_VOLUME, 0x8000, 5, 0, 1,
	},
	/* Mono volume */
	{ AudioCoutputs,	AudioNmono,	NULL,
	  AUDIO_MIXER_VALUE, WRAP(ac97_volume_mono),
	  AC97_REG_MASTER_VOLUME_MONO, 0x8000, 6, 0, 1,
	},
	{ AudioCoutputs,	AudioNmono,	AudioNsource,
	  AUDIO_MIXER_ENUM, WRAP(ac97_mono_select),
	  AC97_REG_GP, 0x0000, 1, 9, 0,
	},
	/* Headphone volume */
	{ AudioCoutputs,	AudioNheadphone, NULL,
	  AUDIO_MIXER_VALUE, WRAP(ac97_volume_stereo),
	  AC97_REG_HEADPHONE_VOLUME, 0x8000, 6, 0, 1, 0, CHECK_HEADPHONES
	},
	/* Surround volume - logic hard coded for mute */
	{ AudioCoutputs,	AudioNsurround,	NULL,
	  AUDIO_MIXER_VALUE, WRAP(ac97_volume_stereo),
	  AC97_REG_SURR_MASTER, 0x8080, 5, 0, 1, 0, CHECK_SURROUND
	},
	/* Center volume*/
	{ AudioCoutputs,	AudioNcenter,	NULL,
	  AUDIO_MIXER_VALUE, WRAP(ac97_volume_mono),
	  AC97_REG_CENTER_LFE_MASTER, 0x8080, 5, 0, 0, 0, CHECK_CENTER
	},
	{ AudioCoutputs,	AudioNcenter,	AudioNmute,
	  AUDIO_MIXER_ENUM, WRAP(ac97_on_off),
	  AC97_REG_CENTER_LFE_MASTER, 0x8080, 1, 7, 0, 0, CHECK_CENTER
	},
	/* LFE volume*/
	{ AudioCoutputs,	AudioNlfe,	NULL,
	  AUDIO_MIXER_VALUE, WRAP(ac97_volume_mono),
	  AC97_REG_CENTER_LFE_MASTER, 0x8080, 5, 8, 0, 0, CHECK_LFE
	},
	{ AudioCoutputs,	AudioNlfe,	AudioNmute,
	  AUDIO_MIXER_ENUM, WRAP(ac97_on_off),
	  AC97_REG_CENTER_LFE_MASTER, 0x8080, 1, 15, 0, 0, CHECK_LFE
	},
	/* Tone */
	{ AudioCoutputs,	"tone",	NULL,
	  AUDIO_MIXER_VALUE, WRAP(ac97_volume_stereo),
	  AC97_REG_MASTER_TONE, 0x0f0f, 4, 0, 0, 0, CHECK_TONE
	},
	/* PC Beep Volume */
	{ AudioCinputs,		AudioNspeaker,	NULL,
	  AUDIO_MIXER_VALUE, WRAP(ac97_volume_mono),
	  AC97_REG_PCBEEP_VOLUME, 0x0000, 4, 1, 1,
	},

	/* Phone */
	{ AudioCinputs,		"phone",	NULL,
	  AUDIO_MIXER_VALUE, WRAP(ac97_volume_mono),
	  AC97_REG_PHONE_VOLUME, 0x8008, 5, 0, 1,
	},
	/* Mic Volume */
	{ AudioCinputs,		AudioNmicrophone, NULL,
	  AUDIO_MIXER_VALUE, WRAP(ac97_volume_mono),
	  AC97_REG_MIC_VOLUME, 0x8008, 5, 0, 1,
	},
	{ AudioCinputs,		AudioNmicrophone, AudioNpreamp,
	  AUDIO_MIXER_ENUM, WRAP(ac97_on_off),
	  AC97_REG_MIC_VOLUME, 0x8008, 1, 6, 0,
	},
	{ AudioCinputs,		AudioNmicrophone, AudioNsource,
	  AUDIO_MIXER_ENUM, WRAP(ac97_mic_select),
	  AC97_REG_GP, 0x0000, 1, 8, 0,
	},
	/* Line in Volume */
	{ AudioCinputs,		AudioNline,	NULL,
	  AUDIO_MIXER_VALUE, WRAP(ac97_volume_stereo),
	  AC97_REG_LINEIN_VOLUME, 0x8808, 5, 0, 1,
	},
	/* CD Volume */
	{ AudioCinputs,		AudioNcd,	NULL,
	  AUDIO_MIXER_VALUE, WRAP(ac97_volume_stereo),
	  AC97_REG_CD_VOLUME, 0x8808, 5, 0, 1,
	},
	/* Video Volume */
	{ AudioCinputs,		AudioNvideo,	NULL,
	  AUDIO_MIXER_VALUE, WRAP(ac97_volume_stereo),
	  AC97_REG_VIDEO_VOLUME, 0x8808, 5, 0, 1,
	},
	/* AUX volume */
	{ AudioCinputs,		AudioNaux,	NULL,
	  AUDIO_MIXER_VALUE, WRAP(ac97_volume_stereo),
	  AC97_REG_AUX_VOLUME, 0x8808, 5, 0, 1,
	},
	/* PCM out volume */
	{ AudioCinputs,		AudioNdac,	NULL,
	  AUDIO_MIXER_VALUE, WRAP(ac97_volume_stereo),
	  AC97_REG_PCMOUT_VOLUME, 0x8808, 5, 0, 1,
	},
	/* Record Source - some logic for this is hard coded - see below */
	{ AudioCrecord,		AudioNsource,	NULL,
	  AUDIO_MIXER_ENUM, WRAP(ac97_source),
	  AC97_REG_RECORD_SELECT, 0x0000, 3, 0, 0,
	},
	/* Record Gain */
	{ AudioCrecord,		AudioNvolume,	NULL,
	  AUDIO_MIXER_VALUE, WRAP(ac97_volume_stereo),
	  AC97_REG_RECORD_GAIN, 0x8000, 4, 0, 1,
	},
	/* Record Gain mic */
	{ AudioCrecord,		AudioNmicrophone, NULL,
	  AUDIO_MIXER_VALUE, WRAP(ac97_volume_mono),
	  AC97_REG_RECORD_GAIN_MIC, 0x8000, 4, 0, 1, 1, CHECK_MIC
	},
	/* */
	{ AudioCoutputs,	AudioNloudness,	NULL,
	  AUDIO_MIXER_ENUM, WRAP(ac97_on_off),
	  AC97_REG_GP, 0x0000, 1, 12, 0, 0, CHECK_LOUDNESS
	},
	{ AudioCoutputs,	AudioNspatial,	NULL,
	  AUDIO_MIXER_ENUM, WRAP(ac97_on_off),
	  AC97_REG_GP, 0x0000, 1, 13, 0, 1, CHECK_3D
	},
	{ AudioCoutputs,	AudioNspatial,	"center",
	  AUDIO_MIXER_VALUE, WRAP(ac97_volume_mono),
	  AC97_REG_3D_CONTROL, 0x0000, 4, 8, 0, 1, CHECK_3D
	},
	{ AudioCoutputs,	AudioNspatial,	"depth",
	  AUDIO_MIXER_VALUE, WRAP(ac97_volume_mono),
	  AC97_REG_3D_CONTROL, 0x0000, 4, 0, 0, 1, CHECK_3D
	},
	/* External Amp */
	{ AudioCoutputs,	AudioNextamp,	NULL,
	  AUDIO_MIXER_ENUM, WRAP(ac97_on_off),
	  AC97_REG_POWER, 0x0000, 1, 15, 0, 0
	},
	/* S/PDIF output enable */
	{ AudioCoutputs,	AudioNspdif,	NULL,
	  AUDIO_MIXER_ENUM, WRAP(ac97_on_off),
	  AC97_REG_EXT_AUDIO_CTRL, 0x0000, 1, 2, 0, 0, CHECK_SPDIF
	}

	/* Missing features: Simulated Stereo, POP, Loopback mode */
};

/*
 * Check out http://www.intel.com/technology/computing/audio/index.htm
 * for information on AC-97
 */

struct ac97_softc {
	/* ac97_codec_if must be at the first of ac97_softc. */
	struct ac97_codec_if codec_if;
	struct ac97_host_if *host_if;
#define MAX_SOURCES	(2 * nitems(source_info))
	struct ac97_source_info source_info[MAX_SOURCES];
	int num_source_info;
	enum ac97_host_flags host_flags;
	unsigned int ac97_clock; /* usually 48000 */
#define AC97_STANDARD_CLOCK	48000U
	u_int16_t caps;		/* -> AC97_REG_RESET */
	u_int16_t ext_id;	/* -> AC97_REG_EXT_AUDIO_ID */
	u_int16_t shadow_reg[128];
	int lock_counter;
};

int	ac97_mixer_get_port(struct ac97_codec_if *, mixer_ctrl_t *);
int	ac97_mixer_set_port(struct ac97_codec_if *, mixer_ctrl_t *);
void	ac97_lock(struct ac97_codec_if *);
void	ac97_unlock(struct ac97_codec_if *);
int	ac97_query_devinfo(struct ac97_codec_if *, mixer_devinfo_t *);
int	ac97_get_portnum_by_name(struct ac97_codec_if *, char *, char *,
	    char *);
void	ac97_restore_shadow(struct ac97_codec_if *);
int	ac97_set_rate(struct ac97_codec_if *codec_if, int target, u_long *rate);
void	ac97_set_clock(struct ac97_codec_if *codec_if, unsigned int clock);
u_int16_t ac97_get_extcaps(struct ac97_codec_if *codec_if);
int	ac97_add_port(struct ac97_softc *as, struct ac97_source_info *src);

void	ac97_ad1885_init(struct ac97_softc *, int);
void	ac97_ad1886_init(struct ac97_softc *, int);
void	ac97_ad198x_init(struct ac97_softc *, int);
void	ac97_alc650_init(struct ac97_softc *, int);
void	ac97_cx20468_init(struct ac97_softc *, int);
void	ac97_vt1616_init(struct ac97_softc *, int);

struct ac97_codec_if_vtbl ac97civ = {
	ac97_mixer_get_port,
	ac97_mixer_set_port,
	ac97_query_devinfo,
	ac97_get_portnum_by_name,
	ac97_restore_shadow,
	ac97_get_extcaps,
	ac97_set_rate,
	ac97_set_clock,
	ac97_lock,
	ac97_unlock
};

const struct ac97_codecid {
	u_int8_t id;
	u_int8_t mask;
	u_int8_t rev;
	u_int8_t shift;	/* no use yet */
	char * const name;
	void (*init)(struct ac97_softc *, int);
}  ac97_ad[] = {
	{ 0x03, 0xff, 0, 0,	"AD1819" },
	{ 0x40, 0xff, 0, 0,	"AD1881" },
	{ 0x48, 0xff, 0, 0,	"AD1881A" },
	{ 0x60, 0xff, 0, 0,	"AD1885", 	ac97_ad1885_init },
	{ 0x61, 0xff, 0, 0,	"AD1886",	ac97_ad1886_init },
	{ 0x63, 0xff, 0, 0,	"AD1886A" },
	{ 0x68, 0xff, 0, 0,	"AD1888",	ac97_ad198x_init },
	{ 0x70, 0xff, 0, 0,	"AD1980",	ac97_ad198x_init },
	{ 0x72, 0xff, 0, 0,	"AD1981A" },
	{ 0x74, 0xff, 0, 0,	"AD1981B" },
	{ 0x75, 0xff, 0, 0,	"AD1985",	ac97_ad198x_init },
}, ac97_ak[] = {
	{ 0x00,	0xfe, 1, 0,	"AK4540" },
	{ 0x01,	0xfe, 1, 0,	"AK4540" },
	{ 0x02,	0xff, 0, 0,	"AK4543" },
	{ 0x05,	0xff, 0, 0,	"AK4544" },
	{ 0x06,	0xff, 0, 0,	"AK4544A" },
	{ 0x07,	0xff, 0, 0,	"AK4545" },
}, ac97_av[] = {
	{ 0x10, 0xff, 0, 0,	"ALC200" },
	{ 0x20, 0xff, 0, 0,	"ALC650" },
	{ 0x21, 0xff, 0, 0,	"ALC650D" },
	{ 0x22, 0xff, 0, 0,	"ALC650E" },
	{ 0x23, 0xff, 0, 0,	"ALC650F" },
	{ 0x30, 0xff, 0, 0,	"ALC101" },
	{ 0x40, 0xff, 0, 0,	"ALC202" },
	{ 0x50, 0xff, 0, 0,	"ALC250" },
	{ 0x52, 0xff, 0, 0,	"ALC250A?" },
	{ 0x60, 0xf0, 0xf, 0,	"ALC655",	ac97_alc650_init },
	{ 0x70, 0xf0, 0xf, 0,	"ALC203" },
	{ 0x80, 0xf0, 0xf, 0,	"ALC658",	ac97_alc650_init },
	{ 0x90, 0xf0, 0xf, 0,	"ALC850" },
}, ac97_rl[] = {
	{ 0x00, 0xf0, 0xf, 0,	"RL5306" },
	{ 0x10, 0xf0, 0xf, 0,	"RL5382" },
	{ 0x20, 0xf0, 0xf, 0,	"RL5383" },
}, ac97_cm[] = {
	{ 0x41,	0xff, 0, 0,	"CMI9738" },
	{ 0x61,	0xff, 0, 0,	"CMI9739" },
	{ 0x78,	0xff, 0, 0,	"CMI9761A" },
	{ 0x82,	0xff, 0, 0,	"CMI9761B" },
	{ 0x83,	0xff, 0, 0,	"CMI9761A+" },
}, ac97_cr[] = {
	{ 0x84,	0xff, 0, 0,	"EV1938" },
}, ac97_cs[] = {
	{ 0x00,	0xf8, 7, 0,	"CS4297" },
	{ 0x10,	0xf8, 7, 0,	"CS4297A" },
	{ 0x20,	0xf8, 7, 0,	"CS4298" },
	{ 0x28,	0xf8, 7, 0,	"CS4294" },
	{ 0x30,	0xf8, 7, 0,	"CS4299" },
	{ 0x48,	0xf8, 7, 0,	"CS4201" },
	{ 0x58,	0xf8, 7, 0,	"CS4205" },
	{ 0x60,	0xf8, 7, 0,	"CS4291" },
	{ 0x70,	0xf8, 7, 0,	"CS4202" },
}, ac97_cx[] = {
	{ 0x21, 0xff, 0, 0,	"HSD11246" },
	{ 0x28, 0xf8, 7, 0,	"CX20468",	ac97_cx20468_init },
	{ 0x30, 0xff, 0, 0,	"CXT48", },
	{ 0x42, 0xff, 0, 0,	"CXT66", },
}, ac97_dt[] = {
	{ 0x00, 0xff, 0, 0,	"DT0398" },
}, ac97_em[] = {
	{ 0x23, 0xff, 0, 0,	"EM28023" },
	{ 0x28, 0xff, 0, 0,	"EM28028" },
}, ac97_es[] = {
	{ 0x08, 0xff, 0, 0,	"ES1921" },
}, ac97_is[] = {
	{ 0x00, 0xff, 0, 0,	"HMP9701" },
}, ac97_ic[] = {
	{ 0x01, 0xff, 0, 0,	"ICE1230" },
	{ 0x11, 0xff, 0, 0,	"ICE1232" },
	{ 0x14, 0xff, 0, 0,	"ICE1232A" },
	{ 0x51, 0xff, 0, 0,	"VIA VT1616" },
	{ 0x52, 0xff, 0, 0,	"VIA VT1616i",	ac97_vt1616_init },
}, ac97_it[] = {
	{ 0x20, 0xff, 0, 0,	"ITE2226E" },
	{ 0x60, 0xff, 0, 0,	"ITE2646E" },
}, ac97_ns[] = {
	{ 0x00,	0xff, 0, 0,	"LM454[03568]" },
	{ 0x31,	0xff, 0, 0,	"LM4549" },
	{ 0x40, 0xff, 0, 0,	"LM4540" },
	{ 0x43, 0xff, 0, 0,	"LM4543" },
	{ 0x46, 0xff, 0, 0,	"LM4546A" },
	{ 0x48, 0xff, 0, 0,	"LM4548A" },
	{ 0x49, 0xff, 0, 0,	"LM4549A" },
	{ 0x50, 0xff, 0, 0,	"LM4550" },
}, ac97_ps[] = {
	{ 0x01,	0xff, 0, 0,	"UCB1510" },
	{ 0x04,	0xff, 0, 0,	"UCB1400" },
}, ac97_sl[] = {
	{ 0x20,	0xe0, 0, 0,	"Si3036/38" },
}, ac97_st[] = {
	{ 0x00,	0xff, 0, 0,	"STAC9700" },
	{ 0x04,	0xff, 0, 0,	"STAC970[135]" },
	{ 0x05,	0xff, 0, 0,	"STAC9704" },
	{ 0x08,	0xff, 0, 0,	"STAC9708/11" },
	{ 0x09,	0xff, 0, 0,	"STAC9721/23" },
	{ 0x44,	0xff, 0, 0,	"STAC9744/45" },
	{ 0x50,	0xff, 0, 0,	"STAC9750/51" },
	{ 0x52,	0xff, 0, 0,	"STAC9752/53" },
	{ 0x56,	0xff, 0, 0,	"STAC9756/57" },
	{ 0x58,	0xff, 0, 0,	"STAC9758/59" },
	{ 0x60,	0xff, 0, 0,	"STAC9760/61" },
	{ 0x62,	0xff, 0, 0,	"STAC9762/63" },
	{ 0x66,	0xff, 0, 0,	"STAC9766/67" },
	{ 0x84,	0xff, 0, 0,	"STAC9784/85" },
}, ac97_vi[] = {
	{ 0x61, 0xff, 0, 0,	"VT1612A" },
	{ 0x70, 0xff, 0, 0,	"VT1617" },
}, ac97_tt[] = {
	{ 0x02,	0xff, 0, 0,	"TR28022" },
	{ 0x03,	0xff, 0, 0,	"TR28023" },
	{ 0x06,	0xff, 0, 0,	"TR28026" },
	{ 0x08,	0xff, 0, 0,	"TR28028" },
	{ 0x23,	0xff, 0, 0,	"TR28602" },
}, ac97_ti[] = {
	{ 0x20, 0xff, 0, 0,	"TLC320AD9xC" },
}, ac97_wb[] = {
	{ 0x01, 0xff, 0, 0,	"W83971D" },
}, ac97_wo[] = {
	{ 0x00,	0xff, 0, 0,	"WM9701A" },
	{ 0x03,	0xff, 0, 0,	"WM9704M/Q-0" }, /* & WM9703 */
	{ 0x04,	0xff, 0, 0,	"WM9704M/Q-1" },
	{ 0x05,	0xff, 0, 0,	"WM9705/10" },
	{ 0x09,	0xff, 0, 0,	"WM9709" },
	{ 0x12,	0xff, 0, 0,	"WM9711/12" },
}, ac97_ym[] = {
	{ 0x00, 0xff, 0, 0,	"YMF743-S" },
	{ 0x02, 0xff, 0, 0,	"YMF752-S" },
	{ 0x03, 0xff, 0, 0,	"YMF753-S" },
};

#define	cl(n)	n, nitems(n)
const struct ac97_vendorid {
	u_int32_t id;
	char * const name;
	const struct ac97_codecid * const codecs;
	u_int8_t num;
} ac97_vendors[] = {
	{ 0x01408300, "Creative",		cl(ac97_cr) },
	{ 0x41445300, "Analog Devices",		cl(ac97_ad) },
	{ 0x414b4D00, "Asahi Kasei",		cl(ac97_ak) },
	{ 0x414c4300, "Realtek",		cl(ac97_rl) },
	{ 0x414c4700, "Avance Logic",		cl(ac97_av) },
	{ 0x434d4900, "C-Media Electronics",	cl(ac97_cm) },
	{ 0x43525900, "Cirrus Logic",		cl(ac97_cs) },
	{ 0x43585400, "Conexant",		cl(ac97_cx) },
	{ 0x44543000, "Diamond Technology",	cl(ac97_dt) },
	{ 0x454d4300, "eMicro",			cl(ac97_em) },
	{ 0x45838300, "ESS Technology",		cl(ac97_es) },
	{ 0x48525300, "Intersil",		cl(ac97_is) },
	{ 0x49434500, "ICEnsemble",		cl(ac97_ic) },
	{ 0x49544500, "ITE, Inc.",		cl(ac97_it) },
	{ 0x4e534300, "National Semiconductor", cl(ac97_ns) },
	{ 0x50534300, "Philips Semiconductor",	cl(ac97_ps) },
	{ 0x53494c00, "Silicon Laboratory",	cl(ac97_sl) },
	{ 0x54524100, "TriTech Microelectronics", cl(ac97_tt) },
	{ 0x54584e00, "Texas Instruments",	cl(ac97_ti) },
	{ 0x56494100, "VIA Technologies",	cl(ac97_vi) },
	{ 0x57454300, "Winbond",		cl(ac97_wb) },
	{ 0x574d4c00, "Wolfson",		cl(ac97_wo) },
	{ 0x594d4800, "Yamaha",			cl(ac97_ym) },
	{ 0x83847600, "SigmaTel",		cl(ac97_st) },
};
#undef cl

const char * const ac97enhancement[] = {
	"No 3D Stereo",
	"Analog Devices Phat Stereo",
	"Creative",
	"National Semi 3D",
	"Yamaha Ymersion",
	"BBE 3D",
	"Crystal Semi 3D",
	"Qsound QXpander",
	"Spatializer 3D",
	"SRS 3D",
	"Platform Tech 3D",
	"AKM 3D",
	"Aureal",
	"AZTECH 3D",
	"Binaura 3D",
	"ESS Technology",
	"Harman International VMAx",
	"Nvidea 3D",
	"Philips Incredible Sound",
	"Texas Instruments 3D",
	"VLSI Technology 3D",
	"TriTech 3D",
	"Realtek 3D",
	"Samsung 3D",
	"Wolfson Microelectronics 3D",
	"Delta Integration 3D",
	"SigmaTel 3D",
	"KS Waves 3D",
	"Rockwell 3D",
	"Unknown 3D",
	"Unknown 3D",
	"Unknown 3D"
};

const char * const ac97feature[] = {
	"mic channel",
	"reserved",
	"tone",
	"simulated stereo",
	"headphone",
	"bass boost",
	"18 bit DAC",
	"20 bit DAC",
	"18 bit ADC",
	"20 bit ADC"
};

int	ac97_str_equal(const char *, const char *);
int	ac97_check_capability(struct ac97_softc *, int);
void	ac97_setup_source_info(struct ac97_softc *);
void	ac97_setup_defaults(struct ac97_softc *);
int	ac97_read(struct ac97_softc *, u_int8_t, u_int16_t *);
int	ac97_write(struct ac97_softc *, u_int8_t, u_int16_t);

#ifdef AUDIO_DEBUG
#define DPRINTF(x)	if (ac97debug) printf x
#define DPRINTFN(n,x)	if (ac97debug>(n)) printf x
#ifdef AC97_DEBUG
int	ac97debug = 1;
#else
int	ac97debug = 0;
#endif
#else
#define DPRINTF(x)
#define DPRINTFN(n,x)
#endif

void
ac97_get_default_params(struct audio_params *params)
{
	*params = ac97_audio_default;
}

int
ac97_read(struct ac97_softc *as, u_int8_t reg, u_int16_t *val)
{
	int error;

	if (((as->host_flags & AC97_HOST_DONT_READ) &&
	    (reg != AC97_REG_VENDOR_ID1 && reg != AC97_REG_VENDOR_ID2 &&
	    reg != AC97_REG_RESET)) ||
	    (as->host_flags & AC97_HOST_DONT_READANY)) {
		*val = as->shadow_reg[reg >> 1];
		return (0);
	}

	if ((error = as->host_if->read(as->host_if->arg, reg, val)))
		*val = as->shadow_reg[reg >> 1];
	return (error);
}

int
ac97_write(struct ac97_softc *as, u_int8_t reg, u_int16_t val)
{
	as->shadow_reg[reg >> 1] = val;
	return (as->host_if->write(as->host_if->arg, reg, val));
}

void
ac97_setup_defaults(struct ac97_softc *as)
{
	int idx;

	bzero(as->shadow_reg, sizeof(as->shadow_reg));

	for (idx = 0; idx < nitems(source_info); idx++) {
		const struct ac97_source_info *si = &source_info[idx];

		ac97_write(as, si->reg, si->default_value);
	}
}

void
ac97_restore_shadow(struct ac97_codec_if *self)
{
	struct ac97_softc *as = (struct ac97_softc *)self;
	int idx;

	for (idx = 0; idx < nitems(source_info); idx++) {
		const struct ac97_source_info *si = &source_info[idx];

		ac97_write(as, si->reg, as->shadow_reg[si->reg >> 1]);
	}
}

int
ac97_str_equal(const char *a, const char *b)
{
	return ((a == b) || (a && b && (!strcmp(a, b))));
}

int
ac97_check_capability(struct ac97_softc *as, int check)
{
	switch (check) {
	case CHECK_NONE:
		return 1;
	case CHECK_SURROUND:
		return as->ext_id & AC97_EXT_AUDIO_SDAC;
	case CHECK_CENTER:
		return as->ext_id & AC97_EXT_AUDIO_CDAC;
	case CHECK_LFE:
		return as->ext_id & AC97_EXT_AUDIO_LDAC;
	case CHECK_SPDIF:
		return as->ext_id & AC97_EXT_AUDIO_SPDIF;
	case CHECK_HEADPHONES:
		return as->caps & AC97_CAPS_HEADPHONES;
	case CHECK_TONE:
		return as->caps & AC97_CAPS_TONECTRL;
	case CHECK_MIC:
		return as->caps & AC97_CAPS_MICIN;
	case CHECK_LOUDNESS:
		return as->caps & AC97_CAPS_LOUDNESS;
	case CHECK_3D:
		return AC97_CAPS_ENHANCEMENT(as->caps) != 0;
	default:
		printf("%s: internal error: feature=%d\n", __func__, check);
		return 0;
	}
}

void
ac97_setup_source_info(struct ac97_softc *as)
{
	struct ac97_source_info *si, *si2;
	int idx, ouridx;

	for (idx = 0, ouridx = 0; idx < nitems(source_info); idx++) {
		si = &as->source_info[ouridx];

		if (!ac97_check_capability(as, source_info[idx].req_feature))
			continue;

		bcopy(&source_info[idx], si, sizeof(*si));

		switch (si->type) {
		case AUDIO_MIXER_CLASS:
			si->mixer_class = ouridx;
			ouridx++;
			break;
		case AUDIO_MIXER_VALUE:
			/* Todo - Test to see if it works */
			ouridx++;

			/* Add an entry for mute, if necessary */
			if (si->mute) {
				si = &as->source_info[ouridx];
				bcopy(&source_info[idx], si, sizeof(*si));
				si->qualifier = AudioNmute;
				si->type = AUDIO_MIXER_ENUM;
				si->info = &ac97_on_off;
				si->info_size = sizeof(ac97_on_off);
				si->bits = 1;
				si->ofs = 15;
				si->mute = 0;
				si->polarity = 0;
				ouridx++;
			}
			break;
		case AUDIO_MIXER_ENUM:
			/* Todo - Test to see if it works */
			ouridx++;
			break;
		default:
			printf ("ac97: shouldn't get here\n");
			break;
		}
	}

	as->num_source_info = ouridx;

	for (idx = 0; idx < as->num_source_info; idx++) {
		int idx2, previdx;

		si = &as->source_info[idx];

		/* Find mixer class */
		for (idx2 = 0; idx2 < as->num_source_info; idx2++) {
			si2 = &as->source_info[idx2];

			if (si2->type == AUDIO_MIXER_CLASS &&
			    ac97_str_equal(si->class, si2->class)) {
				si->mixer_class = idx2;
			}
		}

		/* Setup prev and next pointers */
		if (si->prev != 0 || si->qualifier)
			continue;

		si->prev = AUDIO_MIXER_LAST;
		previdx = idx;

		for (idx2 = 0; idx2 < as->num_source_info; idx2++) {
			if (idx2 == idx)
				continue;

			si2 = &as->source_info[idx2];

			if (!si2->prev &&
			    ac97_str_equal(si->class, si2->class) &&
			    ac97_str_equal(si->device, si2->device)) {
				as->source_info[previdx].next = idx2;
				as->source_info[idx2].prev = previdx;

				previdx = idx2;
			}
		}

		as->source_info[previdx].next = AUDIO_MIXER_LAST;
	}
}

int
ac97_attach(struct ac97_host_if *host_if)
{
	struct ac97_softc *as;
	u_int16_t id1, id2, val;
	u_int32_t id;
	u_int16_t extstat, rate;
	mixer_ctrl_t ctl;
	int error, i;
	void (*initfunc)(struct ac97_softc *, int);

	initfunc = NULL;

	if (!(as = malloc(sizeof(*as), M_DEVBUF, M_NOWAIT | M_ZERO)))
		return (ENOMEM);

	as->codec_if.as = as;
	as->codec_if.vtbl = &ac97civ;
	as->host_if = host_if;

	if ((error = host_if->attach(host_if->arg, &as->codec_if))) {
		free(as, M_DEVBUF, 0);
		return (error);
	}

	host_if->reset(host_if->arg);
	DELAY(1000);

	host_if->write(host_if->arg, AC97_REG_POWER, 0);
	host_if->write(host_if->arg, AC97_REG_RESET, 0);
	DELAY(10000);

	if (host_if->flags)
		as->host_flags = host_if->flags(host_if->arg);

	ac97_setup_defaults(as);
	ac97_read(as, AC97_REG_VENDOR_ID1, &id1);
	ac97_read(as, AC97_REG_VENDOR_ID2, &id2);
	ac97_read(as, AC97_REG_RESET, &as->caps);

	id = (id1 << 16) | id2;
	if (id) {
		register const struct ac97_vendorid *vendor;
		register const struct ac97_codecid *codec;

		printf("ac97: codec id 0x%08x", id);
		for (vendor = &ac97_vendors[sizeof(ac97_vendors) /
		     sizeof(ac97_vendors[0]) - 1];
		     vendor >= ac97_vendors; vendor--) {
			if (vendor->id == (id & AC97_VENDOR_ID_MASK)) {
				printf(" (%s", vendor->name);
				for (codec = &vendor->codecs[vendor->num-1];
				     codec >= vendor->codecs; codec--) {
					if (codec->id == (id & codec->mask))
						break;
				}
				if (codec >= vendor->codecs && codec->mask) {
					printf(" %s", codec->name);
					initfunc = codec->init;
				} else
					printf(" <%02x>", id & 0xff);
				if (codec >= vendor->codecs && codec->rev)
					printf(" rev %d", id & codec->rev);
				printf(")");
				break;
			}
		}
		printf("\n");
	} else
		printf("ac97: codec id not read\n");

	if (as->caps) {
		printf("ac97: codec features ");
		for (i = 0; i < 10; i++) {
			if (as->caps & (1 << i))
				printf("%s, ", ac97feature[i]);
		}
		printf("%s\n",
		    ac97enhancement[AC97_CAPS_ENHANCEMENT(as->caps)]);
	}

	as->ac97_clock = AC97_STANDARD_CLOCK;
	ac97_read(as, AC97_REG_EXT_AUDIO_ID, &as->ext_id);
	if (as->ext_id & (AC97_EXT_AUDIO_VRA | AC97_EXT_AUDIO_DRA
			  | AC97_EXT_AUDIO_SPDIF | AC97_EXT_AUDIO_VRM
			  | AC97_EXT_AUDIO_CDAC | AC97_EXT_AUDIO_SDAC
			  | AC97_EXT_AUDIO_LDAC)) {

		ac97_read(as, AC97_REG_EXT_AUDIO_CTRL, &extstat);
		extstat &= ~AC97_EXT_AUDIO_DRA;

		if (as->ext_id & AC97_EXT_AUDIO_VRM)
			extstat |= AC97_EXT_AUDIO_VRM;

		if (as->ext_id & AC97_EXT_AUDIO_LDAC)
			extstat |= AC97_EXT_AUDIO_LDAC;
		if (as->ext_id & AC97_EXT_AUDIO_SDAC)
			extstat |= AC97_EXT_AUDIO_SDAC;
		if (as->ext_id & AC97_EXT_AUDIO_CDAC)
			extstat |= AC97_EXT_AUDIO_CDAC;
		if (as->ext_id & AC97_EXT_AUDIO_SPDIF) {
			/* XXX S/PDIF gets same data as DAC?
			 * maybe this should be settable?
			 * default is SPSAAB (10/11) on AD1980 and ALC codecs.
			 */
			extstat &= ~AC97_EXT_AUDIO_SPSA_MASK;
			extstat |= AC97_EXT_AUDIO_SPSA34;
			ac97_read(as, AC97_REG_SPDIF_CTRL, &val);
			val = (val & ~AC97_SPDIF_SPSR_MASK) |
			    AC97_SPDIF_SPSR_48K;
			ac97_write(as, AC97_REG_SPDIF_CTRL, val);
		}
		if (as->ext_id & AC97_EXT_AUDIO_VRA)
			extstat |= AC97_EXT_AUDIO_VRA;
		ac97_write(as, AC97_REG_EXT_AUDIO_CTRL, extstat);
		if (as->ext_id & AC97_EXT_AUDIO_VRA) {
			/* VRA should be enabled. */
			/* so it claims to do variable rate, let's make sure */
			ac97_write(as, AC97_REG_PCM_FRONT_DAC_RATE, 44100);
			ac97_read(as, AC97_REG_PCM_FRONT_DAC_RATE, &rate);
			if (rate != 44100) {
				/* We can't believe ext_id */
				as->ext_id = 0;
			}
			/* restore the default value */
			ac97_write(as, AC97_REG_PCM_FRONT_DAC_RATE,
				   AC97_SINGLE_RATE);
		}
	}

	ac97_setup_source_info(as);

	DELAY(900 * 1000);

	/* use initfunc for specific device */
	as->codec_if.initfunc = initfunc;
	if (initfunc != NULL)
		initfunc(as, 0);

	/* Just enable the DAC and master volumes by default */
	bzero(&ctl, sizeof(ctl));

	ctl.type = AUDIO_MIXER_ENUM;
	ctl.un.ord = 0;  /* off */
	ctl.dev = ac97_get_portnum_by_name(&as->codec_if, AudioCoutputs,
	    AudioNmaster, AudioNmute);
	ac97_mixer_set_port(&as->codec_if, &ctl);

	ctl.dev = ac97_get_portnum_by_name(&as->codec_if, AudioCinputs,
	    AudioNdac, AudioNmute);
	ac97_mixer_set_port(&as->codec_if, &ctl);

	ctl.dev = ac97_get_portnum_by_name(&as->codec_if, AudioCrecord,
	    AudioNvolume, AudioNmute);
	ac97_mixer_set_port(&as->codec_if, &ctl);

	ctl.type = AUDIO_MIXER_ENUM;
	ctl.un.ord = 0;
	ctl.dev = ac97_get_portnum_by_name(&as->codec_if, AudioCrecord,
	    AudioNsource, NULL);
	ac97_mixer_set_port(&as->codec_if, &ctl);

	return (0);
}

int
ac97_resume(struct ac97_host_if *host_if, struct ac97_codec_if *codec_if)
{
	struct ac97_softc *as = codec_if->as;
	u_int16_t val, extstat;

	host_if->reset(host_if->arg);
	DELAY(1000);

	host_if->write(host_if->arg, AC97_REG_POWER, 0);
	host_if->write(host_if->arg, AC97_REG_RESET, 0);
	DELAY(10000);

	codec_if->vtbl->restore_ports(codec_if);

	if (as->ext_id & (AC97_EXT_AUDIO_VRA | AC97_EXT_AUDIO_DRA
			  | AC97_EXT_AUDIO_SPDIF | AC97_EXT_AUDIO_VRM
			  | AC97_EXT_AUDIO_CDAC | AC97_EXT_AUDIO_SDAC
			  | AC97_EXT_AUDIO_LDAC)) {

		ac97_read(as, AC97_REG_EXT_AUDIO_CTRL, &extstat);
		extstat &= ~AC97_EXT_AUDIO_DRA;

		if (as->ext_id & AC97_EXT_AUDIO_VRM)
			extstat |= AC97_EXT_AUDIO_VRM;

		if (as->ext_id & AC97_EXT_AUDIO_LDAC)
			extstat |= AC97_EXT_AUDIO_LDAC;
		if (as->ext_id & AC97_EXT_AUDIO_SDAC)
			extstat |= AC97_EXT_AUDIO_SDAC;
		if (as->ext_id & AC97_EXT_AUDIO_CDAC)
			extstat |= AC97_EXT_AUDIO_CDAC;

		if (as->ext_id & AC97_EXT_AUDIO_SPDIF) {
			extstat &= ~AC97_EXT_AUDIO_SPSA_MASK;
			extstat |= AC97_EXT_AUDIO_SPSA34;
			ac97_read(as, AC97_REG_SPDIF_CTRL, &val);
			val = (val & ~AC97_SPDIF_SPSR_MASK) |
			    AC97_SPDIF_SPSR_48K;
			ac97_write(as, AC97_REG_SPDIF_CTRL, val);
		}
		if (as->ext_id & AC97_EXT_AUDIO_VRA)
			extstat |= AC97_EXT_AUDIO_VRA;
		ac97_write(as, AC97_REG_EXT_AUDIO_CTRL, extstat);
	}

	/* use initfunc for specific device */
	if (as->codec_if.initfunc != NULL)
		as->codec_if.initfunc(as, 1);

	return (0);
}

void
ac97_lock(struct ac97_codec_if *codec_if)
{
	struct ac97_softc *as = (struct ac97_softc *)codec_if;
	as->lock_counter++;
}

void
ac97_unlock(struct ac97_codec_if *codec_if)
{
	struct ac97_softc *as = (struct ac97_softc *)codec_if;
	as->lock_counter--;
}

int
ac97_query_devinfo(struct ac97_codec_if *codec_if, mixer_devinfo_t *dip)
{
	struct ac97_softc *as = (struct ac97_softc *)codec_if;

	if (dip->index < as->num_source_info && dip->index >= 0) {
		struct ac97_source_info *si = &as->source_info[dip->index];
		const char *name;

		dip->type = si->type;
		dip->mixer_class = si->mixer_class;
		dip->prev = si->prev;
		dip->next = si->next;

		if (si->qualifier)
			name = si->qualifier;
		else if (si->device)
			name = si->device;
		else if (si->class)
			name = si->class;
		else
			name = NULL;

		if (name)
			strlcpy(dip->label.name, name, sizeof dip->label.name);

		bcopy(si->info, &dip->un, si->info_size);

		/* Set the delta for volume sources */
		if (dip->type == AUDIO_MIXER_VALUE)
			dip->un.v.delta = 1 << (8 - si->bits);

		return (0);
	}

	return (ENXIO);
}

int
ac97_mixer_set_port(struct ac97_codec_if *codec_if, mixer_ctrl_t *cp)
{
	struct ac97_softc *as = (struct ac97_softc *)codec_if;
	struct ac97_source_info *si = &as->source_info[cp->dev];
	u_int16_t mask;
	u_int16_t val, newval;
	int error, spdif;

	if (cp->dev < 0 || cp->dev >= as->num_source_info ||
	    cp->type == AUDIO_MIXER_CLASS || cp->type != si->type)
		return (EINVAL);

	spdif = si->req_feature == CHECK_SPDIF &&
	    si->reg == AC97_REG_EXT_AUDIO_CTRL;
	if (spdif && as->lock_counter >= 0)
		return EBUSY;

	ac97_read(as, si->reg, &val);

	DPRINTFN(5, ("read(%x) = %x\n", si->reg, val));

	mask = (1 << si->bits) - 1;

	switch (cp->type) {
	case AUDIO_MIXER_ENUM:
		if (cp->un.ord > mask || cp->un.ord < 0)
			return (EINVAL);

		newval = (cp->un.ord << si->ofs);
		if (si->reg == AC97_REG_RECORD_SELECT) {
			newval |= (newval << (8 + si->ofs));
			mask |= (mask << 8);
			mask = mask << si->ofs;
		} else if (si->reg == AC97_REG_SURR_MASTER) {
			newval = cp->un.ord ? 0x8080 : 0x0000;
			mask = 0x8080;
		} else
			mask = mask << si->ofs;

		if (si->mute) {
			newval |= newval << 8;
			mask |= mask << 8;
		}

		break;
	case AUDIO_MIXER_VALUE:
	{
		const struct audio_mixer_value *value = si->info;
		u_int16_t  l, r;

		if (cp->un.value.num_channels <= 0 ||
		    cp->un.value.num_channels > value->num_channels)
			return (EINVAL);

		if (cp->un.value.num_channels == 1) {
			l = r = cp->un.value.level[AUDIO_MIXER_LEVEL_MONO];
		} else {
			if (!(as->host_flags & AC97_HOST_SWAPPED_CHANNELS)) {
				l = cp->un.value.level[AUDIO_MIXER_LEVEL_LEFT];
				r = cp->un.value.level[AUDIO_MIXER_LEVEL_RIGHT];
			} else {
				r = cp->un.value.level[AUDIO_MIXER_LEVEL_LEFT];
				l = cp->un.value.level[AUDIO_MIXER_LEVEL_RIGHT];
			}
		}

		if (!si->polarity) {
			l = 255 - l;
			r = 255 - r;
		}

		l >>= 8 - si->bits;
		r >>= 8 - si->bits;

		newval = ((l & mask) << si->ofs);
		if (value->num_channels == 2) {
			newval |= ((r & mask) << (si->ofs + 8));
			mask |= (mask << 8);
		}
		mask = mask << si->ofs;
		break;
	}
	default:
		return (EINVAL);
	}

	error = ac97_write(as, si->reg, (val & ~mask) | newval);
	if (error)
		return (error);

	if (spdif && as->host_if->spdif_event != NULL)
		as->host_if->spdif_event(as->host_if->arg, cp->un.ord);

	return (0);
}

int
ac97_set_rate(struct ac97_codec_if *codec_if, int target, u_long *rate)
{
	struct ac97_softc *as;
	u_long value;
	u_int16_t ext_stat;
	u_int16_t actual;
	u_int16_t power;
	u_int16_t power_bit;

	as = (struct ac97_softc *)codec_if;

	if ((target == AC97_REG_PCM_SURR_DAC_RATE) &&
	    !(as->ext_id & AC97_EXT_AUDIO_SDAC))
			return 0;
	if ((target == AC97_REG_PCM_LFE_DAC_RATE) &&
	    !(as->ext_id & AC97_EXT_AUDIO_LDAC))
			return 0;
	if (target == AC97_REG_PCM_MIC_ADC_RATE) {
		if (!(as->ext_id & AC97_EXT_AUDIO_VRM)) {
			*rate = AC97_SINGLE_RATE;
			return 0;
		}
	} else {
		if (!(as->ext_id & AC97_EXT_AUDIO_VRA)) {
			*rate = AC97_SINGLE_RATE;
			return 0;
		}
	}
	if (as->ac97_clock == 0)
		as->ac97_clock = AC97_STANDARD_CLOCK;
	value = *rate * AC97_STANDARD_CLOCK / as->ac97_clock;
	ext_stat = 0;
	/*
	 * PCM_FRONT_DAC_RATE/PCM_SURR_DAC_RATE/PCM_LFE_DAC_RATE
	 *	Check VRA, DRA
	 * PCM_LR_ADC_RATE
	 *	Check VRA
	 * PCM_MIC_ADC_RATE
	 *	Check VRM
	 */
	switch (target) {
	case AC97_REG_PCM_FRONT_DAC_RATE:
	case AC97_REG_PCM_SURR_DAC_RATE:
	case AC97_REG_PCM_LFE_DAC_RATE:
		power_bit = AC97_POWER_OUT;
		if (as->ext_id & AC97_EXT_AUDIO_DRA) {
			ac97_read(as, AC97_REG_EXT_AUDIO_CTRL, &ext_stat);
			if (value > 0x1ffff) {
				return EINVAL;
			} else if (value > 0xffff) {
				/* Enable DRA */
				ext_stat |= AC97_EXT_AUDIO_DRA;
				ac97_write(as, AC97_REG_EXT_AUDIO_CTRL, ext_stat);
				value /= 2;
			} else {
				/* Disable DRA */
				ext_stat &= ~AC97_EXT_AUDIO_DRA;
				ac97_write(as, AC97_REG_EXT_AUDIO_CTRL, ext_stat);
			}
		} else {
			if (value > 0xffff)
				return EINVAL;
		}
		break;
	case AC97_REG_PCM_LR_ADC_RATE:
		power_bit = AC97_POWER_IN;
		if (value > 0xffff)
			return EINVAL;
		break;
	case AC97_REG_PCM_MIC_ADC_RATE:
		power_bit = AC97_POWER_IN;
		if (value > 0xffff)
			return EINVAL;
		break;
	default:
		printf("%s: Unknown register: 0x%x\n", __func__, target);
		return EINVAL;
	}

	ac97_read(as, AC97_REG_POWER, &power);
	ac97_write(as, AC97_REG_POWER, power | power_bit);

	ac97_write(as, target, (u_int16_t)value);
	ac97_read(as, target, &actual);
	actual = (u_int32_t)actual * as->ac97_clock / AC97_STANDARD_CLOCK;

	ac97_write(as, AC97_REG_POWER, power);
	if (ext_stat & AC97_EXT_AUDIO_DRA) {
		*rate = actual * 2;
	} else {
		*rate = actual;
	}
	return 0;
}

void
ac97_set_clock(struct ac97_codec_if *codec_if, unsigned int clock)
{
	struct ac97_softc *as;

	as = (struct ac97_softc *)codec_if;
	as->ac97_clock = clock;
}

u_int16_t
ac97_get_extcaps(struct ac97_codec_if *codec_if)
{
	struct ac97_softc *as;

	as = (struct ac97_softc *)codec_if;
	return as->ext_id;
}

int
ac97_add_port(struct ac97_softc *as, struct ac97_source_info *src)
{
	struct ac97_source_info *si;
	int ouridx, idx;

	if (as->num_source_info >= MAX_SOURCES) {
		printf("%s: internal error: increase MAX_SOURCES in %s\n",
		       __func__, __FILE__);
		return -1;
	}
	if (!ac97_check_capability(as, src->req_feature))
		return -1;
	ouridx = as->num_source_info;
	si = &as->source_info[ouridx];
	memcpy(si, src, sizeof(*si));

	switch (si->type) {
	case AUDIO_MIXER_CLASS:
	case AUDIO_MIXER_VALUE:
		printf("%s: adding class/value is not supported yet.\n",
		       __func__);
		return -1;
	case AUDIO_MIXER_ENUM:
		break;
	default:
		printf("%s: unknown type: %d\n", __func__, si->type);
		return -1;
	}
	as->num_source_info++;

	si->mixer_class = ac97_get_portnum_by_name(&as->codec_if, si->class,
						   NULL, NULL);
	/* Find the root of the device */
	idx = ac97_get_portnum_by_name(&as->codec_if, si->class,
				       si->device, NULL);
	/* Find the last item */
	while (as->source_info[idx].next != AUDIO_MIXER_LAST)
		idx = as->source_info[idx].next;
	/* Append */
	as->source_info[idx].next = ouridx;
	si->prev = idx;
	si->next = AUDIO_MIXER_LAST;

	return 0;
}

int
ac97_get_portnum_by_name(struct ac97_codec_if *codec_if, char *class,
    char *device, char *qualifier)
{
	struct ac97_softc *as = (struct ac97_softc *)codec_if;
	int idx;

	for (idx = 0; idx < as->num_source_info; idx++) {
		struct ac97_source_info *si = &as->source_info[idx];
		if (ac97_str_equal(class, si->class) &&
		    ac97_str_equal(device, si->device) &&
		    ac97_str_equal(qualifier, si->qualifier))
			return (idx);
	}

	return (-1);
}

int
ac97_mixer_get_port(struct ac97_codec_if *codec_if, mixer_ctrl_t *cp)
{
	struct ac97_softc *as = (struct ac97_softc *)codec_if;
	struct ac97_source_info *si = &as->source_info[cp->dev];
	u_int16_t mask;
	u_int16_t val;

	if (cp->dev < 0 || cp->dev >= as->num_source_info ||
	    cp->type != si->type)
		return (EINVAL);

	ac97_read(as, si->reg, &val);

	DPRINTFN(5, ("read(%x) = %x\n", si->reg, val));

	mask = (1 << si->bits) - 1;

	switch (cp->type) {
	case AUDIO_MIXER_ENUM:
		cp->un.ord = (val >> si->ofs) & mask;
		DPRINTFN(4, ("AUDIO_MIXER_ENUM: %x %d %x %d\n", val, si->ofs,
		    mask, cp->un.ord));
		break;
	case AUDIO_MIXER_VALUE:
	{
		const struct audio_mixer_value *value = si->info;
		u_int16_t  l, r;

		if ((cp->un.value.num_channels <= 0) ||
		    (cp->un.value.num_channels > value->num_channels))
			return (EINVAL);

		if (value->num_channels == 1)
			l = r = (val >> si->ofs) & mask;
		else {
			if (!(as->host_flags & AC97_HOST_SWAPPED_CHANNELS)) {
				l = (val >> si->ofs) & mask;
				r = (val >> (si->ofs + 8)) & mask;
			} else {
				r = (val >> si->ofs) & mask;
				l = (val >> (si->ofs + 8)) & mask;
			}
		}

		l <<= 8 - si->bits;
		r <<= 8 - si->bits;
		if (!si->polarity) {
			l = 255 - l;
			r = 255 - r;
		}

		/*
		 * The EAP driver averages l and r for stereo
		 * channels that are requested in MONO mode. Does this
		 * make sense?
		 */
		if (cp->un.value.num_channels == 1) {
			cp->un.value.level[AUDIO_MIXER_LEVEL_MONO] = l;
		} else if (cp->un.value.num_channels == 2) {
			cp->un.value.level[AUDIO_MIXER_LEVEL_LEFT] = l;
			cp->un.value.level[AUDIO_MIXER_LEVEL_RIGHT] = r;
		}

		break;
	}
	default:
		return (EINVAL);
	}

	return (0);
}

/*
 * Codec-dependent initialization
 */

void
ac97_ad1885_init(struct ac97_softc *as, int resuming)
{
	int i;

	if (resuming)
		return;

	for (i = 0; i < as->num_source_info; i++) {
		if (as->source_info[i].reg == AC97_REG_HEADPHONE_VOLUME)
			as->source_info[i].reg = AC97_REG_MASTER_VOLUME;
		else if (as->source_info[i].reg == AC97_REG_MASTER_VOLUME)
			as->source_info[i].reg = AC97_REG_HEADPHONE_VOLUME;
	}
}

#define AC97_AD1886_JACK_SENSE	0x72

void
ac97_ad1886_init(struct ac97_softc *as, int resuming)
{
	ac97_write(as, AC97_AD1886_JACK_SENSE, 0x0010);
}

void
ac97_ad198x_init(struct ac97_softc *as, int resuming)
{
	int i;
	u_int16_t misc;

	ac97_read(as, AC97_AD_REG_MISC, &misc);
	ac97_write(as, AC97_AD_REG_MISC,
	    misc|AC97_AD_MISC_HPSEL|AC97_AD_MISC_LOSEL);

	if (resuming)
		return;

	for (i = 0; i < as->num_source_info; i++) {
		if (as->source_info[i].reg == AC97_REG_SURR_MASTER)
			as->source_info[i].reg = AC97_REG_MASTER_VOLUME;
		else if (as->source_info[i].reg == AC97_REG_MASTER_VOLUME)
			as->source_info[i].reg = AC97_REG_SURR_MASTER;
	}
}

void
ac97_alc650_init(struct ac97_softc *as, int resuming)
{
	u_int16_t misc;

	ac97_read(as, AC97_ALC650_REG_MISC, &misc);
	if (as->host_flags & AC97_HOST_ALC650_PIN47_IS_EAPD)
		misc &= ~AC97_ALC650_MISC_PIN47;
	misc &= ~AC97_ALC650_MISC_VREFDIS;
	ac97_write(as, AC97_ALC650_REG_MISC, misc);

	if (resuming)
		return;

	struct ac97_source_info sources[3] = {
		{ AudioCoutputs, AudioNsurround, "lineinjack",
		  AUDIO_MIXER_ENUM, WRAP(ac97_on_off),
		  AC97_ALC650_REG_MULTI_CHANNEL_CONTROL,
		  0x0000, 1, 9, 0, 0, CHECK_SURROUND },
		{ AudioCoutputs, AudioNcenter, "micjack",
		  AUDIO_MIXER_ENUM, WRAP(ac97_on_off),
		  AC97_ALC650_REG_MULTI_CHANNEL_CONTROL,
		  0x0000, 1, 10, 0, 0, CHECK_CENTER },
		{ AudioCoutputs, AudioNlfe, "micjack",
		  AUDIO_MIXER_ENUM, WRAP(ac97_on_off),
		  AC97_ALC650_REG_MULTI_CHANNEL_CONTROL,
		  0x0000, 1, 10, 0, 0, CHECK_LFE }};

	ac97_add_port(as, &sources[0]);
	ac97_add_port(as, &sources[1]);
	ac97_add_port(as, &sources[2]);
}

void
ac97_cx20468_init(struct ac97_softc *as, int resuming)
{
	u_int16_t misc;

	ac97_read(as, AC97_CX_REG_MISC, &misc);
	ac97_write(as, AC97_CX_REG_MISC, misc &
	    ~(AC97_CX_SPDIFEN | AC97_CX_COPYRIGHT | AC97_CX_MASK));
}

void
ac97_vt1616_init(struct ac97_softc *as, int resuming)
{
	u_int16_t reg;

	if (as->host_flags & AC97_HOST_VT1616_DYNEX) {
		ac97_read(as, AC97_VT_REG_TEST, &reg);

		/* disable 'hp' mixer controls controlling the surround pins */
		reg &= ~(AC97_VT_LVL);

		/* disable downmixing */
		reg &= ~(AC97_VT_LCTF | AC97_VT_STF);

		/* enable DC offset removal */
		reg |= AC97_VT_BPDC;

		ac97_write(as, AC97_VT_REG_TEST, reg);
	}
}