code:
/*	$OpenBSD: aic7xxxvar.h,v 1.27 2015/07/17 21:42:49 krw Exp $	*/
/*
 * Core definitions and data structures shareable across OS platforms.
 *
 * Copyright (c) 1994-2001 Justin T. Gibbs.
 * Copyright (c) 2000-2001 Adaptec Inc.
 * 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,
 *    without modification.
 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
 *    substantially similar to the "NO WARRANTY" disclaimer below
 *    ("Disclaimer") and any redistribution must be conditioned upon
 *    including a substantially similar Disclaimer requirement for further
 *    binary redistribution.
 * 3. Neither the names of the above-listed copyright holders nor the names
 *    of any contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * Alternatively, this software may be distributed under the terms of the
 * GNU General Public License ("GPL") version 2 as published by the Free
 * Software Foundation.
 *
 * NO WARRANTY
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR 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 DAMAGES.
 *
 * $Id: aic7xxxvar.h,v 1.27 2015/07/17 21:42:49 krw Exp $
 *
 * $FreeBSD: src/sys/dev/aic7xxx/aic7xxx.h,v 1.50 2003/12/17 00:02:09 gibbs Exp $
 */
/*
 * Ported from FreeBSD by Pascal Renauld, Network Storage Solutions, Inc. - April 2003
 */

#ifndef _AIC7XXXVAR_H_
#define _AIC7XXXVAR_H_

#undef AHC_DEBUG

/* Register Definitions */
#include <dev/microcode/aic7xxx/aic7xxx_reg.h>

#include <dev/ic/aic7xxx_cam.h>
/************************* Forward Declarations *******************************/
struct ahc_platform_data;
struct scb_platform_data;
struct seeprom_descriptor;

/****************************** Useful Macros *********************************/
#ifndef MAX
#define MAX(a,b) (((a) > (b)) ? (a) : (b))
#endif

#ifndef MIN
#define MIN(a,b) (((a) < (b)) ? (a) : (b))
#endif

#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif

#define NUM_ELEMENTS(array) (sizeof(array) / sizeof(*array))

#define ALL_CHANNELS '\0'
#define ALL_TARGETS_MASK 0xFFFF
#define INITIATOR_WILDCARD	(~0)

#define SCSIID_TARGET(ahc, scsiid) \
	(((scsiid) & ((((ahc)->features & AHC_TWIN) != 0) ? TWIN_TID : TID)) \
	>> TID_SHIFT)
#define SCSIID_OUR_ID(scsiid) \
	((scsiid) & OID)
#define SCSIID_CHANNEL(ahc, scsiid) \
	((((ahc)->features & AHC_TWIN) != 0) \
        ? ((((scsiid) & TWIN_CHNLB) != 0) ? 'B' : 'A') \
       : 'A')
#define	SCB_IS_SCSIBUS_B(ahc, scb) \
	(SCSIID_CHANNEL(ahc, (scb)->hscb->scsiid) == 'B')
#define	SCB_GET_OUR_ID(scb) \
	SCSIID_OUR_ID((scb)->hscb->scsiid)
#define	SCB_GET_TARGET(ahc, scb) \
	SCSIID_TARGET((ahc), (scb)->hscb->scsiid)
#define	SCB_GET_CHANNEL(ahc, scb) \
	SCSIID_CHANNEL(ahc, (scb)->hscb->scsiid)
#define	SCB_GET_LUN(scb) \
	((scb)->hscb->lun & LID)
#define SCB_GET_TARGET_OFFSET(ahc, scb)	\
	(SCB_GET_TARGET(ahc, scb))
#define SCB_GET_TARGET_MASK(ahc, scb) \
	(0x01 << (SCB_GET_TARGET_OFFSET(ahc, scb)))
#ifdef AHC_DEBUG
#define SCB_IS_SILENT(scb)					\
	((ahc_debug & AHC_SHOW_MASKED_ERRORS) == 0		\
      && (((scb)->flags & SCB_SILENT) != 0))
#else
#define SCB_IS_SILENT(scb)					\
	(((scb)->flags & SCB_SILENT) != 0)
#endif
#define TCL_TARGET_OFFSET(tcl) \
	((((tcl) >> 4) & TID) >> 4)
#define TCL_LUN(tcl) \
	(tcl & (AHC_NUM_LUNS - 1))
#define BUILD_TCL(scsiid, lun) \
	((lun) | (((scsiid) & TID) << 4))

#ifndef	AHC_TARGET_MODE
#undef	AHC_TMODE_ENABLE
#define	AHC_TMODE_ENABLE 0
#endif

/**************************** Driver Constants ********************************/
/*
 * The maximum number of supported targets.
 */
#define AHC_NUM_TARGETS 16

/*
 * The maximum number of supported luns.
 * The identify message only supports 64 luns in SPI3.
 * You can have 2^64 luns when information unit transfers are enabled,
 * but it is doubtful this driver will ever support IUTs.
 */
#define AHC_NUM_LUNS 64

/*
 * The maximum transfer per S/G segment.
 * Limited by MAXPHYS or a 24-bit counter.
 */
#define AHC_MAXTRANSFER_SIZE	 MIN(MAXPHYS,0x00ffffff)

/*
 * The maximum amount of SCB storage in hardware on a controller.
 * This value represents an upper bound.  Controllers vary in the number
 * they actually support.
 */
#define AHC_SCB_MAX	255

/*
 * The maximum number of concurrent transactions supported per driver instance.
 * Sequencer Control Blocks (SCBs) store per-transaction information.  Although
 * the space for SCBs on the host adapter varies by model, the driver will
 * page the SCBs between host and controller memory as needed.  We are limited
 * to 253 because:
 *	1) The 8bit nature of the RISC engine holds us to an 8bit value.
 *	2) We reserve one value, 255, to represent the invalid element.
 *	3) Our input queue scheme requires one SCB to always be reserved
 *	   in advance of queuing any SCBs.  This takes us down to 254.
 *	4) To handle our output queue correctly on machines that only
 *	   support 32bit stores, we must clear the array 4 bytes at a
 *	   time.  To avoid colliding with a DMA write from the sequencer,
 *	   we must be sure that 4 slots are empty when we write to clear
 *	   the queue.  This reduces us to 253 SCBs: 1 that just completed
 *	   and the known three additional empty slots in the queue that
 *	   precede it.
 */
#define AHC_MAX_QUEUE	253

/*
 * The maximum amount of SCB storage we allocate in host memory.  This
 * number should reflect the 1 additional SCB we require to handle our
 * qinfifo mechanism.
 */
#define AHC_SCB_MAX_ALLOC (AHC_MAX_QUEUE+1)

/*
 * Ring Buffer of incoming target commands.
 * We allocate 256 to simplify the logic in the sequencer
 * by using the natural wrap point of an 8bit counter.
 */
#define AHC_TMODE_CMDS	256

/* Reset line assertion time in us */
#define AHC_BUSRESET_DELAY	25

/******************* Chip Characteristics/Operating Settings  *****************/
/*
 * Chip Type
 * The chip order is from least sophisticated to most sophisticated.
 */
typedef enum {
	AHC_NONE	= 0x0000,
	AHC_CHIPID_MASK	= 0x00FF,
	AHC_AIC7770	= 0x0001,
	AHC_AIC7850	= 0x0002,
	AHC_AIC7855	= 0x0003,
	AHC_AIC7859	= 0x0004,
	AHC_AIC7860	= 0x0005,
	AHC_AIC7870	= 0x0006,
	AHC_AIC7880	= 0x0007,
	AHC_AIC7895	= 0x0008,
	AHC_AIC7895C	= 0x0009,
	AHC_AIC7890	= 0x000a,
	AHC_AIC7896	= 0x000b,
	AHC_AIC7892	= 0x000c,
	AHC_AIC7899	= 0x000d,
	AHC_VL		= 0x0100,	/* Bus type VL */
	AHC_EISA	= 0x0200,	/* Bus type EISA */
	AHC_PCI		= 0x0400,	/* Bus type PCI */
	AHC_BUS_MASK	= 0x0F00
} ahc_chip;

/*
 * Features available in each chip type.
 */
typedef enum {
	AHC_FENONE	= 0x00000,
	AHC_ULTRA	= 0x00001,	/* Supports 20MHz Transfers */
	AHC_ULTRA2	= 0x00002,	/* Supports 40MHz Transfers */
	AHC_WIDE	= 0x00004,	/* Wide Channel */
	AHC_TWIN	= 0x00008,	/* Twin Channel */
	AHC_MORE_SRAM	= 0x00010,	/* 80 bytes instead of 64 */
	AHC_CMD_CHAN	= 0x00020,	/* Has a Command DMA Channel */
	AHC_QUEUE_REGS	= 0x00040,	/* Has Queue management registers */
	AHC_SG_PRELOAD	= 0x00080,	/* Can perform auto-SG preload */
	AHC_SPIOCAP	= 0x00100,	/* Has a Serial Port I/O Cap Register */
	AHC_MULTI_TID	= 0x00200,	/* Has bitmask of TIDs for select-in */
	AHC_HS_MAILBOX	= 0x00400,	/* Has HS_MAILBOX register */
	AHC_DT		= 0x00800,	/* Double Transition transfers */
	AHC_NEW_TERMCTL	= 0x01000,	/* Newer termination scheme */
	AHC_MULTI_FUNC	= 0x02000,	/* Multi-Function Twin Channel Device */
	AHC_LARGE_SCBS	= 0x04000,	/* 64byte SCBs */
	AHC_AUTORATE	= 0x08000,	/* Automatic update of SCSIRATE/OFFSET*/
	AHC_AUTOPAUSE	= 0x10000,	/* Automatic pause on register access */
	AHC_TARGETMODE	= 0x20000,	/* Has tested target mode support */
	AHC_MULTIROLE	= 0x40000,	/* Space for two roles at a time */
	AHC_REMOVABLE	= 0x80000,	/* Hot-Swap supported */
	AHC_AIC7770_FE	= AHC_FENONE,
	/*
	 * The real 7850 does not support Ultra modes, but there are
	 * several cards that use the generic 7850 PCI ID even though
	 * they are using an Ultra capable chip (7859/7860).  We start
	 * out with the AHC_ULTRA feature set and then check the DEVSTATUS
	 * register to determine if the capability is really present.
	 */
	AHC_AIC7850_FE	= AHC_SPIOCAP|AHC_AUTOPAUSE|AHC_TARGETMODE|AHC_ULTRA,
	AHC_AIC7860_FE	= AHC_AIC7850_FE,
	AHC_AIC7870_FE	= AHC_TARGETMODE|AHC_AUTOPAUSE,
	AHC_AIC7880_FE	= AHC_AIC7870_FE|AHC_ULTRA,
	/*
	 * Although we have space for both the initiator and
	 * target roles on ULTRA2 chips, we currently disable
	 * the initiator role to allow multi-scsi-id target mode
	 * configurations.  We can only respond on the same SCSI
	 * ID as our initiator role if we allow initiator operation.
	 * At some point, we should add a configuration knob to
	 * allow both roles to be loaded.
	 */
	AHC_AIC7890_FE	= AHC_MORE_SRAM|AHC_CMD_CHAN|AHC_ULTRA2
			  |AHC_QUEUE_REGS|AHC_SG_PRELOAD|AHC_MULTI_TID
			  |AHC_HS_MAILBOX|AHC_NEW_TERMCTL|AHC_LARGE_SCBS
			  |AHC_TARGETMODE,
	AHC_AIC7892_FE	= AHC_AIC7890_FE|AHC_DT|AHC_AUTORATE|AHC_AUTOPAUSE,
	AHC_AIC7895_FE	= AHC_AIC7880_FE|AHC_MORE_SRAM|AHC_AUTOPAUSE
			  |AHC_CMD_CHAN|AHC_MULTI_FUNC|AHC_LARGE_SCBS,
	AHC_AIC7895C_FE	= AHC_AIC7895_FE|AHC_MULTI_TID,
	AHC_AIC7896_FE	= AHC_AIC7890_FE|AHC_MULTI_FUNC,
	AHC_AIC7899_FE	= AHC_AIC7892_FE|AHC_MULTI_FUNC
} ahc_feature;

/*
 * Bugs in the silicon that we work around in software.
 */
typedef enum {
	AHC_BUGNONE		= 0x00,
	/*
	 * On all chips prior to the U2 product line,
	 * the WIDEODD S/G segment feature does not
	 * work during scsi->HostBus transfers.
	 */
	AHC_TMODE_WIDEODD_BUG	= 0x01,
	/*
	 * On the aic7890/91 Rev 0 chips, the autoflush
	 * feature does not work.  A manual flush of
	 * the DMA FIFO is required.
	 */
	AHC_AUTOFLUSH_BUG	= 0x02,
	/*
	 * On many chips, cacheline streaming does not work.
	 */
	AHC_CACHETHEN_BUG	= 0x04,
	/*
	 * On the aic7896/97 chips, cacheline
	 * streaming must be enabled.
	 */
	AHC_CACHETHEN_DIS_BUG	= 0x08,
	/*
	 * PCI 2.1 Retry failure on non-empty data fifo.
	 */
	AHC_PCI_2_1_RETRY_BUG	= 0x10,
	/*
	 * Controller does not handle cacheline residuals
	 * properly on S/G segments if PCI MWI instructions
	 * are allowed.
	 */
	AHC_PCI_MWI_BUG		= 0x20,
	/*
	 * An SCB upload using the SCB channel's
	 * auto array entry copy feature may
	 * corrupt data.  This appears to only
	 * occur on 66MHz systems.
	 */
	AHC_SCBCHAN_UPLOAD_BUG	= 0x40
} ahc_bug;

/*
 * Configuration specific settings.
 * The driver determines these settings by probing the
 * chip/controller's configuration.
 */
typedef enum {
	AHC_FNONE	      = 0x000,
	AHC_PRIMARY_CHANNEL   = 0x003,  /*
					 * The channel that should
					 * be probed first.
					 */
	AHC_USEDEFAULTS	      = 0x004,  /*
					 * For cards without an seeprom
					 * or a BIOS to initialize the chip's
					 * SRAM, we use the default target
					 * settings.
					 */
	AHC_SEQUENCER_DEBUG   = 0x008,
	AHC_SHARED_SRAM	      = 0x010,
	AHC_LARGE_SEEPROM     = 0x020,  /* Uses C56_66 not C46 */
	AHC_RESET_BUS_A	      = 0x040,
	AHC_RESET_BUS_B	      = 0x080,
	AHC_EXTENDED_TRANS_A  = 0x100,
	AHC_EXTENDED_TRANS_B  = 0x200,
	AHC_TERM_ENB_A	      = 0x400,
	AHC_TERM_ENB_B	      = 0x800,
	AHC_INITIATORROLE     = 0x1000,  /*
					  * Allow initiator operations on
					  * this controller.
					  */
	AHC_TARGETROLE	      = 0x2000,  /*
					  * Allow target operations on this
					  * controller.
					  */
	AHC_NEWEEPROM_FMT     = 0x4000,
	AHC_RESOURCE_SHORTAGE = 0x8000,
	AHC_TQINFIFO_BLOCKED  = 0x10000,  /* Blocked waiting for ATIOs */
	AHC_INT50_SPEEDFLEX   = 0x20000,  /*
					   * Internal 50pin connector
					   * sits behind an aic3860
					   */
	AHC_SCB_BTT	      = 0x40000,  /*
					   * The busy targets table is
					   * stored in SCB space rather
					   * than SRAM.
					   */
	AHC_BIOS_ENABLED      = 0x80000,
	AHC_ALL_INTERRUPTS    = 0x100000,
	AHC_PAGESCBS	      = 0x400000,  /* Enable SCB paging */
	AHC_EDGE_INTERRUPT    = 0x800000,  /* Device uses edge triggered ints */
	AHC_39BIT_ADDRESSING  = 0x1000000, /* Use 39 bit addressing scheme. */
	AHC_LSCBS_ENABLED     = 0x2000000, /* 64Byte SCBs enabled */
	AHC_SCB_CONFIG_USED   = 0x4000000, /* No SEEPROM but SCB2 had info. */
	AHC_NO_BIOS_INIT      = 0x8000000, /* No BIOS left over settings. */
	AHC_DISABLE_PCI_PERR  = 0x10000000,
	AHC_HAS_TERM_LOGIC    = 0x20000000,
	AHC_SHUTDOWN_RECOVERY = 0x40000000 /* Terminate recovery thread. */
} ahc_flag;

/************************* Hardware  SCB Definition ***************************/

/*
 * The driver keeps up to MAX_SCB scb structures per card in memory.  The SCB
 * consists of a "hardware SCB" mirroring the fields available on the card
 * and additional information the kernel stores for each transaction.
 *
 * To minimize space utilization, a portion of the hardware scb stores
 * different data during different portions of a SCSI transaction.
 * As initialized by the host driver for the initiator role, this area
 * contains the SCSI cdb (or a pointer to the  cdb) to be executed.  After
 * the cdb has been presented to the target, this area serves to store
 * residual transfer information and the SCSI status byte.
 * For the target role, the contents of this area do not change, but
 * still serve a different purpose than for the initiator role.  See
 * struct target_data for details.
 */

/*
 * Status information embedded in the shared portion of
 * an SCB after passing the cdb to the target.  The kernel
 * driver will only read this data for transactions that
 * complete abnormally (non-zero status byte).
 */
struct status_pkt {
	uint32_t residual_datacnt;	/* Residual in the current S/G seg */
	uint32_t residual_sg_ptr;	/* The next S/G for this transfer */
	uint8_t	 scsi_status;		/* Standard SCSI status byte */
};

/*
 * Target mode version of the shared data SCB segment.
 */
struct target_data {
	uint32_t residual_datacnt;	/* Residual in the current S/G seg */
	uint32_t residual_sg_ptr;	/* The next S/G for this transfer */
	uint8_t  scsi_status;		/* SCSI status to give to initiator */
	uint8_t  target_phases;		/* Bitmap of phases to execute */
	uint8_t  data_phase;		/* Data-In or Data-Out */
	uint8_t  initiator_tag;		/* Initiator's transaction tag */
};

struct hardware_scb {
/*0*/	union {
		/*
		 * If the cdb is 12 bytes or less, we embed it directly
		 * in the SCB.  For longer cdbs, we embed the address
		 * of the cdb payload as seen by the chip and a DMA
		 * is used to pull it in.
		 */
		uint8_t	 cdb[12];
		uint32_t cdb_ptr;
		struct	 status_pkt status;
		struct	 target_data tdata;
	} shared_data;
/*
 * A word about residuals.
 * The scb is presented to the sequencer with the dataptr and datacnt
 * fields initialized to the contents of the first S/G element to
 * transfer.  The sgptr field is initialized to the bus address for
 * the S/G element that follows the first in the in core S/G array
 * or'ed with the SG_FULL_RESID flag.  Sgptr may point to an invalid
 * S/G entry for this transfer (single S/G element transfer with the
 * first elements address and length preloaded in the dataptr/datacnt
 * fields).  If no transfer is to occur, sgptr is set to SG_LIST_NULL.
 * The SG_FULL_RESID flag ensures that the residual will be correctly
 * noted even if no data transfers occur.  Once the data phase is entered,
 * the residual sgptr and datacnt are loaded from the sgptr and the
 * datacnt fields.  After each S/G element's dataptr and length are
 * loaded into the hardware, the residual sgptr is advanced.  After
 * each S/G element is expired, its datacnt field is checked to see
 * if the LAST_SEG flag is set.  If so, SG_LIST_NULL is set in the
 * residual sg ptr and the transfer is considered complete.  If the
 * sequencer determines that there is a residual in the transfer, it
 * will set the SG_RESID_VALID flag in sgptr and DMA the scb back into
 * host memory.  To summarize:
 *
 * Sequencer:
 *	o A residual has occurred if SG_FULL_RESID is set in sgptr,
 *	  or residual_sgptr does not have SG_LIST_NULL set.
 *
 *	o We are transferring the last segment if residual_datacnt has
 *	  the SG_LAST_SEG flag set.
 *
 * Host:
 *	o A residual has occurred if a completed scb has the
 *	  SG_RESID_VALID flag set.
 *
 *	o residual_sgptr and sgptr refer to the "next" sg entry
 *	  and so may point beyond the last valid sg entry for the
 *	  transfer.
 */
/*12*/	uint32_t dataptr;
/*16*/	uint32_t datacnt;		/*
					 * Byte 3 (numbered from 0) of
					 * the datacnt is really the
					 * 4th byte in that data address.
					 */
/*20*/	uint32_t sgptr;
#define SG_PTR_MASK	0xFFFFFFF8
/*24*/	uint8_t  control;	/* See SCB_CONTROL in aic7xxx.reg for details */
/*25*/	uint8_t  scsiid;	/* what to load in the SCSIID register */
/*26*/	uint8_t  lun;
/*27*/	uint8_t  tag;			/*
					 * Index into our kernel SCB array.
					 * Also used as the tag for tagged I/O
					 */
/*28*/	uint8_t  cdb_len;
/*29*/	uint8_t  scsirate;		/* Value for SCSIRATE register */
/*30*/	uint8_t  scsioffset;		/* Value for SCSIOFFSET register */
/*31*/	uint8_t  next;			/*
					 * Used for threading SCBs in the
					 * "Waiting for Selection" and
					 * "Disconnected SCB" lists down
					 * in the sequencer.
					 */
/*32*/	uint8_t  cdb32[32];		/*
					 * CDB storage for cdbs of size
					 * 13->32.  We store them here
					 * because hardware scbs are
					 * allocated from DMA safe
					 * memory so we are guaranteed
					 * the controller can access
					 * this data.
					 */
};

/************************ Kernel SCB Definitions ******************************/
/*
 * Some fields of the SCB are OS dependent.  Here we collect the
 * definitions for elements that all OS platforms need to include
 * in there SCB definition.
 */

/*
 * Definition of a scatter/gather element as transferred to the controller.
 * The aic7xxx chips only support a 24bit length.  We use the top byte of
 * the length to store additional address bits and a flag to indicate
 * that a given segment terminates the transfer.  This gives us an
 * addressable range of 512GB on machines with 64bit PCI or with chips
 * that can support dual address cycles on 32bit PCI busses.
 */
struct ahc_dma_seg {
	uint32_t	addr;
	uint32_t	len;
#define	AHC_DMA_LAST_SEG	0x80000000
#define	AHC_SG_HIGH_ADDR_MASK	0x7F000000
#define	AHC_SG_LEN_MASK		0x00FFFFFF
};

struct sg_map_node {
	bus_dmamap_t		 sg_dmamap;
	bus_addr_t		 sg_physaddr;
	bus_dma_segment_t	 sg_dmasegs;
	int			 sg_nseg;
	struct ahc_dma_seg*	 sg_vaddr;
	SLIST_ENTRY(sg_map_node) links;
};

struct ahc_pci_busdata {
	pci_chipset_tag_t pc;
	pcitag_t tag;
	u_int dev;
	u_int func;
	pcireg_t class;
};

/*
 * The current state of this SCB.
 */
typedef enum {
	SCB_FLAG_NONE		= 0x0000,
	SCB_OTHERTCL_TIMEOUT	= 0x0002,/*
					  * Another device was active
					  * during the first timeout for
					  * this SCB so we gave ourselves
					  * an additional timeout period
					  * in case it was hogging the
					  * bus.
				          */
	SCB_DEVICE_RESET	= 0x0004,
	SCB_SENSE		= 0x0008,
	SCB_CDB32_PTR		= 0x0010,
	SCB_AUTO_NEGOTIATE	= 0x0040,/* Negotiate to achieve goal. */
	SCB_NEGOTIATE		= 0x0080,/* Negotiation forced for command. */
	SCB_ABORT		= 0x0100,
	SCB_UNTAGGEDQ		= 0x0200,
	SCB_ACTIVE		= 0x0400,
	SCB_TARGET_IMMEDIATE	= 0x0800,
	SCB_TRANSMISSION_ERROR	= 0x1000,/*
					  * We detected a parity or CRC
					  * error that has effected the
					  * payload of the command.  This
					  * flag is checked when normal
					  * status is returned to catch
					  * the case of a target not
					  * responding to our attempt
					  * to report the error.
					  */
	SCB_TARGET_SCB		= 0x2000,
	SCB_SILENT		= 0x4000 /*
					  * Be quiet about transmission type
					  * errors.  They are expected and we
					  * don't want to upset the user.  This
					  * flag is typically used during DV.
					  */
} scb_flag;

struct scb {
	struct	hardware_scb	 *hscb;
	union {
		SLIST_ENTRY(scb)  sle;
		TAILQ_ENTRY(scb)  tqe;
	} links;
	LIST_ENTRY(scb)		  pending_links;

	struct scsipi_xfer	 *xs;
	struct ahc_softc	 *ahc_softc;
	scb_flag		  flags;
#ifndef __linux__
	bus_dmamap_t		  dmamap;
#endif
	struct scb_platform_data *platform_data;
	struct sg_map_node	 *sg_map;
	struct ahc_dma_seg	 *sg_list;
	bus_addr_t		  sg_list_phys;
	u_int			  sg_count;/* How full ahc_dma_seg is */
};

struct scb_data {
	SLIST_HEAD(, scb) free_scbs;	/*
					 * Pool of SCBs ready to be assigned
					 * commands to execute.
					 */
	struct	scb *scbindex[256];	/*
					 * Mapping from tag to SCB.
					 * As tag identifiers are an
					 * 8bit value, we provide space
					 * for all possible tag values.
					 * Any lookups to entries at or
					 * above AHC_SCB_MAX_ALLOC will
					 * always fail.
					 */
	struct	hardware_scb	*hscbs;	/* Array of hardware SCBs */
	struct	scb *scbarray;		/* Array of kernel SCBs */
	struct	scsipi_sense_data *sense; /* Per SCB sense data */

	/*
	 * "Bus" addresses of our data structures.
	 */
	bus_dmamap_t	 hscb_dmamap;
	bus_addr_t	 hscb_busaddr;
	bus_dma_segment_t hscb_seg;
	int		  hscb_nseg;
	int		  hscb_size;

	bus_dmamap_t	 sense_dmamap;
	bus_addr_t	 sense_busaddr;
	bus_dma_segment_t sense_seg;
	int		  sense_nseg;
	int		  sense_size;

	SLIST_HEAD(, sg_map_node) sg_maps;
	uint8_t	numscbs;
	uint8_t	maxhscbs;		/* Number of SCBs on the card */
	uint8_t	init_level;		/*
					 * How far we've initialized
					 * this structure.
					 */
};

/************************ Target Mode Definitions *****************************/

/*
 * Connection desciptor for select-in requests in target mode.
 */
struct target_cmd {
	uint8_t scsiid;		/* Our ID and the initiator's ID */
	uint8_t identify;	/* Identify message */
	uint8_t bytes[22];	/*
				 * Bytes contains any additional message
				 * bytes terminated by 0xFF.  The remainder
				 * is the cdb to execute.
				 */
	uint8_t cmd_valid;	/*
				 * When a command is complete, the firmware
				 * will set cmd_valid to all bits set.
				 * After the host has seen the command,
				 * the bits are cleared.  This allows us
				 * to just peek at host memory to determine
				 * if more work is complete. cmd_valid is on
				 * an 8 byte boundary to simplify setting
				 * it on aic7880 hardware which only has
				 * limited direct access to the DMA FIFO.
				 */
	uint8_t pad[7];
};

/*
 * Number of events we can buffer up if we run out
 * of immediate notify ccbs.
 */
#define AHC_TMODE_EVENT_BUFFER_SIZE 8
struct ahc_tmode_event {
	uint8_t initiator_id;
	uint8_t event_type;	/* MSG type or EVENT_TYPE_BUS_RESET */
#define	EVENT_TYPE_BUS_RESET 0xFF
	uint8_t event_arg;
};

/*
 * Per enabled lun target mode state.
 * As this state is directly influenced by the host OS'es target mode
 * environment, we let the OS module define it.  Forward declare the
 * structure here so we can store arrays of them, etc. in OS neutral
 * data structures.
 */
#ifdef AHC_TARGET_MODE
struct ahc_tmode_lstate {
#if 0
	struct cam_path *path;
	struct ccb_hdr_slist accept_tios;
	struct ccb_hdr_slist immed_notifies;
#endif
	struct ahc_tmode_event event_buffer[AHC_TMODE_EVENT_BUFFER_SIZE];
	uint8_t event_r_idx;
	uint8_t event_w_idx;
};
#else
struct ahc_tmode_lstate;
#endif

/******************** Transfer Negotiation Datastructures *********************/
#define AHC_TRANS_CUR		0x01	/* Modify current negotiation status */
#define AHC_TRANS_ACTIVE	0x03	/* Assume this target is on the bus */
#define AHC_TRANS_GOAL		0x04	/* Modify negotiation goal */
#define AHC_TRANS_USER		0x08	/* Modify user negotiation settings */

#define AHC_WIDTH_UNKNOWN	0xFF
#define AHC_PERIOD_UNKNOWN	0xFF
#define AHC_OFFSET_UNKNOWN	0xFF
#define AHC_PPR_OPTS_UNKNOWN	0xFF

/*
 * Transfer Negotiation Information.
 */
struct ahc_transinfo {
	uint8_t protocol_version;	/* SCSI Revision level */
	uint8_t transport_version;	/* SPI Revision level */
	uint8_t width;			/* Bus width */
	uint8_t period;			/* Sync rate factor */
	uint8_t offset;			/* Sync offset */
	uint8_t ppr_options;		/* Parallel Protocol Request options */
};

/*
 * Per-initiator current, goal and user transfer negotiation information. */
struct ahc_initiator_tinfo {
	uint8_t scsirate;		/* Computed value for SCSIRATE reg */
	struct ahc_transinfo curr;
	struct ahc_transinfo goal;
	struct ahc_transinfo user;
};

/*
 * Per enabled target ID state.
 * Pointers to lun target state as well as sync/wide negotiation information
 * for each initiator<->target mapping.  For the initiator role we pretend
 * that we are the target and the targets are the initiators since the
 * negotiation is the same regardless of role.
 */
struct ahc_tmode_tstate {
	struct ahc_tmode_lstate*	enabled_luns[AHC_NUM_LUNS];
	struct ahc_initiator_tinfo	transinfo[AHC_NUM_TARGETS];

	/*
	 * Per initiator state bitmasks.
	 */
	uint16_t	 auto_negotiate;/* Auto Negotiation Required */
	uint16_t	 ultraenb;	/* Using ultra sync rate  */
	uint16_t	 discenable;	/* Disconnection allowed  */
	uint16_t	 tagenable;	/* Tagged Queuing allowed */
};

/*
 * Data structure for our table of allowed synchronous transfer rates.
 */
struct ahc_syncrate {
	u_int sxfr_u2;	/* Value of the SXFR parameter for Ultra2+ Chips */
	u_int sxfr;	/* Value of the SXFR parameter for <= Ultra Chips */
#define		ULTRA_SXFR 0x100	/* Rate Requires Ultra Mode set */
#define		ST_SXFR	   0x010	/* Rate Single Transition Only */
#define		DT_SXFR	   0x040	/* Rate Double Transition Only */
	uint8_t period; /* Period to send to SCSI target */
	char *rate;
};

/* Safe and valid period for async negotiations. */
#define	AHC_ASYNC_XFER_PERIOD 0x45
#define	AHC_ULTRA2_XFER_PERIOD 0x0a

/*
 * Indexes into our table of syncronous transfer rates.
 */
#define AHC_SYNCRATE_DT		0
#define AHC_SYNCRATE_ULTRA2	1
#define AHC_SYNCRATE_ULTRA	3
#define AHC_SYNCRATE_FAST	6
#define AHC_SYNCRATE_MAX	AHC_SYNCRATE_DT
#define	AHC_SYNCRATE_MIN	13

/***************************** Lookup Tables **********************************/
/*
 * Phase -> name and message out response
 * to parity errors in each phase table.
 */
struct ahc_phase_table_entry {
        uint8_t phase;
        uint8_t mesg_out; /* Message response to parity errors */
	char *phasemsg;
};

/************************** Serial EEPROM Format ******************************/

struct seeprom_config {
/*
 * Per SCSI ID Configuration Flags
 */
	uint16_t device_flags[16];	/* words 0-15 */
#define		CFXFER		0x0007	/* synchronous transfer rate */
#define		CFSYNCH		0x0008	/* enable synchronous transfer */
#define		CFDISC		0x0010	/* enable disconnection */
#define		CFWIDEB		0x0020	/* wide bus device */
#define		CFSYNCHISULTRA	0x0040	/* CFSYNCH is an ultra offset (2940AU)*/
#define		CFSYNCSINGLE	0x0080	/* Single-Transition signalling */
#define		CFSTART		0x0100	/* send start unit SCSI command */
#define		CFINCBIOS	0x0200	/* include in BIOS scan */
#define		CFRNFOUND	0x0400	/* report even if not found */
#define		CFMULTILUNDEV	0x0800	/* Probe multiple luns in BIOS scan */
#define		CFWBCACHEENB	0x4000	/* Enable W-Behind Cache on disks */
#define		CFWBCACHENOP	0xc000	/* Don't touch W-Behind Cache */

/*
 * BIOS Control Bits
 */
	uint16_t bios_control;		/* word 16 */
#define		CFSUPREM	0x0001	/* support all removable drives */
#define		CFSUPREMB	0x0002	/* support removable boot drives */
#define		CFBIOSEN	0x0004	/* BIOS enabled */
#define		CFBIOS_BUSSCAN	0x0008	/* Have the BIOS Scan the Bus */
#define		CFSM2DRV	0x0010	/* support more than two drives */
#define		CFSTPWLEVEL	0x0010	/* Termination level control */
#define		CF284XEXTEND	0x0020	/* extended translation (284x cards) */
#define		CFCTRL_A	0x0020	/* BIOS displays Ctrl-A message */
#define		CFTERM_MENU	0x0040	/* BIOS displays termination menu */
#define		CFEXTEND	0x0080	/* extended translation enabled */
#define		CFSCAMEN	0x0100	/* SCAM enable */
#define		CFMSG_LEVEL	0x0600	/* BIOS Message Level */
#define			CFMSG_VERBOSE	0x0000
#define			CFMSG_SILENT	0x0200
#define			CFMSG_DIAG	0x0400
#define		CFBOOTCD	0x0800  /* Support Bootable CD-ROM */
/*		UNUSED		0xff00	*/

/*
 * Host Adapter Control Bits
 */
	uint16_t adapter_control;	/* word 17 */
#define		CFAUTOTERM	0x0001	/* Perform Auto termination */
#define		CFULTRAEN	0x0002	/* Ultra SCSI speed enable */
#define		CF284XSELTO     0x0003	/* Selection timeout (284x cards) */
#define		CF284XFIFO      0x000C	/* FIFO Threshold (284x cards) */
#define		CFSTERM		0x0004	/* SCSI low byte termination */
#define		CFWSTERM	0x0008	/* SCSI high byte termination */
#define		CFSPARITY	0x0010	/* SCSI parity */
#define		CF284XSTERM     0x0020	/* SCSI low byte term (284x cards) */
#define		CFMULTILUN	0x0020
#define		CFRESETB	0x0040	/* reset SCSI bus at boot */
#define		CFCLUSTERENB	0x0080	/* Cluster Enable */
#define		CFBOOTCHAN	0x0300	/* probe this channel first */
#define		CFBOOTCHANSHIFT 8
#define		CFSEAUTOTERM	0x0400	/* Ultra2 Perform secondary Auto Term*/
#define		CFSELOWTERM	0x0800	/* Ultra2 secondary low term */
#define		CFSEHIGHTERM	0x1000	/* Ultra2 secondary high term */
#define		CFENABLEDV	0x4000	/* Perform Domain Validation*/

/*
 * Bus Release Time, Host Adapter ID
 */
	uint16_t brtime_id;		/* word 18 */
#define		CFSCSIID	0x000f	/* host adapter SCSI ID */
/*		UNUSED		0x00f0	*/
#define		CFBRTIME	0xff00	/* bus release time */

/*
 * Maximum targets
 */
	uint16_t max_targets;		/* word 19 */
#define		CFMAXTARG	0x00ff	/* maximum targets */
#define		CFBOOTLUN	0x0f00	/* Lun to boot from */
#define		CFBOOTID	0xf000	/* Target to boot from */
	uint16_t res_1[10];		/* words 20-29 */
	uint16_t signature;		/* Signature == 0x250 */
#define		CFSIGNATURE	0x250
#define		CFSIGNATURE2	0x300
	uint16_t checksum;		/* word 31 */
};

/****************************  Message Buffer *********************************/
typedef enum {
	MSG_TYPE_NONE			= 0x00,
	MSG_TYPE_INITIATOR_MSGOUT	= 0x01,
	MSG_TYPE_INITIATOR_MSGIN	= 0x02,
	MSG_TYPE_TARGET_MSGOUT		= 0x03,
	MSG_TYPE_TARGET_MSGIN		= 0x04
} ahc_msg_type;

typedef enum {
	MSGLOOP_IN_PROG,
	MSGLOOP_MSGCOMPLETE,
	MSGLOOP_TERMINATED
} msg_loop_stat;

/*********************** Software Configuration Structure *********************/
TAILQ_HEAD(scb_tailq, scb);

struct ahc_aic7770_softc {
	/*
	 * Saved register state used for chip_init().
	 */
	uint8_t busspd;
	uint8_t bustime;
};

struct ahc_pci_softc {
	/*
	 * Saved register state used for chip_init().
	 */
	uint32_t  devconfig;
	uint16_t  targcrccnt;
	uint8_t   command;
	uint8_t   csize_lattime;
	uint8_t   optionmode;
	uint8_t   crccontrol1;
	uint8_t   dscommand0;
	uint8_t   dspcistatus;
	uint8_t   scbbaddr;
	uint8_t   dff_thrsh;
};

union ahc_bus_softc {
	struct ahc_aic7770_softc aic7770_softc;
	struct ahc_pci_softc pci_softc;
};

typedef void (*ahc_bus_intr_t)(struct ahc_softc *);
typedef int (*ahc_bus_chip_init_t)(struct ahc_softc *);
typedef void ahc_callback_t (void *);

struct ahc_softc {
	struct device		  sc_dev;

	struct scsipi_channel	  sc_channel;
	struct scsipi_channel	  sc_channel_b;
	struct device *		  sc_child;
	struct device *		  sc_child_b;
	struct scsipi_adapter	  sc_adapter;

	bus_space_tag_t           tag;
	bus_space_handle_t        bsh;

#ifndef __linux__
	bus_dma_tag_t		  buffer_dmat;   /* dmat for buffer I/O */
#endif
	struct scb_data		 *scb_data;

	struct scb		 *next_queued_scb;

	/*
	 * SCBs that have been sent to the controller
	 */
	LIST_HEAD(, scb)	  pending_scbs;

	/*
	 * Counting lock for deferring the release of additional
	 * untagged transactions from the untagged_queues.  When
	 * the lock is decremented to 0, all queues in the
	 * untagged_queues array are run.
	 */
	u_int			  untagged_queue_lock;

	/*
	 * Per-target queue of untagged-transactions.  The
	 * transaction at the head of the queue is the
	 * currently pending untagged transaction for the
	 * target.  The driver only allows a single untagged
	 * transaction per target.
	 */
	struct scb_tailq	  untagged_queues[AHC_NUM_TARGETS];

	/*
	 * Bus attachment specific data.
	 */
	union ahc_bus_softc	  bus_softc;

	/*
	 * Platform specific data.
	 */
	struct ahc_platform_data *platform_data;

	/*
	 * Platform specific device information.
	 */
	ahc_dev_softc_t		  dev_softc;

	/*
	 * Bus specific device information.
	 */
	ahc_bus_intr_t		  bus_intr;

	/*
	 * Bus specific initialization required
	 * after a chip reset.
	 */
	ahc_bus_chip_init_t	  bus_chip_init;

	/*
	 * Target mode related state kept on a per enabled lun basis.
	 * Targets that are not enabled will have null entries.
	 * As an initiator, we keep one target entry for our initiator
	 * ID to store our sync/wide transfer settings.
	 */
	struct ahc_tmode_tstate  *enabled_targets[AHC_NUM_TARGETS];

	char inited_target[AHC_NUM_TARGETS];

	/*
	 * The black hole device responsible for handling requests for
	 * disabled luns on enabled targets.
	 */
	struct ahc_tmode_lstate  *black_hole;

	/*
	 * Device instance currently on the bus awaiting a continue TIO
	 * for a command that was not given the disconnect privilege.
	 */
	struct ahc_tmode_lstate  *pending_device;

	/*
	 * Card characteristics
	 */
	ahc_chip		  chip;
	ahc_feature		  features;
	ahc_bug			  bugs;
	ahc_flag		  flags;
	struct seeprom_config	 *seep_config;

	/* Values to store in the SEQCTL register for pause and unpause */
	uint8_t			  unpause;
	uint8_t			  pause;

	/* Command Queues */
	uint8_t			  qoutfifonext;
	uint8_t			  qinfifonext;
	uint8_t			 *qoutfifo;
	uint8_t			 *qinfifo;

	/* Critical Section Data */
	struct cs		 *critical_sections;
	u_int			  num_critical_sections;

	/* Links for chaining softcs */
	TAILQ_ENTRY(ahc_softc)	  links;

	/* Channel Names ('A', 'B', etc.) */
	char			  channel;
	char			  channel_b;

	/* Initiator Bus ID */
	uint8_t			  our_id;
	uint8_t			  our_id_b;

	/*
	 * PCI error detection.
	 */
	int			  unsolicited_ints;

	/*
	 * Target incoming command FIFO.
	 */
	struct target_cmd	 *targetcmds;
	uint8_t			  tqinfifonext;

	/*
	 * Cached copy of the sequencer control register.
	 */
	uint8_t			  seqctl;

	/*
	 * Incoming and outgoing message handling.
	 */
	uint8_t			  send_msg_perror;
	ahc_msg_type		  msg_type;
	uint8_t			  msgout_buf[12];/* Message we are sending */
	uint8_t			  msgin_buf[12];/* Message we are receiving */
	u_int			  msgout_len;	/* Length of message to send */
	u_int			  msgout_index;	/* Current index in msgout */
	u_int			  msgin_index;	/* Current index in msgin */

	/* Interrupt routine */
	void			 *ih;

	/*
	 * Mapping information for data structures shared
	 * between the sequencer and kernel.
	 */
	bus_dma_tag_t		  parent_dmat;
	bus_dmamap_t		  shared_data_dmamap;
	bus_addr_t		  shared_data_busaddr;

	bus_dma_segment_t	  shared_data_seg;
	int			  shared_data_nseg;
	int			  shared_data_size;
	int			  sc_dmaflags;

	/*
	 * Bus address of the one byte buffer used to
	 * work-around a DMA bug for chips <= aic7880
	 * in target mode.
	 */
	bus_addr_t		  dma_bug_buf;

	/* Number of enabled target mode device on this card */
	u_int			  enabled_luns;

	/* Initialization level of this data structure */
	u_int			  init_level;

	/* PCI cacheline size. */
	u_int			  pci_cachesize;

	/*
	 * Count of parity errors we have seen as a target.
	 * We auto-disable parity error checking after seeing
	 * AHC_PCI_TARGET_PERR_THRESH number of errors.
	 */
	u_int			  pci_target_perr_count;
#define		AHC_PCI_TARGET_PERR_THRESH	10

	/* Maximum number of sequencer instructions supported. */
	u_int			  instruction_ram_size;

	/* Per-Unit descriptive information */
	char			 *name;
	int			  unit;

	/* Selection Timer settings */
	int			  seltime;
	int			  seltime_b;

	uint16_t		  user_discenable;/* Disconnection allowed  */
	uint16_t		  user_tagenable;/* Tagged Queuing allowed */

	struct ahc_pci_busdata	  *bd;
};

TAILQ_HEAD(ahc_softc_tailq, ahc_softc);
extern struct ahc_softc_tailq ahc_tailq;

/************************ Active Device Information ***************************/
typedef enum {
	ROLE_UNKNOWN,
	ROLE_INITIATOR,
	ROLE_TARGET
} role_t;

struct ahc_devinfo {
	int	 our_scsiid;
	int	 target_offset;
	uint16_t target_mask;
	u_int	 target;
	u_int	 lun;
	char	 channel;
	role_t	 role;		/*
				 * Only guaranteed to be correct if not
				 * in the busfree state.
				 */
};

/****************************** PCI Structures ********************************/
typedef int (ahc_device_setup_t)(struct ahc_softc *);

struct ahc_pci_identity {
	uint64_t		 full_id;
	uint64_t		 id_mask;
	ahc_device_setup_t	*setup;
};
extern struct ahc_pci_identity ahc_pci_ident_table[];

/***************************** VL/EISA Declarations ***************************/
struct aic7770_identity {
	uint32_t		 full_id;
	uint32_t		 id_mask;
	const char		*name;
	ahc_device_setup_t	*setup;
};
extern struct aic7770_identity aic7770_ident_table[];
extern const int ahc_num_aic7770_devs;

#define AHC_EISA_SLOT_OFFSET	0xc00
#define AHC_EISA_IOSIZE		0x100

/*************************** Function Declarations ****************************/
/******************************************************************************/
u_int			ahc_index_busy_tcl(struct ahc_softc *, u_int);
void			ahc_unbusy_tcl(struct ahc_softc *, u_int);
void			ahc_busy_tcl(struct ahc_softc *, u_int, u_int);

/***************************** PCI Front End *********************************/
const struct ahc_pci_identity	*ahc_find_pci_device(pcireg_t, pcireg_t, u_int);
int			 ahc_pci_config(struct ahc_softc *,
			    struct ahc_pci_identity *);
int			 ahc_pci_test_register_access(struct ahc_softc *);

/*************************** EISA/VL Front End ********************************/
struct aic7770_identity *aic7770_find_device(uint32_t);
int			 aic7770_config(struct ahc_softc *,
			    struct aic7770_identity *, u_int);

/************************** SCB and SCB queue management **********************/
int		ahc_probe_scbs(struct ahc_softc *);
void		ahc_run_untagged_queues(struct ahc_softc *ahc);
void		ahc_run_untagged_queue(struct ahc_softc *ahc,
				       struct scb_tailq *queue);
void		ahc_qinfifo_requeue_tail(struct ahc_softc *ahc,
					 struct scb *scb);
int		ahc_match_scb(struct ahc_softc *ahc, struct scb *scb,
			      int target, char channel, int lun,
			      u_int tag, role_t role);

/****************************** Initialization ********************************/
int			 ahc_softc_init(struct ahc_softc *);
#ifndef DEBUG
void			 ahc_controller_info(struct ahc_softc *, char *, size_t);
#endif
int			 ahc_chip_init(struct ahc_softc *ahc);
int			 ahc_init(struct ahc_softc *ahc);
void			 ahc_intr_enable(struct ahc_softc *ahc, int enable);
void			 ahc_softc_insert(struct ahc_softc *);
void			 ahc_set_unit(struct ahc_softc *, int);
void			 ahc_set_name(struct ahc_softc *, char *);
void			 ahc_alloc_scbs(struct ahc_softc *ahc);
void			 ahc_free(struct ahc_softc *ahc);
int			 ahc_reset(struct ahc_softc *ahc, int reinit);
void			 ahc_shutdown(void *arg);

/*************************** Interrupt Services *******************************/
void			ahc_pci_intr(struct ahc_softc *);
void			ahc_clear_intstat(struct ahc_softc *);
void			ahc_run_qoutfifo(struct ahc_softc *);
#ifdef AHC_TARGET_MODE
void			ahc_run_tqinfifo(struct ahc_softc *ahc, int paused);
#endif
void			ahc_handle_brkadrint(struct ahc_softc *ahc);
void			ahc_handle_seqint(struct ahc_softc *ahc, u_int intstat);
void			ahc_handle_scsiint(struct ahc_softc *ahc,
					   u_int intstat);
void			ahc_clear_critical_section(struct ahc_softc *ahc);

/***************************** Error Recovery *********************************/
typedef enum {
	SEARCH_COMPLETE,
	SEARCH_COUNT,
	SEARCH_REMOVE
} ahc_search_action;
int			ahc_search_qinfifo(struct ahc_softc *, int, char,
			    int, u_int, role_t, uint32_t, ahc_search_action);
int			ahc_search_untagged_queues(struct ahc_softc *,
			    struct scsipi_xfer *, int, char, int, uint32_t,
			    ahc_search_action);
int			ahc_search_disc_list(struct ahc_softc *, int, char,
			    int, u_int, int, int, int);
void			ahc_freeze_devq(struct ahc_softc *, struct scb *);
int			ahc_reset_channel(struct ahc_softc *, char, int);
int			ahc_abort_scbs(struct ahc_softc *, int, char, int,
			    u_int, role_t, uint32_t);
void			ahc_restart(struct ahc_softc *);
void			ahc_calc_residual(struct ahc_softc *, struct scb *);
/*************************** Utility Functions ********************************/
struct ahc_phase_table_entry*
			ahc_lookup_phase_entry(int phase);
void			ahc_compile_devinfo(struct ahc_devinfo *devinfo,
					    u_int our_id, u_int target,
					    u_int lun, char channel,
					    role_t role);
/************************** Transfer Negotiation ******************************/
struct ahc_syncrate*	ahc_find_syncrate(struct ahc_softc *ahc, u_int *period,
					  u_int *ppr_options, u_int maxsync);
u_int			ahc_find_period(struct ahc_softc *ahc,
					u_int scsirate, u_int maxsync);
void			ahc_validate_offset(struct ahc_softc *ahc,
					    struct ahc_initiator_tinfo *tinfo,
					    struct ahc_syncrate *syncrate,
					    u_int *offset, int wide,
					    role_t role);
void			ahc_validate_width(struct ahc_softc *ahc,
					   struct ahc_initiator_tinfo *tinfo,
					   u_int *bus_width,
					   role_t role);
/*
 * Negotiation types.  These are used to qualify if we should renegotiate
 * even if our goal and current transport parameters are identical.
 */
typedef enum {
	AHC_NEG_TO_GOAL,	/* Renegotiate only if goal and curr differ. */
	AHC_NEG_IF_NON_ASYNC,	/* Renegotiate so long as goal is non-async. */
	AHC_NEG_ALWAYS		/* Renegotiate even if goal is async. */
} ahc_neg_type;
int			ahc_update_neg_request(struct ahc_softc *,
			    struct ahc_devinfo *, struct ahc_tmode_tstate *,
			    struct ahc_initiator_tinfo*, ahc_neg_type);
void			ahc_set_width(struct ahc_softc *, struct ahc_devinfo *,
			    u_int, u_int, int);
void			ahc_set_syncrate(struct ahc_softc *,
			    struct ahc_devinfo *, struct ahc_syncrate *,
			    u_int, u_int, u_int, u_int, int);
void			ahc_scb_devinfo(struct ahc_softc *,
					struct ahc_devinfo *, struct scb *);

typedef enum {
	AHC_QUEUE_NONE,
	AHC_QUEUE_BASIC,
	AHC_QUEUE_TAGGED
} ahc_queue_alg;

void			ahc_set_tags(struct ahc_softc *ahc,
				     struct ahc_devinfo *devinfo,
				     ahc_queue_alg alg);

/**************************** Target Mode *************************************/
#ifdef AHC_TARGET_MODE
void		ahc_send_lstate_events(struct ahc_softc *,
		    struct ahc_tmode_lstate *);
void		ahc_handle_en_lun(struct ahc_softc *, struct scsipi_xfer *);
cam_status	ahc_find_tmode_devs(struct ahc_softc *,
		    struct ahc_tmode_tstate **, struct ahc_tmode_lstate **,
		    int);
#ifndef AHC_TMODE_ENABLE
#define AHC_TMODE_ENABLE 0
#endif
#endif
/******************************* Debug ***************************************/
#ifdef AHC_DEBUG
extern uint32_t ahc_debug;
#define	AHC_SHOW_MISC		0x0001
#define	AHC_SHOW_SENSE		0x0002
#define AHC_DUMP_SEEPROM	0x0004
#define AHC_SHOW_TERMCTL	0x0008
#define AHC_SHOW_MEMORY		0x0010
#define AHC_SHOW_MESSAGES	0x0020
#define	AHC_SHOW_DV		0x0040
#define AHC_SHOW_SELTO		0x0080
#define AHC_SHOW_QFULL		0x0200
#define AHC_SHOW_QUEUE		0x0400
#define AHC_SHOW_TQIN		0x0800
#define AHC_SHOW_MASKED_ERRORS	0x1000
#define AHC_DEBUG_SEQUENCER	0x2000
#endif
void			ahc_print_scb(struct scb *scb);
void			ahc_print_devinfo(struct ahc_softc *ahc,
					  struct ahc_devinfo *dev);
void			ahc_dump_card_state(struct ahc_softc *ahc);
int			ahc_print_register(ahc_reg_parse_entry_t *table,
					   u_int num_entries,
					   const char *name,
					   u_int address,
					   u_int value,
					   u_int *cur_column,
					   u_int wrap_point);
/******************************* SEEPROM *************************************/
int		ahc_acquire_seeprom(struct ahc_softc *ahc,
				    struct seeprom_descriptor *sd);
void		ahc_release_seeprom(struct seeprom_descriptor *sd);

void		ahc_check_extport(struct ahc_softc *, u_int *);
#endif /* _AIC7XXXVAR_H_ */


code:
/*	$OpenBSD: am7930.c,v 1.6 2015/05/11 06:46:21 ratchov Exp $	*/
/*	$NetBSD: am7930.c,v 1.44 2001/11/13 13:14:34 lukem Exp $	*/

/*
 * Copyright (c) 1995 Rolf Grossmann
 * 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.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *      This product includes software developed by Rolf Grossmann.
 * 4. 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 AUTHOR ``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 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.
 */

/*
 * Front-end attachment independent layer for AMD 79c30
 * audio driver.  No ISDN support.
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/errno.h>
#include <sys/ioctl.h>
#include <sys/device.h>
#include <sys/proc.h>

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

#include <dev/ic/am7930reg.h>
#include <dev/ic/am7930var.h>

#ifdef AUDIO_DEBUG
int	am7930debug = 0;
#define	DPRINTF(x)	if (am7930debug) printf x
#else
#define	DPRINTF(x)
#endif

/* The following tables stolen from former (4.4Lite's) sys/sparc/bsd_audio.c */

/*
 * gx, gr & stg gains.  this table must contain 256 elements with
 * the 0th being "infinity" (the magic value 9008).  The remaining
 * elements match sun's gain curve (but with higher resolution):
 * -18 to 0dB in .16dB steps then 0 to 12dB in .08dB steps.
 */
static const uint16_t gx_coeff[256] = {
	0x9008, 0x8e7c, 0x8e51, 0x8e45, 0x8d42, 0x8d3b, 0x8c36, 0x8c33,
	0x8b32, 0x8b2a, 0x8b2b, 0x8b2c, 0x8b25, 0x8b23, 0x8b22, 0x8b22,
	0x9122, 0x8b1a, 0x8aa3, 0x8aa3, 0x8b1c, 0x8aa6, 0x912d, 0x912b,
	0x8aab, 0x8b12, 0x8aaa, 0x8ab2, 0x9132, 0x8ab4, 0x913c, 0x8abb,
	0x9142, 0x9144, 0x9151, 0x8ad5, 0x8aeb, 0x8a79, 0x8a5a, 0x8a4a,
	0x8b03, 0x91c2, 0x91bb, 0x8a3f, 0x8a33, 0x91b2, 0x9212, 0x9213,
	0x8a2c, 0x921d, 0x8a23, 0x921a, 0x9222, 0x9223, 0x922d, 0x9231,
	0x9234, 0x9242, 0x925b, 0x92dd, 0x92c1, 0x92b3, 0x92ab, 0x92a4,
	0x92a2, 0x932b, 0x9341, 0x93d3, 0x93b2, 0x93a2, 0x943c, 0x94b2,
	0x953a, 0x9653, 0x9782, 0x9e21, 0x9d23, 0x9cd2, 0x9c23, 0x9baa,
	0x9bde, 0x9b33, 0x9b22, 0x9b1d, 0x9ab2, 0xa142, 0xa1e5, 0x9a3b,
	0xa213, 0xa1a2, 0xa231, 0xa2eb, 0xa313, 0xa334, 0xa421, 0xa54b,
	0xada4, 0xac23, 0xab3b, 0xaaab, 0xaa5c, 0xb1a3, 0xb2ca, 0xb3bd,
	0xbe24, 0xbb2b, 0xba33, 0xc32b, 0xcb5a, 0xd2a2, 0xe31d, 0x0808,
	0x72ba, 0x62c2, 0x5c32, 0x52db, 0x513e, 0x4cce, 0x43b2, 0x4243,
	0x41b4, 0x3b12, 0x3bc3, 0x3df2, 0x34bd, 0x3334, 0x32c2, 0x3224,
	0x31aa, 0x2a7b, 0x2aaa, 0x2b23, 0x2bba, 0x2c42, 0x2e23, 0x25bb,
	0x242b, 0x240f, 0x231a, 0x22bb, 0x2241, 0x2223, 0x221f, 0x1a33,
	0x1a4a, 0x1acd, 0x2132, 0x1b1b, 0x1b2c, 0x1b62, 0x1c12, 0x1c32,
	0x1d1b, 0x1e71, 0x16b1, 0x1522, 0x1434, 0x1412, 0x1352, 0x1323,
	0x1315, 0x12bc, 0x127a, 0x1235, 0x1226, 0x11a2, 0x1216, 0x0a2a,
	0x11bc, 0x11d1, 0x1163, 0x0ac2, 0x0ab2, 0x0aab, 0x0b1b, 0x0b23,
	0x0b33, 0x0c0f, 0x0bb3, 0x0c1b, 0x0c3e, 0x0cb1, 0x0d4c, 0x0ec1,
	0x079a, 0x0614, 0x0521, 0x047c, 0x0422, 0x03b1, 0x03e3, 0x0333,
	0x0322, 0x031c, 0x02aa, 0x02ba, 0x02f2, 0x0242, 0x0232, 0x0227,
	0x0222, 0x021b, 0x01ad, 0x0212, 0x01b2, 0x01bb, 0x01cb, 0x01f6,
	0x0152, 0x013a, 0x0133, 0x0131, 0x012c, 0x0123, 0x0122, 0x00a2,
	0x011b, 0x011e, 0x0114, 0x00b1, 0x00aa, 0x00b3, 0x00bd, 0x00ba,
	0x00c5, 0x00d3, 0x00f3, 0x0062, 0x0051, 0x0042, 0x003b, 0x0033,
	0x0032, 0x002a, 0x002c, 0x0025, 0x0023, 0x0022, 0x001a, 0x0021,
	0x001b, 0x001b, 0x001d, 0x0015, 0x0013, 0x0013, 0x0012, 0x0012,
	0x000a, 0x000a, 0x0011, 0x0011, 0x000b, 0x000b, 0x000c, 0x000e,
};

/*
 * second stage play gain.
 */
static const uint16_t ger_coeff[] = {
	0x431f, /* 5. dB */
	0x331f, /* 5.5 dB */
	0x40dd, /* 6. dB */
	0x11dd, /* 6.5 dB */
	0x440f, /* 7. dB */
	0x411f, /* 7.5 dB */
	0x311f, /* 8. dB */
	0x5520, /* 8.5 dB */
	0x10dd, /* 9. dB */
	0x4211, /* 9.5 dB */
	0x410f, /* 10. dB */
	0x111f, /* 10.5 dB */
	0x600b, /* 11. dB */
	0x00dd, /* 11.5 dB */
	0x4210, /* 12. dB */
	0x110f, /* 13. dB */
	0x7200, /* 14. dB */
	0x2110, /* 15. dB */
	0x2200, /* 15.9 dB */
	0x000b, /* 16.9 dB */
	0x000f  /* 18. dB */
#define NGER (sizeof(ger_coeff) / sizeof(ger_coeff[0]))
};

/*
 * Reset chip and set boot-time softc defaults.
 */
void
am7930_init(struct am7930_softc *sc, int flag)
{
	DPRINTF(("am7930_init()\n"));

	/* set boot defaults */
	sc->sc_rlevel = 128;
	sc->sc_plevel = 128;
	sc->sc_mlevel = 0;
	sc->sc_out_port = AUDIOAMD_SPEAKER_VOL;
	sc->sc_mic_mute = 0;

	/* disable sample interrupts */
	AM7930_IWRITE(sc, AM7930_IREG_MUX_MCR4, 0);

	/* initialise voice and data, and disable interrupts */
	AM7930_IWRITE(sc, AM7930_IREG_INIT,
	    AM7930_INIT_PMS_ACTIVE | AM7930_INIT_INT_DISABLE);

	if (flag == AUDIOAMD_DMA_MODE) {
		/* configure PP for serial (SBP) mode */
		AM7930_IWRITE(sc, AM7930_IREG_PP_PPCR1, AM7930_PPCR1_SBP);

		/*
		 * Initialise the MUX unit - route the MAP to the PP
		 */
		AM7930_IWRITE(sc, AM7930_IREG_MUX_MCR1,
		    (AM7930_MCRCHAN_BA << 4) | AM7930_MCRCHAN_BD);
		AM7930_IWRITE(sc, AM7930_IREG_MUX_MCR2, AM7930_MCRCHAN_NC);
		AM7930_IWRITE(sc, AM7930_IREG_MUX_MCR3, AM7930_MCRCHAN_NC);
	} else {
		/*
		 * Initialize the MUX unit.  We use MCR3 to route the MAP
		 * through channel Bb.  MCR1 and MCR2 are unused.
		 * Setting the INT enable bit in MCR4 will generate an
		 * interrupt on each converted audio sample.
		 */
		AM7930_IWRITE(sc, AM7930_IREG_MUX_MCR1, 0);
		AM7930_IWRITE(sc, AM7930_IREG_MUX_MCR2, 0);
		AM7930_IWRITE(sc, AM7930_IREG_MUX_MCR3,
		    (AM7930_MCRCHAN_BB << 4) | AM7930_MCRCHAN_BA);
		AM7930_IWRITE(sc, AM7930_IREG_MUX_MCR4,
		    AM7930_MCR4_INT_ENABLE);
	}
}

int
am7930_open(void *addr, int flags)
{
	struct am7930_softc *sc = addr;

	DPRINTF(("sa_open: unit %p\n", sc));
	if (sc->sc_open)
		return EBUSY;
	sc->sc_open = 1;
	sc->sc_locked = 0;

	sc->sc_glue->onopen(sc);
	DPRINTF(("saopen: ok -> sc=%p\n",sc));
	return 0;
}

void
am7930_close(void *addr)
{
	struct am7930_softc *sc = addr;

	DPRINTF(("sa_close: sc=%p\n", sc));
	sc->sc_glue->onclose(sc);
	sc->sc_open = 0;
	DPRINTF(("sa_close: closed.\n"));
}

int
am7930_set_params(void *addr, int setmode, int usemode,
    struct audio_params *play, struct audio_params *rec)
{
	struct am7930_softc *sc = addr;
	struct audio_params *p;
	int mode;

	for (mode = AUMODE_RECORD; mode != -1;
	    mode = mode == AUMODE_RECORD ? AUMODE_PLAY : -1) {
		if ((setmode & mode) == 0)
			continue;

		p = mode == AUMODE_PLAY ? play : rec;
		if (p == NULL)
			continue;

		p->encoding = AUDIO_ENCODING_ULAW;
		p->precision = sc->sc_glue->precision;
		p->bps = AUDIO_BPS(p->precision);
		p->msb = 0;
		p->channels = 1;
		/* no other rates supported by amd chip */
		p->sample_rate = 8000;
	}

	return 0;
}

int
am7930_query_encoding(void *addr, struct audio_encoding *fp)
{
	struct am7930_softc *sc = addr;

	switch (fp->index) {
	case 0:
		strlcpy(fp->name, AudioEmulaw, sizeof fp->name);
		fp->encoding = AUDIO_ENCODING_ULAW;
		fp->precision = sc->sc_glue->precision;
		fp->bps = AUDIO_BPS(fp->precision);
		fp->msb = 0;
		fp->flags = 0;
		break;
	default:
		return EINVAL;
		/*NOTREACHED*/
	}
	return 0;
}

int
am7930_round_blocksize(void *addr, int blk)
{
	return blk;
}

int
am7930_commit_settings(void *addr)
{
	struct am7930_softc *sc = addr;
	uint16_t ger, gr, gx, stgr;
	uint8_t mmr2, mmr3;
	int level;

	DPRINTF(("sa_commit.\n"));
	gx = gx_coeff[sc->sc_rlevel];
	stgr = gx_coeff[sc->sc_mlevel];

	level = (sc->sc_plevel * (256 + NGER)) >> 8;
	if (level >= 256) {
		ger = ger_coeff[level - 256];
		gr = gx_coeff[255];
	} else {
		ger = ger_coeff[0];
		gr = gx_coeff[level];
	}

	/* XXX: this is called before DMA is setup, useful ? */
	mtx_enter(&audio_lock);

	mmr2 = AM7930_IREAD(sc, AM7930_IREG_MAP_MMR2);
	if (sc->sc_out_port == AUDIOAMD_SPEAKER_VOL)
		mmr2 |= AM7930_MMR2_LS;
	else
		mmr2 &= ~AM7930_MMR2_LS;
	AM7930_IWRITE(sc, AM7930_IREG_MAP_MMR2, mmr2);

	mmr3 = AM7930_IREAD(sc, AM7930_IREG_MAP_MMR3);
	if (sc->sc_mic_mute)
		mmr3 |= AM7930_MMR3_MUTE;
	else
		mmr3 &= ~AM7930_MMR3_MUTE;
	AM7930_IWRITE(sc, AM7930_IREG_MAP_MMR3, mmr3);

	AM7930_IWRITE(sc, AM7930_IREG_MAP_MMR1,
	    AM7930_MMR1_GX | AM7930_MMR1_GER |
	    AM7930_MMR1_GR | AM7930_MMR1_STG);

	AM7930_IWRITE16(sc, AM7930_IREG_MAP_GX, gx);
	AM7930_IWRITE16(sc, AM7930_IREG_MAP_STG, stgr);
	AM7930_IWRITE16(sc, AM7930_IREG_MAP_GR, gr);
	AM7930_IWRITE16(sc, AM7930_IREG_MAP_GER, ger);

	mtx_leave(&audio_lock);

	return 0;
}

int
am7930_halt_output(void *addr)
{
	struct am7930_softc *sc = addr;

	/* XXX only halt, if input is also halted ?? */
	AM7930_IWRITE(sc, AM7930_IREG_INIT,
	    AM7930_INIT_PMS_ACTIVE | AM7930_INIT_INT_DISABLE);
	sc->sc_locked = 0;
	return 0;
}

int
am7930_halt_input(void *addr)
{
	struct am7930_softc *sc = addr;

	/* XXX only halt, if output is also halted ?? */
	AM7930_IWRITE(sc, AM7930_IREG_INIT,
	    AM7930_INIT_PMS_ACTIVE | AM7930_INIT_INT_DISABLE);
	sc->sc_locked = 0;
	return 0;
}

/*
 * XXX chip is full-duplex, but really attach-dependent.
 * For now we know of no half-duplex attachments.
 */
int
am7930_get_props(void *addr)
{
	return AUDIO_PROP_FULLDUPLEX;
}

/*
 * Attach-dependent channel set/query
 */
int
am7930_set_port(void *addr, mixer_ctrl_t *cp)
{
	struct am7930_softc *sc = addr;

	DPRINTF(("am7930_set_port: port=%d", cp->dev));
	if (cp->dev == AUDIOAMD_RECORD_SOURCE ||
	    cp->dev == AUDIOAMD_MONITOR_OUTPUT ||
	    cp->dev == AUDIOAMD_MIC_MUTE) {
		if (cp->type != AUDIO_MIXER_ENUM)
			return EINVAL;
	} else if (cp->type != AUDIO_MIXER_VALUE ||
	    cp->un.value.num_channels != 1) {
		return EINVAL;
	}

	switch(cp->dev) {
	case AUDIOAMD_MIC_VOL:
		sc->sc_rlevel = cp->un.value.level[AUDIO_MIXER_LEVEL_MONO];
		break;
	case AUDIOAMD_SPEAKER_VOL:
	case AUDIOAMD_HEADPHONES_VOL:
		sc->sc_plevel = cp->un.value.level[AUDIO_MIXER_LEVEL_MONO];
		break;
	case AUDIOAMD_MONITOR_VOL:
		sc->sc_mlevel = cp->un.value.level[AUDIO_MIXER_LEVEL_MONO];
		break;
	case AUDIOAMD_RECORD_SOURCE:
		if (cp->un.ord != AUDIOAMD_MIC_VOL)
			return EINVAL;
		break;
	case AUDIOAMD_MIC_MUTE:
		sc->sc_mic_mute = cp->un.ord;
		break;
	case AUDIOAMD_MONITOR_OUTPUT:
		if (cp->un.ord != AUDIOAMD_SPEAKER_VOL &&
		    cp->un.ord != AUDIOAMD_HEADPHONES_VOL)
			return EINVAL;
		sc->sc_out_port = cp->un.ord;
		break;
	default:
		return EINVAL;
		/* NOTREACHED */
	}
	return 0;
}

int
am7930_get_port(void *addr, mixer_ctrl_t *cp)
{
	struct am7930_softc *sc = addr;

	DPRINTF(("am7930_get_port: port=%d\n", cp->dev));
	if (cp->dev == AUDIOAMD_RECORD_SOURCE ||
	    cp->dev == AUDIOAMD_MONITOR_OUTPUT ||
	    cp->dev == AUDIOAMD_MIC_MUTE) {
		if (cp->type != AUDIO_MIXER_ENUM)
			return EINVAL;
	} else if (cp->type != AUDIO_MIXER_VALUE ||
	    cp->un.value.num_channels != 1) {
		return EINVAL;
	}

	switch(cp->dev) {
	case AUDIOAMD_MIC_VOL:
		cp->un.value.level[AUDIO_MIXER_LEVEL_MONO] = sc->sc_rlevel;
		break;
	case AUDIOAMD_SPEAKER_VOL:
	case AUDIOAMD_HEADPHONES_VOL:
		cp->un.value.level[AUDIO_MIXER_LEVEL_MONO] = sc->sc_plevel;
		break;
	case AUDIOAMD_MONITOR_VOL:
		cp->un.value.level[AUDIO_MIXER_LEVEL_MONO] = sc->sc_mlevel;
		break;
	case AUDIOAMD_RECORD_SOURCE:
		cp->un.ord = AUDIOAMD_MIC_VOL;
		break;
	case AUDIOAMD_MIC_MUTE:
		cp->un.ord = sc->sc_mic_mute;
		break;
	case AUDIOAMD_MONITOR_OUTPUT:
		cp->un.ord = sc->sc_out_port;
		break;
	default:
		return EINVAL;
		/* NOTREACHED */
	}
	return 0;
}

/*
 * Define mixer control facilities.
 */
int
am7930_query_devinfo(void *addr, mixer_devinfo_t *dip)
{
	DPRINTF(("am7930_query_devinfo()\n"));

	switch(dip->index) {
	case AUDIOAMD_MIC_VOL:
		dip->type = AUDIO_MIXER_VALUE;
		dip->mixer_class = AUDIOAMD_INPUT_CLASS;
		dip->prev =  AUDIO_MIXER_LAST;
		dip->next = AUDIOAMD_MIC_MUTE;
		strlcpy(dip->label.name, AudioNmicrophone,
		    sizeof dip->label.name);
		dip->un.v.num_channels = 1;
		strlcpy(dip->un.v.units.name, AudioNvolume,
		    sizeof dip->un.v.units.name);
		break;
	case AUDIOAMD_SPEAKER_VOL:
		dip->type = AUDIO_MIXER_VALUE;
		dip->mixer_class = AUDIOAMD_OUTPUT_CLASS;
		dip->prev = dip->next = AUDIO_MIXER_LAST;
		strlcpy(dip->label.name, AudioNspeaker,
		    sizeof dip->label.name);
		dip->un.v.num_channels = 1;
		strlcpy(dip->un.v.units.name, AudioNvolume,
		    sizeof dip->un.v.units.name);
		break;
	case AUDIOAMD_HEADPHONES_VOL:
		dip->type = AUDIO_MIXER_VALUE;
		dip->mixer_class = AUDIOAMD_OUTPUT_CLASS;
		dip->prev = dip->next = AUDIO_MIXER_LAST;
		strlcpy(dip->label.name, AudioNheadphone,
		    sizeof dip->label.name);
		dip->un.v.num_channels = 1;
		strlcpy(dip->un.v.units.name, AudioNvolume,
		    sizeof dip->un.v.units.name);
		break;
	case AUDIOAMD_MONITOR_VOL:
		dip->type = AUDIO_MIXER_VALUE;
		dip->mixer_class = AUDIOAMD_MONITOR_CLASS;
		dip->prev = dip->next = AUDIO_MIXER_LAST;
		strlcpy(dip->label.name, AudioNmonitor,
		    sizeof dip->label.name);
		dip->un.v.num_channels = 1;
		strlcpy(dip->un.v.units.name, AudioNvolume,
		    sizeof dip->un.v.units.name);
		break;
	case AUDIOAMD_RECORD_SOURCE:
		dip->type = AUDIO_MIXER_ENUM;
		dip->mixer_class = AUDIOAMD_RECORD_CLASS;
		dip->prev = dip->next = AUDIO_MIXER_LAST;
		strlcpy(dip->label.name, AudioNsource,
		    sizeof dip->label.name);
		dip->un.e.num_mem = 1;
		strlcpy(dip->un.e.member[0].label.name, AudioNmicrophone,
		    sizeof dip->un.e.member[0].label.name);
		dip->un.e.member[0].ord = AUDIOAMD_MIC_VOL;
		break;
	case AUDIOAMD_MONITOR_OUTPUT:
		dip->type = AUDIO_MIXER_ENUM;
		dip->mixer_class = AUDIOAMD_MONITOR_CLASS;
		dip->prev = dip->next = AUDIO_MIXER_LAST;
		strlcpy(dip->label.name, AudioNoutput,
		    sizeof dip->label.name);
		dip->un.e.num_mem = 2;
		strlcpy(dip->un.e.member[0].label.name, AudioNspeaker,
		    sizeof dip->un.e.member[0].label.name);
		dip->un.e.member[0].ord = AUDIOAMD_SPEAKER_VOL;
		strlcpy(dip->un.e.member[1].label.name, AudioNheadphone,
		    sizeof dip->un.e.member[1].label.name);
		dip->un.e.member[1].ord = AUDIOAMD_HEADPHONES_VOL;
		break;
	case AUDIOAMD_MIC_MUTE:
		dip->type = AUDIO_MIXER_ENUM;
		dip->mixer_class = AUDIOAMD_INPUT_CLASS;
		dip->prev =  AUDIOAMD_MIC_VOL;
		dip->next = AUDIO_MIXER_LAST;
		strlcpy(dip->label.name, AudioNmute,
		    sizeof dip->label.name);
		dip->un.e.num_mem = 2;
		strlcpy(dip->un.e.member[0].label.name, AudioNoff,
		    sizeof dip->un.e.member[0].label.name);
		dip->un.e.member[0].ord = 0;
		strlcpy(dip->un.e.member[1].label.name, AudioNon,
		    sizeof dip->un.e.member[1].label.name);
		dip->un.e.member[1].ord = 1;
		break;
	case AUDIOAMD_INPUT_CLASS:
		dip->type = AUDIO_MIXER_CLASS;
		dip->mixer_class = AUDIOAMD_INPUT_CLASS;
		dip->prev = dip->next = AUDIO_MIXER_LAST;
		strlcpy(dip->label.name, AudioCinputs,
		    sizeof dip->label.name);
		break;
	case AUDIOAMD_OUTPUT_CLASS:
		dip->type = AUDIO_MIXER_CLASS;
		dip->mixer_class = AUDIOAMD_OUTPUT_CLASS;
		dip->prev = dip->next = AUDIO_MIXER_LAST;
		strlcpy(dip->label.name, AudioCoutputs,
		    sizeof dip->label.name);
		break;
	case AUDIOAMD_RECORD_CLASS:
		dip->type = AUDIO_MIXER_CLASS;
		dip->mixer_class = AUDIOAMD_RECORD_CLASS;
		dip->prev = dip->next = AUDIO_MIXER_LAST;
		strlcpy(dip->label.name, AudioCrecord,
		    sizeof dip->label.name);
		break;
	case AUDIOAMD_MONITOR_CLASS:
		dip->type = AUDIO_MIXER_CLASS;
		dip->mixer_class = AUDIOAMD_MONITOR_CLASS;
		dip->prev = dip->next = AUDIO_MIXER_LAST;
		strlcpy(dip->label.name, AudioCmonitor,
		    sizeof dip->label.name);
		break;
	default:
		return ENXIO;
		/*NOTREACHED*/
	}

	DPRINTF(("AUDIO_MIXER_DEVINFO: name=%s\n", dip->label.name));

	return 0;
}

license: unknown


code:
/*	$OpenBSD: am7930reg.h,v 1.6 2011/09/03 20:03:29 miod Exp $	*/
/* $NetBSD: am7930reg.h,v 1.7 2005/12/11 12:21:25 christos Exp $ */

/*
 * Copyright (c) 1992, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This software was developed by the Computer Systems Engineering group
 * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
 * contributed to Berkeley.
 *
 * All advertising materials mentioning features or use of this software
 * must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Lawrence Berkeley Laboratory.
 *
 * 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. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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.
 *
 *	@(#)bsd_audioreg.h	8.1 (Berkeley) 6/11/93
 */

/*
 * Am79C30A direct registers
 */

#define AM7930_DREG_CR		0	/* command register (wo) */
#define AM7930_DREG_IR		0	/* interrupt register (ro) */
#define		AM7930_IR_DTTHRSH	0x01	/* D-channel TX empty */
#define		AM7930_IR_DRTHRSH	0x02	/* D-channel RX avail */
#define		AM7930_IR_DSRI		0x04	/* D-channel packet status */
#define		AM7930_IR_DERI		0x08	/* D-channel error */
#define		AM7930_IR_BBUFF		0x10	/* Bb or Bc byte avail/empty */
#define		AM7930_IR_LSRI		0x20	/* LIU status */
#define		AM7930_IR_DSR2I		0x40	/* D-channel buffer status */
#define		AM7930_IR_PPMF		0x80	/* Multiframe or PP */
#define AM7930_DREG_DR		1	/* data register (rw) */
#define AM7930_DREG_DSR1	2	/* D-channel status register 1 (ro) */
#define AM7930_DREG_DER		3	/* D-channel error register (ro) */
#define AM7930_DREG_DCTB	4	/* D-channel transmit register (wo) */
#define AM7930_DREG_DCRB	4	/* D-channel receive register (ro) */
#define AM7930_DREG_BBTB	5	/* Bb-channel transmit register (wo) */
#define AM7930_DREG_BBRB	5	/* Bb-channel receive register (ro) */
#define AM7930_DREG_BCTB	6	/* Bc-channel transmit register (wo) */
#define AM7930_DREG_BCRB	6	/* Bc-channel receive register (ro) */
#define AM7930_DREG_DSR2	7	/* D-channel status register 2 (ro) */

#define	AM7930_DREG_SIZE	8

/*
 * Am79C30A indirect registers
 */

/* Initialisation registers */

#define AM7930_IREG_INIT	0x21
#define AM7930_IREG_INIT2	0x20
/* power mode selection */
#define		AM7930_INIT_PMS_IDLE		0x00
#define		AM7930_INIT_PMS_ACTIVE		0x01
#define		AM7930_INIT_PMS_ACTIVE_DATA	0x02
#define		AM7930_INIT_PMS_MASK		0x03
/* interrupt selection */
#define		AM7930_INIT_INT_ENABLE		0x00
#define		AM7930_INIT_INT_DISABLE		0x04
#define		AM7930_INIT_INT_MASK		0x04
/* clock divider selection */
#define		AM7930_INIT_CDS_DIV2		0x00
#define		AM7930_INIT_CDS_DIV1		0x08
#define		AM7930_INIT_CDS_DIV4		0x10
#define		AM7930_INIT_CDS_DIV3		0x20
#define		AM7930_INIT_CDS_MASK		0x38
/* abort selection */
#define		AM7930_INIT_AS_RX		0x40
#define		AM7930_INIT_AS_NRX		0x00
#define		AM7930_INIT_AS_TX		0x80
#define		AM7930_INIT_AS_NTX		0x00
#define		AM7930_INIT_AS_MASK		0xc0

/* Line Interface Unit registers */

#define AM7930_IREG_LIU_LSR	0xa1	/* LIU status (ro) */
#define AM7930_IREG_LIU_LPR	0xa2	/* LIU priority (rw) */
#define AM7930_IREG_LIU_LMR1	0xa3	/* LIU mode register 1 (rw) */
#define AM7930_IREG_LIU_LMR2	0xa4	/* LIU mode register 2 (rw) */
#define AM7930_IREG_LIU_2_4	0xa5
#define AM7930_IREG_LIU_MF	0xa6	/* Multiframe (rw) */
#define AM7930_IREG_LIU_MFSB	0xa7	/* Multiframe S-bit/status (ro) */
#define AM7930_IREG_LIU_MFQB	0xa8	/* Multiframe Q-bit buffer (wo) */

/* Multiplexer registers */

#define AM7930_IREG_MUX_MCR1	0x41	/* MUX command register 1 (rw) */
#define AM7930_IREG_MUX_MCR2	0x42	/* MUX command register 2 (rw) */
#define AM7930_IREG_MUX_MCR3	0x43	/* MUX command register 3 (rw) */
#define		AM7930_MCRCHAN_NC		0x00
#define		AM7930_MCRCHAN_B1		0x01
#define		AM7930_MCRCHAN_B2		0x02
#define		AM7930_MCRCHAN_BA		0x03
#define		AM7930_MCRCHAN_BB		0x04
#define		AM7930_MCRCHAN_BC		0x05
#define		AM7930_MCRCHAN_BD		0x06
#define		AM7930_MCRCHAN_BE		0x07
#define		AM7930_MCRCHAN_BF		0x08
#define AM7930_IREG_MUX_MCR4	0x44	/* MUX command register 4 (rw) */
#define		AM7930_MCR4_INT_ENABLE		(1 << 3)
#define		AM7930_MCR4_SWAPBB		(1 << 4)
#define		AM7930_MCR4_SWAPBC		(1 << 5)
#define AM7930_IREG_MUX_1_4	0x45

/* Main Audio Processor registers */

#define AM7930_IREG_MAP_X	0x61	/* X filter coefficient (rw) */
#define AM7930_IREG_MAP_R	0x62	/* R filter coefficient (rw) */
#define AM7930_IREG_MAP_GX	0x63	/* GX gain coefficient (rw) */
#define AM7930_IREG_MAP_GR	0x64	/* GR gain coefficient (rw) */
#define AM7930_IREG_MAP_GER	0x65	/* GER gain coefficient (rw) */
#define AM7930_IREG_MAP_STG	0x66	/* Sidetone gain coefficient (rw) */
#define AM7930_IREG_MAP_FTGR	0x67	/* Frequency tone generator 1,2 (rw) */
#define AM7930_IREG_MAP_ATGR	0x68	/* Amplitude tone generator 1,2 (rw) */
#define AM7930_IREG_MAP_MMR1	0x69	/* MAP mode register 1 (rw) */
#define		AM7930_MMR1_ALAW	0x01
#define		AM7930_MMR1_GX		0x02
#define		AM7930_MMR1_GR		0x04
#define		AM7930_MMR1_GER		0x08
#define		AM7930_MMR1_X		0x10
#define		AM7930_MMR1_R		0x20
#define		AM7930_MMR1_STG		0x40
#define		AM7930_MMR1_LOOP	0x80
#define AM7930_IREG_MAP_MMR2	0x6a	/* MAP mode register 2 (rw) */
#define		AM7930_MMR2_AINB	0x01
#define		AM7930_MMR2_LS		0x02
#define		AM7930_MMR2_DTMF	0x04
#define		AM7930_MMR2_GEN		0x08
#define		AM7930_MMR2_RNG		0x10
#define		AM7930_MMR2_DIS_HPF	0x20
#define		AM7930_MMR2_DIS_AZ	0x40
#define AM7930_IREG_MAP_1_10	0x6b
#define AM7930_IREG_MAP_MMR3	0x6c	/* MAP mode register 3 (rw) */
#define		AM7930_MMR3_BOTH	0x02
#define		AM7930_MMR3_MBZ		0x01
#define		AM7930_MMR3_GA		0x70
#define		AM7930_MMR3_GA0		0x00
#define		AM7930_MMR3_GA6		0x10
#define		AM7930_MMR3_GA12	0x20
#define		AM7930_MMR3_GA18	0x30
#define		AM7930_MMR3_GA24	0x40
#define		AM7930_MMR3_MUTE	0x08
#define		AM7930_MMR3_STR		0x01
#define AM7930_IREG_MAP_STRA	0x6d	/* Second tone ringer amplitude (rw) */
#define AM7930_IREG_MAP_STRF	0x6e	/* Second tone ringer frequency (rw) */

/* Data Link Controller registers */

#define AM7930_IREG_DLC_FRAR123	0x81	/* First rcvd byte address 123 (rw) */
#define AM7930_IREG_DLC_SRAR123 0x82	/* Second rcvd byte address 123 (rw) */
#define AM7930_IREG_DLC_TAR	0x83	/* Transmit address (rw) */
#define AM7930_IREG_DLC_DRLR	0x84	/* D-channel receive byte limit (rw) */
#define AM7930_IREG_DLC_DTCR	0x85	/* D-channel transmit byte count (rw)*/
#define AM7930_IREG_DLC_DMR1	0x86	/* D-channel mode register 1 (rw) */
#define AM7930_IREG_DLC_DMR2	0x87	/* D-channel mode register 2 (rw) */
#define AM7930_IREG_DLC_1_7	0x88
#define AM7930_IREG_DLC_DRCR	0x89	/* D-channel receive byte count (ro) */
#define AM7930_IREG_DLC_RNGR1	0x8a	/* Random number generator LSB (rw) */
#define AM7930_IREG_DLC_RNGR2	0x8b	/* Random number generator MSB (rw) */
#define AM7930_IREG_DLC_FRAR4	0x8c	/* First rcvd byte address 4 (rw) */
#define AM7930_IREG_DLC_SRAR4	0x8d	/* Second rcvd byte address 4 (rw) */
#define AM7930_IREG_DLC_DMR3	0x8e	/* D-channel mode register 3 (rw) */
#define AM7930_IREG_DLC_DMR4	0x8f	/* D-channel mode register 4 (rw) */
#define AM7930_IREG_DLC_12_15	0x90
#define AM7930_IREG_DLC_ASR	0x91	/* Address status register (ro) */
#define AM7930_IREG_DLC_EFCR	0x92	/* Extended FIFO control (rw) */

/* Peripheral Port registers */

#define AM7930_IREG_PP_PPCR1	0xc0	/* Peripheral port control 1 (rw) */
#define		AM7930_PPCR1_DISABLE	0x00
#define		AM7930_PPCR1_SBP	0x01
#define		AM7930_PPCR1_IOM2SL	0x10
#define		AM7930_PPCR1_IOM2MA	0x11
#define AM7930_IREG_PP_PPSR	0xc1	/* Peripheral port control 2 (ro) */
#define AM7930_IREG_PP_PPIER	0xc2	/* Peripheral port intr enable (rw) */
#define AM7930_IREG_PP_MTDR	0xc3	/* monitor transmit data (wo) */
#define AM7930_IREG_PP_MRDR	0xc3	/* monitor receive data (ro) */
#define AM7930_IREG_PP_CITDR0	0xc4	/* C/I transmit data register 0 (wo) */
#define AM7930_IREG_PP_CIRDR0	0xc4	/* C/I receive data register 0 (ro) */
#define AM7930_IREG_PP_CITDR1	0xc5	/* C/I transmit data register 1 (wo) */
#define AM7930_IREG_PP_CIRDR1	0xc5	/* C/I receive data register 1 (ro) */
#define AM7930_IREG_PP_PPCR2	0xc8	/* Peripheral port control 2 (rw) */


code:
/*	$OpenBSD: am7930var.h,v 1.3 2015/05/11 06:46:21 ratchov Exp $	*/
/*	$NetBSD: am7930var.h,v 1.10 2005/01/15 15:19:52 kent Exp $	*/

/*
 * Copyright (c) 1992, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This software was developed by the Computer Systems Engineering group
 * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
 * contributed to Berkeley.
 *
 * All advertising materials mentioning features or use of this software
 * must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Lawrence Berkeley Laboratory.
 *
 * 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. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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.
 *
 *	@(#)bsd_audiovar.h	8.1 (Berkeley) 6/11/93
 */

struct am7930_softc;

struct am7930_glue {
	uint8_t	(*codec_iread)(struct am7930_softc *sc, int);
	void	(*codec_iwrite)(struct am7930_softc *sc, int, uint8_t);
	uint16_t	(*codec_iread16)(struct am7930_softc *sc, int);
	void	(*codec_iwrite16)(struct am7930_softc *sc, int, uint16_t);
	void	(*onopen)(struct am7930_softc *sc);
	void	(*onclose)(struct am7930_softc *sc);
	int	precision;
};

struct am7930_softc {
	struct device sc_dev;	/* base device */
	int	sc_open;
	int	sc_locked;

	uint8_t	sc_rlevel;	/* record level */
	uint8_t	sc_plevel;	/* play level */
	uint8_t	sc_mlevel;	/* monitor level */
	uint8_t	sc_out_port;	/* output port */
	uint8_t	sc_mic_mute;

	struct am7930_glue *sc_glue;
};

extern int     am7930debug;

void	am7930_init(struct am7930_softc *, int);

#define AM7930_IWRITE(x,y,z)	(*(x)->sc_glue->codec_iwrite)((x),(y),(z))
#define AM7930_IREAD(x,y)	(*(x)->sc_glue->codec_iread)((x),(y))
#define AM7930_IWRITE16(x,y,z)	(*(x)->sc_glue->codec_iwrite16)((x),(y),(z))
#define AM7930_IREAD16(x,y)	(*(x)->sc_glue->codec_iread16)((x),(y))

#define AUDIOAMD_POLL_MODE	0
#define AUDIOAMD_DMA_MODE	1

/*
 * audio channel definitions.
 */

#define AUDIOAMD_SPEAKER_VOL	0	/* speaker volume */
#define AUDIOAMD_HEADPHONES_VOL	1	/* headphones volume */
#define AUDIOAMD_OUTPUT_CLASS	2

#define AUDIOAMD_MONITOR_VOL	3	/* monitor input volume */
#define AUDIOAMD_MONITOR_OUTPUT	4	/* output selector */
#define AUDIOAMD_MONITOR_CLASS	5

#define AUDIOAMD_MIC_VOL	6	/* microphone volume */
#define AUDIOAMD_MIC_MUTE	7
#define AUDIOAMD_INPUT_CLASS	8

#define AUDIOAMD_RECORD_SOURCE	9	/* source selector */
#define AUDIOAMD_RECORD_CLASS	10

/*
 * audio(9) MI callbacks from upper-level audio layer.
 */

struct audio_device;
struct audio_encoding;
struct audio_params;

int	am7930_open(void *, int);
void	am7930_close(void *);
int	am7930_query_encoding(void *, struct audio_encoding *);
int	am7930_set_params(void *, int, int, struct audio_params *,
	    struct audio_params *);
int	am7930_commit_settings(void *);
int	am7930_round_blocksize(void *, int);
int	am7930_halt_output(void *);
int	am7930_halt_input(void *);
int	am7930_getdev(void *, struct audio_device *);
int	am7930_get_props(void *);
int	am7930_set_port(void *, mixer_ctrl_t *);
int	am7930_get_port(void *, mixer_ctrl_t *);
int	am7930_query_devinfo(void *, mixer_devinfo_t *);


code:
/*	$OpenBSD: am7990.c,v 1.51 2015/05/13 10:42:46 jsg Exp $	*/
/*	$NetBSD: am7990.c,v 1.74 2012/02/02 19:43:02 tls Exp $	*/

/*-
 * Copyright (c) 1997, 1998 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Charles M. Hannum and by Jason R. Thorpe of the Numerical Aerospace
 * Simulation Facility, NASA Ames Research Center.
 *
 * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
 */

/*-
 * Copyright (c) 1992, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Ralph Campbell and Rick Macklem.
 *
 * 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. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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.
 *
 *	@(#)if_le.c	8.2 (Berkeley) 11/16/93
 */

#include "bpfilter.h"

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/mbuf.h>
#include <sys/syslog.h>
#include <sys/socket.h>
#include <sys/device.h>
#include <sys/malloc.h>
#include <sys/ioctl.h>
#include <sys/errno.h>

#include <net/if.h>
#include <net/if_media.h>

#include <netinet/in.h>
#include <netinet/if_ether.h>

#if NBPFILTER > 0
#include <net/bpf.h>
#endif

#include <dev/ic/lancereg.h>
#include <dev/ic/lancevar.h>
#include <dev/ic/am7990reg.h>
#include <dev/ic/am7990var.h>

void	am7990_meminit(struct lance_softc *);
void	am7990_start(struct ifnet *);

void	am7990_rint(struct lance_softc *);
void	am7990_tint(struct lance_softc *);

#ifdef LEDEBUG
void	am7990_recv_print(struct lance_softc *, int);
void	am7990_xmit_print(struct lance_softc *, int);
#endif

/*
 * am7990 configuration driver.  Attachments are provided by
 * machine-dependent driver front-ends.
 */
void
am7990_config(struct am7990_softc *sc)
{
	int mem, i;

	sc->lsc.sc_meminit = am7990_meminit;
	sc->lsc.sc_start = am7990_start;

	lance_config(&sc->lsc);

	mem = 0;
	sc->lsc.sc_initaddr = mem;
	mem += sizeof(struct leinit);
	sc->lsc.sc_rmdaddr = mem;
	mem += sizeof(struct lermd) * sc->lsc.sc_nrbuf;
	sc->lsc.sc_tmdaddr = mem;
	mem += sizeof(struct letmd) * sc->lsc.sc_ntbuf;
	for (i = 0; i < sc->lsc.sc_nrbuf; i++, mem += LEBLEN)
		sc->lsc.sc_rbufaddr[i] = mem;
	for (i = 0; i < sc->lsc.sc_ntbuf; i++, mem += LEBLEN)
		sc->lsc.sc_tbufaddr[i] = mem;
#ifdef notyet
	if (mem > ...)
		panic(...);
#endif
}

/*
 * Set up the initialization block and the descriptor rings.
 */
void
am7990_meminit(struct lance_softc *sc)
{
	struct ifnet *ifp = &sc->sc_arpcom.ac_if;
	u_long a;
	int bix;
	struct leinit init;
	struct lermd rmd;
	struct letmd tmd;
	uint8_t *myaddr;

	if (ifp->if_flags & IFF_PROMISC)
		init.init_mode = LE_MODE_NORMAL | LE_MODE_PROM;
	else
		init.init_mode = LE_MODE_NORMAL;
	if (sc->sc_initmodemedia == 1)
		init.init_mode |= LE_MODE_PSEL0;

	/*
	 * Update our private copy of the Ethernet address.
	 * We NEED the copy so we can ensure its alignment!
	 */
	memcpy(sc->sc_enaddr, sc->sc_arpcom.ac_enaddr, ETHER_ADDR_LEN);
	myaddr = sc->sc_enaddr;

	init.init_padr[0] = (myaddr[1] << 8) | myaddr[0];
	init.init_padr[1] = (myaddr[3] << 8) | myaddr[2];
	init.init_padr[2] = (myaddr[5] << 8) | myaddr[4];
	lance_setladrf(&sc->sc_arpcom, init.init_ladrf);

	sc->sc_last_rd = 0;
	sc->sc_first_td = sc->sc_last_td = sc->sc_no_td = 0;

	a = sc->sc_addr + LE_RMDADDR(sc, 0);
	init.init_rdra = a;
	init.init_rlen = (a >> 16) | ((ffs(sc->sc_nrbuf) - 1) << 13);

	a = sc->sc_addr + LE_TMDADDR(sc, 0);
	init.init_tdra = a;
	init.init_tlen = (a >> 16) | ((ffs(sc->sc_ntbuf) - 1) << 13);

	(*sc->sc_copytodesc)(sc, &init, LE_INITADDR(sc), sizeof(init));

	/*
	 * Set up receive ring descriptors.
	 */
	for (bix = 0; bix < sc->sc_nrbuf; bix++) {
		a = sc->sc_addr + LE_RBUFADDR(sc, bix);
		rmd.rmd0 = a;
		rmd.rmd1_hadr = a >> 16;
		rmd.rmd1_bits = LE_R1_OWN;
		rmd.rmd2 = -LEBLEN | LE_XMD2_ONES;
		rmd.rmd3 = 0;
		(*sc->sc_copytodesc)(sc, &rmd, LE_RMDADDR(sc, bix),
		    sizeof(rmd));
	}

	/*
	 * Set up transmit ring descriptors.
	 */
	for (bix = 0; bix < sc->sc_ntbuf; bix++) {
		a = sc->sc_addr + LE_TBUFADDR(sc, bix);
		tmd.tmd0 = a;
		tmd.tmd1_hadr = a >> 16;
		tmd.tmd1_bits = 0;
		tmd.tmd2 = 0 | LE_XMD2_ONES;
		tmd.tmd3 = 0;
		(*sc->sc_copytodesc)(sc, &tmd, LE_TMDADDR(sc, bix),
		    sizeof(tmd));
	}
}

void
am7990_rint(struct lance_softc *sc)
{
	struct ifnet *ifp = &sc->sc_arpcom.ac_if;
	struct mbuf *m;
	struct mbuf_list ml = MBUF_LIST_INITIALIZER();
	int bix;
	int rp;
	struct lermd rmd;

	bix = sc->sc_last_rd;

	/* Process all buffers with valid data. */
	for (;;) {
		rp = LE_RMDADDR(sc, bix);
		(*sc->sc_copyfromdesc)(sc, &rmd, rp, sizeof(rmd));

		if (rmd.rmd1_bits & LE_R1_OWN)
			break;

		if (rmd.rmd1_bits & LE_R1_ERR) {
			if (rmd.rmd1_bits & LE_R1_ENP) {
#ifdef LEDEBUG
				if ((rmd.rmd1_bits & LE_R1_OFLO) == 0) {
					if (rmd.rmd1_bits & LE_R1_FRAM)
						printf("%s: framing error\n",
						    sc->sc_dev.dv_xname);
					if (rmd.rmd1_bits & LE_R1_CRC)
						printf("%s: crc mismatch\n",
						    sc->sc_dev.dv_xname);
				}
#endif
			} else {
				if (rmd.rmd1_bits & LE_R1_OFLO)
					printf("%s: overflow\n",
					    sc->sc_dev.dv_xname);
			}
			if (rmd.rmd1_bits & LE_R1_BUFF)
				printf("%s: receive buffer error\n",
				    sc->sc_dev.dv_xname);
			ifp->if_ierrors++;
		} else if ((rmd.rmd1_bits & (LE_R1_STP | LE_R1_ENP)) !=
		    (LE_R1_STP | LE_R1_ENP)) {
			printf("%s: dropping chained buffer\n",
			    sc->sc_dev.dv_xname);
			ifp->if_ierrors++;
		} else {
#ifdef LEDEBUG
			if (sc->sc_debug > 1)
				am7990_recv_print(sc, sc->sc_last_rd);
#endif
			m = lance_read(sc, LE_RBUFADDR(sc, bix),
			    (int)rmd.rmd3 - 4);
			if (m != NULL)
				ml_enqueue(&ml, m);
		}

		rmd.rmd1_bits = LE_R1_OWN;
		rmd.rmd2 = -LEBLEN | LE_XMD2_ONES;
		rmd.rmd3 = 0;
		(*sc->sc_copytodesc)(sc, &rmd, rp, sizeof(rmd));

#ifdef LEDEBUG
		if (sc->sc_debug)
			printf("sc->sc_last_rd = %x, rmd: "
			       "ladr %04x, hadr %02x, flags %02x, "
			       "bcnt %04x, mcnt %04x\n",
				sc->sc_last_rd,
				rmd.rmd0, rmd.rmd1_hadr, rmd.rmd1_bits,
				rmd.rmd2, rmd.rmd3);
#endif

		if (++bix == sc->sc_nrbuf)
			bix = 0;
	}

	sc->sc_last_rd = bix;

	if_input(ifp, &ml);
}

void
am7990_tint(struct lance_softc *sc)
{
	struct ifnet *ifp = &sc->sc_arpcom.ac_if;
	int bix;
	struct letmd tmd;

	bix = sc->sc_first_td;

	for (;;) {
		if (sc->sc_no_td <= 0)
			break;

		(*sc->sc_copyfromdesc)(sc, &tmd, LE_TMDADDR(sc, bix),
		    sizeof(tmd));

#ifdef LEDEBUG
		if (sc->sc_debug)
			printf("trans tmd: "
			    "ladr %04x, hadr %02x, flags %02x, "
			    "bcnt %04x, mcnt %04x\n",
			    tmd.tmd0, tmd.tmd1_hadr, tmd.tmd1_bits,
			    tmd.tmd2, tmd.tmd3);
#endif

		if (tmd.tmd1_bits & LE_T1_OWN)
			break;

		ifp->if_flags &= ~IFF_OACTIVE;

		if (tmd.tmd1_bits & LE_T1_ERR) {
			if (tmd.tmd3 & LE_T3_BUFF)
				printf("%s: transmit buffer error\n",
				    sc->sc_dev.dv_xname);
			else if (tmd.tmd3 & LE_T3_UFLO)
				printf("%s: underflow\n", sc->sc_dev.dv_xname);
			if (tmd.tmd3 & (LE_T3_BUFF | LE_T3_UFLO)) {
				lance_reset(sc);
				return;
			}
			if (tmd.tmd3 & LE_T3_LCAR) {
				sc->sc_havecarrier = 0;
				if (sc->sc_nocarrier)
					(*sc->sc_nocarrier)(sc);
				else
					printf("%s: lost carrier\n",
					    sc->sc_dev.dv_xname);
			}
			if (tmd.tmd3 & LE_T3_LCOL)
				ifp->if_collisions++;
			if (tmd.tmd3 & LE_T3_RTRY) {
#ifdef LEDEBUG
				printf("%s: excessive collisions, tdr %d\n",
				    sc->sc_dev.dv_xname,
				    tmd.tmd3 & LE_T3_TDR_MASK);
#endif
				ifp->if_collisions += 16;
			}
			ifp->if_oerrors++;
		} else {
			if (tmd.tmd1_bits & LE_T1_ONE)
				ifp->if_collisions++;
			else if (tmd.tmd1_bits & LE_T1_MORE)
				/* Real number is unknown. */
				ifp->if_collisions += 2;
			ifp->if_opackets++;
		}

		if (++bix == sc->sc_ntbuf)
			bix = 0;

		--sc->sc_no_td;
	}

	sc->sc_first_td = bix;

	am7990_start(ifp);

	if (sc->sc_no_td == 0)
		ifp->if_timer = 0;
}

/*
 * Controller interrupt.
 */
int
am7990_intr(void *arg)
{
	struct lance_softc *sc = arg;
	struct ifnet *ifp = &sc->sc_arpcom.ac_if;
	uint16_t isr;

	isr = (*sc->sc_rdcsr)(sc, LE_CSR0) | sc->sc_saved_csr0;
	sc->sc_saved_csr0 = 0;
#if defined(LEDEBUG) && LEDEBUG > 1
	if (sc->sc_debug)
		printf("%s: am7990_intr entering with isr=%04x\n",
		    sc->sc_dev.dv_xname, isr);
#endif
	if ((isr & LE_C0_INTR) == 0)
		return (0);

	/*
	 * After receiving an interrupt, we need to toggle the interrupt
	 * enable bit in order to keep receiving them (some chips works
	 * without this, some do not)
	 */
	(*sc->sc_wrcsr)(sc, LE_CSR0, isr & ~LE_C0_INEA);
	(*sc->sc_wrcsr)(sc, LE_CSR0, LE_C0_INEA);

	if (isr & LE_C0_ERR) {
		if (isr & LE_C0_BABL) {
#ifdef LEDEBUG
			printf("%s: babble\n", sc->sc_dev.dv_xname);
#endif
			ifp->if_oerrors++;
		}
#if 0
		if (isr & LE_C0_CERR) {
			printf("%s: collision error\n", sc->sc_dev.dv_xname);
			ifp->if_collisions++;
		}
#endif
		if (isr & LE_C0_MISS) {
#ifdef LEDEBUG
			printf("%s: missed packet\n", sc->sc_dev.dv_xname);
#endif
			ifp->if_ierrors++;
		}
		if (isr & LE_C0_MERR) {
			printf("%s: memory error\n", sc->sc_dev.dv_xname);
			lance_reset(sc);
			return (1);
		}
	}

	if ((isr & LE_C0_RXON) == 0) {
		printf("%s: receiver disabled\n", sc->sc_dev.dv_xname);
		ifp->if_ierrors++;
		lance_reset(sc);
		return (1);
	}
	if ((isr & LE_C0_TXON) == 0) {
		printf("%s: transmitter disabled\n", sc->sc_dev.dv_xname);
		ifp->if_oerrors++;
		lance_reset(sc);
		return (1);
	}

	/*
	 * Pretend we have carrier; if we don't this will be cleared
	 * shortly.
	 */
	sc->sc_havecarrier = 1;

	if (isr & LE_C0_RINT)
		am7990_rint(sc);
	if (isr & LE_C0_TINT)
		am7990_tint(sc);

	return (1);
}

/*
 * Setup output on interface.
 * Get another datagram to send off of the interface queue, and map it to the
 * interface before starting the output.
 * Called only at splnet or interrupt level.
 */
void
am7990_start(struct ifnet *ifp)
{
	struct lance_softc *sc = ifp->if_softc;
	int bix;
	struct mbuf *m;
	struct letmd tmd;
	int rp;
	int len;

	if ((ifp->if_flags & (IFF_RUNNING | IFF_OACTIVE)) != IFF_RUNNING)
		return;

	bix = sc->sc_last_td;

	for (;;) {
		rp = LE_TMDADDR(sc, bix);
		(*sc->sc_copyfromdesc)(sc, &tmd, rp, sizeof(tmd));

		if (tmd.tmd1_bits & LE_T1_OWN) {
			ifp->if_flags |= IFF_OACTIVE;
			printf("missing buffer, no_td = %d, last_td = %d\n",
			    sc->sc_no_td, sc->sc_last_td);
		}

		IFQ_DEQUEUE(&ifp->if_snd, m);
		if (m == NULL)
			break;

#if NBPFILTER > 0
		/*
		 * If BPF is listening on this interface, let it see the packet
		 * before we commit it to the wire.
		 */
		if (ifp->if_bpf)
			bpf_mtap(ifp->if_bpf, m, BPF_DIRECTION_OUT);
#endif

		/*
		 * Copy the mbuf chain into the transmit buffer.
		 */
		len = lance_put(sc, LE_TBUFADDR(sc, bix), m);

#ifdef LEDEBUG
		if (len > ETHERMTU + sizeof(struct ether_header))
			printf("packet length %d\n", len);
#endif

		ifp->if_timer = 5;

		/*
		 * Init transmit registers, and set transmit start flag.
		 */
		tmd.tmd1_bits = LE_T1_OWN | LE_T1_STP | LE_T1_ENP;
		tmd.tmd2 = -len | LE_XMD2_ONES;
		tmd.tmd3 = 0;

		(*sc->sc_copytodesc)(sc, &tmd, rp, sizeof(tmd));

#ifdef LEDEBUG
		if (sc->sc_debug > 1)
			am7990_xmit_print(sc, sc->sc_last_td);
#endif

		(*sc->sc_wrcsr)(sc, LE_CSR0, LE_C0_INEA | LE_C0_TDMD);

		if (++bix == sc->sc_ntbuf)
			bix = 0;

		if (++sc->sc_no_td == sc->sc_ntbuf) {
			ifp->if_flags |= IFF_OACTIVE;
			break;
		}

	}

	sc->sc_last_td = bix;
}

#ifdef LEDEBUG
void
am7990_recv_print(struct lance_softc *sc, int no)
{
	struct lermd rmd;
	uint16_t len;
	struct ether_header eh;

	(*sc->sc_copyfromdesc)(sc, &rmd, LE_RMDADDR(sc, no), sizeof(rmd));
	len = rmd.rmd3;
	printf("%s: receive buffer %d, len = %d\n",
	    sc->sc_dev.dv_xname, no, len);
	printf("%s: status %04x\n", sc->sc_dev.dv_xname,
	    (*sc->sc_rdcsr)(sc, LE_CSR0));
	printf("%s: ladr %04x, hadr %02x, flags %02x, bcnt %04x, mcnt %04x\n",
	    sc->sc_dev.dv_xname,
	    rmd.rmd0, rmd.rmd1_hadr, rmd.rmd1_bits, rmd.rmd2, rmd.rmd3);
	if (len >= sizeof(eh)) {
		(*sc->sc_copyfrombuf)(sc, &eh, LE_RBUFADDR(sc, no), sizeof(eh));
		printf("%s: dst %s", sc->sc_dev.dv_xname,
			ether_sprintf(eh.ether_dhost));
		printf(" src %s type %04x\n", ether_sprintf(eh.ether_shost),
			ntohs(eh.ether_type));
	}
}

void
am7990_xmit_print(struct lance_softc *sc, int no)
{
	struct letmd tmd;
	uint16_t len;
	struct ether_header eh;

	(*sc->sc_copyfromdesc)(sc, &tmd, LE_TMDADDR(sc, no), sizeof(tmd));
	len = -tmd.tmd2;
	printf("%s: transmit buffer %d, len = %d\n",
	    sc->sc_dev.dv_xname, no, len);
	printf("%s: status %04x\n", sc->sc_dev.dv_xname,
	    (*sc->sc_rdcsr)(sc, LE_CSR0));
	printf("%s: ladr %04x, hadr %02x, flags %02x, bcnt %04x, mcnt %04x\n",
	    sc->sc_dev.dv_xname,
	    tmd.tmd0, tmd.tmd1_hadr, tmd.tmd1_bits, tmd.tmd2, tmd.tmd3);
	if (len >= sizeof(eh)) {
		(*sc->sc_copyfrombuf)(sc, &eh, LE_TBUFADDR(sc, no), sizeof(eh));
		printf("%s: dst %s", sc->sc_dev.dv_xname,
			ether_sprintf(eh.ether_dhost));
		printf(" src %s type %04x\n", ether_sprintf(eh.ether_shost),
		    ntohs(eh.ether_type));
	}
}
#endif /* LEDEBUG */