repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
stas2z/linux-3.10-witi | drivers/staging/wlags49_h2/wl_netdev.c | 2382 | 61141 | /*******************************************************************************
* Agere Systems Inc.
* Wireless device driver for Linux (wlags49).
*
* Copyright (c) 1998-2003 Agere Systems Inc.
* All rights reserved.
* http://www.agere.com
*
* Initially developed by TriplePoint, Inc.
* http://www.triplepoint.com
*
*------------------------------------------------------------------------------
*
* This file contains handler functions registered with the net_device
* structure.
*
*------------------------------------------------------------------------------
*
* SOFTWARE LICENSE
*
* This software is provided subject to the following terms and conditions,
* which you should read carefully before using the software. Using this
* software indicates your acceptance of these terms and conditions. If you do
* not agree with these terms and conditions, do not use the software.
*
* Copyright © 2003 Agere Systems Inc.
* All rights reserved.
*
* Redistribution and use in source or binary forms, with or without
* modifications, are permitted provided that the following conditions are met:
*
* . Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following Disclaimer as comments in the code as
* well as in the documentation and/or other materials provided with the
* distribution.
*
* . 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.
*
* . Neither the name of Agere Systems Inc. nor the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* Disclaimer
*
* THIS SOFTWARE IS PROVIDED AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, INFRINGEMENT AND THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ANY
* USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE IS SOLELY AT THE USERS OWN
* RISK. IN NO EVENT SHALL AGERE SYSTEMS INC. 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, INCLUDING, BUT NOT LIMITED TO, 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.
*
******************************************************************************/
/*******************************************************************************
* include files
******************************************************************************/
#include <wl_version.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/kernel.h>
// #include <linux/sched.h>
// #include <linux/ptrace.h>
// #include <linux/slab.h>
// #include <linux/ctype.h>
// #include <linux/string.h>
//#include <linux/timer.h>
// #include <linux/interrupt.h>
// #include <linux/in.h>
// #include <linux/delay.h>
// #include <linux/skbuff.h>
// #include <asm/io.h>
// // #include <asm/bitops.h>
#include <linux/netdevice.h>
#include <linux/ethtool.h>
#include <linux/etherdevice.h>
// #include <linux/skbuff.h>
// #include <linux/if_arp.h>
// #include <linux/ioport.h>
#include <debug.h>
#include <hcf.h>
#include <dhf.h>
// #include <hcfdef.h>
#include <wl_if.h>
#include <wl_internal.h>
#include <wl_util.h>
#include <wl_priv.h>
#include <wl_main.h>
#include <wl_netdev.h>
#include <wl_wext.h>
#ifdef USE_PROFILE
#include <wl_profile.h>
#endif /* USE_PROFILE */
#ifdef BUS_PCMCIA
#include <wl_cs.h>
#endif /* BUS_PCMCIA */
#ifdef BUS_PCI
#include <wl_pci.h>
#endif /* BUS_PCI */
/*******************************************************************************
* global variables
******************************************************************************/
#if DBG
extern dbg_info_t *DbgInfo;
#endif /* DBG */
#if HCF_ENCAP
#define MTU_MAX (HCF_MAX_MSG - ETH_HLEN - 8)
#else
#define MTU_MAX (HCF_MAX_MSG - ETH_HLEN)
#endif
//static int mtu = MTU_MAX;
//MODULE_PARM(mtu, "i");
//MODULE_PARM_DESC(mtu, "MTU");
/*******************************************************************************
* macros
******************************************************************************/
#define BLOCK_INPUT(buf, len) \
desc->buf_addr = buf; \
desc->BUF_SIZE = len; \
status = hcf_rcv_msg(&(lp->hcfCtx), desc, 0)
#define BLOCK_INPUT_DMA(buf, len) memcpy( buf, desc_next->buf_addr, pktlen )
/*******************************************************************************
* function prototypes
******************************************************************************/
/*******************************************************************************
* wl_init()
*******************************************************************************
*
* DESCRIPTION:
*
* We never need to do anything when a "Wireless" device is "initialized"
* by the net software, because we only register already-found cards.
*
* PARAMETERS:
*
* dev - a pointer to the device's net_device structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
int wl_init( struct net_device *dev )
{
// unsigned long flags;
// struct wl_private *lp = wl_priv(dev);
/*------------------------------------------------------------------------*/
DBG_FUNC( "wl_init" );
DBG_ENTER( DbgInfo );
DBG_PARAM( DbgInfo, "dev", "%s (0x%p)", dev->name, dev );
/* Nothing to do, but grab the spinlock anyway just in case we ever need
this routine */
// wl_lock( lp, &flags );
// wl_unlock( lp, &flags );
DBG_LEAVE( DbgInfo );
return 0;
} // wl_init
/*============================================================================*/
/*******************************************************************************
* wl_config()
*******************************************************************************
*
* DESCRIPTION:
*
* Implement the SIOCSIFMAP interface.
*
* PARAMETERS:
*
* dev - a pointer to the device's net_device structure
* map - a pointer to the device's ifmap structure
*
* RETURNS:
*
* 0 on success
* errno otherwise
*
******************************************************************************/
int wl_config( struct net_device *dev, struct ifmap *map )
{
DBG_FUNC( "wl_config" );
DBG_ENTER( DbgInfo );
DBG_PARAM( DbgInfo, "dev", "%s (0x%p)", dev->name, dev );
DBG_PARAM( DbgInfo, "map", "0x%p", map );
/* The only thing we care about here is a port change. Since this not needed,
ignore the request. */
DBG_TRACE(DbgInfo, "%s: %s called.\n", dev->name, __func__);
DBG_LEAVE( DbgInfo );
return 0;
} // wl_config
/*============================================================================*/
/*******************************************************************************
* wl_stats()
*******************************************************************************
*
* DESCRIPTION:
*
* Return the current device statistics.
*
* PARAMETERS:
*
* dev - a pointer to the device's net_device structure
*
* RETURNS:
*
* a pointer to a net_device_stats structure containing the network
* statistics.
*
******************************************************************************/
struct net_device_stats *wl_stats( struct net_device *dev )
{
#ifdef USE_WDS
int count;
#endif /* USE_WDS */
unsigned long flags;
struct net_device_stats *pStats;
struct wl_private *lp = wl_priv(dev);
/*------------------------------------------------------------------------*/
//DBG_FUNC( "wl_stats" );
//DBG_ENTER( DbgInfo );
//DBG_PARAM( DbgInfo, "dev", "%s (0x%p)", dev->name, dev );
pStats = NULL;
wl_lock( lp, &flags );
#ifdef USE_RTS
if( lp->useRTS == 1 ) {
wl_unlock( lp, &flags );
//DBG_LEAVE( DbgInfo );
return NULL;
}
#endif /* USE_RTS */
/* Return the statistics for the appropriate device */
#ifdef USE_WDS
for( count = 0; count < NUM_WDS_PORTS; count++ ) {
if( dev == lp->wds_port[count].dev ) {
pStats = &( lp->wds_port[count].stats );
}
}
#endif /* USE_WDS */
/* If pStats is still NULL, then the device is not a WDS port */
if( pStats == NULL ) {
pStats = &( lp->stats );
}
wl_unlock( lp, &flags );
//DBG_LEAVE( DbgInfo );
return pStats;
} // wl_stats
/*============================================================================*/
/*******************************************************************************
* wl_open()
*******************************************************************************
*
* DESCRIPTION:
*
* Open the device.
*
* PARAMETERS:
*
* dev - a pointer to the device's net_device structure
*
* RETURNS:
*
* 0 on success
* errno otherwise
*
******************************************************************************/
int wl_open(struct net_device *dev)
{
int status = HCF_SUCCESS;
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wl_open" );
DBG_ENTER( DbgInfo );
wl_lock( lp, &flags );
#ifdef USE_RTS
if( lp->useRTS == 1 ) {
DBG_TRACE( DbgInfo, "Skipping device open, in RTS mode\n" );
wl_unlock( lp, &flags );
DBG_LEAVE( DbgInfo );
return -EIO;
}
#endif /* USE_RTS */
#ifdef USE_PROFILE
parse_config( dev );
#endif
if( lp->portState == WVLAN_PORT_STATE_DISABLED ) {
DBG_TRACE( DbgInfo, "Enabling Port 0\n" );
status = wl_enable( lp );
if( status != HCF_SUCCESS ) {
DBG_TRACE( DbgInfo, "Enable port 0 failed: 0x%x\n", status );
}
}
// Holding the lock too long, make a gap to allow other processes
wl_unlock(lp, &flags);
wl_lock( lp, &flags );
if ( strlen( lp->fw_image_filename ) ) {
DBG_TRACE( DbgInfo, ";???? Kludgy way to force a download\n" );
status = wl_go( lp );
} else {
status = wl_apply( lp );
}
// Holding the lock too long, make a gap to allow other processes
wl_unlock(lp, &flags);
wl_lock( lp, &flags );
if( status != HCF_SUCCESS ) {
// Unsuccessful, try reset of the card to recover
status = wl_reset( dev );
}
// Holding the lock too long, make a gap to allow other processes
wl_unlock(lp, &flags);
wl_lock( lp, &flags );
if( status == HCF_SUCCESS ) {
netif_carrier_on( dev );
WL_WDS_NETIF_CARRIER_ON( lp );
lp->is_handling_int = WL_HANDLING_INT; // Start handling interrupts
wl_act_int_on( lp );
netif_start_queue( dev );
WL_WDS_NETIF_START_QUEUE( lp );
} else {
wl_hcf_error( dev, status ); /* Report the error */
netif_device_detach( dev ); /* Stop the device and queue */
}
wl_unlock( lp, &flags );
DBG_LEAVE( DbgInfo );
return status;
} // wl_open
/*============================================================================*/
/*******************************************************************************
* wl_close()
*******************************************************************************
*
* DESCRIPTION:
*
* Close the device.
*
* PARAMETERS:
*
* dev - a pointer to the device's net_device structure
*
* RETURNS:
*
* 0 on success
* errno otherwise
*
******************************************************************************/
int wl_close( struct net_device *dev )
{
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
/*------------------------------------------------------------------------*/
DBG_FUNC("wl_close");
DBG_ENTER(DbgInfo);
DBG_PARAM(DbgInfo, "dev", "%s (0x%p)", dev->name, dev);
/* Mark the adapter as busy */
netif_stop_queue( dev );
WL_WDS_NETIF_STOP_QUEUE( lp );
netif_carrier_off( dev );
WL_WDS_NETIF_CARRIER_OFF( lp );
/* Shutdown the adapter:
Disable adapter interrupts
Stop Tx/Rx
Update statistics
Set low power mode
*/
wl_lock( lp, &flags );
wl_act_int_off( lp );
lp->is_handling_int = WL_NOT_HANDLING_INT; // Stop handling interrupts
#ifdef USE_RTS
if( lp->useRTS == 1 ) {
DBG_TRACE( DbgInfo, "Skipping device close, in RTS mode\n" );
wl_unlock( lp, &flags );
DBG_LEAVE( DbgInfo );
return -EIO;
}
#endif /* USE_RTS */
/* Disable the ports */
wl_disable( lp );
wl_unlock( lp, &flags );
DBG_LEAVE( DbgInfo );
return 0;
} // wl_close
/*============================================================================*/
static void wl_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
{
strlcpy(info->driver, DRIVER_NAME, sizeof(info->driver));
strlcpy(info->version, DRV_VERSION_STR, sizeof(info->version));
// strlcpy(info.fw_version, priv->fw_name,
// sizeof(info.fw_version));
if (dev->dev.parent) {
dev_set_name(dev->dev.parent, "%s", info->bus_info);
//strlcpy(info->bus_info, dev->dev.parent->bus_id,
// sizeof(info->bus_info));
} else {
snprintf(info->bus_info, sizeof(info->bus_info),
"PCMCIA FIXME");
// "PCMCIA 0x%lx", priv->hw.iobase);
}
} // wl_get_drvinfo
static struct ethtool_ops wl_ethtool_ops = {
.get_drvinfo = wl_get_drvinfo,
.get_link = ethtool_op_get_link,
};
/*******************************************************************************
* wl_ioctl()
*******************************************************************************
*
* DESCRIPTION:
*
* The IOCTL handler for the device.
*
* PARAMETERS:
*
* dev - a pointer to the device's net_device struct.
* rq - a pointer to the IOCTL request buffer.
* cmd - the IOCTL command code.
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
int wl_ioctl( struct net_device *dev, struct ifreq *rq, int cmd )
{
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
int ret = 0;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wl_ioctl" );
DBG_ENTER(DbgInfo);
DBG_PARAM(DbgInfo, "dev", "%s (0x%p)", dev->name, dev);
DBG_PARAM(DbgInfo, "rq", "0x%p", rq);
DBG_PARAM(DbgInfo, "cmd", "0x%04x", cmd);
wl_lock( lp, &flags );
wl_act_int_off( lp );
#ifdef USE_RTS
if( lp->useRTS == 1 ) {
/* Handle any RTS IOCTL here */
if( cmd == WL_IOCTL_RTS ) {
DBG_TRACE( DbgInfo, "IOCTL: WL_IOCTL_RTS\n" );
ret = wvlan_rts( (struct rtsreq *)rq, dev->base_addr );
} else {
DBG_TRACE( DbgInfo, "IOCTL not supported in RTS mode: 0x%X\n", cmd );
ret = -EOPNOTSUPP;
}
goto out_act_int_on_unlock;
}
#endif /* USE_RTS */
/* Only handle UIL IOCTL requests when the UIL has the system blocked. */
if( !(( lp->flags & WVLAN2_UIL_BUSY ) && ( cmd != WVLAN2_IOCTL_UIL ))) {
#ifdef USE_UIL
struct uilreq *urq = (struct uilreq *)rq;
#endif /* USE_UIL */
switch( cmd ) {
// ================== Private IOCTLs (up to 16) ==================
#ifdef USE_UIL
case WVLAN2_IOCTL_UIL:
DBG_TRACE( DbgInfo, "IOCTL: WVLAN2_IOCTL_UIL\n" );
ret = wvlan_uil( urq, lp );
break;
#endif /* USE_UIL */
default:
DBG_TRACE(DbgInfo, "IOCTL CODE NOT SUPPORTED: 0x%X\n", cmd );
ret = -EOPNOTSUPP;
break;
}
} else {
DBG_WARNING( DbgInfo, "DEVICE IS BUSY, CANNOT PROCESS REQUEST\n" );
ret = -EBUSY;
}
#ifdef USE_RTS
out_act_int_on_unlock:
#endif /* USE_RTS */
wl_act_int_on( lp );
wl_unlock( lp, &flags );
DBG_LEAVE( DbgInfo );
return ret;
} // wl_ioctl
/*============================================================================*/
#ifdef CONFIG_NET_POLL_CONTROLLER
void wl_poll(struct net_device *dev)
{
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
struct pt_regs regs;
wl_lock( lp, &flags );
wl_isr(dev->irq, dev, ®s);
wl_unlock( lp, &flags );
}
#endif
/*******************************************************************************
* wl_tx_timeout()
*******************************************************************************
*
* DESCRIPTION:
*
* The handler called when, for some reason, a Tx request is not completed.
*
* PARAMETERS:
*
* dev - a pointer to the device's net_device struct.
*
* RETURNS:
*
* N/A
*
******************************************************************************/
void wl_tx_timeout( struct net_device *dev )
{
#ifdef USE_WDS
int count;
#endif /* USE_WDS */
unsigned long flags;
struct wl_private *lp = wl_priv(dev);
struct net_device_stats *pStats = NULL;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wl_tx_timeout" );
DBG_ENTER( DbgInfo );
DBG_WARNING( DbgInfo, "%s: Transmit timeout.\n", dev->name );
wl_lock( lp, &flags );
#ifdef USE_RTS
if( lp->useRTS == 1 ) {
DBG_TRACE( DbgInfo, "Skipping tx_timeout handler, in RTS mode\n" );
wl_unlock( lp, &flags );
DBG_LEAVE( DbgInfo );
return;
}
#endif /* USE_RTS */
/* Figure out which device (the "root" device or WDS port) this timeout
is for */
#ifdef USE_WDS
for( count = 0; count < NUM_WDS_PORTS; count++ ) {
if( dev == lp->wds_port[count].dev ) {
pStats = &( lp->wds_port[count].stats );
/* Break the loop so that we can use the counter to access WDS
information in the private structure */
break;
}
}
#endif /* USE_WDS */
/* If pStats is still NULL, then the device is not a WDS port */
if( pStats == NULL ) {
pStats = &( lp->stats );
}
/* Accumulate the timeout error */
pStats->tx_errors++;
wl_unlock( lp, &flags );
DBG_LEAVE( DbgInfo );
} // wl_tx_timeout
/*============================================================================*/
/*******************************************************************************
* wl_send()
*******************************************************************************
*
* DESCRIPTION:
*
* The routine which performs data transmits.
*
* PARAMETERS:
*
* lp - a pointer to the device's wl_private struct.
*
* RETURNS:
*
* 0 on success
* 1 on error
*
******************************************************************************/
int wl_send( struct wl_private *lp )
{
int status;
DESC_STRCT *desc;
WVLAN_LFRAME *txF = NULL;
struct list_head *element;
int len;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wl_send" );
if( lp == NULL ) {
DBG_ERROR( DbgInfo, "Private adapter struct is NULL\n" );
return FALSE;
}
if( lp->dev == NULL ) {
DBG_ERROR( DbgInfo, "net_device struct in wl_private is NULL\n" );
return FALSE;
}
/* Check for the availability of FIDs; if none are available, don't take any
frames off the txQ */
if( lp->hcfCtx.IFB_RscInd == 0 ) {
return FALSE;
}
/* Reclaim the TxQ Elements and place them back on the free queue */
if( !list_empty( &( lp->txQ[0] ))) {
element = lp->txQ[0].next;
txF = (WVLAN_LFRAME * )list_entry( element, WVLAN_LFRAME, node );
if( txF != NULL ) {
lp->txF.skb = txF->frame.skb;
lp->txF.port = txF->frame.port;
txF->frame.skb = NULL;
txF->frame.port = 0;
list_del( &( txF->node ));
list_add( element, &( lp->txFree ));
lp->txQ_count--;
if( lp->txQ_count < TX_Q_LOW_WATER_MARK ) {
if( lp->netif_queue_on == FALSE ) {
DBG_TX( DbgInfo, "Kickstarting Q: %d\n", lp->txQ_count );
netif_wake_queue( lp->dev );
WL_WDS_NETIF_WAKE_QUEUE( lp );
lp->netif_queue_on = TRUE;
}
}
}
}
if( lp->txF.skb == NULL ) {
return FALSE;
}
/* If the device has resources (FIDs) available, then Tx the packet */
/* Format the TxRequest and send it to the adapter */
len = lp->txF.skb->len < ETH_ZLEN ? ETH_ZLEN : lp->txF.skb->len;
desc = &( lp->desc_tx );
desc->buf_addr = lp->txF.skb->data;
desc->BUF_CNT = len;
desc->next_desc_addr = NULL;
status = hcf_send_msg( &( lp->hcfCtx ), desc, lp->txF.port );
if( status == HCF_SUCCESS ) {
lp->dev->trans_start = jiffies;
DBG_TX( DbgInfo, "Transmit...\n" );
if( lp->txF.port == HCF_PORT_0 ) {
lp->stats.tx_packets++;
lp->stats.tx_bytes += lp->txF.skb->len;
}
#ifdef USE_WDS
else
{
lp->wds_port[(( lp->txF.port >> 8 ) - 1)].stats.tx_packets++;
lp->wds_port[(( lp->txF.port >> 8 ) - 1)].stats.tx_bytes += lp->txF.skb->len;
}
#endif /* USE_WDS */
/* Free the skb and perform queue cleanup, as the buffer was
transmitted successfully */
dev_kfree_skb( lp->txF.skb );
lp->txF.skb = NULL;
lp->txF.port = 0;
}
return TRUE;
} // wl_send
/*============================================================================*/
/*******************************************************************************
* wl_tx()
*******************************************************************************
*
* DESCRIPTION:
*
* The Tx handler function for the network layer.
*
* PARAMETERS:
*
* skb - a pointer to the sk_buff structure containing the data to transfer.
* dev - a pointer to the device's net_device structure.
*
* RETURNS:
*
* 0 on success
* 1 on error
*
******************************************************************************/
int wl_tx( struct sk_buff *skb, struct net_device *dev, int port )
{
unsigned long flags;
struct wl_private *lp = wl_priv(dev);
WVLAN_LFRAME *txF = NULL;
struct list_head *element;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wl_tx" );
/* Grab the spinlock */
wl_lock( lp, &flags );
if( lp->flags & WVLAN2_UIL_BUSY ) {
DBG_WARNING( DbgInfo, "UIL has device blocked\n" );
/* Start dropping packets here??? */
wl_unlock( lp, &flags );
return 1;
}
#ifdef USE_RTS
if( lp->useRTS == 1 ) {
DBG_PRINT( "RTS: we're getting a Tx...\n" );
wl_unlock( lp, &flags );
return 1;
}
#endif /* USE_RTS */
if( !lp->use_dma ) {
/* Get an element from the queue */
element = lp->txFree.next;
txF = (WVLAN_LFRAME *)list_entry( element, WVLAN_LFRAME, node );
if( txF == NULL ) {
DBG_ERROR( DbgInfo, "Problem with list_entry\n" );
wl_unlock( lp, &flags );
return 1;
}
/* Fill out the frame */
txF->frame.skb = skb;
txF->frame.port = port;
/* Move the frame to the txQ */
/* NOTE: Here's where we would do priority queueing */
list_move(&(txF->node), &(lp->txQ[0]));
lp->txQ_count++;
if( lp->txQ_count >= DEFAULT_NUM_TX_FRAMES ) {
DBG_TX( DbgInfo, "Q Full: %d\n", lp->txQ_count );
if( lp->netif_queue_on == TRUE ) {
netif_stop_queue( lp->dev );
WL_WDS_NETIF_STOP_QUEUE( lp );
lp->netif_queue_on = FALSE;
}
}
}
wl_act_int_off( lp ); /* Disable Interrupts */
/* Send the data to the hardware using the appropriate method */
#ifdef ENABLE_DMA
if( lp->use_dma ) {
wl_send_dma( lp, skb, port );
}
else
#endif
{
wl_send( lp );
}
/* Re-enable Interrupts, release the spinlock and return */
wl_act_int_on( lp );
wl_unlock( lp, &flags );
return 0;
} // wl_tx
/*============================================================================*/
/*******************************************************************************
* wl_rx()
*******************************************************************************
*
* DESCRIPTION:
*
* The routine which performs data reception.
*
* PARAMETERS:
*
* dev - a pointer to the device's net_device structure.
*
* RETURNS:
*
* 0 on success
* 1 on error
*
******************************************************************************/
int wl_rx(struct net_device *dev)
{
int port;
struct sk_buff *skb;
struct wl_private *lp = wl_priv(dev);
int status;
hcf_16 pktlen;
hcf_16 hfs_stat;
DESC_STRCT *desc;
/*------------------------------------------------------------------------*/
DBG_FUNC("wl_rx")
DBG_PARAM(DbgInfo, "dev", "%s (0x%p)", dev->name, dev);
if(!( lp->flags & WVLAN2_UIL_BUSY )) {
#ifdef USE_RTS
if( lp->useRTS == 1 ) {
DBG_PRINT( "RTS: We're getting an Rx...\n" );
return -EIO;
}
#endif /* USE_RTS */
/* Read the HFS_STAT register from the lookahead buffer */
hfs_stat = (hcf_16)(( lp->lookAheadBuf[HFS_STAT] ) |
( lp->lookAheadBuf[HFS_STAT + 1] << 8 ));
/* Make sure the frame isn't bad */
if(( hfs_stat & HFS_STAT_ERR ) != HCF_SUCCESS ) {
DBG_WARNING( DbgInfo, "HFS_STAT_ERROR (0x%x) in Rx Packet\n",
lp->lookAheadBuf[HFS_STAT] );
return -EIO;
}
/* Determine what port this packet is for */
port = ( hfs_stat >> 8 ) & 0x0007;
DBG_RX( DbgInfo, "Rx frame for port %d\n", port );
pktlen = lp->hcfCtx.IFB_RxLen;
if (pktlen != 0) {
skb = ALLOC_SKB(pktlen);
if (skb != NULL) {
/* Set the netdev based on the port */
switch( port ) {
#ifdef USE_WDS
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
skb->dev = lp->wds_port[port-1].dev;
break;
#endif /* USE_WDS */
case 0:
default:
skb->dev = dev;
break;
}
desc = &( lp->desc_rx );
desc->next_desc_addr = NULL;
/*
#define BLOCK_INPUT(buf, len) \
desc->buf_addr = buf; \
desc->BUF_SIZE = len; \
status = hcf_rcv_msg(&(lp->hcfCtx), desc, 0)
*/
GET_PACKET( skb->dev, skb, pktlen );
if( status == HCF_SUCCESS ) {
netif_rx( skb );
if( port == 0 ) {
lp->stats.rx_packets++;
lp->stats.rx_bytes += pktlen;
}
#ifdef USE_WDS
else
{
lp->wds_port[port-1].stats.rx_packets++;
lp->wds_port[port-1].stats.rx_bytes += pktlen;
}
#endif /* USE_WDS */
dev->last_rx = jiffies;
#ifdef WIRELESS_EXT
#ifdef WIRELESS_SPY
if( lp->spydata.spy_number > 0 ) {
char *srcaddr = skb->mac.raw + MAC_ADDR_SIZE;
wl_spy_gather( dev, srcaddr );
}
#endif /* WIRELESS_SPY */
#endif /* WIRELESS_EXT */
} else {
DBG_ERROR( DbgInfo, "Rx request to card FAILED\n" );
if( port == 0 ) {
lp->stats.rx_dropped++;
}
#ifdef USE_WDS
else
{
lp->wds_port[port-1].stats.rx_dropped++;
}
#endif /* USE_WDS */
dev_kfree_skb( skb );
}
} else {
DBG_ERROR( DbgInfo, "Could not alloc skb\n" );
if( port == 0 ) {
lp->stats.rx_dropped++;
}
#ifdef USE_WDS
else
{
lp->wds_port[port-1].stats.rx_dropped++;
}
#endif /* USE_WDS */
}
}
}
return 0;
} // wl_rx
/*============================================================================*/
/*******************************************************************************
* wl_multicast()
*******************************************************************************
*
* DESCRIPTION:
*
* Function to handle multicast packets
*
* PARAMETERS:
*
* dev - a pointer to the device's net_device structure.
*
* RETURNS:
*
* N/A
*
******************************************************************************/
#ifdef NEW_MULTICAST
void wl_multicast( struct net_device *dev )
{
#if 1 //;? (HCF_TYPE) & HCF_TYPE_STA //;?should we return an error status in AP mode
//;?seems reasonable that even an AP-only driver could afford this small additional footprint
int x;
struct netdev_hw_addr *ha;
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wl_multicast" );
DBG_ENTER( DbgInfo );
DBG_PARAM( DbgInfo, "dev", "%s (0x%p)", dev->name, dev );
if( !wl_adapter_is_open( dev )) {
DBG_LEAVE( DbgInfo );
return;
}
#if DBG
if( DBG_FLAGS( DbgInfo ) & DBG_PARAM_ON ) {
DBG_PRINT(" flags: %s%s%s\n",
( dev->flags & IFF_PROMISC ) ? "Promiscuous " : "",
( dev->flags & IFF_MULTICAST ) ? "Multicast " : "",
( dev->flags & IFF_ALLMULTI ) ? "All-Multicast" : "" );
DBG_PRINT( " mc_count: %d\n", netdev_mc_count(dev));
netdev_for_each_mc_addr(ha, dev)
DBG_PRINT(" %pM (%d)\n", ha->addr, dev->addr_len);
}
#endif /* DBG */
if(!( lp->flags & WVLAN2_UIL_BUSY )) {
#ifdef USE_RTS
if( lp->useRTS == 1 ) {
DBG_TRACE( DbgInfo, "Skipping multicast, in RTS mode\n" );
DBG_LEAVE( DbgInfo );
return;
}
#endif /* USE_RTS */
wl_lock( lp, &flags );
wl_act_int_off( lp );
if ( CNV_INT_TO_LITTLE( lp->hcfCtx.IFB_FWIdentity.comp_id ) == COMP_ID_FW_STA ) {
if( dev->flags & IFF_PROMISC ) {
/* Enable promiscuous mode */
lp->ltvRecord.len = 2;
lp->ltvRecord.typ = CFG_PROMISCUOUS_MODE;
lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( 1 );
DBG_PRINT( "Enabling Promiscuous mode (IFF_PROMISC)\n" );
hcf_put_info( &( lp->hcfCtx ), (LTVP)&( lp->ltvRecord ));
}
else if ((netdev_mc_count(dev) > HCF_MAX_MULTICAST) ||
( dev->flags & IFF_ALLMULTI )) {
/* Shutting off this filter will enable all multicast frames to
be sent up from the device; however, this is a static RID, so
a call to wl_apply() is needed */
lp->ltvRecord.len = 2;
lp->ltvRecord.typ = CFG_CNF_RX_ALL_GROUP_ADDR;
lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( 0 );
DBG_PRINT( "Enabling all multicast mode (IFF_ALLMULTI)\n" );
hcf_put_info( &( lp->hcfCtx ), (LTVP)&( lp->ltvRecord ));
wl_apply( lp );
}
else if (!netdev_mc_empty(dev)) {
/* Set the multicast addresses */
lp->ltvRecord.len = ( netdev_mc_count(dev) * 3 ) + 1;
lp->ltvRecord.typ = CFG_GROUP_ADDR;
x = 0;
netdev_for_each_mc_addr(ha, dev)
memcpy(&(lp->ltvRecord.u.u8[x++ * ETH_ALEN]),
ha->addr, ETH_ALEN);
DBG_PRINT( "Setting multicast list\n" );
hcf_put_info( &( lp->hcfCtx ), (LTVP)&( lp->ltvRecord ));
} else {
/* Disable promiscuous mode */
lp->ltvRecord.len = 2;
lp->ltvRecord.typ = CFG_PROMISCUOUS_MODE;
lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( 0 );
DBG_PRINT( "Disabling Promiscuous mode\n" );
hcf_put_info( &( lp->hcfCtx ), (LTVP)&( lp->ltvRecord ));
/* Disable multicast mode */
lp->ltvRecord.len = 2;
lp->ltvRecord.typ = CFG_GROUP_ADDR;
DBG_PRINT( "Disabling Multicast mode\n" );
hcf_put_info( &( lp->hcfCtx ), (LTVP)&( lp->ltvRecord ));
/* Turning on this filter will prevent all multicast frames from
being sent up from the device; however, this is a static RID,
so a call to wl_apply() is needed */
lp->ltvRecord.len = 2;
lp->ltvRecord.typ = CFG_CNF_RX_ALL_GROUP_ADDR;
lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( 1 );
DBG_PRINT( "Disabling all multicast mode (IFF_ALLMULTI)\n" );
hcf_put_info( &( lp->hcfCtx ), (LTVP)&( lp->ltvRecord ));
wl_apply( lp );
}
}
wl_act_int_on( lp );
wl_unlock( lp, &flags );
}
DBG_LEAVE( DbgInfo );
#endif /* HCF_STA */
} // wl_multicast
/*============================================================================*/
#else /* NEW_MULTICAST */
void wl_multicast( struct net_device *dev, int num_addrs, void *addrs )
{
DBG_FUNC( "wl_multicast");
DBG_ENTER(DbgInfo);
DBG_PARAM( DbgInfo, "dev", "%s (0x%p)", dev->name, dev );
DBG_PARAM( DbgInfo, "num_addrs", "%d", num_addrs );
DBG_PARAM( DbgInfo, "addrs", "0x%p", addrs );
#error Obsolete set multicast interface!
DBG_LEAVE( DbgInfo );
} // wl_multicast
/*============================================================================*/
#endif /* NEW_MULTICAST */
static const struct net_device_ops wl_netdev_ops =
{
.ndo_start_xmit = &wl_tx_port0,
.ndo_set_config = &wl_config,
.ndo_get_stats = &wl_stats,
.ndo_set_rx_mode = &wl_multicast,
.ndo_init = &wl_insert,
.ndo_open = &wl_adapter_open,
.ndo_stop = &wl_adapter_close,
.ndo_do_ioctl = &wl_ioctl,
.ndo_tx_timeout = &wl_tx_timeout,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = wl_poll,
#endif
};
/*******************************************************************************
* wl_device_alloc()
*******************************************************************************
*
* DESCRIPTION:
*
* Create instances of net_device and wl_private for the new adapter
* and register the device's entry points in the net_device structure.
*
* PARAMETERS:
*
* N/A
*
* RETURNS:
*
* a pointer to an allocated and initialized net_device struct for this
* device.
*
******************************************************************************/
struct net_device * wl_device_alloc( void )
{
struct net_device *dev = NULL;
struct wl_private *lp = NULL;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wl_device_alloc" );
DBG_ENTER( DbgInfo );
/* Alloc a net_device struct */
dev = alloc_etherdev(sizeof(struct wl_private));
if (!dev)
return NULL;
/* Initialize the 'next' pointer in the struct. Currently only used for PCI,
but do it here just in case it's used for other buses in the future */
lp = wl_priv(dev);
/* Check MTU */
if( dev->mtu > MTU_MAX )
{
DBG_WARNING( DbgInfo, "%s: MTU set too high, limiting to %d.\n",
dev->name, MTU_MAX );
dev->mtu = MTU_MAX;
}
/* Setup the function table in the device structure. */
dev->wireless_handlers = (struct iw_handler_def *)&wl_iw_handler_def;
lp->wireless_data.spy_data = &lp->spy_data;
dev->wireless_data = &lp->wireless_data;
dev->netdev_ops = &wl_netdev_ops;
dev->watchdog_timeo = TX_TIMEOUT;
dev->ethtool_ops = &wl_ethtool_ops;
netif_stop_queue( dev );
/* Allocate virtual devices for WDS support if needed */
WL_WDS_DEVICE_ALLOC( lp );
DBG_LEAVE( DbgInfo );
return dev;
} // wl_device_alloc
/*============================================================================*/
/*******************************************************************************
* wl_device_dealloc()
*******************************************************************************
*
* DESCRIPTION:
*
* Free instances of net_device and wl_private strcutres for an adapter
* and perform basic cleanup.
*
* PARAMETERS:
*
* dev - a pointer to the device's net_device structure.
*
* RETURNS:
*
* N/A
*
******************************************************************************/
void wl_device_dealloc( struct net_device *dev )
{
// struct wl_private *lp = wl_priv(dev);
/*------------------------------------------------------------------------*/
DBG_FUNC( "wl_device_dealloc" );
DBG_ENTER( DbgInfo );
/* Dealloc the WDS ports */
WL_WDS_DEVICE_DEALLOC( lp );
free_netdev( dev );
DBG_LEAVE( DbgInfo );
} // wl_device_dealloc
/*============================================================================*/
/*******************************************************************************
* wl_tx_port0()
*******************************************************************************
*
* DESCRIPTION:
*
* The handler routine for Tx over HCF_PORT_0.
*
* PARAMETERS:
*
* skb - a pointer to the sk_buff to transmit.
* dev - a pointer to a net_device structure representing HCF_PORT_0.
*
* RETURNS:
*
* N/A
*
******************************************************************************/
int wl_tx_port0( struct sk_buff *skb, struct net_device *dev )
{
DBG_TX( DbgInfo, "Tx on Port 0\n" );
return wl_tx( skb, dev, HCF_PORT_0 );
#ifdef ENABLE_DMA
return wl_tx_dma( skb, dev, HCF_PORT_0 );
#endif
} // wl_tx_port0
/*============================================================================*/
#ifdef USE_WDS
/*******************************************************************************
* wl_tx_port1()
*******************************************************************************
*
* DESCRIPTION:
*
* The handler routine for Tx over HCF_PORT_1.
*
* PARAMETERS:
*
* skb - a pointer to the sk_buff to transmit.
* dev - a pointer to a net_device structure representing HCF_PORT_1.
*
* RETURNS:
*
* N/A
*
******************************************************************************/
int wl_tx_port1( struct sk_buff *skb, struct net_device *dev )
{
DBG_TX( DbgInfo, "Tx on Port 1\n" );
return wl_tx( skb, dev, HCF_PORT_1 );
} // wl_tx_port1
/*============================================================================*/
/*******************************************************************************
* wl_tx_port2()
*******************************************************************************
*
* DESCRIPTION:
*
* The handler routine for Tx over HCF_PORT_2.
*
* PARAMETERS:
*
* skb - a pointer to the sk_buff to transmit.
* dev - a pointer to a net_device structure representing HCF_PORT_2.
*
* RETURNS:
*
* N/A
*
******************************************************************************/
int wl_tx_port2( struct sk_buff *skb, struct net_device *dev )
{
DBG_TX( DbgInfo, "Tx on Port 2\n" );
return wl_tx( skb, dev, HCF_PORT_2 );
} // wl_tx_port2
/*============================================================================*/
/*******************************************************************************
* wl_tx_port3()
*******************************************************************************
*
* DESCRIPTION:
*
* The handler routine for Tx over HCF_PORT_3.
*
* PARAMETERS:
*
* skb - a pointer to the sk_buff to transmit.
* dev - a pointer to a net_device structure representing HCF_PORT_3.
*
* RETURNS:
*
* N/A
*
******************************************************************************/
int wl_tx_port3( struct sk_buff *skb, struct net_device *dev )
{
DBG_TX( DbgInfo, "Tx on Port 3\n" );
return wl_tx( skb, dev, HCF_PORT_3 );
} // wl_tx_port3
/*============================================================================*/
/*******************************************************************************
* wl_tx_port4()
*******************************************************************************
*
* DESCRIPTION:
*
* The handler routine for Tx over HCF_PORT_4.
*
* PARAMETERS:
*
* skb - a pointer to the sk_buff to transmit.
* dev - a pointer to a net_device structure representing HCF_PORT_4.
*
* RETURNS:
*
* N/A
*
******************************************************************************/
int wl_tx_port4( struct sk_buff *skb, struct net_device *dev )
{
DBG_TX( DbgInfo, "Tx on Port 4\n" );
return wl_tx( skb, dev, HCF_PORT_4 );
} // wl_tx_port4
/*============================================================================*/
/*******************************************************************************
* wl_tx_port5()
*******************************************************************************
*
* DESCRIPTION:
*
* The handler routine for Tx over HCF_PORT_5.
*
* PARAMETERS:
*
* skb - a pointer to the sk_buff to transmit.
* dev - a pointer to a net_device structure representing HCF_PORT_5.
*
* RETURNS:
*
* N/A
*
******************************************************************************/
int wl_tx_port5( struct sk_buff *skb, struct net_device *dev )
{
DBG_TX( DbgInfo, "Tx on Port 5\n" );
return wl_tx( skb, dev, HCF_PORT_5 );
} // wl_tx_port5
/*============================================================================*/
/*******************************************************************************
* wl_tx_port6()
*******************************************************************************
*
* DESCRIPTION:
*
* The handler routine for Tx over HCF_PORT_6.
*
* PARAMETERS:
*
* skb - a pointer to the sk_buff to transmit.
* dev - a pointer to a net_device structure representing HCF_PORT_6.
*
* RETURNS:
*
* N/A
*
******************************************************************************/
int wl_tx_port6( struct sk_buff *skb, struct net_device *dev )
{
DBG_TX( DbgInfo, "Tx on Port 6\n" );
return wl_tx( skb, dev, HCF_PORT_6 );
} // wl_tx_port6
/*============================================================================*/
/*******************************************************************************
* wl_wds_device_alloc()
*******************************************************************************
*
* DESCRIPTION:
*
* Create instances of net_device to represent the WDS ports, and register
* the device's entry points in the net_device structure.
*
* PARAMETERS:
*
* lp - a pointer to the device's private adapter structure
*
* RETURNS:
*
* N/A, but will place pointers to the allocated and initialized net_device
* structs in the private adapter structure.
*
******************************************************************************/
void wl_wds_device_alloc( struct wl_private *lp )
{
int count;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wl_wds_device_alloc" );
DBG_ENTER( DbgInfo );
/* WDS support requires additional net_device structs to be allocated,
so that user space apps can use these virtual devices to specify the
port on which to Tx/Rx */
for( count = 0; count < NUM_WDS_PORTS; count++ ) {
struct net_device *dev_wds = NULL;
dev_wds = kzalloc(sizeof(struct net_device), GFP_KERNEL);
if (!dev_wds) {
DBG_LEAVE(DbgInfo);
return;
}
ether_setup( dev_wds );
lp->wds_port[count].dev = dev_wds;
/* Re-use wl_init for all the devices, as it currently does nothing, but
is required. Re-use the stats/tx_timeout handler for all as well; the
WDS port which is requesting these operations can be determined by
the net_device pointer. Set the private member of all devices to point
to the same net_device struct; that way, all information gets
funnelled through the one "real" net_device. Name the WDS ports
"wds<n>" */
lp->wds_port[count].dev->init = &wl_init;
lp->wds_port[count].dev->get_stats = &wl_stats;
lp->wds_port[count].dev->tx_timeout = &wl_tx_timeout;
lp->wds_port[count].dev->watchdog_timeo = TX_TIMEOUT;
lp->wds_port[count].dev->priv = lp;
sprintf( lp->wds_port[count].dev->name, "wds%d", count );
}
/* Register the Tx handlers */
lp->wds_port[0].dev->hard_start_xmit = &wl_tx_port1;
lp->wds_port[1].dev->hard_start_xmit = &wl_tx_port2;
lp->wds_port[2].dev->hard_start_xmit = &wl_tx_port3;
lp->wds_port[3].dev->hard_start_xmit = &wl_tx_port4;
lp->wds_port[4].dev->hard_start_xmit = &wl_tx_port5;
lp->wds_port[5].dev->hard_start_xmit = &wl_tx_port6;
WL_WDS_NETIF_STOP_QUEUE( lp );
DBG_LEAVE( DbgInfo );
} // wl_wds_device_alloc
/*============================================================================*/
/*******************************************************************************
* wl_wds_device_dealloc()
*******************************************************************************
*
* DESCRIPTION:
*
* Free instances of net_device structures used to support WDS.
*
* PARAMETERS:
*
* lp - a pointer to the device's private adapter structure
*
* RETURNS:
*
* N/A
*
******************************************************************************/
void wl_wds_device_dealloc( struct wl_private *lp )
{
int count;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wl_wds_device_dealloc" );
DBG_ENTER( DbgInfo );
for( count = 0; count < NUM_WDS_PORTS; count++ ) {
struct net_device *dev_wds = NULL;
dev_wds = lp->wds_port[count].dev;
if( dev_wds != NULL ) {
if( dev_wds->flags & IFF_UP ) {
dev_close( dev_wds );
dev_wds->flags &= ~( IFF_UP | IFF_RUNNING );
}
free_netdev(dev_wds);
lp->wds_port[count].dev = NULL;
}
}
DBG_LEAVE( DbgInfo );
} // wl_wds_device_dealloc
/*============================================================================*/
/*******************************************************************************
* wl_wds_netif_start_queue()
*******************************************************************************
*
* DESCRIPTION:
*
* Used to start the netif queues of all the "virtual" network devices
* which represent the WDS ports.
*
* PARAMETERS:
*
* lp - a pointer to the device's private adapter structure
*
* RETURNS:
*
* N/A
*
******************************************************************************/
void wl_wds_netif_start_queue( struct wl_private *lp )
{
int count;
/*------------------------------------------------------------------------*/
if( lp != NULL ) {
for( count = 0; count < NUM_WDS_PORTS; count++ ) {
if( lp->wds_port[count].is_registered &&
lp->wds_port[count].netif_queue_on == FALSE ) {
netif_start_queue( lp->wds_port[count].dev );
lp->wds_port[count].netif_queue_on = TRUE;
}
}
}
} // wl_wds_netif_start_queue
/*============================================================================*/
/*******************************************************************************
* wl_wds_netif_stop_queue()
*******************************************************************************
*
* DESCRIPTION:
*
* Used to stop the netif queues of all the "virtual" network devices
* which represent the WDS ports.
*
* PARAMETERS:
*
* lp - a pointer to the device's private adapter structure
*
* RETURNS:
*
* N/A
*
******************************************************************************/
void wl_wds_netif_stop_queue( struct wl_private *lp )
{
int count;
/*------------------------------------------------------------------------*/
if( lp != NULL ) {
for( count = 0; count < NUM_WDS_PORTS; count++ ) {
if( lp->wds_port[count].is_registered &&
lp->wds_port[count].netif_queue_on == TRUE ) {
netif_stop_queue( lp->wds_port[count].dev );
lp->wds_port[count].netif_queue_on = FALSE;
}
}
}
} // wl_wds_netif_stop_queue
/*============================================================================*/
/*******************************************************************************
* wl_wds_netif_wake_queue()
*******************************************************************************
*
* DESCRIPTION:
*
* Used to wake the netif queues of all the "virtual" network devices
* which represent the WDS ports.
*
* PARAMETERS:
*
* lp - a pointer to the device's private adapter structure
*
* RETURNS:
*
* N/A
*
******************************************************************************/
void wl_wds_netif_wake_queue( struct wl_private *lp )
{
int count;
/*------------------------------------------------------------------------*/
if( lp != NULL ) {
for( count = 0; count < NUM_WDS_PORTS; count++ ) {
if( lp->wds_port[count].is_registered &&
lp->wds_port[count].netif_queue_on == FALSE ) {
netif_wake_queue( lp->wds_port[count].dev );
lp->wds_port[count].netif_queue_on = TRUE;
}
}
}
} // wl_wds_netif_wake_queue
/*============================================================================*/
/*******************************************************************************
* wl_wds_netif_carrier_on()
*******************************************************************************
*
* DESCRIPTION:
*
* Used to signal the network layer that carrier is present on all of the
* "virtual" network devices which represent the WDS ports.
*
* PARAMETERS:
*
* lp - a pointer to the device's private adapter structure
*
* RETURNS:
*
* N/A
*
******************************************************************************/
void wl_wds_netif_carrier_on( struct wl_private *lp )
{
int count;
/*------------------------------------------------------------------------*/
if( lp != NULL ) {
for( count = 0; count < NUM_WDS_PORTS; count++ ) {
if( lp->wds_port[count].is_registered ) {
netif_carrier_on( lp->wds_port[count].dev );
}
}
}
} // wl_wds_netif_carrier_on
/*============================================================================*/
/*******************************************************************************
* wl_wds_netif_carrier_off()
*******************************************************************************
*
* DESCRIPTION:
*
* Used to signal the network layer that carrier is NOT present on all of
* the "virtual" network devices which represent the WDS ports.
*
* PARAMETERS:
*
* lp - a pointer to the device's private adapter structure
*
* RETURNS:
*
* N/A
*
******************************************************************************/
void wl_wds_netif_carrier_off( struct wl_private *lp )
{
int count;
if(lp != NULL) {
for(count = 0; count < NUM_WDS_PORTS; count++) {
if(lp->wds_port[count].is_registered)
netif_carrier_off(lp->wds_port[count].dev);
}
}
} // wl_wds_netif_carrier_off
/*============================================================================*/
#endif /* USE_WDS */
#ifdef ENABLE_DMA
/*******************************************************************************
* wl_send_dma()
*******************************************************************************
*
* DESCRIPTION:
*
* The routine which performs data transmits when using busmaster DMA.
*
* PARAMETERS:
*
* lp - a pointer to the device's wl_private struct.
* skb - a pointer to the network layer's data buffer.
* port - the Hermes port on which to transmit.
*
* RETURNS:
*
* 0 on success
* 1 on error
*
******************************************************************************/
int wl_send_dma( struct wl_private *lp, struct sk_buff *skb, int port )
{
int len;
DESC_STRCT *desc = NULL;
DESC_STRCT *desc_next = NULL;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wl_send_dma" );
if( lp == NULL ) {
DBG_ERROR( DbgInfo, "Private adapter struct is NULL\n" );
return FALSE;
}
if( lp->dev == NULL ) {
DBG_ERROR( DbgInfo, "net_device struct in wl_private is NULL\n" );
return FALSE;
}
/* AGAIN, ALL THE QUEUEING DONE HERE IN I/O MODE IS NOT PERFORMED */
if( skb == NULL ) {
DBG_WARNING (DbgInfo, "Nothing to send.\n");
return FALSE;
}
len = skb->len;
/* Get a free descriptor */
desc = wl_pci_dma_get_tx_packet( lp );
if( desc == NULL ) {
if( lp->netif_queue_on == TRUE ) {
netif_stop_queue( lp->dev );
WL_WDS_NETIF_STOP_QUEUE( lp );
lp->netif_queue_on = FALSE;
dev_kfree_skb( skb );
return 0;
}
}
SET_BUF_CNT( desc, /*HCF_DMA_FD_CNT*/HFS_ADDR_DEST );
SET_BUF_SIZE( desc, HCF_DMA_TX_BUF1_SIZE );
desc_next = desc->next_desc_addr;
if( desc_next->buf_addr == NULL ) {
DBG_ERROR( DbgInfo, "DMA descriptor buf_addr is NULL\n" );
return FALSE;
}
/* Copy the payload into the DMA packet */
memcpy( desc_next->buf_addr, skb->data, len );
SET_BUF_CNT( desc_next, len );
SET_BUF_SIZE( desc_next, HCF_MAX_PACKET_SIZE );
hcf_dma_tx_put( &( lp->hcfCtx ), desc, 0 );
/* Free the skb and perform queue cleanup, as the buffer was
transmitted successfully */
dev_kfree_skb( skb );
return TRUE;
} // wl_send_dma
/*============================================================================*/
/*******************************************************************************
* wl_rx_dma()
*******************************************************************************
*
* DESCRIPTION:
*
* The routine which performs data reception when using busmaster DMA.
*
* PARAMETERS:
*
* dev - a pointer to the device's net_device structure.
*
* RETURNS:
*
* 0 on success
* 1 on error
*
******************************************************************************/
int wl_rx_dma( struct net_device *dev )
{
int port;
hcf_16 pktlen;
hcf_16 hfs_stat;
struct sk_buff *skb;
struct wl_private *lp = NULL;
DESC_STRCT *desc, *desc_next;
//CFG_MB_INFO_RANGE2_STRCT x;
/*------------------------------------------------------------------------*/
DBG_FUNC("wl_rx")
DBG_PARAM(DbgInfo, "dev", "%s (0x%p)", dev->name, dev);
if((( lp = dev->priv ) != NULL ) &&
!( lp->flags & WVLAN2_UIL_BUSY )) {
#ifdef USE_RTS
if( lp->useRTS == 1 ) {
DBG_PRINT( "RTS: We're getting an Rx...\n" );
return -EIO;
}
#endif /* USE_RTS */
//if( lp->dma.status == 0 )
//{
desc = hcf_dma_rx_get( &( lp->hcfCtx ));
if( desc != NULL )
{
/* Check and see if we rcvd. a WMP frame */
/*
if((( *(hcf_8 *)&desc->buf_addr[HFS_STAT] ) &
( HFS_STAT_MSG_TYPE | HFS_STAT_ERR )) == HFS_STAT_WMP_MSG )
{
DBG_TRACE( DbgInfo, "Got a WMP frame\n" );
x.len = sizeof( CFG_MB_INFO_RANGE2_STRCT ) / sizeof( hcf_16 );
x.typ = CFG_MB_INFO;
x.base_typ = CFG_WMP;
x.frag_cnt = 2;
x.frag_buf[0].frag_len = GET_BUF_CNT( descp ) / sizeof( hcf_16 );
x.frag_buf[0].frag_addr = (hcf_8 *) descp->buf_addr ;
x.frag_buf[1].frag_len = ( GET_BUF_CNT( descp->next_desc_addr ) + 1 ) / sizeof( hcf_16 );
x.frag_buf[1].frag_addr = (hcf_8 *) descp->next_desc_addr->buf_addr ;
hcf_put_info( &( lp->hcfCtx ), (LTVP)&x );
}
*/
desc_next = desc->next_desc_addr;
/* Make sure the buffer isn't empty */
if( GET_BUF_CNT( desc ) == 0 ) {
DBG_WARNING( DbgInfo, "Buffer is empty!\n" );
/* Give the descriptor back to the HCF */
hcf_dma_rx_put( &( lp->hcfCtx ), desc );
return -EIO;
}
/* Read the HFS_STAT register from the lookahead buffer */
hfs_stat = (hcf_16)( desc->buf_addr[HFS_STAT/2] );
/* Make sure the frame isn't bad */
if(( hfs_stat & HFS_STAT_ERR ) != HCF_SUCCESS )
{
DBG_WARNING( DbgInfo, "HFS_STAT_ERROR (0x%x) in Rx Packet\n",
desc->buf_addr[HFS_STAT/2] );
/* Give the descriptor back to the HCF */
hcf_dma_rx_put( &( lp->hcfCtx ), desc );
return -EIO;
}
/* Determine what port this packet is for */
port = ( hfs_stat >> 8 ) & 0x0007;
DBG_RX( DbgInfo, "Rx frame for port %d\n", port );
pktlen = GET_BUF_CNT(desc_next);
if (pktlen != 0) {
skb = ALLOC_SKB(pktlen);
if (skb != NULL) {
switch( port ) {
#ifdef USE_WDS
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
skb->dev = lp->wds_port[port-1].dev;
break;
#endif /* USE_WDS */
case 0:
default:
skb->dev = dev;
break;
}
GET_PACKET_DMA( skb->dev, skb, pktlen );
/* Give the descriptor back to the HCF */
hcf_dma_rx_put( &( lp->hcfCtx ), desc );
netif_rx( skb );
if( port == 0 ) {
lp->stats.rx_packets++;
lp->stats.rx_bytes += pktlen;
}
#ifdef USE_WDS
else
{
lp->wds_port[port-1].stats.rx_packets++;
lp->wds_port[port-1].stats.rx_bytes += pktlen;
}
#endif /* USE_WDS */
dev->last_rx = jiffies;
} else {
DBG_ERROR( DbgInfo, "Could not alloc skb\n" );
if( port == 0 )
{
lp->stats.rx_dropped++;
}
#ifdef USE_WDS
else
{
lp->wds_port[port-1].stats.rx_dropped++;
}
#endif /* USE_WDS */
}
}
}
//}
}
return 0;
} // wl_rx_dma
/*============================================================================*/
#endif // ENABLE_DMA
| gpl-2.0 |
nosnilwar/linux-raw-gov-2.6.38.8 | drivers/scsi/bfa/bfad_attr.c | 2638 | 26349 | /*
* Copyright (c) 2005-2010 Brocade Communications Systems, Inc.
* All rights reserved
* www.brocade.com
*
* Linux driver for Brocade Fibre Channel Host Bus Adapter.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License (GPL) Version 2 as
* published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*/
/*
* bfa_attr.c Linux driver configuration interface module.
*/
#include "bfad_drv.h"
#include "bfad_im.h"
/*
* FC transport template entry, get SCSI target port ID.
*/
static void
bfad_im_get_starget_port_id(struct scsi_target *starget)
{
struct Scsi_Host *shost;
struct bfad_im_port_s *im_port;
struct bfad_s *bfad;
struct bfad_itnim_s *itnim = NULL;
u32 fc_id = -1;
unsigned long flags;
shost = dev_to_shost(starget->dev.parent);
im_port = (struct bfad_im_port_s *) shost->hostdata[0];
bfad = im_port->bfad;
spin_lock_irqsave(&bfad->bfad_lock, flags);
itnim = bfad_get_itnim(im_port, starget->id);
if (itnim)
fc_id = bfa_fcs_itnim_get_fcid(&itnim->fcs_itnim);
fc_starget_port_id(starget) = fc_id;
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
}
/*
* FC transport template entry, get SCSI target nwwn.
*/
static void
bfad_im_get_starget_node_name(struct scsi_target *starget)
{
struct Scsi_Host *shost;
struct bfad_im_port_s *im_port;
struct bfad_s *bfad;
struct bfad_itnim_s *itnim = NULL;
u64 node_name = 0;
unsigned long flags;
shost = dev_to_shost(starget->dev.parent);
im_port = (struct bfad_im_port_s *) shost->hostdata[0];
bfad = im_port->bfad;
spin_lock_irqsave(&bfad->bfad_lock, flags);
itnim = bfad_get_itnim(im_port, starget->id);
if (itnim)
node_name = bfa_fcs_itnim_get_nwwn(&itnim->fcs_itnim);
fc_starget_node_name(starget) = cpu_to_be64(node_name);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
}
/*
* FC transport template entry, get SCSI target pwwn.
*/
static void
bfad_im_get_starget_port_name(struct scsi_target *starget)
{
struct Scsi_Host *shost;
struct bfad_im_port_s *im_port;
struct bfad_s *bfad;
struct bfad_itnim_s *itnim = NULL;
u64 port_name = 0;
unsigned long flags;
shost = dev_to_shost(starget->dev.parent);
im_port = (struct bfad_im_port_s *) shost->hostdata[0];
bfad = im_port->bfad;
spin_lock_irqsave(&bfad->bfad_lock, flags);
itnim = bfad_get_itnim(im_port, starget->id);
if (itnim)
port_name = bfa_fcs_itnim_get_pwwn(&itnim->fcs_itnim);
fc_starget_port_name(starget) = cpu_to_be64(port_name);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
}
/*
* FC transport template entry, get SCSI host port ID.
*/
static void
bfad_im_get_host_port_id(struct Scsi_Host *shost)
{
struct bfad_im_port_s *im_port =
(struct bfad_im_port_s *) shost->hostdata[0];
struct bfad_port_s *port = im_port->port;
fc_host_port_id(shost) =
bfa_hton3b(bfa_fcs_lport_get_fcid(port->fcs_port));
}
/*
* FC transport template entry, get SCSI host port type.
*/
static void
bfad_im_get_host_port_type(struct Scsi_Host *shost)
{
struct bfad_im_port_s *im_port =
(struct bfad_im_port_s *) shost->hostdata[0];
struct bfad_s *bfad = im_port->bfad;
struct bfa_lport_attr_s port_attr;
bfa_fcs_lport_get_attr(&bfad->bfa_fcs.fabric.bport, &port_attr);
switch (port_attr.port_type) {
case BFA_PORT_TYPE_NPORT:
fc_host_port_type(shost) = FC_PORTTYPE_NPORT;
break;
case BFA_PORT_TYPE_NLPORT:
fc_host_port_type(shost) = FC_PORTTYPE_NLPORT;
break;
case BFA_PORT_TYPE_P2P:
fc_host_port_type(shost) = FC_PORTTYPE_PTP;
break;
case BFA_PORT_TYPE_LPORT:
fc_host_port_type(shost) = FC_PORTTYPE_LPORT;
break;
default:
fc_host_port_type(shost) = FC_PORTTYPE_UNKNOWN;
break;
}
}
/*
* FC transport template entry, get SCSI host port state.
*/
static void
bfad_im_get_host_port_state(struct Scsi_Host *shost)
{
struct bfad_im_port_s *im_port =
(struct bfad_im_port_s *) shost->hostdata[0];
struct bfad_s *bfad = im_port->bfad;
struct bfa_port_attr_s attr;
bfa_fcport_get_attr(&bfad->bfa, &attr);
switch (attr.port_state) {
case BFA_PORT_ST_LINKDOWN:
fc_host_port_state(shost) = FC_PORTSTATE_LINKDOWN;
break;
case BFA_PORT_ST_LINKUP:
fc_host_port_state(shost) = FC_PORTSTATE_ONLINE;
break;
case BFA_PORT_ST_DISABLED:
case BFA_PORT_ST_STOPPED:
case BFA_PORT_ST_IOCDOWN:
case BFA_PORT_ST_IOCDIS:
fc_host_port_state(shost) = FC_PORTSTATE_OFFLINE;
break;
case BFA_PORT_ST_UNINIT:
case BFA_PORT_ST_ENABLING_QWAIT:
case BFA_PORT_ST_ENABLING:
case BFA_PORT_ST_DISABLING_QWAIT:
case BFA_PORT_ST_DISABLING:
default:
fc_host_port_state(shost) = FC_PORTSTATE_UNKNOWN;
break;
}
}
/*
* FC transport template entry, get SCSI host active fc4s.
*/
static void
bfad_im_get_host_active_fc4s(struct Scsi_Host *shost)
{
struct bfad_im_port_s *im_port =
(struct bfad_im_port_s *) shost->hostdata[0];
struct bfad_port_s *port = im_port->port;
memset(fc_host_active_fc4s(shost), 0,
sizeof(fc_host_active_fc4s(shost)));
if (port->supported_fc4s & BFA_LPORT_ROLE_FCP_IM)
fc_host_active_fc4s(shost)[2] = 1;
fc_host_active_fc4s(shost)[7] = 1;
}
/*
* FC transport template entry, get SCSI host link speed.
*/
static void
bfad_im_get_host_speed(struct Scsi_Host *shost)
{
struct bfad_im_port_s *im_port =
(struct bfad_im_port_s *) shost->hostdata[0];
struct bfad_s *bfad = im_port->bfad;
struct bfa_port_attr_s attr;
bfa_fcport_get_attr(&bfad->bfa, &attr);
switch (attr.speed) {
case BFA_PORT_SPEED_10GBPS:
fc_host_speed(shost) = FC_PORTSPEED_10GBIT;
break;
case BFA_PORT_SPEED_8GBPS:
fc_host_speed(shost) = FC_PORTSPEED_8GBIT;
break;
case BFA_PORT_SPEED_4GBPS:
fc_host_speed(shost) = FC_PORTSPEED_4GBIT;
break;
case BFA_PORT_SPEED_2GBPS:
fc_host_speed(shost) = FC_PORTSPEED_2GBIT;
break;
case BFA_PORT_SPEED_1GBPS:
fc_host_speed(shost) = FC_PORTSPEED_1GBIT;
break;
default:
fc_host_speed(shost) = FC_PORTSPEED_UNKNOWN;
break;
}
}
/*
* FC transport template entry, get SCSI host port type.
*/
static void
bfad_im_get_host_fabric_name(struct Scsi_Host *shost)
{
struct bfad_im_port_s *im_port =
(struct bfad_im_port_s *) shost->hostdata[0];
struct bfad_port_s *port = im_port->port;
wwn_t fabric_nwwn = 0;
fabric_nwwn = bfa_fcs_lport_get_fabric_name(port->fcs_port);
fc_host_fabric_name(shost) = cpu_to_be64(fabric_nwwn);
}
/*
* FC transport template entry, get BFAD statistics.
*/
static struct fc_host_statistics *
bfad_im_get_stats(struct Scsi_Host *shost)
{
struct bfad_im_port_s *im_port =
(struct bfad_im_port_s *) shost->hostdata[0];
struct bfad_s *bfad = im_port->bfad;
struct bfad_hal_comp fcomp;
union bfa_port_stats_u *fcstats;
struct fc_host_statistics *hstats;
bfa_status_t rc;
unsigned long flags;
fcstats = kzalloc(sizeof(union bfa_port_stats_u), GFP_KERNEL);
if (fcstats == NULL)
return NULL;
hstats = &bfad->link_stats;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
memset(hstats, 0, sizeof(struct fc_host_statistics));
rc = bfa_port_get_stats(BFA_FCPORT(&bfad->bfa),
fcstats, bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (rc != BFA_STATUS_OK)
return NULL;
wait_for_completion(&fcomp.comp);
/* Fill the fc_host_statistics structure */
hstats->seconds_since_last_reset = fcstats->fc.secs_reset;
hstats->tx_frames = fcstats->fc.tx_frames;
hstats->tx_words = fcstats->fc.tx_words;
hstats->rx_frames = fcstats->fc.rx_frames;
hstats->rx_words = fcstats->fc.rx_words;
hstats->lip_count = fcstats->fc.lip_count;
hstats->nos_count = fcstats->fc.nos_count;
hstats->error_frames = fcstats->fc.error_frames;
hstats->dumped_frames = fcstats->fc.dropped_frames;
hstats->link_failure_count = fcstats->fc.link_failures;
hstats->loss_of_sync_count = fcstats->fc.loss_of_syncs;
hstats->loss_of_signal_count = fcstats->fc.loss_of_signals;
hstats->prim_seq_protocol_err_count = fcstats->fc.primseq_errs;
hstats->invalid_crc_count = fcstats->fc.invalid_crcs;
kfree(fcstats);
return hstats;
}
/*
* FC transport template entry, reset BFAD statistics.
*/
static void
bfad_im_reset_stats(struct Scsi_Host *shost)
{
struct bfad_im_port_s *im_port =
(struct bfad_im_port_s *) shost->hostdata[0];
struct bfad_s *bfad = im_port->bfad;
struct bfad_hal_comp fcomp;
unsigned long flags;
bfa_status_t rc;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
rc = bfa_port_clear_stats(BFA_FCPORT(&bfad->bfa), bfad_hcb_comp,
&fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (rc != BFA_STATUS_OK)
return;
wait_for_completion(&fcomp.comp);
return;
}
/*
* FC transport template entry, get rport loss timeout.
*/
static void
bfad_im_get_rport_loss_tmo(struct fc_rport *rport)
{
struct bfad_itnim_data_s *itnim_data = rport->dd_data;
struct bfad_itnim_s *itnim = itnim_data->itnim;
struct bfad_s *bfad = itnim->im->bfad;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
rport->dev_loss_tmo = bfa_fcpim_path_tov_get(&bfad->bfa);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
}
/*
* FC transport template entry, set rport loss timeout.
*/
static void
bfad_im_set_rport_loss_tmo(struct fc_rport *rport, u32 timeout)
{
struct bfad_itnim_data_s *itnim_data = rport->dd_data;
struct bfad_itnim_s *itnim = itnim_data->itnim;
struct bfad_s *bfad = itnim->im->bfad;
unsigned long flags;
if (timeout > 0) {
spin_lock_irqsave(&bfad->bfad_lock, flags);
bfa_fcpim_path_tov_set(&bfad->bfa, timeout);
rport->dev_loss_tmo = bfa_fcpim_path_tov_get(&bfad->bfa);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
}
}
static int
bfad_im_vport_create(struct fc_vport *fc_vport, bool disable)
{
char *vname = fc_vport->symbolic_name;
struct Scsi_Host *shost = fc_vport->shost;
struct bfad_im_port_s *im_port =
(struct bfad_im_port_s *) shost->hostdata[0];
struct bfad_s *bfad = im_port->bfad;
struct bfa_lport_cfg_s port_cfg;
struct bfad_vport_s *vp;
int status = 0, rc;
unsigned long flags;
memset(&port_cfg, 0, sizeof(port_cfg));
u64_to_wwn(fc_vport->node_name, (u8 *)&port_cfg.nwwn);
u64_to_wwn(fc_vport->port_name, (u8 *)&port_cfg.pwwn);
if (strlen(vname) > 0)
strcpy((char *)&port_cfg.sym_name, vname);
port_cfg.roles = BFA_LPORT_ROLE_FCP_IM;
spin_lock_irqsave(&bfad->bfad_lock, flags);
list_for_each_entry(vp, &bfad->pbc_vport_list, list_entry) {
if (port_cfg.pwwn ==
vp->fcs_vport.lport.port_cfg.pwwn) {
port_cfg.preboot_vp =
vp->fcs_vport.lport.port_cfg.preboot_vp;
break;
}
}
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
rc = bfad_vport_create(bfad, 0, &port_cfg, &fc_vport->dev);
if (rc == BFA_STATUS_OK) {
struct bfad_vport_s *vport;
struct bfa_fcs_vport_s *fcs_vport;
struct Scsi_Host *vshost;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_vport = bfa_fcs_vport_lookup(&bfad->bfa_fcs, 0,
port_cfg.pwwn);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (fcs_vport == NULL)
return VPCERR_BAD_WWN;
fc_vport_set_state(fc_vport, FC_VPORT_ACTIVE);
if (disable) {
spin_lock_irqsave(&bfad->bfad_lock, flags);
bfa_fcs_vport_stop(fcs_vport);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
fc_vport_set_state(fc_vport, FC_VPORT_DISABLED);
}
vport = fcs_vport->vport_drv;
vshost = vport->drv_port.im_port->shost;
fc_host_node_name(vshost) = wwn_to_u64((u8 *)&port_cfg.nwwn);
fc_host_port_name(vshost) = wwn_to_u64((u8 *)&port_cfg.pwwn);
fc_vport->dd_data = vport;
vport->drv_port.im_port->fc_vport = fc_vport;
} else if (rc == BFA_STATUS_INVALID_WWN)
return VPCERR_BAD_WWN;
else if (rc == BFA_STATUS_VPORT_EXISTS)
return VPCERR_BAD_WWN;
else if (rc == BFA_STATUS_VPORT_MAX)
return VPCERR_NO_FABRIC_SUPP;
else if (rc == BFA_STATUS_VPORT_WWN_BP)
return VPCERR_BAD_WWN;
else
return FC_VPORT_FAILED;
return status;
}
static int
bfad_im_vport_delete(struct fc_vport *fc_vport)
{
struct bfad_vport_s *vport = (struct bfad_vport_s *)fc_vport->dd_data;
struct bfad_im_port_s *im_port =
(struct bfad_im_port_s *) vport->drv_port.im_port;
struct bfad_s *bfad = im_port->bfad;
struct bfad_port_s *port;
struct bfa_fcs_vport_s *fcs_vport;
struct Scsi_Host *vshost;
wwn_t pwwn;
int rc;
unsigned long flags;
struct completion fcomp;
if (im_port->flags & BFAD_PORT_DELETE)
goto free_scsi_host;
port = im_port->port;
vshost = vport->drv_port.im_port->shost;
u64_to_wwn(fc_host_port_name(vshost), (u8 *)&pwwn);
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_vport = bfa_fcs_vport_lookup(&bfad->bfa_fcs, 0, pwwn);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (fcs_vport == NULL)
return VPCERR_BAD_WWN;
vport->drv_port.flags |= BFAD_PORT_DELETE;
vport->comp_del = &fcomp;
init_completion(vport->comp_del);
spin_lock_irqsave(&bfad->bfad_lock, flags);
rc = bfa_fcs_vport_delete(&vport->fcs_vport);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (rc == BFA_STATUS_PBC) {
vport->drv_port.flags &= ~BFAD_PORT_DELETE;
vport->comp_del = NULL;
return -1;
}
wait_for_completion(vport->comp_del);
free_scsi_host:
bfad_scsi_host_free(bfad, im_port);
kfree(vport);
return 0;
}
static int
bfad_im_vport_disable(struct fc_vport *fc_vport, bool disable)
{
struct bfad_vport_s *vport;
struct bfad_s *bfad;
struct bfa_fcs_vport_s *fcs_vport;
struct Scsi_Host *vshost;
wwn_t pwwn;
unsigned long flags;
vport = (struct bfad_vport_s *)fc_vport->dd_data;
bfad = vport->drv_port.bfad;
vshost = vport->drv_port.im_port->shost;
u64_to_wwn(fc_host_port_name(vshost), (u8 *)&pwwn);
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_vport = bfa_fcs_vport_lookup(&bfad->bfa_fcs, 0, pwwn);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (fcs_vport == NULL)
return VPCERR_BAD_WWN;
if (disable) {
bfa_fcs_vport_stop(fcs_vport);
fc_vport_set_state(fc_vport, FC_VPORT_DISABLED);
} else {
bfa_fcs_vport_start(fcs_vport);
fc_vport_set_state(fc_vport, FC_VPORT_ACTIVE);
}
return 0;
}
struct fc_function_template bfad_im_fc_function_template = {
/* Target dynamic attributes */
.get_starget_port_id = bfad_im_get_starget_port_id,
.show_starget_port_id = 1,
.get_starget_node_name = bfad_im_get_starget_node_name,
.show_starget_node_name = 1,
.get_starget_port_name = bfad_im_get_starget_port_name,
.show_starget_port_name = 1,
/* Host dynamic attribute */
.get_host_port_id = bfad_im_get_host_port_id,
.show_host_port_id = 1,
/* Host fixed attributes */
.show_host_node_name = 1,
.show_host_port_name = 1,
.show_host_supported_classes = 1,
.show_host_supported_fc4s = 1,
.show_host_supported_speeds = 1,
.show_host_maxframe_size = 1,
/* More host dynamic attributes */
.show_host_port_type = 1,
.get_host_port_type = bfad_im_get_host_port_type,
.show_host_port_state = 1,
.get_host_port_state = bfad_im_get_host_port_state,
.show_host_active_fc4s = 1,
.get_host_active_fc4s = bfad_im_get_host_active_fc4s,
.show_host_speed = 1,
.get_host_speed = bfad_im_get_host_speed,
.show_host_fabric_name = 1,
.get_host_fabric_name = bfad_im_get_host_fabric_name,
.show_host_symbolic_name = 1,
/* Statistics */
.get_fc_host_stats = bfad_im_get_stats,
.reset_fc_host_stats = bfad_im_reset_stats,
/* Allocation length for host specific data */
.dd_fcrport_size = sizeof(struct bfad_itnim_data_s *),
/* Remote port fixed attributes */
.show_rport_maxframe_size = 1,
.show_rport_supported_classes = 1,
.show_rport_dev_loss_tmo = 1,
.get_rport_dev_loss_tmo = bfad_im_get_rport_loss_tmo,
.set_rport_dev_loss_tmo = bfad_im_set_rport_loss_tmo,
.vport_create = bfad_im_vport_create,
.vport_delete = bfad_im_vport_delete,
.vport_disable = bfad_im_vport_disable,
};
struct fc_function_template bfad_im_vport_fc_function_template = {
/* Target dynamic attributes */
.get_starget_port_id = bfad_im_get_starget_port_id,
.show_starget_port_id = 1,
.get_starget_node_name = bfad_im_get_starget_node_name,
.show_starget_node_name = 1,
.get_starget_port_name = bfad_im_get_starget_port_name,
.show_starget_port_name = 1,
/* Host dynamic attribute */
.get_host_port_id = bfad_im_get_host_port_id,
.show_host_port_id = 1,
/* Host fixed attributes */
.show_host_node_name = 1,
.show_host_port_name = 1,
.show_host_supported_classes = 1,
.show_host_supported_fc4s = 1,
.show_host_supported_speeds = 1,
.show_host_maxframe_size = 1,
/* More host dynamic attributes */
.show_host_port_type = 1,
.get_host_port_type = bfad_im_get_host_port_type,
.show_host_port_state = 1,
.get_host_port_state = bfad_im_get_host_port_state,
.show_host_active_fc4s = 1,
.get_host_active_fc4s = bfad_im_get_host_active_fc4s,
.show_host_speed = 1,
.get_host_speed = bfad_im_get_host_speed,
.show_host_fabric_name = 1,
.get_host_fabric_name = bfad_im_get_host_fabric_name,
.show_host_symbolic_name = 1,
/* Statistics */
.get_fc_host_stats = bfad_im_get_stats,
.reset_fc_host_stats = bfad_im_reset_stats,
/* Allocation length for host specific data */
.dd_fcrport_size = sizeof(struct bfad_itnim_data_s *),
/* Remote port fixed attributes */
.show_rport_maxframe_size = 1,
.show_rport_supported_classes = 1,
.show_rport_dev_loss_tmo = 1,
.get_rport_dev_loss_tmo = bfad_im_get_rport_loss_tmo,
.set_rport_dev_loss_tmo = bfad_im_set_rport_loss_tmo,
};
/*
* Scsi_Host_attrs SCSI host attributes
*/
static ssize_t
bfad_im_serial_num_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct Scsi_Host *shost = class_to_shost(dev);
struct bfad_im_port_s *im_port =
(struct bfad_im_port_s *) shost->hostdata[0];
struct bfad_s *bfad = im_port->bfad;
char serial_num[BFA_ADAPTER_SERIAL_NUM_LEN];
bfa_get_adapter_serial_num(&bfad->bfa, serial_num);
return snprintf(buf, PAGE_SIZE, "%s\n", serial_num);
}
static ssize_t
bfad_im_model_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct Scsi_Host *shost = class_to_shost(dev);
struct bfad_im_port_s *im_port =
(struct bfad_im_port_s *) shost->hostdata[0];
struct bfad_s *bfad = im_port->bfad;
char model[BFA_ADAPTER_MODEL_NAME_LEN];
bfa_get_adapter_model(&bfad->bfa, model);
return snprintf(buf, PAGE_SIZE, "%s\n", model);
}
static ssize_t
bfad_im_model_desc_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct Scsi_Host *shost = class_to_shost(dev);
struct bfad_im_port_s *im_port =
(struct bfad_im_port_s *) shost->hostdata[0];
struct bfad_s *bfad = im_port->bfad;
char model[BFA_ADAPTER_MODEL_NAME_LEN];
char model_descr[BFA_ADAPTER_MODEL_DESCR_LEN];
bfa_get_adapter_model(&bfad->bfa, model);
if (!strcmp(model, "Brocade-425"))
snprintf(model_descr, BFA_ADAPTER_MODEL_DESCR_LEN,
"Brocade 4Gbps PCIe dual port FC HBA");
else if (!strcmp(model, "Brocade-825"))
snprintf(model_descr, BFA_ADAPTER_MODEL_DESCR_LEN,
"Brocade 8Gbps PCIe dual port FC HBA");
else if (!strcmp(model, "Brocade-42B"))
snprintf(model_descr, BFA_ADAPTER_MODEL_DESCR_LEN,
"HP 4Gbps PCIe dual port FC HBA");
else if (!strcmp(model, "Brocade-82B"))
snprintf(model_descr, BFA_ADAPTER_MODEL_DESCR_LEN,
"HP 8Gbps PCIe dual port FC HBA");
else if (!strcmp(model, "Brocade-1010"))
snprintf(model_descr, BFA_ADAPTER_MODEL_DESCR_LEN,
"Brocade 10Gbps single port CNA");
else if (!strcmp(model, "Brocade-1020"))
snprintf(model_descr, BFA_ADAPTER_MODEL_DESCR_LEN,
"Brocade 10Gbps dual port CNA");
else if (!strcmp(model, "Brocade-1007"))
snprintf(model_descr, BFA_ADAPTER_MODEL_DESCR_LEN,
"Brocade 10Gbps CNA");
else if (!strcmp(model, "Brocade-415"))
snprintf(model_descr, BFA_ADAPTER_MODEL_DESCR_LEN,
"Brocade 4Gbps PCIe single port FC HBA");
else if (!strcmp(model, "Brocade-815"))
snprintf(model_descr, BFA_ADAPTER_MODEL_DESCR_LEN,
"Brocade 8Gbps PCIe single port FC HBA");
else if (!strcmp(model, "Brocade-41B"))
snprintf(model_descr, BFA_ADAPTER_MODEL_DESCR_LEN,
"HP 4Gbps PCIe single port FC HBA");
else if (!strcmp(model, "Brocade-81B"))
snprintf(model_descr, BFA_ADAPTER_MODEL_DESCR_LEN,
"HP 8Gbps PCIe single port FC HBA");
else if (!strcmp(model, "Brocade-804"))
snprintf(model_descr, BFA_ADAPTER_MODEL_DESCR_LEN,
"HP Bladesystem C-class 8Gbps FC HBA");
else if (!strcmp(model, "Brocade-902"))
snprintf(model_descr, BFA_ADAPTER_MODEL_DESCR_LEN,
"Brocade 10Gbps CNA");
else
snprintf(model_descr, BFA_ADAPTER_MODEL_DESCR_LEN,
"Invalid Model");
return snprintf(buf, PAGE_SIZE, "%s\n", model_descr);
}
static ssize_t
bfad_im_node_name_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct Scsi_Host *shost = class_to_shost(dev);
struct bfad_im_port_s *im_port =
(struct bfad_im_port_s *) shost->hostdata[0];
struct bfad_port_s *port = im_port->port;
u64 nwwn;
nwwn = bfa_fcs_lport_get_nwwn(port->fcs_port);
return snprintf(buf, PAGE_SIZE, "0x%llx\n", cpu_to_be64(nwwn));
}
static ssize_t
bfad_im_symbolic_name_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct Scsi_Host *shost = class_to_shost(dev);
struct bfad_im_port_s *im_port =
(struct bfad_im_port_s *) shost->hostdata[0];
struct bfad_s *bfad = im_port->bfad;
struct bfa_lport_attr_s port_attr;
char symname[BFA_SYMNAME_MAXLEN];
bfa_fcs_lport_get_attr(&bfad->bfa_fcs.fabric.bport, &port_attr);
strncpy(symname, port_attr.port_cfg.sym_name.symname,
BFA_SYMNAME_MAXLEN);
return snprintf(buf, PAGE_SIZE, "%s\n", symname);
}
static ssize_t
bfad_im_hw_version_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct Scsi_Host *shost = class_to_shost(dev);
struct bfad_im_port_s *im_port =
(struct bfad_im_port_s *) shost->hostdata[0];
struct bfad_s *bfad = im_port->bfad;
char hw_ver[BFA_VERSION_LEN];
bfa_get_pci_chip_rev(&bfad->bfa, hw_ver);
return snprintf(buf, PAGE_SIZE, "%s\n", hw_ver);
}
static ssize_t
bfad_im_drv_version_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
return snprintf(buf, PAGE_SIZE, "%s\n", BFAD_DRIVER_VERSION);
}
static ssize_t
bfad_im_optionrom_version_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct Scsi_Host *shost = class_to_shost(dev);
struct bfad_im_port_s *im_port =
(struct bfad_im_port_s *) shost->hostdata[0];
struct bfad_s *bfad = im_port->bfad;
char optrom_ver[BFA_VERSION_LEN];
bfa_get_adapter_optrom_ver(&bfad->bfa, optrom_ver);
return snprintf(buf, PAGE_SIZE, "%s\n", optrom_ver);
}
static ssize_t
bfad_im_fw_version_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct Scsi_Host *shost = class_to_shost(dev);
struct bfad_im_port_s *im_port =
(struct bfad_im_port_s *) shost->hostdata[0];
struct bfad_s *bfad = im_port->bfad;
char fw_ver[BFA_VERSION_LEN];
bfa_get_adapter_fw_ver(&bfad->bfa, fw_ver);
return snprintf(buf, PAGE_SIZE, "%s\n", fw_ver);
}
static ssize_t
bfad_im_num_of_ports_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct Scsi_Host *shost = class_to_shost(dev);
struct bfad_im_port_s *im_port =
(struct bfad_im_port_s *) shost->hostdata[0];
struct bfad_s *bfad = im_port->bfad;
return snprintf(buf, PAGE_SIZE, "%d\n",
bfa_get_nports(&bfad->bfa));
}
static ssize_t
bfad_im_drv_name_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
return snprintf(buf, PAGE_SIZE, "%s\n", BFAD_DRIVER_NAME);
}
static ssize_t
bfad_im_num_of_discovered_ports_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct Scsi_Host *shost = class_to_shost(dev);
struct bfad_im_port_s *im_port =
(struct bfad_im_port_s *) shost->hostdata[0];
struct bfad_port_s *port = im_port->port;
struct bfad_s *bfad = im_port->bfad;
int nrports = 2048;
wwn_t *rports = NULL;
unsigned long flags;
rports = kzalloc(sizeof(wwn_t) * nrports , GFP_ATOMIC);
if (rports == NULL)
return snprintf(buf, PAGE_SIZE, "Failed\n");
spin_lock_irqsave(&bfad->bfad_lock, flags);
bfa_fcs_lport_get_rports(port->fcs_port, rports, &nrports);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
kfree(rports);
return snprintf(buf, PAGE_SIZE, "%d\n", nrports);
}
static DEVICE_ATTR(serial_number, S_IRUGO,
bfad_im_serial_num_show, NULL);
static DEVICE_ATTR(model, S_IRUGO, bfad_im_model_show, NULL);
static DEVICE_ATTR(model_description, S_IRUGO,
bfad_im_model_desc_show, NULL);
static DEVICE_ATTR(node_name, S_IRUGO, bfad_im_node_name_show, NULL);
static DEVICE_ATTR(symbolic_name, S_IRUGO,
bfad_im_symbolic_name_show, NULL);
static DEVICE_ATTR(hardware_version, S_IRUGO,
bfad_im_hw_version_show, NULL);
static DEVICE_ATTR(driver_version, S_IRUGO,
bfad_im_drv_version_show, NULL);
static DEVICE_ATTR(option_rom_version, S_IRUGO,
bfad_im_optionrom_version_show, NULL);
static DEVICE_ATTR(firmware_version, S_IRUGO,
bfad_im_fw_version_show, NULL);
static DEVICE_ATTR(number_of_ports, S_IRUGO,
bfad_im_num_of_ports_show, NULL);
static DEVICE_ATTR(driver_name, S_IRUGO, bfad_im_drv_name_show, NULL);
static DEVICE_ATTR(number_of_discovered_ports, S_IRUGO,
bfad_im_num_of_discovered_ports_show, NULL);
struct device_attribute *bfad_im_host_attrs[] = {
&dev_attr_serial_number,
&dev_attr_model,
&dev_attr_model_description,
&dev_attr_node_name,
&dev_attr_symbolic_name,
&dev_attr_hardware_version,
&dev_attr_driver_version,
&dev_attr_option_rom_version,
&dev_attr_firmware_version,
&dev_attr_number_of_ports,
&dev_attr_driver_name,
&dev_attr_number_of_discovered_ports,
NULL,
};
struct device_attribute *bfad_im_vport_attrs[] = {
&dev_attr_serial_number,
&dev_attr_model,
&dev_attr_model_description,
&dev_attr_node_name,
&dev_attr_symbolic_name,
&dev_attr_hardware_version,
&dev_attr_driver_version,
&dev_attr_option_rom_version,
&dev_attr_firmware_version,
&dev_attr_number_of_ports,
&dev_attr_driver_name,
&dev_attr_number_of_discovered_ports,
NULL,
};
| gpl-2.0 |
Grarak/android_kernel_oneplus_msm8996 | drivers/leds/leds-lp8788.c | 3150 | 4437 | /*
* TI LP8788 MFD - keyled driver
*
* Copyright 2012 Texas Instruments
*
* Author: Milo(Woogyom) Kim <milo.kim@ti.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/err.h>
#include <linux/platform_device.h>
#include <linux/leds.h>
#include <linux/mutex.h>
#include <linux/mfd/lp8788.h>
#include <linux/mfd/lp8788-isink.h>
#define MAX_BRIGHTNESS LP8788_ISINK_MAX_PWM
#define DEFAULT_LED_NAME "keyboard-backlight"
struct lp8788_led {
struct lp8788 *lp;
struct mutex lock;
struct work_struct work;
struct led_classdev led_dev;
enum lp8788_isink_number isink_num;
enum led_brightness brightness;
int on;
};
struct lp8788_led_config {
enum lp8788_isink_scale scale;
enum lp8788_isink_number num;
int iout;
};
static struct lp8788_led_config default_led_config = {
.scale = LP8788_ISINK_SCALE_100mA,
.num = LP8788_ISINK_3,
.iout = 0,
};
static int lp8788_led_init_device(struct lp8788_led *led,
struct lp8788_led_platform_data *pdata)
{
struct lp8788_led_config *cfg = &default_led_config;
u8 addr, mask, val;
int ret;
if (pdata) {
cfg->scale = pdata->scale;
cfg->num = pdata->num;
cfg->iout = pdata->iout_code;
}
led->isink_num = cfg->num;
/* scale configuration */
addr = LP8788_ISINK_CTRL;
mask = 1 << (cfg->num + LP8788_ISINK_SCALE_OFFSET);
val = cfg->scale << (cfg->num + LP8788_ISINK_SCALE_OFFSET);
ret = lp8788_update_bits(led->lp, addr, mask, val);
if (ret)
return ret;
/* current configuration */
addr = lp8788_iout_addr[cfg->num];
mask = lp8788_iout_mask[cfg->num];
val = cfg->iout;
return lp8788_update_bits(led->lp, addr, mask, val);
}
static void lp8788_led_enable(struct lp8788_led *led,
enum lp8788_isink_number num, int on)
{
u8 mask = 1 << num;
u8 val = on << num;
if (lp8788_update_bits(led->lp, LP8788_ISINK_CTRL, mask, val))
return;
led->on = on;
}
static void lp8788_led_work(struct work_struct *work)
{
struct lp8788_led *led = container_of(work, struct lp8788_led, work);
enum lp8788_isink_number num = led->isink_num;
int enable;
u8 val = led->brightness;
mutex_lock(&led->lock);
switch (num) {
case LP8788_ISINK_1:
case LP8788_ISINK_2:
case LP8788_ISINK_3:
lp8788_write_byte(led->lp, lp8788_pwm_addr[num], val);
break;
default:
mutex_unlock(&led->lock);
return;
}
enable = (val > 0) ? 1 : 0;
if (enable != led->on)
lp8788_led_enable(led, num, enable);
mutex_unlock(&led->lock);
}
static void lp8788_brightness_set(struct led_classdev *led_cdev,
enum led_brightness brt_val)
{
struct lp8788_led *led =
container_of(led_cdev, struct lp8788_led, led_dev);
led->brightness = brt_val;
schedule_work(&led->work);
}
static int lp8788_led_probe(struct platform_device *pdev)
{
struct lp8788 *lp = dev_get_drvdata(pdev->dev.parent);
struct lp8788_led_platform_data *led_pdata;
struct lp8788_led *led;
struct device *dev = &pdev->dev;
int ret;
led = devm_kzalloc(dev, sizeof(struct lp8788_led), GFP_KERNEL);
if (!led)
return -ENOMEM;
led->lp = lp;
led->led_dev.max_brightness = MAX_BRIGHTNESS;
led->led_dev.brightness_set = lp8788_brightness_set;
led_pdata = lp->pdata ? lp->pdata->led_pdata : NULL;
if (!led_pdata || !led_pdata->name)
led->led_dev.name = DEFAULT_LED_NAME;
else
led->led_dev.name = led_pdata->name;
mutex_init(&led->lock);
INIT_WORK(&led->work, lp8788_led_work);
platform_set_drvdata(pdev, led);
ret = lp8788_led_init_device(led, led_pdata);
if (ret) {
dev_err(dev, "led init device err: %d\n", ret);
return ret;
}
ret = led_classdev_register(dev, &led->led_dev);
if (ret) {
dev_err(dev, "led register err: %d\n", ret);
return ret;
}
return 0;
}
static int lp8788_led_remove(struct platform_device *pdev)
{
struct lp8788_led *led = platform_get_drvdata(pdev);
led_classdev_unregister(&led->led_dev);
flush_work(&led->work);
return 0;
}
static struct platform_driver lp8788_led_driver = {
.probe = lp8788_led_probe,
.remove = lp8788_led_remove,
.driver = {
.name = LP8788_DEV_KEYLED,
.owner = THIS_MODULE,
},
};
module_platform_driver(lp8788_led_driver);
MODULE_DESCRIPTION("Texas Instruments LP8788 Keyboard LED Driver");
MODULE_AUTHOR("Milo Kim");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:lp8788-keyled");
| gpl-2.0 |
sub77/kernel_msm | arch/mips/lantiq/xway/gpio.c | 4686 | 5144 | /*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* Copyright (C) 2010 John Crispin <blogic@openwrt.org>
*/
#include <linux/slab.h>
#include <linux/export.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <linux/ioport.h>
#include <linux/io.h>
#include <lantiq_soc.h>
#define LTQ_GPIO_OUT 0x00
#define LTQ_GPIO_IN 0x04
#define LTQ_GPIO_DIR 0x08
#define LTQ_GPIO_ALTSEL0 0x0C
#define LTQ_GPIO_ALTSEL1 0x10
#define LTQ_GPIO_OD 0x14
#define PINS_PER_PORT 16
#define MAX_PORTS 3
#define ltq_gpio_getbit(m, r, p) (!!(ltq_r32(m + r) & (1 << p)))
#define ltq_gpio_setbit(m, r, p) ltq_w32_mask(0, (1 << p), m + r)
#define ltq_gpio_clearbit(m, r, p) ltq_w32_mask((1 << p), 0, m + r)
struct ltq_gpio {
void __iomem *membase;
struct gpio_chip chip;
};
static struct ltq_gpio ltq_gpio_port[MAX_PORTS];
int gpio_to_irq(unsigned int gpio)
{
return -EINVAL;
}
EXPORT_SYMBOL(gpio_to_irq);
int irq_to_gpio(unsigned int gpio)
{
return -EINVAL;
}
EXPORT_SYMBOL(irq_to_gpio);
int ltq_gpio_request(unsigned int pin, unsigned int alt0,
unsigned int alt1, unsigned int dir, const char *name)
{
int id = 0;
if (pin >= (MAX_PORTS * PINS_PER_PORT))
return -EINVAL;
if (gpio_request(pin, name)) {
pr_err("failed to setup lantiq gpio: %s\n", name);
return -EBUSY;
}
if (dir)
gpio_direction_output(pin, 1);
else
gpio_direction_input(pin);
while (pin >= PINS_PER_PORT) {
pin -= PINS_PER_PORT;
id++;
}
if (alt0)
ltq_gpio_setbit(ltq_gpio_port[id].membase,
LTQ_GPIO_ALTSEL0, pin);
else
ltq_gpio_clearbit(ltq_gpio_port[id].membase,
LTQ_GPIO_ALTSEL0, pin);
if (alt1)
ltq_gpio_setbit(ltq_gpio_port[id].membase,
LTQ_GPIO_ALTSEL1, pin);
else
ltq_gpio_clearbit(ltq_gpio_port[id].membase,
LTQ_GPIO_ALTSEL1, pin);
return 0;
}
EXPORT_SYMBOL(ltq_gpio_request);
static void ltq_gpio_set(struct gpio_chip *chip, unsigned int offset, int value)
{
struct ltq_gpio *ltq_gpio = container_of(chip, struct ltq_gpio, chip);
if (value)
ltq_gpio_setbit(ltq_gpio->membase, LTQ_GPIO_OUT, offset);
else
ltq_gpio_clearbit(ltq_gpio->membase, LTQ_GPIO_OUT, offset);
}
static int ltq_gpio_get(struct gpio_chip *chip, unsigned int offset)
{
struct ltq_gpio *ltq_gpio = container_of(chip, struct ltq_gpio, chip);
return ltq_gpio_getbit(ltq_gpio->membase, LTQ_GPIO_IN, offset);
}
static int ltq_gpio_direction_input(struct gpio_chip *chip, unsigned int offset)
{
struct ltq_gpio *ltq_gpio = container_of(chip, struct ltq_gpio, chip);
ltq_gpio_clearbit(ltq_gpio->membase, LTQ_GPIO_OD, offset);
ltq_gpio_clearbit(ltq_gpio->membase, LTQ_GPIO_DIR, offset);
return 0;
}
static int ltq_gpio_direction_output(struct gpio_chip *chip,
unsigned int offset, int value)
{
struct ltq_gpio *ltq_gpio = container_of(chip, struct ltq_gpio, chip);
ltq_gpio_setbit(ltq_gpio->membase, LTQ_GPIO_OD, offset);
ltq_gpio_setbit(ltq_gpio->membase, LTQ_GPIO_DIR, offset);
ltq_gpio_set(chip, offset, value);
return 0;
}
static int ltq_gpio_req(struct gpio_chip *chip, unsigned offset)
{
struct ltq_gpio *ltq_gpio = container_of(chip, struct ltq_gpio, chip);
ltq_gpio_clearbit(ltq_gpio->membase, LTQ_GPIO_ALTSEL0, offset);
ltq_gpio_clearbit(ltq_gpio->membase, LTQ_GPIO_ALTSEL1, offset);
return 0;
}
static int ltq_gpio_probe(struct platform_device *pdev)
{
struct resource *res;
if (pdev->id >= MAX_PORTS) {
dev_err(&pdev->dev, "invalid gpio port %d\n",
pdev->id);
return -EINVAL;
}
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(&pdev->dev, "failed to get memory for gpio port %d\n",
pdev->id);
return -ENOENT;
}
res = devm_request_mem_region(&pdev->dev, res->start,
resource_size(res), dev_name(&pdev->dev));
if (!res) {
dev_err(&pdev->dev,
"failed to request memory for gpio port %d\n",
pdev->id);
return -EBUSY;
}
ltq_gpio_port[pdev->id].membase = devm_ioremap_nocache(&pdev->dev,
res->start, resource_size(res));
if (!ltq_gpio_port[pdev->id].membase) {
dev_err(&pdev->dev, "failed to remap memory for gpio port %d\n",
pdev->id);
return -ENOMEM;
}
ltq_gpio_port[pdev->id].chip.label = "ltq_gpio";
ltq_gpio_port[pdev->id].chip.direction_input = ltq_gpio_direction_input;
ltq_gpio_port[pdev->id].chip.direction_output =
ltq_gpio_direction_output;
ltq_gpio_port[pdev->id].chip.get = ltq_gpio_get;
ltq_gpio_port[pdev->id].chip.set = ltq_gpio_set;
ltq_gpio_port[pdev->id].chip.request = ltq_gpio_req;
ltq_gpio_port[pdev->id].chip.base = PINS_PER_PORT * pdev->id;
ltq_gpio_port[pdev->id].chip.ngpio = PINS_PER_PORT;
platform_set_drvdata(pdev, <q_gpio_port[pdev->id]);
return gpiochip_add(<q_gpio_port[pdev->id].chip);
}
static struct platform_driver
ltq_gpio_driver = {
.probe = ltq_gpio_probe,
.driver = {
.name = "ltq_gpio",
.owner = THIS_MODULE,
},
};
int __init ltq_gpio_init(void)
{
int ret = platform_driver_register(<q_gpio_driver);
if (ret)
pr_info("ltq_gpio : Error registering platfom driver!");
return ret;
}
postcore_initcall(ltq_gpio_init);
| gpl-2.0 |
copolii/android_kernel_lge_msm8974 | arch/tile/kernel/backtrace.c | 4686 | 18097 | /*
* Copyright 2011 Tilera Corporation. All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, version 2.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
* NON INFRINGEMENT. See the GNU General Public License for
* more details.
*/
#include <linux/kernel.h>
#include <linux/string.h>
#include <asm/backtrace.h>
#include <asm/tile-desc.h>
#include <arch/abi.h>
#ifdef __tilegx__
#define TILE_MAX_INSTRUCTIONS_PER_BUNDLE TILEGX_MAX_INSTRUCTIONS_PER_BUNDLE
#define tile_decoded_instruction tilegx_decoded_instruction
#define tile_mnemonic tilegx_mnemonic
#define parse_insn_tile parse_insn_tilegx
#define TILE_OPC_IRET TILEGX_OPC_IRET
#define TILE_OPC_ADDI TILEGX_OPC_ADDI
#define TILE_OPC_ADDLI TILEGX_OPC_ADDLI
#define TILE_OPC_INFO TILEGX_OPC_INFO
#define TILE_OPC_INFOL TILEGX_OPC_INFOL
#define TILE_OPC_JRP TILEGX_OPC_JRP
#define TILE_OPC_MOVE TILEGX_OPC_MOVE
#define OPCODE_STORE TILEGX_OPC_ST
typedef long long bt_int_reg_t;
#else
#define TILE_MAX_INSTRUCTIONS_PER_BUNDLE TILEPRO_MAX_INSTRUCTIONS_PER_BUNDLE
#define tile_decoded_instruction tilepro_decoded_instruction
#define tile_mnemonic tilepro_mnemonic
#define parse_insn_tile parse_insn_tilepro
#define TILE_OPC_IRET TILEPRO_OPC_IRET
#define TILE_OPC_ADDI TILEPRO_OPC_ADDI
#define TILE_OPC_ADDLI TILEPRO_OPC_ADDLI
#define TILE_OPC_INFO TILEPRO_OPC_INFO
#define TILE_OPC_INFOL TILEPRO_OPC_INFOL
#define TILE_OPC_JRP TILEPRO_OPC_JRP
#define TILE_OPC_MOVE TILEPRO_OPC_MOVE
#define OPCODE_STORE TILEPRO_OPC_SW
typedef int bt_int_reg_t;
#endif
/* A decoded bundle used for backtracer analysis. */
struct BacktraceBundle {
tile_bundle_bits bits;
int num_insns;
struct tile_decoded_instruction
insns[TILE_MAX_INSTRUCTIONS_PER_BUNDLE];
};
/* Locates an instruction inside the given bundle that
* has the specified mnemonic, and whose first 'num_operands_to_match'
* operands exactly match those in 'operand_values'.
*/
static const struct tile_decoded_instruction *find_matching_insn(
const struct BacktraceBundle *bundle,
tile_mnemonic mnemonic,
const int *operand_values,
int num_operands_to_match)
{
int i, j;
bool match;
for (i = 0; i < bundle->num_insns; i++) {
const struct tile_decoded_instruction *insn =
&bundle->insns[i];
if (insn->opcode->mnemonic != mnemonic)
continue;
match = true;
for (j = 0; j < num_operands_to_match; j++) {
if (operand_values[j] != insn->operand_values[j]) {
match = false;
break;
}
}
if (match)
return insn;
}
return NULL;
}
/* Does this bundle contain an 'iret' instruction? */
static inline bool bt_has_iret(const struct BacktraceBundle *bundle)
{
return find_matching_insn(bundle, TILE_OPC_IRET, NULL, 0) != NULL;
}
/* Does this bundle contain an 'addi sp, sp, OFFSET' or
* 'addli sp, sp, OFFSET' instruction, and if so, what is OFFSET?
*/
static bool bt_has_addi_sp(const struct BacktraceBundle *bundle, int *adjust)
{
static const int vals[2] = { TREG_SP, TREG_SP };
const struct tile_decoded_instruction *insn =
find_matching_insn(bundle, TILE_OPC_ADDI, vals, 2);
if (insn == NULL)
insn = find_matching_insn(bundle, TILE_OPC_ADDLI, vals, 2);
#ifdef __tilegx__
if (insn == NULL)
insn = find_matching_insn(bundle, TILEGX_OPC_ADDXLI, vals, 2);
if (insn == NULL)
insn = find_matching_insn(bundle, TILEGX_OPC_ADDXI, vals, 2);
#endif
if (insn == NULL)
return false;
*adjust = insn->operand_values[2];
return true;
}
/* Does this bundle contain any 'info OP' or 'infol OP'
* instruction, and if so, what are their OP? Note that OP is interpreted
* as an unsigned value by this code since that's what the caller wants.
* Returns the number of info ops found.
*/
static int bt_get_info_ops(const struct BacktraceBundle *bundle,
int operands[MAX_INFO_OPS_PER_BUNDLE])
{
int num_ops = 0;
int i;
for (i = 0; i < bundle->num_insns; i++) {
const struct tile_decoded_instruction *insn =
&bundle->insns[i];
if (insn->opcode->mnemonic == TILE_OPC_INFO ||
insn->opcode->mnemonic == TILE_OPC_INFOL) {
operands[num_ops++] = insn->operand_values[0];
}
}
return num_ops;
}
/* Does this bundle contain a jrp instruction, and if so, to which
* register is it jumping?
*/
static bool bt_has_jrp(const struct BacktraceBundle *bundle, int *target_reg)
{
const struct tile_decoded_instruction *insn =
find_matching_insn(bundle, TILE_OPC_JRP, NULL, 0);
if (insn == NULL)
return false;
*target_reg = insn->operand_values[0];
return true;
}
/* Does this bundle modify the specified register in any way? */
static bool bt_modifies_reg(const struct BacktraceBundle *bundle, int reg)
{
int i, j;
for (i = 0; i < bundle->num_insns; i++) {
const struct tile_decoded_instruction *insn =
&bundle->insns[i];
if (insn->opcode->implicitly_written_register == reg)
return true;
for (j = 0; j < insn->opcode->num_operands; j++)
if (insn->operands[j]->is_dest_reg &&
insn->operand_values[j] == reg)
return true;
}
return false;
}
/* Does this bundle modify sp? */
static inline bool bt_modifies_sp(const struct BacktraceBundle *bundle)
{
return bt_modifies_reg(bundle, TREG_SP);
}
/* Does this bundle modify lr? */
static inline bool bt_modifies_lr(const struct BacktraceBundle *bundle)
{
return bt_modifies_reg(bundle, TREG_LR);
}
/* Does this bundle contain the instruction 'move fp, sp'? */
static inline bool bt_has_move_r52_sp(const struct BacktraceBundle *bundle)
{
static const int vals[2] = { 52, TREG_SP };
return find_matching_insn(bundle, TILE_OPC_MOVE, vals, 2) != NULL;
}
/* Does this bundle contain a store of lr to sp? */
static inline bool bt_has_sw_sp_lr(const struct BacktraceBundle *bundle)
{
static const int vals[2] = { TREG_SP, TREG_LR };
return find_matching_insn(bundle, OPCODE_STORE, vals, 2) != NULL;
}
#ifdef __tilegx__
/* Track moveli values placed into registers. */
static inline void bt_update_moveli(const struct BacktraceBundle *bundle,
int moveli_args[])
{
int i;
for (i = 0; i < bundle->num_insns; i++) {
const struct tile_decoded_instruction *insn =
&bundle->insns[i];
if (insn->opcode->mnemonic == TILEGX_OPC_MOVELI) {
int reg = insn->operand_values[0];
moveli_args[reg] = insn->operand_values[1];
}
}
}
/* Does this bundle contain an 'add sp, sp, reg' instruction
* from a register that we saw a moveli into, and if so, what
* is the value in the register?
*/
static bool bt_has_add_sp(const struct BacktraceBundle *bundle, int *adjust,
int moveli_args[])
{
static const int vals[2] = { TREG_SP, TREG_SP };
const struct tile_decoded_instruction *insn =
find_matching_insn(bundle, TILEGX_OPC_ADDX, vals, 2);
if (insn) {
int reg = insn->operand_values[2];
if (moveli_args[reg]) {
*adjust = moveli_args[reg];
return true;
}
}
return false;
}
#endif
/* Locates the caller's PC and SP for a program starting at the
* given address.
*/
static void find_caller_pc_and_caller_sp(CallerLocation *location,
const unsigned long start_pc,
BacktraceMemoryReader read_memory_func,
void *read_memory_func_extra)
{
/* Have we explicitly decided what the sp is,
* rather than just the default?
*/
bool sp_determined = false;
/* Has any bundle seen so far modified lr? */
bool lr_modified = false;
/* Have we seen a move from sp to fp? */
bool sp_moved_to_r52 = false;
/* Have we seen a terminating bundle? */
bool seen_terminating_bundle = false;
/* Cut down on round-trip reading overhead by reading several
* bundles at a time.
*/
tile_bundle_bits prefetched_bundles[32];
int num_bundles_prefetched = 0;
int next_bundle = 0;
unsigned long pc;
#ifdef __tilegx__
/* Naively try to track moveli values to support addx for -m32. */
int moveli_args[TILEGX_NUM_REGISTERS] = { 0 };
#endif
/* Default to assuming that the caller's sp is the current sp.
* This is necessary to handle the case where we start backtracing
* right at the end of the epilog.
*/
location->sp_location = SP_LOC_OFFSET;
location->sp_offset = 0;
/* Default to having no idea where the caller PC is. */
location->pc_location = PC_LOC_UNKNOWN;
/* Don't even try if the PC is not aligned. */
if (start_pc % TILE_BUNDLE_ALIGNMENT_IN_BYTES != 0)
return;
for (pc = start_pc;; pc += sizeof(tile_bundle_bits)) {
struct BacktraceBundle bundle;
int num_info_ops, info_operands[MAX_INFO_OPS_PER_BUNDLE];
int one_ago, jrp_reg;
bool has_jrp;
if (next_bundle >= num_bundles_prefetched) {
/* Prefetch some bytes, but don't cross a page
* boundary since that might cause a read failure we
* don't care about if we only need the first few
* bytes. Note: we don't care what the actual page
* size is; using the minimum possible page size will
* prevent any problems.
*/
unsigned int bytes_to_prefetch = 4096 - (pc & 4095);
if (bytes_to_prefetch > sizeof prefetched_bundles)
bytes_to_prefetch = sizeof prefetched_bundles;
if (!read_memory_func(prefetched_bundles, pc,
bytes_to_prefetch,
read_memory_func_extra)) {
if (pc == start_pc) {
/* The program probably called a bad
* address, such as a NULL pointer.
* So treat this as if we are at the
* start of the function prolog so the
* backtrace will show how we got here.
*/
location->pc_location = PC_LOC_IN_LR;
return;
}
/* Unreadable address. Give up. */
break;
}
next_bundle = 0;
num_bundles_prefetched =
bytes_to_prefetch / sizeof(tile_bundle_bits);
}
/* Decode the next bundle. */
bundle.bits = prefetched_bundles[next_bundle++];
bundle.num_insns =
parse_insn_tile(bundle.bits, pc, bundle.insns);
num_info_ops = bt_get_info_ops(&bundle, info_operands);
/* First look at any one_ago info ops if they are interesting,
* since they should shadow any non-one-ago info ops.
*/
for (one_ago = (pc != start_pc) ? 1 : 0;
one_ago >= 0; one_ago--) {
int i;
for (i = 0; i < num_info_ops; i++) {
int info_operand = info_operands[i];
if (info_operand < CALLER_UNKNOWN_BASE) {
/* Weird; reserved value, ignore it. */
continue;
}
/* Skip info ops which are not in the
* "one_ago" mode we want right now.
*/
if (((info_operand & ONE_BUNDLE_AGO_FLAG) != 0)
!= (one_ago != 0))
continue;
/* Clear the flag to make later checking
* easier. */
info_operand &= ~ONE_BUNDLE_AGO_FLAG;
/* Default to looking at PC_IN_LR_FLAG. */
if (info_operand & PC_IN_LR_FLAG)
location->pc_location =
PC_LOC_IN_LR;
else
location->pc_location =
PC_LOC_ON_STACK;
switch (info_operand) {
case CALLER_UNKNOWN_BASE:
location->pc_location = PC_LOC_UNKNOWN;
location->sp_location = SP_LOC_UNKNOWN;
return;
case CALLER_SP_IN_R52_BASE:
case CALLER_SP_IN_R52_BASE | PC_IN_LR_FLAG:
location->sp_location = SP_LOC_IN_R52;
return;
default:
{
const unsigned int val = info_operand
- CALLER_SP_OFFSET_BASE;
const unsigned int sp_offset =
(val >> NUM_INFO_OP_FLAGS) * 8;
if (sp_offset < 32768) {
/* This is a properly encoded
* SP offset. */
location->sp_location =
SP_LOC_OFFSET;
location->sp_offset =
sp_offset;
return;
} else {
/* This looked like an SP
* offset, but it's outside
* the legal range, so this
* must be an unrecognized
* info operand. Ignore it.
*/
}
}
break;
}
}
}
if (seen_terminating_bundle) {
/* We saw a terminating bundle during the previous
* iteration, so we were only looking for an info op.
*/
break;
}
if (bundle.bits == 0) {
/* Wacky terminating bundle. Stop looping, and hope
* we've already seen enough to find the caller.
*/
break;
}
/*
* Try to determine caller's SP.
*/
if (!sp_determined) {
int adjust;
if (bt_has_addi_sp(&bundle, &adjust)
#ifdef __tilegx__
|| bt_has_add_sp(&bundle, &adjust, moveli_args)
#endif
) {
location->sp_location = SP_LOC_OFFSET;
if (adjust <= 0) {
/* We are in prolog about to adjust
* SP. */
location->sp_offset = 0;
} else {
/* We are in epilog restoring SP. */
location->sp_offset = adjust;
}
sp_determined = true;
} else {
if (bt_has_move_r52_sp(&bundle)) {
/* Maybe in prolog, creating an
* alloca-style frame. But maybe in
* the middle of a fixed-size frame
* clobbering r52 with SP.
*/
sp_moved_to_r52 = true;
}
if (bt_modifies_sp(&bundle)) {
if (sp_moved_to_r52) {
/* We saw SP get saved into
* r52 earlier (or now), which
* must have been in the
* prolog, so we now know that
* SP is still holding the
* caller's sp value.
*/
location->sp_location =
SP_LOC_OFFSET;
location->sp_offset = 0;
} else {
/* Someone must have saved
* aside the caller's SP value
* into r52, so r52 holds the
* current value.
*/
location->sp_location =
SP_LOC_IN_R52;
}
sp_determined = true;
}
}
#ifdef __tilegx__
/* Track moveli arguments for -m32 mode. */
bt_update_moveli(&bundle, moveli_args);
#endif
}
if (bt_has_iret(&bundle)) {
/* This is a terminating bundle. */
seen_terminating_bundle = true;
continue;
}
/*
* Try to determine caller's PC.
*/
jrp_reg = -1;
has_jrp = bt_has_jrp(&bundle, &jrp_reg);
if (has_jrp)
seen_terminating_bundle = true;
if (location->pc_location == PC_LOC_UNKNOWN) {
if (has_jrp) {
if (jrp_reg == TREG_LR && !lr_modified) {
/* Looks like a leaf function, or else
* lr is already restored. */
location->pc_location =
PC_LOC_IN_LR;
} else {
location->pc_location =
PC_LOC_ON_STACK;
}
} else if (bt_has_sw_sp_lr(&bundle)) {
/* In prolog, spilling initial lr to stack. */
location->pc_location = PC_LOC_IN_LR;
} else if (bt_modifies_lr(&bundle)) {
lr_modified = true;
}
}
}
}
/* Initializes a backtracer to start from the given location.
*
* If the frame pointer cannot be determined it is set to -1.
*
* state: The state to be filled in.
* read_memory_func: A callback that reads memory.
* read_memory_func_extra: An arbitrary argument to read_memory_func.
* pc: The current PC.
* lr: The current value of the 'lr' register.
* sp: The current value of the 'sp' register.
* r52: The current value of the 'r52' register.
*/
void backtrace_init(BacktraceIterator *state,
BacktraceMemoryReader read_memory_func,
void *read_memory_func_extra,
unsigned long pc, unsigned long lr,
unsigned long sp, unsigned long r52)
{
CallerLocation location;
unsigned long fp, initial_frame_caller_pc;
/* Find out where we are in the initial frame. */
find_caller_pc_and_caller_sp(&location, pc,
read_memory_func, read_memory_func_extra);
switch (location.sp_location) {
case SP_LOC_UNKNOWN:
/* Give up. */
fp = -1;
break;
case SP_LOC_IN_R52:
fp = r52;
break;
case SP_LOC_OFFSET:
fp = sp + location.sp_offset;
break;
default:
/* Give up. */
fp = -1;
break;
}
/* If the frame pointer is not aligned to the basic word size
* something terrible happened and we should mark it as invalid.
*/
if (fp % sizeof(bt_int_reg_t) != 0)
fp = -1;
/* -1 means "don't know initial_frame_caller_pc". */
initial_frame_caller_pc = -1;
switch (location.pc_location) {
case PC_LOC_UNKNOWN:
/* Give up. */
fp = -1;
break;
case PC_LOC_IN_LR:
if (lr == 0 || lr % TILE_BUNDLE_ALIGNMENT_IN_BYTES != 0) {
/* Give up. */
fp = -1;
} else {
initial_frame_caller_pc = lr;
}
break;
case PC_LOC_ON_STACK:
/* Leave initial_frame_caller_pc as -1,
* meaning check the stack.
*/
break;
default:
/* Give up. */
fp = -1;
break;
}
state->pc = pc;
state->sp = sp;
state->fp = fp;
state->initial_frame_caller_pc = initial_frame_caller_pc;
state->read_memory_func = read_memory_func;
state->read_memory_func_extra = read_memory_func_extra;
}
/* Handle the case where the register holds more bits than the VA. */
static bool valid_addr_reg(bt_int_reg_t reg)
{
return ((unsigned long)reg == reg);
}
/* Advances the backtracing state to the calling frame, returning
* true iff successful.
*/
bool backtrace_next(BacktraceIterator *state)
{
unsigned long next_fp, next_pc;
bt_int_reg_t next_frame[2];
if (state->fp == -1) {
/* No parent frame. */
return false;
}
/* Try to read the frame linkage data chaining to the next function. */
if (!state->read_memory_func(&next_frame, state->fp, sizeof next_frame,
state->read_memory_func_extra)) {
return false;
}
next_fp = next_frame[1];
if (!valid_addr_reg(next_frame[1]) ||
next_fp % sizeof(bt_int_reg_t) != 0) {
/* Caller's frame pointer is suspect, so give up. */
return false;
}
if (state->initial_frame_caller_pc != -1) {
/* We must be in the initial stack frame and already know the
* caller PC.
*/
next_pc = state->initial_frame_caller_pc;
/* Force reading stack next time, in case we were in the
* initial frame. We don't do this above just to paranoidly
* avoid changing the struct at all when we return false.
*/
state->initial_frame_caller_pc = -1;
} else {
/* Get the caller PC from the frame linkage area. */
next_pc = next_frame[0];
if (!valid_addr_reg(next_frame[0]) || next_pc == 0 ||
next_pc % TILE_BUNDLE_ALIGNMENT_IN_BYTES != 0) {
/* The PC is suspect, so give up. */
return false;
}
}
/* Update state to become the caller's stack frame. */
state->pc = next_pc;
state->sp = state->fp;
state->fp = next_fp;
return true;
}
| gpl-2.0 |
elektroschmock/android_kernel_lge_hammerhead | arch/microblaze/kernel/traps.c | 4686 | 2027 | /*
* Copyright (C) 2007-2009 Michal Simek <monstr@monstr.eu>
* Copyright (C) 2007-2009 PetaLogix
* Copyright (C) 2006 Atmark Techno, Inc.
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/kernel.h>
#include <linux/kallsyms.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/debug_locks.h>
#include <asm/exceptions.h>
#include <asm/unwind.h>
void trap_init(void)
{
__enable_hw_exceptions();
}
static unsigned long kstack_depth_to_print; /* 0 == entire stack */
static int __init kstack_setup(char *s)
{
return !strict_strtoul(s, 0, &kstack_depth_to_print);
}
__setup("kstack=", kstack_setup);
void show_stack(struct task_struct *task, unsigned long *sp)
{
unsigned long words_to_show;
u32 fp = (u32) sp;
if (fp == 0) {
if (task) {
fp = ((struct thread_info *)
(task->stack))->cpu_context.r1;
} else {
/* Pick up caller of dump_stack() */
fp = (u32)&sp - 8;
}
}
words_to_show = (THREAD_SIZE - (fp & (THREAD_SIZE - 1))) >> 2;
if (kstack_depth_to_print && (words_to_show > kstack_depth_to_print))
words_to_show = kstack_depth_to_print;
pr_info("Kernel Stack:\n");
/*
* Make the first line an 'odd' size if necessary to get
* remaining lines to start at an address multiple of 0x10
*/
if (fp & 0xF) {
unsigned long line1_words = (0x10 - (fp & 0xF)) >> 2;
if (line1_words < words_to_show) {
print_hex_dump(KERN_INFO, "", DUMP_PREFIX_ADDRESS, 32,
4, (void *)fp, line1_words << 2, 0);
fp += line1_words << 2;
words_to_show -= line1_words;
}
}
print_hex_dump(KERN_INFO, "", DUMP_PREFIX_ADDRESS, 32, 4, (void *)fp,
words_to_show << 2, 0);
printk(KERN_INFO "\n\n");
pr_info("Call Trace:\n");
microblaze_unwind(task, NULL);
pr_info("\n");
if (!task)
task = current;
debug_show_held_locks(task);
}
void dump_stack(void)
{
show_stack(NULL, NULL);
}
EXPORT_SYMBOL(dump_stack);
| gpl-2.0 |
o11s/open80211s | drivers/hid/hid-twinhan.c | 4686 | 4767 | /*
* HID driver for TwinHan IR remote control
*
* Based on hid-gyration.c
*
* Copyright (c) 2009 Bruno Prémont <bonbons@linux-vserver.org>
*/
/*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License.
*/
#include <linux/device.h>
#include <linux/input.h>
#include <linux/hid.h>
#include <linux/module.h>
#include "hid-ids.h"
/* Remote control key layout + listing:
*
* Full Screen Power
* KEY_SCREEN KEY_POWER2
*
* 1 2 3
* KEY_NUMERIC_1 KEY_NUMERIC_2 KEY_NUMERIC_3
*
* 4 5 6
* KEY_NUMERIC_4 KEY_NUMERIC_5 KEY_NUMERIC_6
*
* 7 8 9
* KEY_NUMERIC_7 KEY_NUMERIC_8 KEY_NUMERIC_9
*
* REC 0 Favorite
* KEY_RECORD KEY_NUMERIC_0 KEY_FAVORITES
*
* Rewind Forward
* KEY_REWIND CH+ KEY_FORWARD
* KEY_CHANNELUP
*
* VOL- > VOL+
* KEY_VOLUMEDOWN KEY_PLAY KEY_VOLUMEUP
*
* CH-
* KEY_CHANNELDOWN
* Recall Stop
* KEY_RESTART KEY_STOP
*
* Timeshift/Pause Mute Cancel
* KEY_PAUSE KEY_MUTE KEY_CANCEL
*
* Capture Preview EPG
* KEY_PRINT KEY_PROGRAM KEY_EPG
*
* Record List Tab Teletext
* KEY_LIST KEY_TAB KEY_TEXT
*/
#define th_map_key_clear(c) hid_map_usage_clear(hi, usage, bit, max, \
EV_KEY, (c))
static int twinhan_input_mapping(struct hid_device *hdev, struct hid_input *hi,
struct hid_field *field, struct hid_usage *usage,
unsigned long **bit, int *max)
{
if ((usage->hid & HID_USAGE_PAGE) != HID_UP_KEYBOARD)
return 0;
switch (usage->hid & HID_USAGE) {
/* Map all keys from Twinhan Remote */
case 0x004: th_map_key_clear(KEY_TEXT); break;
case 0x006: th_map_key_clear(KEY_RESTART); break;
case 0x008: th_map_key_clear(KEY_EPG); break;
case 0x00c: th_map_key_clear(KEY_REWIND); break;
case 0x00e: th_map_key_clear(KEY_PROGRAM); break;
case 0x00f: th_map_key_clear(KEY_LIST); break;
case 0x010: th_map_key_clear(KEY_MUTE); break;
case 0x011: th_map_key_clear(KEY_FORWARD); break;
case 0x013: th_map_key_clear(KEY_PRINT); break;
case 0x017: th_map_key_clear(KEY_PAUSE); break;
case 0x019: th_map_key_clear(KEY_FAVORITES); break;
case 0x01d: th_map_key_clear(KEY_SCREEN); break;
case 0x01e: th_map_key_clear(KEY_NUMERIC_1); break;
case 0x01f: th_map_key_clear(KEY_NUMERIC_2); break;
case 0x020: th_map_key_clear(KEY_NUMERIC_3); break;
case 0x021: th_map_key_clear(KEY_NUMERIC_4); break;
case 0x022: th_map_key_clear(KEY_NUMERIC_5); break;
case 0x023: th_map_key_clear(KEY_NUMERIC_6); break;
case 0x024: th_map_key_clear(KEY_NUMERIC_7); break;
case 0x025: th_map_key_clear(KEY_NUMERIC_8); break;
case 0x026: th_map_key_clear(KEY_NUMERIC_9); break;
case 0x027: th_map_key_clear(KEY_NUMERIC_0); break;
case 0x028: th_map_key_clear(KEY_PLAY); break;
case 0x029: th_map_key_clear(KEY_CANCEL); break;
case 0x02b: th_map_key_clear(KEY_TAB); break;
/* Power = 0x0e0 + 0x0e1 + 0x0e2 + 0x03f */
case 0x03f: th_map_key_clear(KEY_POWER2); break;
case 0x04a: th_map_key_clear(KEY_RECORD); break;
case 0x04b: th_map_key_clear(KEY_CHANNELUP); break;
case 0x04d: th_map_key_clear(KEY_STOP); break;
case 0x04e: th_map_key_clear(KEY_CHANNELDOWN); break;
/* Volume down = 0x0e1 + 0x051 */
case 0x051: th_map_key_clear(KEY_VOLUMEDOWN); break;
/* Volume up = 0x0e1 + 0x052 */
case 0x052: th_map_key_clear(KEY_VOLUMEUP); break;
/* Kill the extra keys used for multi-key "power" and "volume" keys
* as well as continuously to release CTRL,ALT,META,... keys */
case 0x0e0:
case 0x0e1:
case 0x0e2:
case 0x0e3:
case 0x0e4:
case 0x0e5:
case 0x0e6:
case 0x0e7:
default:
return -1;
}
return 1;
}
static const struct hid_device_id twinhan_devices[] = {
{ HID_USB_DEVICE(USB_VENDOR_ID_TWINHAN, USB_DEVICE_ID_TWINHAN_IR_REMOTE) },
{ }
};
MODULE_DEVICE_TABLE(hid, twinhan_devices);
static struct hid_driver twinhan_driver = {
.name = "twinhan",
.id_table = twinhan_devices,
.input_mapping = twinhan_input_mapping,
};
module_hid_driver(twinhan_driver);
MODULE_LICENSE("GPL");
| gpl-2.0 |
Fechinator/FechdaKernel_V500 | sound/drivers/portman2x4.c | 4942 | 25892 | /*
* Driver for Midiman Portman2x4 parallel port midi interface
*
* Copyright (c) by Levent Guendogdu <levon@feature-it.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* ChangeLog
* Jan 24 2007 Matthias Koenig <mkoenig@suse.de>
* - cleanup and rewrite
* Sep 30 2004 Tobias Gehrig <tobias@gehrig.tk>
* - source code cleanup
* Sep 03 2004 Tobias Gehrig <tobias@gehrig.tk>
* - fixed compilation problem with alsa 1.0.6a (removed MODULE_CLASSES,
* MODULE_PARM_SYNTAX and changed MODULE_DEVICES to
* MODULE_SUPPORTED_DEVICE)
* Mar 24 2004 Tobias Gehrig <tobias@gehrig.tk>
* - added 2.6 kernel support
* Mar 18 2004 Tobias Gehrig <tobias@gehrig.tk>
* - added parport_unregister_driver to the startup routine if the driver fails to detect a portman
* - added support for all 4 output ports in portman_putmidi
* Mar 17 2004 Tobias Gehrig <tobias@gehrig.tk>
* - added checks for opened input device in interrupt handler
* Feb 20 2004 Tobias Gehrig <tobias@gehrig.tk>
* - ported from alsa 0.5 to 1.0
*/
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/parport.h>
#include <linux/spinlock.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <sound/core.h>
#include <sound/initval.h>
#include <sound/rawmidi.h>
#include <sound/control.h>
#define CARD_NAME "Portman 2x4"
#define DRIVER_NAME "portman"
#define PLATFORM_DRIVER "snd_portman2x4"
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;
static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;
static struct platform_device *platform_devices[SNDRV_CARDS];
static int device_count;
module_param_array(index, int, NULL, S_IRUGO);
MODULE_PARM_DESC(index, "Index value for " CARD_NAME " soundcard.");
module_param_array(id, charp, NULL, S_IRUGO);
MODULE_PARM_DESC(id, "ID string for " CARD_NAME " soundcard.");
module_param_array(enable, bool, NULL, S_IRUGO);
MODULE_PARM_DESC(enable, "Enable " CARD_NAME " soundcard.");
MODULE_AUTHOR("Levent Guendogdu, Tobias Gehrig, Matthias Koenig");
MODULE_DESCRIPTION("Midiman Portman2x4");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("{{Midiman,Portman2x4}}");
/*********************************************************************
* Chip specific
*********************************************************************/
#define PORTMAN_NUM_INPUT_PORTS 2
#define PORTMAN_NUM_OUTPUT_PORTS 4
struct portman {
spinlock_t reg_lock;
struct snd_card *card;
struct snd_rawmidi *rmidi;
struct pardevice *pardev;
int pardev_claimed;
int open_count;
int mode[PORTMAN_NUM_INPUT_PORTS];
struct snd_rawmidi_substream *midi_input[PORTMAN_NUM_INPUT_PORTS];
};
static int portman_free(struct portman *pm)
{
kfree(pm);
return 0;
}
static int __devinit portman_create(struct snd_card *card,
struct pardevice *pardev,
struct portman **rchip)
{
struct portman *pm;
*rchip = NULL;
pm = kzalloc(sizeof(struct portman), GFP_KERNEL);
if (pm == NULL)
return -ENOMEM;
/* Init chip specific data */
spin_lock_init(&pm->reg_lock);
pm->card = card;
pm->pardev = pardev;
*rchip = pm;
return 0;
}
/*********************************************************************
* HW related constants
*********************************************************************/
/* Standard PC parallel port status register equates. */
#define PP_STAT_BSY 0x80 /* Busy status. Inverted. */
#define PP_STAT_ACK 0x40 /* Acknowledge. Non-Inverted. */
#define PP_STAT_POUT 0x20 /* Paper Out. Non-Inverted. */
#define PP_STAT_SEL 0x10 /* Select. Non-Inverted. */
#define PP_STAT_ERR 0x08 /* Error. Non-Inverted. */
/* Standard PC parallel port command register equates. */
#define PP_CMD_IEN 0x10 /* IRQ Enable. Non-Inverted. */
#define PP_CMD_SELI 0x08 /* Select Input. Inverted. */
#define PP_CMD_INIT 0x04 /* Init Printer. Non-Inverted. */
#define PP_CMD_FEED 0x02 /* Auto Feed. Inverted. */
#define PP_CMD_STB 0x01 /* Strobe. Inverted. */
/* Parallel Port Command Register as implemented by PCP2x4. */
#define INT_EN PP_CMD_IEN /* Interrupt enable. */
#define STROBE PP_CMD_STB /* Command strobe. */
/* The parallel port command register field (b1..b3) selects the
* various "registers" within the PC/P 2x4. These are the internal
* address of these "registers" that must be written to the parallel
* port command register.
*/
#define RXDATA0 (0 << 1) /* PCP RxData channel 0. */
#define RXDATA1 (1 << 1) /* PCP RxData channel 1. */
#define GEN_CTL (2 << 1) /* PCP General Control Register. */
#define SYNC_CTL (3 << 1) /* PCP Sync Control Register. */
#define TXDATA0 (4 << 1) /* PCP TxData channel 0. */
#define TXDATA1 (5 << 1) /* PCP TxData channel 1. */
#define TXDATA2 (6 << 1) /* PCP TxData channel 2. */
#define TXDATA3 (7 << 1) /* PCP TxData channel 3. */
/* Parallel Port Status Register as implemented by PCP2x4. */
#define ESTB PP_STAT_POUT /* Echoed strobe. */
#define INT_REQ PP_STAT_ACK /* Input data int request. */
#define BUSY PP_STAT_ERR /* Interface Busy. */
/* Parallel Port Status Register BUSY and SELECT lines are multiplexed
* between several functions. Depending on which 2x4 "register" is
* currently selected (b1..b3), the BUSY and SELECT lines are
* assigned as follows:
*
* SELECT LINE: A3 A2 A1
* --------
*/
#define RXAVAIL PP_STAT_SEL /* Rx Available, channel 0. 0 0 0 */
// RXAVAIL1 PP_STAT_SEL /* Rx Available, channel 1. 0 0 1 */
#define SYNC_STAT PP_STAT_SEL /* Reserved - Sync Status. 0 1 0 */
// /* Reserved. 0 1 1 */
#define TXEMPTY PP_STAT_SEL /* Tx Empty, channel 0. 1 0 0 */
// TXEMPTY1 PP_STAT_SEL /* Tx Empty, channel 1. 1 0 1 */
// TXEMPTY2 PP_STAT_SEL /* Tx Empty, channel 2. 1 1 0 */
// TXEMPTY3 PP_STAT_SEL /* Tx Empty, channel 3. 1 1 1 */
/* BUSY LINE: A3 A2 A1
* --------
*/
#define RXDATA PP_STAT_BSY /* Rx Input Data, channel 0. 0 0 0 */
// RXDATA1 PP_STAT_BSY /* Rx Input Data, channel 1. 0 0 1 */
#define SYNC_DATA PP_STAT_BSY /* Reserved - Sync Data. 0 1 0 */
/* Reserved. 0 1 1 */
#define DATA_ECHO PP_STAT_BSY /* Parallel Port Data Echo. 1 0 0 */
#define A0_ECHO PP_STAT_BSY /* Address 0 Echo. 1 0 1 */
#define A1_ECHO PP_STAT_BSY /* Address 1 Echo. 1 1 0 */
#define A2_ECHO PP_STAT_BSY /* Address 2 Echo. 1 1 1 */
#define PORTMAN2X4_MODE_INPUT_TRIGGERED 0x01
/*********************************************************************
* Hardware specific functions
*********************************************************************/
static inline void portman_write_command(struct portman *pm, u8 value)
{
parport_write_control(pm->pardev->port, value);
}
static inline u8 portman_read_command(struct portman *pm)
{
return parport_read_control(pm->pardev->port);
}
static inline u8 portman_read_status(struct portman *pm)
{
return parport_read_status(pm->pardev->port);
}
static inline u8 portman_read_data(struct portman *pm)
{
return parport_read_data(pm->pardev->port);
}
static inline void portman_write_data(struct portman *pm, u8 value)
{
parport_write_data(pm->pardev->port, value);
}
static void portman_write_midi(struct portman *pm,
int port, u8 mididata)
{
int command = ((port + 4) << 1);
/* Get entering data byte and port number in BL and BH respectively.
* Set up Tx Channel address field for use with PP Cmd Register.
* Store address field in BH register.
* Inputs: AH = Output port number (0..3).
* AL = Data byte.
* command = TXDATA0 | INT_EN;
* Align port num with address field (b1...b3),
* set address for TXDatax, Strobe=0
*/
command |= INT_EN;
/* Disable interrupts so that the process is not interrupted, then
* write the address associated with the current Tx channel to the
* PP Command Reg. Do not set the Strobe signal yet.
*/
do {
portman_write_command(pm, command);
/* While the address lines settle, write parallel output data to
* PP Data Reg. This has no effect until Strobe signal is asserted.
*/
portman_write_data(pm, mididata);
/* If PCP channel's TxEmpty is set (TxEmpty is read through the PP
* Status Register), then go write data. Else go back and wait.
*/
} while ((portman_read_status(pm) & TXEMPTY) != TXEMPTY);
/* TxEmpty is set. Maintain PC/P destination address and assert
* Strobe through the PP Command Reg. This will Strobe data into
* the PC/P transmitter and set the PC/P BUSY signal.
*/
portman_write_command(pm, command | STROBE);
/* Wait for strobe line to settle and echo back through hardware.
* Once it has echoed back, assume that the address and data lines
* have settled!
*/
while ((portman_read_status(pm) & ESTB) == 0)
cpu_relax();
/* Release strobe and immediately re-allow interrupts. */
portman_write_command(pm, command);
while ((portman_read_status(pm) & ESTB) == ESTB)
cpu_relax();
/* PC/P BUSY is now set. We must wait until BUSY resets itself.
* We'll reenable ints while we're waiting.
*/
while ((portman_read_status(pm) & BUSY) == BUSY)
cpu_relax();
/* Data sent. */
}
/*
* Read MIDI byte from port
* Attempt to read input byte from specified hardware input port (0..).
* Return -1 if no data
*/
static int portman_read_midi(struct portman *pm, int port)
{
unsigned char midi_data = 0;
unsigned char cmdout; /* Saved address+IE bit. */
/* Make sure clocking edge is down before starting... */
portman_write_data(pm, 0); /* Make sure edge is down. */
/* Set destination address to PCP. */
cmdout = (port << 1) | INT_EN; /* Address + IE + No Strobe. */
portman_write_command(pm, cmdout);
while ((portman_read_status(pm) & ESTB) == ESTB)
cpu_relax(); /* Wait for strobe echo. */
/* After the address lines settle, check multiplexed RxAvail signal.
* If data is available, read it.
*/
if ((portman_read_status(pm) & RXAVAIL) == 0)
return -1; /* No data. */
/* Set the Strobe signal to enable the Rx clocking circuitry. */
portman_write_command(pm, cmdout | STROBE); /* Write address+IE+Strobe. */
while ((portman_read_status(pm) & ESTB) == 0)
cpu_relax(); /* Wait for strobe echo. */
/* The first data bit (msb) is already sitting on the input line. */
midi_data = (portman_read_status(pm) & 128);
portman_write_data(pm, 1); /* Cause rising edge, which shifts data. */
/* Data bit 6. */
portman_write_data(pm, 0); /* Cause falling edge while data settles. */
midi_data |= (portman_read_status(pm) >> 1) & 64;
portman_write_data(pm, 1); /* Cause rising edge, which shifts data. */
/* Data bit 5. */
portman_write_data(pm, 0); /* Cause falling edge while data settles. */
midi_data |= (portman_read_status(pm) >> 2) & 32;
portman_write_data(pm, 1); /* Cause rising edge, which shifts data. */
/* Data bit 4. */
portman_write_data(pm, 0); /* Cause falling edge while data settles. */
midi_data |= (portman_read_status(pm) >> 3) & 16;
portman_write_data(pm, 1); /* Cause rising edge, which shifts data. */
/* Data bit 3. */
portman_write_data(pm, 0); /* Cause falling edge while data settles. */
midi_data |= (portman_read_status(pm) >> 4) & 8;
portman_write_data(pm, 1); /* Cause rising edge, which shifts data. */
/* Data bit 2. */
portman_write_data(pm, 0); /* Cause falling edge while data settles. */
midi_data |= (portman_read_status(pm) >> 5) & 4;
portman_write_data(pm, 1); /* Cause rising edge, which shifts data. */
/* Data bit 1. */
portman_write_data(pm, 0); /* Cause falling edge while data settles. */
midi_data |= (portman_read_status(pm) >> 6) & 2;
portman_write_data(pm, 1); /* Cause rising edge, which shifts data. */
/* Data bit 0. */
portman_write_data(pm, 0); /* Cause falling edge while data settles. */
midi_data |= (portman_read_status(pm) >> 7) & 1;
portman_write_data(pm, 1); /* Cause rising edge, which shifts data. */
portman_write_data(pm, 0); /* Return data clock low. */
/* De-assert Strobe and return data. */
portman_write_command(pm, cmdout); /* Output saved address+IE. */
/* Wait for strobe echo. */
while ((portman_read_status(pm) & ESTB) == ESTB)
cpu_relax();
return (midi_data & 255); /* Shift back and return value. */
}
/*
* Checks if any input data on the given channel is available
* Checks RxAvail
*/
static int portman_data_avail(struct portman *pm, int channel)
{
int command = INT_EN;
switch (channel) {
case 0:
command |= RXDATA0;
break;
case 1:
command |= RXDATA1;
break;
}
/* Write hardware (assumme STROBE=0) */
portman_write_command(pm, command);
/* Check multiplexed RxAvail signal */
if ((portman_read_status(pm) & RXAVAIL) == RXAVAIL)
return 1; /* Data available */
/* No Data available */
return 0;
}
/*
* Flushes any input
*/
static void portman_flush_input(struct portman *pm, unsigned char port)
{
/* Local variable for counting things */
unsigned int i = 0;
unsigned char command = 0;
switch (port) {
case 0:
command = RXDATA0;
break;
case 1:
command = RXDATA1;
break;
default:
snd_printk(KERN_WARNING
"portman_flush_input() Won't flush port %i\n",
port);
return;
}
/* Set address for specified channel in port and allow to settle. */
portman_write_command(pm, command);
/* Assert the Strobe and wait for echo back. */
portman_write_command(pm, command | STROBE);
/* Wait for ESTB */
while ((portman_read_status(pm) & ESTB) == 0)
cpu_relax();
/* Output clock cycles to the Rx circuitry. */
portman_write_data(pm, 0);
/* Flush 250 bits... */
for (i = 0; i < 250; i++) {
portman_write_data(pm, 1);
portman_write_data(pm, 0);
}
/* Deassert the Strobe signal of the port and wait for it to settle. */
portman_write_command(pm, command | INT_EN);
/* Wait for settling */
while ((portman_read_status(pm) & ESTB) == ESTB)
cpu_relax();
}
static int portman_probe(struct parport *p)
{
/* Initialize the parallel port data register. Will set Rx clocks
* low in case we happen to be addressing the Rx ports at this time.
*/
/* 1 */
parport_write_data(p, 0);
/* Initialize the parallel port command register, thus initializing
* hardware handshake lines to midi box:
*
* Strobe = 0
* Interrupt Enable = 0
*/
/* 2 */
parport_write_control(p, 0);
/* Check if Portman PC/P 2x4 is out there. */
/* 3 */
parport_write_control(p, RXDATA0); /* Write Strobe=0 to command reg. */
/* Check for ESTB to be clear */
/* 4 */
if ((parport_read_status(p) & ESTB) == ESTB)
return 1; /* CODE 1 - Strobe Failure. */
/* Set for RXDATA0 where no damage will be done. */
/* 5 */
parport_write_control(p, RXDATA0 + STROBE); /* Write Strobe=1 to command reg. */
/* 6 */
if ((parport_read_status(p) & ESTB) != ESTB)
return 1; /* CODE 1 - Strobe Failure. */
/* 7 */
parport_write_control(p, 0); /* Reset Strobe=0. */
/* Check if Tx circuitry is functioning properly. If initialized
* unit TxEmpty is false, send out char and see if if goes true.
*/
/* 8 */
parport_write_control(p, TXDATA0); /* Tx channel 0, strobe off. */
/* If PCP channel's TxEmpty is set (TxEmpty is read through the PP
* Status Register), then go write data. Else go back and wait.
*/
/* 9 */
if ((parport_read_status(p) & TXEMPTY) == 0)
return 2;
/* Return OK status. */
return 0;
}
static int portman_device_init(struct portman *pm)
{
portman_flush_input(pm, 0);
portman_flush_input(pm, 1);
return 0;
}
/*********************************************************************
* Rawmidi
*********************************************************************/
static int snd_portman_midi_open(struct snd_rawmidi_substream *substream)
{
return 0;
}
static int snd_portman_midi_close(struct snd_rawmidi_substream *substream)
{
return 0;
}
static void snd_portman_midi_input_trigger(struct snd_rawmidi_substream *substream,
int up)
{
struct portman *pm = substream->rmidi->private_data;
unsigned long flags;
spin_lock_irqsave(&pm->reg_lock, flags);
if (up)
pm->mode[substream->number] |= PORTMAN2X4_MODE_INPUT_TRIGGERED;
else
pm->mode[substream->number] &= ~PORTMAN2X4_MODE_INPUT_TRIGGERED;
spin_unlock_irqrestore(&pm->reg_lock, flags);
}
static void snd_portman_midi_output_trigger(struct snd_rawmidi_substream *substream,
int up)
{
struct portman *pm = substream->rmidi->private_data;
unsigned long flags;
unsigned char byte;
spin_lock_irqsave(&pm->reg_lock, flags);
if (up) {
while ((snd_rawmidi_transmit(substream, &byte, 1) == 1))
portman_write_midi(pm, substream->number, byte);
}
spin_unlock_irqrestore(&pm->reg_lock, flags);
}
static struct snd_rawmidi_ops snd_portman_midi_output = {
.open = snd_portman_midi_open,
.close = snd_portman_midi_close,
.trigger = snd_portman_midi_output_trigger,
};
static struct snd_rawmidi_ops snd_portman_midi_input = {
.open = snd_portman_midi_open,
.close = snd_portman_midi_close,
.trigger = snd_portman_midi_input_trigger,
};
/* Create and initialize the rawmidi component */
static int __devinit snd_portman_rawmidi_create(struct snd_card *card)
{
struct portman *pm = card->private_data;
struct snd_rawmidi *rmidi;
struct snd_rawmidi_substream *substream;
int err;
err = snd_rawmidi_new(card, CARD_NAME, 0,
PORTMAN_NUM_OUTPUT_PORTS,
PORTMAN_NUM_INPUT_PORTS,
&rmidi);
if (err < 0)
return err;
rmidi->private_data = pm;
strcpy(rmidi->name, CARD_NAME);
rmidi->info_flags = SNDRV_RAWMIDI_INFO_OUTPUT |
SNDRV_RAWMIDI_INFO_INPUT |
SNDRV_RAWMIDI_INFO_DUPLEX;
pm->rmidi = rmidi;
/* register rawmidi ops */
snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_OUTPUT,
&snd_portman_midi_output);
snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_INPUT,
&snd_portman_midi_input);
/* name substreams */
/* output */
list_for_each_entry(substream,
&rmidi->streams[SNDRV_RAWMIDI_STREAM_OUTPUT].substreams,
list) {
sprintf(substream->name,
"Portman2x4 %d", substream->number+1);
}
/* input */
list_for_each_entry(substream,
&rmidi->streams[SNDRV_RAWMIDI_STREAM_INPUT].substreams,
list) {
pm->midi_input[substream->number] = substream;
sprintf(substream->name,
"Portman2x4 %d", substream->number+1);
}
return err;
}
/*********************************************************************
* parport stuff
*********************************************************************/
static void snd_portman_interrupt(void *userdata)
{
unsigned char midivalue = 0;
struct portman *pm = ((struct snd_card*)userdata)->private_data;
spin_lock(&pm->reg_lock);
/* While any input data is waiting */
while ((portman_read_status(pm) & INT_REQ) == INT_REQ) {
/* If data available on channel 0,
read it and stuff it into the queue. */
if (portman_data_avail(pm, 0)) {
/* Read Midi */
midivalue = portman_read_midi(pm, 0);
/* put midi into queue... */
if (pm->mode[0] & PORTMAN2X4_MODE_INPUT_TRIGGERED)
snd_rawmidi_receive(pm->midi_input[0],
&midivalue, 1);
}
/* If data available on channel 1,
read it and stuff it into the queue. */
if (portman_data_avail(pm, 1)) {
/* Read Midi */
midivalue = portman_read_midi(pm, 1);
/* put midi into queue... */
if (pm->mode[1] & PORTMAN2X4_MODE_INPUT_TRIGGERED)
snd_rawmidi_receive(pm->midi_input[1],
&midivalue, 1);
}
}
spin_unlock(&pm->reg_lock);
}
static int __devinit snd_portman_probe_port(struct parport *p)
{
struct pardevice *pardev;
int res;
pardev = parport_register_device(p, DRIVER_NAME,
NULL, NULL, NULL,
0, NULL);
if (!pardev)
return -EIO;
if (parport_claim(pardev)) {
parport_unregister_device(pardev);
return -EIO;
}
res = portman_probe(p);
parport_release(pardev);
parport_unregister_device(pardev);
return res ? -EIO : 0;
}
static void __devinit snd_portman_attach(struct parport *p)
{
struct platform_device *device;
device = platform_device_alloc(PLATFORM_DRIVER, device_count);
if (!device)
return;
/* Temporary assignment to forward the parport */
platform_set_drvdata(device, p);
if (platform_device_add(device) < 0) {
platform_device_put(device);
return;
}
/* Since we dont get the return value of probe
* We need to check if device probing succeeded or not */
if (!platform_get_drvdata(device)) {
platform_device_unregister(device);
return;
}
/* register device in global table */
platform_devices[device_count] = device;
device_count++;
}
static void snd_portman_detach(struct parport *p)
{
/* nothing to do here */
}
static struct parport_driver portman_parport_driver = {
.name = "portman2x4",
.attach = snd_portman_attach,
.detach = snd_portman_detach
};
/*********************************************************************
* platform stuff
*********************************************************************/
static void snd_portman_card_private_free(struct snd_card *card)
{
struct portman *pm = card->private_data;
struct pardevice *pardev = pm->pardev;
if (pardev) {
if (pm->pardev_claimed)
parport_release(pardev);
parport_unregister_device(pardev);
}
portman_free(pm);
}
static int __devinit snd_portman_probe(struct platform_device *pdev)
{
struct pardevice *pardev;
struct parport *p;
int dev = pdev->id;
struct snd_card *card = NULL;
struct portman *pm = NULL;
int err;
p = platform_get_drvdata(pdev);
platform_set_drvdata(pdev, NULL);
if (dev >= SNDRV_CARDS)
return -ENODEV;
if (!enable[dev])
return -ENOENT;
if ((err = snd_portman_probe_port(p)) < 0)
return err;
err = snd_card_create(index[dev], id[dev], THIS_MODULE, 0, &card);
if (err < 0) {
snd_printd("Cannot create card\n");
return err;
}
strcpy(card->driver, DRIVER_NAME);
strcpy(card->shortname, CARD_NAME);
sprintf(card->longname, "%s at 0x%lx, irq %i",
card->shortname, p->base, p->irq);
pardev = parport_register_device(p, /* port */
DRIVER_NAME, /* name */
NULL, /* preempt */
NULL, /* wakeup */
snd_portman_interrupt, /* ISR */
PARPORT_DEV_EXCL, /* flags */
(void *)card); /* private */
if (pardev == NULL) {
snd_printd("Cannot register pardevice\n");
err = -EIO;
goto __err;
}
if ((err = portman_create(card, pardev, &pm)) < 0) {
snd_printd("Cannot create main component\n");
parport_unregister_device(pardev);
goto __err;
}
card->private_data = pm;
card->private_free = snd_portman_card_private_free;
if ((err = snd_portman_rawmidi_create(card)) < 0) {
snd_printd("Creating Rawmidi component failed\n");
goto __err;
}
/* claim parport */
if (parport_claim(pardev)) {
snd_printd("Cannot claim parport 0x%lx\n", pardev->port->base);
err = -EIO;
goto __err;
}
pm->pardev_claimed = 1;
/* init device */
if ((err = portman_device_init(pm)) < 0)
goto __err;
platform_set_drvdata(pdev, card);
snd_card_set_dev(card, &pdev->dev);
/* At this point card will be usable */
if ((err = snd_card_register(card)) < 0) {
snd_printd("Cannot register card\n");
goto __err;
}
snd_printk(KERN_INFO "Portman 2x4 on 0x%lx\n", p->base);
return 0;
__err:
snd_card_free(card);
return err;
}
static int __devexit snd_portman_remove(struct platform_device *pdev)
{
struct snd_card *card = platform_get_drvdata(pdev);
if (card)
snd_card_free(card);
return 0;
}
static struct platform_driver snd_portman_driver = {
.probe = snd_portman_probe,
.remove = __devexit_p(snd_portman_remove),
.driver = {
.name = PLATFORM_DRIVER
}
};
/*********************************************************************
* module init stuff
*********************************************************************/
static void snd_portman_unregister_all(void)
{
int i;
for (i = 0; i < SNDRV_CARDS; ++i) {
if (platform_devices[i]) {
platform_device_unregister(platform_devices[i]);
platform_devices[i] = NULL;
}
}
platform_driver_unregister(&snd_portman_driver);
parport_unregister_driver(&portman_parport_driver);
}
static int __init snd_portman_module_init(void)
{
int err;
if ((err = platform_driver_register(&snd_portman_driver)) < 0)
return err;
if (parport_register_driver(&portman_parport_driver) != 0) {
platform_driver_unregister(&snd_portman_driver);
return -EIO;
}
if (device_count == 0) {
snd_portman_unregister_all();
return -ENODEV;
}
return 0;
}
static void __exit snd_portman_module_exit(void)
{
snd_portman_unregister_all();
}
module_init(snd_portman_module_init);
module_exit(snd_portman_module_exit);
| gpl-2.0 |
UISS-Dev-Team/android_kernel_huawei_msm8x25 | drivers/hwmon/mcp3021.c | 4942 | 4005 | /*
* mcp3021.c - driver for the Microchip MCP3021 chip
*
* Copyright (C) 2008-2009, 2012 Freescale Semiconductor, Inc.
* Author: Mingkai Hu <Mingkai.hu@freescale.com>
*
* This driver export the value of analog input voltage to sysfs, the
* voltage unit is mV. Through the sysfs interface, lm-sensors tool
* can also display the input voltage.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/hwmon.h>
#include <linux/slab.h>
#include <linux/i2c.h>
#include <linux/err.h>
#include <linux/device.h>
/* Vdd info */
#define MCP3021_VDD_MAX 5500
#define MCP3021_VDD_MIN 2700
#define MCP3021_VDD_REF 3300
/* output format */
#define MCP3021_SAR_SHIFT 2
#define MCP3021_SAR_MASK 0x3ff
#define MCP3021_OUTPUT_RES 10 /* 10-bit resolution */
#define MCP3021_OUTPUT_SCALE 4
/*
* Client data (each client gets its own)
*/
struct mcp3021_data {
struct device *hwmon_dev;
u32 vdd; /* device power supply */
};
static int mcp3021_read16(struct i2c_client *client)
{
int ret;
u16 reg;
__be16 buf;
ret = i2c_master_recv(client, (char *)&buf, 2);
if (ret < 0)
return ret;
if (ret != 2)
return -EIO;
/* The output code of the MCP3021 is transmitted with MSB first. */
reg = be16_to_cpu(buf);
/*
* The ten-bit output code is composed of the lower 4-bit of the
* first byte and the upper 6-bit of the second byte.
*/
reg = (reg >> MCP3021_SAR_SHIFT) & MCP3021_SAR_MASK;
return reg;
}
static inline u16 volts_from_reg(u16 vdd, u16 val)
{
if (val == 0)
return 0;
val = val * MCP3021_OUTPUT_SCALE - MCP3021_OUTPUT_SCALE / 2;
return val * DIV_ROUND_CLOSEST(vdd,
(1 << MCP3021_OUTPUT_RES) * MCP3021_OUTPUT_SCALE);
}
static ssize_t show_in_input(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct i2c_client *client = to_i2c_client(dev);
struct mcp3021_data *data = i2c_get_clientdata(client);
int reg, in_input;
reg = mcp3021_read16(client);
if (reg < 0)
return reg;
in_input = volts_from_reg(data->vdd, reg);
return sprintf(buf, "%d\n", in_input);
}
static DEVICE_ATTR(in0_input, S_IRUGO, show_in_input, NULL);
static int mcp3021_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
int err;
struct mcp3021_data *data = NULL;
if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C))
return -ENODEV;
data = kzalloc(sizeof(struct mcp3021_data), GFP_KERNEL);
if (!data)
return -ENOMEM;
i2c_set_clientdata(client, data);
if (client->dev.platform_data) {
data->vdd = *(u32 *)client->dev.platform_data;
if (data->vdd > MCP3021_VDD_MAX ||
data->vdd < MCP3021_VDD_MIN) {
err = -EINVAL;
goto exit_free;
}
} else
data->vdd = MCP3021_VDD_REF;
err = sysfs_create_file(&client->dev.kobj, &dev_attr_in0_input.attr);
if (err)
goto exit_free;
data->hwmon_dev = hwmon_device_register(&client->dev);
if (IS_ERR(data->hwmon_dev)) {
err = PTR_ERR(data->hwmon_dev);
goto exit_remove;
}
return 0;
exit_remove:
sysfs_remove_file(&client->dev.kobj, &dev_attr_in0_input.attr);
exit_free:
kfree(data);
return err;
}
static int mcp3021_remove(struct i2c_client *client)
{
struct mcp3021_data *data = i2c_get_clientdata(client);
hwmon_device_unregister(data->hwmon_dev);
sysfs_remove_file(&client->dev.kobj, &dev_attr_in0_input.attr);
kfree(data);
return 0;
}
static const struct i2c_device_id mcp3021_id[] = {
{ "mcp3021", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, mcp3021_id);
static struct i2c_driver mcp3021_driver = {
.driver = {
.name = "mcp3021",
},
.probe = mcp3021_probe,
.remove = mcp3021_remove,
.id_table = mcp3021_id,
};
module_i2c_driver(mcp3021_driver);
MODULE_AUTHOR("Mingkai Hu <Mingkai.hu@freescale.com>");
MODULE_DESCRIPTION("Microchip MCP3021 driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
akw28888/caf2 | drivers/gpu/drm/radeon/radeon_encoders.c | 4942 | 11912 | /*
* Copyright 2007-8 Advanced Micro Devices, Inc.
* Copyright 2008 Red Hat Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Dave Airlie
* Alex Deucher
*/
#include "drmP.h"
#include "drm_crtc_helper.h"
#include "radeon_drm.h"
#include "radeon.h"
#include "atom.h"
static uint32_t radeon_encoder_clones(struct drm_encoder *encoder)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
struct drm_encoder *clone_encoder;
uint32_t index_mask = 0;
int count;
/* DIG routing gets problematic */
if (rdev->family >= CHIP_R600)
return index_mask;
/* LVDS/TV are too wacky */
if (radeon_encoder->devices & ATOM_DEVICE_LCD_SUPPORT)
return index_mask;
/* DVO requires 2x ppll clocks depending on tmds chip */
if (radeon_encoder->devices & ATOM_DEVICE_DFP2_SUPPORT)
return index_mask;
count = -1;
list_for_each_entry(clone_encoder, &dev->mode_config.encoder_list, head) {
struct radeon_encoder *radeon_clone = to_radeon_encoder(clone_encoder);
count++;
if (clone_encoder == encoder)
continue;
if (radeon_clone->devices & (ATOM_DEVICE_LCD_SUPPORT))
continue;
if (radeon_clone->devices & ATOM_DEVICE_DFP2_SUPPORT)
continue;
else
index_mask |= (1 << count);
}
return index_mask;
}
void radeon_setup_encoder_clones(struct drm_device *dev)
{
struct drm_encoder *encoder;
list_for_each_entry(encoder, &dev->mode_config.encoder_list, head) {
encoder->possible_clones = radeon_encoder_clones(encoder);
}
}
uint32_t
radeon_get_encoder_enum(struct drm_device *dev, uint32_t supported_device, uint8_t dac)
{
struct radeon_device *rdev = dev->dev_private;
uint32_t ret = 0;
switch (supported_device) {
case ATOM_DEVICE_CRT1_SUPPORT:
case ATOM_DEVICE_TV1_SUPPORT:
case ATOM_DEVICE_TV2_SUPPORT:
case ATOM_DEVICE_CRT2_SUPPORT:
case ATOM_DEVICE_CV_SUPPORT:
switch (dac) {
case 1: /* dac a */
if ((rdev->family == CHIP_RS300) ||
(rdev->family == CHIP_RS400) ||
(rdev->family == CHIP_RS480))
ret = ENCODER_INTERNAL_DAC2_ENUM_ID1;
else if (ASIC_IS_AVIVO(rdev))
ret = ENCODER_INTERNAL_KLDSCP_DAC1_ENUM_ID1;
else
ret = ENCODER_INTERNAL_DAC1_ENUM_ID1;
break;
case 2: /* dac b */
if (ASIC_IS_AVIVO(rdev))
ret = ENCODER_INTERNAL_KLDSCP_DAC2_ENUM_ID1;
else {
/*if (rdev->family == CHIP_R200)
ret = ENCODER_INTERNAL_DVO1_ENUM_ID1;
else*/
ret = ENCODER_INTERNAL_DAC2_ENUM_ID1;
}
break;
case 3: /* external dac */
if (ASIC_IS_AVIVO(rdev))
ret = ENCODER_INTERNAL_KLDSCP_DVO1_ENUM_ID1;
else
ret = ENCODER_INTERNAL_DVO1_ENUM_ID1;
break;
}
break;
case ATOM_DEVICE_LCD1_SUPPORT:
if (ASIC_IS_AVIVO(rdev))
ret = ENCODER_INTERNAL_LVTM1_ENUM_ID1;
else
ret = ENCODER_INTERNAL_LVDS_ENUM_ID1;
break;
case ATOM_DEVICE_DFP1_SUPPORT:
if ((rdev->family == CHIP_RS300) ||
(rdev->family == CHIP_RS400) ||
(rdev->family == CHIP_RS480))
ret = ENCODER_INTERNAL_DVO1_ENUM_ID1;
else if (ASIC_IS_AVIVO(rdev))
ret = ENCODER_INTERNAL_KLDSCP_TMDS1_ENUM_ID1;
else
ret = ENCODER_INTERNAL_TMDS1_ENUM_ID1;
break;
case ATOM_DEVICE_LCD2_SUPPORT:
case ATOM_DEVICE_DFP2_SUPPORT:
if ((rdev->family == CHIP_RS600) ||
(rdev->family == CHIP_RS690) ||
(rdev->family == CHIP_RS740))
ret = ENCODER_INTERNAL_DDI_ENUM_ID1;
else if (ASIC_IS_AVIVO(rdev))
ret = ENCODER_INTERNAL_KLDSCP_DVO1_ENUM_ID1;
else
ret = ENCODER_INTERNAL_DVO1_ENUM_ID1;
break;
case ATOM_DEVICE_DFP3_SUPPORT:
ret = ENCODER_INTERNAL_LVTM1_ENUM_ID1;
break;
}
return ret;
}
void
radeon_link_encoder_connector(struct drm_device *dev)
{
struct drm_connector *connector;
struct radeon_connector *radeon_connector;
struct drm_encoder *encoder;
struct radeon_encoder *radeon_encoder;
/* walk the list and link encoders to connectors */
list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
radeon_connector = to_radeon_connector(connector);
list_for_each_entry(encoder, &dev->mode_config.encoder_list, head) {
radeon_encoder = to_radeon_encoder(encoder);
if (radeon_encoder->devices & radeon_connector->devices)
drm_mode_connector_attach_encoder(connector, encoder);
}
}
}
void radeon_encoder_set_active_device(struct drm_encoder *encoder)
{
struct drm_device *dev = encoder->dev;
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
struct drm_connector *connector;
list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
if (connector->encoder == encoder) {
struct radeon_connector *radeon_connector = to_radeon_connector(connector);
radeon_encoder->active_device = radeon_encoder->devices & radeon_connector->devices;
DRM_DEBUG_KMS("setting active device to %08x from %08x %08x for encoder %d\n",
radeon_encoder->active_device, radeon_encoder->devices,
radeon_connector->devices, encoder->encoder_type);
}
}
}
struct drm_connector *
radeon_get_connector_for_encoder(struct drm_encoder *encoder)
{
struct drm_device *dev = encoder->dev;
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
struct drm_connector *connector;
struct radeon_connector *radeon_connector;
list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
radeon_connector = to_radeon_connector(connector);
if (radeon_encoder->active_device & radeon_connector->devices)
return connector;
}
return NULL;
}
struct drm_connector *
radeon_get_connector_for_encoder_init(struct drm_encoder *encoder)
{
struct drm_device *dev = encoder->dev;
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
struct drm_connector *connector;
struct radeon_connector *radeon_connector;
list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
radeon_connector = to_radeon_connector(connector);
if (radeon_encoder->devices & radeon_connector->devices)
return connector;
}
return NULL;
}
struct drm_encoder *radeon_get_external_encoder(struct drm_encoder *encoder)
{
struct drm_device *dev = encoder->dev;
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
struct drm_encoder *other_encoder;
struct radeon_encoder *other_radeon_encoder;
if (radeon_encoder->is_ext_encoder)
return NULL;
list_for_each_entry(other_encoder, &dev->mode_config.encoder_list, head) {
if (other_encoder == encoder)
continue;
other_radeon_encoder = to_radeon_encoder(other_encoder);
if (other_radeon_encoder->is_ext_encoder &&
(radeon_encoder->devices & other_radeon_encoder->devices))
return other_encoder;
}
return NULL;
}
u16 radeon_encoder_get_dp_bridge_encoder_id(struct drm_encoder *encoder)
{
struct drm_encoder *other_encoder = radeon_get_external_encoder(encoder);
if (other_encoder) {
struct radeon_encoder *radeon_encoder = to_radeon_encoder(other_encoder);
switch (radeon_encoder->encoder_id) {
case ENCODER_OBJECT_ID_TRAVIS:
case ENCODER_OBJECT_ID_NUTMEG:
return radeon_encoder->encoder_id;
default:
return ENCODER_OBJECT_ID_NONE;
}
}
return ENCODER_OBJECT_ID_NONE;
}
void radeon_panel_mode_fixup(struct drm_encoder *encoder,
struct drm_display_mode *adjusted_mode)
{
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
struct drm_display_mode *native_mode = &radeon_encoder->native_mode;
unsigned hblank = native_mode->htotal - native_mode->hdisplay;
unsigned vblank = native_mode->vtotal - native_mode->vdisplay;
unsigned hover = native_mode->hsync_start - native_mode->hdisplay;
unsigned vover = native_mode->vsync_start - native_mode->vdisplay;
unsigned hsync_width = native_mode->hsync_end - native_mode->hsync_start;
unsigned vsync_width = native_mode->vsync_end - native_mode->vsync_start;
adjusted_mode->clock = native_mode->clock;
adjusted_mode->flags = native_mode->flags;
if (ASIC_IS_AVIVO(rdev)) {
adjusted_mode->hdisplay = native_mode->hdisplay;
adjusted_mode->vdisplay = native_mode->vdisplay;
}
adjusted_mode->htotal = native_mode->hdisplay + hblank;
adjusted_mode->hsync_start = native_mode->hdisplay + hover;
adjusted_mode->hsync_end = adjusted_mode->hsync_start + hsync_width;
adjusted_mode->vtotal = native_mode->vdisplay + vblank;
adjusted_mode->vsync_start = native_mode->vdisplay + vover;
adjusted_mode->vsync_end = adjusted_mode->vsync_start + vsync_width;
drm_mode_set_crtcinfo(adjusted_mode, CRTC_INTERLACE_HALVE_V);
if (ASIC_IS_AVIVO(rdev)) {
adjusted_mode->crtc_hdisplay = native_mode->hdisplay;
adjusted_mode->crtc_vdisplay = native_mode->vdisplay;
}
adjusted_mode->crtc_htotal = adjusted_mode->crtc_hdisplay + hblank;
adjusted_mode->crtc_hsync_start = adjusted_mode->crtc_hdisplay + hover;
adjusted_mode->crtc_hsync_end = adjusted_mode->crtc_hsync_start + hsync_width;
adjusted_mode->crtc_vtotal = adjusted_mode->crtc_vdisplay + vblank;
adjusted_mode->crtc_vsync_start = adjusted_mode->crtc_vdisplay + vover;
adjusted_mode->crtc_vsync_end = adjusted_mode->crtc_vsync_start + vsync_width;
}
bool radeon_dig_monitor_is_duallink(struct drm_encoder *encoder,
u32 pixel_clock)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
struct drm_connector *connector;
struct radeon_connector *radeon_connector;
struct radeon_connector_atom_dig *dig_connector;
connector = radeon_get_connector_for_encoder(encoder);
/* if we don't have an active device yet, just use one of
* the connectors tied to the encoder.
*/
if (!connector)
connector = radeon_get_connector_for_encoder_init(encoder);
radeon_connector = to_radeon_connector(connector);
switch (connector->connector_type) {
case DRM_MODE_CONNECTOR_DVII:
case DRM_MODE_CONNECTOR_HDMIB:
if (radeon_connector->use_digital) {
/* HDMI 1.3 supports up to 340 Mhz over single link */
if (ASIC_IS_DCE6(rdev) && drm_detect_hdmi_monitor(radeon_connector->edid)) {
if (pixel_clock > 340000)
return true;
else
return false;
} else {
if (pixel_clock > 165000)
return true;
else
return false;
}
} else
return false;
case DRM_MODE_CONNECTOR_DVID:
case DRM_MODE_CONNECTOR_HDMIA:
case DRM_MODE_CONNECTOR_DisplayPort:
dig_connector = radeon_connector->con_priv;
if ((dig_connector->dp_sink_type == CONNECTOR_OBJECT_ID_DISPLAYPORT) ||
(dig_connector->dp_sink_type == CONNECTOR_OBJECT_ID_eDP))
return false;
else {
/* HDMI 1.3 supports up to 340 Mhz over single link */
if (ASIC_IS_DCE6(rdev) && drm_detect_hdmi_monitor(radeon_connector->edid)) {
if (pixel_clock > 340000)
return true;
else
return false;
} else {
if (pixel_clock > 165000)
return true;
else
return false;
}
}
default:
return false;
}
}
| gpl-2.0 |
gdetal/kernel_msm_mptcp | drivers/i2c/busses/i2c-amd8111.c | 4942 | 12503 | /*
* SMBus 2.0 driver for AMD-8111 IO-Hub.
*
* Copyright (c) 2002 Vojtech Pavlik
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation version 2.
*/
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/kernel.h>
#include <linux/stddef.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <linux/i2c.h>
#include <linux/delay.h>
#include <linux/acpi.h>
#include <linux/slab.h>
#include <linux/io.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR ("Vojtech Pavlik <vojtech@suse.cz>");
MODULE_DESCRIPTION("AMD8111 SMBus 2.0 driver");
struct amd_smbus {
struct pci_dev *dev;
struct i2c_adapter adapter;
int base;
int size;
};
static struct pci_driver amd8111_driver;
/*
* AMD PCI control registers definitions.
*/
#define AMD_PCI_MISC 0x48
#define AMD_PCI_MISC_SCI 0x04 /* deliver SCI */
#define AMD_PCI_MISC_INT 0x02 /* deliver PCI IRQ */
#define AMD_PCI_MISC_SPEEDUP 0x01 /* 16x clock speedup */
/*
* ACPI 2.0 chapter 13 PCI interface definitions.
*/
#define AMD_EC_DATA 0x00 /* data register */
#define AMD_EC_SC 0x04 /* status of controller */
#define AMD_EC_CMD 0x04 /* command register */
#define AMD_EC_ICR 0x08 /* interrupt control register */
#define AMD_EC_SC_SMI 0x04 /* smi event pending */
#define AMD_EC_SC_SCI 0x02 /* sci event pending */
#define AMD_EC_SC_BURST 0x01 /* burst mode enabled */
#define AMD_EC_SC_CMD 0x08 /* byte in data reg is command */
#define AMD_EC_SC_IBF 0x02 /* data ready for embedded controller */
#define AMD_EC_SC_OBF 0x01 /* data ready for host */
#define AMD_EC_CMD_RD 0x80 /* read EC */
#define AMD_EC_CMD_WR 0x81 /* write EC */
#define AMD_EC_CMD_BE 0x82 /* enable burst mode */
#define AMD_EC_CMD_BD 0x83 /* disable burst mode */
#define AMD_EC_CMD_QR 0x84 /* query EC */
/*
* ACPI 2.0 chapter 13 access of registers of the EC
*/
static int amd_ec_wait_write(struct amd_smbus *smbus)
{
int timeout = 500;
while ((inb(smbus->base + AMD_EC_SC) & AMD_EC_SC_IBF) && --timeout)
udelay(1);
if (!timeout) {
dev_warn(&smbus->dev->dev,
"Timeout while waiting for IBF to clear\n");
return -ETIMEDOUT;
}
return 0;
}
static int amd_ec_wait_read(struct amd_smbus *smbus)
{
int timeout = 500;
while ((~inb(smbus->base + AMD_EC_SC) & AMD_EC_SC_OBF) && --timeout)
udelay(1);
if (!timeout) {
dev_warn(&smbus->dev->dev,
"Timeout while waiting for OBF to set\n");
return -ETIMEDOUT;
}
return 0;
}
static int amd_ec_read(struct amd_smbus *smbus, unsigned char address,
unsigned char *data)
{
int status;
status = amd_ec_wait_write(smbus);
if (status)
return status;
outb(AMD_EC_CMD_RD, smbus->base + AMD_EC_CMD);
status = amd_ec_wait_write(smbus);
if (status)
return status;
outb(address, smbus->base + AMD_EC_DATA);
status = amd_ec_wait_read(smbus);
if (status)
return status;
*data = inb(smbus->base + AMD_EC_DATA);
return 0;
}
static int amd_ec_write(struct amd_smbus *smbus, unsigned char address,
unsigned char data)
{
int status;
status = amd_ec_wait_write(smbus);
if (status)
return status;
outb(AMD_EC_CMD_WR, smbus->base + AMD_EC_CMD);
status = amd_ec_wait_write(smbus);
if (status)
return status;
outb(address, smbus->base + AMD_EC_DATA);
status = amd_ec_wait_write(smbus);
if (status)
return status;
outb(data, smbus->base + AMD_EC_DATA);
return 0;
}
/*
* ACPI 2.0 chapter 13 SMBus 2.0 EC register model
*/
#define AMD_SMB_PRTCL 0x00 /* protocol, PEC */
#define AMD_SMB_STS 0x01 /* status */
#define AMD_SMB_ADDR 0x02 /* address */
#define AMD_SMB_CMD 0x03 /* command */
#define AMD_SMB_DATA 0x04 /* 32 data registers */
#define AMD_SMB_BCNT 0x24 /* number of data bytes */
#define AMD_SMB_ALRM_A 0x25 /* alarm address */
#define AMD_SMB_ALRM_D 0x26 /* 2 bytes alarm data */
#define AMD_SMB_STS_DONE 0x80
#define AMD_SMB_STS_ALRM 0x40
#define AMD_SMB_STS_RES 0x20
#define AMD_SMB_STS_STATUS 0x1f
#define AMD_SMB_STATUS_OK 0x00
#define AMD_SMB_STATUS_FAIL 0x07
#define AMD_SMB_STATUS_DNAK 0x10
#define AMD_SMB_STATUS_DERR 0x11
#define AMD_SMB_STATUS_CMD_DENY 0x12
#define AMD_SMB_STATUS_UNKNOWN 0x13
#define AMD_SMB_STATUS_ACC_DENY 0x17
#define AMD_SMB_STATUS_TIMEOUT 0x18
#define AMD_SMB_STATUS_NOTSUP 0x19
#define AMD_SMB_STATUS_BUSY 0x1A
#define AMD_SMB_STATUS_PEC 0x1F
#define AMD_SMB_PRTCL_WRITE 0x00
#define AMD_SMB_PRTCL_READ 0x01
#define AMD_SMB_PRTCL_QUICK 0x02
#define AMD_SMB_PRTCL_BYTE 0x04
#define AMD_SMB_PRTCL_BYTE_DATA 0x06
#define AMD_SMB_PRTCL_WORD_DATA 0x08
#define AMD_SMB_PRTCL_BLOCK_DATA 0x0a
#define AMD_SMB_PRTCL_PROC_CALL 0x0c
#define AMD_SMB_PRTCL_BLOCK_PROC_CALL 0x0d
#define AMD_SMB_PRTCL_I2C_BLOCK_DATA 0x4a
#define AMD_SMB_PRTCL_PEC 0x80
static s32 amd8111_access(struct i2c_adapter * adap, u16 addr,
unsigned short flags, char read_write, u8 command, int size,
union i2c_smbus_data * data)
{
struct amd_smbus *smbus = adap->algo_data;
unsigned char protocol, len, pec, temp[2];
int i, status;
protocol = (read_write == I2C_SMBUS_READ) ? AMD_SMB_PRTCL_READ
: AMD_SMB_PRTCL_WRITE;
pec = (flags & I2C_CLIENT_PEC) ? AMD_SMB_PRTCL_PEC : 0;
switch (size) {
case I2C_SMBUS_QUICK:
protocol |= AMD_SMB_PRTCL_QUICK;
read_write = I2C_SMBUS_WRITE;
break;
case I2C_SMBUS_BYTE:
if (read_write == I2C_SMBUS_WRITE) {
status = amd_ec_write(smbus, AMD_SMB_CMD,
command);
if (status)
return status;
}
protocol |= AMD_SMB_PRTCL_BYTE;
break;
case I2C_SMBUS_BYTE_DATA:
status = amd_ec_write(smbus, AMD_SMB_CMD, command);
if (status)
return status;
if (read_write == I2C_SMBUS_WRITE) {
status = amd_ec_write(smbus, AMD_SMB_DATA,
data->byte);
if (status)
return status;
}
protocol |= AMD_SMB_PRTCL_BYTE_DATA;
break;
case I2C_SMBUS_WORD_DATA:
status = amd_ec_write(smbus, AMD_SMB_CMD, command);
if (status)
return status;
if (read_write == I2C_SMBUS_WRITE) {
status = amd_ec_write(smbus, AMD_SMB_DATA,
data->word & 0xff);
if (status)
return status;
status = amd_ec_write(smbus, AMD_SMB_DATA + 1,
data->word >> 8);
if (status)
return status;
}
protocol |= AMD_SMB_PRTCL_WORD_DATA | pec;
break;
case I2C_SMBUS_BLOCK_DATA:
status = amd_ec_write(smbus, AMD_SMB_CMD, command);
if (status)
return status;
if (read_write == I2C_SMBUS_WRITE) {
len = min_t(u8, data->block[0],
I2C_SMBUS_BLOCK_MAX);
status = amd_ec_write(smbus, AMD_SMB_BCNT, len);
if (status)
return status;
for (i = 0; i < len; i++) {
status =
amd_ec_write(smbus, AMD_SMB_DATA + i,
data->block[i + 1]);
if (status)
return status;
}
}
protocol |= AMD_SMB_PRTCL_BLOCK_DATA | pec;
break;
case I2C_SMBUS_I2C_BLOCK_DATA:
len = min_t(u8, data->block[0],
I2C_SMBUS_BLOCK_MAX);
status = amd_ec_write(smbus, AMD_SMB_CMD, command);
if (status)
return status;
status = amd_ec_write(smbus, AMD_SMB_BCNT, len);
if (status)
return status;
if (read_write == I2C_SMBUS_WRITE)
for (i = 0; i < len; i++) {
status =
amd_ec_write(smbus, AMD_SMB_DATA + i,
data->block[i + 1]);
if (status)
return status;
}
protocol |= AMD_SMB_PRTCL_I2C_BLOCK_DATA;
break;
case I2C_SMBUS_PROC_CALL:
status = amd_ec_write(smbus, AMD_SMB_CMD, command);
if (status)
return status;
status = amd_ec_write(smbus, AMD_SMB_DATA,
data->word & 0xff);
if (status)
return status;
status = amd_ec_write(smbus, AMD_SMB_DATA + 1,
data->word >> 8);
if (status)
return status;
protocol = AMD_SMB_PRTCL_PROC_CALL | pec;
read_write = I2C_SMBUS_READ;
break;
case I2C_SMBUS_BLOCK_PROC_CALL:
len = min_t(u8, data->block[0],
I2C_SMBUS_BLOCK_MAX - 1);
status = amd_ec_write(smbus, AMD_SMB_CMD, command);
if (status)
return status;
status = amd_ec_write(smbus, AMD_SMB_BCNT, len);
if (status)
return status;
for (i = 0; i < len; i++) {
status = amd_ec_write(smbus, AMD_SMB_DATA + i,
data->block[i + 1]);
if (status)
return status;
}
protocol = AMD_SMB_PRTCL_BLOCK_PROC_CALL | pec;
read_write = I2C_SMBUS_READ;
break;
default:
dev_warn(&adap->dev, "Unsupported transaction %d\n", size);
return -EOPNOTSUPP;
}
status = amd_ec_write(smbus, AMD_SMB_ADDR, addr << 1);
if (status)
return status;
status = amd_ec_write(smbus, AMD_SMB_PRTCL, protocol);
if (status)
return status;
status = amd_ec_read(smbus, AMD_SMB_STS, temp + 0);
if (status)
return status;
if (~temp[0] & AMD_SMB_STS_DONE) {
udelay(500);
status = amd_ec_read(smbus, AMD_SMB_STS, temp + 0);
if (status)
return status;
}
if (~temp[0] & AMD_SMB_STS_DONE) {
msleep(1);
status = amd_ec_read(smbus, AMD_SMB_STS, temp + 0);
if (status)
return status;
}
if ((~temp[0] & AMD_SMB_STS_DONE) || (temp[0] & AMD_SMB_STS_STATUS))
return -EIO;
if (read_write == I2C_SMBUS_WRITE)
return 0;
switch (size) {
case I2C_SMBUS_BYTE:
case I2C_SMBUS_BYTE_DATA:
status = amd_ec_read(smbus, AMD_SMB_DATA, &data->byte);
if (status)
return status;
break;
case I2C_SMBUS_WORD_DATA:
case I2C_SMBUS_PROC_CALL:
status = amd_ec_read(smbus, AMD_SMB_DATA, temp + 0);
if (status)
return status;
status = amd_ec_read(smbus, AMD_SMB_DATA + 1, temp + 1);
if (status)
return status;
data->word = (temp[1] << 8) | temp[0];
break;
case I2C_SMBUS_BLOCK_DATA:
case I2C_SMBUS_BLOCK_PROC_CALL:
status = amd_ec_read(smbus, AMD_SMB_BCNT, &len);
if (status)
return status;
len = min_t(u8, len, I2C_SMBUS_BLOCK_MAX);
case I2C_SMBUS_I2C_BLOCK_DATA:
for (i = 0; i < len; i++) {
status = amd_ec_read(smbus, AMD_SMB_DATA + i,
data->block + i + 1);
if (status)
return status;
}
data->block[0] = len;
break;
}
return 0;
}
static u32 amd8111_func(struct i2c_adapter *adapter)
{
return I2C_FUNC_SMBUS_QUICK | I2C_FUNC_SMBUS_BYTE |
I2C_FUNC_SMBUS_BYTE_DATA |
I2C_FUNC_SMBUS_WORD_DATA | I2C_FUNC_SMBUS_BLOCK_DATA |
I2C_FUNC_SMBUS_PROC_CALL | I2C_FUNC_SMBUS_BLOCK_PROC_CALL |
I2C_FUNC_SMBUS_I2C_BLOCK | I2C_FUNC_SMBUS_PEC;
}
static const struct i2c_algorithm smbus_algorithm = {
.smbus_xfer = amd8111_access,
.functionality = amd8111_func,
};
static DEFINE_PCI_DEVICE_TABLE(amd8111_ids) = {
{ PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_8111_SMBUS2) },
{ 0, }
};
MODULE_DEVICE_TABLE (pci, amd8111_ids);
static int __devinit amd8111_probe(struct pci_dev *dev,
const struct pci_device_id *id)
{
struct amd_smbus *smbus;
int error;
if (!(pci_resource_flags(dev, 0) & IORESOURCE_IO))
return -ENODEV;
smbus = kzalloc(sizeof(struct amd_smbus), GFP_KERNEL);
if (!smbus)
return -ENOMEM;
smbus->dev = dev;
smbus->base = pci_resource_start(dev, 0);
smbus->size = pci_resource_len(dev, 0);
error = acpi_check_resource_conflict(&dev->resource[0]);
if (error) {
error = -ENODEV;
goto out_kfree;
}
if (!request_region(smbus->base, smbus->size, amd8111_driver.name)) {
error = -EBUSY;
goto out_kfree;
}
smbus->adapter.owner = THIS_MODULE;
snprintf(smbus->adapter.name, sizeof(smbus->adapter.name),
"SMBus2 AMD8111 adapter at %04x", smbus->base);
smbus->adapter.class = I2C_CLASS_HWMON | I2C_CLASS_SPD;
smbus->adapter.algo = &smbus_algorithm;
smbus->adapter.algo_data = smbus;
/* set up the sysfs linkage to our parent device */
smbus->adapter.dev.parent = &dev->dev;
pci_write_config_dword(smbus->dev, AMD_PCI_MISC, 0);
error = i2c_add_adapter(&smbus->adapter);
if (error)
goto out_release_region;
pci_set_drvdata(dev, smbus);
return 0;
out_release_region:
release_region(smbus->base, smbus->size);
out_kfree:
kfree(smbus);
return error;
}
static void __devexit amd8111_remove(struct pci_dev *dev)
{
struct amd_smbus *smbus = pci_get_drvdata(dev);
i2c_del_adapter(&smbus->adapter);
release_region(smbus->base, smbus->size);
kfree(smbus);
}
static struct pci_driver amd8111_driver = {
.name = "amd8111_smbus2",
.id_table = amd8111_ids,
.probe = amd8111_probe,
.remove = __devexit_p(amd8111_remove),
};
static int __init i2c_amd8111_init(void)
{
return pci_register_driver(&amd8111_driver);
}
static void __exit i2c_amd8111_exit(void)
{
pci_unregister_driver(&amd8111_driver);
}
module_init(i2c_amd8111_init);
module_exit(i2c_amd8111_exit);
| gpl-2.0 |
mseskir/android_kernel_vestel_55g | arch/sh/kernel/cpu/proc.c | 7502 | 4041 | #include <linux/seq_file.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <asm/machvec.h>
#include <asm/processor.h>
static const char *cpu_name[] = {
[CPU_SH7201] = "SH7201",
[CPU_SH7203] = "SH7203", [CPU_SH7263] = "SH7263",
[CPU_SH7206] = "SH7206", [CPU_SH7619] = "SH7619",
[CPU_SH7705] = "SH7705", [CPU_SH7706] = "SH7706",
[CPU_SH7707] = "SH7707", [CPU_SH7708] = "SH7708",
[CPU_SH7709] = "SH7709", [CPU_SH7710] = "SH7710",
[CPU_SH7712] = "SH7712", [CPU_SH7720] = "SH7720",
[CPU_SH7721] = "SH7721", [CPU_SH7729] = "SH7729",
[CPU_SH7750] = "SH7750", [CPU_SH7750S] = "SH7750S",
[CPU_SH7750R] = "SH7750R", [CPU_SH7751] = "SH7751",
[CPU_SH7751R] = "SH7751R", [CPU_SH7760] = "SH7760",
[CPU_SH4_202] = "SH4-202", [CPU_SH4_501] = "SH4-501",
[CPU_SH7763] = "SH7763", [CPU_SH7770] = "SH7770",
[CPU_SH7780] = "SH7780", [CPU_SH7781] = "SH7781",
[CPU_SH7343] = "SH7343", [CPU_SH7785] = "SH7785",
[CPU_SH7786] = "SH7786", [CPU_SH7757] = "SH7757",
[CPU_SH7722] = "SH7722", [CPU_SHX3] = "SH-X3",
[CPU_SH5_101] = "SH5-101", [CPU_SH5_103] = "SH5-103",
[CPU_MXG] = "MX-G", [CPU_SH7723] = "SH7723",
[CPU_SH7366] = "SH7366", [CPU_SH7724] = "SH7724",
[CPU_SH7372] = "SH7372", [CPU_SH_NONE] = "Unknown"
};
const char *get_cpu_subtype(struct sh_cpuinfo *c)
{
return cpu_name[c->type];
}
EXPORT_SYMBOL(get_cpu_subtype);
#ifdef CONFIG_PROC_FS
/* Symbolic CPU flags, keep in sync with asm/cpu-features.h */
static const char *cpu_flags[] = {
"none", "fpu", "p2flush", "mmuassoc", "dsp", "perfctr",
"ptea", "llsc", "l2", "op32", "pteaex", NULL
};
static void show_cpuflags(struct seq_file *m, struct sh_cpuinfo *c)
{
unsigned long i;
seq_printf(m, "cpu flags\t:");
if (!c->flags) {
seq_printf(m, " %s\n", cpu_flags[0]);
return;
}
for (i = 0; cpu_flags[i]; i++)
if ((c->flags & (1 << i)))
seq_printf(m, " %s", cpu_flags[i+1]);
seq_printf(m, "\n");
}
static void show_cacheinfo(struct seq_file *m, const char *type,
struct cache_info info)
{
unsigned int cache_size;
cache_size = info.ways * info.sets * info.linesz;
seq_printf(m, "%s size\t: %2dKiB (%d-way)\n",
type, cache_size >> 10, info.ways);
}
/*
* Get CPU information for use by the procfs.
*/
static int show_cpuinfo(struct seq_file *m, void *v)
{
struct sh_cpuinfo *c = v;
unsigned int cpu = c - cpu_data;
if (!cpu_online(cpu))
return 0;
if (cpu == 0)
seq_printf(m, "machine\t\t: %s\n", get_system_type());
else
seq_printf(m, "\n");
seq_printf(m, "processor\t: %d\n", cpu);
seq_printf(m, "cpu family\t: %s\n", init_utsname()->machine);
seq_printf(m, "cpu type\t: %s\n", get_cpu_subtype(c));
if (c->cut_major == -1)
seq_printf(m, "cut\t\t: unknown\n");
else if (c->cut_minor == -1)
seq_printf(m, "cut\t\t: %d.x\n", c->cut_major);
else
seq_printf(m, "cut\t\t: %d.%d\n", c->cut_major, c->cut_minor);
show_cpuflags(m, c);
seq_printf(m, "cache type\t: ");
/*
* Check for what type of cache we have, we support both the
* unified cache on the SH-2 and SH-3, as well as the harvard
* style cache on the SH-4.
*/
if (c->icache.flags & SH_CACHE_COMBINED) {
seq_printf(m, "unified\n");
show_cacheinfo(m, "cache", c->icache);
} else {
seq_printf(m, "split (harvard)\n");
show_cacheinfo(m, "icache", c->icache);
show_cacheinfo(m, "dcache", c->dcache);
}
/* Optional secondary cache */
if (c->flags & CPU_HAS_L2_CACHE)
show_cacheinfo(m, "scache", c->scache);
seq_printf(m, "address sizes\t: %u bits physical\n", c->phys_bits);
seq_printf(m, "bogomips\t: %lu.%02lu\n",
c->loops_per_jiffy/(500000/HZ),
(c->loops_per_jiffy/(5000/HZ)) % 100);
return 0;
}
static void *c_start(struct seq_file *m, loff_t *pos)
{
return *pos < NR_CPUS ? cpu_data + *pos : NULL;
}
static void *c_next(struct seq_file *m, void *v, loff_t *pos)
{
++*pos;
return c_start(m, pos);
}
static void c_stop(struct seq_file *m, void *v)
{
}
const struct seq_operations cpuinfo_op = {
.start = c_start,
.next = c_next,
.stop = c_stop,
.show = show_cpuinfo,
};
#endif /* CONFIG_PROC_FS */
| gpl-2.0 |
goodwin/android_kernel_lge_hammerhead-1 | arch/sh/kernel/cpu/proc.c | 7502 | 4041 | #include <linux/seq_file.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <asm/machvec.h>
#include <asm/processor.h>
static const char *cpu_name[] = {
[CPU_SH7201] = "SH7201",
[CPU_SH7203] = "SH7203", [CPU_SH7263] = "SH7263",
[CPU_SH7206] = "SH7206", [CPU_SH7619] = "SH7619",
[CPU_SH7705] = "SH7705", [CPU_SH7706] = "SH7706",
[CPU_SH7707] = "SH7707", [CPU_SH7708] = "SH7708",
[CPU_SH7709] = "SH7709", [CPU_SH7710] = "SH7710",
[CPU_SH7712] = "SH7712", [CPU_SH7720] = "SH7720",
[CPU_SH7721] = "SH7721", [CPU_SH7729] = "SH7729",
[CPU_SH7750] = "SH7750", [CPU_SH7750S] = "SH7750S",
[CPU_SH7750R] = "SH7750R", [CPU_SH7751] = "SH7751",
[CPU_SH7751R] = "SH7751R", [CPU_SH7760] = "SH7760",
[CPU_SH4_202] = "SH4-202", [CPU_SH4_501] = "SH4-501",
[CPU_SH7763] = "SH7763", [CPU_SH7770] = "SH7770",
[CPU_SH7780] = "SH7780", [CPU_SH7781] = "SH7781",
[CPU_SH7343] = "SH7343", [CPU_SH7785] = "SH7785",
[CPU_SH7786] = "SH7786", [CPU_SH7757] = "SH7757",
[CPU_SH7722] = "SH7722", [CPU_SHX3] = "SH-X3",
[CPU_SH5_101] = "SH5-101", [CPU_SH5_103] = "SH5-103",
[CPU_MXG] = "MX-G", [CPU_SH7723] = "SH7723",
[CPU_SH7366] = "SH7366", [CPU_SH7724] = "SH7724",
[CPU_SH7372] = "SH7372", [CPU_SH_NONE] = "Unknown"
};
const char *get_cpu_subtype(struct sh_cpuinfo *c)
{
return cpu_name[c->type];
}
EXPORT_SYMBOL(get_cpu_subtype);
#ifdef CONFIG_PROC_FS
/* Symbolic CPU flags, keep in sync with asm/cpu-features.h */
static const char *cpu_flags[] = {
"none", "fpu", "p2flush", "mmuassoc", "dsp", "perfctr",
"ptea", "llsc", "l2", "op32", "pteaex", NULL
};
static void show_cpuflags(struct seq_file *m, struct sh_cpuinfo *c)
{
unsigned long i;
seq_printf(m, "cpu flags\t:");
if (!c->flags) {
seq_printf(m, " %s\n", cpu_flags[0]);
return;
}
for (i = 0; cpu_flags[i]; i++)
if ((c->flags & (1 << i)))
seq_printf(m, " %s", cpu_flags[i+1]);
seq_printf(m, "\n");
}
static void show_cacheinfo(struct seq_file *m, const char *type,
struct cache_info info)
{
unsigned int cache_size;
cache_size = info.ways * info.sets * info.linesz;
seq_printf(m, "%s size\t: %2dKiB (%d-way)\n",
type, cache_size >> 10, info.ways);
}
/*
* Get CPU information for use by the procfs.
*/
static int show_cpuinfo(struct seq_file *m, void *v)
{
struct sh_cpuinfo *c = v;
unsigned int cpu = c - cpu_data;
if (!cpu_online(cpu))
return 0;
if (cpu == 0)
seq_printf(m, "machine\t\t: %s\n", get_system_type());
else
seq_printf(m, "\n");
seq_printf(m, "processor\t: %d\n", cpu);
seq_printf(m, "cpu family\t: %s\n", init_utsname()->machine);
seq_printf(m, "cpu type\t: %s\n", get_cpu_subtype(c));
if (c->cut_major == -1)
seq_printf(m, "cut\t\t: unknown\n");
else if (c->cut_minor == -1)
seq_printf(m, "cut\t\t: %d.x\n", c->cut_major);
else
seq_printf(m, "cut\t\t: %d.%d\n", c->cut_major, c->cut_minor);
show_cpuflags(m, c);
seq_printf(m, "cache type\t: ");
/*
* Check for what type of cache we have, we support both the
* unified cache on the SH-2 and SH-3, as well as the harvard
* style cache on the SH-4.
*/
if (c->icache.flags & SH_CACHE_COMBINED) {
seq_printf(m, "unified\n");
show_cacheinfo(m, "cache", c->icache);
} else {
seq_printf(m, "split (harvard)\n");
show_cacheinfo(m, "icache", c->icache);
show_cacheinfo(m, "dcache", c->dcache);
}
/* Optional secondary cache */
if (c->flags & CPU_HAS_L2_CACHE)
show_cacheinfo(m, "scache", c->scache);
seq_printf(m, "address sizes\t: %u bits physical\n", c->phys_bits);
seq_printf(m, "bogomips\t: %lu.%02lu\n",
c->loops_per_jiffy/(500000/HZ),
(c->loops_per_jiffy/(5000/HZ)) % 100);
return 0;
}
static void *c_start(struct seq_file *m, loff_t *pos)
{
return *pos < NR_CPUS ? cpu_data + *pos : NULL;
}
static void *c_next(struct seq_file *m, void *v, loff_t *pos)
{
++*pos;
return c_start(m, pos);
}
static void c_stop(struct seq_file *m, void *v)
{
}
const struct seq_operations cpuinfo_op = {
.start = c_start,
.next = c_next,
.stop = c_stop,
.show = show_cpuinfo,
};
#endif /* CONFIG_PROC_FS */
| gpl-2.0 |
bossino/panda_es_kernel | drivers/s390/char/sclp_rw.c | 9806 | 12923 | /*
* driver: reading from and writing to system console on S/390 via SCLP
*
* Copyright IBM Corp. 1999, 2009
*
* Author(s): Martin Peschke <mpeschke@de.ibm.com>
* Martin Schwidefsky <schwidefsky@de.ibm.com>
*/
#include <linux/kmod.h>
#include <linux/types.h>
#include <linux/err.h>
#include <linux/string.h>
#include <linux/spinlock.h>
#include <linux/ctype.h>
#include <asm/uaccess.h>
#include "sclp.h"
#include "sclp_rw.h"
/*
* The room for the SCCB (only for writing) is not equal to a pages size
* (as it is specified as the maximum size in the SCLP documentation)
* because of the additional data structure described above.
*/
#define MAX_SCCB_ROOM (PAGE_SIZE - sizeof(struct sclp_buffer))
static void sclp_rw_pm_event(struct sclp_register *reg,
enum sclp_pm_event sclp_pm_event)
{
sclp_console_pm_event(sclp_pm_event);
}
/* Event type structure for write message and write priority message */
static struct sclp_register sclp_rw_event = {
.send_mask = EVTYP_MSG_MASK | EVTYP_PMSGCMD_MASK,
.pm_event_fn = sclp_rw_pm_event,
};
/*
* Setup a sclp write buffer. Gets a page as input (4K) and returns
* a pointer to a struct sclp_buffer structure that is located at the
* end of the input page. This reduces the buffer space by a few
* bytes but simplifies things.
*/
struct sclp_buffer *
sclp_make_buffer(void *page, unsigned short columns, unsigned short htab)
{
struct sclp_buffer *buffer;
struct write_sccb *sccb;
sccb = (struct write_sccb *) page;
/*
* We keep the struct sclp_buffer structure at the end
* of the sccb page.
*/
buffer = ((struct sclp_buffer *) ((addr_t) sccb + PAGE_SIZE)) - 1;
buffer->sccb = sccb;
buffer->retry_count = 0;
buffer->mto_number = 0;
buffer->mto_char_sum = 0;
buffer->current_line = NULL;
buffer->current_length = 0;
buffer->columns = columns;
buffer->htab = htab;
/* initialize sccb */
memset(sccb, 0, sizeof(struct write_sccb));
sccb->header.length = sizeof(struct write_sccb);
sccb->msg_buf.header.length = sizeof(struct msg_buf);
sccb->msg_buf.header.type = EVTYP_MSG;
sccb->msg_buf.mdb.header.length = sizeof(struct mdb);
sccb->msg_buf.mdb.header.type = 1;
sccb->msg_buf.mdb.header.tag = 0xD4C4C240; /* ebcdic "MDB " */
sccb->msg_buf.mdb.header.revision_code = 1;
sccb->msg_buf.mdb.go.length = sizeof(struct go);
sccb->msg_buf.mdb.go.type = 1;
return buffer;
}
/*
* Return a pointer to the original page that has been used to create
* the buffer.
*/
void *
sclp_unmake_buffer(struct sclp_buffer *buffer)
{
return buffer->sccb;
}
/*
* Initialize a new Message Text Object (MTO) at the end of the provided buffer
* with enough room for max_len characters. Return 0 on success.
*/
static int
sclp_initialize_mto(struct sclp_buffer *buffer, int max_len)
{
struct write_sccb *sccb;
struct mto *mto;
int mto_size;
/* max size of new Message Text Object including message text */
mto_size = sizeof(struct mto) + max_len;
/* check if current buffer sccb can contain the mto */
sccb = buffer->sccb;
if ((MAX_SCCB_ROOM - sccb->header.length) < mto_size)
return -ENOMEM;
/* find address of new message text object */
mto = (struct mto *)(((addr_t) sccb) + sccb->header.length);
/*
* fill the new Message-Text Object,
* starting behind the former last byte of the SCCB
*/
memset(mto, 0, sizeof(struct mto));
mto->length = sizeof(struct mto);
mto->type = 4; /* message text object */
mto->line_type_flags = LNTPFLGS_ENDTEXT; /* end text */
/* set pointer to first byte after struct mto. */
buffer->current_line = (char *) (mto + 1);
buffer->current_length = 0;
return 0;
}
/*
* Finalize MTO initialized by sclp_initialize_mto(), updating the sizes of
* MTO, enclosing MDB, event buffer and SCCB.
*/
static void
sclp_finalize_mto(struct sclp_buffer *buffer)
{
struct write_sccb *sccb;
struct mto *mto;
int str_len, mto_size;
str_len = buffer->current_length;
buffer->current_line = NULL;
buffer->current_length = 0;
/* real size of new Message Text Object including message text */
mto_size = sizeof(struct mto) + str_len;
/* find address of new message text object */
sccb = buffer->sccb;
mto = (struct mto *)(((addr_t) sccb) + sccb->header.length);
/* set size of message text object */
mto->length = mto_size;
/*
* update values of sizes
* (SCCB, Event(Message) Buffer, Message Data Block)
*/
sccb->header.length += mto_size;
sccb->msg_buf.header.length += mto_size;
sccb->msg_buf.mdb.header.length += mto_size;
/*
* count number of buffered messages (= number of Message Text
* Objects) and number of buffered characters
* for the SCCB currently used for buffering and at all
*/
buffer->mto_number++;
buffer->mto_char_sum += str_len;
}
/*
* processing of a message including escape characters,
* returns number of characters written to the output sccb
* ("processed" means that is not guaranteed that the character have already
* been sent to the SCLP but that it will be done at least next time the SCLP
* is not busy)
*/
int
sclp_write(struct sclp_buffer *buffer, const unsigned char *msg, int count)
{
int spaces, i_msg;
int rc;
/*
* parse msg for escape sequences (\t,\v ...) and put formated
* msg into an mto (created by sclp_initialize_mto).
*
* We have to do this work ourselfs because there is no support for
* these characters on the native machine and only partial support
* under VM (Why does VM interpret \n but the native machine doesn't ?)
*
* Depending on i/o-control setting the message is always written
* immediately or we wait for a final new line maybe coming with the
* next message. Besides we avoid a buffer overrun by writing its
* content.
*
* RESTRICTIONS:
*
* \r and \b work within one line because we are not able to modify
* previous output that have already been accepted by the SCLP.
*
* \t combined with following \r is not correctly represented because
* \t is expanded to some spaces but \r does not know about a
* previous \t and decreases the current position by one column.
* This is in order to a slim and quick implementation.
*/
for (i_msg = 0; i_msg < count; i_msg++) {
switch (msg[i_msg]) {
case '\n': /* new line, line feed (ASCII) */
/* check if new mto needs to be created */
if (buffer->current_line == NULL) {
rc = sclp_initialize_mto(buffer, 0);
if (rc)
return i_msg;
}
sclp_finalize_mto(buffer);
break;
case '\a': /* bell, one for several times */
/* set SCLP sound alarm bit in General Object */
buffer->sccb->msg_buf.mdb.go.general_msg_flags |=
GNRLMSGFLGS_SNDALRM;
break;
case '\t': /* horizontal tabulator */
/* check if new mto needs to be created */
if (buffer->current_line == NULL) {
rc = sclp_initialize_mto(buffer,
buffer->columns);
if (rc)
return i_msg;
}
/* "go to (next htab-boundary + 1, same line)" */
do {
if (buffer->current_length >= buffer->columns)
break;
/* ok, add a blank */
*buffer->current_line++ = 0x40;
buffer->current_length++;
} while (buffer->current_length % buffer->htab);
break;
case '\f': /* form feed */
case '\v': /* vertical tabulator */
/* "go to (actual column, actual line + 1)" */
/* = new line, leading spaces */
if (buffer->current_line != NULL) {
spaces = buffer->current_length;
sclp_finalize_mto(buffer);
rc = sclp_initialize_mto(buffer,
buffer->columns);
if (rc)
return i_msg;
memset(buffer->current_line, 0x40, spaces);
buffer->current_line += spaces;
buffer->current_length = spaces;
} else {
/* one an empty line this is the same as \n */
rc = sclp_initialize_mto(buffer,
buffer->columns);
if (rc)
return i_msg;
sclp_finalize_mto(buffer);
}
break;
case '\b': /* backspace */
/* "go to (actual column - 1, actual line)" */
/* decrement counter indicating position, */
/* do not remove last character */
if (buffer->current_line != NULL &&
buffer->current_length > 0) {
buffer->current_length--;
buffer->current_line--;
}
break;
case 0x00: /* end of string */
/* transfer current line to SCCB */
if (buffer->current_line != NULL)
sclp_finalize_mto(buffer);
/* skip the rest of the message including the 0 byte */
i_msg = count - 1;
break;
default: /* no escape character */
/* do not output unprintable characters */
if (!isprint(msg[i_msg]))
break;
/* check if new mto needs to be created */
if (buffer->current_line == NULL) {
rc = sclp_initialize_mto(buffer,
buffer->columns);
if (rc)
return i_msg;
}
*buffer->current_line++ = sclp_ascebc(msg[i_msg]);
buffer->current_length++;
break;
}
/* check if current mto is full */
if (buffer->current_line != NULL &&
buffer->current_length >= buffer->columns)
sclp_finalize_mto(buffer);
}
/* return number of processed characters */
return i_msg;
}
/*
* Return the number of free bytes in the sccb
*/
int
sclp_buffer_space(struct sclp_buffer *buffer)
{
int count;
count = MAX_SCCB_ROOM - buffer->sccb->header.length;
if (buffer->current_line != NULL)
count -= sizeof(struct mto) + buffer->current_length;
return count;
}
/*
* Return number of characters in buffer
*/
int
sclp_chars_in_buffer(struct sclp_buffer *buffer)
{
int count;
count = buffer->mto_char_sum;
if (buffer->current_line != NULL)
count += buffer->current_length;
return count;
}
/*
* sets or provides some values that influence the drivers behaviour
*/
void
sclp_set_columns(struct sclp_buffer *buffer, unsigned short columns)
{
buffer->columns = columns;
if (buffer->current_line != NULL &&
buffer->current_length > buffer->columns)
sclp_finalize_mto(buffer);
}
void
sclp_set_htab(struct sclp_buffer *buffer, unsigned short htab)
{
buffer->htab = htab;
}
/*
* called by sclp_console_init and/or sclp_tty_init
*/
int
sclp_rw_init(void)
{
static int init_done = 0;
int rc;
if (init_done)
return 0;
rc = sclp_register(&sclp_rw_event);
if (rc == 0)
init_done = 1;
return rc;
}
#define SCLP_BUFFER_MAX_RETRY 1
/*
* second half of Write Event Data-function that has to be done after
* interruption indicating completion of Service Call.
*/
static void
sclp_writedata_callback(struct sclp_req *request, void *data)
{
int rc;
struct sclp_buffer *buffer;
struct write_sccb *sccb;
buffer = (struct sclp_buffer *) data;
sccb = buffer->sccb;
if (request->status == SCLP_REQ_FAILED) {
if (buffer->callback != NULL)
buffer->callback(buffer, -EIO);
return;
}
/* check SCLP response code and choose suitable action */
switch (sccb->header.response_code) {
case 0x0020 :
/* Normal completion, buffer processed, message(s) sent */
rc = 0;
break;
case 0x0340: /* Contained SCLP equipment check */
if (++buffer->retry_count > SCLP_BUFFER_MAX_RETRY) {
rc = -EIO;
break;
}
/* remove processed buffers and requeue rest */
if (sclp_remove_processed((struct sccb_header *) sccb) > 0) {
/* not all buffers were processed */
sccb->header.response_code = 0x0000;
buffer->request.status = SCLP_REQ_FILLED;
rc = sclp_add_request(request);
if (rc == 0)
return;
} else
rc = 0;
break;
case 0x0040: /* SCLP equipment check */
case 0x05f0: /* Target resource in improper state */
if (++buffer->retry_count > SCLP_BUFFER_MAX_RETRY) {
rc = -EIO;
break;
}
/* retry request */
sccb->header.response_code = 0x0000;
buffer->request.status = SCLP_REQ_FILLED;
rc = sclp_add_request(request);
if (rc == 0)
return;
break;
default:
if (sccb->header.response_code == 0x71f0)
rc = -ENOMEM;
else
rc = -EINVAL;
break;
}
if (buffer->callback != NULL)
buffer->callback(buffer, rc);
}
/*
* Setup the request structure in the struct sclp_buffer to do SCLP Write
* Event Data and pass the request to the core SCLP loop. Return zero on
* success, non-zero otherwise.
*/
int
sclp_emit_buffer(struct sclp_buffer *buffer,
void (*callback)(struct sclp_buffer *, int))
{
struct write_sccb *sccb;
/* add current line if there is one */
if (buffer->current_line != NULL)
sclp_finalize_mto(buffer);
/* Are there messages in the output buffer ? */
if (buffer->mto_number == 0)
return -EIO;
sccb = buffer->sccb;
if (sclp_rw_event.sclp_receive_mask & EVTYP_MSG_MASK)
/* Use normal write message */
sccb->msg_buf.header.type = EVTYP_MSG;
else if (sclp_rw_event.sclp_receive_mask & EVTYP_PMSGCMD_MASK)
/* Use write priority message */
sccb->msg_buf.header.type = EVTYP_PMSGCMD;
else
return -ENOSYS;
buffer->request.command = SCLP_CMDW_WRITE_EVENT_DATA;
buffer->request.status = SCLP_REQ_FILLED;
buffer->request.callback = sclp_writedata_callback;
buffer->request.callback_data = buffer;
buffer->request.sccb = sccb;
buffer->callback = callback;
return sclp_add_request(&buffer->request);
}
| gpl-2.0 |
gompa/linux | drivers/scsi/ufs/ufshcd.c | 79 | 174834 | /*
* Universal Flash Storage Host controller driver Core
*
* This code is based on drivers/scsi/ufs/ufshcd.c
* Copyright (C) 2011-2013 Samsung India Software Operations
* Copyright (c) 2013-2016, The Linux Foundation. All rights reserved.
*
* Authors:
* Santosh Yaraganavi <santosh.sy@samsung.com>
* Vinayak Holikatti <h.vinayak@samsung.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* See the COPYING file in the top-level directory or visit
* <http://www.gnu.org/licenses/gpl-2.0.html>
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* This program is provided "AS IS" and "WITH ALL FAULTS" and
* without warranty of any kind. You are solely responsible for
* determining the appropriateness of using and distributing
* the program and assume all risks associated with your exercise
* of rights with respect to the program, including but not limited
* to infringement of third party rights, the risks and costs of
* program errors, damage to or loss of data, programs or equipment,
* and unavailability or interruption of operations. Under no
* circumstances will the contributor of this Program be liable for
* any damages of any kind arising from your use or distribution of
* this program.
*
* The Linux Foundation chooses to take subject only to the GPLv2
* license terms, and distributes only under these terms.
*/
#include <linux/async.h>
#include <linux/devfreq.h>
#include <linux/nls.h>
#include <linux/of.h>
#include "ufshcd.h"
#include "ufs_quirks.h"
#include "unipro.h"
#define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
UTP_TASK_REQ_COMPL |\
UFSHCD_ERROR_MASK)
/* UIC command timeout, unit: ms */
#define UIC_CMD_TIMEOUT 500
/* NOP OUT retries waiting for NOP IN response */
#define NOP_OUT_RETRIES 10
/* Timeout after 30 msecs if NOP OUT hangs without response */
#define NOP_OUT_TIMEOUT 30 /* msecs */
/* Query request retries */
#define QUERY_REQ_RETRIES 10
/* Query request timeout */
#define QUERY_REQ_TIMEOUT 30 /* msec */
/*
* Query request timeout for fDeviceInit flag
* fDeviceInit query response time for some devices is too large that default
* QUERY_REQ_TIMEOUT may not be enough for such devices.
*/
#define QUERY_FDEVICEINIT_REQ_TIMEOUT 600 /* msec */
/* Task management command timeout */
#define TM_CMD_TIMEOUT 100 /* msecs */
/* maximum number of retries for a general UIC command */
#define UFS_UIC_COMMAND_RETRIES 3
/* maximum number of link-startup retries */
#define DME_LINKSTARTUP_RETRIES 3
/* Maximum retries for Hibern8 enter */
#define UIC_HIBERN8_ENTER_RETRIES 3
/* maximum number of reset retries before giving up */
#define MAX_HOST_RESET_RETRIES 5
/* Expose the flag value from utp_upiu_query.value */
#define MASK_QUERY_UPIU_FLAG_LOC 0xFF
/* Interrupt aggregation default timeout, unit: 40us */
#define INT_AGGR_DEF_TO 0x02
#define ufshcd_toggle_vreg(_dev, _vreg, _on) \
({ \
int _ret; \
if (_on) \
_ret = ufshcd_enable_vreg(_dev, _vreg); \
else \
_ret = ufshcd_disable_vreg(_dev, _vreg); \
_ret; \
})
static u32 ufs_query_desc_max_size[] = {
QUERY_DESC_DEVICE_MAX_SIZE,
QUERY_DESC_CONFIGURAION_MAX_SIZE,
QUERY_DESC_UNIT_MAX_SIZE,
QUERY_DESC_RFU_MAX_SIZE,
QUERY_DESC_INTERCONNECT_MAX_SIZE,
QUERY_DESC_STRING_MAX_SIZE,
QUERY_DESC_RFU_MAX_SIZE,
QUERY_DESC_GEOMETRY_MAX_SIZE,
QUERY_DESC_POWER_MAX_SIZE,
QUERY_DESC_RFU_MAX_SIZE,
};
enum {
UFSHCD_MAX_CHANNEL = 0,
UFSHCD_MAX_ID = 1,
UFSHCD_CMD_PER_LUN = 32,
UFSHCD_CAN_QUEUE = 32,
};
/* UFSHCD states */
enum {
UFSHCD_STATE_RESET,
UFSHCD_STATE_ERROR,
UFSHCD_STATE_OPERATIONAL,
};
/* UFSHCD error handling flags */
enum {
UFSHCD_EH_IN_PROGRESS = (1 << 0),
};
/* UFSHCD UIC layer error flags */
enum {
UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
};
/* Interrupt configuration options */
enum {
UFSHCD_INT_DISABLE,
UFSHCD_INT_ENABLE,
UFSHCD_INT_CLEAR,
};
#define ufshcd_set_eh_in_progress(h) \
(h->eh_flags |= UFSHCD_EH_IN_PROGRESS)
#define ufshcd_eh_in_progress(h) \
(h->eh_flags & UFSHCD_EH_IN_PROGRESS)
#define ufshcd_clear_eh_in_progress(h) \
(h->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
#define ufshcd_set_ufs_dev_active(h) \
((h)->curr_dev_pwr_mode = UFS_ACTIVE_PWR_MODE)
#define ufshcd_set_ufs_dev_sleep(h) \
((h)->curr_dev_pwr_mode = UFS_SLEEP_PWR_MODE)
#define ufshcd_set_ufs_dev_poweroff(h) \
((h)->curr_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE)
#define ufshcd_is_ufs_dev_active(h) \
((h)->curr_dev_pwr_mode == UFS_ACTIVE_PWR_MODE)
#define ufshcd_is_ufs_dev_sleep(h) \
((h)->curr_dev_pwr_mode == UFS_SLEEP_PWR_MODE)
#define ufshcd_is_ufs_dev_poweroff(h) \
((h)->curr_dev_pwr_mode == UFS_POWERDOWN_PWR_MODE)
static struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
{UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
{UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
{UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
{UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
{UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
{UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
};
static inline enum ufs_dev_pwr_mode
ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
{
return ufs_pm_lvl_states[lvl].dev_state;
}
static inline enum uic_link_state
ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
{
return ufs_pm_lvl_states[lvl].link_state;
}
static void ufshcd_tmc_handler(struct ufs_hba *hba);
static void ufshcd_async_scan(void *data, async_cookie_t cookie);
static int ufshcd_reset_and_restore(struct ufs_hba *hba);
static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
static void ufshcd_hba_exit(struct ufs_hba *hba);
static int ufshcd_probe_hba(struct ufs_hba *hba);
static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
bool skip_ref_clk);
static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
static int ufshcd_set_vccq_rail_unused(struct ufs_hba *hba, bool unused);
static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba);
static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba);
static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
static irqreturn_t ufshcd_intr(int irq, void *__hba);
static int ufshcd_config_pwr_mode(struct ufs_hba *hba,
struct ufs_pa_layer_attr *desired_pwr_mode);
static int ufshcd_change_power_mode(struct ufs_hba *hba,
struct ufs_pa_layer_attr *pwr_mode);
static inline bool ufshcd_valid_tag(struct ufs_hba *hba, int tag)
{
return tag >= 0 && tag < hba->nutrs;
}
static inline int ufshcd_enable_irq(struct ufs_hba *hba)
{
int ret = 0;
if (!hba->is_irq_enabled) {
ret = request_irq(hba->irq, ufshcd_intr, IRQF_SHARED, UFSHCD,
hba);
if (ret)
dev_err(hba->dev, "%s: request_irq failed, ret=%d\n",
__func__, ret);
hba->is_irq_enabled = true;
}
return ret;
}
static inline void ufshcd_disable_irq(struct ufs_hba *hba)
{
if (hba->is_irq_enabled) {
free_irq(hba->irq, hba);
hba->is_irq_enabled = false;
}
}
/* replace non-printable or non-ASCII characters with spaces */
static inline void ufshcd_remove_non_printable(char *val)
{
if (!val)
return;
if (*val < 0x20 || *val > 0x7e)
*val = ' ';
}
/*
* ufshcd_wait_for_register - wait for register value to change
* @hba - per-adapter interface
* @reg - mmio register offset
* @mask - mask to apply to read register value
* @val - wait condition
* @interval_us - polling interval in microsecs
* @timeout_ms - timeout in millisecs
* @can_sleep - perform sleep or just spin
*
* Returns -ETIMEDOUT on error, zero on success
*/
int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
u32 val, unsigned long interval_us,
unsigned long timeout_ms, bool can_sleep)
{
int err = 0;
unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
/* ignore bits that we don't intend to wait on */
val = val & mask;
while ((ufshcd_readl(hba, reg) & mask) != val) {
if (can_sleep)
usleep_range(interval_us, interval_us + 50);
else
udelay(interval_us);
if (time_after(jiffies, timeout)) {
if ((ufshcd_readl(hba, reg) & mask) != val)
err = -ETIMEDOUT;
break;
}
}
return err;
}
/**
* ufshcd_get_intr_mask - Get the interrupt bit mask
* @hba - Pointer to adapter instance
*
* Returns interrupt bit mask per version
*/
static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
{
if (hba->ufs_version == UFSHCI_VERSION_10)
return INTERRUPT_MASK_ALL_VER_10;
else
return INTERRUPT_MASK_ALL_VER_11;
}
/**
* ufshcd_get_ufs_version - Get the UFS version supported by the HBA
* @hba - Pointer to adapter instance
*
* Returns UFSHCI version supported by the controller
*/
static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
{
if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
return ufshcd_vops_get_ufs_hci_version(hba);
return ufshcd_readl(hba, REG_UFS_VERSION);
}
/**
* ufshcd_is_device_present - Check if any device connected to
* the host controller
* @hba: pointer to adapter instance
*
* Returns 1 if device present, 0 if no device detected
*/
static inline int ufshcd_is_device_present(struct ufs_hba *hba)
{
return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) &
DEVICE_PRESENT) ? 1 : 0;
}
/**
* ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
* @lrb: pointer to local command reference block
*
* This function is used to get the OCS field from UTRD
* Returns the OCS field in the UTRD
*/
static inline int ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
{
return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
}
/**
* ufshcd_get_tmr_ocs - Get the UTMRD Overall Command Status
* @task_req_descp: pointer to utp_task_req_desc structure
*
* This function is used to get the OCS field from UTMRD
* Returns the OCS field in the UTMRD
*/
static inline int
ufshcd_get_tmr_ocs(struct utp_task_req_desc *task_req_descp)
{
return le32_to_cpu(task_req_descp->header.dword_2) & MASK_OCS;
}
/**
* ufshcd_get_tm_free_slot - get a free slot for task management request
* @hba: per adapter instance
* @free_slot: pointer to variable with available slot value
*
* Get a free tag and lock it until ufshcd_put_tm_slot() is called.
* Returns 0 if free slot is not available, else return 1 with tag value
* in @free_slot.
*/
static bool ufshcd_get_tm_free_slot(struct ufs_hba *hba, int *free_slot)
{
int tag;
bool ret = false;
if (!free_slot)
goto out;
do {
tag = find_first_zero_bit(&hba->tm_slots_in_use, hba->nutmrs);
if (tag >= hba->nutmrs)
goto out;
} while (test_and_set_bit_lock(tag, &hba->tm_slots_in_use));
*free_slot = tag;
ret = true;
out:
return ret;
}
static inline void ufshcd_put_tm_slot(struct ufs_hba *hba, int slot)
{
clear_bit_unlock(slot, &hba->tm_slots_in_use);
}
/**
* ufshcd_utrl_clear - Clear a bit in UTRLCLR register
* @hba: per adapter instance
* @pos: position of the bit to be cleared
*/
static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 pos)
{
ufshcd_writel(hba, ~(1 << pos), REG_UTP_TRANSFER_REQ_LIST_CLEAR);
}
/**
* ufshcd_outstanding_req_clear - Clear a bit in outstanding request field
* @hba: per adapter instance
* @tag: position of the bit to be cleared
*/
static inline void ufshcd_outstanding_req_clear(struct ufs_hba *hba, int tag)
{
__clear_bit(tag, &hba->outstanding_reqs);
}
/**
* ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
* @reg: Register value of host controller status
*
* Returns integer, 0 on Success and positive value if failed
*/
static inline int ufshcd_get_lists_status(u32 reg)
{
/*
* The mask 0xFF is for the following HCS register bits
* Bit Description
* 0 Device Present
* 1 UTRLRDY
* 2 UTMRLRDY
* 3 UCRDY
* 4-7 reserved
*/
return ((reg & 0xFF) >> 1) ^ 0x07;
}
/**
* ufshcd_get_uic_cmd_result - Get the UIC command result
* @hba: Pointer to adapter instance
*
* This function gets the result of UIC command completion
* Returns 0 on success, non zero value on error
*/
static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
{
return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
MASK_UIC_COMMAND_RESULT;
}
/**
* ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
* @hba: Pointer to adapter instance
*
* This function gets UIC command argument3
* Returns 0 on success, non zero value on error
*/
static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
{
return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
}
/**
* ufshcd_get_req_rsp - returns the TR response transaction type
* @ucd_rsp_ptr: pointer to response UPIU
*/
static inline int
ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
{
return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
}
/**
* ufshcd_get_rsp_upiu_result - Get the result from response UPIU
* @ucd_rsp_ptr: pointer to response UPIU
*
* This function gets the response status and scsi_status from response UPIU
* Returns the response result code.
*/
static inline int
ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
{
return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
}
/*
* ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
* from response UPIU
* @ucd_rsp_ptr: pointer to response UPIU
*
* Return the data segment length.
*/
static inline unsigned int
ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
{
return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
MASK_RSP_UPIU_DATA_SEG_LEN;
}
/**
* ufshcd_is_exception_event - Check if the device raised an exception event
* @ucd_rsp_ptr: pointer to response UPIU
*
* The function checks if the device raised an exception event indicated in
* the Device Information field of response UPIU.
*
* Returns true if exception is raised, false otherwise.
*/
static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
{
return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
MASK_RSP_EXCEPTION_EVENT ? true : false;
}
/**
* ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
* @hba: per adapter instance
*/
static inline void
ufshcd_reset_intr_aggr(struct ufs_hba *hba)
{
ufshcd_writel(hba, INT_AGGR_ENABLE |
INT_AGGR_COUNTER_AND_TIMER_RESET,
REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
}
/**
* ufshcd_config_intr_aggr - Configure interrupt aggregation values.
* @hba: per adapter instance
* @cnt: Interrupt aggregation counter threshold
* @tmout: Interrupt aggregation timeout value
*/
static inline void
ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
{
ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
INT_AGGR_COUNTER_THLD_VAL(cnt) |
INT_AGGR_TIMEOUT_VAL(tmout),
REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
}
/**
* ufshcd_disable_intr_aggr - Disables interrupt aggregation.
* @hba: per adapter instance
*/
static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
{
ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
}
/**
* ufshcd_enable_run_stop_reg - Enable run-stop registers,
* When run-stop registers are set to 1, it indicates the
* host controller that it can process the requests
* @hba: per adapter instance
*/
static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
{
ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
REG_UTP_TASK_REQ_LIST_RUN_STOP);
ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
}
/**
* ufshcd_hba_start - Start controller initialization sequence
* @hba: per adapter instance
*/
static inline void ufshcd_hba_start(struct ufs_hba *hba)
{
ufshcd_writel(hba, CONTROLLER_ENABLE, REG_CONTROLLER_ENABLE);
}
/**
* ufshcd_is_hba_active - Get controller state
* @hba: per adapter instance
*
* Returns zero if controller is active, 1 otherwise
*/
static inline int ufshcd_is_hba_active(struct ufs_hba *hba)
{
return (ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & 0x1) ? 0 : 1;
}
u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
{
/* HCI version 1.0 and 1.1 supports UniPro 1.41 */
if ((hba->ufs_version == UFSHCI_VERSION_10) ||
(hba->ufs_version == UFSHCI_VERSION_11))
return UFS_UNIPRO_VER_1_41;
else
return UFS_UNIPRO_VER_1_6;
}
EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
{
/*
* If both host and device support UniPro ver1.6 or later, PA layer
* parameters tuning happens during link startup itself.
*
* We can manually tune PA layer parameters if either host or device
* doesn't support UniPro ver 1.6 or later. But to keep manual tuning
* logic simple, we will only do manual tuning if local unipro version
* doesn't support ver1.6 or later.
*/
if (ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6)
return true;
else
return false;
}
static void ufshcd_ungate_work(struct work_struct *work)
{
int ret;
unsigned long flags;
struct ufs_hba *hba = container_of(work, struct ufs_hba,
clk_gating.ungate_work);
cancel_delayed_work_sync(&hba->clk_gating.gate_work);
spin_lock_irqsave(hba->host->host_lock, flags);
if (hba->clk_gating.state == CLKS_ON) {
spin_unlock_irqrestore(hba->host->host_lock, flags);
goto unblock_reqs;
}
spin_unlock_irqrestore(hba->host->host_lock, flags);
ufshcd_setup_clocks(hba, true);
/* Exit from hibern8 */
if (ufshcd_can_hibern8_during_gating(hba)) {
/* Prevent gating in this path */
hba->clk_gating.is_suspended = true;
if (ufshcd_is_link_hibern8(hba)) {
ret = ufshcd_uic_hibern8_exit(hba);
if (ret)
dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
__func__, ret);
else
ufshcd_set_link_active(hba);
}
hba->clk_gating.is_suspended = false;
}
unblock_reqs:
if (ufshcd_is_clkscaling_enabled(hba))
devfreq_resume_device(hba->devfreq);
scsi_unblock_requests(hba->host);
}
/**
* ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
* Also, exit from hibern8 mode and set the link as active.
* @hba: per adapter instance
* @async: This indicates whether caller should ungate clocks asynchronously.
*/
int ufshcd_hold(struct ufs_hba *hba, bool async)
{
int rc = 0;
unsigned long flags;
if (!ufshcd_is_clkgating_allowed(hba))
goto out;
spin_lock_irqsave(hba->host->host_lock, flags);
hba->clk_gating.active_reqs++;
if (ufshcd_eh_in_progress(hba)) {
spin_unlock_irqrestore(hba->host->host_lock, flags);
return 0;
}
start:
switch (hba->clk_gating.state) {
case CLKS_ON:
break;
case REQ_CLKS_OFF:
if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
hba->clk_gating.state = CLKS_ON;
break;
}
/*
* If we here, it means gating work is either done or
* currently running. Hence, fall through to cancel gating
* work and to enable clocks.
*/
case CLKS_OFF:
scsi_block_requests(hba->host);
hba->clk_gating.state = REQ_CLKS_ON;
schedule_work(&hba->clk_gating.ungate_work);
/*
* fall through to check if we should wait for this
* work to be done or not.
*/
case REQ_CLKS_ON:
if (async) {
rc = -EAGAIN;
hba->clk_gating.active_reqs--;
break;
}
spin_unlock_irqrestore(hba->host->host_lock, flags);
flush_work(&hba->clk_gating.ungate_work);
/* Make sure state is CLKS_ON before returning */
spin_lock_irqsave(hba->host->host_lock, flags);
goto start;
default:
dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
__func__, hba->clk_gating.state);
break;
}
spin_unlock_irqrestore(hba->host->host_lock, flags);
out:
return rc;
}
EXPORT_SYMBOL_GPL(ufshcd_hold);
static void ufshcd_gate_work(struct work_struct *work)
{
struct ufs_hba *hba = container_of(work, struct ufs_hba,
clk_gating.gate_work.work);
unsigned long flags;
spin_lock_irqsave(hba->host->host_lock, flags);
if (hba->clk_gating.is_suspended) {
hba->clk_gating.state = CLKS_ON;
goto rel_lock;
}
if (hba->clk_gating.active_reqs
|| hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
|| hba->lrb_in_use || hba->outstanding_tasks
|| hba->active_uic_cmd || hba->uic_async_done)
goto rel_lock;
spin_unlock_irqrestore(hba->host->host_lock, flags);
/* put the link into hibern8 mode before turning off clocks */
if (ufshcd_can_hibern8_during_gating(hba)) {
if (ufshcd_uic_hibern8_enter(hba)) {
hba->clk_gating.state = CLKS_ON;
goto out;
}
ufshcd_set_link_hibern8(hba);
}
if (ufshcd_is_clkscaling_enabled(hba)) {
devfreq_suspend_device(hba->devfreq);
hba->clk_scaling.window_start_t = 0;
}
if (!ufshcd_is_link_active(hba))
ufshcd_setup_clocks(hba, false);
else
/* If link is active, device ref_clk can't be switched off */
__ufshcd_setup_clocks(hba, false, true);
/*
* In case you are here to cancel this work the gating state
* would be marked as REQ_CLKS_ON. In this case keep the state
* as REQ_CLKS_ON which would anyway imply that clocks are off
* and a request to turn them on is pending. By doing this way,
* we keep the state machine in tact and this would ultimately
* prevent from doing cancel work multiple times when there are
* new requests arriving before the current cancel work is done.
*/
spin_lock_irqsave(hba->host->host_lock, flags);
if (hba->clk_gating.state == REQ_CLKS_OFF)
hba->clk_gating.state = CLKS_OFF;
rel_lock:
spin_unlock_irqrestore(hba->host->host_lock, flags);
out:
return;
}
/* host lock must be held before calling this variant */
static void __ufshcd_release(struct ufs_hba *hba)
{
if (!ufshcd_is_clkgating_allowed(hba))
return;
hba->clk_gating.active_reqs--;
if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended
|| hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
|| hba->lrb_in_use || hba->outstanding_tasks
|| hba->active_uic_cmd || hba->uic_async_done
|| ufshcd_eh_in_progress(hba))
return;
hba->clk_gating.state = REQ_CLKS_OFF;
schedule_delayed_work(&hba->clk_gating.gate_work,
msecs_to_jiffies(hba->clk_gating.delay_ms));
}
void ufshcd_release(struct ufs_hba *hba)
{
unsigned long flags;
spin_lock_irqsave(hba->host->host_lock, flags);
__ufshcd_release(hba);
spin_unlock_irqrestore(hba->host->host_lock, flags);
}
EXPORT_SYMBOL_GPL(ufshcd_release);
static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct ufs_hba *hba = dev_get_drvdata(dev);
return snprintf(buf, PAGE_SIZE, "%lu\n", hba->clk_gating.delay_ms);
}
static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct ufs_hba *hba = dev_get_drvdata(dev);
unsigned long flags, value;
if (kstrtoul(buf, 0, &value))
return -EINVAL;
spin_lock_irqsave(hba->host->host_lock, flags);
hba->clk_gating.delay_ms = value;
spin_unlock_irqrestore(hba->host->host_lock, flags);
return count;
}
static void ufshcd_init_clk_gating(struct ufs_hba *hba)
{
if (!ufshcd_is_clkgating_allowed(hba))
return;
hba->clk_gating.delay_ms = 150;
INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
hba->clk_gating.delay_attr.attr.mode = S_IRUGO | S_IWUSR;
if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
}
static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
{
if (!ufshcd_is_clkgating_allowed(hba))
return;
device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
cancel_work_sync(&hba->clk_gating.ungate_work);
cancel_delayed_work_sync(&hba->clk_gating.gate_work);
}
/* Must be called with host lock acquired */
static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
{
if (!ufshcd_is_clkscaling_enabled(hba))
return;
if (!hba->clk_scaling.is_busy_started) {
hba->clk_scaling.busy_start_t = ktime_get();
hba->clk_scaling.is_busy_started = true;
}
}
static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
{
struct ufs_clk_scaling *scaling = &hba->clk_scaling;
if (!ufshcd_is_clkscaling_enabled(hba))
return;
if (!hba->outstanding_reqs && scaling->is_busy_started) {
scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
scaling->busy_start_t));
scaling->busy_start_t = ktime_set(0, 0);
scaling->is_busy_started = false;
}
}
/**
* ufshcd_send_command - Send SCSI or device management commands
* @hba: per adapter instance
* @task_tag: Task tag of the command
*/
static inline
void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
{
ufshcd_clk_scaling_start_busy(hba);
__set_bit(task_tag, &hba->outstanding_reqs);
ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
}
/**
* ufshcd_copy_sense_data - Copy sense data in case of check condition
* @lrb - pointer to local reference block
*/
static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
{
int len;
if (lrbp->sense_buffer &&
ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
memcpy(lrbp->sense_buffer,
lrbp->ucd_rsp_ptr->sr.sense_data,
min_t(int, len, SCSI_SENSE_BUFFERSIZE));
}
}
/**
* ufshcd_copy_query_response() - Copy the Query Response and the data
* descriptor
* @hba: per adapter instance
* @lrb - pointer to local reference block
*/
static
int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
{
struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
/* Get the descriptor */
if (lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
GENERAL_UPIU_REQUEST_SIZE;
u16 resp_len;
u16 buf_len;
/* data segment length */
resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
MASK_QUERY_DATA_SEG_LEN;
buf_len = be16_to_cpu(
hba->dev_cmd.query.request.upiu_req.length);
if (likely(buf_len >= resp_len)) {
memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
} else {
dev_warn(hba->dev,
"%s: Response size is bigger than buffer",
__func__);
return -EINVAL;
}
}
return 0;
}
/**
* ufshcd_hba_capabilities - Read controller capabilities
* @hba: per adapter instance
*/
static inline void ufshcd_hba_capabilities(struct ufs_hba *hba)
{
hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
/* nutrs and nutmrs are 0 based values */
hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
hba->nutmrs =
((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
}
/**
* ufshcd_ready_for_uic_cmd - Check if controller is ready
* to accept UIC commands
* @hba: per adapter instance
* Return true on success, else false
*/
static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
{
if (ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY)
return true;
else
return false;
}
/**
* ufshcd_get_upmcrs - Get the power mode change request status
* @hba: Pointer to adapter instance
*
* This function gets the UPMCRS field of HCS register
* Returns value of UPMCRS field
*/
static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
{
return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
}
/**
* ufshcd_dispatch_uic_cmd - Dispatch UIC commands to unipro layers
* @hba: per adapter instance
* @uic_cmd: UIC command
*
* Mutex must be held.
*/
static inline void
ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
{
WARN_ON(hba->active_uic_cmd);
hba->active_uic_cmd = uic_cmd;
/* Write Args */
ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
/* Write UIC Cmd */
ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
REG_UIC_COMMAND);
}
/**
* ufshcd_wait_for_uic_cmd - Wait complectioin of UIC command
* @hba: per adapter instance
* @uic_command: UIC command
*
* Must be called with mutex held.
* Returns 0 only if success.
*/
static int
ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
{
int ret;
unsigned long flags;
if (wait_for_completion_timeout(&uic_cmd->done,
msecs_to_jiffies(UIC_CMD_TIMEOUT)))
ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
else
ret = -ETIMEDOUT;
spin_lock_irqsave(hba->host->host_lock, flags);
hba->active_uic_cmd = NULL;
spin_unlock_irqrestore(hba->host->host_lock, flags);
return ret;
}
/**
* __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
* @hba: per adapter instance
* @uic_cmd: UIC command
* @completion: initialize the completion only if this is set to true
*
* Identical to ufshcd_send_uic_cmd() expect mutex. Must be called
* with mutex held and host_lock locked.
* Returns 0 only if success.
*/
static int
__ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
bool completion)
{
if (!ufshcd_ready_for_uic_cmd(hba)) {
dev_err(hba->dev,
"Controller not ready to accept UIC commands\n");
return -EIO;
}
if (completion)
init_completion(&uic_cmd->done);
ufshcd_dispatch_uic_cmd(hba, uic_cmd);
return 0;
}
/**
* ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
* @hba: per adapter instance
* @uic_cmd: UIC command
*
* Returns 0 only if success.
*/
static int
ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
{
int ret;
unsigned long flags;
ufshcd_hold(hba, false);
mutex_lock(&hba->uic_cmd_mutex);
ufshcd_add_delay_before_dme_cmd(hba);
spin_lock_irqsave(hba->host->host_lock, flags);
ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
spin_unlock_irqrestore(hba->host->host_lock, flags);
if (!ret)
ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
mutex_unlock(&hba->uic_cmd_mutex);
ufshcd_release(hba);
return ret;
}
/**
* ufshcd_map_sg - Map scatter-gather list to prdt
* @lrbp - pointer to local reference block
*
* Returns 0 in case of success, non-zero value in case of failure
*/
static int ufshcd_map_sg(struct ufshcd_lrb *lrbp)
{
struct ufshcd_sg_entry *prd_table;
struct scatterlist *sg;
struct scsi_cmnd *cmd;
int sg_segments;
int i;
cmd = lrbp->cmd;
sg_segments = scsi_dma_map(cmd);
if (sg_segments < 0)
return sg_segments;
if (sg_segments) {
lrbp->utr_descriptor_ptr->prd_table_length =
cpu_to_le16((u16) (sg_segments));
prd_table = (struct ufshcd_sg_entry *)lrbp->ucd_prdt_ptr;
scsi_for_each_sg(cmd, sg, sg_segments, i) {
prd_table[i].size =
cpu_to_le32(((u32) sg_dma_len(sg))-1);
prd_table[i].base_addr =
cpu_to_le32(lower_32_bits(sg->dma_address));
prd_table[i].upper_addr =
cpu_to_le32(upper_32_bits(sg->dma_address));
prd_table[i].reserved = 0;
}
} else {
lrbp->utr_descriptor_ptr->prd_table_length = 0;
}
return 0;
}
/**
* ufshcd_enable_intr - enable interrupts
* @hba: per adapter instance
* @intrs: interrupt bits
*/
static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
{
u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
if (hba->ufs_version == UFSHCI_VERSION_10) {
u32 rw;
rw = set & INTERRUPT_MASK_RW_VER_10;
set = rw | ((set ^ intrs) & intrs);
} else {
set |= intrs;
}
ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
}
/**
* ufshcd_disable_intr - disable interrupts
* @hba: per adapter instance
* @intrs: interrupt bits
*/
static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
{
u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
if (hba->ufs_version == UFSHCI_VERSION_10) {
u32 rw;
rw = (set & INTERRUPT_MASK_RW_VER_10) &
~(intrs & INTERRUPT_MASK_RW_VER_10);
set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
} else {
set &= ~intrs;
}
ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
}
/**
* ufshcd_prepare_req_desc_hdr() - Fills the requests header
* descriptor according to request
* @lrbp: pointer to local reference block
* @upiu_flags: flags required in the header
* @cmd_dir: requests data direction
*/
static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
u32 *upiu_flags, enum dma_data_direction cmd_dir)
{
struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
u32 data_direction;
u32 dword_0;
if (cmd_dir == DMA_FROM_DEVICE) {
data_direction = UTP_DEVICE_TO_HOST;
*upiu_flags = UPIU_CMD_FLAGS_READ;
} else if (cmd_dir == DMA_TO_DEVICE) {
data_direction = UTP_HOST_TO_DEVICE;
*upiu_flags = UPIU_CMD_FLAGS_WRITE;
} else {
data_direction = UTP_NO_DATA_TRANSFER;
*upiu_flags = UPIU_CMD_FLAGS_NONE;
}
dword_0 = data_direction | (lrbp->command_type
<< UPIU_COMMAND_TYPE_OFFSET);
if (lrbp->intr_cmd)
dword_0 |= UTP_REQ_DESC_INT_CMD;
/* Transfer request descriptor header fields */
req_desc->header.dword_0 = cpu_to_le32(dword_0);
/* dword_1 is reserved, hence it is set to 0 */
req_desc->header.dword_1 = 0;
/*
* assigning invalid value for command status. Controller
* updates OCS on command completion, with the command
* status
*/
req_desc->header.dword_2 =
cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
/* dword_3 is reserved, hence it is set to 0 */
req_desc->header.dword_3 = 0;
req_desc->prd_table_length = 0;
}
/**
* ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
* for scsi commands
* @lrbp - local reference block pointer
* @upiu_flags - flags
*/
static
void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u32 upiu_flags)
{
struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
unsigned short cdb_len;
/* command descriptor fields */
ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
UPIU_TRANSACTION_COMMAND, upiu_flags,
lrbp->lun, lrbp->task_tag);
ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
/* Total EHS length and Data segment length will be zero */
ucd_req_ptr->header.dword_2 = 0;
ucd_req_ptr->sc.exp_data_transfer_len =
cpu_to_be32(lrbp->cmd->sdb.length);
cdb_len = min_t(unsigned short, lrbp->cmd->cmd_len, MAX_CDB_SIZE);
memset(ucd_req_ptr->sc.cdb, 0, MAX_CDB_SIZE);
memcpy(ucd_req_ptr->sc.cdb, lrbp->cmd->cmnd, cdb_len);
memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
}
/**
* ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
* for query requsts
* @hba: UFS hba
* @lrbp: local reference block pointer
* @upiu_flags: flags
*/
static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
struct ufshcd_lrb *lrbp, u32 upiu_flags)
{
struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
struct ufs_query *query = &hba->dev_cmd.query;
u16 len = be16_to_cpu(query->request.upiu_req.length);
u8 *descp = (u8 *)lrbp->ucd_req_ptr + GENERAL_UPIU_REQUEST_SIZE;
/* Query request header */
ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
lrbp->lun, lrbp->task_tag);
ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
0, query->request.query_func, 0, 0);
/* Data segment length */
ucd_req_ptr->header.dword_2 = UPIU_HEADER_DWORD(
0, 0, len >> 8, (u8)len);
/* Copy the Query Request buffer as is */
memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
QUERY_OSF_SIZE);
/* Copy the Descriptor */
if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
memcpy(descp, query->descriptor, len);
memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
}
static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
{
struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
/* command descriptor fields */
ucd_req_ptr->header.dword_0 =
UPIU_HEADER_DWORD(
UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
/* clear rest of the fields of basic header */
ucd_req_ptr->header.dword_1 = 0;
ucd_req_ptr->header.dword_2 = 0;
memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
}
/**
* ufshcd_compose_upiu - form UFS Protocol Information Unit(UPIU)
* @hba - per adapter instance
* @lrb - pointer to local reference block
*/
static int ufshcd_compose_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
{
u32 upiu_flags;
int ret = 0;
switch (lrbp->command_type) {
case UTP_CMD_TYPE_SCSI:
if (likely(lrbp->cmd)) {
ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
lrbp->cmd->sc_data_direction);
ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
} else {
ret = -EINVAL;
}
break;
case UTP_CMD_TYPE_DEV_MANAGE:
ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
ufshcd_prepare_utp_query_req_upiu(
hba, lrbp, upiu_flags);
else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
ufshcd_prepare_utp_nop_upiu(lrbp);
else
ret = -EINVAL;
break;
case UTP_CMD_TYPE_UFS:
/* For UFS native command implementation */
ret = -ENOTSUPP;
dev_err(hba->dev, "%s: UFS native command are not supported\n",
__func__);
break;
default:
ret = -ENOTSUPP;
dev_err(hba->dev, "%s: unknown command type: 0x%x\n",
__func__, lrbp->command_type);
break;
} /* end of switch */
return ret;
}
/*
* ufshcd_scsi_to_upiu_lun - maps scsi LUN to UPIU LUN
* @scsi_lun: scsi LUN id
*
* Returns UPIU LUN id
*/
static inline u8 ufshcd_scsi_to_upiu_lun(unsigned int scsi_lun)
{
if (scsi_is_wlun(scsi_lun))
return (scsi_lun & UFS_UPIU_MAX_UNIT_NUM_ID)
| UFS_UPIU_WLUN_ID;
else
return scsi_lun & UFS_UPIU_MAX_UNIT_NUM_ID;
}
/**
* ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
* @scsi_lun: UPIU W-LUN id
*
* Returns SCSI W-LUN id
*/
static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
{
return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
}
/**
* ufshcd_queuecommand - main entry point for SCSI requests
* @cmd: command from SCSI Midlayer
* @done: call back function
*
* Returns 0 for success, non-zero in case of failure
*/
static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
{
struct ufshcd_lrb *lrbp;
struct ufs_hba *hba;
unsigned long flags;
int tag;
int err = 0;
hba = shost_priv(host);
tag = cmd->request->tag;
if (!ufshcd_valid_tag(hba, tag)) {
dev_err(hba->dev,
"%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
__func__, tag, cmd, cmd->request);
BUG();
}
spin_lock_irqsave(hba->host->host_lock, flags);
switch (hba->ufshcd_state) {
case UFSHCD_STATE_OPERATIONAL:
break;
case UFSHCD_STATE_RESET:
err = SCSI_MLQUEUE_HOST_BUSY;
goto out_unlock;
case UFSHCD_STATE_ERROR:
set_host_byte(cmd, DID_ERROR);
cmd->scsi_done(cmd);
goto out_unlock;
default:
dev_WARN_ONCE(hba->dev, 1, "%s: invalid state %d\n",
__func__, hba->ufshcd_state);
set_host_byte(cmd, DID_BAD_TARGET);
cmd->scsi_done(cmd);
goto out_unlock;
}
/* if error handling is in progress, don't issue commands */
if (ufshcd_eh_in_progress(hba)) {
set_host_byte(cmd, DID_ERROR);
cmd->scsi_done(cmd);
goto out_unlock;
}
spin_unlock_irqrestore(hba->host->host_lock, flags);
/* acquire the tag to make sure device cmds don't use it */
if (test_and_set_bit_lock(tag, &hba->lrb_in_use)) {
/*
* Dev manage command in progress, requeue the command.
* Requeuing the command helps in cases where the request *may*
* find different tag instead of waiting for dev manage command
* completion.
*/
err = SCSI_MLQUEUE_HOST_BUSY;
goto out;
}
err = ufshcd_hold(hba, true);
if (err) {
err = SCSI_MLQUEUE_HOST_BUSY;
clear_bit_unlock(tag, &hba->lrb_in_use);
goto out;
}
WARN_ON(hba->clk_gating.state != CLKS_ON);
lrbp = &hba->lrb[tag];
WARN_ON(lrbp->cmd);
lrbp->cmd = cmd;
lrbp->sense_bufflen = SCSI_SENSE_BUFFERSIZE;
lrbp->sense_buffer = cmd->sense_buffer;
lrbp->task_tag = tag;
lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba) ? true : false;
lrbp->command_type = UTP_CMD_TYPE_SCSI;
/* form UPIU before issuing the command */
ufshcd_compose_upiu(hba, lrbp);
err = ufshcd_map_sg(lrbp);
if (err) {
lrbp->cmd = NULL;
clear_bit_unlock(tag, &hba->lrb_in_use);
goto out;
}
/* issue command to the controller */
spin_lock_irqsave(hba->host->host_lock, flags);
ufshcd_send_command(hba, tag);
out_unlock:
spin_unlock_irqrestore(hba->host->host_lock, flags);
out:
return err;
}
static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
{
lrbp->cmd = NULL;
lrbp->sense_bufflen = 0;
lrbp->sense_buffer = NULL;
lrbp->task_tag = tag;
lrbp->lun = 0; /* device management cmd is not specific to any LUN */
lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
lrbp->intr_cmd = true; /* No interrupt aggregation */
hba->dev_cmd.type = cmd_type;
return ufshcd_compose_upiu(hba, lrbp);
}
static int
ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
{
int err = 0;
unsigned long flags;
u32 mask = 1 << tag;
/* clear outstanding transaction before retry */
spin_lock_irqsave(hba->host->host_lock, flags);
ufshcd_utrl_clear(hba, tag);
spin_unlock_irqrestore(hba->host->host_lock, flags);
/*
* wait for for h/w to clear corresponding bit in door-bell.
* max. wait is 1 sec.
*/
err = ufshcd_wait_for_register(hba,
REG_UTP_TRANSFER_REQ_DOOR_BELL,
mask, ~mask, 1000, 1000, true);
return err;
}
static int
ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
{
struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
/* Get the UPIU response */
query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
UPIU_RSP_CODE_OFFSET;
return query_res->response;
}
/**
* ufshcd_dev_cmd_completion() - handles device management command responses
* @hba: per adapter instance
* @lrbp: pointer to local reference block
*/
static int
ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
{
int resp;
int err = 0;
resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
switch (resp) {
case UPIU_TRANSACTION_NOP_IN:
if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
err = -EINVAL;
dev_err(hba->dev, "%s: unexpected response %x\n",
__func__, resp);
}
break;
case UPIU_TRANSACTION_QUERY_RSP:
err = ufshcd_check_query_response(hba, lrbp);
if (!err)
err = ufshcd_copy_query_response(hba, lrbp);
break;
case UPIU_TRANSACTION_REJECT_UPIU:
/* TODO: handle Reject UPIU Response */
err = -EPERM;
dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
__func__);
break;
default:
err = -EINVAL;
dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
__func__, resp);
break;
}
return err;
}
static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
struct ufshcd_lrb *lrbp, int max_timeout)
{
int err = 0;
unsigned long time_left;
unsigned long flags;
time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
msecs_to_jiffies(max_timeout));
spin_lock_irqsave(hba->host->host_lock, flags);
hba->dev_cmd.complete = NULL;
if (likely(time_left)) {
err = ufshcd_get_tr_ocs(lrbp);
if (!err)
err = ufshcd_dev_cmd_completion(hba, lrbp);
}
spin_unlock_irqrestore(hba->host->host_lock, flags);
if (!time_left) {
err = -ETIMEDOUT;
dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
__func__, lrbp->task_tag);
if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
/* successfully cleared the command, retry if needed */
err = -EAGAIN;
/*
* in case of an error, after clearing the doorbell,
* we also need to clear the outstanding_request
* field in hba
*/
ufshcd_outstanding_req_clear(hba, lrbp->task_tag);
}
return err;
}
/**
* ufshcd_get_dev_cmd_tag - Get device management command tag
* @hba: per-adapter instance
* @tag: pointer to variable with available slot value
*
* Get a free slot and lock it until device management command
* completes.
*
* Returns false if free slot is unavailable for locking, else
* return true with tag value in @tag.
*/
static bool ufshcd_get_dev_cmd_tag(struct ufs_hba *hba, int *tag_out)
{
int tag;
bool ret = false;
unsigned long tmp;
if (!tag_out)
goto out;
do {
tmp = ~hba->lrb_in_use;
tag = find_last_bit(&tmp, hba->nutrs);
if (tag >= hba->nutrs)
goto out;
} while (test_and_set_bit_lock(tag, &hba->lrb_in_use));
*tag_out = tag;
ret = true;
out:
return ret;
}
static inline void ufshcd_put_dev_cmd_tag(struct ufs_hba *hba, int tag)
{
clear_bit_unlock(tag, &hba->lrb_in_use);
}
/**
* ufshcd_exec_dev_cmd - API for sending device management requests
* @hba - UFS hba
* @cmd_type - specifies the type (NOP, Query...)
* @timeout - time in seconds
*
* NOTE: Since there is only one available tag for device management commands,
* it is expected you hold the hba->dev_cmd.lock mutex.
*/
static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
enum dev_cmd_type cmd_type, int timeout)
{
struct ufshcd_lrb *lrbp;
int err;
int tag;
struct completion wait;
unsigned long flags;
/*
* Get free slot, sleep if slots are unavailable.
* Even though we use wait_event() which sleeps indefinitely,
* the maximum wait time is bounded by SCSI request timeout.
*/
wait_event(hba->dev_cmd.tag_wq, ufshcd_get_dev_cmd_tag(hba, &tag));
init_completion(&wait);
lrbp = &hba->lrb[tag];
WARN_ON(lrbp->cmd);
err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
if (unlikely(err))
goto out_put_tag;
hba->dev_cmd.complete = &wait;
/* Make sure descriptors are ready before ringing the doorbell */
wmb();
spin_lock_irqsave(hba->host->host_lock, flags);
ufshcd_send_command(hba, tag);
spin_unlock_irqrestore(hba->host->host_lock, flags);
err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
out_put_tag:
ufshcd_put_dev_cmd_tag(hba, tag);
wake_up(&hba->dev_cmd.tag_wq);
return err;
}
/**
* ufshcd_init_query() - init the query response and request parameters
* @hba: per-adapter instance
* @request: address of the request pointer to be initialized
* @response: address of the response pointer to be initialized
* @opcode: operation to perform
* @idn: flag idn to access
* @index: LU number to access
* @selector: query/flag/descriptor further identification
*/
static inline void ufshcd_init_query(struct ufs_hba *hba,
struct ufs_query_req **request, struct ufs_query_res **response,
enum query_opcode opcode, u8 idn, u8 index, u8 selector)
{
*request = &hba->dev_cmd.query.request;
*response = &hba->dev_cmd.query.response;
memset(*request, 0, sizeof(struct ufs_query_req));
memset(*response, 0, sizeof(struct ufs_query_res));
(*request)->upiu_req.opcode = opcode;
(*request)->upiu_req.idn = idn;
(*request)->upiu_req.index = index;
(*request)->upiu_req.selector = selector;
}
static int ufshcd_query_flag_retry(struct ufs_hba *hba,
enum query_opcode opcode, enum flag_idn idn, bool *flag_res)
{
int ret;
int retries;
for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
ret = ufshcd_query_flag(hba, opcode, idn, flag_res);
if (ret)
dev_dbg(hba->dev,
"%s: failed with error %d, retries %d\n",
__func__, ret, retries);
else
break;
}
if (ret)
dev_err(hba->dev,
"%s: query attribute, opcode %d, idn %d, failed with error %d after %d retires\n",
__func__, opcode, idn, ret, retries);
return ret;
}
/**
* ufshcd_query_flag() - API function for sending flag query requests
* hba: per-adapter instance
* query_opcode: flag query to perform
* idn: flag idn to access
* flag_res: the flag value after the query request completes
*
* Returns 0 for success, non-zero in case of failure
*/
int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
enum flag_idn idn, bool *flag_res)
{
struct ufs_query_req *request = NULL;
struct ufs_query_res *response = NULL;
int err, index = 0, selector = 0;
int timeout = QUERY_REQ_TIMEOUT;
BUG_ON(!hba);
ufshcd_hold(hba, false);
mutex_lock(&hba->dev_cmd.lock);
ufshcd_init_query(hba, &request, &response, opcode, idn, index,
selector);
switch (opcode) {
case UPIU_QUERY_OPCODE_SET_FLAG:
case UPIU_QUERY_OPCODE_CLEAR_FLAG:
case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
break;
case UPIU_QUERY_OPCODE_READ_FLAG:
request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
if (!flag_res) {
/* No dummy reads */
dev_err(hba->dev, "%s: Invalid argument for read request\n",
__func__);
err = -EINVAL;
goto out_unlock;
}
break;
default:
dev_err(hba->dev,
"%s: Expected query flag opcode but got = %d\n",
__func__, opcode);
err = -EINVAL;
goto out_unlock;
}
if (idn == QUERY_FLAG_IDN_FDEVICEINIT)
timeout = QUERY_FDEVICEINIT_REQ_TIMEOUT;
err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
if (err) {
dev_err(hba->dev,
"%s: Sending flag query for idn %d failed, err = %d\n",
__func__, idn, err);
goto out_unlock;
}
if (flag_res)
*flag_res = (be32_to_cpu(response->upiu_res.value) &
MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
out_unlock:
mutex_unlock(&hba->dev_cmd.lock);
ufshcd_release(hba);
return err;
}
/**
* ufshcd_query_attr - API function for sending attribute requests
* hba: per-adapter instance
* opcode: attribute opcode
* idn: attribute idn to access
* index: index field
* selector: selector field
* attr_val: the attribute value after the query request completes
*
* Returns 0 for success, non-zero in case of failure
*/
static int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
{
struct ufs_query_req *request = NULL;
struct ufs_query_res *response = NULL;
int err;
BUG_ON(!hba);
ufshcd_hold(hba, false);
if (!attr_val) {
dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
__func__, opcode);
err = -EINVAL;
goto out;
}
mutex_lock(&hba->dev_cmd.lock);
ufshcd_init_query(hba, &request, &response, opcode, idn, index,
selector);
switch (opcode) {
case UPIU_QUERY_OPCODE_WRITE_ATTR:
request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
request->upiu_req.value = cpu_to_be32(*attr_val);
break;
case UPIU_QUERY_OPCODE_READ_ATTR:
request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
break;
default:
dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
__func__, opcode);
err = -EINVAL;
goto out_unlock;
}
err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
if (err) {
dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, err = %d\n",
__func__, opcode, idn, err);
goto out_unlock;
}
*attr_val = be32_to_cpu(response->upiu_res.value);
out_unlock:
mutex_unlock(&hba->dev_cmd.lock);
out:
ufshcd_release(hba);
return err;
}
/**
* ufshcd_query_attr_retry() - API function for sending query
* attribute with retries
* @hba: per-adapter instance
* @opcode: attribute opcode
* @idn: attribute idn to access
* @index: index field
* @selector: selector field
* @attr_val: the attribute value after the query request
* completes
*
* Returns 0 for success, non-zero in case of failure
*/
static int ufshcd_query_attr_retry(struct ufs_hba *hba,
enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
u32 *attr_val)
{
int ret = 0;
u32 retries;
for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
ret = ufshcd_query_attr(hba, opcode, idn, index,
selector, attr_val);
if (ret)
dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
__func__, ret, retries);
else
break;
}
if (ret)
dev_err(hba->dev,
"%s: query attribute, idn %d, failed with error %d after %d retires\n",
__func__, idn, ret, QUERY_REQ_RETRIES);
return ret;
}
static int __ufshcd_query_descriptor(struct ufs_hba *hba,
enum query_opcode opcode, enum desc_idn idn, u8 index,
u8 selector, u8 *desc_buf, int *buf_len)
{
struct ufs_query_req *request = NULL;
struct ufs_query_res *response = NULL;
int err;
BUG_ON(!hba);
ufshcd_hold(hba, false);
if (!desc_buf) {
dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
__func__, opcode);
err = -EINVAL;
goto out;
}
if (*buf_len <= QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
__func__, *buf_len);
err = -EINVAL;
goto out;
}
mutex_lock(&hba->dev_cmd.lock);
ufshcd_init_query(hba, &request, &response, opcode, idn, index,
selector);
hba->dev_cmd.query.descriptor = desc_buf;
request->upiu_req.length = cpu_to_be16(*buf_len);
switch (opcode) {
case UPIU_QUERY_OPCODE_WRITE_DESC:
request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
break;
case UPIU_QUERY_OPCODE_READ_DESC:
request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
break;
default:
dev_err(hba->dev,
"%s: Expected query descriptor opcode but got = 0x%.2x\n",
__func__, opcode);
err = -EINVAL;
goto out_unlock;
}
err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
if (err) {
dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, err = %d\n",
__func__, opcode, idn, err);
goto out_unlock;
}
hba->dev_cmd.query.descriptor = NULL;
*buf_len = be16_to_cpu(response->upiu_res.length);
out_unlock:
mutex_unlock(&hba->dev_cmd.lock);
out:
ufshcd_release(hba);
return err;
}
/**
* ufshcd_query_descriptor_retry - API function for sending descriptor
* requests
* hba: per-adapter instance
* opcode: attribute opcode
* idn: attribute idn to access
* index: index field
* selector: selector field
* desc_buf: the buffer that contains the descriptor
* buf_len: length parameter passed to the device
*
* Returns 0 for success, non-zero in case of failure.
* The buf_len parameter will contain, on return, the length parameter
* received on the response.
*/
int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
enum query_opcode opcode, enum desc_idn idn, u8 index,
u8 selector, u8 *desc_buf, int *buf_len)
{
int err;
int retries;
for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
err = __ufshcd_query_descriptor(hba, opcode, idn, index,
selector, desc_buf, buf_len);
if (!err || err == -EINVAL)
break;
}
return err;
}
EXPORT_SYMBOL(ufshcd_query_descriptor_retry);
/**
* ufshcd_read_desc_param - read the specified descriptor parameter
* @hba: Pointer to adapter instance
* @desc_id: descriptor idn value
* @desc_index: descriptor index
* @param_offset: offset of the parameter to read
* @param_read_buf: pointer to buffer where parameter would be read
* @param_size: sizeof(param_read_buf)
*
* Return 0 in case of success, non-zero otherwise
*/
static int ufshcd_read_desc_param(struct ufs_hba *hba,
enum desc_idn desc_id,
int desc_index,
u32 param_offset,
u8 *param_read_buf,
u32 param_size)
{
int ret;
u8 *desc_buf;
u32 buff_len;
bool is_kmalloc = true;
/* safety checks */
if (desc_id >= QUERY_DESC_IDN_MAX)
return -EINVAL;
buff_len = ufs_query_desc_max_size[desc_id];
if ((param_offset + param_size) > buff_len)
return -EINVAL;
if (!param_offset && (param_size == buff_len)) {
/* memory space already available to hold full descriptor */
desc_buf = param_read_buf;
is_kmalloc = false;
} else {
/* allocate memory to hold full descriptor */
desc_buf = kmalloc(buff_len, GFP_KERNEL);
if (!desc_buf)
return -ENOMEM;
}
ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
desc_id, desc_index, 0, desc_buf,
&buff_len);
if (ret || (buff_len < ufs_query_desc_max_size[desc_id]) ||
(desc_buf[QUERY_DESC_LENGTH_OFFSET] !=
ufs_query_desc_max_size[desc_id])
|| (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id)) {
dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d param_offset %d buff_len %d ret %d",
__func__, desc_id, param_offset, buff_len, ret);
if (!ret)
ret = -EINVAL;
goto out;
}
if (is_kmalloc)
memcpy(param_read_buf, &desc_buf[param_offset], param_size);
out:
if (is_kmalloc)
kfree(desc_buf);
return ret;
}
static inline int ufshcd_read_desc(struct ufs_hba *hba,
enum desc_idn desc_id,
int desc_index,
u8 *buf,
u32 size)
{
return ufshcd_read_desc_param(hba, desc_id, desc_index, 0, buf, size);
}
static inline int ufshcd_read_power_desc(struct ufs_hba *hba,
u8 *buf,
u32 size)
{
return ufshcd_read_desc(hba, QUERY_DESC_IDN_POWER, 0, buf, size);
}
int ufshcd_read_device_desc(struct ufs_hba *hba, u8 *buf, u32 size)
{
return ufshcd_read_desc(hba, QUERY_DESC_IDN_DEVICE, 0, buf, size);
}
EXPORT_SYMBOL(ufshcd_read_device_desc);
/**
* ufshcd_read_string_desc - read string descriptor
* @hba: pointer to adapter instance
* @desc_index: descriptor index
* @buf: pointer to buffer where descriptor would be read
* @size: size of buf
* @ascii: if true convert from unicode to ascii characters
*
* Return 0 in case of success, non-zero otherwise
*/
int ufshcd_read_string_desc(struct ufs_hba *hba, int desc_index, u8 *buf,
u32 size, bool ascii)
{
int err = 0;
err = ufshcd_read_desc(hba,
QUERY_DESC_IDN_STRING, desc_index, buf, size);
if (err) {
dev_err(hba->dev, "%s: reading String Desc failed after %d retries. err = %d\n",
__func__, QUERY_REQ_RETRIES, err);
goto out;
}
if (ascii) {
int desc_len;
int ascii_len;
int i;
char *buff_ascii;
desc_len = buf[0];
/* remove header and divide by 2 to move from UTF16 to UTF8 */
ascii_len = (desc_len - QUERY_DESC_HDR_SIZE) / 2 + 1;
if (size < ascii_len + QUERY_DESC_HDR_SIZE) {
dev_err(hba->dev, "%s: buffer allocated size is too small\n",
__func__);
err = -ENOMEM;
goto out;
}
buff_ascii = kmalloc(ascii_len, GFP_KERNEL);
if (!buff_ascii) {
err = -ENOMEM;
goto out_free_buff;
}
/*
* the descriptor contains string in UTF16 format
* we need to convert to utf-8 so it can be displayed
*/
utf16s_to_utf8s((wchar_t *)&buf[QUERY_DESC_HDR_SIZE],
desc_len - QUERY_DESC_HDR_SIZE,
UTF16_BIG_ENDIAN, buff_ascii, ascii_len);
/* replace non-printable or non-ASCII characters with spaces */
for (i = 0; i < ascii_len; i++)
ufshcd_remove_non_printable(&buff_ascii[i]);
memset(buf + QUERY_DESC_HDR_SIZE, 0,
size - QUERY_DESC_HDR_SIZE);
memcpy(buf + QUERY_DESC_HDR_SIZE, buff_ascii, ascii_len);
buf[QUERY_DESC_LENGTH_OFFSET] = ascii_len + QUERY_DESC_HDR_SIZE;
out_free_buff:
kfree(buff_ascii);
}
out:
return err;
}
EXPORT_SYMBOL(ufshcd_read_string_desc);
/**
* ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
* @hba: Pointer to adapter instance
* @lun: lun id
* @param_offset: offset of the parameter to read
* @param_read_buf: pointer to buffer where parameter would be read
* @param_size: sizeof(param_read_buf)
*
* Return 0 in case of success, non-zero otherwise
*/
static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
int lun,
enum unit_desc_param param_offset,
u8 *param_read_buf,
u32 param_size)
{
/*
* Unit descriptors are only available for general purpose LUs (LUN id
* from 0 to 7) and RPMB Well known LU.
*/
if (lun != UFS_UPIU_RPMB_WLUN && (lun >= UFS_UPIU_MAX_GENERAL_LUN))
return -EOPNOTSUPP;
return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
param_offset, param_read_buf, param_size);
}
/**
* ufshcd_memory_alloc - allocate memory for host memory space data structures
* @hba: per adapter instance
*
* 1. Allocate DMA memory for Command Descriptor array
* Each command descriptor consist of Command UPIU, Response UPIU and PRDT
* 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
* 3. Allocate DMA memory for UTP Task Management Request Descriptor List
* (UTMRDL)
* 4. Allocate memory for local reference block(lrb).
*
* Returns 0 for success, non-zero in case of failure
*/
static int ufshcd_memory_alloc(struct ufs_hba *hba)
{
size_t utmrdl_size, utrdl_size, ucdl_size;
/* Allocate memory for UTP command descriptors */
ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
ucdl_size,
&hba->ucdl_dma_addr,
GFP_KERNEL);
/*
* UFSHCI requires UTP command descriptor to be 128 byte aligned.
* make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
* if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
* be aligned to 128 bytes as well
*/
if (!hba->ucdl_base_addr ||
WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
dev_err(hba->dev,
"Command Descriptor Memory allocation failed\n");
goto out;
}
/*
* Allocate memory for UTP Transfer descriptors
* UFSHCI requires 1024 byte alignment of UTRD
*/
utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
utrdl_size,
&hba->utrdl_dma_addr,
GFP_KERNEL);
if (!hba->utrdl_base_addr ||
WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
dev_err(hba->dev,
"Transfer Descriptor Memory allocation failed\n");
goto out;
}
/*
* Allocate memory for UTP Task Management descriptors
* UFSHCI requires 1024 byte alignment of UTMRD
*/
utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
utmrdl_size,
&hba->utmrdl_dma_addr,
GFP_KERNEL);
if (!hba->utmrdl_base_addr ||
WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
dev_err(hba->dev,
"Task Management Descriptor Memory allocation failed\n");
goto out;
}
/* Allocate memory for local reference block */
hba->lrb = devm_kzalloc(hba->dev,
hba->nutrs * sizeof(struct ufshcd_lrb),
GFP_KERNEL);
if (!hba->lrb) {
dev_err(hba->dev, "LRB Memory allocation failed\n");
goto out;
}
return 0;
out:
return -ENOMEM;
}
/**
* ufshcd_host_memory_configure - configure local reference block with
* memory offsets
* @hba: per adapter instance
*
* Configure Host memory space
* 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
* address.
* 2. Update each UTRD with Response UPIU offset, Response UPIU length
* and PRDT offset.
* 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
* into local reference block.
*/
static void ufshcd_host_memory_configure(struct ufs_hba *hba)
{
struct utp_transfer_cmd_desc *cmd_descp;
struct utp_transfer_req_desc *utrdlp;
dma_addr_t cmd_desc_dma_addr;
dma_addr_t cmd_desc_element_addr;
u16 response_offset;
u16 prdt_offset;
int cmd_desc_size;
int i;
utrdlp = hba->utrdl_base_addr;
cmd_descp = hba->ucdl_base_addr;
response_offset =
offsetof(struct utp_transfer_cmd_desc, response_upiu);
prdt_offset =
offsetof(struct utp_transfer_cmd_desc, prd_table);
cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
cmd_desc_dma_addr = hba->ucdl_dma_addr;
for (i = 0; i < hba->nutrs; i++) {
/* Configure UTRD with command descriptor base address */
cmd_desc_element_addr =
(cmd_desc_dma_addr + (cmd_desc_size * i));
utrdlp[i].command_desc_base_addr_lo =
cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
utrdlp[i].command_desc_base_addr_hi =
cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
/* Response upiu and prdt offset should be in double words */
utrdlp[i].response_upiu_offset =
cpu_to_le16((response_offset >> 2));
utrdlp[i].prd_table_offset =
cpu_to_le16((prdt_offset >> 2));
utrdlp[i].response_upiu_length =
cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
hba->lrb[i].utr_descriptor_ptr = (utrdlp + i);
hba->lrb[i].ucd_req_ptr =
(struct utp_upiu_req *)(cmd_descp + i);
hba->lrb[i].ucd_rsp_ptr =
(struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
hba->lrb[i].ucd_prdt_ptr =
(struct ufshcd_sg_entry *)cmd_descp[i].prd_table;
}
}
/**
* ufshcd_dme_link_startup - Notify Unipro to perform link startup
* @hba: per adapter instance
*
* UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
* in order to initialize the Unipro link startup procedure.
* Once the Unipro links are up, the device connected to the controller
* is detected.
*
* Returns 0 on success, non-zero value on failure
*/
static int ufshcd_dme_link_startup(struct ufs_hba *hba)
{
struct uic_command uic_cmd = {0};
int ret;
uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
if (ret)
dev_err(hba->dev,
"dme-link-startup: error code %d\n", ret);
return ret;
}
static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
{
#define MIN_DELAY_BEFORE_DME_CMDS_US 1000
unsigned long min_sleep_time_us;
if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
return;
/*
* last_dme_cmd_tstamp will be 0 only for 1st call to
* this function
*/
if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
} else {
unsigned long delta =
(unsigned long) ktime_to_us(
ktime_sub(ktime_get(),
hba->last_dme_cmd_tstamp));
if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
min_sleep_time_us =
MIN_DELAY_BEFORE_DME_CMDS_US - delta;
else
return; /* no more delay required */
}
/* allow sleep for extra 50us if needed */
usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
}
/**
* ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
* @hba: per adapter instance
* @attr_sel: uic command argument1
* @attr_set: attribute set type as uic command argument2
* @mib_val: setting value as uic command argument3
* @peer: indicate whether peer or local
*
* Returns 0 on success, non-zero value on failure
*/
int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
u8 attr_set, u32 mib_val, u8 peer)
{
struct uic_command uic_cmd = {0};
static const char *const action[] = {
"dme-set",
"dme-peer-set"
};
const char *set = action[!!peer];
int ret;
int retries = UFS_UIC_COMMAND_RETRIES;
uic_cmd.command = peer ?
UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
uic_cmd.argument1 = attr_sel;
uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
uic_cmd.argument3 = mib_val;
do {
/* for peer attributes we retry upon failure */
ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
if (ret)
dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
} while (ret && peer && --retries);
if (!retries)
dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
set, UIC_GET_ATTR_ID(attr_sel), mib_val,
retries);
return ret;
}
EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
/**
* ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
* @hba: per adapter instance
* @attr_sel: uic command argument1
* @mib_val: the value of the attribute as returned by the UIC command
* @peer: indicate whether peer or local
*
* Returns 0 on success, non-zero value on failure
*/
int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
u32 *mib_val, u8 peer)
{
struct uic_command uic_cmd = {0};
static const char *const action[] = {
"dme-get",
"dme-peer-get"
};
const char *get = action[!!peer];
int ret;
int retries = UFS_UIC_COMMAND_RETRIES;
struct ufs_pa_layer_attr orig_pwr_info;
struct ufs_pa_layer_attr temp_pwr_info;
bool pwr_mode_change = false;
if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
orig_pwr_info = hba->pwr_info;
temp_pwr_info = orig_pwr_info;
if (orig_pwr_info.pwr_tx == FAST_MODE ||
orig_pwr_info.pwr_rx == FAST_MODE) {
temp_pwr_info.pwr_tx = FASTAUTO_MODE;
temp_pwr_info.pwr_rx = FASTAUTO_MODE;
pwr_mode_change = true;
} else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
orig_pwr_info.pwr_rx == SLOW_MODE) {
temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
pwr_mode_change = true;
}
if (pwr_mode_change) {
ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
if (ret)
goto out;
}
}
uic_cmd.command = peer ?
UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
uic_cmd.argument1 = attr_sel;
do {
/* for peer attributes we retry upon failure */
ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
if (ret)
dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
get, UIC_GET_ATTR_ID(attr_sel), ret);
} while (ret && peer && --retries);
if (!retries)
dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
get, UIC_GET_ATTR_ID(attr_sel), retries);
if (mib_val && !ret)
*mib_val = uic_cmd.argument3;
if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
&& pwr_mode_change)
ufshcd_change_power_mode(hba, &orig_pwr_info);
out:
return ret;
}
EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
/**
* ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
* state) and waits for it to take effect.
*
* @hba: per adapter instance
* @cmd: UIC command to execute
*
* DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
* DME_HIBERNATE_EXIT commands take some time to take its effect on both host
* and device UniPro link and hence it's final completion would be indicated by
* dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
* addition to normal UIC command completion Status (UCCS). This function only
* returns after the relevant status bits indicate the completion.
*
* Returns 0 on success, non-zero value on failure
*/
static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
{
struct completion uic_async_done;
unsigned long flags;
u8 status;
int ret;
bool reenable_intr = false;
mutex_lock(&hba->uic_cmd_mutex);
init_completion(&uic_async_done);
ufshcd_add_delay_before_dme_cmd(hba);
spin_lock_irqsave(hba->host->host_lock, flags);
hba->uic_async_done = &uic_async_done;
if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
/*
* Make sure UIC command completion interrupt is disabled before
* issuing UIC command.
*/
wmb();
reenable_intr = true;
}
ret = __ufshcd_send_uic_cmd(hba, cmd, false);
spin_unlock_irqrestore(hba->host->host_lock, flags);
if (ret) {
dev_err(hba->dev,
"pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
cmd->command, cmd->argument3, ret);
goto out;
}
if (!wait_for_completion_timeout(hba->uic_async_done,
msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
dev_err(hba->dev,
"pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
cmd->command, cmd->argument3);
ret = -ETIMEDOUT;
goto out;
}
status = ufshcd_get_upmcrs(hba);
if (status != PWR_LOCAL) {
dev_err(hba->dev,
"pwr ctrl cmd 0x%0x failed, host umpcrs:0x%x\n",
cmd->command, status);
ret = (status != PWR_OK) ? status : -1;
}
out:
spin_lock_irqsave(hba->host->host_lock, flags);
hba->active_uic_cmd = NULL;
hba->uic_async_done = NULL;
if (reenable_intr)
ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
spin_unlock_irqrestore(hba->host->host_lock, flags);
mutex_unlock(&hba->uic_cmd_mutex);
return ret;
}
/**
* ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
* using DME_SET primitives.
* @hba: per adapter instance
* @mode: powr mode value
*
* Returns 0 on success, non-zero value on failure
*/
static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
{
struct uic_command uic_cmd = {0};
int ret;
if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
ret = ufshcd_dme_set(hba,
UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
if (ret) {
dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
__func__, ret);
goto out;
}
}
uic_cmd.command = UIC_CMD_DME_SET;
uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
uic_cmd.argument3 = mode;
ufshcd_hold(hba, false);
ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
ufshcd_release(hba);
out:
return ret;
}
static int ufshcd_link_recovery(struct ufs_hba *hba)
{
int ret;
unsigned long flags;
spin_lock_irqsave(hba->host->host_lock, flags);
hba->ufshcd_state = UFSHCD_STATE_RESET;
ufshcd_set_eh_in_progress(hba);
spin_unlock_irqrestore(hba->host->host_lock, flags);
ret = ufshcd_host_reset_and_restore(hba);
spin_lock_irqsave(hba->host->host_lock, flags);
if (ret)
hba->ufshcd_state = UFSHCD_STATE_ERROR;
ufshcd_clear_eh_in_progress(hba);
spin_unlock_irqrestore(hba->host->host_lock, flags);
if (ret)
dev_err(hba->dev, "%s: link recovery failed, err %d",
__func__, ret);
return ret;
}
static int __ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
{
int ret;
struct uic_command uic_cmd = {0};
uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
if (ret) {
dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
__func__, ret);
/*
* If link recovery fails then return error so that caller
* don't retry the hibern8 enter again.
*/
if (ufshcd_link_recovery(hba))
ret = -ENOLINK;
}
return ret;
}
static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
{
int ret = 0, retries;
for (retries = UIC_HIBERN8_ENTER_RETRIES; retries > 0; retries--) {
ret = __ufshcd_uic_hibern8_enter(hba);
if (!ret || ret == -ENOLINK)
goto out;
}
out:
return ret;
}
static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
{
struct uic_command uic_cmd = {0};
int ret;
uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
if (ret) {
dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
__func__, ret);
ret = ufshcd_link_recovery(hba);
}
return ret;
}
/**
* ufshcd_init_pwr_info - setting the POR (power on reset)
* values in hba power info
* @hba: per-adapter instance
*/
static void ufshcd_init_pwr_info(struct ufs_hba *hba)
{
hba->pwr_info.gear_rx = UFS_PWM_G1;
hba->pwr_info.gear_tx = UFS_PWM_G1;
hba->pwr_info.lane_rx = 1;
hba->pwr_info.lane_tx = 1;
hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
hba->pwr_info.hs_rate = 0;
}
/**
* ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
* @hba: per-adapter instance
*/
static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
{
struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
if (hba->max_pwr_info.is_valid)
return 0;
pwr_info->pwr_tx = FASTAUTO_MODE;
pwr_info->pwr_rx = FASTAUTO_MODE;
pwr_info->hs_rate = PA_HS_MODE_B;
/* Get the connected lane count */
ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
&pwr_info->lane_rx);
ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
&pwr_info->lane_tx);
if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
__func__,
pwr_info->lane_rx,
pwr_info->lane_tx);
return -EINVAL;
}
/*
* First, get the maximum gears of HS speed.
* If a zero value, it means there is no HSGEAR capability.
* Then, get the maximum gears of PWM speed.
*/
ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
if (!pwr_info->gear_rx) {
ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
&pwr_info->gear_rx);
if (!pwr_info->gear_rx) {
dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
__func__, pwr_info->gear_rx);
return -EINVAL;
}
pwr_info->pwr_rx = SLOWAUTO_MODE;
}
ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
&pwr_info->gear_tx);
if (!pwr_info->gear_tx) {
ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
&pwr_info->gear_tx);
if (!pwr_info->gear_tx) {
dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
__func__, pwr_info->gear_tx);
return -EINVAL;
}
pwr_info->pwr_tx = SLOWAUTO_MODE;
}
hba->max_pwr_info.is_valid = true;
return 0;
}
static int ufshcd_change_power_mode(struct ufs_hba *hba,
struct ufs_pa_layer_attr *pwr_mode)
{
int ret;
/* if already configured to the requested pwr_mode */
if (pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
dev_dbg(hba->dev, "%s: power already configured\n", __func__);
return 0;
}
/*
* Configure attributes for power mode change with below.
* - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
* - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
* - PA_HSSERIES
*/
ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
pwr_mode->lane_rx);
if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
pwr_mode->pwr_rx == FAST_MODE)
ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
else
ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
pwr_mode->lane_tx);
if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
pwr_mode->pwr_tx == FAST_MODE)
ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
else
ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
pwr_mode->pwr_tx == FASTAUTO_MODE ||
pwr_mode->pwr_rx == FAST_MODE ||
pwr_mode->pwr_tx == FAST_MODE)
ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
pwr_mode->hs_rate);
ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
| pwr_mode->pwr_tx);
if (ret) {
dev_err(hba->dev,
"%s: power mode change failed %d\n", __func__, ret);
} else {
ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
pwr_mode);
memcpy(&hba->pwr_info, pwr_mode,
sizeof(struct ufs_pa_layer_attr));
}
return ret;
}
/**
* ufshcd_config_pwr_mode - configure a new power mode
* @hba: per-adapter instance
* @desired_pwr_mode: desired power configuration
*/
static int ufshcd_config_pwr_mode(struct ufs_hba *hba,
struct ufs_pa_layer_attr *desired_pwr_mode)
{
struct ufs_pa_layer_attr final_params = { 0 };
int ret;
ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
desired_pwr_mode, &final_params);
if (ret)
memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
ret = ufshcd_change_power_mode(hba, &final_params);
return ret;
}
/**
* ufshcd_complete_dev_init() - checks device readiness
* hba: per-adapter instance
*
* Set fDeviceInit flag and poll until device toggles it.
*/
static int ufshcd_complete_dev_init(struct ufs_hba *hba)
{
int i;
int err;
bool flag_res = 1;
err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
QUERY_FLAG_IDN_FDEVICEINIT, NULL);
if (err) {
dev_err(hba->dev,
"%s setting fDeviceInit flag failed with error %d\n",
__func__, err);
goto out;
}
/* poll for max. 1000 iterations for fDeviceInit flag to clear */
for (i = 0; i < 1000 && !err && flag_res; i++)
err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
QUERY_FLAG_IDN_FDEVICEINIT, &flag_res);
if (err)
dev_err(hba->dev,
"%s reading fDeviceInit flag failed with error %d\n",
__func__, err);
else if (flag_res)
dev_err(hba->dev,
"%s fDeviceInit was not cleared by the device\n",
__func__);
out:
return err;
}
/**
* ufshcd_make_hba_operational - Make UFS controller operational
* @hba: per adapter instance
*
* To bring UFS host controller to operational state,
* 1. Enable required interrupts
* 2. Configure interrupt aggregation
* 3. Program UTRL and UTMRL base address
* 4. Configure run-stop-registers
*
* Returns 0 on success, non-zero value on failure
*/
static int ufshcd_make_hba_operational(struct ufs_hba *hba)
{
int err = 0;
u32 reg;
/* Enable required interrupts */
ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
/* Configure interrupt aggregation */
if (ufshcd_is_intr_aggr_allowed(hba))
ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
else
ufshcd_disable_intr_aggr(hba);
/* Configure UTRL and UTMRL base address registers */
ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
REG_UTP_TRANSFER_REQ_LIST_BASE_L);
ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
REG_UTP_TRANSFER_REQ_LIST_BASE_H);
ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
REG_UTP_TASK_REQ_LIST_BASE_L);
ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
REG_UTP_TASK_REQ_LIST_BASE_H);
/*
* Make sure base address and interrupt setup are updated before
* enabling the run/stop registers below.
*/
wmb();
/*
* UCRDY, UTMRLDY and UTRLRDY bits must be 1
*/
reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
if (!(ufshcd_get_lists_status(reg))) {
ufshcd_enable_run_stop_reg(hba);
} else {
dev_err(hba->dev,
"Host controller not ready to process requests");
err = -EIO;
goto out;
}
out:
return err;
}
/**
* ufshcd_hba_stop - Send controller to reset state
* @hba: per adapter instance
* @can_sleep: perform sleep or just spin
*/
static inline void ufshcd_hba_stop(struct ufs_hba *hba, bool can_sleep)
{
int err;
ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
CONTROLLER_ENABLE, CONTROLLER_DISABLE,
10, 1, can_sleep);
if (err)
dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
}
/**
* ufshcd_hba_enable - initialize the controller
* @hba: per adapter instance
*
* The controller resets itself and controller firmware initialization
* sequence kicks off. When controller is ready it will set
* the Host Controller Enable bit to 1.
*
* Returns 0 on success, non-zero value on failure
*/
static int ufshcd_hba_enable(struct ufs_hba *hba)
{
int retry;
/*
* msleep of 1 and 5 used in this function might result in msleep(20),
* but it was necessary to send the UFS FPGA to reset mode during
* development and testing of this driver. msleep can be changed to
* mdelay and retry count can be reduced based on the controller.
*/
if (!ufshcd_is_hba_active(hba))
/* change controller state to "reset state" */
ufshcd_hba_stop(hba, true);
/* UniPro link is disabled at this point */
ufshcd_set_link_off(hba);
ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
/* start controller initialization sequence */
ufshcd_hba_start(hba);
/*
* To initialize a UFS host controller HCE bit must be set to 1.
* During initialization the HCE bit value changes from 1->0->1.
* When the host controller completes initialization sequence
* it sets the value of HCE bit to 1. The same HCE bit is read back
* to check if the controller has completed initialization sequence.
* So without this delay the value HCE = 1, set in the previous
* instruction might be read back.
* This delay can be changed based on the controller.
*/
msleep(1);
/* wait for the host controller to complete initialization */
retry = 10;
while (ufshcd_is_hba_active(hba)) {
if (retry) {
retry--;
} else {
dev_err(hba->dev,
"Controller enable failed\n");
return -EIO;
}
msleep(5);
}
/* enable UIC related interrupts */
ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
return 0;
}
static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
{
int tx_lanes, i, err = 0;
if (!peer)
ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
&tx_lanes);
else
ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
&tx_lanes);
for (i = 0; i < tx_lanes; i++) {
if (!peer)
err = ufshcd_dme_set(hba,
UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
0);
else
err = ufshcd_dme_peer_set(hba,
UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
0);
if (err) {
dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
__func__, peer, i, err);
break;
}
}
return err;
}
static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
{
return ufshcd_disable_tx_lcc(hba, true);
}
/**
* ufshcd_link_startup - Initialize unipro link startup
* @hba: per adapter instance
*
* Returns 0 for success, non-zero in case of failure
*/
static int ufshcd_link_startup(struct ufs_hba *hba)
{
int ret;
int retries = DME_LINKSTARTUP_RETRIES;
do {
ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
ret = ufshcd_dme_link_startup(hba);
/* check if device is detected by inter-connect layer */
if (!ret && !ufshcd_is_device_present(hba)) {
dev_err(hba->dev, "%s: Device not present\n", __func__);
ret = -ENXIO;
goto out;
}
/*
* DME link lost indication is only received when link is up,
* but we can't be sure if the link is up until link startup
* succeeds. So reset the local Uni-Pro and try again.
*/
if (ret && ufshcd_hba_enable(hba))
goto out;
} while (ret && retries--);
if (ret)
/* failed to get the link up... retire */
goto out;
if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
ret = ufshcd_disable_device_tx_lcc(hba);
if (ret)
goto out;
}
/* Include any host controller configuration via UIC commands */
ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
if (ret)
goto out;
ret = ufshcd_make_hba_operational(hba);
out:
if (ret)
dev_err(hba->dev, "link startup failed %d\n", ret);
return ret;
}
/**
* ufshcd_verify_dev_init() - Verify device initialization
* @hba: per-adapter instance
*
* Send NOP OUT UPIU and wait for NOP IN response to check whether the
* device Transport Protocol (UTP) layer is ready after a reset.
* If the UTP layer at the device side is not initialized, it may
* not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
* and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
*/
static int ufshcd_verify_dev_init(struct ufs_hba *hba)
{
int err = 0;
int retries;
ufshcd_hold(hba, false);
mutex_lock(&hba->dev_cmd.lock);
for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
NOP_OUT_TIMEOUT);
if (!err || err == -ETIMEDOUT)
break;
dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
}
mutex_unlock(&hba->dev_cmd.lock);
ufshcd_release(hba);
if (err)
dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
return err;
}
/**
* ufshcd_set_queue_depth - set lun queue depth
* @sdev: pointer to SCSI device
*
* Read bLUQueueDepth value and activate scsi tagged command
* queueing. For WLUN, queue depth is set to 1. For best-effort
* cases (bLUQueueDepth = 0) the queue depth is set to a maximum
* value that host can queue.
*/
static void ufshcd_set_queue_depth(struct scsi_device *sdev)
{
int ret = 0;
u8 lun_qdepth;
struct ufs_hba *hba;
hba = shost_priv(sdev->host);
lun_qdepth = hba->nutrs;
ret = ufshcd_read_unit_desc_param(hba,
ufshcd_scsi_to_upiu_lun(sdev->lun),
UNIT_DESC_PARAM_LU_Q_DEPTH,
&lun_qdepth,
sizeof(lun_qdepth));
/* Some WLUN doesn't support unit descriptor */
if (ret == -EOPNOTSUPP)
lun_qdepth = 1;
else if (!lun_qdepth)
/* eventually, we can figure out the real queue depth */
lun_qdepth = hba->nutrs;
else
lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
__func__, lun_qdepth);
scsi_change_queue_depth(sdev, lun_qdepth);
}
/*
* ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
* @hba: per-adapter instance
* @lun: UFS device lun id
* @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
*
* Returns 0 in case of success and b_lu_write_protect status would be returned
* @b_lu_write_protect parameter.
* Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
* Returns -EINVAL in case of invalid parameters passed to this function.
*/
static int ufshcd_get_lu_wp(struct ufs_hba *hba,
u8 lun,
u8 *b_lu_write_protect)
{
int ret;
if (!b_lu_write_protect)
ret = -EINVAL;
/*
* According to UFS device spec, RPMB LU can't be write
* protected so skip reading bLUWriteProtect parameter for
* it. For other W-LUs, UNIT DESCRIPTOR is not available.
*/
else if (lun >= UFS_UPIU_MAX_GENERAL_LUN)
ret = -ENOTSUPP;
else
ret = ufshcd_read_unit_desc_param(hba,
lun,
UNIT_DESC_PARAM_LU_WR_PROTECT,
b_lu_write_protect,
sizeof(*b_lu_write_protect));
return ret;
}
/**
* ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
* status
* @hba: per-adapter instance
* @sdev: pointer to SCSI device
*
*/
static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
struct scsi_device *sdev)
{
if (hba->dev_info.f_power_on_wp_en &&
!hba->dev_info.is_lu_power_on_wp) {
u8 b_lu_write_protect;
if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
&b_lu_write_protect) &&
(b_lu_write_protect == UFS_LU_POWER_ON_WP))
hba->dev_info.is_lu_power_on_wp = true;
}
}
/**
* ufshcd_slave_alloc - handle initial SCSI device configurations
* @sdev: pointer to SCSI device
*
* Returns success
*/
static int ufshcd_slave_alloc(struct scsi_device *sdev)
{
struct ufs_hba *hba;
hba = shost_priv(sdev->host);
/* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
sdev->use_10_for_ms = 1;
/* allow SCSI layer to restart the device in case of errors */
sdev->allow_restart = 1;
/* REPORT SUPPORTED OPERATION CODES is not supported */
sdev->no_report_opcodes = 1;
ufshcd_set_queue_depth(sdev);
ufshcd_get_lu_power_on_wp_status(hba, sdev);
return 0;
}
/**
* ufshcd_change_queue_depth - change queue depth
* @sdev: pointer to SCSI device
* @depth: required depth to set
*
* Change queue depth and make sure the max. limits are not crossed.
*/
static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
{
struct ufs_hba *hba = shost_priv(sdev->host);
if (depth > hba->nutrs)
depth = hba->nutrs;
return scsi_change_queue_depth(sdev, depth);
}
/**
* ufshcd_slave_configure - adjust SCSI device configurations
* @sdev: pointer to SCSI device
*/
static int ufshcd_slave_configure(struct scsi_device *sdev)
{
struct request_queue *q = sdev->request_queue;
blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
blk_queue_max_segment_size(q, PRDT_DATA_BYTE_COUNT_MAX);
return 0;
}
/**
* ufshcd_slave_destroy - remove SCSI device configurations
* @sdev: pointer to SCSI device
*/
static void ufshcd_slave_destroy(struct scsi_device *sdev)
{
struct ufs_hba *hba;
hba = shost_priv(sdev->host);
/* Drop the reference as it won't be needed anymore */
if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
unsigned long flags;
spin_lock_irqsave(hba->host->host_lock, flags);
hba->sdev_ufs_device = NULL;
spin_unlock_irqrestore(hba->host->host_lock, flags);
}
}
/**
* ufshcd_task_req_compl - handle task management request completion
* @hba: per adapter instance
* @index: index of the completed request
* @resp: task management service response
*
* Returns non-zero value on error, zero on success
*/
static int ufshcd_task_req_compl(struct ufs_hba *hba, u32 index, u8 *resp)
{
struct utp_task_req_desc *task_req_descp;
struct utp_upiu_task_rsp *task_rsp_upiup;
unsigned long flags;
int ocs_value;
int task_result;
spin_lock_irqsave(hba->host->host_lock, flags);
/* Clear completed tasks from outstanding_tasks */
__clear_bit(index, &hba->outstanding_tasks);
task_req_descp = hba->utmrdl_base_addr;
ocs_value = ufshcd_get_tmr_ocs(&task_req_descp[index]);
if (ocs_value == OCS_SUCCESS) {
task_rsp_upiup = (struct utp_upiu_task_rsp *)
task_req_descp[index].task_rsp_upiu;
task_result = be32_to_cpu(task_rsp_upiup->header.dword_1);
task_result = ((task_result & MASK_TASK_RESPONSE) >> 8);
if (resp)
*resp = (u8)task_result;
} else {
dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
__func__, ocs_value);
}
spin_unlock_irqrestore(hba->host->host_lock, flags);
return ocs_value;
}
/**
* ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
* @lrb: pointer to local reference block of completed command
* @scsi_status: SCSI command status
*
* Returns value base on SCSI command status
*/
static inline int
ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
{
int result = 0;
switch (scsi_status) {
case SAM_STAT_CHECK_CONDITION:
ufshcd_copy_sense_data(lrbp);
case SAM_STAT_GOOD:
result |= DID_OK << 16 |
COMMAND_COMPLETE << 8 |
scsi_status;
break;
case SAM_STAT_TASK_SET_FULL:
case SAM_STAT_BUSY:
case SAM_STAT_TASK_ABORTED:
ufshcd_copy_sense_data(lrbp);
result |= scsi_status;
break;
default:
result |= DID_ERROR << 16;
break;
} /* end of switch */
return result;
}
/**
* ufshcd_transfer_rsp_status - Get overall status of the response
* @hba: per adapter instance
* @lrb: pointer to local reference block of completed command
*
* Returns result of the command to notify SCSI midlayer
*/
static inline int
ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
{
int result = 0;
int scsi_status;
int ocs;
/* overall command status of utrd */
ocs = ufshcd_get_tr_ocs(lrbp);
switch (ocs) {
case OCS_SUCCESS:
result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
switch (result) {
case UPIU_TRANSACTION_RESPONSE:
/*
* get the response UPIU result to extract
* the SCSI command status
*/
result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
/*
* get the result based on SCSI status response
* to notify the SCSI midlayer of the command status
*/
scsi_status = result & MASK_SCSI_STATUS;
result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
/*
* Currently we are only supporting BKOPs exception
* events hence we can ignore BKOPs exception event
* during power management callbacks. BKOPs exception
* event is not expected to be raised in runtime suspend
* callback as it allows the urgent bkops.
* During system suspend, we are anyway forcefully
* disabling the bkops and if urgent bkops is needed
* it will be enabled on system resume. Long term
* solution could be to abort the system suspend if
* UFS device needs urgent BKOPs.
*/
if (!hba->pm_op_in_progress &&
ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
schedule_work(&hba->eeh_work);
break;
case UPIU_TRANSACTION_REJECT_UPIU:
/* TODO: handle Reject UPIU Response */
result = DID_ERROR << 16;
dev_err(hba->dev,
"Reject UPIU not fully implemented\n");
break;
default:
result = DID_ERROR << 16;
dev_err(hba->dev,
"Unexpected request response code = %x\n",
result);
break;
}
break;
case OCS_ABORTED:
result |= DID_ABORT << 16;
break;
case OCS_INVALID_COMMAND_STATUS:
result |= DID_REQUEUE << 16;
break;
case OCS_INVALID_CMD_TABLE_ATTR:
case OCS_INVALID_PRDT_ATTR:
case OCS_MISMATCH_DATA_BUF_SIZE:
case OCS_MISMATCH_RESP_UPIU_SIZE:
case OCS_PEER_COMM_FAILURE:
case OCS_FATAL_ERROR:
default:
result |= DID_ERROR << 16;
dev_err(hba->dev,
"OCS error from controller = %x\n", ocs);
break;
} /* end of switch */
return result;
}
/**
* ufshcd_uic_cmd_compl - handle completion of uic command
* @hba: per adapter instance
* @intr_status: interrupt status generated by the controller
*/
static void ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
{
if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
hba->active_uic_cmd->argument2 |=
ufshcd_get_uic_cmd_result(hba);
hba->active_uic_cmd->argument3 =
ufshcd_get_dme_attr_val(hba);
complete(&hba->active_uic_cmd->done);
}
if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done)
complete(hba->uic_async_done);
}
/**
* __ufshcd_transfer_req_compl - handle SCSI and query command completion
* @hba: per adapter instance
* @completed_reqs: requests to complete
*/
static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
unsigned long completed_reqs)
{
struct ufshcd_lrb *lrbp;
struct scsi_cmnd *cmd;
int result;
int index;
for_each_set_bit(index, &completed_reqs, hba->nutrs) {
lrbp = &hba->lrb[index];
cmd = lrbp->cmd;
if (cmd) {
result = ufshcd_transfer_rsp_status(hba, lrbp);
scsi_dma_unmap(cmd);
cmd->result = result;
/* Mark completed command as NULL in LRB */
lrbp->cmd = NULL;
clear_bit_unlock(index, &hba->lrb_in_use);
/* Do not touch lrbp after scsi done */
cmd->scsi_done(cmd);
__ufshcd_release(hba);
} else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE) {
if (hba->dev_cmd.complete)
complete(hba->dev_cmd.complete);
}
}
/* clear corresponding bits of completed commands */
hba->outstanding_reqs ^= completed_reqs;
ufshcd_clk_scaling_update_busy(hba);
/* we might have free'd some tags above */
wake_up(&hba->dev_cmd.tag_wq);
}
/**
* ufshcd_transfer_req_compl - handle SCSI and query command completion
* @hba: per adapter instance
*/
static void ufshcd_transfer_req_compl(struct ufs_hba *hba)
{
unsigned long completed_reqs;
u32 tr_doorbell;
/* Resetting interrupt aggregation counters first and reading the
* DOOR_BELL afterward allows us to handle all the completed requests.
* In order to prevent other interrupts starvation the DB is read once
* after reset. The down side of this solution is the possibility of
* false interrupt if device completes another request after resetting
* aggregation and before reading the DB.
*/
if (ufshcd_is_intr_aggr_allowed(hba))
ufshcd_reset_intr_aggr(hba);
tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
completed_reqs = tr_doorbell ^ hba->outstanding_reqs;
__ufshcd_transfer_req_compl(hba, completed_reqs);
}
/**
* ufshcd_disable_ee - disable exception event
* @hba: per-adapter instance
* @mask: exception event to disable
*
* Disables exception event in the device so that the EVENT_ALERT
* bit is not set.
*
* Returns zero on success, non-zero error value on failure.
*/
static int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
{
int err = 0;
u32 val;
if (!(hba->ee_ctrl_mask & mask))
goto out;
val = hba->ee_ctrl_mask & ~mask;
val &= 0xFFFF; /* 2 bytes */
err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
if (!err)
hba->ee_ctrl_mask &= ~mask;
out:
return err;
}
/**
* ufshcd_enable_ee - enable exception event
* @hba: per-adapter instance
* @mask: exception event to enable
*
* Enable corresponding exception event in the device to allow
* device to alert host in critical scenarios.
*
* Returns zero on success, non-zero error value on failure.
*/
static int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
{
int err = 0;
u32 val;
if (hba->ee_ctrl_mask & mask)
goto out;
val = hba->ee_ctrl_mask | mask;
val &= 0xFFFF; /* 2 bytes */
err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
if (!err)
hba->ee_ctrl_mask |= mask;
out:
return err;
}
/**
* ufshcd_enable_auto_bkops - Allow device managed BKOPS
* @hba: per-adapter instance
*
* Allow device to manage background operations on its own. Enabling
* this might lead to inconsistent latencies during normal data transfers
* as the device is allowed to manage its own way of handling background
* operations.
*
* Returns zero on success, non-zero on failure.
*/
static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
{
int err = 0;
if (hba->auto_bkops_enabled)
goto out;
err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
QUERY_FLAG_IDN_BKOPS_EN, NULL);
if (err) {
dev_err(hba->dev, "%s: failed to enable bkops %d\n",
__func__, err);
goto out;
}
hba->auto_bkops_enabled = true;
/* No need of URGENT_BKOPS exception from the device */
err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
if (err)
dev_err(hba->dev, "%s: failed to disable exception event %d\n",
__func__, err);
out:
return err;
}
/**
* ufshcd_disable_auto_bkops - block device in doing background operations
* @hba: per-adapter instance
*
* Disabling background operations improves command response latency but
* has drawback of device moving into critical state where the device is
* not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
* host is idle so that BKOPS are managed effectively without any negative
* impacts.
*
* Returns zero on success, non-zero on failure.
*/
static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
{
int err = 0;
if (!hba->auto_bkops_enabled)
goto out;
/*
* If host assisted BKOPs is to be enabled, make sure
* urgent bkops exception is allowed.
*/
err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
if (err) {
dev_err(hba->dev, "%s: failed to enable exception event %d\n",
__func__, err);
goto out;
}
err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
QUERY_FLAG_IDN_BKOPS_EN, NULL);
if (err) {
dev_err(hba->dev, "%s: failed to disable bkops %d\n",
__func__, err);
ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
goto out;
}
hba->auto_bkops_enabled = false;
out:
return err;
}
/**
* ufshcd_force_reset_auto_bkops - force enable of auto bkops
* @hba: per adapter instance
*
* After a device reset the device may toggle the BKOPS_EN flag
* to default value. The s/w tracking variables should be updated
* as well. Do this by forcing enable of auto bkops.
*/
static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
{
hba->auto_bkops_enabled = false;
hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
ufshcd_enable_auto_bkops(hba);
}
static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
{
return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
}
/**
* ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
* @hba: per-adapter instance
* @status: bkops_status value
*
* Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
* flag in the device to permit background operations if the device
* bkops_status is greater than or equal to "status" argument passed to
* this function, disable otherwise.
*
* Returns 0 for success, non-zero in case of failure.
*
* NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
* to know whether auto bkops is enabled or disabled after this function
* returns control to it.
*/
static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
enum bkops_status status)
{
int err;
u32 curr_status = 0;
err = ufshcd_get_bkops_status(hba, &curr_status);
if (err) {
dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
__func__, err);
goto out;
} else if (curr_status > BKOPS_STATUS_MAX) {
dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
__func__, curr_status);
err = -EINVAL;
goto out;
}
if (curr_status >= status)
err = ufshcd_enable_auto_bkops(hba);
else
err = ufshcd_disable_auto_bkops(hba);
out:
return err;
}
/**
* ufshcd_urgent_bkops - handle urgent bkops exception event
* @hba: per-adapter instance
*
* Enable fBackgroundOpsEn flag in the device to permit background
* operations.
*
* If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
* and negative error value for any other failure.
*/
static int ufshcd_urgent_bkops(struct ufs_hba *hba)
{
return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
}
static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
{
return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
}
static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
{
int err;
u32 curr_status = 0;
if (hba->is_urgent_bkops_lvl_checked)
goto enable_auto_bkops;
err = ufshcd_get_bkops_status(hba, &curr_status);
if (err) {
dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
__func__, err);
goto out;
}
/*
* We are seeing that some devices are raising the urgent bkops
* exception events even when BKOPS status doesn't indicate performace
* impacted or critical. Handle these device by determining their urgent
* bkops status at runtime.
*/
if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
__func__, curr_status);
/* update the current status as the urgent bkops level */
hba->urgent_bkops_lvl = curr_status;
hba->is_urgent_bkops_lvl_checked = true;
}
enable_auto_bkops:
err = ufshcd_enable_auto_bkops(hba);
out:
if (err < 0)
dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
__func__, err);
}
/**
* ufshcd_exception_event_handler - handle exceptions raised by device
* @work: pointer to work data
*
* Read bExceptionEventStatus attribute from the device and handle the
* exception event accordingly.
*/
static void ufshcd_exception_event_handler(struct work_struct *work)
{
struct ufs_hba *hba;
int err;
u32 status = 0;
hba = container_of(work, struct ufs_hba, eeh_work);
pm_runtime_get_sync(hba->dev);
err = ufshcd_get_ee_status(hba, &status);
if (err) {
dev_err(hba->dev, "%s: failed to get exception status %d\n",
__func__, err);
goto out;
}
status &= hba->ee_ctrl_mask;
if (status & MASK_EE_URGENT_BKOPS)
ufshcd_bkops_exception_event_handler(hba);
out:
pm_runtime_put_sync(hba->dev);
return;
}
/* Complete requests that have door-bell cleared */
static void ufshcd_complete_requests(struct ufs_hba *hba)
{
ufshcd_transfer_req_compl(hba);
ufshcd_tmc_handler(hba);
}
/**
* ufshcd_quirk_dl_nac_errors - This function checks if error handling is
* to recover from the DL NAC errors or not.
* @hba: per-adapter instance
*
* Returns true if error handling is required, false otherwise
*/
static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
{
unsigned long flags;
bool err_handling = true;
spin_lock_irqsave(hba->host->host_lock, flags);
/*
* UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
* device fatal error and/or DL NAC & REPLAY timeout errors.
*/
if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
goto out;
if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
((hba->saved_err & UIC_ERROR) &&
(hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
goto out;
if ((hba->saved_err & UIC_ERROR) &&
(hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
int err;
/*
* wait for 50ms to see if we can get any other errors or not.
*/
spin_unlock_irqrestore(hba->host->host_lock, flags);
msleep(50);
spin_lock_irqsave(hba->host->host_lock, flags);
/*
* now check if we have got any other severe errors other than
* DL NAC error?
*/
if ((hba->saved_err & INT_FATAL_ERRORS) ||
((hba->saved_err & UIC_ERROR) &&
(hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
goto out;
/*
* As DL NAC is the only error received so far, send out NOP
* command to confirm if link is still active or not.
* - If we don't get any response then do error recovery.
* - If we get response then clear the DL NAC error bit.
*/
spin_unlock_irqrestore(hba->host->host_lock, flags);
err = ufshcd_verify_dev_init(hba);
spin_lock_irqsave(hba->host->host_lock, flags);
if (err)
goto out;
/* Link seems to be alive hence ignore the DL NAC errors */
if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
hba->saved_err &= ~UIC_ERROR;
/* clear NAC error */
hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
if (!hba->saved_uic_err) {
err_handling = false;
goto out;
}
}
out:
spin_unlock_irqrestore(hba->host->host_lock, flags);
return err_handling;
}
/**
* ufshcd_err_handler - handle UFS errors that require s/w attention
* @work: pointer to work structure
*/
static void ufshcd_err_handler(struct work_struct *work)
{
struct ufs_hba *hba;
unsigned long flags;
u32 err_xfer = 0;
u32 err_tm = 0;
int err = 0;
int tag;
bool needs_reset = false;
hba = container_of(work, struct ufs_hba, eh_work);
pm_runtime_get_sync(hba->dev);
ufshcd_hold(hba, false);
spin_lock_irqsave(hba->host->host_lock, flags);
if (hba->ufshcd_state == UFSHCD_STATE_RESET)
goto out;
hba->ufshcd_state = UFSHCD_STATE_RESET;
ufshcd_set_eh_in_progress(hba);
/* Complete requests that have door-bell cleared by h/w */
ufshcd_complete_requests(hba);
if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
bool ret;
spin_unlock_irqrestore(hba->host->host_lock, flags);
/* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
ret = ufshcd_quirk_dl_nac_errors(hba);
spin_lock_irqsave(hba->host->host_lock, flags);
if (!ret)
goto skip_err_handling;
}
if ((hba->saved_err & INT_FATAL_ERRORS) ||
((hba->saved_err & UIC_ERROR) &&
(hba->saved_uic_err & (UFSHCD_UIC_DL_PA_INIT_ERROR |
UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
UFSHCD_UIC_DL_TCx_REPLAY_ERROR))))
needs_reset = true;
/*
* if host reset is required then skip clearing the pending
* transfers forcefully because they will automatically get
* cleared after link startup.
*/
if (needs_reset)
goto skip_pending_xfer_clear;
/* release lock as clear command might sleep */
spin_unlock_irqrestore(hba->host->host_lock, flags);
/* Clear pending transfer requests */
for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
if (ufshcd_clear_cmd(hba, tag)) {
err_xfer = true;
goto lock_skip_pending_xfer_clear;
}
}
/* Clear pending task management requests */
for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
if (ufshcd_clear_tm_cmd(hba, tag)) {
err_tm = true;
goto lock_skip_pending_xfer_clear;
}
}
lock_skip_pending_xfer_clear:
spin_lock_irqsave(hba->host->host_lock, flags);
/* Complete the requests that are cleared by s/w */
ufshcd_complete_requests(hba);
if (err_xfer || err_tm)
needs_reset = true;
skip_pending_xfer_clear:
/* Fatal errors need reset */
if (needs_reset) {
unsigned long max_doorbells = (1UL << hba->nutrs) - 1;
/*
* ufshcd_reset_and_restore() does the link reinitialization
* which will need atleast one empty doorbell slot to send the
* device management commands (NOP and query commands).
* If there is no slot empty at this moment then free up last
* slot forcefully.
*/
if (hba->outstanding_reqs == max_doorbells)
__ufshcd_transfer_req_compl(hba,
(1UL << (hba->nutrs - 1)));
spin_unlock_irqrestore(hba->host->host_lock, flags);
err = ufshcd_reset_and_restore(hba);
spin_lock_irqsave(hba->host->host_lock, flags);
if (err) {
dev_err(hba->dev, "%s: reset and restore failed\n",
__func__);
hba->ufshcd_state = UFSHCD_STATE_ERROR;
}
/*
* Inform scsi mid-layer that we did reset and allow to handle
* Unit Attention properly.
*/
scsi_report_bus_reset(hba->host, 0);
hba->saved_err = 0;
hba->saved_uic_err = 0;
}
skip_err_handling:
if (!needs_reset) {
hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
if (hba->saved_err || hba->saved_uic_err)
dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
__func__, hba->saved_err, hba->saved_uic_err);
}
ufshcd_clear_eh_in_progress(hba);
out:
spin_unlock_irqrestore(hba->host->host_lock, flags);
scsi_unblock_requests(hba->host);
ufshcd_release(hba);
pm_runtime_put_sync(hba->dev);
}
/**
* ufshcd_update_uic_error - check and set fatal UIC error flags.
* @hba: per-adapter instance
*/
static void ufshcd_update_uic_error(struct ufs_hba *hba)
{
u32 reg;
/* PA_INIT_ERROR is fatal and needs UIC reset */
reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
else if (hba->dev_quirks &
UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
hba->uic_error |=
UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
}
/* UIC NL/TL/DME errors needs software retry */
reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
if (reg)
hba->uic_error |= UFSHCD_UIC_NL_ERROR;
reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
if (reg)
hba->uic_error |= UFSHCD_UIC_TL_ERROR;
reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
if (reg)
hba->uic_error |= UFSHCD_UIC_DME_ERROR;
dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
__func__, hba->uic_error);
}
/**
* ufshcd_check_errors - Check for errors that need s/w attention
* @hba: per-adapter instance
*/
static void ufshcd_check_errors(struct ufs_hba *hba)
{
bool queue_eh_work = false;
if (hba->errors & INT_FATAL_ERRORS)
queue_eh_work = true;
if (hba->errors & UIC_ERROR) {
hba->uic_error = 0;
ufshcd_update_uic_error(hba);
if (hba->uic_error)
queue_eh_work = true;
}
if (queue_eh_work) {
/*
* update the transfer error masks to sticky bits, let's do this
* irrespective of current ufshcd_state.
*/
hba->saved_err |= hba->errors;
hba->saved_uic_err |= hba->uic_error;
/* handle fatal errors only when link is functional */
if (hba->ufshcd_state == UFSHCD_STATE_OPERATIONAL) {
/* block commands from scsi mid-layer */
scsi_block_requests(hba->host);
hba->ufshcd_state = UFSHCD_STATE_ERROR;
schedule_work(&hba->eh_work);
}
}
/*
* if (!queue_eh_work) -
* Other errors are either non-fatal where host recovers
* itself without s/w intervention or errors that will be
* handled by the SCSI core layer.
*/
}
/**
* ufshcd_tmc_handler - handle task management function completion
* @hba: per adapter instance
*/
static void ufshcd_tmc_handler(struct ufs_hba *hba)
{
u32 tm_doorbell;
tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
hba->tm_condition = tm_doorbell ^ hba->outstanding_tasks;
wake_up(&hba->tm_wq);
}
/**
* ufshcd_sl_intr - Interrupt service routine
* @hba: per adapter instance
* @intr_status: contains interrupts generated by the controller
*/
static void ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
{
hba->errors = UFSHCD_ERROR_MASK & intr_status;
if (hba->errors)
ufshcd_check_errors(hba);
if (intr_status & UFSHCD_UIC_MASK)
ufshcd_uic_cmd_compl(hba, intr_status);
if (intr_status & UTP_TASK_REQ_COMPL)
ufshcd_tmc_handler(hba);
if (intr_status & UTP_TRANSFER_REQ_COMPL)
ufshcd_transfer_req_compl(hba);
}
/**
* ufshcd_intr - Main interrupt service routine
* @irq: irq number
* @__hba: pointer to adapter instance
*
* Returns IRQ_HANDLED - If interrupt is valid
* IRQ_NONE - If invalid interrupt
*/
static irqreturn_t ufshcd_intr(int irq, void *__hba)
{
u32 intr_status, enabled_intr_status;
irqreturn_t retval = IRQ_NONE;
struct ufs_hba *hba = __hba;
spin_lock(hba->host->host_lock);
intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
enabled_intr_status =
intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
if (intr_status)
ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
if (enabled_intr_status) {
ufshcd_sl_intr(hba, enabled_intr_status);
retval = IRQ_HANDLED;
}
spin_unlock(hba->host->host_lock);
return retval;
}
static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
{
int err = 0;
u32 mask = 1 << tag;
unsigned long flags;
if (!test_bit(tag, &hba->outstanding_tasks))
goto out;
spin_lock_irqsave(hba->host->host_lock, flags);
ufshcd_writel(hba, ~(1 << tag), REG_UTP_TASK_REQ_LIST_CLEAR);
spin_unlock_irqrestore(hba->host->host_lock, flags);
/* poll for max. 1 sec to clear door bell register by h/w */
err = ufshcd_wait_for_register(hba,
REG_UTP_TASK_REQ_DOOR_BELL,
mask, 0, 1000, 1000, true);
out:
return err;
}
/**
* ufshcd_issue_tm_cmd - issues task management commands to controller
* @hba: per adapter instance
* @lun_id: LUN ID to which TM command is sent
* @task_id: task ID to which the TM command is applicable
* @tm_function: task management function opcode
* @tm_response: task management service response return value
*
* Returns non-zero value on error, zero on success.
*/
static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
u8 tm_function, u8 *tm_response)
{
struct utp_task_req_desc *task_req_descp;
struct utp_upiu_task_req *task_req_upiup;
struct Scsi_Host *host;
unsigned long flags;
int free_slot;
int err;
int task_tag;
host = hba->host;
/*
* Get free slot, sleep if slots are unavailable.
* Even though we use wait_event() which sleeps indefinitely,
* the maximum wait time is bounded by %TM_CMD_TIMEOUT.
*/
wait_event(hba->tm_tag_wq, ufshcd_get_tm_free_slot(hba, &free_slot));
ufshcd_hold(hba, false);
spin_lock_irqsave(host->host_lock, flags);
task_req_descp = hba->utmrdl_base_addr;
task_req_descp += free_slot;
/* Configure task request descriptor */
task_req_descp->header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
task_req_descp->header.dword_2 =
cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
/* Configure task request UPIU */
task_req_upiup =
(struct utp_upiu_task_req *) task_req_descp->task_req_upiu;
task_tag = hba->nutrs + free_slot;
task_req_upiup->header.dword_0 =
UPIU_HEADER_DWORD(UPIU_TRANSACTION_TASK_REQ, 0,
lun_id, task_tag);
task_req_upiup->header.dword_1 =
UPIU_HEADER_DWORD(0, tm_function, 0, 0);
/*
* The host shall provide the same value for LUN field in the basic
* header and for Input Parameter.
*/
task_req_upiup->input_param1 = cpu_to_be32(lun_id);
task_req_upiup->input_param2 = cpu_to_be32(task_id);
/* send command to the controller */
__set_bit(free_slot, &hba->outstanding_tasks);
/* Make sure descriptors are ready before ringing the task doorbell */
wmb();
ufshcd_writel(hba, 1 << free_slot, REG_UTP_TASK_REQ_DOOR_BELL);
spin_unlock_irqrestore(host->host_lock, flags);
/* wait until the task management command is completed */
err = wait_event_timeout(hba->tm_wq,
test_bit(free_slot, &hba->tm_condition),
msecs_to_jiffies(TM_CMD_TIMEOUT));
if (!err) {
dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
__func__, tm_function);
if (ufshcd_clear_tm_cmd(hba, free_slot))
dev_WARN(hba->dev, "%s: unable clear tm cmd (slot %d) after timeout\n",
__func__, free_slot);
err = -ETIMEDOUT;
} else {
err = ufshcd_task_req_compl(hba, free_slot, tm_response);
}
clear_bit(free_slot, &hba->tm_condition);
ufshcd_put_tm_slot(hba, free_slot);
wake_up(&hba->tm_tag_wq);
ufshcd_release(hba);
return err;
}
/**
* ufshcd_eh_device_reset_handler - device reset handler registered to
* scsi layer.
* @cmd: SCSI command pointer
*
* Returns SUCCESS/FAILED
*/
static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
{
struct Scsi_Host *host;
struct ufs_hba *hba;
unsigned int tag;
u32 pos;
int err;
u8 resp = 0xF;
struct ufshcd_lrb *lrbp;
unsigned long flags;
host = cmd->device->host;
hba = shost_priv(host);
tag = cmd->request->tag;
lrbp = &hba->lrb[tag];
err = ufshcd_issue_tm_cmd(hba, lrbp->lun, 0, UFS_LOGICAL_RESET, &resp);
if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
if (!err)
err = resp;
goto out;
}
/* clear the commands that were pending for corresponding LUN */
for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
if (hba->lrb[pos].lun == lrbp->lun) {
err = ufshcd_clear_cmd(hba, pos);
if (err)
break;
}
}
spin_lock_irqsave(host->host_lock, flags);
ufshcd_transfer_req_compl(hba);
spin_unlock_irqrestore(host->host_lock, flags);
out:
if (!err) {
err = SUCCESS;
} else {
dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
err = FAILED;
}
return err;
}
/**
* ufshcd_abort - abort a specific command
* @cmd: SCSI command pointer
*
* Abort the pending command in device by sending UFS_ABORT_TASK task management
* command, and in host controller by clearing the door-bell register. There can
* be race between controller sending the command to the device while abort is
* issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
* really issued and then try to abort it.
*
* Returns SUCCESS/FAILED
*/
static int ufshcd_abort(struct scsi_cmnd *cmd)
{
struct Scsi_Host *host;
struct ufs_hba *hba;
unsigned long flags;
unsigned int tag;
int err = 0;
int poll_cnt;
u8 resp = 0xF;
struct ufshcd_lrb *lrbp;
u32 reg;
host = cmd->device->host;
hba = shost_priv(host);
tag = cmd->request->tag;
if (!ufshcd_valid_tag(hba, tag)) {
dev_err(hba->dev,
"%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
__func__, tag, cmd, cmd->request);
BUG();
}
ufshcd_hold(hba, false);
reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
/* If command is already aborted/completed, return SUCCESS */
if (!(test_bit(tag, &hba->outstanding_reqs))) {
dev_err(hba->dev,
"%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
__func__, tag, hba->outstanding_reqs, reg);
goto out;
}
if (!(reg & (1 << tag))) {
dev_err(hba->dev,
"%s: cmd was completed, but without a notifying intr, tag = %d",
__func__, tag);
}
lrbp = &hba->lrb[tag];
for (poll_cnt = 100; poll_cnt; poll_cnt--) {
err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
UFS_QUERY_TASK, &resp);
if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
/* cmd pending in the device */
break;
} else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
/*
* cmd not pending in the device, check if it is
* in transition.
*/
reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
if (reg & (1 << tag)) {
/* sleep for max. 200us to stabilize */
usleep_range(100, 200);
continue;
}
/* command completed already */
goto out;
} else {
if (!err)
err = resp; /* service response error */
goto out;
}
}
if (!poll_cnt) {
err = -EBUSY;
goto out;
}
err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
UFS_ABORT_TASK, &resp);
if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
if (!err)
err = resp; /* service response error */
goto out;
}
err = ufshcd_clear_cmd(hba, tag);
if (err)
goto out;
scsi_dma_unmap(cmd);
spin_lock_irqsave(host->host_lock, flags);
ufshcd_outstanding_req_clear(hba, tag);
hba->lrb[tag].cmd = NULL;
spin_unlock_irqrestore(host->host_lock, flags);
clear_bit_unlock(tag, &hba->lrb_in_use);
wake_up(&hba->dev_cmd.tag_wq);
out:
if (!err) {
err = SUCCESS;
} else {
dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
err = FAILED;
}
/*
* This ufshcd_release() corresponds to the original scsi cmd that got
* aborted here (as we won't get any IRQ for it).
*/
ufshcd_release(hba);
return err;
}
/**
* ufshcd_host_reset_and_restore - reset and restore host controller
* @hba: per-adapter instance
*
* Note that host controller reset may issue DME_RESET to
* local and remote (device) Uni-Pro stack and the attributes
* are reset to default state.
*
* Returns zero on success, non-zero on failure
*/
static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
{
int err;
unsigned long flags;
/* Reset the host controller */
spin_lock_irqsave(hba->host->host_lock, flags);
ufshcd_hba_stop(hba, false);
spin_unlock_irqrestore(hba->host->host_lock, flags);
err = ufshcd_hba_enable(hba);
if (err)
goto out;
/* Establish the link again and restore the device */
err = ufshcd_probe_hba(hba);
if (!err && (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL))
err = -EIO;
out:
if (err)
dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
return err;
}
/**
* ufshcd_reset_and_restore - reset and re-initialize host/device
* @hba: per-adapter instance
*
* Reset and recover device, host and re-establish link. This
* is helpful to recover the communication in fatal error conditions.
*
* Returns zero on success, non-zero on failure
*/
static int ufshcd_reset_and_restore(struct ufs_hba *hba)
{
int err = 0;
unsigned long flags;
int retries = MAX_HOST_RESET_RETRIES;
do {
err = ufshcd_host_reset_and_restore(hba);
} while (err && --retries);
/*
* After reset the door-bell might be cleared, complete
* outstanding requests in s/w here.
*/
spin_lock_irqsave(hba->host->host_lock, flags);
ufshcd_transfer_req_compl(hba);
ufshcd_tmc_handler(hba);
spin_unlock_irqrestore(hba->host->host_lock, flags);
return err;
}
/**
* ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
* @cmd - SCSI command pointer
*
* Returns SUCCESS/FAILED
*/
static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
{
int err;
unsigned long flags;
struct ufs_hba *hba;
hba = shost_priv(cmd->device->host);
ufshcd_hold(hba, false);
/*
* Check if there is any race with fatal error handling.
* If so, wait for it to complete. Even though fatal error
* handling does reset and restore in some cases, don't assume
* anything out of it. We are just avoiding race here.
*/
do {
spin_lock_irqsave(hba->host->host_lock, flags);
if (!(work_pending(&hba->eh_work) ||
hba->ufshcd_state == UFSHCD_STATE_RESET))
break;
spin_unlock_irqrestore(hba->host->host_lock, flags);
dev_dbg(hba->dev, "%s: reset in progress\n", __func__);
flush_work(&hba->eh_work);
} while (1);
hba->ufshcd_state = UFSHCD_STATE_RESET;
ufshcd_set_eh_in_progress(hba);
spin_unlock_irqrestore(hba->host->host_lock, flags);
err = ufshcd_reset_and_restore(hba);
spin_lock_irqsave(hba->host->host_lock, flags);
if (!err) {
err = SUCCESS;
hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
} else {
err = FAILED;
hba->ufshcd_state = UFSHCD_STATE_ERROR;
}
ufshcd_clear_eh_in_progress(hba);
spin_unlock_irqrestore(hba->host->host_lock, flags);
ufshcd_release(hba);
return err;
}
/**
* ufshcd_get_max_icc_level - calculate the ICC level
* @sup_curr_uA: max. current supported by the regulator
* @start_scan: row at the desc table to start scan from
* @buff: power descriptor buffer
*
* Returns calculated max ICC level for specific regulator
*/
static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
{
int i;
int curr_uA;
u16 data;
u16 unit;
for (i = start_scan; i >= 0; i--) {
data = be16_to_cpu(*((u16 *)(buff + 2*i)));
unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
ATTR_ICC_LVL_UNIT_OFFSET;
curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
switch (unit) {
case UFSHCD_NANO_AMP:
curr_uA = curr_uA / 1000;
break;
case UFSHCD_MILI_AMP:
curr_uA = curr_uA * 1000;
break;
case UFSHCD_AMP:
curr_uA = curr_uA * 1000 * 1000;
break;
case UFSHCD_MICRO_AMP:
default:
break;
}
if (sup_curr_uA >= curr_uA)
break;
}
if (i < 0) {
i = 0;
pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
}
return (u32)i;
}
/**
* ufshcd_calc_icc_level - calculate the max ICC level
* In case regulators are not initialized we'll return 0
* @hba: per-adapter instance
* @desc_buf: power descriptor buffer to extract ICC levels from.
* @len: length of desc_buff
*
* Returns calculated ICC level
*/
static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
u8 *desc_buf, int len)
{
u32 icc_level = 0;
if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
!hba->vreg_info.vccq2) {
dev_err(hba->dev,
"%s: Regulator capability was not set, actvIccLevel=%d",
__func__, icc_level);
goto out;
}
if (hba->vreg_info.vcc)
icc_level = ufshcd_get_max_icc_level(
hba->vreg_info.vcc->max_uA,
POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
&desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
if (hba->vreg_info.vccq)
icc_level = ufshcd_get_max_icc_level(
hba->vreg_info.vccq->max_uA,
icc_level,
&desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
if (hba->vreg_info.vccq2)
icc_level = ufshcd_get_max_icc_level(
hba->vreg_info.vccq2->max_uA,
icc_level,
&desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
out:
return icc_level;
}
static void ufshcd_init_icc_levels(struct ufs_hba *hba)
{
int ret;
int buff_len = QUERY_DESC_POWER_MAX_SIZE;
u8 desc_buf[QUERY_DESC_POWER_MAX_SIZE];
ret = ufshcd_read_power_desc(hba, desc_buf, buff_len);
if (ret) {
dev_err(hba->dev,
"%s: Failed reading power descriptor.len = %d ret = %d",
__func__, buff_len, ret);
return;
}
hba->init_prefetch_data.icc_level =
ufshcd_find_max_sup_active_icc_level(hba,
desc_buf, buff_len);
dev_dbg(hba->dev, "%s: setting icc_level 0x%x",
__func__, hba->init_prefetch_data.icc_level);
ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0,
&hba->init_prefetch_data.icc_level);
if (ret)
dev_err(hba->dev,
"%s: Failed configuring bActiveICCLevel = %d ret = %d",
__func__, hba->init_prefetch_data.icc_level , ret);
}
/**
* ufshcd_scsi_add_wlus - Adds required W-LUs
* @hba: per-adapter instance
*
* UFS device specification requires the UFS devices to support 4 well known
* logical units:
* "REPORT_LUNS" (address: 01h)
* "UFS Device" (address: 50h)
* "RPMB" (address: 44h)
* "BOOT" (address: 30h)
* UFS device's power management needs to be controlled by "POWER CONDITION"
* field of SSU (START STOP UNIT) command. But this "power condition" field
* will take effect only when its sent to "UFS device" well known logical unit
* hence we require the scsi_device instance to represent this logical unit in
* order for the UFS host driver to send the SSU command for power management.
* We also require the scsi_device instance for "RPMB" (Replay Protected Memory
* Block) LU so user space process can control this LU. User space may also
* want to have access to BOOT LU.
* This function adds scsi device instances for each of all well known LUs
* (except "REPORT LUNS" LU).
*
* Returns zero on success (all required W-LUs are added successfully),
* non-zero error value on failure (if failed to add any of the required W-LU).
*/
static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
{
int ret = 0;
struct scsi_device *sdev_rpmb;
struct scsi_device *sdev_boot;
hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
if (IS_ERR(hba->sdev_ufs_device)) {
ret = PTR_ERR(hba->sdev_ufs_device);
hba->sdev_ufs_device = NULL;
goto out;
}
scsi_device_put(hba->sdev_ufs_device);
sdev_boot = __scsi_add_device(hba->host, 0, 0,
ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
if (IS_ERR(sdev_boot)) {
ret = PTR_ERR(sdev_boot);
goto remove_sdev_ufs_device;
}
scsi_device_put(sdev_boot);
sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
if (IS_ERR(sdev_rpmb)) {
ret = PTR_ERR(sdev_rpmb);
goto remove_sdev_boot;
}
scsi_device_put(sdev_rpmb);
goto out;
remove_sdev_boot:
scsi_remove_device(sdev_boot);
remove_sdev_ufs_device:
scsi_remove_device(hba->sdev_ufs_device);
out:
return ret;
}
static int ufs_get_device_info(struct ufs_hba *hba,
struct ufs_device_info *card_data)
{
int err;
u8 model_index;
u8 str_desc_buf[QUERY_DESC_STRING_MAX_SIZE + 1] = {0};
u8 desc_buf[QUERY_DESC_DEVICE_MAX_SIZE];
err = ufshcd_read_device_desc(hba, desc_buf,
QUERY_DESC_DEVICE_MAX_SIZE);
if (err) {
dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
__func__, err);
goto out;
}
/*
* getting vendor (manufacturerID) and Bank Index in big endian
* format
*/
card_data->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
err = ufshcd_read_string_desc(hba, model_index, str_desc_buf,
QUERY_DESC_STRING_MAX_SIZE, ASCII_STD);
if (err) {
dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
__func__, err);
goto out;
}
str_desc_buf[QUERY_DESC_STRING_MAX_SIZE] = '\0';
strlcpy(card_data->model, (str_desc_buf + QUERY_DESC_HDR_SIZE),
min_t(u8, str_desc_buf[QUERY_DESC_LENGTH_OFFSET],
MAX_MODEL_LEN));
/* Null terminate the model string */
card_data->model[MAX_MODEL_LEN] = '\0';
out:
return err;
}
void ufs_advertise_fixup_device(struct ufs_hba *hba)
{
int err;
struct ufs_dev_fix *f;
struct ufs_device_info card_data;
card_data.wmanufacturerid = 0;
err = ufs_get_device_info(hba, &card_data);
if (err) {
dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
__func__, err);
return;
}
for (f = ufs_fixups; f->quirk; f++) {
if (((f->card.wmanufacturerid == card_data.wmanufacturerid) ||
(f->card.wmanufacturerid == UFS_ANY_VENDOR)) &&
(STR_PRFX_EQUAL(f->card.model, card_data.model) ||
!strcmp(f->card.model, UFS_ANY_MODEL)))
hba->dev_quirks |= f->quirk;
}
}
/**
* ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
* @hba: per-adapter instance
*
* PA_TActivate parameter can be tuned manually if UniPro version is less than
* 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
* RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
* the hibern8 exit latency.
*
* Returns zero on success, non-zero error value on failure.
*/
static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
{
int ret = 0;
u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
ret = ufshcd_dme_peer_get(hba,
UIC_ARG_MIB_SEL(
RX_MIN_ACTIVATETIME_CAPABILITY,
UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
&peer_rx_min_activatetime);
if (ret)
goto out;
/* make sure proper unit conversion is applied */
tuned_pa_tactivate =
((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
/ PA_TACTIVATE_TIME_UNIT_US);
ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
tuned_pa_tactivate);
out:
return ret;
}
/**
* ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
* @hba: per-adapter instance
*
* PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
* 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
* TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
* This optimal value can help reduce the hibern8 exit latency.
*
* Returns zero on success, non-zero error value on failure.
*/
static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
{
int ret = 0;
u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
u32 max_hibern8_time, tuned_pa_hibern8time;
ret = ufshcd_dme_get(hba,
UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
&local_tx_hibern8_time_cap);
if (ret)
goto out;
ret = ufshcd_dme_peer_get(hba,
UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
&peer_rx_hibern8_time_cap);
if (ret)
goto out;
max_hibern8_time = max(local_tx_hibern8_time_cap,
peer_rx_hibern8_time_cap);
/* make sure proper unit conversion is applied */
tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
/ PA_HIBERN8_TIME_UNIT_US);
ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
tuned_pa_hibern8time);
out:
return ret;
}
static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
{
if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
ufshcd_tune_pa_tactivate(hba);
ufshcd_tune_pa_hibern8time(hba);
}
if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
/* set 1ms timeout for PA_TACTIVATE */
ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
}
/**
* ufshcd_probe_hba - probe hba to detect device and initialize
* @hba: per-adapter instance
*
* Execute link-startup and verify device initialization
*/
static int ufshcd_probe_hba(struct ufs_hba *hba)
{
int ret;
ret = ufshcd_link_startup(hba);
if (ret)
goto out;
ufshcd_init_pwr_info(hba);
/* set the default level for urgent bkops */
hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
hba->is_urgent_bkops_lvl_checked = false;
/* UniPro link is active now */
ufshcd_set_link_active(hba);
ret = ufshcd_verify_dev_init(hba);
if (ret)
goto out;
ret = ufshcd_complete_dev_init(hba);
if (ret)
goto out;
ufs_advertise_fixup_device(hba);
ufshcd_tune_unipro_params(hba);
ret = ufshcd_set_vccq_rail_unused(hba,
(hba->dev_quirks & UFS_DEVICE_NO_VCCQ) ? true : false);
if (ret)
goto out;
/* UFS device is also active now */
ufshcd_set_ufs_dev_active(hba);
ufshcd_force_reset_auto_bkops(hba);
hba->wlun_dev_clr_ua = true;
if (ufshcd_get_max_pwr_mode(hba)) {
dev_err(hba->dev,
"%s: Failed getting max supported power mode\n",
__func__);
} else {
ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
if (ret)
dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
__func__, ret);
}
/* set the state as operational after switching to desired gear */
hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
/*
* If we are in error handling context or in power management callbacks
* context, no need to scan the host
*/
if (!ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
bool flag;
/* clear any previous UFS device information */
memset(&hba->dev_info, 0, sizeof(hba->dev_info));
if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
QUERY_FLAG_IDN_PWR_ON_WPE, &flag))
hba->dev_info.f_power_on_wp_en = flag;
if (!hba->is_init_prefetch)
ufshcd_init_icc_levels(hba);
/* Add required well known logical units to scsi mid layer */
if (ufshcd_scsi_add_wlus(hba))
goto out;
scsi_scan_host(hba->host);
pm_runtime_put_sync(hba->dev);
}
if (!hba->is_init_prefetch)
hba->is_init_prefetch = true;
/* Resume devfreq after UFS device is detected */
if (ufshcd_is_clkscaling_enabled(hba))
devfreq_resume_device(hba->devfreq);
out:
/*
* If we failed to initialize the device or the device is not
* present, turn off the power/clocks etc.
*/
if (ret && !ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
pm_runtime_put_sync(hba->dev);
ufshcd_hba_exit(hba);
}
return ret;
}
/**
* ufshcd_async_scan - asynchronous execution for probing hba
* @data: data pointer to pass to this function
* @cookie: cookie data
*/
static void ufshcd_async_scan(void *data, async_cookie_t cookie)
{
struct ufs_hba *hba = (struct ufs_hba *)data;
ufshcd_probe_hba(hba);
}
static enum blk_eh_timer_return ufshcd_eh_timed_out(struct scsi_cmnd *scmd)
{
unsigned long flags;
struct Scsi_Host *host;
struct ufs_hba *hba;
int index;
bool found = false;
if (!scmd || !scmd->device || !scmd->device->host)
return BLK_EH_NOT_HANDLED;
host = scmd->device->host;
hba = shost_priv(host);
if (!hba)
return BLK_EH_NOT_HANDLED;
spin_lock_irqsave(host->host_lock, flags);
for_each_set_bit(index, &hba->outstanding_reqs, hba->nutrs) {
if (hba->lrb[index].cmd == scmd) {
found = true;
break;
}
}
spin_unlock_irqrestore(host->host_lock, flags);
/*
* Bypass SCSI error handling and reset the block layer timer if this
* SCSI command was not actually dispatched to UFS driver, otherwise
* let SCSI layer handle the error as usual.
*/
return found ? BLK_EH_NOT_HANDLED : BLK_EH_RESET_TIMER;
}
static struct scsi_host_template ufshcd_driver_template = {
.module = THIS_MODULE,
.name = UFSHCD,
.proc_name = UFSHCD,
.queuecommand = ufshcd_queuecommand,
.slave_alloc = ufshcd_slave_alloc,
.slave_configure = ufshcd_slave_configure,
.slave_destroy = ufshcd_slave_destroy,
.change_queue_depth = ufshcd_change_queue_depth,
.eh_abort_handler = ufshcd_abort,
.eh_device_reset_handler = ufshcd_eh_device_reset_handler,
.eh_host_reset_handler = ufshcd_eh_host_reset_handler,
.eh_timed_out = ufshcd_eh_timed_out,
.this_id = -1,
.sg_tablesize = SG_ALL,
.cmd_per_lun = UFSHCD_CMD_PER_LUN,
.can_queue = UFSHCD_CAN_QUEUE,
.max_host_blocked = 1,
.track_queue_depth = 1,
};
static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
int ua)
{
int ret;
if (!vreg)
return 0;
ret = regulator_set_load(vreg->reg, ua);
if (ret < 0) {
dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
__func__, vreg->name, ua, ret);
}
return ret;
}
static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
struct ufs_vreg *vreg)
{
if (!vreg)
return 0;
else if (vreg->unused)
return 0;
else
return ufshcd_config_vreg_load(hba->dev, vreg,
UFS_VREG_LPM_LOAD_UA);
}
static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
struct ufs_vreg *vreg)
{
if (!vreg)
return 0;
else if (vreg->unused)
return 0;
else
return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
}
static int ufshcd_config_vreg(struct device *dev,
struct ufs_vreg *vreg, bool on)
{
int ret = 0;
struct regulator *reg = vreg->reg;
const char *name = vreg->name;
int min_uV, uA_load;
BUG_ON(!vreg);
if (regulator_count_voltages(reg) > 0) {
min_uV = on ? vreg->min_uV : 0;
ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
if (ret) {
dev_err(dev, "%s: %s set voltage failed, err=%d\n",
__func__, name, ret);
goto out;
}
uA_load = on ? vreg->max_uA : 0;
ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
if (ret)
goto out;
}
out:
return ret;
}
static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
{
int ret = 0;
if (!vreg)
goto out;
else if (vreg->enabled || vreg->unused)
goto out;
ret = ufshcd_config_vreg(dev, vreg, true);
if (!ret)
ret = regulator_enable(vreg->reg);
if (!ret)
vreg->enabled = true;
else
dev_err(dev, "%s: %s enable failed, err=%d\n",
__func__, vreg->name, ret);
out:
return ret;
}
static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
{
int ret = 0;
if (!vreg)
goto out;
else if (!vreg->enabled || vreg->unused)
goto out;
ret = regulator_disable(vreg->reg);
if (!ret) {
/* ignore errors on applying disable config */
ufshcd_config_vreg(dev, vreg, false);
vreg->enabled = false;
} else {
dev_err(dev, "%s: %s disable failed, err=%d\n",
__func__, vreg->name, ret);
}
out:
return ret;
}
static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
{
int ret = 0;
struct device *dev = hba->dev;
struct ufs_vreg_info *info = &hba->vreg_info;
if (!info)
goto out;
ret = ufshcd_toggle_vreg(dev, info->vcc, on);
if (ret)
goto out;
ret = ufshcd_toggle_vreg(dev, info->vccq, on);
if (ret)
goto out;
ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
if (ret)
goto out;
out:
if (ret) {
ufshcd_toggle_vreg(dev, info->vccq2, false);
ufshcd_toggle_vreg(dev, info->vccq, false);
ufshcd_toggle_vreg(dev, info->vcc, false);
}
return ret;
}
static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
{
struct ufs_vreg_info *info = &hba->vreg_info;
if (info)
return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
return 0;
}
static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
{
int ret = 0;
if (!vreg)
goto out;
vreg->reg = devm_regulator_get(dev, vreg->name);
if (IS_ERR(vreg->reg)) {
ret = PTR_ERR(vreg->reg);
dev_err(dev, "%s: %s get failed, err=%d\n",
__func__, vreg->name, ret);
}
out:
return ret;
}
static int ufshcd_init_vreg(struct ufs_hba *hba)
{
int ret = 0;
struct device *dev = hba->dev;
struct ufs_vreg_info *info = &hba->vreg_info;
if (!info)
goto out;
ret = ufshcd_get_vreg(dev, info->vcc);
if (ret)
goto out;
ret = ufshcd_get_vreg(dev, info->vccq);
if (ret)
goto out;
ret = ufshcd_get_vreg(dev, info->vccq2);
out:
return ret;
}
static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
{
struct ufs_vreg_info *info = &hba->vreg_info;
if (info)
return ufshcd_get_vreg(hba->dev, info->vdd_hba);
return 0;
}
static int ufshcd_set_vccq_rail_unused(struct ufs_hba *hba, bool unused)
{
int ret = 0;
struct ufs_vreg_info *info = &hba->vreg_info;
if (!info)
goto out;
else if (!info->vccq)
goto out;
if (unused) {
/* shut off the rail here */
ret = ufshcd_toggle_vreg(hba->dev, info->vccq, false);
/*
* Mark this rail as no longer used, so it doesn't get enabled
* later by mistake
*/
if (!ret)
info->vccq->unused = true;
} else {
/*
* rail should have been already enabled hence just make sure
* that unused flag is cleared.
*/
info->vccq->unused = false;
}
out:
return ret;
}
static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
bool skip_ref_clk)
{
int ret = 0;
struct ufs_clk_info *clki;
struct list_head *head = &hba->clk_list_head;
unsigned long flags;
if (!head || list_empty(head))
goto out;
list_for_each_entry(clki, head, list) {
if (!IS_ERR_OR_NULL(clki->clk)) {
if (skip_ref_clk && !strcmp(clki->name, "ref_clk"))
continue;
if (on && !clki->enabled) {
ret = clk_prepare_enable(clki->clk);
if (ret) {
dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
__func__, clki->name, ret);
goto out;
}
} else if (!on && clki->enabled) {
clk_disable_unprepare(clki->clk);
}
clki->enabled = on;
dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
clki->name, on ? "en" : "dis");
}
}
ret = ufshcd_vops_setup_clocks(hba, on);
out:
if (ret) {
list_for_each_entry(clki, head, list) {
if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
clk_disable_unprepare(clki->clk);
}
} else if (on) {
spin_lock_irqsave(hba->host->host_lock, flags);
hba->clk_gating.state = CLKS_ON;
spin_unlock_irqrestore(hba->host->host_lock, flags);
}
return ret;
}
static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
{
return __ufshcd_setup_clocks(hba, on, false);
}
static int ufshcd_init_clocks(struct ufs_hba *hba)
{
int ret = 0;
struct ufs_clk_info *clki;
struct device *dev = hba->dev;
struct list_head *head = &hba->clk_list_head;
if (!head || list_empty(head))
goto out;
list_for_each_entry(clki, head, list) {
if (!clki->name)
continue;
clki->clk = devm_clk_get(dev, clki->name);
if (IS_ERR(clki->clk)) {
ret = PTR_ERR(clki->clk);
dev_err(dev, "%s: %s clk get failed, %d\n",
__func__, clki->name, ret);
goto out;
}
if (clki->max_freq) {
ret = clk_set_rate(clki->clk, clki->max_freq);
if (ret) {
dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
__func__, clki->name,
clki->max_freq, ret);
goto out;
}
clki->curr_freq = clki->max_freq;
}
dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
clki->name, clk_get_rate(clki->clk));
}
out:
return ret;
}
static int ufshcd_variant_hba_init(struct ufs_hba *hba)
{
int err = 0;
if (!hba->vops)
goto out;
err = ufshcd_vops_init(hba);
if (err)
goto out;
err = ufshcd_vops_setup_regulators(hba, true);
if (err)
goto out_exit;
goto out;
out_exit:
ufshcd_vops_exit(hba);
out:
if (err)
dev_err(hba->dev, "%s: variant %s init failed err %d\n",
__func__, ufshcd_get_var_name(hba), err);
return err;
}
static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
{
if (!hba->vops)
return;
ufshcd_vops_setup_clocks(hba, false);
ufshcd_vops_setup_regulators(hba, false);
ufshcd_vops_exit(hba);
}
static int ufshcd_hba_init(struct ufs_hba *hba)
{
int err;
/*
* Handle host controller power separately from the UFS device power
* rails as it will help controlling the UFS host controller power
* collapse easily which is different than UFS device power collapse.
* Also, enable the host controller power before we go ahead with rest
* of the initialization here.
*/
err = ufshcd_init_hba_vreg(hba);
if (err)
goto out;
err = ufshcd_setup_hba_vreg(hba, true);
if (err)
goto out;
err = ufshcd_init_clocks(hba);
if (err)
goto out_disable_hba_vreg;
err = ufshcd_setup_clocks(hba, true);
if (err)
goto out_disable_hba_vreg;
err = ufshcd_init_vreg(hba);
if (err)
goto out_disable_clks;
err = ufshcd_setup_vreg(hba, true);
if (err)
goto out_disable_clks;
err = ufshcd_variant_hba_init(hba);
if (err)
goto out_disable_vreg;
hba->is_powered = true;
goto out;
out_disable_vreg:
ufshcd_setup_vreg(hba, false);
out_disable_clks:
ufshcd_setup_clocks(hba, false);
out_disable_hba_vreg:
ufshcd_setup_hba_vreg(hba, false);
out:
return err;
}
static void ufshcd_hba_exit(struct ufs_hba *hba)
{
if (hba->is_powered) {
ufshcd_variant_hba_exit(hba);
ufshcd_setup_vreg(hba, false);
ufshcd_setup_clocks(hba, false);
ufshcd_setup_hba_vreg(hba, false);
hba->is_powered = false;
}
}
static int
ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp)
{
unsigned char cmd[6] = {REQUEST_SENSE,
0,
0,
0,
SCSI_SENSE_BUFFERSIZE,
0};
char *buffer;
int ret;
buffer = kzalloc(SCSI_SENSE_BUFFERSIZE, GFP_KERNEL);
if (!buffer) {
ret = -ENOMEM;
goto out;
}
ret = scsi_execute_req_flags(sdp, cmd, DMA_FROM_DEVICE, buffer,
SCSI_SENSE_BUFFERSIZE, NULL,
msecs_to_jiffies(1000), 3, NULL, REQ_PM);
if (ret)
pr_err("%s: failed with err %d\n", __func__, ret);
kfree(buffer);
out:
return ret;
}
/**
* ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
* power mode
* @hba: per adapter instance
* @pwr_mode: device power mode to set
*
* Returns 0 if requested power mode is set successfully
* Returns non-zero if failed to set the requested power mode
*/
static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
enum ufs_dev_pwr_mode pwr_mode)
{
unsigned char cmd[6] = { START_STOP };
struct scsi_sense_hdr sshdr;
struct scsi_device *sdp;
unsigned long flags;
int ret;
spin_lock_irqsave(hba->host->host_lock, flags);
sdp = hba->sdev_ufs_device;
if (sdp) {
ret = scsi_device_get(sdp);
if (!ret && !scsi_device_online(sdp)) {
ret = -ENODEV;
scsi_device_put(sdp);
}
} else {
ret = -ENODEV;
}
spin_unlock_irqrestore(hba->host->host_lock, flags);
if (ret)
return ret;
/*
* If scsi commands fail, the scsi mid-layer schedules scsi error-
* handling, which would wait for host to be resumed. Since we know
* we are functional while we are here, skip host resume in error
* handling context.
*/
hba->host->eh_noresume = 1;
if (hba->wlun_dev_clr_ua) {
ret = ufshcd_send_request_sense(hba, sdp);
if (ret)
goto out;
/* Unit attention condition is cleared now */
hba->wlun_dev_clr_ua = false;
}
cmd[4] = pwr_mode << 4;
/*
* Current function would be generally called from the power management
* callbacks hence set the REQ_PM flag so that it doesn't resume the
* already suspended childs.
*/
ret = scsi_execute_req_flags(sdp, cmd, DMA_NONE, NULL, 0, &sshdr,
START_STOP_TIMEOUT, 0, NULL, REQ_PM);
if (ret) {
sdev_printk(KERN_WARNING, sdp,
"START_STOP failed for power mode: %d, result %x\n",
pwr_mode, ret);
if (driver_byte(ret) & DRIVER_SENSE)
scsi_print_sense_hdr(sdp, NULL, &sshdr);
}
if (!ret)
hba->curr_dev_pwr_mode = pwr_mode;
out:
scsi_device_put(sdp);
hba->host->eh_noresume = 0;
return ret;
}
static int ufshcd_link_state_transition(struct ufs_hba *hba,
enum uic_link_state req_link_state,
int check_for_bkops)
{
int ret = 0;
if (req_link_state == hba->uic_link_state)
return 0;
if (req_link_state == UIC_LINK_HIBERN8_STATE) {
ret = ufshcd_uic_hibern8_enter(hba);
if (!ret)
ufshcd_set_link_hibern8(hba);
else
goto out;
}
/*
* If autobkops is enabled, link can't be turned off because
* turning off the link would also turn off the device.
*/
else if ((req_link_state == UIC_LINK_OFF_STATE) &&
(!check_for_bkops || (check_for_bkops &&
!hba->auto_bkops_enabled))) {
/*
* Let's make sure that link is in low power mode, we are doing
* this currently by putting the link in Hibern8. Otherway to
* put the link in low power mode is to send the DME end point
* to device and then send the DME reset command to local
* unipro. But putting the link in hibern8 is much faster.
*/
ret = ufshcd_uic_hibern8_enter(hba);
if (ret)
goto out;
/*
* Change controller state to "reset state" which
* should also put the link in off/reset state
*/
ufshcd_hba_stop(hba, true);
/*
* TODO: Check if we need any delay to make sure that
* controller is reset
*/
ufshcd_set_link_off(hba);
}
out:
return ret;
}
static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
{
/*
* It seems some UFS devices may keep drawing more than sleep current
* (atleast for 500us) from UFS rails (especially from VCCQ rail).
* To avoid this situation, add 2ms delay before putting these UFS
* rails in LPM mode.
*/
if (!ufshcd_is_link_active(hba) &&
hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
usleep_range(2000, 2100);
/*
* If UFS device is either in UFS_Sleep turn off VCC rail to save some
* power.
*
* If UFS device and link is in OFF state, all power supplies (VCC,
* VCCQ, VCCQ2) can be turned off if power on write protect is not
* required. If UFS link is inactive (Hibern8 or OFF state) and device
* is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
*
* Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
* in low power state which would save some power.
*/
if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
!hba->dev_info.is_lu_power_on_wp) {
ufshcd_setup_vreg(hba, false);
} else if (!ufshcd_is_ufs_dev_active(hba)) {
ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
if (!ufshcd_is_link_active(hba)) {
ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
}
}
}
static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
{
int ret = 0;
if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
!hba->dev_info.is_lu_power_on_wp) {
ret = ufshcd_setup_vreg(hba, true);
} else if (!ufshcd_is_ufs_dev_active(hba)) {
ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
if (!ret && !ufshcd_is_link_active(hba)) {
ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
if (ret)
goto vcc_disable;
ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
if (ret)
goto vccq_lpm;
}
}
goto out;
vccq_lpm:
ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
vcc_disable:
ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
out:
return ret;
}
static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
{
if (ufshcd_is_link_off(hba))
ufshcd_setup_hba_vreg(hba, false);
}
static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
{
if (ufshcd_is_link_off(hba))
ufshcd_setup_hba_vreg(hba, true);
}
/**
* ufshcd_suspend - helper function for suspend operations
* @hba: per adapter instance
* @pm_op: desired low power operation type
*
* This function will try to put the UFS device and link into low power
* mode based on the "rpm_lvl" (Runtime PM level) or "spm_lvl"
* (System PM level).
*
* If this function is called during shutdown, it will make sure that
* both UFS device and UFS link is powered off.
*
* NOTE: UFS device & link must be active before we enter in this function.
*
* Returns 0 for success and non-zero for failure
*/
static int ufshcd_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
{
int ret = 0;
enum ufs_pm_level pm_lvl;
enum ufs_dev_pwr_mode req_dev_pwr_mode;
enum uic_link_state req_link_state;
hba->pm_op_in_progress = 1;
if (!ufshcd_is_shutdown_pm(pm_op)) {
pm_lvl = ufshcd_is_runtime_pm(pm_op) ?
hba->rpm_lvl : hba->spm_lvl;
req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
} else {
req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
req_link_state = UIC_LINK_OFF_STATE;
}
/*
* If we can't transition into any of the low power modes
* just gate the clocks.
*/
ufshcd_hold(hba, false);
hba->clk_gating.is_suspended = true;
if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
req_link_state == UIC_LINK_ACTIVE_STATE) {
goto disable_clks;
}
if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
(req_link_state == hba->uic_link_state))
goto out;
/* UFS device & link must be active before we enter in this function */
if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
ret = -EINVAL;
goto out;
}
if (ufshcd_is_runtime_pm(pm_op)) {
if (ufshcd_can_autobkops_during_suspend(hba)) {
/*
* The device is idle with no requests in the queue,
* allow background operations if bkops status shows
* that performance might be impacted.
*/
ret = ufshcd_urgent_bkops(hba);
if (ret)
goto enable_gating;
} else {
/* make sure that auto bkops is disabled */
ufshcd_disable_auto_bkops(hba);
}
}
if ((req_dev_pwr_mode != hba->curr_dev_pwr_mode) &&
((ufshcd_is_runtime_pm(pm_op) && !hba->auto_bkops_enabled) ||
!ufshcd_is_runtime_pm(pm_op))) {
/* ensure that bkops is disabled */
ufshcd_disable_auto_bkops(hba);
ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
if (ret)
goto enable_gating;
}
ret = ufshcd_link_state_transition(hba, req_link_state, 1);
if (ret)
goto set_dev_active;
ufshcd_vreg_set_lpm(hba);
disable_clks:
/*
* The clock scaling needs access to controller registers. Hence, Wait
* for pending clock scaling work to be done before clocks are
* turned off.
*/
if (ufshcd_is_clkscaling_enabled(hba)) {
devfreq_suspend_device(hba->devfreq);
hba->clk_scaling.window_start_t = 0;
}
/*
* Call vendor specific suspend callback. As these callbacks may access
* vendor specific host controller register space call them before the
* host clocks are ON.
*/
ret = ufshcd_vops_suspend(hba, pm_op);
if (ret)
goto set_link_active;
ret = ufshcd_vops_setup_clocks(hba, false);
if (ret)
goto vops_resume;
if (!ufshcd_is_link_active(hba))
ufshcd_setup_clocks(hba, false);
else
/* If link is active, device ref_clk can't be switched off */
__ufshcd_setup_clocks(hba, false, true);
hba->clk_gating.state = CLKS_OFF;
/*
* Disable the host irq as host controller as there won't be any
* host controller transaction expected till resume.
*/
ufshcd_disable_irq(hba);
/* Put the host controller in low power mode if possible */
ufshcd_hba_vreg_set_lpm(hba);
goto out;
vops_resume:
ufshcd_vops_resume(hba, pm_op);
set_link_active:
ufshcd_vreg_set_hpm(hba);
if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
ufshcd_set_link_active(hba);
else if (ufshcd_is_link_off(hba))
ufshcd_host_reset_and_restore(hba);
set_dev_active:
if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
ufshcd_disable_auto_bkops(hba);
enable_gating:
hba->clk_gating.is_suspended = false;
ufshcd_release(hba);
out:
hba->pm_op_in_progress = 0;
return ret;
}
/**
* ufshcd_resume - helper function for resume operations
* @hba: per adapter instance
* @pm_op: runtime PM or system PM
*
* This function basically brings the UFS device, UniPro link and controller
* to active state.
*
* Returns 0 for success and non-zero for failure
*/
static int ufshcd_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
{
int ret;
enum uic_link_state old_link_state;
hba->pm_op_in_progress = 1;
old_link_state = hba->uic_link_state;
ufshcd_hba_vreg_set_hpm(hba);
/* Make sure clocks are enabled before accessing controller */
ret = ufshcd_setup_clocks(hba, true);
if (ret)
goto out;
/* enable the host irq as host controller would be active soon */
ret = ufshcd_enable_irq(hba);
if (ret)
goto disable_irq_and_vops_clks;
ret = ufshcd_vreg_set_hpm(hba);
if (ret)
goto disable_irq_and_vops_clks;
/*
* Call vendor specific resume callback. As these callbacks may access
* vendor specific host controller register space call them when the
* host clocks are ON.
*/
ret = ufshcd_vops_resume(hba, pm_op);
if (ret)
goto disable_vreg;
if (ufshcd_is_link_hibern8(hba)) {
ret = ufshcd_uic_hibern8_exit(hba);
if (!ret)
ufshcd_set_link_active(hba);
else
goto vendor_suspend;
} else if (ufshcd_is_link_off(hba)) {
ret = ufshcd_host_reset_and_restore(hba);
/*
* ufshcd_host_reset_and_restore() should have already
* set the link state as active
*/
if (ret || !ufshcd_is_link_active(hba))
goto vendor_suspend;
}
if (!ufshcd_is_ufs_dev_active(hba)) {
ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
if (ret)
goto set_old_link_state;
}
/*
* If BKOPs operations are urgently needed at this moment then
* keep auto-bkops enabled or else disable it.
*/
ufshcd_urgent_bkops(hba);
hba->clk_gating.is_suspended = false;
if (ufshcd_is_clkscaling_enabled(hba))
devfreq_resume_device(hba->devfreq);
/* Schedule clock gating in case of no access to UFS device yet */
ufshcd_release(hba);
goto out;
set_old_link_state:
ufshcd_link_state_transition(hba, old_link_state, 0);
vendor_suspend:
ufshcd_vops_suspend(hba, pm_op);
disable_vreg:
ufshcd_vreg_set_lpm(hba);
disable_irq_and_vops_clks:
ufshcd_disable_irq(hba);
ufshcd_setup_clocks(hba, false);
out:
hba->pm_op_in_progress = 0;
return ret;
}
/**
* ufshcd_system_suspend - system suspend routine
* @hba: per adapter instance
* @pm_op: runtime PM or system PM
*
* Check the description of ufshcd_suspend() function for more details.
*
* Returns 0 for success and non-zero for failure
*/
int ufshcd_system_suspend(struct ufs_hba *hba)
{
int ret = 0;
if (!hba || !hba->is_powered)
return 0;
if (pm_runtime_suspended(hba->dev)) {
if (hba->rpm_lvl == hba->spm_lvl)
/*
* There is possibility that device may still be in
* active state during the runtime suspend.
*/
if ((ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl) ==
hba->curr_dev_pwr_mode) && !hba->auto_bkops_enabled)
goto out;
/*
* UFS device and/or UFS link low power states during runtime
* suspend seems to be different than what is expected during
* system suspend. Hence runtime resume the devic & link and
* let the system suspend low power states to take effect.
* TODO: If resume takes longer time, we might have optimize
* it in future by not resuming everything if possible.
*/
ret = ufshcd_runtime_resume(hba);
if (ret)
goto out;
}
ret = ufshcd_suspend(hba, UFS_SYSTEM_PM);
out:
if (!ret)
hba->is_sys_suspended = true;
return ret;
}
EXPORT_SYMBOL(ufshcd_system_suspend);
/**
* ufshcd_system_resume - system resume routine
* @hba: per adapter instance
*
* Returns 0 for success and non-zero for failure
*/
int ufshcd_system_resume(struct ufs_hba *hba)
{
if (!hba || !hba->is_powered || pm_runtime_suspended(hba->dev))
/*
* Let the runtime resume take care of resuming
* if runtime suspended.
*/
return 0;
return ufshcd_resume(hba, UFS_SYSTEM_PM);
}
EXPORT_SYMBOL(ufshcd_system_resume);
/**
* ufshcd_runtime_suspend - runtime suspend routine
* @hba: per adapter instance
*
* Check the description of ufshcd_suspend() function for more details.
*
* Returns 0 for success and non-zero for failure
*/
int ufshcd_runtime_suspend(struct ufs_hba *hba)
{
if (!hba || !hba->is_powered)
return 0;
return ufshcd_suspend(hba, UFS_RUNTIME_PM);
}
EXPORT_SYMBOL(ufshcd_runtime_suspend);
/**
* ufshcd_runtime_resume - runtime resume routine
* @hba: per adapter instance
*
* This function basically brings the UFS device, UniPro link and controller
* to active state. Following operations are done in this function:
*
* 1. Turn on all the controller related clocks
* 2. Bring the UniPro link out of Hibernate state
* 3. If UFS device is in sleep state, turn ON VCC rail and bring the UFS device
* to active state.
* 4. If auto-bkops is enabled on the device, disable it.
*
* So following would be the possible power state after this function return
* successfully:
* S1: UFS device in Active state with VCC rail ON
* UniPro link in Active state
* All the UFS/UniPro controller clocks are ON
*
* Returns 0 for success and non-zero for failure
*/
int ufshcd_runtime_resume(struct ufs_hba *hba)
{
if (!hba || !hba->is_powered)
return 0;
else
return ufshcd_resume(hba, UFS_RUNTIME_PM);
}
EXPORT_SYMBOL(ufshcd_runtime_resume);
int ufshcd_runtime_idle(struct ufs_hba *hba)
{
return 0;
}
EXPORT_SYMBOL(ufshcd_runtime_idle);
/**
* ufshcd_shutdown - shutdown routine
* @hba: per adapter instance
*
* This function would power off both UFS device and UFS link.
*
* Returns 0 always to allow force shutdown even in case of errors.
*/
int ufshcd_shutdown(struct ufs_hba *hba)
{
int ret = 0;
if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
goto out;
if (pm_runtime_suspended(hba->dev)) {
ret = ufshcd_runtime_resume(hba);
if (ret)
goto out;
}
ret = ufshcd_suspend(hba, UFS_SHUTDOWN_PM);
out:
if (ret)
dev_err(hba->dev, "%s failed, err %d\n", __func__, ret);
/* allow force shutdown even in case of errors */
return 0;
}
EXPORT_SYMBOL(ufshcd_shutdown);
/**
* ufshcd_remove - de-allocate SCSI host and host memory space
* data structure memory
* @hba - per adapter instance
*/
void ufshcd_remove(struct ufs_hba *hba)
{
scsi_remove_host(hba->host);
/* disable interrupts */
ufshcd_disable_intr(hba, hba->intr_mask);
ufshcd_hba_stop(hba, true);
scsi_host_put(hba->host);
ufshcd_exit_clk_gating(hba);
if (ufshcd_is_clkscaling_enabled(hba))
devfreq_remove_device(hba->devfreq);
ufshcd_hba_exit(hba);
}
EXPORT_SYMBOL_GPL(ufshcd_remove);
/**
* ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
* @hba: pointer to Host Bus Adapter (HBA)
*/
void ufshcd_dealloc_host(struct ufs_hba *hba)
{
scsi_host_put(hba->host);
}
EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
/**
* ufshcd_set_dma_mask - Set dma mask based on the controller
* addressing capability
* @hba: per adapter instance
*
* Returns 0 for success, non-zero for failure
*/
static int ufshcd_set_dma_mask(struct ufs_hba *hba)
{
if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
return 0;
}
return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
}
/**
* ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
* @dev: pointer to device handle
* @hba_handle: driver private handle
* Returns 0 on success, non-zero value on failure
*/
int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
{
struct Scsi_Host *host;
struct ufs_hba *hba;
int err = 0;
if (!dev) {
dev_err(dev,
"Invalid memory reference for dev is NULL\n");
err = -ENODEV;
goto out_error;
}
host = scsi_host_alloc(&ufshcd_driver_template,
sizeof(struct ufs_hba));
if (!host) {
dev_err(dev, "scsi_host_alloc failed\n");
err = -ENOMEM;
goto out_error;
}
hba = shost_priv(host);
hba->host = host;
hba->dev = dev;
*hba_handle = hba;
out_error:
return err;
}
EXPORT_SYMBOL(ufshcd_alloc_host);
static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
{
int ret = 0;
struct ufs_clk_info *clki;
struct list_head *head = &hba->clk_list_head;
if (!head || list_empty(head))
goto out;
ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
if (ret)
return ret;
list_for_each_entry(clki, head, list) {
if (!IS_ERR_OR_NULL(clki->clk)) {
if (scale_up && clki->max_freq) {
if (clki->curr_freq == clki->max_freq)
continue;
ret = clk_set_rate(clki->clk, clki->max_freq);
if (ret) {
dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
__func__, clki->name,
clki->max_freq, ret);
break;
}
clki->curr_freq = clki->max_freq;
} else if (!scale_up && clki->min_freq) {
if (clki->curr_freq == clki->min_freq)
continue;
ret = clk_set_rate(clki->clk, clki->min_freq);
if (ret) {
dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
__func__, clki->name,
clki->min_freq, ret);
break;
}
clki->curr_freq = clki->min_freq;
}
}
dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
clki->name, clk_get_rate(clki->clk));
}
ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
out:
return ret;
}
static int ufshcd_devfreq_target(struct device *dev,
unsigned long *freq, u32 flags)
{
int err = 0;
struct ufs_hba *hba = dev_get_drvdata(dev);
if (!ufshcd_is_clkscaling_enabled(hba))
return -EINVAL;
if (*freq == UINT_MAX)
err = ufshcd_scale_clks(hba, true);
else if (*freq == 0)
err = ufshcd_scale_clks(hba, false);
return err;
}
static int ufshcd_devfreq_get_dev_status(struct device *dev,
struct devfreq_dev_status *stat)
{
struct ufs_hba *hba = dev_get_drvdata(dev);
struct ufs_clk_scaling *scaling = &hba->clk_scaling;
unsigned long flags;
if (!ufshcd_is_clkscaling_enabled(hba))
return -EINVAL;
memset(stat, 0, sizeof(*stat));
spin_lock_irqsave(hba->host->host_lock, flags);
if (!scaling->window_start_t)
goto start_window;
if (scaling->is_busy_started)
scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
scaling->busy_start_t));
stat->total_time = jiffies_to_usecs((long)jiffies -
(long)scaling->window_start_t);
stat->busy_time = scaling->tot_busy_t;
start_window:
scaling->window_start_t = jiffies;
scaling->tot_busy_t = 0;
if (hba->outstanding_reqs) {
scaling->busy_start_t = ktime_get();
scaling->is_busy_started = true;
} else {
scaling->busy_start_t = ktime_set(0, 0);
scaling->is_busy_started = false;
}
spin_unlock_irqrestore(hba->host->host_lock, flags);
return 0;
}
static struct devfreq_dev_profile ufs_devfreq_profile = {
.polling_ms = 100,
.target = ufshcd_devfreq_target,
.get_dev_status = ufshcd_devfreq_get_dev_status,
};
/**
* ufshcd_init - Driver initialization routine
* @hba: per-adapter instance
* @mmio_base: base register address
* @irq: Interrupt line of device
* Returns 0 on success, non-zero value on failure
*/
int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
{
int err;
struct Scsi_Host *host = hba->host;
struct device *dev = hba->dev;
if (!mmio_base) {
dev_err(hba->dev,
"Invalid memory reference for mmio_base is NULL\n");
err = -ENODEV;
goto out_error;
}
hba->mmio_base = mmio_base;
hba->irq = irq;
err = ufshcd_hba_init(hba);
if (err)
goto out_error;
/* Read capabilities registers */
ufshcd_hba_capabilities(hba);
/* Get UFS version supported by the controller */
hba->ufs_version = ufshcd_get_ufs_version(hba);
/* Get Interrupt bit mask per version */
hba->intr_mask = ufshcd_get_intr_mask(hba);
err = ufshcd_set_dma_mask(hba);
if (err) {
dev_err(hba->dev, "set dma mask failed\n");
goto out_disable;
}
/* Allocate memory for host memory space */
err = ufshcd_memory_alloc(hba);
if (err) {
dev_err(hba->dev, "Memory allocation failed\n");
goto out_disable;
}
/* Configure LRB */
ufshcd_host_memory_configure(hba);
host->can_queue = hba->nutrs;
host->cmd_per_lun = hba->nutrs;
host->max_id = UFSHCD_MAX_ID;
host->max_lun = UFS_MAX_LUNS;
host->max_channel = UFSHCD_MAX_CHANNEL;
host->unique_id = host->host_no;
host->max_cmd_len = MAX_CDB_SIZE;
hba->max_pwr_info.is_valid = false;
/* Initailize wait queue for task management */
init_waitqueue_head(&hba->tm_wq);
init_waitqueue_head(&hba->tm_tag_wq);
/* Initialize work queues */
INIT_WORK(&hba->eh_work, ufshcd_err_handler);
INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
/* Initialize UIC command mutex */
mutex_init(&hba->uic_cmd_mutex);
/* Initialize mutex for device management commands */
mutex_init(&hba->dev_cmd.lock);
/* Initialize device management tag acquire wait queue */
init_waitqueue_head(&hba->dev_cmd.tag_wq);
ufshcd_init_clk_gating(hba);
/*
* In order to avoid any spurious interrupt immediately after
* registering UFS controller interrupt handler, clear any pending UFS
* interrupt status and disable all the UFS interrupts.
*/
ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
REG_INTERRUPT_STATUS);
ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
/*
* Make sure that UFS interrupts are disabled and any pending interrupt
* status is cleared before registering UFS interrupt handler.
*/
mb();
/* IRQ registration */
err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
if (err) {
dev_err(hba->dev, "request irq failed\n");
goto exit_gating;
} else {
hba->is_irq_enabled = true;
}
err = scsi_add_host(host, hba->dev);
if (err) {
dev_err(hba->dev, "scsi_add_host failed\n");
goto exit_gating;
}
/* Host controller enable */
err = ufshcd_hba_enable(hba);
if (err) {
dev_err(hba->dev, "Host controller enable failed\n");
goto out_remove_scsi_host;
}
if (ufshcd_is_clkscaling_enabled(hba)) {
hba->devfreq = devfreq_add_device(dev, &ufs_devfreq_profile,
"simple_ondemand", NULL);
if (IS_ERR(hba->devfreq)) {
dev_err(hba->dev, "Unable to register with devfreq %ld\n",
PTR_ERR(hba->devfreq));
goto out_remove_scsi_host;
}
/* Suspend devfreq until the UFS device is detected */
devfreq_suspend_device(hba->devfreq);
hba->clk_scaling.window_start_t = 0;
}
/* Hold auto suspend until async scan completes */
pm_runtime_get_sync(dev);
/*
* The device-initialize-sequence hasn't been invoked yet.
* Set the device to power-off state
*/
ufshcd_set_ufs_dev_poweroff(hba);
async_schedule(ufshcd_async_scan, hba);
return 0;
out_remove_scsi_host:
scsi_remove_host(hba->host);
exit_gating:
ufshcd_exit_clk_gating(hba);
out_disable:
hba->is_irq_enabled = false;
scsi_host_put(host);
ufshcd_hba_exit(hba);
out_error:
return err;
}
EXPORT_SYMBOL_GPL(ufshcd_init);
MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
MODULE_DESCRIPTION("Generic UFS host controller driver Core");
MODULE_LICENSE("GPL");
MODULE_VERSION(UFSHCD_DRIVER_VERSION);
| gpl-2.0 |
Hlkz/Acore | src/server/scripts/Kalimdor/RazorfenDowns/razorfen_downs.cpp | 79 | 14080 | /*
* Copyright (C) 2008-2015 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
SDName: Razorfen_Downs
SD%Complete: 100
SDComment: Support for Henry Stern(2 recipes)
SDCategory: Razorfen Downs
EndScriptData */
/* ContentData
npc_henry_stern
EndContentData */
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "ScriptedGossip.h"
#include "razorfen_downs.h"
#include "Player.h"
#include "GridNotifiers.h"
#include "GridNotifiersImpl.h"
#include "Cell.h"
#include "CellImpl.h"
/*###
## npc_belnistrasz for Quest 3525 "Extinguishing the Idol"
######*/
Position const PosSummonSpawner[3] =
{
{ 2582.789f, 954.3925f, 52.48214f, 3.787364f },
{ 2569.42f, 956.3801f, 52.27323f, 5.427974f },
{ 2570.62f, 942.3934f, 53.7433f, 0.715585f }
};
enum Belnistrasz
{
EVENT_CHANNEL = 1,
EVENT_IDOL_ROOM_SPAWNER = 2,
EVENT_PROGRESS = 3,
EVENT_COMPLETE = 4,
EVENT_FIREBALL = 5,
EVENT_FROST_NOVA = 6,
FACTION_ESCORT = 250,
PATH_ESCORT = 871710,
POINT_REACH_IDOL = 17,
QUEST_EXTINGUISHING_THE_IDOL = 3525,
SAY_QUEST_ACCEPTED = 0,
SAY_EVENT_START = 1,
SAY_EVENT_THREE_MIN_LEFT = 2,
SAY_EVENT_TWO_MIN_LEFT = 3,
SAY_EVENT_ONE_MIN_LEFT = 4,
SAY_EVENT_END = 5,
SAY_AGGRO = 6, // Combat
SAY_WATCH_OUT = 7, // 25% chance to target random creature and say on wave spawn
SPELL_ARCANE_INTELLECT = 13326,
SPELL_FIREBALL = 9053,
SPELL_FROST_NOVA = 11831,
SPELL_IDOL_SHUTDOWN_VISUAL = 12774, // Hits Unit Entry: 8662
SPELL_IDOM_ROOM_CAMERA_SHAKE = 12816 // Dummy needs scripting
};
class npc_belnistrasz : public CreatureScript
{
public:
npc_belnistrasz() : CreatureScript("npc_belnistrasz") { }
struct npc_belnistraszAI : public ScriptedAI
{
npc_belnistraszAI(Creature* creature) : ScriptedAI(creature)
{
instance = creature->GetInstanceScript();
eventInProgress = false;
channeling = false;
eventProgress = 0;
spawnerCount = 0;
}
void Reset() override
{
if (!eventInProgress)
{
if (!me->HasAura(SPELL_ARCANE_INTELLECT))
DoCast(me, SPELL_ARCANE_INTELLECT);
channeling = false;
eventProgress = 0;
spawnerCount = 0;
me->SetFlag(UNIT_NPC_FLAGS, GOSSIP_OPTION_QUESTGIVER);
}
}
void EnterCombat(Unit* who) override
{
if (channeling)
Talk(SAY_WATCH_OUT, who);
else
{
events.ScheduleEvent(EVENT_FIREBALL, 1000);
events.ScheduleEvent(EVENT_FROST_NOVA, urand(8000, 12000));
if (urand(0, 100) > 40)
Talk(SAY_AGGRO, who);
}
}
void JustDied(Unit* /*killer*/) override
{
instance->SetBossState(DATA_EXTINGUISHING_THE_IDOL, DONE);
me->DespawnOrUnsummon(5000);
}
void sQuestAccept(Player* /*player*/, Quest const* quest) override
{
if (quest->GetQuestId() == QUEST_EXTINGUISHING_THE_IDOL)
{
eventInProgress = true;
Talk(SAY_QUEST_ACCEPTED);
me->RemoveFlag(UNIT_NPC_FLAGS, GOSSIP_OPTION_QUESTGIVER);
me->setFaction(FACTION_ESCORT);
me->GetMotionMaster()->MovePath(PATH_ESCORT, false);
}
}
void MovementInform(uint32 type, uint32 id) override
{
if (type == WAYPOINT_MOTION_TYPE && id == POINT_REACH_IDOL)
{
channeling = true;
events.ScheduleEvent(EVENT_CHANNEL, 2000);
}
}
void UpdateAI(uint32 diff) override
{
if (!eventInProgress)
return;
events.Update(diff);
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_CHANNEL:
Talk(SAY_EVENT_START);
DoCast(me, SPELL_IDOL_SHUTDOWN_VISUAL);
events.ScheduleEvent(EVENT_IDOL_ROOM_SPAWNER, 100);
events.ScheduleEvent(EVENT_PROGRESS, 120000);
break;
case EVENT_IDOL_ROOM_SPAWNER:
if (Creature* creature = me->SummonCreature(NPC_IDOL_ROOM_SPAWNER, PosSummonSpawner[urand(0,2)], TEMPSUMMON_TIMED_DESPAWN, 4000))
creature->AI()->SetData(0,spawnerCount);
if (++spawnerCount < 8)
events.ScheduleEvent(EVENT_IDOL_ROOM_SPAWNER, 35000);
break;
case EVENT_PROGRESS:
{
switch (eventProgress)
{
case 0:
Talk(SAY_EVENT_THREE_MIN_LEFT);
++eventProgress;
events.ScheduleEvent(EVENT_PROGRESS, 60000);
break;
case 1:
Talk(SAY_EVENT_TWO_MIN_LEFT);
++eventProgress;
events.ScheduleEvent(EVENT_PROGRESS, 60000);
break;
case 2:
Talk(SAY_EVENT_ONE_MIN_LEFT);
++eventProgress;
events.ScheduleEvent(EVENT_PROGRESS, 60000);
break;
case 3:
events.CancelEvent(EVENT_IDOL_ROOM_SPAWNER);
me->InterruptSpell(CURRENT_CHANNELED_SPELL);
Talk(SAY_EVENT_END);
events.ScheduleEvent(EVENT_COMPLETE, 3000);
break;
}
break;
}
case EVENT_COMPLETE:
{
DoCast(me, SPELL_IDOM_ROOM_CAMERA_SHAKE);
me->SummonGameObject(GO_BELNISTRASZS_BRAZIER, 2577.196f, 947.0781f, 53.16757f, 2.356195f, 0, 0, 0.9238796f, 0.3826832f, 3600);
std::list<WorldObject*> ClusterList;
Trinity::AllWorldObjectsInRange objects(me, 50.0f);
Trinity::WorldObjectListSearcher<Trinity::AllWorldObjectsInRange> searcher(me, ClusterList, objects);
me->VisitNearbyObject(50.0f, searcher);
for (std::list<WorldObject*>::const_iterator itr = ClusterList.begin(); itr != ClusterList.end(); ++itr)
{
if (Player* player = (*itr)->ToPlayer())
{
if (player->GetQuestStatus(QUEST_EXTINGUISHING_THE_IDOL) == QUEST_STATUS_INCOMPLETE)
player->CompleteQuest(QUEST_EXTINGUISHING_THE_IDOL);
}
else if (GameObject* go = (*itr)->ToGameObject())
{
if (go->GetEntry() == GO_IDOL_OVEN_FIRE || go->GetEntry() == GO_IDOL_CUP_FIRE || go->GetEntry() == GO_IDOL_MOUTH_FIRE)
go->Delete();
}
}
instance->SetBossState(DATA_EXTINGUISHING_THE_IDOL, DONE);
me->DespawnOrUnsummon();
break;
}
case EVENT_FIREBALL:
if (me->HasUnitState(UNIT_STATE_CASTING) || !UpdateVictim())
return;
DoCastVictim(SPELL_FIREBALL);
events.ScheduleEvent(EVENT_FIREBALL, 8000);
break;
case EVENT_FROST_NOVA:
if (me->HasUnitState(UNIT_STATE_CASTING) || !UpdateVictim())
return;
DoCast(me, SPELL_FROST_NOVA);
events.ScheduleEvent(EVENT_FROST_NOVA, 15000);
break;
}
}
if (!channeling)
DoMeleeAttackIfReady();
}
private:
InstanceScript* instance;
EventMap events;
bool eventInProgress;
bool channeling;
uint8 eventProgress;
uint8 spawnerCount;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<npc_belnistraszAI>(creature);
}
};
class npc_idol_room_spawner : public CreatureScript
{
public:
npc_idol_room_spawner() : CreatureScript("npc_idol_room_spawner") { }
struct npc_idol_room_spawnerAI : public ScriptedAI
{
npc_idol_room_spawnerAI(Creature* creature) : ScriptedAI(creature)
{
instance = creature->GetInstanceScript();
}
void Reset() override { }
void SetData(uint32 /*type*/, uint32 data) override
{
if (data < 7)
{
me->SummonCreature(NPC_WITHERED_BATTLE_BOAR, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), me->GetOrientation());
if (data > 0 && me->GetOrientation() < 4.0f)
me->SummonCreature(NPC_WITHERED_BATTLE_BOAR, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), me->GetOrientation());
me->SummonCreature(NPC_DEATHS_HEAD_GEOMANCER, me->GetPositionX() + (std::cos(me->GetOrientation() - (float(M_PI) / 2)) * 2), me->GetPositionY() + (std::sin(me->GetOrientation() - (float(M_PI) / 2)) * 2), me->GetPositionZ(), me->GetOrientation());
me->SummonCreature(NPC_WITHERED_QUILGUARD, me->GetPositionX() + (std::cos(me->GetOrientation() + (float(M_PI) / 2)) * 2), me->GetPositionY() + (std::sin(me->GetOrientation() + (float(M_PI) / 2)) * 2), me->GetPositionZ(), me->GetOrientation());
}
else if (data == 7)
me->SummonCreature(NPC_PLAGUEMAW_THE_ROTTING, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), me->GetOrientation());
}
private:
InstanceScript* instance;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<npc_idol_room_spawnerAI>(creature);
}
};
enum TombCreature
{
EVENT_WEB = 7,
SPELL_POISON_PROC = 3616,
SPELL_VIRULENT_POISON_PROC = 12254,
SPELL_WEB = 745
};
class npc_tomb_creature : public CreatureScript
{
public:
npc_tomb_creature() : CreatureScript("npc_tomb_creature") { }
struct npc_tomb_creatureAI : public ScriptedAI
{
npc_tomb_creatureAI(Creature* creature) : ScriptedAI(creature)
{
instance = creature->GetInstanceScript();
}
void Reset() override
{
if (!me->HasAura(SPELL_POISON_PROC) && me->GetEntry() == NPC_TOMB_FIEND)
DoCast(me, SPELL_POISON_PROC);
if (!me->HasAura(SPELL_VIRULENT_POISON_PROC) && me->GetEntry() == NPC_TOMB_REAVER)
DoCast(me, SPELL_VIRULENT_POISON_PROC);
}
void JustDied(Unit* /*killer*/) override
{
instance->SetData(DATA_WAVE, me->GetEntry());
}
void EnterCombat(Unit* /*who*/) override
{
events.ScheduleEvent(EVENT_WEB, urand(5000, 8000));
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_WEB:
DoCastVictim(SPELL_WEB);
events.ScheduleEvent(EVENT_WEB, urand(7000, 16000));
break;
}
}
DoMeleeAttackIfReady();
}
private:
InstanceScript* instance;
EventMap events;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<npc_tomb_creatureAI>(creature);
}
};
/*######
## go_gong
######*/
class go_gong : public GameObjectScript
{
public:
go_gong() : GameObjectScript("go_gong") { }
bool OnGossipHello(Player* /*player*/, GameObject* go) override
{
InstanceScript* instance = go->GetInstanceScript();
if (instance)
{
go->SendCustomAnim(0);
instance->SetData(DATA_WAVE, IN_PROGRESS);
return true;
}
return false;
}
};
void AddSC_razorfen_downs()
{
new npc_belnistrasz();
new npc_idol_room_spawner();
new npc_tomb_creature();
new go_gong();
}
| gpl-2.0 |
pengdonglin137/linux-2.6.24 | fs/xfs/support/ktrace.c | 79 | 7339 | /*
* Copyright (c) 2000-2003,2005 Silicon Graphics, Inc.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <xfs.h>
static kmem_zone_t *ktrace_hdr_zone;
static kmem_zone_t *ktrace_ent_zone;
static int ktrace_zentries;
void
ktrace_init(int zentries)
{
ktrace_zentries = zentries;
ktrace_hdr_zone = kmem_zone_init(sizeof(ktrace_t),
"ktrace_hdr");
ASSERT(ktrace_hdr_zone);
ktrace_ent_zone = kmem_zone_init(ktrace_zentries
* sizeof(ktrace_entry_t),
"ktrace_ent");
ASSERT(ktrace_ent_zone);
}
void
ktrace_uninit(void)
{
kmem_zone_destroy(ktrace_hdr_zone);
kmem_zone_destroy(ktrace_ent_zone);
}
/*
* ktrace_alloc()
*
* Allocate a ktrace header and enough buffering for the given
* number of entries.
*/
ktrace_t *
ktrace_alloc(int nentries, unsigned int __nocast sleep)
{
ktrace_t *ktp;
ktrace_entry_t *ktep;
ktp = (ktrace_t*)kmem_zone_alloc(ktrace_hdr_zone, sleep);
if (ktp == (ktrace_t*)NULL) {
/*
* KM_SLEEP callers don't expect failure.
*/
if (sleep & KM_SLEEP)
panic("ktrace_alloc: NULL memory on KM_SLEEP request!");
return NULL;
}
/*
* Special treatment for buffers with the ktrace_zentries entries
*/
if (nentries == ktrace_zentries) {
ktep = (ktrace_entry_t*)kmem_zone_zalloc(ktrace_ent_zone,
sleep);
} else {
ktep = (ktrace_entry_t*)kmem_zalloc((nentries * sizeof(*ktep)),
sleep | KM_LARGE);
}
if (ktep == NULL) {
/*
* KM_SLEEP callers don't expect failure.
*/
if (sleep & KM_SLEEP)
panic("ktrace_alloc: NULL memory on KM_SLEEP request!");
kmem_free(ktp, sizeof(*ktp));
return NULL;
}
spinlock_init(&(ktp->kt_lock), "kt_lock");
ktp->kt_entries = ktep;
ktp->kt_nentries = nentries;
ktp->kt_index = 0;
ktp->kt_rollover = 0;
return ktp;
}
/*
* ktrace_free()
*
* Free up the ktrace header and buffer. It is up to the caller
* to ensure that no-one is referencing it.
*/
void
ktrace_free(ktrace_t *ktp)
{
int entries_size;
if (ktp == (ktrace_t *)NULL)
return;
spinlock_destroy(&ktp->kt_lock);
/*
* Special treatment for the Vnode trace buffer.
*/
if (ktp->kt_nentries == ktrace_zentries) {
kmem_zone_free(ktrace_ent_zone, ktp->kt_entries);
} else {
entries_size = (int)(ktp->kt_nentries * sizeof(ktrace_entry_t));
kmem_free(ktp->kt_entries, entries_size);
}
kmem_zone_free(ktrace_hdr_zone, ktp);
}
/*
* Enter the given values into the "next" entry in the trace buffer.
* kt_index is always the index of the next entry to be filled.
*/
void
ktrace_enter(
ktrace_t *ktp,
void *val0,
void *val1,
void *val2,
void *val3,
void *val4,
void *val5,
void *val6,
void *val7,
void *val8,
void *val9,
void *val10,
void *val11,
void *val12,
void *val13,
void *val14,
void *val15)
{
static DEFINE_SPINLOCK(wrap_lock);
unsigned long flags;
int index;
ktrace_entry_t *ktep;
ASSERT(ktp != NULL);
/*
* Grab an entry by pushing the index up to the next one.
*/
spin_lock_irqsave(&wrap_lock, flags);
index = ktp->kt_index;
if (++ktp->kt_index == ktp->kt_nentries)
ktp->kt_index = 0;
spin_unlock_irqrestore(&wrap_lock, flags);
if (!ktp->kt_rollover && index == ktp->kt_nentries - 1)
ktp->kt_rollover = 1;
ASSERT((index >= 0) && (index < ktp->kt_nentries));
ktep = &(ktp->kt_entries[index]);
ktep->val[0] = val0;
ktep->val[1] = val1;
ktep->val[2] = val2;
ktep->val[3] = val3;
ktep->val[4] = val4;
ktep->val[5] = val5;
ktep->val[6] = val6;
ktep->val[7] = val7;
ktep->val[8] = val8;
ktep->val[9] = val9;
ktep->val[10] = val10;
ktep->val[11] = val11;
ktep->val[12] = val12;
ktep->val[13] = val13;
ktep->val[14] = val14;
ktep->val[15] = val15;
}
/*
* Return the number of entries in the trace buffer.
*/
int
ktrace_nentries(
ktrace_t *ktp)
{
if (ktp == NULL) {
return 0;
}
return (ktp->kt_rollover ? ktp->kt_nentries : ktp->kt_index);
}
/*
* ktrace_first()
*
* This is used to find the start of the trace buffer.
* In conjunction with ktrace_next() it can be used to
* iterate through the entire trace buffer. This code does
* not do any locking because it is assumed that it is called
* from the debugger.
*
* The caller must pass in a pointer to a ktrace_snap
* structure in which we will keep some state used to
* iterate through the buffer. This state must not touched
* by any code outside of this module.
*/
ktrace_entry_t *
ktrace_first(ktrace_t *ktp, ktrace_snap_t *ktsp)
{
ktrace_entry_t *ktep;
int index;
int nentries;
if (ktp->kt_rollover)
index = ktp->kt_index;
else
index = 0;
ktsp->ks_start = index;
ktep = &(ktp->kt_entries[index]);
nentries = ktrace_nentries(ktp);
index++;
if (index < nentries) {
ktsp->ks_index = index;
} else {
ktsp->ks_index = 0;
if (index > nentries)
ktep = NULL;
}
return ktep;
}
/*
* ktrace_next()
*
* This is used to iterate through the entries of the given
* trace buffer. The caller must pass in the ktrace_snap_t
* structure initialized by ktrace_first(). The return value
* will be either a pointer to the next ktrace_entry or NULL
* if all of the entries have been traversed.
*/
ktrace_entry_t *
ktrace_next(
ktrace_t *ktp,
ktrace_snap_t *ktsp)
{
int index;
ktrace_entry_t *ktep;
index = ktsp->ks_index;
if (index == ktsp->ks_start) {
ktep = NULL;
} else {
ktep = &ktp->kt_entries[index];
}
index++;
if (index == ktrace_nentries(ktp)) {
ktsp->ks_index = 0;
} else {
ktsp->ks_index = index;
}
return ktep;
}
/*
* ktrace_skip()
*
* Skip the next "count" entries and return the entry after that.
* Return NULL if this causes us to iterate past the beginning again.
*/
ktrace_entry_t *
ktrace_skip(
ktrace_t *ktp,
int count,
ktrace_snap_t *ktsp)
{
int index;
int new_index;
ktrace_entry_t *ktep;
int nentries = ktrace_nentries(ktp);
index = ktsp->ks_index;
new_index = index + count;
while (new_index >= nentries) {
new_index -= nentries;
}
if (index == ktsp->ks_start) {
/*
* We've iterated around to the start, so we're done.
*/
ktep = NULL;
} else if ((new_index < index) && (index < ktsp->ks_index)) {
/*
* We've skipped past the start again, so we're done.
*/
ktep = NULL;
ktsp->ks_index = ktsp->ks_start;
} else {
ktep = &(ktp->kt_entries[new_index]);
new_index++;
if (new_index == nentries) {
ktsp->ks_index = 0;
} else {
ktsp->ks_index = new_index;
}
}
return ktep;
}
| gpl-2.0 |
b-man/hp-kernel-tenderloin-ubuntu | drivers/char/agp/amd64-agp.c | 847 | 20465 | /*
* Copyright 2001-2003 SuSE Labs.
* Distributed under the GNU public license, v2.
*
* This is a GART driver for the AMD Opteron/Athlon64 on-CPU northbridge.
* It also includes support for the AMD 8151 AGP bridge,
* although it doesn't actually do much, as all the real
* work is done in the northbridge(s).
*/
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/agp_backend.h>
#include <linux/mmzone.h>
#include <asm/page.h> /* PAGE_SIZE */
#include <asm/e820.h>
#include <asm/k8.h>
#include <asm/gart.h>
#include "agp.h"
/* NVIDIA K8 registers */
#define NVIDIA_X86_64_0_APBASE 0x10
#define NVIDIA_X86_64_1_APBASE1 0x50
#define NVIDIA_X86_64_1_APLIMIT1 0x54
#define NVIDIA_X86_64_1_APSIZE 0xa8
#define NVIDIA_X86_64_1_APBASE2 0xd8
#define NVIDIA_X86_64_1_APLIMIT2 0xdc
/* ULi K8 registers */
#define ULI_X86_64_BASE_ADDR 0x10
#define ULI_X86_64_HTT_FEA_REG 0x50
#define ULI_X86_64_ENU_SCR_REG 0x54
static struct resource *aperture_resource;
static int __initdata agp_try_unsupported = 1;
static int agp_bridges_found;
static void amd64_tlbflush(struct agp_memory *temp)
{
k8_flush_garts();
}
static int amd64_insert_memory(struct agp_memory *mem, off_t pg_start, int type)
{
int i, j, num_entries;
long long tmp;
int mask_type;
struct agp_bridge_data *bridge = mem->bridge;
u32 pte;
num_entries = agp_num_entries();
if (type != mem->type)
return -EINVAL;
mask_type = bridge->driver->agp_type_to_mask_type(bridge, type);
if (mask_type != 0)
return -EINVAL;
/* Make sure we can fit the range in the gatt table. */
/* FIXME: could wrap */
if (((unsigned long)pg_start + mem->page_count) > num_entries)
return -EINVAL;
j = pg_start;
/* gatt table should be empty. */
while (j < (pg_start + mem->page_count)) {
if (!PGE_EMPTY(agp_bridge, readl(agp_bridge->gatt_table+j)))
return -EBUSY;
j++;
}
if (!mem->is_flushed) {
global_cache_flush();
mem->is_flushed = true;
}
for (i = 0, j = pg_start; i < mem->page_count; i++, j++) {
tmp = agp_bridge->driver->mask_memory(agp_bridge,
page_to_phys(mem->pages[i]),
mask_type);
BUG_ON(tmp & 0xffffff0000000ffcULL);
pte = (tmp & 0x000000ff00000000ULL) >> 28;
pte |=(tmp & 0x00000000fffff000ULL);
pte |= GPTE_VALID | GPTE_COHERENT;
writel(pte, agp_bridge->gatt_table+j);
readl(agp_bridge->gatt_table+j); /* PCI Posting. */
}
amd64_tlbflush(mem);
return 0;
}
/*
* This hack alters the order element according
* to the size of a long. It sucks. I totally disown this, even
* though it does appear to work for the most part.
*/
static struct aper_size_info_32 amd64_aperture_sizes[7] =
{
{32, 8192, 3+(sizeof(long)/8), 0 },
{64, 16384, 4+(sizeof(long)/8), 1<<1 },
{128, 32768, 5+(sizeof(long)/8), 1<<2 },
{256, 65536, 6+(sizeof(long)/8), 1<<1 | 1<<2 },
{512, 131072, 7+(sizeof(long)/8), 1<<3 },
{1024, 262144, 8+(sizeof(long)/8), 1<<1 | 1<<3},
{2048, 524288, 9+(sizeof(long)/8), 1<<2 | 1<<3}
};
/*
* Get the current Aperture size from the x86-64.
* Note, that there may be multiple x86-64's, but we just return
* the value from the first one we find. The set_size functions
* keep the rest coherent anyway. Or at least should do.
*/
static int amd64_fetch_size(void)
{
struct pci_dev *dev;
int i;
u32 temp;
struct aper_size_info_32 *values;
dev = k8_northbridges[0];
if (dev==NULL)
return 0;
pci_read_config_dword(dev, AMD64_GARTAPERTURECTL, &temp);
temp = (temp & 0xe);
values = A_SIZE_32(amd64_aperture_sizes);
for (i = 0; i < agp_bridge->driver->num_aperture_sizes; i++) {
if (temp == values[i].size_value) {
agp_bridge->previous_size =
agp_bridge->current_size = (void *) (values + i);
agp_bridge->aperture_size_idx = i;
return values[i].size;
}
}
return 0;
}
/*
* In a multiprocessor x86-64 system, this function gets
* called once for each CPU.
*/
static u64 amd64_configure(struct pci_dev *hammer, u64 gatt_table)
{
u64 aperturebase;
u32 tmp;
u64 aper_base;
/* Address to map to */
pci_read_config_dword(hammer, AMD64_GARTAPERTUREBASE, &tmp);
aperturebase = tmp << 25;
aper_base = (aperturebase & PCI_BASE_ADDRESS_MEM_MASK);
enable_gart_translation(hammer, gatt_table);
return aper_base;
}
static const struct aper_size_info_32 amd_8151_sizes[7] =
{
{2048, 524288, 9, 0x00000000 }, /* 0 0 0 0 0 0 */
{1024, 262144, 8, 0x00000400 }, /* 1 0 0 0 0 0 */
{512, 131072, 7, 0x00000600 }, /* 1 1 0 0 0 0 */
{256, 65536, 6, 0x00000700 }, /* 1 1 1 0 0 0 */
{128, 32768, 5, 0x00000720 }, /* 1 1 1 1 0 0 */
{64, 16384, 4, 0x00000730 }, /* 1 1 1 1 1 0 */
{32, 8192, 3, 0x00000738 } /* 1 1 1 1 1 1 */
};
static int amd_8151_configure(void)
{
unsigned long gatt_bus = virt_to_phys(agp_bridge->gatt_table_real);
int i;
/* Configure AGP regs in each x86-64 host bridge. */
for (i = 0; i < num_k8_northbridges; i++) {
agp_bridge->gart_bus_addr =
amd64_configure(k8_northbridges[i], gatt_bus);
}
k8_flush_garts();
return 0;
}
static void amd64_cleanup(void)
{
u32 tmp;
int i;
for (i = 0; i < num_k8_northbridges; i++) {
struct pci_dev *dev = k8_northbridges[i];
/* disable gart translation */
pci_read_config_dword(dev, AMD64_GARTAPERTURECTL, &tmp);
tmp &= ~AMD64_GARTEN;
pci_write_config_dword(dev, AMD64_GARTAPERTURECTL, tmp);
}
}
static const struct agp_bridge_driver amd_8151_driver = {
.owner = THIS_MODULE,
.aperture_sizes = amd_8151_sizes,
.size_type = U32_APER_SIZE,
.num_aperture_sizes = 7,
.needs_scratch_page = true,
.configure = amd_8151_configure,
.fetch_size = amd64_fetch_size,
.cleanup = amd64_cleanup,
.tlb_flush = amd64_tlbflush,
.mask_memory = agp_generic_mask_memory,
.masks = NULL,
.agp_enable = agp_generic_enable,
.cache_flush = global_cache_flush,
.create_gatt_table = agp_generic_create_gatt_table,
.free_gatt_table = agp_generic_free_gatt_table,
.insert_memory = amd64_insert_memory,
.remove_memory = agp_generic_remove_memory,
.alloc_by_type = agp_generic_alloc_by_type,
.free_by_type = agp_generic_free_by_type,
.agp_alloc_page = agp_generic_alloc_page,
.agp_alloc_pages = agp_generic_alloc_pages,
.agp_destroy_page = agp_generic_destroy_page,
.agp_destroy_pages = agp_generic_destroy_pages,
.agp_type_to_mask_type = agp_generic_type_to_mask_type,
};
/* Some basic sanity checks for the aperture. */
static int __devinit agp_aperture_valid(u64 aper, u32 size)
{
if (!aperture_valid(aper, size, 32*1024*1024))
return 0;
/* Request the Aperture. This catches cases when someone else
already put a mapping in there - happens with some very broken BIOS
Maybe better to use pci_assign_resource/pci_enable_device instead
trusting the bridges? */
if (!aperture_resource &&
!(aperture_resource = request_mem_region(aper, size, "aperture"))) {
printk(KERN_ERR PFX "Aperture conflicts with PCI mapping.\n");
return 0;
}
return 1;
}
/*
* W*s centric BIOS sometimes only set up the aperture in the AGP
* bridge, not the northbridge. On AMD64 this is handled early
* in aperture.c, but when IOMMU is not enabled or we run
* on a 32bit kernel this needs to be redone.
* Unfortunately it is impossible to fix the aperture here because it's too late
* to allocate that much memory. But at least error out cleanly instead of
* crashing.
*/
static __devinit int fix_northbridge(struct pci_dev *nb, struct pci_dev *agp,
u16 cap)
{
u32 aper_low, aper_hi;
u64 aper, nb_aper;
int order = 0;
u32 nb_order, nb_base;
u16 apsize;
pci_read_config_dword(nb, AMD64_GARTAPERTURECTL, &nb_order);
nb_order = (nb_order >> 1) & 7;
pci_read_config_dword(nb, AMD64_GARTAPERTUREBASE, &nb_base);
nb_aper = nb_base << 25;
/* Northbridge seems to contain crap. Try the AGP bridge. */
pci_read_config_word(agp, cap+0x14, &apsize);
if (apsize == 0xffff) {
if (agp_aperture_valid(nb_aper, (32*1024*1024)<<nb_order))
return 0;
return -1;
}
apsize &= 0xfff;
/* Some BIOS use weird encodings not in the AGPv3 table. */
if (apsize & 0xff)
apsize |= 0xf00;
order = 7 - hweight16(apsize);
pci_read_config_dword(agp, 0x10, &aper_low);
pci_read_config_dword(agp, 0x14, &aper_hi);
aper = (aper_low & ~((1<<22)-1)) | ((u64)aper_hi << 32);
/*
* On some sick chips APSIZE is 0. This means it wants 4G
* so let double check that order, and lets trust the AMD NB settings
*/
if (order >=0 && aper + (32ULL<<(20 + order)) > 0x100000000ULL) {
dev_info(&agp->dev, "aperture size %u MB is not right, using settings from NB\n",
32 << order);
order = nb_order;
}
if (nb_order >= order) {
if (agp_aperture_valid(nb_aper, (32*1024*1024)<<nb_order))
return 0;
}
dev_info(&agp->dev, "aperture from AGP @ %Lx size %u MB\n",
aper, 32 << order);
if (order < 0 || !agp_aperture_valid(aper, (32*1024*1024)<<order))
return -1;
pci_write_config_dword(nb, AMD64_GARTAPERTURECTL, order << 1);
pci_write_config_dword(nb, AMD64_GARTAPERTUREBASE, aper >> 25);
return 0;
}
static __devinit int cache_nbs (struct pci_dev *pdev, u32 cap_ptr)
{
int i;
if (cache_k8_northbridges() < 0)
return -ENODEV;
i = 0;
for (i = 0; i < num_k8_northbridges; i++) {
struct pci_dev *dev = k8_northbridges[i];
if (fix_northbridge(dev, pdev, cap_ptr) < 0) {
dev_err(&dev->dev, "no usable aperture found\n");
#ifdef __x86_64__
/* should port this to i386 */
dev_err(&dev->dev, "consider rebooting with iommu=memaper=2 to get a good aperture\n");
#endif
return -1;
}
}
return 0;
}
/* Handle AMD 8151 quirks */
static void __devinit amd8151_init(struct pci_dev *pdev, struct agp_bridge_data *bridge)
{
char *revstring;
switch (pdev->revision) {
case 0x01: revstring="A0"; break;
case 0x02: revstring="A1"; break;
case 0x11: revstring="B0"; break;
case 0x12: revstring="B1"; break;
case 0x13: revstring="B2"; break;
case 0x14: revstring="B3"; break;
default: revstring="??"; break;
}
dev_info(&pdev->dev, "AMD 8151 AGP Bridge rev %s\n", revstring);
/*
* Work around errata.
* Chips before B2 stepping incorrectly reporting v3.5
*/
if (pdev->revision < 0x13) {
dev_info(&pdev->dev, "correcting AGP revision (reports 3.5, is really 3.0)\n");
bridge->major_version = 3;
bridge->minor_version = 0;
}
}
static const struct aper_size_info_32 uli_sizes[7] =
{
{256, 65536, 6, 10},
{128, 32768, 5, 9},
{64, 16384, 4, 8},
{32, 8192, 3, 7},
{16, 4096, 2, 6},
{8, 2048, 1, 4},
{4, 1024, 0, 3}
};
static int __devinit uli_agp_init(struct pci_dev *pdev)
{
u32 httfea,baseaddr,enuscr;
struct pci_dev *dev1;
int i, ret;
unsigned size = amd64_fetch_size();
dev_info(&pdev->dev, "setting up ULi AGP\n");
dev1 = pci_get_slot (pdev->bus,PCI_DEVFN(0,0));
if (dev1 == NULL) {
dev_info(&pdev->dev, "can't find ULi secondary device\n");
return -ENODEV;
}
for (i = 0; i < ARRAY_SIZE(uli_sizes); i++)
if (uli_sizes[i].size == size)
break;
if (i == ARRAY_SIZE(uli_sizes)) {
dev_info(&pdev->dev, "no ULi size found for %d\n", size);
ret = -ENODEV;
goto put;
}
/* shadow x86-64 registers into ULi registers */
pci_read_config_dword (k8_northbridges[0], AMD64_GARTAPERTUREBASE, &httfea);
/* if x86-64 aperture base is beyond 4G, exit here */
if ((httfea & 0x7fff) >> (32 - 25)) {
ret = -ENODEV;
goto put;
}
httfea = (httfea& 0x7fff) << 25;
pci_read_config_dword(pdev, ULI_X86_64_BASE_ADDR, &baseaddr);
baseaddr&= ~PCI_BASE_ADDRESS_MEM_MASK;
baseaddr|= httfea;
pci_write_config_dword(pdev, ULI_X86_64_BASE_ADDR, baseaddr);
enuscr= httfea+ (size * 1024 * 1024) - 1;
pci_write_config_dword(dev1, ULI_X86_64_HTT_FEA_REG, httfea);
pci_write_config_dword(dev1, ULI_X86_64_ENU_SCR_REG, enuscr);
ret = 0;
put:
pci_dev_put(dev1);
return ret;
}
static const struct aper_size_info_32 nforce3_sizes[5] =
{
{512, 131072, 7, 0x00000000 },
{256, 65536, 6, 0x00000008 },
{128, 32768, 5, 0x0000000C },
{64, 16384, 4, 0x0000000E },
{32, 8192, 3, 0x0000000F }
};
/* Handle shadow device of the Nvidia NForce3 */
/* CHECK-ME original 2.4 version set up some IORRs. Check if that is needed. */
static int nforce3_agp_init(struct pci_dev *pdev)
{
u32 tmp, apbase, apbar, aplimit;
struct pci_dev *dev1;
int i, ret;
unsigned size = amd64_fetch_size();
dev_info(&pdev->dev, "setting up Nforce3 AGP\n");
dev1 = pci_get_slot(pdev->bus, PCI_DEVFN(11, 0));
if (dev1 == NULL) {
dev_info(&pdev->dev, "can't find Nforce3 secondary device\n");
return -ENODEV;
}
for (i = 0; i < ARRAY_SIZE(nforce3_sizes); i++)
if (nforce3_sizes[i].size == size)
break;
if (i == ARRAY_SIZE(nforce3_sizes)) {
dev_info(&pdev->dev, "no NForce3 size found for %d\n", size);
ret = -ENODEV;
goto put;
}
pci_read_config_dword(dev1, NVIDIA_X86_64_1_APSIZE, &tmp);
tmp &= ~(0xf);
tmp |= nforce3_sizes[i].size_value;
pci_write_config_dword(dev1, NVIDIA_X86_64_1_APSIZE, tmp);
/* shadow x86-64 registers into NVIDIA registers */
pci_read_config_dword (k8_northbridges[0], AMD64_GARTAPERTUREBASE, &apbase);
/* if x86-64 aperture base is beyond 4G, exit here */
if ( (apbase & 0x7fff) >> (32 - 25) ) {
dev_info(&pdev->dev, "aperture base > 4G\n");
ret = -ENODEV;
goto put;
}
apbase = (apbase & 0x7fff) << 25;
pci_read_config_dword(pdev, NVIDIA_X86_64_0_APBASE, &apbar);
apbar &= ~PCI_BASE_ADDRESS_MEM_MASK;
apbar |= apbase;
pci_write_config_dword(pdev, NVIDIA_X86_64_0_APBASE, apbar);
aplimit = apbase + (size * 1024 * 1024) - 1;
pci_write_config_dword(dev1, NVIDIA_X86_64_1_APBASE1, apbase);
pci_write_config_dword(dev1, NVIDIA_X86_64_1_APLIMIT1, aplimit);
pci_write_config_dword(dev1, NVIDIA_X86_64_1_APBASE2, apbase);
pci_write_config_dword(dev1, NVIDIA_X86_64_1_APLIMIT2, aplimit);
ret = 0;
put:
pci_dev_put(dev1);
return ret;
}
static int __devinit agp_amd64_probe(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct agp_bridge_data *bridge;
u8 cap_ptr;
int err;
/* The Highlander principle */
if (agp_bridges_found)
return -ENODEV;
cap_ptr = pci_find_capability(pdev, PCI_CAP_ID_AGP);
if (!cap_ptr)
return -ENODEV;
/* Could check for AGPv3 here */
bridge = agp_alloc_bridge();
if (!bridge)
return -ENOMEM;
if (pdev->vendor == PCI_VENDOR_ID_AMD &&
pdev->device == PCI_DEVICE_ID_AMD_8151_0) {
amd8151_init(pdev, bridge);
} else {
dev_info(&pdev->dev, "AGP bridge [%04x/%04x]\n",
pdev->vendor, pdev->device);
}
bridge->driver = &amd_8151_driver;
bridge->dev = pdev;
bridge->capndx = cap_ptr;
/* Fill in the mode register */
pci_read_config_dword(pdev, bridge->capndx+PCI_AGP_STATUS, &bridge->mode);
if (cache_nbs(pdev, cap_ptr) == -1) {
agp_put_bridge(bridge);
return -ENODEV;
}
if (pdev->vendor == PCI_VENDOR_ID_NVIDIA) {
int ret = nforce3_agp_init(pdev);
if (ret) {
agp_put_bridge(bridge);
return ret;
}
}
if (pdev->vendor == PCI_VENDOR_ID_AL) {
int ret = uli_agp_init(pdev);
if (ret) {
agp_put_bridge(bridge);
return ret;
}
}
pci_set_drvdata(pdev, bridge);
err = agp_add_bridge(bridge);
if (err < 0)
return err;
agp_bridges_found++;
return 0;
}
static void __devexit agp_amd64_remove(struct pci_dev *pdev)
{
struct agp_bridge_data *bridge = pci_get_drvdata(pdev);
release_mem_region(virt_to_phys(bridge->gatt_table_real),
amd64_aperture_sizes[bridge->aperture_size_idx].size);
agp_remove_bridge(bridge);
agp_put_bridge(bridge);
agp_bridges_found--;
}
#ifdef CONFIG_PM
static int agp_amd64_suspend(struct pci_dev *pdev, pm_message_t state)
{
pci_save_state(pdev);
pci_set_power_state(pdev, pci_choose_state(pdev, state));
return 0;
}
static int agp_amd64_resume(struct pci_dev *pdev)
{
pci_set_power_state(pdev, PCI_D0);
pci_restore_state(pdev);
if (pdev->vendor == PCI_VENDOR_ID_NVIDIA)
nforce3_agp_init(pdev);
return amd_8151_configure();
}
#endif /* CONFIG_PM */
static struct pci_device_id agp_amd64_pci_table[] = {
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_AMD,
.device = PCI_DEVICE_ID_AMD_8151_0,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
/* ULi M1689 */
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_AL,
.device = PCI_DEVICE_ID_AL_M1689,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
/* VIA K8T800Pro */
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_VIA,
.device = PCI_DEVICE_ID_VIA_K8T800PRO_0,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
/* VIA K8T800 */
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_VIA,
.device = PCI_DEVICE_ID_VIA_8385_0,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
/* VIA K8M800 / K8N800 */
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_VIA,
.device = PCI_DEVICE_ID_VIA_8380_0,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
/* VIA K8M890 / K8N890 */
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_VIA,
.device = PCI_DEVICE_ID_VIA_VT3336,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
/* VIA K8T890 */
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_VIA,
.device = PCI_DEVICE_ID_VIA_3238_0,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
/* VIA K8T800/K8M800/K8N800 */
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_VIA,
.device = PCI_DEVICE_ID_VIA_838X_1,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
/* NForce3 */
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_NVIDIA,
.device = PCI_DEVICE_ID_NVIDIA_NFORCE3,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_NVIDIA,
.device = PCI_DEVICE_ID_NVIDIA_NFORCE3S,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
/* SIS 755 */
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_SI,
.device = PCI_DEVICE_ID_SI_755,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
/* SIS 760 */
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_SI,
.device = PCI_DEVICE_ID_SI_760,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
/* ALI/ULI M1695 */
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_AL,
.device = 0x1695,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{ }
};
MODULE_DEVICE_TABLE(pci, agp_amd64_pci_table);
static DEFINE_PCI_DEVICE_TABLE(agp_amd64_pci_promisc_table) = {
{ PCI_DEVICE_CLASS(0, 0) },
{ }
};
static struct pci_driver agp_amd64_pci_driver = {
.name = "agpgart-amd64",
.id_table = agp_amd64_pci_table,
.probe = agp_amd64_probe,
.remove = agp_amd64_remove,
#ifdef CONFIG_PM
.suspend = agp_amd64_suspend,
.resume = agp_amd64_resume,
#endif
};
/* Not static due to IOMMU code calling it early. */
int __init agp_amd64_init(void)
{
int err = 0;
if (agp_off)
return -EINVAL;
err = pci_register_driver(&agp_amd64_pci_driver);
if (err < 0)
return err;
if (agp_bridges_found == 0) {
if (!agp_try_unsupported && !agp_try_unsupported_boot) {
printk(KERN_INFO PFX "No supported AGP bridge found.\n");
#ifdef MODULE
printk(KERN_INFO PFX "You can try agp_try_unsupported=1\n");
#else
printk(KERN_INFO PFX "You can boot with agp=try_unsupported\n");
#endif
return -ENODEV;
}
/* First check that we have at least one AMD64 NB */
if (!pci_dev_present(k8_nb_ids))
return -ENODEV;
/* Look for any AGP bridge */
agp_amd64_pci_driver.id_table = agp_amd64_pci_promisc_table;
err = driver_attach(&agp_amd64_pci_driver.driver);
if (err == 0 && agp_bridges_found == 0)
err = -ENODEV;
}
return err;
}
static int __init agp_amd64_mod_init(void)
{
#ifndef MODULE
if (gart_iommu_aperture)
return agp_bridges_found ? 0 : -ENODEV;
#endif
return agp_amd64_init();
}
static void __exit agp_amd64_cleanup(void)
{
#ifndef MODULE
if (gart_iommu_aperture)
return;
#endif
if (aperture_resource)
release_resource(aperture_resource);
pci_unregister_driver(&agp_amd64_pci_driver);
}
module_init(agp_amd64_mod_init);
module_exit(agp_amd64_cleanup);
MODULE_AUTHOR("Dave Jones <davej@redhat.com>, Andi Kleen");
module_param(agp_try_unsupported, bool, 0);
MODULE_LICENSE("GPL");
| gpl-2.0 |
rkollataj/linux-can-next | arch/sparc/kernel/ebus.c | 2127 | 5959 | /* ebus.c: EBUS DMA library code.
*
* Copyright (C) 1997 Eddie C. Dost (ecd@skynet.be)
* Copyright (C) 1999 David S. Miller (davem@redhat.com)
*/
#include <linux/export.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <asm/ebus_dma.h>
#include <asm/io.h>
#define EBDMA_CSR 0x00UL /* Control/Status */
#define EBDMA_ADDR 0x04UL /* DMA Address */
#define EBDMA_COUNT 0x08UL /* DMA Count */
#define EBDMA_CSR_INT_PEND 0x00000001
#define EBDMA_CSR_ERR_PEND 0x00000002
#define EBDMA_CSR_DRAIN 0x00000004
#define EBDMA_CSR_INT_EN 0x00000010
#define EBDMA_CSR_RESET 0x00000080
#define EBDMA_CSR_WRITE 0x00000100
#define EBDMA_CSR_EN_DMA 0x00000200
#define EBDMA_CSR_CYC_PEND 0x00000400
#define EBDMA_CSR_DIAG_RD_DONE 0x00000800
#define EBDMA_CSR_DIAG_WR_DONE 0x00001000
#define EBDMA_CSR_EN_CNT 0x00002000
#define EBDMA_CSR_TC 0x00004000
#define EBDMA_CSR_DIS_CSR_DRN 0x00010000
#define EBDMA_CSR_BURST_SZ_MASK 0x000c0000
#define EBDMA_CSR_BURST_SZ_1 0x00080000
#define EBDMA_CSR_BURST_SZ_4 0x00000000
#define EBDMA_CSR_BURST_SZ_8 0x00040000
#define EBDMA_CSR_BURST_SZ_16 0x000c0000
#define EBDMA_CSR_DIAG_EN 0x00100000
#define EBDMA_CSR_DIS_ERR_PEND 0x00400000
#define EBDMA_CSR_TCI_DIS 0x00800000
#define EBDMA_CSR_EN_NEXT 0x01000000
#define EBDMA_CSR_DMA_ON 0x02000000
#define EBDMA_CSR_A_LOADED 0x04000000
#define EBDMA_CSR_NA_LOADED 0x08000000
#define EBDMA_CSR_DEV_ID_MASK 0xf0000000
#define EBUS_DMA_RESET_TIMEOUT 10000
static void __ebus_dma_reset(struct ebus_dma_info *p, int no_drain)
{
int i;
u32 val = 0;
writel(EBDMA_CSR_RESET, p->regs + EBDMA_CSR);
udelay(1);
if (no_drain)
return;
for (i = EBUS_DMA_RESET_TIMEOUT; i > 0; i--) {
val = readl(p->regs + EBDMA_CSR);
if (!(val & (EBDMA_CSR_DRAIN | EBDMA_CSR_CYC_PEND)))
break;
udelay(10);
}
}
static irqreturn_t ebus_dma_irq(int irq, void *dev_id)
{
struct ebus_dma_info *p = dev_id;
unsigned long flags;
u32 csr = 0;
spin_lock_irqsave(&p->lock, flags);
csr = readl(p->regs + EBDMA_CSR);
writel(csr, p->regs + EBDMA_CSR);
spin_unlock_irqrestore(&p->lock, flags);
if (csr & EBDMA_CSR_ERR_PEND) {
printk(KERN_CRIT "ebus_dma(%s): DMA error!\n", p->name);
p->callback(p, EBUS_DMA_EVENT_ERROR, p->client_cookie);
return IRQ_HANDLED;
} else if (csr & EBDMA_CSR_INT_PEND) {
p->callback(p,
(csr & EBDMA_CSR_TC) ?
EBUS_DMA_EVENT_DMA : EBUS_DMA_EVENT_DEVICE,
p->client_cookie);
return IRQ_HANDLED;
}
return IRQ_NONE;
}
int ebus_dma_register(struct ebus_dma_info *p)
{
u32 csr;
if (!p->regs)
return -EINVAL;
if (p->flags & ~(EBUS_DMA_FLAG_USE_EBDMA_HANDLER |
EBUS_DMA_FLAG_TCI_DISABLE))
return -EINVAL;
if ((p->flags & EBUS_DMA_FLAG_USE_EBDMA_HANDLER) && !p->callback)
return -EINVAL;
if (!strlen(p->name))
return -EINVAL;
__ebus_dma_reset(p, 1);
csr = EBDMA_CSR_BURST_SZ_16 | EBDMA_CSR_EN_CNT;
if (p->flags & EBUS_DMA_FLAG_TCI_DISABLE)
csr |= EBDMA_CSR_TCI_DIS;
writel(csr, p->regs + EBDMA_CSR);
return 0;
}
EXPORT_SYMBOL(ebus_dma_register);
int ebus_dma_irq_enable(struct ebus_dma_info *p, int on)
{
unsigned long flags;
u32 csr;
if (on) {
if (p->flags & EBUS_DMA_FLAG_USE_EBDMA_HANDLER) {
if (request_irq(p->irq, ebus_dma_irq, IRQF_SHARED, p->name, p))
return -EBUSY;
}
spin_lock_irqsave(&p->lock, flags);
csr = readl(p->regs + EBDMA_CSR);
csr |= EBDMA_CSR_INT_EN;
writel(csr, p->regs + EBDMA_CSR);
spin_unlock_irqrestore(&p->lock, flags);
} else {
spin_lock_irqsave(&p->lock, flags);
csr = readl(p->regs + EBDMA_CSR);
csr &= ~EBDMA_CSR_INT_EN;
writel(csr, p->regs + EBDMA_CSR);
spin_unlock_irqrestore(&p->lock, flags);
if (p->flags & EBUS_DMA_FLAG_USE_EBDMA_HANDLER) {
free_irq(p->irq, p);
}
}
return 0;
}
EXPORT_SYMBOL(ebus_dma_irq_enable);
void ebus_dma_unregister(struct ebus_dma_info *p)
{
unsigned long flags;
u32 csr;
int irq_on = 0;
spin_lock_irqsave(&p->lock, flags);
csr = readl(p->regs + EBDMA_CSR);
if (csr & EBDMA_CSR_INT_EN) {
csr &= ~EBDMA_CSR_INT_EN;
writel(csr, p->regs + EBDMA_CSR);
irq_on = 1;
}
spin_unlock_irqrestore(&p->lock, flags);
if (irq_on)
free_irq(p->irq, p);
}
EXPORT_SYMBOL(ebus_dma_unregister);
int ebus_dma_request(struct ebus_dma_info *p, dma_addr_t bus_addr, size_t len)
{
unsigned long flags;
u32 csr;
int err;
if (len >= (1 << 24))
return -EINVAL;
spin_lock_irqsave(&p->lock, flags);
csr = readl(p->regs + EBDMA_CSR);
err = -EINVAL;
if (!(csr & EBDMA_CSR_EN_DMA))
goto out;
err = -EBUSY;
if (csr & EBDMA_CSR_NA_LOADED)
goto out;
writel(len, p->regs + EBDMA_COUNT);
writel(bus_addr, p->regs + EBDMA_ADDR);
err = 0;
out:
spin_unlock_irqrestore(&p->lock, flags);
return err;
}
EXPORT_SYMBOL(ebus_dma_request);
void ebus_dma_prepare(struct ebus_dma_info *p, int write)
{
unsigned long flags;
u32 csr;
spin_lock_irqsave(&p->lock, flags);
__ebus_dma_reset(p, 0);
csr = (EBDMA_CSR_INT_EN |
EBDMA_CSR_EN_CNT |
EBDMA_CSR_BURST_SZ_16 |
EBDMA_CSR_EN_NEXT);
if (write)
csr |= EBDMA_CSR_WRITE;
if (p->flags & EBUS_DMA_FLAG_TCI_DISABLE)
csr |= EBDMA_CSR_TCI_DIS;
writel(csr, p->regs + EBDMA_CSR);
spin_unlock_irqrestore(&p->lock, flags);
}
EXPORT_SYMBOL(ebus_dma_prepare);
unsigned int ebus_dma_residue(struct ebus_dma_info *p)
{
return readl(p->regs + EBDMA_COUNT);
}
EXPORT_SYMBOL(ebus_dma_residue);
unsigned int ebus_dma_addr(struct ebus_dma_info *p)
{
return readl(p->regs + EBDMA_ADDR);
}
EXPORT_SYMBOL(ebus_dma_addr);
void ebus_dma_enable(struct ebus_dma_info *p, int on)
{
unsigned long flags;
u32 orig_csr, csr;
spin_lock_irqsave(&p->lock, flags);
orig_csr = csr = readl(p->regs + EBDMA_CSR);
if (on)
csr |= EBDMA_CSR_EN_DMA;
else
csr &= ~EBDMA_CSR_EN_DMA;
if ((orig_csr & EBDMA_CSR_EN_DMA) !=
(csr & EBDMA_CSR_EN_DMA))
writel(csr, p->regs + EBDMA_CSR);
spin_unlock_irqrestore(&p->lock, flags);
}
EXPORT_SYMBOL(ebus_dma_enable);
| gpl-2.0 |
ssuthiku/linux | arch/sparc/kernel/ebus.c | 2127 | 5959 | /* ebus.c: EBUS DMA library code.
*
* Copyright (C) 1997 Eddie C. Dost (ecd@skynet.be)
* Copyright (C) 1999 David S. Miller (davem@redhat.com)
*/
#include <linux/export.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <asm/ebus_dma.h>
#include <asm/io.h>
#define EBDMA_CSR 0x00UL /* Control/Status */
#define EBDMA_ADDR 0x04UL /* DMA Address */
#define EBDMA_COUNT 0x08UL /* DMA Count */
#define EBDMA_CSR_INT_PEND 0x00000001
#define EBDMA_CSR_ERR_PEND 0x00000002
#define EBDMA_CSR_DRAIN 0x00000004
#define EBDMA_CSR_INT_EN 0x00000010
#define EBDMA_CSR_RESET 0x00000080
#define EBDMA_CSR_WRITE 0x00000100
#define EBDMA_CSR_EN_DMA 0x00000200
#define EBDMA_CSR_CYC_PEND 0x00000400
#define EBDMA_CSR_DIAG_RD_DONE 0x00000800
#define EBDMA_CSR_DIAG_WR_DONE 0x00001000
#define EBDMA_CSR_EN_CNT 0x00002000
#define EBDMA_CSR_TC 0x00004000
#define EBDMA_CSR_DIS_CSR_DRN 0x00010000
#define EBDMA_CSR_BURST_SZ_MASK 0x000c0000
#define EBDMA_CSR_BURST_SZ_1 0x00080000
#define EBDMA_CSR_BURST_SZ_4 0x00000000
#define EBDMA_CSR_BURST_SZ_8 0x00040000
#define EBDMA_CSR_BURST_SZ_16 0x000c0000
#define EBDMA_CSR_DIAG_EN 0x00100000
#define EBDMA_CSR_DIS_ERR_PEND 0x00400000
#define EBDMA_CSR_TCI_DIS 0x00800000
#define EBDMA_CSR_EN_NEXT 0x01000000
#define EBDMA_CSR_DMA_ON 0x02000000
#define EBDMA_CSR_A_LOADED 0x04000000
#define EBDMA_CSR_NA_LOADED 0x08000000
#define EBDMA_CSR_DEV_ID_MASK 0xf0000000
#define EBUS_DMA_RESET_TIMEOUT 10000
static void __ebus_dma_reset(struct ebus_dma_info *p, int no_drain)
{
int i;
u32 val = 0;
writel(EBDMA_CSR_RESET, p->regs + EBDMA_CSR);
udelay(1);
if (no_drain)
return;
for (i = EBUS_DMA_RESET_TIMEOUT; i > 0; i--) {
val = readl(p->regs + EBDMA_CSR);
if (!(val & (EBDMA_CSR_DRAIN | EBDMA_CSR_CYC_PEND)))
break;
udelay(10);
}
}
static irqreturn_t ebus_dma_irq(int irq, void *dev_id)
{
struct ebus_dma_info *p = dev_id;
unsigned long flags;
u32 csr = 0;
spin_lock_irqsave(&p->lock, flags);
csr = readl(p->regs + EBDMA_CSR);
writel(csr, p->regs + EBDMA_CSR);
spin_unlock_irqrestore(&p->lock, flags);
if (csr & EBDMA_CSR_ERR_PEND) {
printk(KERN_CRIT "ebus_dma(%s): DMA error!\n", p->name);
p->callback(p, EBUS_DMA_EVENT_ERROR, p->client_cookie);
return IRQ_HANDLED;
} else if (csr & EBDMA_CSR_INT_PEND) {
p->callback(p,
(csr & EBDMA_CSR_TC) ?
EBUS_DMA_EVENT_DMA : EBUS_DMA_EVENT_DEVICE,
p->client_cookie);
return IRQ_HANDLED;
}
return IRQ_NONE;
}
int ebus_dma_register(struct ebus_dma_info *p)
{
u32 csr;
if (!p->regs)
return -EINVAL;
if (p->flags & ~(EBUS_DMA_FLAG_USE_EBDMA_HANDLER |
EBUS_DMA_FLAG_TCI_DISABLE))
return -EINVAL;
if ((p->flags & EBUS_DMA_FLAG_USE_EBDMA_HANDLER) && !p->callback)
return -EINVAL;
if (!strlen(p->name))
return -EINVAL;
__ebus_dma_reset(p, 1);
csr = EBDMA_CSR_BURST_SZ_16 | EBDMA_CSR_EN_CNT;
if (p->flags & EBUS_DMA_FLAG_TCI_DISABLE)
csr |= EBDMA_CSR_TCI_DIS;
writel(csr, p->regs + EBDMA_CSR);
return 0;
}
EXPORT_SYMBOL(ebus_dma_register);
int ebus_dma_irq_enable(struct ebus_dma_info *p, int on)
{
unsigned long flags;
u32 csr;
if (on) {
if (p->flags & EBUS_DMA_FLAG_USE_EBDMA_HANDLER) {
if (request_irq(p->irq, ebus_dma_irq, IRQF_SHARED, p->name, p))
return -EBUSY;
}
spin_lock_irqsave(&p->lock, flags);
csr = readl(p->regs + EBDMA_CSR);
csr |= EBDMA_CSR_INT_EN;
writel(csr, p->regs + EBDMA_CSR);
spin_unlock_irqrestore(&p->lock, flags);
} else {
spin_lock_irqsave(&p->lock, flags);
csr = readl(p->regs + EBDMA_CSR);
csr &= ~EBDMA_CSR_INT_EN;
writel(csr, p->regs + EBDMA_CSR);
spin_unlock_irqrestore(&p->lock, flags);
if (p->flags & EBUS_DMA_FLAG_USE_EBDMA_HANDLER) {
free_irq(p->irq, p);
}
}
return 0;
}
EXPORT_SYMBOL(ebus_dma_irq_enable);
void ebus_dma_unregister(struct ebus_dma_info *p)
{
unsigned long flags;
u32 csr;
int irq_on = 0;
spin_lock_irqsave(&p->lock, flags);
csr = readl(p->regs + EBDMA_CSR);
if (csr & EBDMA_CSR_INT_EN) {
csr &= ~EBDMA_CSR_INT_EN;
writel(csr, p->regs + EBDMA_CSR);
irq_on = 1;
}
spin_unlock_irqrestore(&p->lock, flags);
if (irq_on)
free_irq(p->irq, p);
}
EXPORT_SYMBOL(ebus_dma_unregister);
int ebus_dma_request(struct ebus_dma_info *p, dma_addr_t bus_addr, size_t len)
{
unsigned long flags;
u32 csr;
int err;
if (len >= (1 << 24))
return -EINVAL;
spin_lock_irqsave(&p->lock, flags);
csr = readl(p->regs + EBDMA_CSR);
err = -EINVAL;
if (!(csr & EBDMA_CSR_EN_DMA))
goto out;
err = -EBUSY;
if (csr & EBDMA_CSR_NA_LOADED)
goto out;
writel(len, p->regs + EBDMA_COUNT);
writel(bus_addr, p->regs + EBDMA_ADDR);
err = 0;
out:
spin_unlock_irqrestore(&p->lock, flags);
return err;
}
EXPORT_SYMBOL(ebus_dma_request);
void ebus_dma_prepare(struct ebus_dma_info *p, int write)
{
unsigned long flags;
u32 csr;
spin_lock_irqsave(&p->lock, flags);
__ebus_dma_reset(p, 0);
csr = (EBDMA_CSR_INT_EN |
EBDMA_CSR_EN_CNT |
EBDMA_CSR_BURST_SZ_16 |
EBDMA_CSR_EN_NEXT);
if (write)
csr |= EBDMA_CSR_WRITE;
if (p->flags & EBUS_DMA_FLAG_TCI_DISABLE)
csr |= EBDMA_CSR_TCI_DIS;
writel(csr, p->regs + EBDMA_CSR);
spin_unlock_irqrestore(&p->lock, flags);
}
EXPORT_SYMBOL(ebus_dma_prepare);
unsigned int ebus_dma_residue(struct ebus_dma_info *p)
{
return readl(p->regs + EBDMA_COUNT);
}
EXPORT_SYMBOL(ebus_dma_residue);
unsigned int ebus_dma_addr(struct ebus_dma_info *p)
{
return readl(p->regs + EBDMA_ADDR);
}
EXPORT_SYMBOL(ebus_dma_addr);
void ebus_dma_enable(struct ebus_dma_info *p, int on)
{
unsigned long flags;
u32 orig_csr, csr;
spin_lock_irqsave(&p->lock, flags);
orig_csr = csr = readl(p->regs + EBDMA_CSR);
if (on)
csr |= EBDMA_CSR_EN_DMA;
else
csr &= ~EBDMA_CSR_EN_DMA;
if ((orig_csr & EBDMA_CSR_EN_DMA) !=
(csr & EBDMA_CSR_EN_DMA))
writel(csr, p->regs + EBDMA_CSR);
spin_unlock_irqrestore(&p->lock, flags);
}
EXPORT_SYMBOL(ebus_dma_enable);
| gpl-2.0 |
dhiru1602/android_kernel_samsung_latona | drivers/media/rc/redrat3.c | 2383 | 35620 | /*
* USB RedRat3 IR Transceiver rc-core driver
*
* Copyright (c) 2011 by Jarod Wilson <jarod@redhat.com>
* based heavily on the work of Stephen Cox, with additional
* help from RedRat Ltd.
*
* This driver began life based an an old version of the first-generation
* lirc_mceusb driver from the lirc 0.7.2 distribution. It was then
* significantly rewritten by Stephen Cox with the aid of RedRat Ltd's
* Chris Dodge.
*
* The driver was then ported to rc-core and significantly rewritten again,
* by Jarod, using the in-kernel mceusb driver as a guide, after an initial
* port effort was started by Stephen.
*
* TODO LIST:
* - fix lirc not showing repeats properly
* --
*
* The RedRat3 is a USB transceiver with both send & receive,
* with 2 separate sensors available for receive to enable
* both good long range reception for general use, and good
* short range reception when required for learning a signal.
*
* http://www.redrat.co.uk/
*
* It uses its own little protocol to communicate, the required
* parts of which are embedded within this driver.
* --
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/device.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/usb.h>
#include <linux/usb/input.h>
#include <media/rc-core.h>
/* Driver Information */
#define DRIVER_VERSION "0.70"
#define DRIVER_AUTHOR "Jarod Wilson <jarod@redhat.com>"
#define DRIVER_AUTHOR2 "The Dweller, Stephen Cox"
#define DRIVER_DESC "RedRat3 USB IR Transceiver Driver"
#define DRIVER_NAME "redrat3"
/* module parameters */
#ifdef CONFIG_USB_DEBUG
static int debug = 1;
#else
static int debug;
#endif
#define RR3_DEBUG_STANDARD 0x1
#define RR3_DEBUG_FUNCTION_TRACE 0x2
#define rr3_dbg(dev, fmt, ...) \
do { \
if (debug & RR3_DEBUG_STANDARD) \
dev_info(dev, fmt, ## __VA_ARGS__); \
} while (0)
#define rr3_ftr(dev, fmt, ...) \
do { \
if (debug & RR3_DEBUG_FUNCTION_TRACE) \
dev_info(dev, fmt, ## __VA_ARGS__); \
} while (0)
/* bulk data transfer types */
#define RR3_ERROR 0x01
#define RR3_MOD_SIGNAL_IN 0x20
#define RR3_MOD_SIGNAL_OUT 0x21
/* Get the RR firmware version */
#define RR3_FW_VERSION 0xb1
#define RR3_FW_VERSION_LEN 64
/* Send encoded signal bulk-sent earlier*/
#define RR3_TX_SEND_SIGNAL 0xb3
#define RR3_SET_IR_PARAM 0xb7
#define RR3_GET_IR_PARAM 0xb8
/* Blink the red LED on the device */
#define RR3_BLINK_LED 0xb9
/* Read serial number of device */
#define RR3_READ_SER_NO 0xba
#define RR3_SER_NO_LEN 4
/* Start capture with the RC receiver */
#define RR3_RC_DET_ENABLE 0xbb
/* Stop capture with the RC receiver */
#define RR3_RC_DET_DISABLE 0xbc
/* Return the status of RC detector capture */
#define RR3_RC_DET_STATUS 0xbd
/* Reset redrat */
#define RR3_RESET 0xa0
/* Max number of lengths in the signal. */
#define RR3_IR_IO_MAX_LENGTHS 0x01
/* Periods to measure mod. freq. */
#define RR3_IR_IO_PERIODS_MF 0x02
/* Size of memory for main signal data */
#define RR3_IR_IO_SIG_MEM_SIZE 0x03
/* Delta value when measuring lengths */
#define RR3_IR_IO_LENGTH_FUZZ 0x04
/* Timeout for end of signal detection */
#define RR3_IR_IO_SIG_TIMEOUT 0x05
/* Minumum value for pause recognition. */
#define RR3_IR_IO_MIN_PAUSE 0x06
/* Clock freq. of EZ-USB chip */
#define RR3_CLK 24000000
/* Clock periods per timer count */
#define RR3_CLK_PER_COUNT 12
/* (RR3_CLK / RR3_CLK_PER_COUNT) */
#define RR3_CLK_CONV_FACTOR 2000000
/* USB bulk-in IR data endpoint address */
#define RR3_BULK_IN_EP_ADDR 0x82
/* Raw Modulated signal data value offsets */
#define RR3_PAUSE_OFFSET 0
#define RR3_FREQ_COUNT_OFFSET 4
#define RR3_NUM_PERIOD_OFFSET 6
#define RR3_MAX_LENGTHS_OFFSET 8
#define RR3_NUM_LENGTHS_OFFSET 9
#define RR3_MAX_SIGS_OFFSET 10
#define RR3_NUM_SIGS_OFFSET 12
#define RR3_REPEATS_OFFSET 14
/* Size of the fixed-length portion of the signal */
#define RR3_HEADER_LENGTH 15
#define RR3_DRIVER_MAXLENS 128
#define RR3_MAX_SIG_SIZE 512
#define RR3_MAX_BUF_SIZE \
((2 * RR3_HEADER_LENGTH) + RR3_DRIVER_MAXLENS + RR3_MAX_SIG_SIZE)
#define RR3_TIME_UNIT 50
#define RR3_END_OF_SIGNAL 0x7f
#define RR3_TX_HEADER_OFFSET 4
#define RR3_TX_TRAILER_LEN 2
#define RR3_RX_MIN_TIMEOUT 5
#define RR3_RX_MAX_TIMEOUT 2000
/* The 8051's CPUCS Register address */
#define RR3_CPUCS_REG_ADDR 0x7f92
#define USB_RR3USB_VENDOR_ID 0x112a
#define USB_RR3USB_PRODUCT_ID 0x0001
#define USB_RR3IIUSB_PRODUCT_ID 0x0005
/* table of devices that work with this driver */
static struct usb_device_id redrat3_dev_table[] = {
/* Original version of the RedRat3 */
{USB_DEVICE(USB_RR3USB_VENDOR_ID, USB_RR3USB_PRODUCT_ID)},
/* Second Version/release of the RedRat3 - RetRat3-II */
{USB_DEVICE(USB_RR3USB_VENDOR_ID, USB_RR3IIUSB_PRODUCT_ID)},
{} /* Terminating entry */
};
/* Structure to hold all of our device specific stuff */
struct redrat3_dev {
/* core device bits */
struct rc_dev *rc;
struct device *dev;
/* save off the usb device pointer */
struct usb_device *udev;
/* the receive endpoint */
struct usb_endpoint_descriptor *ep_in;
/* the buffer to receive data */
unsigned char *bulk_in_buf;
/* urb used to read ir data */
struct urb *read_urb;
/* the send endpoint */
struct usb_endpoint_descriptor *ep_out;
/* the buffer to send data */
unsigned char *bulk_out_buf;
/* the urb used to send data */
struct urb *write_urb;
/* usb dma */
dma_addr_t dma_in;
dma_addr_t dma_out;
/* true if write urb is busy */
bool write_busy;
/* wait for the write to finish */
struct completion write_finished;
/* locks this structure */
struct mutex lock;
/* rx signal timeout timer */
struct timer_list rx_timeout;
/* Is the device currently receiving? */
bool recv_in_progress;
/* is the detector enabled*/
bool det_enabled;
/* Is the device currently transmitting?*/
bool transmitting;
/* store for current packet */
char pbuf[RR3_MAX_BUF_SIZE];
u16 pktlen;
u16 pkttype;
u16 bytes_read;
/* indicate whether we are going to reprocess
* the USB callback with a bigger buffer */
int buftoosmall;
char *datap;
u32 carrier;
char name[128];
char phys[64];
};
/* All incoming data buffers adhere to a very specific data format */
struct redrat3_signal_header {
u16 length; /* Length of data being transferred */
u16 transfer_type; /* Type of data transferred */
u32 pause; /* Pause between main and repeat signals */
u16 mod_freq_count; /* Value of timer on mod. freq. measurement */
u16 no_periods; /* No. of periods over which mod. freq. is measured */
u8 max_lengths; /* Max no. of lengths (i.e. size of array) */
u8 no_lengths; /* Actual no. of elements in lengths array */
u16 max_sig_size; /* Max no. of values in signal data array */
u16 sig_size; /* Acuto no. of values in signal data array */
u8 no_repeats; /* No. of repeats of repeat signal section */
/* Here forward is the lengths and signal data */
};
static void redrat3_dump_signal_header(struct redrat3_signal_header *header)
{
pr_info("%s:\n", __func__);
pr_info(" * length: %u, transfer_type: 0x%02x\n",
header->length, header->transfer_type);
pr_info(" * pause: %u, freq_count: %u, no_periods: %u\n",
header->pause, header->mod_freq_count, header->no_periods);
pr_info(" * lengths: %u (max: %u)\n",
header->no_lengths, header->max_lengths);
pr_info(" * sig_size: %u (max: %u)\n",
header->sig_size, header->max_sig_size);
pr_info(" * repeats: %u\n", header->no_repeats);
}
static void redrat3_dump_signal_data(char *buffer, u16 len)
{
int offset, i;
char *data_vals;
pr_info("%s:", __func__);
offset = RR3_TX_HEADER_OFFSET + RR3_HEADER_LENGTH
+ (RR3_DRIVER_MAXLENS * sizeof(u16));
/* read RR3_DRIVER_MAXLENS from ctrl msg */
data_vals = buffer + offset;
for (i = 0; i < len; i++) {
if (i % 10 == 0)
pr_cont("\n * ");
pr_cont("%02x ", *data_vals++);
}
pr_cont("\n");
}
/*
* redrat3_issue_async
*
* Issues an async read to the ir data in port..
* sets the callback to be redrat3_handle_async
*/
static void redrat3_issue_async(struct redrat3_dev *rr3)
{
int res;
rr3_ftr(rr3->dev, "Entering %s\n", __func__);
if (!rr3->det_enabled) {
dev_warn(rr3->dev, "not issuing async read, "
"detector not enabled\n");
return;
}
memset(rr3->bulk_in_buf, 0, rr3->ep_in->wMaxPacketSize);
res = usb_submit_urb(rr3->read_urb, GFP_ATOMIC);
if (res)
rr3_dbg(rr3->dev, "%s: receive request FAILED! "
"(res %d, len %d)\n", __func__, res,
rr3->read_urb->transfer_buffer_length);
}
static void redrat3_dump_fw_error(struct redrat3_dev *rr3, int code)
{
if (!rr3->transmitting && (code != 0x40))
dev_info(rr3->dev, "fw error code 0x%02x: ", code);
switch (code) {
case 0x00:
pr_cont("No Error\n");
break;
/* Codes 0x20 through 0x2f are IR Firmware Errors */
case 0x20:
pr_cont("Initial signal pulse not long enough "
"to measure carrier frequency\n");
break;
case 0x21:
pr_cont("Not enough length values allocated for signal\n");
break;
case 0x22:
pr_cont("Not enough memory allocated for signal data\n");
break;
case 0x23:
pr_cont("Too many signal repeats\n");
break;
case 0x28:
pr_cont("Insufficient memory available for IR signal "
"data memory allocation\n");
break;
case 0x29:
pr_cont("Insufficient memory available "
"for IrDa signal data memory allocation\n");
break;
/* Codes 0x30 through 0x3f are USB Firmware Errors */
case 0x30:
pr_cont("Insufficient memory available for bulk "
"transfer structure\n");
break;
/*
* Other error codes... These are primarily errors that can occur in
* the control messages sent to the redrat
*/
case 0x40:
if (!rr3->transmitting)
pr_cont("Signal capture has been terminated\n");
break;
case 0x41:
pr_cont("Attempt to set/get and unknown signal I/O "
"algorithm parameter\n");
break;
case 0x42:
pr_cont("Signal capture already started\n");
break;
default:
pr_cont("Unknown Error\n");
break;
}
}
static u32 redrat3_val_to_mod_freq(struct redrat3_signal_header *ph)
{
u32 mod_freq = 0;
if (ph->mod_freq_count != 0)
mod_freq = (RR3_CLK * ph->no_periods) /
(ph->mod_freq_count * RR3_CLK_PER_COUNT);
return mod_freq;
}
/* this function scales down the figures for the same result... */
static u32 redrat3_len_to_us(u32 length)
{
u32 biglen = length * 1000;
u32 divisor = (RR3_CLK_CONV_FACTOR) / 1000;
u32 result = (u32) (biglen / divisor);
/* don't allow zero lengths to go back, breaks lirc */
return result ? result : 1;
}
/*
* convert us back into redrat3 lengths
*
* length * 1000 length * 1000000
* ------------- = ---------------- = micro
* rr3clk / 1000 rr3clk
* 6 * 2 4 * 3 micro * rr3clk micro * rr3clk / 1000
* ----- = 4 ----- = 6 -------------- = len ---------------------
* 3 2 1000000 1000
*/
static u32 redrat3_us_to_len(u32 microsec)
{
u32 result;
u32 divisor;
microsec &= IR_MAX_DURATION;
divisor = (RR3_CLK_CONV_FACTOR / 1000);
result = (u32)(microsec * divisor) / 1000;
/* don't allow zero lengths to go back, breaks lirc */
return result ? result : 1;
}
/* timer callback to send long trailing space on receive timeout */
static void redrat3_rx_timeout(unsigned long data)
{
struct redrat3_dev *rr3 = (struct redrat3_dev *)data;
DEFINE_IR_RAW_EVENT(rawir);
rawir.pulse = false;
rawir.duration = rr3->rc->timeout;
rr3_dbg(rr3->dev, "storing trailing space with duration %d\n",
rawir.duration);
ir_raw_event_store_with_filter(rr3->rc, &rawir);
rr3_dbg(rr3->dev, "calling ir_raw_event_handle\n");
ir_raw_event_handle(rr3->rc);
rr3_dbg(rr3->dev, "calling ir_raw_event_reset\n");
ir_raw_event_reset(rr3->rc);
}
static void redrat3_process_ir_data(struct redrat3_dev *rr3)
{
DEFINE_IR_RAW_EVENT(rawir);
struct redrat3_signal_header header;
struct device *dev;
int i;
unsigned long delay;
u32 mod_freq, single_len;
u16 *len_vals;
u8 *data_vals;
u32 tmp32;
u16 tmp16;
char *sig_data;
if (!rr3) {
pr_err("%s called with no context!\n", __func__);
return;
}
rr3_ftr(rr3->dev, "Entered %s\n", __func__);
dev = rr3->dev;
sig_data = rr3->pbuf;
header.length = rr3->pktlen;
header.transfer_type = rr3->pkttype;
/* Sanity check */
if (!(header.length >= RR3_HEADER_LENGTH))
dev_warn(dev, "read returned less than rr3 header len\n");
delay = usecs_to_jiffies(rr3->rc->timeout / 1000);
mod_timer(&rr3->rx_timeout, jiffies + delay);
memcpy(&tmp32, sig_data + RR3_PAUSE_OFFSET, sizeof(tmp32));
header.pause = be32_to_cpu(tmp32);
memcpy(&tmp16, sig_data + RR3_FREQ_COUNT_OFFSET, sizeof(tmp16));
header.mod_freq_count = be16_to_cpu(tmp16);
memcpy(&tmp16, sig_data + RR3_NUM_PERIOD_OFFSET, sizeof(tmp16));
header.no_periods = be16_to_cpu(tmp16);
header.max_lengths = sig_data[RR3_MAX_LENGTHS_OFFSET];
header.no_lengths = sig_data[RR3_NUM_LENGTHS_OFFSET];
memcpy(&tmp16, sig_data + RR3_MAX_SIGS_OFFSET, sizeof(tmp16));
header.max_sig_size = be16_to_cpu(tmp16);
memcpy(&tmp16, sig_data + RR3_NUM_SIGS_OFFSET, sizeof(tmp16));
header.sig_size = be16_to_cpu(tmp16);
header.no_repeats= sig_data[RR3_REPEATS_OFFSET];
if (debug) {
redrat3_dump_signal_header(&header);
redrat3_dump_signal_data(sig_data, header.sig_size);
}
mod_freq = redrat3_val_to_mod_freq(&header);
rr3_dbg(dev, "Got mod_freq of %u\n", mod_freq);
/* Here we pull out the 'length' values from the signal */
len_vals = (u16 *)(sig_data + RR3_HEADER_LENGTH);
data_vals = sig_data + RR3_HEADER_LENGTH +
(header.max_lengths * sizeof(u16));
/* process each rr3 encoded byte into an int */
for (i = 0; i < header.sig_size; i++) {
u16 val = len_vals[data_vals[i]];
single_len = redrat3_len_to_us((u32)be16_to_cpu(val));
/* cap the value to IR_MAX_DURATION */
single_len &= IR_MAX_DURATION;
/* we should always get pulse/space/pulse/space samples */
if (i % 2)
rawir.pulse = false;
else
rawir.pulse = true;
rawir.duration = US_TO_NS(single_len);
rr3_dbg(dev, "storing %s with duration %d (i: %d)\n",
rawir.pulse ? "pulse" : "space", rawir.duration, i);
ir_raw_event_store_with_filter(rr3->rc, &rawir);
}
/* add a trailing space, if need be */
if (i % 2) {
rawir.pulse = false;
/* this duration is made up, and may not be ideal... */
rawir.duration = rr3->rc->timeout / 2;
rr3_dbg(dev, "storing trailing space with duration %d\n",
rawir.duration);
ir_raw_event_store_with_filter(rr3->rc, &rawir);
}
rr3_dbg(dev, "calling ir_raw_event_handle\n");
ir_raw_event_handle(rr3->rc);
return;
}
/* Util fn to send rr3 cmds */
static u8 redrat3_send_cmd(int cmd, struct redrat3_dev *rr3)
{
struct usb_device *udev;
u8 *data;
int res;
data = kzalloc(sizeof(u8), GFP_KERNEL);
if (!data)
return -ENOMEM;
udev = rr3->udev;
res = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), cmd,
USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
0x0000, 0x0000, data, sizeof(u8), HZ * 10);
if (res < 0) {
dev_err(rr3->dev, "%s: Error sending rr3 cmd res %d, data %d",
__func__, res, *data);
res = -EIO;
} else
res = (u8)data[0];
kfree(data);
return res;
}
/* Enables the long range detector and starts async receive */
static int redrat3_enable_detector(struct redrat3_dev *rr3)
{
struct device *dev = rr3->dev;
u8 ret;
rr3_ftr(dev, "Entering %s\n", __func__);
ret = redrat3_send_cmd(RR3_RC_DET_ENABLE, rr3);
if (ret != 0)
dev_dbg(dev, "%s: unexpected ret of %d\n",
__func__, ret);
ret = redrat3_send_cmd(RR3_RC_DET_STATUS, rr3);
if (ret != 1) {
dev_err(dev, "%s: detector status: %d, should be 1\n",
__func__, ret);
return -EIO;
}
rr3->det_enabled = true;
redrat3_issue_async(rr3);
return 0;
}
/* Disables the rr3 long range detector */
static void redrat3_disable_detector(struct redrat3_dev *rr3)
{
struct device *dev = rr3->dev;
u8 ret;
rr3_ftr(dev, "Entering %s\n", __func__);
ret = redrat3_send_cmd(RR3_RC_DET_DISABLE, rr3);
if (ret != 0)
dev_err(dev, "%s: failure!\n", __func__);
ret = redrat3_send_cmd(RR3_RC_DET_STATUS, rr3);
if (ret != 0)
dev_warn(dev, "%s: detector status: %d, should be 0\n",
__func__, ret);
rr3->det_enabled = false;
}
static inline void redrat3_delete(struct redrat3_dev *rr3,
struct usb_device *udev)
{
rr3_ftr(rr3->dev, "%s cleaning up\n", __func__);
usb_kill_urb(rr3->read_urb);
usb_kill_urb(rr3->write_urb);
usb_free_urb(rr3->read_urb);
usb_free_urb(rr3->write_urb);
usb_free_coherent(udev, rr3->ep_in->wMaxPacketSize,
rr3->bulk_in_buf, rr3->dma_in);
usb_free_coherent(udev, rr3->ep_out->wMaxPacketSize,
rr3->bulk_out_buf, rr3->dma_out);
kfree(rr3);
}
static u32 redrat3_get_timeout(struct device *dev,
struct rc_dev *rc, struct usb_device *udev)
{
u32 *tmp;
u32 timeout = MS_TO_NS(150); /* a sane default, if things go haywire */
int len, ret, pipe;
len = sizeof(*tmp);
tmp = kzalloc(len, GFP_KERNEL);
if (!tmp) {
dev_warn(dev, "Memory allocation faillure\n");
return timeout;
}
pipe = usb_rcvctrlpipe(udev, 0);
ret = usb_control_msg(udev, pipe, RR3_GET_IR_PARAM,
USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
RR3_IR_IO_SIG_TIMEOUT, 0, tmp, len, HZ * 5);
if (ret != len) {
dev_warn(dev, "Failed to read timeout from hardware\n");
return timeout;
}
timeout = US_TO_NS(redrat3_len_to_us(be32_to_cpu(*tmp)));
if (timeout < rc->min_timeout)
timeout = rc->min_timeout;
else if (timeout > rc->max_timeout)
timeout = rc->max_timeout;
rr3_dbg(dev, "Got timeout of %d ms\n", timeout / (1000 * 1000));
return timeout;
}
static void redrat3_reset(struct redrat3_dev *rr3)
{
struct usb_device *udev = rr3->udev;
struct device *dev = rr3->dev;
int rc, rxpipe, txpipe;
u8 *val;
int len = sizeof(u8);
rr3_ftr(dev, "Entering %s\n", __func__);
rxpipe = usb_rcvctrlpipe(udev, 0);
txpipe = usb_sndctrlpipe(udev, 0);
val = kzalloc(len, GFP_KERNEL);
if (!val) {
dev_err(dev, "Memory allocation failure\n");
return;
}
*val = 0x01;
rc = usb_control_msg(udev, rxpipe, RR3_RESET,
USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
RR3_CPUCS_REG_ADDR, 0, val, len, HZ * 25);
rr3_dbg(dev, "reset returned 0x%02x\n", rc);
*val = 5;
rc = usb_control_msg(udev, txpipe, RR3_SET_IR_PARAM,
USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_OUT,
RR3_IR_IO_LENGTH_FUZZ, 0, val, len, HZ * 25);
rr3_dbg(dev, "set ir parm len fuzz %d rc 0x%02x\n", *val, rc);
*val = RR3_DRIVER_MAXLENS;
rc = usb_control_msg(udev, txpipe, RR3_SET_IR_PARAM,
USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_OUT,
RR3_IR_IO_MAX_LENGTHS, 0, val, len, HZ * 25);
rr3_dbg(dev, "set ir parm max lens %d rc 0x%02x\n", *val, rc);
kfree(val);
}
static void redrat3_get_firmware_rev(struct redrat3_dev *rr3)
{
int rc = 0;
char *buffer;
rr3_ftr(rr3->dev, "Entering %s\n", __func__);
buffer = kzalloc(sizeof(char) * (RR3_FW_VERSION_LEN + 1), GFP_KERNEL);
if (!buffer) {
dev_err(rr3->dev, "Memory allocation failure\n");
return;
}
rc = usb_control_msg(rr3->udev, usb_rcvctrlpipe(rr3->udev, 0),
RR3_FW_VERSION,
USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
0, 0, buffer, RR3_FW_VERSION_LEN, HZ * 5);
if (rc >= 0)
dev_info(rr3->dev, "Firmware rev: %s", buffer);
else
dev_err(rr3->dev, "Problem fetching firmware ID\n");
kfree(buffer);
rr3_ftr(rr3->dev, "Exiting %s\n", __func__);
}
static void redrat3_read_packet_start(struct redrat3_dev *rr3, int len)
{
u16 tx_error;
u16 hdrlen;
rr3_ftr(rr3->dev, "Entering %s\n", __func__);
/* grab the Length and type of transfer */
memcpy(&(rr3->pktlen), (unsigned char *) rr3->bulk_in_buf,
sizeof(rr3->pktlen));
memcpy(&(rr3->pkttype), ((unsigned char *) rr3->bulk_in_buf +
sizeof(rr3->pktlen)),
sizeof(rr3->pkttype));
/*data needs conversion to know what its real values are*/
rr3->pktlen = be16_to_cpu(rr3->pktlen);
rr3->pkttype = be16_to_cpu(rr3->pkttype);
switch (rr3->pkttype) {
case RR3_ERROR:
memcpy(&tx_error, ((unsigned char *)rr3->bulk_in_buf
+ (sizeof(rr3->pktlen) + sizeof(rr3->pkttype))),
sizeof(tx_error));
tx_error = be16_to_cpu(tx_error);
redrat3_dump_fw_error(rr3, tx_error);
break;
case RR3_MOD_SIGNAL_IN:
hdrlen = sizeof(rr3->pktlen) + sizeof(rr3->pkttype);
rr3->bytes_read = len;
rr3->bytes_read -= hdrlen;
rr3->datap = &(rr3->pbuf[0]);
memcpy(rr3->datap, ((unsigned char *)rr3->bulk_in_buf + hdrlen),
rr3->bytes_read);
rr3->datap += rr3->bytes_read;
rr3_dbg(rr3->dev, "bytes_read %d, pktlen %d\n",
rr3->bytes_read, rr3->pktlen);
break;
default:
rr3_dbg(rr3->dev, "ignoring packet with type 0x%02x, "
"len of %d, 0x%02x\n", rr3->pkttype, len, rr3->pktlen);
break;
}
}
static void redrat3_read_packet_continue(struct redrat3_dev *rr3, int len)
{
rr3_ftr(rr3->dev, "Entering %s\n", __func__);
memcpy(rr3->datap, (unsigned char *)rr3->bulk_in_buf, len);
rr3->datap += len;
rr3->bytes_read += len;
rr3_dbg(rr3->dev, "bytes_read %d, pktlen %d\n",
rr3->bytes_read, rr3->pktlen);
}
/* gather IR data from incoming urb, process it when we have enough */
static int redrat3_get_ir_data(struct redrat3_dev *rr3, int len)
{
struct device *dev = rr3->dev;
int ret = 0;
rr3_ftr(dev, "Entering %s\n", __func__);
if (rr3->pktlen > RR3_MAX_BUF_SIZE) {
dev_err(rr3->dev, "error: packet larger than buffer\n");
ret = -EINVAL;
goto out;
}
if ((rr3->bytes_read == 0) &&
(len >= (sizeof(rr3->pkttype) + sizeof(rr3->pktlen)))) {
redrat3_read_packet_start(rr3, len);
} else if (rr3->bytes_read != 0) {
redrat3_read_packet_continue(rr3, len);
} else if (rr3->bytes_read == 0) {
dev_err(dev, "error: no packet data read\n");
ret = -ENODATA;
goto out;
}
if (rr3->bytes_read > rr3->pktlen) {
dev_err(dev, "bytes_read (%d) greater than pktlen (%d)\n",
rr3->bytes_read, rr3->pktlen);
ret = -EINVAL;
goto out;
} else if (rr3->bytes_read < rr3->pktlen)
/* we're still accumulating data */
return 0;
/* if we get here, we've got IR data to decode */
if (rr3->pkttype == RR3_MOD_SIGNAL_IN)
redrat3_process_ir_data(rr3);
else
rr3_dbg(dev, "discarding non-signal data packet "
"(type 0x%02x)\n", rr3->pkttype);
out:
rr3->bytes_read = 0;
rr3->pktlen = 0;
rr3->pkttype = 0;
return ret;
}
/* callback function from USB when async USB request has completed */
static void redrat3_handle_async(struct urb *urb, struct pt_regs *regs)
{
struct redrat3_dev *rr3;
if (!urb)
return;
rr3 = urb->context;
if (!rr3) {
pr_err("%s called with invalid context!\n", __func__);
usb_unlink_urb(urb);
return;
}
rr3_ftr(rr3->dev, "Entering %s\n", __func__);
if (!rr3->det_enabled) {
rr3_dbg(rr3->dev, "received a read callback but detector "
"disabled - ignoring\n");
return;
}
switch (urb->status) {
case 0:
redrat3_get_ir_data(rr3, urb->actual_length);
break;
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
usb_unlink_urb(urb);
return;
case -EPIPE:
default:
dev_warn(rr3->dev, "Error: urb status = %d\n", urb->status);
rr3->bytes_read = 0;
rr3->pktlen = 0;
rr3->pkttype = 0;
break;
}
if (!rr3->transmitting)
redrat3_issue_async(rr3);
else
rr3_dbg(rr3->dev, "IR transmit in progress\n");
}
static void redrat3_write_bulk_callback(struct urb *urb, struct pt_regs *regs)
{
struct redrat3_dev *rr3;
int len;
if (!urb)
return;
rr3 = urb->context;
if (rr3) {
len = urb->actual_length;
rr3_ftr(rr3->dev, "%s: called (status=%d len=%d)\n",
__func__, urb->status, len);
}
}
static u16 mod_freq_to_val(unsigned int mod_freq)
{
int mult = 6000000;
/* Clk used in mod. freq. generation is CLK24/4. */
return (u16)(65536 - (mult / mod_freq));
}
static int redrat3_set_tx_carrier(struct rc_dev *dev, u32 carrier)
{
struct redrat3_dev *rr3 = dev->priv;
rr3->carrier = carrier;
return carrier;
}
static int redrat3_transmit_ir(struct rc_dev *rcdev, int *txbuf, u32 n)
{
struct redrat3_dev *rr3 = rcdev->priv;
struct device *dev = rr3->dev;
struct redrat3_signal_header header;
int i, j, count, ret, ret_len, offset;
int lencheck, cur_sample_len, pipe;
char *buffer = NULL, *sigdata = NULL;
int *sample_lens = NULL;
u32 tmpi;
u16 tmps;
u8 *datap;
u8 curlencheck = 0;
u16 *lengths_ptr;
int sendbuf_len;
rr3_ftr(dev, "Entering %s\n", __func__);
if (rr3->transmitting) {
dev_warn(dev, "%s: transmitter already in use\n", __func__);
return -EAGAIN;
}
count = n / sizeof(int);
if (count > (RR3_DRIVER_MAXLENS * 2))
return -EINVAL;
rr3->transmitting = true;
redrat3_disable_detector(rr3);
if (rr3->det_enabled) {
dev_err(dev, "%s: cannot tx while rx is enabled\n", __func__);
ret = -EIO;
goto out;
}
sample_lens = kzalloc(sizeof(int) * RR3_DRIVER_MAXLENS, GFP_KERNEL);
if (!sample_lens) {
ret = -ENOMEM;
goto out;
}
for (i = 0; i < count; i++) {
for (lencheck = 0; lencheck < curlencheck; lencheck++) {
cur_sample_len = redrat3_us_to_len(txbuf[i]);
if (sample_lens[lencheck] == cur_sample_len)
break;
}
if (lencheck == curlencheck) {
cur_sample_len = redrat3_us_to_len(txbuf[i]);
rr3_dbg(dev, "txbuf[%d]=%u, pos %d, enc %u\n",
i, txbuf[i], curlencheck, cur_sample_len);
if (curlencheck < 255) {
/* now convert the value to a proper
* rr3 value.. */
sample_lens[curlencheck] = cur_sample_len;
curlencheck++;
} else {
dev_err(dev, "signal too long\n");
ret = -EINVAL;
goto out;
}
}
}
sigdata = kzalloc((count + RR3_TX_TRAILER_LEN), GFP_KERNEL);
if (!sigdata) {
ret = -ENOMEM;
goto out;
}
sigdata[count] = RR3_END_OF_SIGNAL;
sigdata[count + 1] = RR3_END_OF_SIGNAL;
for (i = 0; i < count; i++) {
for (j = 0; j < curlencheck; j++) {
if (sample_lens[j] == redrat3_us_to_len(txbuf[i]))
sigdata[i] = j;
}
}
offset = RR3_TX_HEADER_OFFSET;
sendbuf_len = RR3_HEADER_LENGTH + (sizeof(u16) * RR3_DRIVER_MAXLENS)
+ count + RR3_TX_TRAILER_LEN + offset;
buffer = kzalloc(sendbuf_len, GFP_KERNEL);
if (!buffer) {
ret = -ENOMEM;
goto out;
}
/* fill in our packet header */
header.length = sendbuf_len - offset;
header.transfer_type = RR3_MOD_SIGNAL_OUT;
header.pause = redrat3_len_to_us(100);
header.mod_freq_count = mod_freq_to_val(rr3->carrier);
header.no_periods = 0; /* n/a to transmit */
header.max_lengths = RR3_DRIVER_MAXLENS;
header.no_lengths = curlencheck;
header.max_sig_size = RR3_MAX_SIG_SIZE;
header.sig_size = count + RR3_TX_TRAILER_LEN;
/* we currently rely on repeat handling in the IR encoding source */
header.no_repeats = 0;
tmps = cpu_to_be16(header.length);
memcpy(buffer, &tmps, 2);
tmps = cpu_to_be16(header.transfer_type);
memcpy(buffer + 2, &tmps, 2);
tmpi = cpu_to_be32(header.pause);
memcpy(buffer + offset, &tmpi, sizeof(tmpi));
tmps = cpu_to_be16(header.mod_freq_count);
memcpy(buffer + offset + RR3_FREQ_COUNT_OFFSET, &tmps, 2);
buffer[offset + RR3_NUM_LENGTHS_OFFSET] = header.no_lengths;
tmps = cpu_to_be16(header.sig_size);
memcpy(buffer + offset + RR3_NUM_SIGS_OFFSET, &tmps, 2);
buffer[offset + RR3_REPEATS_OFFSET] = header.no_repeats;
lengths_ptr = (u16 *)(buffer + offset + RR3_HEADER_LENGTH);
for (i = 0; i < curlencheck; ++i)
lengths_ptr[i] = cpu_to_be16(sample_lens[i]);
datap = (u8 *)(buffer + offset + RR3_HEADER_LENGTH +
(sizeof(u16) * RR3_DRIVER_MAXLENS));
memcpy(datap, sigdata, (count + RR3_TX_TRAILER_LEN));
if (debug) {
redrat3_dump_signal_header(&header);
redrat3_dump_signal_data(buffer, header.sig_size);
}
pipe = usb_sndbulkpipe(rr3->udev, rr3->ep_out->bEndpointAddress);
tmps = usb_bulk_msg(rr3->udev, pipe, buffer,
sendbuf_len, &ret_len, 10 * HZ);
rr3_dbg(dev, "sent %d bytes, (ret %d)\n", ret_len, tmps);
/* now tell the hardware to transmit what we sent it */
pipe = usb_rcvctrlpipe(rr3->udev, 0);
ret = usb_control_msg(rr3->udev, pipe, RR3_TX_SEND_SIGNAL,
USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
0, 0, buffer, 2, HZ * 10);
if (ret < 0)
dev_err(dev, "Error: control msg send failed, rc %d\n", ret);
else
ret = n;
out:
kfree(sample_lens);
kfree(buffer);
kfree(sigdata);
rr3->transmitting = false;
redrat3_enable_detector(rr3);
return ret;
}
static struct rc_dev *redrat3_init_rc_dev(struct redrat3_dev *rr3)
{
struct device *dev = rr3->dev;
struct rc_dev *rc;
int ret = -ENODEV;
u16 prod = le16_to_cpu(rr3->udev->descriptor.idProduct);
rc = rc_allocate_device();
if (!rc) {
dev_err(dev, "remote input dev allocation failed\n");
goto out;
}
snprintf(rr3->name, sizeof(rr3->name), "RedRat3%s "
"Infrared Remote Transceiver (%04x:%04x)",
prod == USB_RR3IIUSB_PRODUCT_ID ? "-II" : "",
le16_to_cpu(rr3->udev->descriptor.idVendor), prod);
usb_make_path(rr3->udev, rr3->phys, sizeof(rr3->phys));
rc->input_name = rr3->name;
rc->input_phys = rr3->phys;
usb_to_input_id(rr3->udev, &rc->input_id);
rc->dev.parent = dev;
rc->priv = rr3;
rc->driver_type = RC_DRIVER_IR_RAW;
rc->allowed_protos = RC_TYPE_ALL;
rc->min_timeout = MS_TO_NS(RR3_RX_MIN_TIMEOUT);
rc->max_timeout = MS_TO_NS(RR3_RX_MAX_TIMEOUT);
rc->timeout = redrat3_get_timeout(dev, rc, rr3->udev);
rc->tx_ir = redrat3_transmit_ir;
rc->s_tx_carrier = redrat3_set_tx_carrier;
rc->driver_name = DRIVER_NAME;
rc->map_name = RC_MAP_HAUPPAUGE;
ret = rc_register_device(rc);
if (ret < 0) {
dev_err(dev, "remote dev registration failed\n");
goto out;
}
return rc;
out:
rc_free_device(rc);
return NULL;
}
static int __devinit redrat3_dev_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct usb_device *udev = interface_to_usbdev(intf);
struct device *dev = &intf->dev;
struct usb_host_interface *uhi;
struct redrat3_dev *rr3;
struct usb_endpoint_descriptor *ep;
struct usb_endpoint_descriptor *ep_in = NULL;
struct usb_endpoint_descriptor *ep_out = NULL;
u8 addr, attrs;
int pipe, i;
int retval = -ENOMEM;
rr3_ftr(dev, "%s called\n", __func__);
uhi = intf->cur_altsetting;
/* find our bulk-in and bulk-out endpoints */
for (i = 0; i < uhi->desc.bNumEndpoints; ++i) {
ep = &uhi->endpoint[i].desc;
addr = ep->bEndpointAddress;
attrs = ep->bmAttributes;
if ((ep_in == NULL) &&
((addr & USB_ENDPOINT_DIR_MASK) == USB_DIR_IN) &&
((attrs & USB_ENDPOINT_XFERTYPE_MASK) ==
USB_ENDPOINT_XFER_BULK)) {
rr3_dbg(dev, "found bulk-in endpoint at 0x%02x\n",
ep->bEndpointAddress);
/* data comes in on 0x82, 0x81 is for other data... */
if (ep->bEndpointAddress == RR3_BULK_IN_EP_ADDR)
ep_in = ep;
}
if ((ep_out == NULL) &&
((addr & USB_ENDPOINT_DIR_MASK) == USB_DIR_OUT) &&
((attrs & USB_ENDPOINT_XFERTYPE_MASK) ==
USB_ENDPOINT_XFER_BULK)) {
rr3_dbg(dev, "found bulk-out endpoint at 0x%02x\n",
ep->bEndpointAddress);
ep_out = ep;
}
}
if (!ep_in || !ep_out) {
dev_err(dev, "Couldn't find both in and out endpoints\n");
retval = -ENODEV;
goto no_endpoints;
}
/* allocate memory for our device state and initialize it */
rr3 = kzalloc(sizeof(*rr3), GFP_KERNEL);
if (rr3 == NULL) {
dev_err(dev, "Memory allocation failure\n");
goto error;
}
rr3->dev = &intf->dev;
/* set up bulk-in endpoint */
rr3->read_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!rr3->read_urb) {
dev_err(dev, "Read urb allocation failure\n");
goto error;
}
rr3->ep_in = ep_in;
rr3->bulk_in_buf = usb_alloc_coherent(udev, ep_in->wMaxPacketSize,
GFP_ATOMIC, &rr3->dma_in);
if (!rr3->bulk_in_buf) {
dev_err(dev, "Read buffer allocation failure\n");
goto error;
}
pipe = usb_rcvbulkpipe(udev, ep_in->bEndpointAddress);
usb_fill_bulk_urb(rr3->read_urb, udev, pipe,
rr3->bulk_in_buf, ep_in->wMaxPacketSize,
(usb_complete_t)redrat3_handle_async, rr3);
/* set up bulk-out endpoint*/
rr3->write_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!rr3->write_urb) {
dev_err(dev, "Write urb allocation failure\n");
goto error;
}
rr3->ep_out = ep_out;
rr3->bulk_out_buf = usb_alloc_coherent(udev, ep_out->wMaxPacketSize,
GFP_ATOMIC, &rr3->dma_out);
if (!rr3->bulk_out_buf) {
dev_err(dev, "Write buffer allocation failure\n");
goto error;
}
pipe = usb_sndbulkpipe(udev, ep_out->bEndpointAddress);
usb_fill_bulk_urb(rr3->write_urb, udev, pipe,
rr3->bulk_out_buf, ep_out->wMaxPacketSize,
(usb_complete_t)redrat3_write_bulk_callback, rr3);
mutex_init(&rr3->lock);
rr3->udev = udev;
redrat3_reset(rr3);
redrat3_get_firmware_rev(rr3);
/* might be all we need to do? */
retval = redrat3_enable_detector(rr3);
if (retval < 0)
goto error;
/* default.. will get overridden by any sends with a freq defined */
rr3->carrier = 38000;
rr3->rc = redrat3_init_rc_dev(rr3);
if (!rr3->rc)
goto error;
setup_timer(&rr3->rx_timeout, redrat3_rx_timeout, (unsigned long)rr3);
/* we can register the device now, as it is ready */
usb_set_intfdata(intf, rr3);
rr3_ftr(dev, "Exiting %s\n", __func__);
return 0;
error:
redrat3_delete(rr3, rr3->udev);
no_endpoints:
dev_err(dev, "%s: retval = %x", __func__, retval);
return retval;
}
static void __devexit redrat3_dev_disconnect(struct usb_interface *intf)
{
struct usb_device *udev = interface_to_usbdev(intf);
struct redrat3_dev *rr3 = usb_get_intfdata(intf);
rr3_ftr(&intf->dev, "Entering %s\n", __func__);
if (!rr3)
return;
redrat3_disable_detector(rr3);
usb_set_intfdata(intf, NULL);
rc_unregister_device(rr3->rc);
redrat3_delete(rr3, udev);
rr3_ftr(&intf->dev, "RedRat3 IR Transceiver now disconnected\n");
}
static int redrat3_dev_suspend(struct usb_interface *intf, pm_message_t message)
{
struct redrat3_dev *rr3 = usb_get_intfdata(intf);
rr3_ftr(rr3->dev, "suspend\n");
usb_kill_urb(rr3->read_urb);
return 0;
}
static int redrat3_dev_resume(struct usb_interface *intf)
{
struct redrat3_dev *rr3 = usb_get_intfdata(intf);
rr3_ftr(rr3->dev, "resume\n");
if (usb_submit_urb(rr3->read_urb, GFP_ATOMIC))
return -EIO;
return 0;
}
static struct usb_driver redrat3_dev_driver = {
.name = DRIVER_NAME,
.probe = redrat3_dev_probe,
.disconnect = redrat3_dev_disconnect,
.suspend = redrat3_dev_suspend,
.resume = redrat3_dev_resume,
.reset_resume = redrat3_dev_resume,
.id_table = redrat3_dev_table
};
static int __init redrat3_dev_init(void)
{
int ret;
ret = usb_register(&redrat3_dev_driver);
if (ret < 0)
pr_err(DRIVER_NAME
": usb register failed, result = %d\n", ret);
return ret;
}
static void __exit redrat3_dev_exit(void)
{
usb_deregister(&redrat3_dev_driver);
}
module_init(redrat3_dev_init);
module_exit(redrat3_dev_exit);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_AUTHOR(DRIVER_AUTHOR2);
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(usb, redrat3_dev_table);
module_param(debug, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(debug, "Enable module debug spew. 0 = no debugging (default) "
"0x1 = standard debug messages, 0x2 = function tracing debug. "
"Flag bits are addative (i.e., 0x3 for both debug types).");
| gpl-2.0 |
rickyzhang82/linux-allwinner | drivers/net/chelsio/cxgb2.c | 2383 | 37669 | /*****************************************************************************
* *
* File: cxgb2.c *
* $Revision: 1.25 $ *
* $Date: 2005/06/22 00:43:25 $ *
* Description: *
* Chelsio 10Gb Ethernet Driver. *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License, version 2, as *
* published by the Free Software Foundation. *
* *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED *
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF *
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. *
* *
* http://www.chelsio.com *
* *
* Copyright (c) 2003 - 2005 Chelsio Communications, Inc. *
* All rights reserved. *
* *
* Maintainers: maintainers@chelsio.com *
* *
* Authors: Dimitrios Michailidis <dm@chelsio.com> *
* Tina Yang <tainay@chelsio.com> *
* Felix Marti <felix@chelsio.com> *
* Scott Bardone <sbardone@chelsio.com> *
* Kurt Ottaway <kottaway@chelsio.com> *
* Frank DiMambro <frank@chelsio.com> *
* *
* History: *
* *
****************************************************************************/
#include "common.h"
#include <linux/module.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/if_vlan.h>
#include <linux/mii.h>
#include <linux/sockios.h>
#include <linux/dma-mapping.h>
#include <asm/uaccess.h>
#include "cpl5_cmd.h"
#include "regs.h"
#include "gmac.h"
#include "cphy.h"
#include "sge.h"
#include "tp.h"
#include "espi.h"
#include "elmer0.h"
#include <linux/workqueue.h>
static inline void schedule_mac_stats_update(struct adapter *ap, int secs)
{
schedule_delayed_work(&ap->stats_update_task, secs * HZ);
}
static inline void cancel_mac_stats_update(struct adapter *ap)
{
cancel_delayed_work(&ap->stats_update_task);
}
#define MAX_CMDQ_ENTRIES 16384
#define MAX_CMDQ1_ENTRIES 1024
#define MAX_RX_BUFFERS 16384
#define MAX_RX_JUMBO_BUFFERS 16384
#define MAX_TX_BUFFERS_HIGH 16384U
#define MAX_TX_BUFFERS_LOW 1536U
#define MAX_TX_BUFFERS 1460U
#define MIN_FL_ENTRIES 32
#define DFLT_MSG_ENABLE (NETIF_MSG_DRV | NETIF_MSG_PROBE | NETIF_MSG_LINK | \
NETIF_MSG_TIMER | NETIF_MSG_IFDOWN | NETIF_MSG_IFUP |\
NETIF_MSG_RX_ERR | NETIF_MSG_TX_ERR)
/*
* The EEPROM is actually bigger but only the first few bytes are used so we
* only report those.
*/
#define EEPROM_SIZE 32
MODULE_DESCRIPTION(DRV_DESCRIPTION);
MODULE_AUTHOR("Chelsio Communications");
MODULE_LICENSE("GPL");
static int dflt_msg_enable = DFLT_MSG_ENABLE;
module_param(dflt_msg_enable, int, 0);
MODULE_PARM_DESC(dflt_msg_enable, "Chelsio T1 default message enable bitmap");
#define HCLOCK 0x0
#define LCLOCK 0x1
/* T1 cards powersave mode */
static int t1_clock(struct adapter *adapter, int mode);
static int t1powersave = 1; /* HW default is powersave mode. */
module_param(t1powersave, int, 0);
MODULE_PARM_DESC(t1powersave, "Enable/Disable T1 powersaving mode");
static int disable_msi = 0;
module_param(disable_msi, int, 0);
MODULE_PARM_DESC(disable_msi, "Disable Message Signaled Interrupt (MSI)");
static const char pci_speed[][4] = {
"33", "66", "100", "133"
};
/*
* Setup MAC to receive the types of packets we want.
*/
static void t1_set_rxmode(struct net_device *dev)
{
struct adapter *adapter = dev->ml_priv;
struct cmac *mac = adapter->port[dev->if_port].mac;
struct t1_rx_mode rm;
rm.dev = dev;
mac->ops->set_rx_mode(mac, &rm);
}
static void link_report(struct port_info *p)
{
if (!netif_carrier_ok(p->dev))
printk(KERN_INFO "%s: link down\n", p->dev->name);
else {
const char *s = "10Mbps";
switch (p->link_config.speed) {
case SPEED_10000: s = "10Gbps"; break;
case SPEED_1000: s = "1000Mbps"; break;
case SPEED_100: s = "100Mbps"; break;
}
printk(KERN_INFO "%s: link up, %s, %s-duplex\n",
p->dev->name, s,
p->link_config.duplex == DUPLEX_FULL ? "full" : "half");
}
}
void t1_link_negotiated(struct adapter *adapter, int port_id, int link_stat,
int speed, int duplex, int pause)
{
struct port_info *p = &adapter->port[port_id];
if (link_stat != netif_carrier_ok(p->dev)) {
if (link_stat)
netif_carrier_on(p->dev);
else
netif_carrier_off(p->dev);
link_report(p);
/* multi-ports: inform toe */
if ((speed > 0) && (adapter->params.nports > 1)) {
unsigned int sched_speed = 10;
switch (speed) {
case SPEED_1000:
sched_speed = 1000;
break;
case SPEED_100:
sched_speed = 100;
break;
case SPEED_10:
sched_speed = 10;
break;
}
t1_sched_update_parms(adapter->sge, port_id, 0, sched_speed);
}
}
}
static void link_start(struct port_info *p)
{
struct cmac *mac = p->mac;
mac->ops->reset(mac);
if (mac->ops->macaddress_set)
mac->ops->macaddress_set(mac, p->dev->dev_addr);
t1_set_rxmode(p->dev);
t1_link_start(p->phy, mac, &p->link_config);
mac->ops->enable(mac, MAC_DIRECTION_RX | MAC_DIRECTION_TX);
}
static void enable_hw_csum(struct adapter *adapter)
{
if (adapter->port[0].dev->hw_features & NETIF_F_TSO)
t1_tp_set_ip_checksum_offload(adapter->tp, 1); /* for TSO only */
t1_tp_set_tcp_checksum_offload(adapter->tp, 1);
}
/*
* Things to do upon first use of a card.
* This must run with the rtnl lock held.
*/
static int cxgb_up(struct adapter *adapter)
{
int err = 0;
if (!(adapter->flags & FULL_INIT_DONE)) {
err = t1_init_hw_modules(adapter);
if (err)
goto out_err;
enable_hw_csum(adapter);
adapter->flags |= FULL_INIT_DONE;
}
t1_interrupts_clear(adapter);
adapter->params.has_msi = !disable_msi && !pci_enable_msi(adapter->pdev);
err = request_irq(adapter->pdev->irq, t1_interrupt,
adapter->params.has_msi ? 0 : IRQF_SHARED,
adapter->name, adapter);
if (err) {
if (adapter->params.has_msi)
pci_disable_msi(adapter->pdev);
goto out_err;
}
t1_sge_start(adapter->sge);
t1_interrupts_enable(adapter);
out_err:
return err;
}
/*
* Release resources when all the ports have been stopped.
*/
static void cxgb_down(struct adapter *adapter)
{
t1_sge_stop(adapter->sge);
t1_interrupts_disable(adapter);
free_irq(adapter->pdev->irq, adapter);
if (adapter->params.has_msi)
pci_disable_msi(adapter->pdev);
}
static int cxgb_open(struct net_device *dev)
{
int err;
struct adapter *adapter = dev->ml_priv;
int other_ports = adapter->open_device_map & PORT_MASK;
napi_enable(&adapter->napi);
if (!adapter->open_device_map && (err = cxgb_up(adapter)) < 0) {
napi_disable(&adapter->napi);
return err;
}
__set_bit(dev->if_port, &adapter->open_device_map);
link_start(&adapter->port[dev->if_port]);
netif_start_queue(dev);
if (!other_ports && adapter->params.stats_update_period)
schedule_mac_stats_update(adapter,
adapter->params.stats_update_period);
return 0;
}
static int cxgb_close(struct net_device *dev)
{
struct adapter *adapter = dev->ml_priv;
struct port_info *p = &adapter->port[dev->if_port];
struct cmac *mac = p->mac;
netif_stop_queue(dev);
napi_disable(&adapter->napi);
mac->ops->disable(mac, MAC_DIRECTION_TX | MAC_DIRECTION_RX);
netif_carrier_off(dev);
clear_bit(dev->if_port, &adapter->open_device_map);
if (adapter->params.stats_update_period &&
!(adapter->open_device_map & PORT_MASK)) {
/* Stop statistics accumulation. */
smp_mb__after_clear_bit();
spin_lock(&adapter->work_lock); /* sync with update task */
spin_unlock(&adapter->work_lock);
cancel_mac_stats_update(adapter);
}
if (!adapter->open_device_map)
cxgb_down(adapter);
return 0;
}
static struct net_device_stats *t1_get_stats(struct net_device *dev)
{
struct adapter *adapter = dev->ml_priv;
struct port_info *p = &adapter->port[dev->if_port];
struct net_device_stats *ns = &p->netstats;
const struct cmac_statistics *pstats;
/* Do a full update of the MAC stats */
pstats = p->mac->ops->statistics_update(p->mac,
MAC_STATS_UPDATE_FULL);
ns->tx_packets = pstats->TxUnicastFramesOK +
pstats->TxMulticastFramesOK + pstats->TxBroadcastFramesOK;
ns->rx_packets = pstats->RxUnicastFramesOK +
pstats->RxMulticastFramesOK + pstats->RxBroadcastFramesOK;
ns->tx_bytes = pstats->TxOctetsOK;
ns->rx_bytes = pstats->RxOctetsOK;
ns->tx_errors = pstats->TxLateCollisions + pstats->TxLengthErrors +
pstats->TxUnderrun + pstats->TxFramesAbortedDueToXSCollisions;
ns->rx_errors = pstats->RxDataErrors + pstats->RxJabberErrors +
pstats->RxFCSErrors + pstats->RxAlignErrors +
pstats->RxSequenceErrors + pstats->RxFrameTooLongErrors +
pstats->RxSymbolErrors + pstats->RxRuntErrors;
ns->multicast = pstats->RxMulticastFramesOK;
ns->collisions = pstats->TxTotalCollisions;
/* detailed rx_errors */
ns->rx_length_errors = pstats->RxFrameTooLongErrors +
pstats->RxJabberErrors;
ns->rx_over_errors = 0;
ns->rx_crc_errors = pstats->RxFCSErrors;
ns->rx_frame_errors = pstats->RxAlignErrors;
ns->rx_fifo_errors = 0;
ns->rx_missed_errors = 0;
/* detailed tx_errors */
ns->tx_aborted_errors = pstats->TxFramesAbortedDueToXSCollisions;
ns->tx_carrier_errors = 0;
ns->tx_fifo_errors = pstats->TxUnderrun;
ns->tx_heartbeat_errors = 0;
ns->tx_window_errors = pstats->TxLateCollisions;
return ns;
}
static u32 get_msglevel(struct net_device *dev)
{
struct adapter *adapter = dev->ml_priv;
return adapter->msg_enable;
}
static void set_msglevel(struct net_device *dev, u32 val)
{
struct adapter *adapter = dev->ml_priv;
adapter->msg_enable = val;
}
static char stats_strings[][ETH_GSTRING_LEN] = {
"TxOctetsOK",
"TxOctetsBad",
"TxUnicastFramesOK",
"TxMulticastFramesOK",
"TxBroadcastFramesOK",
"TxPauseFrames",
"TxFramesWithDeferredXmissions",
"TxLateCollisions",
"TxTotalCollisions",
"TxFramesAbortedDueToXSCollisions",
"TxUnderrun",
"TxLengthErrors",
"TxInternalMACXmitError",
"TxFramesWithExcessiveDeferral",
"TxFCSErrors",
"TxJumboFramesOk",
"TxJumboOctetsOk",
"RxOctetsOK",
"RxOctetsBad",
"RxUnicastFramesOK",
"RxMulticastFramesOK",
"RxBroadcastFramesOK",
"RxPauseFrames",
"RxFCSErrors",
"RxAlignErrors",
"RxSymbolErrors",
"RxDataErrors",
"RxSequenceErrors",
"RxRuntErrors",
"RxJabberErrors",
"RxInternalMACRcvError",
"RxInRangeLengthErrors",
"RxOutOfRangeLengthField",
"RxFrameTooLongErrors",
"RxJumboFramesOk",
"RxJumboOctetsOk",
/* Port stats */
"RxCsumGood",
"TxCsumOffload",
"TxTso",
"RxVlan",
"TxVlan",
"TxNeedHeadroom",
/* Interrupt stats */
"rx drops",
"pure_rsps",
"unhandled irqs",
"respQ_empty",
"respQ_overflow",
"freelistQ_empty",
"pkt_too_big",
"pkt_mismatch",
"cmdQ_full0",
"cmdQ_full1",
"espi_DIP2ParityErr",
"espi_DIP4Err",
"espi_RxDrops",
"espi_TxDrops",
"espi_RxOvfl",
"espi_ParityErr"
};
#define T2_REGMAP_SIZE (3 * 1024)
static int get_regs_len(struct net_device *dev)
{
return T2_REGMAP_SIZE;
}
static void get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
{
struct adapter *adapter = dev->ml_priv;
strcpy(info->driver, DRV_NAME);
strcpy(info->version, DRV_VERSION);
strcpy(info->fw_version, "N/A");
strcpy(info->bus_info, pci_name(adapter->pdev));
}
static int get_sset_count(struct net_device *dev, int sset)
{
switch (sset) {
case ETH_SS_STATS:
return ARRAY_SIZE(stats_strings);
default:
return -EOPNOTSUPP;
}
}
static void get_strings(struct net_device *dev, u32 stringset, u8 *data)
{
if (stringset == ETH_SS_STATS)
memcpy(data, stats_strings, sizeof(stats_strings));
}
static void get_stats(struct net_device *dev, struct ethtool_stats *stats,
u64 *data)
{
struct adapter *adapter = dev->ml_priv;
struct cmac *mac = adapter->port[dev->if_port].mac;
const struct cmac_statistics *s;
const struct sge_intr_counts *t;
struct sge_port_stats ss;
s = mac->ops->statistics_update(mac, MAC_STATS_UPDATE_FULL);
t = t1_sge_get_intr_counts(adapter->sge);
t1_sge_get_port_stats(adapter->sge, dev->if_port, &ss);
*data++ = s->TxOctetsOK;
*data++ = s->TxOctetsBad;
*data++ = s->TxUnicastFramesOK;
*data++ = s->TxMulticastFramesOK;
*data++ = s->TxBroadcastFramesOK;
*data++ = s->TxPauseFrames;
*data++ = s->TxFramesWithDeferredXmissions;
*data++ = s->TxLateCollisions;
*data++ = s->TxTotalCollisions;
*data++ = s->TxFramesAbortedDueToXSCollisions;
*data++ = s->TxUnderrun;
*data++ = s->TxLengthErrors;
*data++ = s->TxInternalMACXmitError;
*data++ = s->TxFramesWithExcessiveDeferral;
*data++ = s->TxFCSErrors;
*data++ = s->TxJumboFramesOK;
*data++ = s->TxJumboOctetsOK;
*data++ = s->RxOctetsOK;
*data++ = s->RxOctetsBad;
*data++ = s->RxUnicastFramesOK;
*data++ = s->RxMulticastFramesOK;
*data++ = s->RxBroadcastFramesOK;
*data++ = s->RxPauseFrames;
*data++ = s->RxFCSErrors;
*data++ = s->RxAlignErrors;
*data++ = s->RxSymbolErrors;
*data++ = s->RxDataErrors;
*data++ = s->RxSequenceErrors;
*data++ = s->RxRuntErrors;
*data++ = s->RxJabberErrors;
*data++ = s->RxInternalMACRcvError;
*data++ = s->RxInRangeLengthErrors;
*data++ = s->RxOutOfRangeLengthField;
*data++ = s->RxFrameTooLongErrors;
*data++ = s->RxJumboFramesOK;
*data++ = s->RxJumboOctetsOK;
*data++ = ss.rx_cso_good;
*data++ = ss.tx_cso;
*data++ = ss.tx_tso;
*data++ = ss.vlan_xtract;
*data++ = ss.vlan_insert;
*data++ = ss.tx_need_hdrroom;
*data++ = t->rx_drops;
*data++ = t->pure_rsps;
*data++ = t->unhandled_irqs;
*data++ = t->respQ_empty;
*data++ = t->respQ_overflow;
*data++ = t->freelistQ_empty;
*data++ = t->pkt_too_big;
*data++ = t->pkt_mismatch;
*data++ = t->cmdQ_full[0];
*data++ = t->cmdQ_full[1];
if (adapter->espi) {
const struct espi_intr_counts *e;
e = t1_espi_get_intr_counts(adapter->espi);
*data++ = e->DIP2_parity_err;
*data++ = e->DIP4_err;
*data++ = e->rx_drops;
*data++ = e->tx_drops;
*data++ = e->rx_ovflw;
*data++ = e->parity_err;
}
}
static inline void reg_block_dump(struct adapter *ap, void *buf,
unsigned int start, unsigned int end)
{
u32 *p = buf + start;
for ( ; start <= end; start += sizeof(u32))
*p++ = readl(ap->regs + start);
}
static void get_regs(struct net_device *dev, struct ethtool_regs *regs,
void *buf)
{
struct adapter *ap = dev->ml_priv;
/*
* Version scheme: bits 0..9: chip version, bits 10..15: chip revision
*/
regs->version = 2;
memset(buf, 0, T2_REGMAP_SIZE);
reg_block_dump(ap, buf, 0, A_SG_RESPACCUTIMER);
reg_block_dump(ap, buf, A_MC3_CFG, A_MC4_INT_CAUSE);
reg_block_dump(ap, buf, A_TPI_ADDR, A_TPI_PAR);
reg_block_dump(ap, buf, A_TP_IN_CONFIG, A_TP_TX_DROP_COUNT);
reg_block_dump(ap, buf, A_RAT_ROUTE_CONTROL, A_RAT_INTR_CAUSE);
reg_block_dump(ap, buf, A_CSPI_RX_AE_WM, A_CSPI_INTR_ENABLE);
reg_block_dump(ap, buf, A_ESPI_SCH_TOKEN0, A_ESPI_GOSTAT);
reg_block_dump(ap, buf, A_ULP_ULIMIT, A_ULP_PIO_CTRL);
reg_block_dump(ap, buf, A_PL_ENABLE, A_PL_CAUSE);
reg_block_dump(ap, buf, A_MC5_CONFIG, A_MC5_MASK_WRITE_CMD);
}
static int get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct adapter *adapter = dev->ml_priv;
struct port_info *p = &adapter->port[dev->if_port];
cmd->supported = p->link_config.supported;
cmd->advertising = p->link_config.advertising;
if (netif_carrier_ok(dev)) {
ethtool_cmd_speed_set(cmd, p->link_config.speed);
cmd->duplex = p->link_config.duplex;
} else {
ethtool_cmd_speed_set(cmd, -1);
cmd->duplex = -1;
}
cmd->port = (cmd->supported & SUPPORTED_TP) ? PORT_TP : PORT_FIBRE;
cmd->phy_address = p->phy->mdio.prtad;
cmd->transceiver = XCVR_EXTERNAL;
cmd->autoneg = p->link_config.autoneg;
cmd->maxtxpkt = 0;
cmd->maxrxpkt = 0;
return 0;
}
static int speed_duplex_to_caps(int speed, int duplex)
{
int cap = 0;
switch (speed) {
case SPEED_10:
if (duplex == DUPLEX_FULL)
cap = SUPPORTED_10baseT_Full;
else
cap = SUPPORTED_10baseT_Half;
break;
case SPEED_100:
if (duplex == DUPLEX_FULL)
cap = SUPPORTED_100baseT_Full;
else
cap = SUPPORTED_100baseT_Half;
break;
case SPEED_1000:
if (duplex == DUPLEX_FULL)
cap = SUPPORTED_1000baseT_Full;
else
cap = SUPPORTED_1000baseT_Half;
break;
case SPEED_10000:
if (duplex == DUPLEX_FULL)
cap = SUPPORTED_10000baseT_Full;
}
return cap;
}
#define ADVERTISED_MASK (ADVERTISED_10baseT_Half | ADVERTISED_10baseT_Full | \
ADVERTISED_100baseT_Half | ADVERTISED_100baseT_Full | \
ADVERTISED_1000baseT_Half | ADVERTISED_1000baseT_Full | \
ADVERTISED_10000baseT_Full)
static int set_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct adapter *adapter = dev->ml_priv;
struct port_info *p = &adapter->port[dev->if_port];
struct link_config *lc = &p->link_config;
if (!(lc->supported & SUPPORTED_Autoneg))
return -EOPNOTSUPP; /* can't change speed/duplex */
if (cmd->autoneg == AUTONEG_DISABLE) {
u32 speed = ethtool_cmd_speed(cmd);
int cap = speed_duplex_to_caps(speed, cmd->duplex);
if (!(lc->supported & cap) || (speed == SPEED_1000))
return -EINVAL;
lc->requested_speed = speed;
lc->requested_duplex = cmd->duplex;
lc->advertising = 0;
} else {
cmd->advertising &= ADVERTISED_MASK;
if (cmd->advertising & (cmd->advertising - 1))
cmd->advertising = lc->supported;
cmd->advertising &= lc->supported;
if (!cmd->advertising)
return -EINVAL;
lc->requested_speed = SPEED_INVALID;
lc->requested_duplex = DUPLEX_INVALID;
lc->advertising = cmd->advertising | ADVERTISED_Autoneg;
}
lc->autoneg = cmd->autoneg;
if (netif_running(dev))
t1_link_start(p->phy, p->mac, lc);
return 0;
}
static void get_pauseparam(struct net_device *dev,
struct ethtool_pauseparam *epause)
{
struct adapter *adapter = dev->ml_priv;
struct port_info *p = &adapter->port[dev->if_port];
epause->autoneg = (p->link_config.requested_fc & PAUSE_AUTONEG) != 0;
epause->rx_pause = (p->link_config.fc & PAUSE_RX) != 0;
epause->tx_pause = (p->link_config.fc & PAUSE_TX) != 0;
}
static int set_pauseparam(struct net_device *dev,
struct ethtool_pauseparam *epause)
{
struct adapter *adapter = dev->ml_priv;
struct port_info *p = &adapter->port[dev->if_port];
struct link_config *lc = &p->link_config;
if (epause->autoneg == AUTONEG_DISABLE)
lc->requested_fc = 0;
else if (lc->supported & SUPPORTED_Autoneg)
lc->requested_fc = PAUSE_AUTONEG;
else
return -EINVAL;
if (epause->rx_pause)
lc->requested_fc |= PAUSE_RX;
if (epause->tx_pause)
lc->requested_fc |= PAUSE_TX;
if (lc->autoneg == AUTONEG_ENABLE) {
if (netif_running(dev))
t1_link_start(p->phy, p->mac, lc);
} else {
lc->fc = lc->requested_fc & (PAUSE_RX | PAUSE_TX);
if (netif_running(dev))
p->mac->ops->set_speed_duplex_fc(p->mac, -1, -1,
lc->fc);
}
return 0;
}
static void get_sge_param(struct net_device *dev, struct ethtool_ringparam *e)
{
struct adapter *adapter = dev->ml_priv;
int jumbo_fl = t1_is_T1B(adapter) ? 1 : 0;
e->rx_max_pending = MAX_RX_BUFFERS;
e->rx_mini_max_pending = 0;
e->rx_jumbo_max_pending = MAX_RX_JUMBO_BUFFERS;
e->tx_max_pending = MAX_CMDQ_ENTRIES;
e->rx_pending = adapter->params.sge.freelQ_size[!jumbo_fl];
e->rx_mini_pending = 0;
e->rx_jumbo_pending = adapter->params.sge.freelQ_size[jumbo_fl];
e->tx_pending = adapter->params.sge.cmdQ_size[0];
}
static int set_sge_param(struct net_device *dev, struct ethtool_ringparam *e)
{
struct adapter *adapter = dev->ml_priv;
int jumbo_fl = t1_is_T1B(adapter) ? 1 : 0;
if (e->rx_pending > MAX_RX_BUFFERS || e->rx_mini_pending ||
e->rx_jumbo_pending > MAX_RX_JUMBO_BUFFERS ||
e->tx_pending > MAX_CMDQ_ENTRIES ||
e->rx_pending < MIN_FL_ENTRIES ||
e->rx_jumbo_pending < MIN_FL_ENTRIES ||
e->tx_pending < (adapter->params.nports + 1) * (MAX_SKB_FRAGS + 1))
return -EINVAL;
if (adapter->flags & FULL_INIT_DONE)
return -EBUSY;
adapter->params.sge.freelQ_size[!jumbo_fl] = e->rx_pending;
adapter->params.sge.freelQ_size[jumbo_fl] = e->rx_jumbo_pending;
adapter->params.sge.cmdQ_size[0] = e->tx_pending;
adapter->params.sge.cmdQ_size[1] = e->tx_pending > MAX_CMDQ1_ENTRIES ?
MAX_CMDQ1_ENTRIES : e->tx_pending;
return 0;
}
static int set_coalesce(struct net_device *dev, struct ethtool_coalesce *c)
{
struct adapter *adapter = dev->ml_priv;
adapter->params.sge.rx_coalesce_usecs = c->rx_coalesce_usecs;
adapter->params.sge.coalesce_enable = c->use_adaptive_rx_coalesce;
adapter->params.sge.sample_interval_usecs = c->rate_sample_interval;
t1_sge_set_coalesce_params(adapter->sge, &adapter->params.sge);
return 0;
}
static int get_coalesce(struct net_device *dev, struct ethtool_coalesce *c)
{
struct adapter *adapter = dev->ml_priv;
c->rx_coalesce_usecs = adapter->params.sge.rx_coalesce_usecs;
c->rate_sample_interval = adapter->params.sge.sample_interval_usecs;
c->use_adaptive_rx_coalesce = adapter->params.sge.coalesce_enable;
return 0;
}
static int get_eeprom_len(struct net_device *dev)
{
struct adapter *adapter = dev->ml_priv;
return t1_is_asic(adapter) ? EEPROM_SIZE : 0;
}
#define EEPROM_MAGIC(ap) \
(PCI_VENDOR_ID_CHELSIO | ((ap)->params.chip_version << 16))
static int get_eeprom(struct net_device *dev, struct ethtool_eeprom *e,
u8 *data)
{
int i;
u8 buf[EEPROM_SIZE] __attribute__((aligned(4)));
struct adapter *adapter = dev->ml_priv;
e->magic = EEPROM_MAGIC(adapter);
for (i = e->offset & ~3; i < e->offset + e->len; i += sizeof(u32))
t1_seeprom_read(adapter, i, (__le32 *)&buf[i]);
memcpy(data, buf + e->offset, e->len);
return 0;
}
static const struct ethtool_ops t1_ethtool_ops = {
.get_settings = get_settings,
.set_settings = set_settings,
.get_drvinfo = get_drvinfo,
.get_msglevel = get_msglevel,
.set_msglevel = set_msglevel,
.get_ringparam = get_sge_param,
.set_ringparam = set_sge_param,
.get_coalesce = get_coalesce,
.set_coalesce = set_coalesce,
.get_eeprom_len = get_eeprom_len,
.get_eeprom = get_eeprom,
.get_pauseparam = get_pauseparam,
.set_pauseparam = set_pauseparam,
.get_link = ethtool_op_get_link,
.get_strings = get_strings,
.get_sset_count = get_sset_count,
.get_ethtool_stats = get_stats,
.get_regs_len = get_regs_len,
.get_regs = get_regs,
};
static int t1_ioctl(struct net_device *dev, struct ifreq *req, int cmd)
{
struct adapter *adapter = dev->ml_priv;
struct mdio_if_info *mdio = &adapter->port[dev->if_port].phy->mdio;
return mdio_mii_ioctl(mdio, if_mii(req), cmd);
}
static int t1_change_mtu(struct net_device *dev, int new_mtu)
{
int ret;
struct adapter *adapter = dev->ml_priv;
struct cmac *mac = adapter->port[dev->if_port].mac;
if (!mac->ops->set_mtu)
return -EOPNOTSUPP;
if (new_mtu < 68)
return -EINVAL;
if ((ret = mac->ops->set_mtu(mac, new_mtu)))
return ret;
dev->mtu = new_mtu;
return 0;
}
static int t1_set_mac_addr(struct net_device *dev, void *p)
{
struct adapter *adapter = dev->ml_priv;
struct cmac *mac = adapter->port[dev->if_port].mac;
struct sockaddr *addr = p;
if (!mac->ops->macaddress_set)
return -EOPNOTSUPP;
memcpy(dev->dev_addr, addr->sa_data, dev->addr_len);
mac->ops->macaddress_set(mac, dev->dev_addr);
return 0;
}
#if defined(CONFIG_VLAN_8021Q) || defined(CONFIG_VLAN_8021Q_MODULE)
static void t1_vlan_rx_register(struct net_device *dev,
struct vlan_group *grp)
{
struct adapter *adapter = dev->ml_priv;
spin_lock_irq(&adapter->async_lock);
adapter->vlan_grp = grp;
t1_set_vlan_accel(adapter, grp != NULL);
spin_unlock_irq(&adapter->async_lock);
}
#endif
#ifdef CONFIG_NET_POLL_CONTROLLER
static void t1_netpoll(struct net_device *dev)
{
unsigned long flags;
struct adapter *adapter = dev->ml_priv;
local_irq_save(flags);
t1_interrupt(adapter->pdev->irq, adapter);
local_irq_restore(flags);
}
#endif
/*
* Periodic accumulation of MAC statistics. This is used only if the MAC
* does not have any other way to prevent stats counter overflow.
*/
static void mac_stats_task(struct work_struct *work)
{
int i;
struct adapter *adapter =
container_of(work, struct adapter, stats_update_task.work);
for_each_port(adapter, i) {
struct port_info *p = &adapter->port[i];
if (netif_running(p->dev))
p->mac->ops->statistics_update(p->mac,
MAC_STATS_UPDATE_FAST);
}
/* Schedule the next statistics update if any port is active. */
spin_lock(&adapter->work_lock);
if (adapter->open_device_map & PORT_MASK)
schedule_mac_stats_update(adapter,
adapter->params.stats_update_period);
spin_unlock(&adapter->work_lock);
}
/*
* Processes elmer0 external interrupts in process context.
*/
static void ext_intr_task(struct work_struct *work)
{
struct adapter *adapter =
container_of(work, struct adapter, ext_intr_handler_task);
t1_elmer0_ext_intr_handler(adapter);
/* Now reenable external interrupts */
spin_lock_irq(&adapter->async_lock);
adapter->slow_intr_mask |= F_PL_INTR_EXT;
writel(F_PL_INTR_EXT, adapter->regs + A_PL_CAUSE);
writel(adapter->slow_intr_mask | F_PL_INTR_SGE_DATA,
adapter->regs + A_PL_ENABLE);
spin_unlock_irq(&adapter->async_lock);
}
/*
* Interrupt-context handler for elmer0 external interrupts.
*/
void t1_elmer0_ext_intr(struct adapter *adapter)
{
/*
* Schedule a task to handle external interrupts as we require
* a process context. We disable EXT interrupts in the interim
* and let the task reenable them when it's done.
*/
adapter->slow_intr_mask &= ~F_PL_INTR_EXT;
writel(adapter->slow_intr_mask | F_PL_INTR_SGE_DATA,
adapter->regs + A_PL_ENABLE);
schedule_work(&adapter->ext_intr_handler_task);
}
void t1_fatal_err(struct adapter *adapter)
{
if (adapter->flags & FULL_INIT_DONE) {
t1_sge_stop(adapter->sge);
t1_interrupts_disable(adapter);
}
pr_alert("%s: encountered fatal error, operation suspended\n",
adapter->name);
}
static const struct net_device_ops cxgb_netdev_ops = {
.ndo_open = cxgb_open,
.ndo_stop = cxgb_close,
.ndo_start_xmit = t1_start_xmit,
.ndo_get_stats = t1_get_stats,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_multicast_list = t1_set_rxmode,
.ndo_do_ioctl = t1_ioctl,
.ndo_change_mtu = t1_change_mtu,
.ndo_set_mac_address = t1_set_mac_addr,
#if defined(CONFIG_VLAN_8021Q) || defined(CONFIG_VLAN_8021Q_MODULE)
.ndo_vlan_rx_register = t1_vlan_rx_register,
#endif
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = t1_netpoll,
#endif
};
static int __devinit init_one(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
static int version_printed;
int i, err, pci_using_dac = 0;
unsigned long mmio_start, mmio_len;
const struct board_info *bi;
struct adapter *adapter = NULL;
struct port_info *pi;
if (!version_printed) {
printk(KERN_INFO "%s - version %s\n", DRV_DESCRIPTION,
DRV_VERSION);
++version_printed;
}
err = pci_enable_device(pdev);
if (err)
return err;
if (!(pci_resource_flags(pdev, 0) & IORESOURCE_MEM)) {
pr_err("%s: cannot find PCI device memory base address\n",
pci_name(pdev));
err = -ENODEV;
goto out_disable_pdev;
}
if (!pci_set_dma_mask(pdev, DMA_BIT_MASK(64))) {
pci_using_dac = 1;
if (pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64))) {
pr_err("%s: unable to obtain 64-bit DMA for "
"consistent allocations\n", pci_name(pdev));
err = -ENODEV;
goto out_disable_pdev;
}
} else if ((err = pci_set_dma_mask(pdev, DMA_BIT_MASK(32))) != 0) {
pr_err("%s: no usable DMA configuration\n", pci_name(pdev));
goto out_disable_pdev;
}
err = pci_request_regions(pdev, DRV_NAME);
if (err) {
pr_err("%s: cannot obtain PCI resources\n", pci_name(pdev));
goto out_disable_pdev;
}
pci_set_master(pdev);
mmio_start = pci_resource_start(pdev, 0);
mmio_len = pci_resource_len(pdev, 0);
bi = t1_get_board_info(ent->driver_data);
for (i = 0; i < bi->port_number; ++i) {
struct net_device *netdev;
netdev = alloc_etherdev(adapter ? 0 : sizeof(*adapter));
if (!netdev) {
err = -ENOMEM;
goto out_free_dev;
}
SET_NETDEV_DEV(netdev, &pdev->dev);
if (!adapter) {
adapter = netdev_priv(netdev);
adapter->pdev = pdev;
adapter->port[0].dev = netdev; /* so we don't leak it */
adapter->regs = ioremap(mmio_start, mmio_len);
if (!adapter->regs) {
pr_err("%s: cannot map device registers\n",
pci_name(pdev));
err = -ENOMEM;
goto out_free_dev;
}
if (t1_get_board_rev(adapter, bi, &adapter->params)) {
err = -ENODEV; /* Can't handle this chip rev */
goto out_free_dev;
}
adapter->name = pci_name(pdev);
adapter->msg_enable = dflt_msg_enable;
adapter->mmio_len = mmio_len;
spin_lock_init(&adapter->tpi_lock);
spin_lock_init(&adapter->work_lock);
spin_lock_init(&adapter->async_lock);
spin_lock_init(&adapter->mac_lock);
INIT_WORK(&adapter->ext_intr_handler_task,
ext_intr_task);
INIT_DELAYED_WORK(&adapter->stats_update_task,
mac_stats_task);
pci_set_drvdata(pdev, netdev);
}
pi = &adapter->port[i];
pi->dev = netdev;
netif_carrier_off(netdev);
netdev->irq = pdev->irq;
netdev->if_port = i;
netdev->mem_start = mmio_start;
netdev->mem_end = mmio_start + mmio_len - 1;
netdev->ml_priv = adapter;
netdev->hw_features |= NETIF_F_SG | NETIF_F_IP_CSUM |
NETIF_F_RXCSUM;
netdev->features |= NETIF_F_SG | NETIF_F_IP_CSUM |
NETIF_F_RXCSUM | NETIF_F_LLTX;
if (pci_using_dac)
netdev->features |= NETIF_F_HIGHDMA;
if (vlan_tso_capable(adapter)) {
#if defined(CONFIG_VLAN_8021Q) || defined(CONFIG_VLAN_8021Q_MODULE)
netdev->features |=
NETIF_F_HW_VLAN_TX | NETIF_F_HW_VLAN_RX;
#endif
/* T204: disable TSO */
if (!(is_T2(adapter)) || bi->port_number != 4) {
netdev->hw_features |= NETIF_F_TSO;
netdev->features |= NETIF_F_TSO;
}
}
netdev->netdev_ops = &cxgb_netdev_ops;
netdev->hard_header_len += (netdev->hw_features & NETIF_F_TSO) ?
sizeof(struct cpl_tx_pkt_lso) : sizeof(struct cpl_tx_pkt);
netif_napi_add(netdev, &adapter->napi, t1_poll, 64);
SET_ETHTOOL_OPS(netdev, &t1_ethtool_ops);
}
if (t1_init_sw_modules(adapter, bi) < 0) {
err = -ENODEV;
goto out_free_dev;
}
/*
* The card is now ready to go. If any errors occur during device
* registration we do not fail the whole card but rather proceed only
* with the ports we manage to register successfully. However we must
* register at least one net device.
*/
for (i = 0; i < bi->port_number; ++i) {
err = register_netdev(adapter->port[i].dev);
if (err)
pr_warning("%s: cannot register net device %s, skipping\n",
pci_name(pdev), adapter->port[i].dev->name);
else {
/*
* Change the name we use for messages to the name of
* the first successfully registered interface.
*/
if (!adapter->registered_device_map)
adapter->name = adapter->port[i].dev->name;
__set_bit(i, &adapter->registered_device_map);
}
}
if (!adapter->registered_device_map) {
pr_err("%s: could not register any net devices\n",
pci_name(pdev));
goto out_release_adapter_res;
}
printk(KERN_INFO "%s: %s (rev %d), %s %dMHz/%d-bit\n", adapter->name,
bi->desc, adapter->params.chip_revision,
adapter->params.pci.is_pcix ? "PCIX" : "PCI",
adapter->params.pci.speed, adapter->params.pci.width);
/*
* Set the T1B ASIC and memory clocks.
*/
if (t1powersave)
adapter->t1powersave = LCLOCK; /* HW default is powersave mode. */
else
adapter->t1powersave = HCLOCK;
if (t1_is_T1B(adapter))
t1_clock(adapter, t1powersave);
return 0;
out_release_adapter_res:
t1_free_sw_modules(adapter);
out_free_dev:
if (adapter) {
if (adapter->regs)
iounmap(adapter->regs);
for (i = bi->port_number - 1; i >= 0; --i)
if (adapter->port[i].dev)
free_netdev(adapter->port[i].dev);
}
pci_release_regions(pdev);
out_disable_pdev:
pci_disable_device(pdev);
pci_set_drvdata(pdev, NULL);
return err;
}
static void bit_bang(struct adapter *adapter, int bitdata, int nbits)
{
int data;
int i;
u32 val;
enum {
S_CLOCK = 1 << 3,
S_DATA = 1 << 4
};
for (i = (nbits - 1); i > -1; i--) {
udelay(50);
data = ((bitdata >> i) & 0x1);
__t1_tpi_read(adapter, A_ELMER0_GPO, &val);
if (data)
val |= S_DATA;
else
val &= ~S_DATA;
udelay(50);
/* Set SCLOCK low */
val &= ~S_CLOCK;
__t1_tpi_write(adapter, A_ELMER0_GPO, val);
udelay(50);
/* Write SCLOCK high */
val |= S_CLOCK;
__t1_tpi_write(adapter, A_ELMER0_GPO, val);
}
}
static int t1_clock(struct adapter *adapter, int mode)
{
u32 val;
int M_CORE_VAL;
int M_MEM_VAL;
enum {
M_CORE_BITS = 9,
T_CORE_VAL = 0,
T_CORE_BITS = 2,
N_CORE_VAL = 0,
N_CORE_BITS = 2,
M_MEM_BITS = 9,
T_MEM_VAL = 0,
T_MEM_BITS = 2,
N_MEM_VAL = 0,
N_MEM_BITS = 2,
NP_LOAD = 1 << 17,
S_LOAD_MEM = 1 << 5,
S_LOAD_CORE = 1 << 6,
S_CLOCK = 1 << 3
};
if (!t1_is_T1B(adapter))
return -ENODEV; /* Can't re-clock this chip. */
if (mode & 2)
return 0; /* show current mode. */
if ((adapter->t1powersave & 1) == (mode & 1))
return -EALREADY; /* ASIC already running in mode. */
if ((mode & 1) == HCLOCK) {
M_CORE_VAL = 0x14;
M_MEM_VAL = 0x18;
adapter->t1powersave = HCLOCK; /* overclock */
} else {
M_CORE_VAL = 0xe;
M_MEM_VAL = 0x10;
adapter->t1powersave = LCLOCK; /* underclock */
}
/* Don't interrupt this serial stream! */
spin_lock(&adapter->tpi_lock);
/* Initialize for ASIC core */
__t1_tpi_read(adapter, A_ELMER0_GPO, &val);
val |= NP_LOAD;
udelay(50);
__t1_tpi_write(adapter, A_ELMER0_GPO, val);
udelay(50);
__t1_tpi_read(adapter, A_ELMER0_GPO, &val);
val &= ~S_LOAD_CORE;
val &= ~S_CLOCK;
__t1_tpi_write(adapter, A_ELMER0_GPO, val);
udelay(50);
/* Serial program the ASIC clock synthesizer */
bit_bang(adapter, T_CORE_VAL, T_CORE_BITS);
bit_bang(adapter, N_CORE_VAL, N_CORE_BITS);
bit_bang(adapter, M_CORE_VAL, M_CORE_BITS);
udelay(50);
/* Finish ASIC core */
__t1_tpi_read(adapter, A_ELMER0_GPO, &val);
val |= S_LOAD_CORE;
udelay(50);
__t1_tpi_write(adapter, A_ELMER0_GPO, val);
udelay(50);
__t1_tpi_read(adapter, A_ELMER0_GPO, &val);
val &= ~S_LOAD_CORE;
udelay(50);
__t1_tpi_write(adapter, A_ELMER0_GPO, val);
udelay(50);
/* Initialize for memory */
__t1_tpi_read(adapter, A_ELMER0_GPO, &val);
val |= NP_LOAD;
udelay(50);
__t1_tpi_write(adapter, A_ELMER0_GPO, val);
udelay(50);
__t1_tpi_read(adapter, A_ELMER0_GPO, &val);
val &= ~S_LOAD_MEM;
val &= ~S_CLOCK;
udelay(50);
__t1_tpi_write(adapter, A_ELMER0_GPO, val);
udelay(50);
/* Serial program the memory clock synthesizer */
bit_bang(adapter, T_MEM_VAL, T_MEM_BITS);
bit_bang(adapter, N_MEM_VAL, N_MEM_BITS);
bit_bang(adapter, M_MEM_VAL, M_MEM_BITS);
udelay(50);
/* Finish memory */
__t1_tpi_read(adapter, A_ELMER0_GPO, &val);
val |= S_LOAD_MEM;
udelay(50);
__t1_tpi_write(adapter, A_ELMER0_GPO, val);
udelay(50);
__t1_tpi_read(adapter, A_ELMER0_GPO, &val);
val &= ~S_LOAD_MEM;
udelay(50);
__t1_tpi_write(adapter, A_ELMER0_GPO, val);
spin_unlock(&adapter->tpi_lock);
return 0;
}
static inline void t1_sw_reset(struct pci_dev *pdev)
{
pci_write_config_dword(pdev, A_PCICFG_PM_CSR, 3);
pci_write_config_dword(pdev, A_PCICFG_PM_CSR, 0);
}
static void __devexit remove_one(struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata(pdev);
struct adapter *adapter = dev->ml_priv;
int i;
for_each_port(adapter, i) {
if (test_bit(i, &adapter->registered_device_map))
unregister_netdev(adapter->port[i].dev);
}
t1_free_sw_modules(adapter);
iounmap(adapter->regs);
while (--i >= 0) {
if (adapter->port[i].dev)
free_netdev(adapter->port[i].dev);
}
pci_release_regions(pdev);
pci_disable_device(pdev);
pci_set_drvdata(pdev, NULL);
t1_sw_reset(pdev);
}
static struct pci_driver driver = {
.name = DRV_NAME,
.id_table = t1_pci_tbl,
.probe = init_one,
.remove = __devexit_p(remove_one),
};
static int __init t1_init_module(void)
{
return pci_register_driver(&driver);
}
static void __exit t1_cleanup_module(void)
{
pci_unregister_driver(&driver);
}
module_init(t1_init_module);
module_exit(t1_cleanup_module);
| gpl-2.0 |
z8cpaul/lsikernel-3.10 | arch/arm/mach-imx/mach-mx35_3ds.c | 2639 | 15304 | /*
* Copyright 2009 Freescale Semiconductor, Inc. All Rights Reserved.
* Copyright (C) 2009 Marc Kleine-Budde, Pengutronix
*
* Author: Fabio Estevam <fabio.estevam@freescale.com>
*
* Copyright (C) 2011 Meprolight, Ltd.
* Alex Gershgorin <alexg@meprolight.com>
*
* Modified from i.MX31 3-Stack Development System
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
/*
* This machine is known as:
* - i.MX35 3-Stack Development System
* - i.MX35 Platform Development Kit (i.MX35 PDK)
*/
#include <linux/types.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/memory.h>
#include <linux/gpio.h>
#include <linux/usb/otg.h>
#include <linux/mtd/physmap.h>
#include <linux/mfd/mc13892.h>
#include <linux/regulator/machine.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/time.h>
#include <asm/mach/map.h>
#include <asm/memblock.h>
#include <video/platform_lcd.h>
#include <media/soc_camera.h>
#include "3ds_debugboard.h"
#include "common.h"
#include "devices-imx35.h"
#include "hardware.h"
#include "iomux-mx35.h"
#define GPIO_MC9S08DZ60_GPS_ENABLE 0
#define GPIO_MC9S08DZ60_HDD_ENABLE 4
#define GPIO_MC9S08DZ60_WIFI_ENABLE 5
#define GPIO_MC9S08DZ60_LCD_ENABLE 6
#define GPIO_MC9S08DZ60_SPEAKER_ENABLE 8
static const struct fb_videomode fb_modedb[] = {
{
/* 800x480 @ 55 Hz */
.name = "Ceramate-CLAA070VC01",
.refresh = 55,
.xres = 800,
.yres = 480,
.pixclock = 40000,
.left_margin = 40,
.right_margin = 40,
.upper_margin = 5,
.lower_margin = 5,
.hsync_len = 20,
.vsync_len = 10,
.sync = FB_SYNC_OE_ACT_HIGH,
.vmode = FB_VMODE_NONINTERLACED,
.flag = 0,
},
};
static struct mx3fb_platform_data mx3fb_pdata __initdata = {
.name = "Ceramate-CLAA070VC01",
.mode = fb_modedb,
.num_modes = ARRAY_SIZE(fb_modedb),
};
static struct i2c_board_info __initdata i2c_devices_3ds[] = {
{
I2C_BOARD_INFO("mc9s08dz60", 0x69),
},
};
static int lcd_power_gpio = -ENXIO;
static int mc9s08dz60_gpiochip_match(struct gpio_chip *chip, void *data)
{
return !strcmp(chip->label, data);
}
static void mx35_3ds_lcd_set_power(
struct plat_lcd_data *pd, unsigned int power)
{
struct gpio_chip *chip;
if (!gpio_is_valid(lcd_power_gpio)) {
chip = gpiochip_find(
"mc9s08dz60", mc9s08dz60_gpiochip_match);
if (chip) {
lcd_power_gpio =
chip->base + GPIO_MC9S08DZ60_LCD_ENABLE;
if (gpio_request(lcd_power_gpio, "lcd_power") < 0) {
pr_err("error: gpio already requested!\n");
lcd_power_gpio = -ENXIO;
}
} else {
pr_err("error: didn't find mc9s08dz60 gpio chip\n");
}
}
if (gpio_is_valid(lcd_power_gpio))
gpio_set_value_cansleep(lcd_power_gpio, power);
}
static struct plat_lcd_data mx35_3ds_lcd_data = {
.set_power = mx35_3ds_lcd_set_power,
};
static struct platform_device mx35_3ds_lcd = {
.name = "platform-lcd",
.dev.platform_data = &mx35_3ds_lcd_data,
};
static const struct imxuart_platform_data uart_pdata __initconst = {
.flags = IMXUART_HAVE_RTSCTS,
};
static struct physmap_flash_data mx35pdk_flash_data = {
.width = 2,
};
static struct resource mx35pdk_flash_resource = {
.start = MX35_CS0_BASE_ADDR,
.end = MX35_CS0_BASE_ADDR + SZ_64M - 1,
.flags = IORESOURCE_MEM,
};
static struct platform_device mx35pdk_flash = {
.name = "physmap-flash",
.id = 0,
.dev = {
.platform_data = &mx35pdk_flash_data,
},
.resource = &mx35pdk_flash_resource,
.num_resources = 1,
};
static const struct mxc_nand_platform_data mx35pdk_nand_board_info __initconst = {
.width = 1,
.hw_ecc = 1,
.flash_bbt = 1,
};
static struct platform_device *devices[] __initdata = {
&mx35pdk_flash,
};
static iomux_v3_cfg_t mx35pdk_pads[] = {
/* UART1 */
MX35_PAD_CTS1__UART1_CTS,
MX35_PAD_RTS1__UART1_RTS,
MX35_PAD_TXD1__UART1_TXD_MUX,
MX35_PAD_RXD1__UART1_RXD_MUX,
/* FEC */
MX35_PAD_FEC_TX_CLK__FEC_TX_CLK,
MX35_PAD_FEC_RX_CLK__FEC_RX_CLK,
MX35_PAD_FEC_RX_DV__FEC_RX_DV,
MX35_PAD_FEC_COL__FEC_COL,
MX35_PAD_FEC_RDATA0__FEC_RDATA_0,
MX35_PAD_FEC_TDATA0__FEC_TDATA_0,
MX35_PAD_FEC_TX_EN__FEC_TX_EN,
MX35_PAD_FEC_MDC__FEC_MDC,
MX35_PAD_FEC_MDIO__FEC_MDIO,
MX35_PAD_FEC_TX_ERR__FEC_TX_ERR,
MX35_PAD_FEC_RX_ERR__FEC_RX_ERR,
MX35_PAD_FEC_CRS__FEC_CRS,
MX35_PAD_FEC_RDATA1__FEC_RDATA_1,
MX35_PAD_FEC_TDATA1__FEC_TDATA_1,
MX35_PAD_FEC_RDATA2__FEC_RDATA_2,
MX35_PAD_FEC_TDATA2__FEC_TDATA_2,
MX35_PAD_FEC_RDATA3__FEC_RDATA_3,
MX35_PAD_FEC_TDATA3__FEC_TDATA_3,
/* USBOTG */
MX35_PAD_USBOTG_PWR__USB_TOP_USBOTG_PWR,
MX35_PAD_USBOTG_OC__USB_TOP_USBOTG_OC,
/* USBH1 */
MX35_PAD_I2C2_CLK__USB_TOP_USBH2_PWR,
MX35_PAD_I2C2_DAT__USB_TOP_USBH2_OC,
/* SDCARD */
MX35_PAD_SD1_CMD__ESDHC1_CMD,
MX35_PAD_SD1_CLK__ESDHC1_CLK,
MX35_PAD_SD1_DATA0__ESDHC1_DAT0,
MX35_PAD_SD1_DATA1__ESDHC1_DAT1,
MX35_PAD_SD1_DATA2__ESDHC1_DAT2,
MX35_PAD_SD1_DATA3__ESDHC1_DAT3,
/* I2C1 */
MX35_PAD_I2C1_CLK__I2C1_SCL,
MX35_PAD_I2C1_DAT__I2C1_SDA,
/* Display */
MX35_PAD_LD0__IPU_DISPB_DAT_0,
MX35_PAD_LD1__IPU_DISPB_DAT_1,
MX35_PAD_LD2__IPU_DISPB_DAT_2,
MX35_PAD_LD3__IPU_DISPB_DAT_3,
MX35_PAD_LD4__IPU_DISPB_DAT_4,
MX35_PAD_LD5__IPU_DISPB_DAT_5,
MX35_PAD_LD6__IPU_DISPB_DAT_6,
MX35_PAD_LD7__IPU_DISPB_DAT_7,
MX35_PAD_LD8__IPU_DISPB_DAT_8,
MX35_PAD_LD9__IPU_DISPB_DAT_9,
MX35_PAD_LD10__IPU_DISPB_DAT_10,
MX35_PAD_LD11__IPU_DISPB_DAT_11,
MX35_PAD_LD12__IPU_DISPB_DAT_12,
MX35_PAD_LD13__IPU_DISPB_DAT_13,
MX35_PAD_LD14__IPU_DISPB_DAT_14,
MX35_PAD_LD15__IPU_DISPB_DAT_15,
MX35_PAD_LD16__IPU_DISPB_DAT_16,
MX35_PAD_LD17__IPU_DISPB_DAT_17,
MX35_PAD_D3_HSYNC__IPU_DISPB_D3_HSYNC,
MX35_PAD_D3_FPSHIFT__IPU_DISPB_D3_CLK,
MX35_PAD_D3_DRDY__IPU_DISPB_D3_DRDY,
MX35_PAD_CONTRAST__IPU_DISPB_CONTR,
MX35_PAD_D3_VSYNC__IPU_DISPB_D3_VSYNC,
MX35_PAD_D3_REV__IPU_DISPB_D3_REV,
MX35_PAD_D3_CLS__IPU_DISPB_D3_CLS,
/* CSI */
MX35_PAD_TX1__IPU_CSI_D_6,
MX35_PAD_TX0__IPU_CSI_D_7,
MX35_PAD_CSI_D8__IPU_CSI_D_8,
MX35_PAD_CSI_D9__IPU_CSI_D_9,
MX35_PAD_CSI_D10__IPU_CSI_D_10,
MX35_PAD_CSI_D11__IPU_CSI_D_11,
MX35_PAD_CSI_D12__IPU_CSI_D_12,
MX35_PAD_CSI_D13__IPU_CSI_D_13,
MX35_PAD_CSI_D14__IPU_CSI_D_14,
MX35_PAD_CSI_D15__IPU_CSI_D_15,
MX35_PAD_CSI_HSYNC__IPU_CSI_HSYNC,
MX35_PAD_CSI_MCLK__IPU_CSI_MCLK,
MX35_PAD_CSI_PIXCLK__IPU_CSI_PIXCLK,
MX35_PAD_CSI_VSYNC__IPU_CSI_VSYNC,
/*PMIC IRQ*/
MX35_PAD_GPIO2_0__GPIO2_0,
};
/*
* Camera support
*/
static phys_addr_t mx3_camera_base __initdata;
#define MX35_3DS_CAMERA_BUF_SIZE SZ_8M
static const struct mx3_camera_pdata mx35_3ds_camera_pdata __initconst = {
.flags = MX3_CAMERA_DATAWIDTH_8,
.mclk_10khz = 2000,
};
static int __init imx35_3ds_init_camera(void)
{
int dma, ret = -ENOMEM;
struct platform_device *pdev =
imx35_alloc_mx3_camera(&mx35_3ds_camera_pdata);
if (IS_ERR(pdev))
return PTR_ERR(pdev);
if (!mx3_camera_base)
goto err;
dma = dma_declare_coherent_memory(&pdev->dev,
mx3_camera_base, mx3_camera_base,
MX35_3DS_CAMERA_BUF_SIZE,
DMA_MEMORY_MAP | DMA_MEMORY_EXCLUSIVE);
if (!(dma & DMA_MEMORY_MAP))
goto err;
ret = platform_device_add(pdev);
if (ret)
err:
platform_device_put(pdev);
return ret;
}
static struct i2c_board_info mx35_3ds_i2c_camera = {
I2C_BOARD_INFO("ov2640", 0x30),
};
static struct soc_camera_link iclink_ov2640 = {
.bus_id = 0,
.board_info = &mx35_3ds_i2c_camera,
.i2c_adapter_id = 0,
.power = NULL,
};
static struct platform_device mx35_3ds_ov2640 = {
.name = "soc-camera-pdrv",
.id = 0,
.dev = {
.platform_data = &iclink_ov2640,
},
};
static struct regulator_consumer_supply sw1_consumers[] = {
{
.supply = "cpu_vcc",
}
};
static struct regulator_consumer_supply vcam_consumers[] = {
/* sgtl5000 */
REGULATOR_SUPPLY("VDDA", "0-000a"),
};
static struct regulator_consumer_supply vaudio_consumers[] = {
REGULATOR_SUPPLY("cmos_vio", "soc-camera-pdrv.0"),
};
static struct regulator_init_data sw1_init = {
.constraints = {
.name = "SW1",
.min_uV = 600000,
.max_uV = 1375000,
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE,
.valid_modes_mask = 0,
.always_on = 1,
.boot_on = 1,
},
.num_consumer_supplies = ARRAY_SIZE(sw1_consumers),
.consumer_supplies = sw1_consumers,
};
static struct regulator_init_data sw2_init = {
.constraints = {
.name = "SW2",
.always_on = 1,
.boot_on = 1,
}
};
static struct regulator_init_data sw3_init = {
.constraints = {
.name = "SW3",
.always_on = 1,
.boot_on = 1,
}
};
static struct regulator_init_data sw4_init = {
.constraints = {
.name = "SW4",
.always_on = 1,
.boot_on = 1,
}
};
static struct regulator_init_data viohi_init = {
.constraints = {
.name = "VIOHI",
.boot_on = 1,
}
};
static struct regulator_init_data vusb_init = {
.constraints = {
.name = "VUSB",
.boot_on = 1,
}
};
static struct regulator_init_data vdig_init = {
.constraints = {
.name = "VDIG",
.boot_on = 1,
}
};
static struct regulator_init_data vpll_init = {
.constraints = {
.name = "VPLL",
.boot_on = 1,
}
};
static struct regulator_init_data vusb2_init = {
.constraints = {
.name = "VUSB2",
.boot_on = 1,
}
};
static struct regulator_init_data vvideo_init = {
.constraints = {
.name = "VVIDEO",
.boot_on = 1
}
};
static struct regulator_init_data vaudio_init = {
.constraints = {
.name = "VAUDIO",
.min_uV = 2300000,
.max_uV = 3000000,
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE,
.boot_on = 1
},
.num_consumer_supplies = ARRAY_SIZE(vaudio_consumers),
.consumer_supplies = vaudio_consumers,
};
static struct regulator_init_data vcam_init = {
.constraints = {
.name = "VCAM",
.min_uV = 2500000,
.max_uV = 3000000,
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE |
REGULATOR_CHANGE_MODE,
.valid_modes_mask = REGULATOR_MODE_FAST | REGULATOR_MODE_NORMAL,
.boot_on = 1
},
.num_consumer_supplies = ARRAY_SIZE(vcam_consumers),
.consumer_supplies = vcam_consumers,
};
static struct regulator_init_data vgen1_init = {
.constraints = {
.name = "VGEN1",
}
};
static struct regulator_init_data vgen2_init = {
.constraints = {
.name = "VGEN2",
.boot_on = 1,
}
};
static struct regulator_init_data vgen3_init = {
.constraints = {
.name = "VGEN3",
}
};
static struct mc13xxx_regulator_init_data mx35_3ds_regulators[] = {
{ .id = MC13892_SW1, .init_data = &sw1_init },
{ .id = MC13892_SW2, .init_data = &sw2_init },
{ .id = MC13892_SW3, .init_data = &sw3_init },
{ .id = MC13892_SW4, .init_data = &sw4_init },
{ .id = MC13892_VIOHI, .init_data = &viohi_init },
{ .id = MC13892_VPLL, .init_data = &vpll_init },
{ .id = MC13892_VDIG, .init_data = &vdig_init },
{ .id = MC13892_VUSB2, .init_data = &vusb2_init },
{ .id = MC13892_VVIDEO, .init_data = &vvideo_init },
{ .id = MC13892_VAUDIO, .init_data = &vaudio_init },
{ .id = MC13892_VCAM, .init_data = &vcam_init },
{ .id = MC13892_VGEN1, .init_data = &vgen1_init },
{ .id = MC13892_VGEN2, .init_data = &vgen2_init },
{ .id = MC13892_VGEN3, .init_data = &vgen3_init },
{ .id = MC13892_VUSB, .init_data = &vusb_init },
};
static struct mc13xxx_platform_data mx35_3ds_mc13892_data = {
.flags = MC13XXX_USE_RTC | MC13XXX_USE_TOUCHSCREEN,
.regulators = {
.num_regulators = ARRAY_SIZE(mx35_3ds_regulators),
.regulators = mx35_3ds_regulators,
},
};
#define GPIO_PMIC_INT IMX_GPIO_NR(2, 0)
static struct i2c_board_info mx35_3ds_i2c_mc13892 = {
I2C_BOARD_INFO("mc13892", 0x08),
.platform_data = &mx35_3ds_mc13892_data,
/* irq number is run-time assigned */
};
static void __init imx35_3ds_init_mc13892(void)
{
int ret = gpio_request_one(GPIO_PMIC_INT, GPIOF_DIR_IN, "pmic irq");
if (ret) {
pr_err("failed to get pmic irq: %d\n", ret);
return;
}
mx35_3ds_i2c_mc13892.irq = gpio_to_irq(GPIO_PMIC_INT);
i2c_register_board_info(0, &mx35_3ds_i2c_mc13892, 1);
}
static int mx35_3ds_otg_init(struct platform_device *pdev)
{
return mx35_initialize_usb_hw(pdev->id, MXC_EHCI_INTERNAL_PHY);
}
/* OTG config */
static const struct fsl_usb2_platform_data usb_otg_pdata __initconst = {
.operating_mode = FSL_USB2_DR_DEVICE,
.phy_mode = FSL_USB2_PHY_UTMI_WIDE,
.workaround = FLS_USB2_WORKAROUND_ENGCM09152,
/*
* ENGCM09152 also requires a hardware change.
* Please check the MX35 Chip Errata document for details.
*/
};
static struct mxc_usbh_platform_data otg_pdata __initdata = {
.init = mx35_3ds_otg_init,
.portsc = MXC_EHCI_MODE_UTMI,
};
static int mx35_3ds_usbh_init(struct platform_device *pdev)
{
return mx35_initialize_usb_hw(pdev->id, MXC_EHCI_INTERFACE_SINGLE_UNI |
MXC_EHCI_INTERNAL_PHY);
}
/* USB HOST config */
static const struct mxc_usbh_platform_data usb_host_pdata __initconst = {
.init = mx35_3ds_usbh_init,
.portsc = MXC_EHCI_MODE_SERIAL,
};
static bool otg_mode_host __initdata;
static int __init mx35_3ds_otg_mode(char *options)
{
if (!strcmp(options, "host"))
otg_mode_host = true;
else if (!strcmp(options, "device"))
otg_mode_host = false;
else
pr_info("otg_mode neither \"host\" nor \"device\". "
"Defaulting to device\n");
return 1;
}
__setup("otg_mode=", mx35_3ds_otg_mode);
static const struct imxi2c_platform_data mx35_3ds_i2c0_data __initconst = {
.bitrate = 100000,
};
/*
* Board specific initialization.
*/
static void __init mx35_3ds_init(void)
{
struct platform_device *imx35_fb_pdev;
imx35_soc_init();
mxc_iomux_v3_setup_multiple_pads(mx35pdk_pads, ARRAY_SIZE(mx35pdk_pads));
imx35_add_fec(NULL);
imx35_add_imx2_wdt();
imx35_add_mxc_rtc();
platform_add_devices(devices, ARRAY_SIZE(devices));
imx35_add_imx_uart0(&uart_pdata);
if (otg_mode_host)
imx35_add_mxc_ehci_otg(&otg_pdata);
imx35_add_mxc_ehci_hs(&usb_host_pdata);
if (!otg_mode_host)
imx35_add_fsl_usb2_udc(&usb_otg_pdata);
imx35_add_mxc_nand(&mx35pdk_nand_board_info);
imx35_add_sdhci_esdhc_imx(0, NULL);
if (mxc_expio_init(MX35_CS5_BASE_ADDR, IMX_GPIO_NR(1, 1)))
pr_warn("Init of the debugboard failed, all "
"devices on the debugboard are unusable.\n");
imx35_add_imx_i2c0(&mx35_3ds_i2c0_data);
i2c_register_board_info(
0, i2c_devices_3ds, ARRAY_SIZE(i2c_devices_3ds));
imx35_add_ipu_core();
platform_device_register(&mx35_3ds_ov2640);
imx35_3ds_init_camera();
imx35_fb_pdev = imx35_add_mx3_sdc_fb(&mx3fb_pdata);
mx35_3ds_lcd.dev.parent = &imx35_fb_pdev->dev;
platform_device_register(&mx35_3ds_lcd);
imx35_3ds_init_mc13892();
}
static void __init mx35pdk_timer_init(void)
{
mx35_clocks_init();
}
static void __init mx35_3ds_reserve(void)
{
/* reserve MX35_3DS_CAMERA_BUF_SIZE bytes for mx3-camera */
mx3_camera_base = arm_memblock_steal(MX35_3DS_CAMERA_BUF_SIZE,
MX35_3DS_CAMERA_BUF_SIZE);
}
MACHINE_START(MX35_3DS, "Freescale MX35PDK")
/* Maintainer: Freescale Semiconductor, Inc */
.atag_offset = 0x100,
.map_io = mx35_map_io,
.init_early = imx35_init_early,
.init_irq = mx35_init_irq,
.handle_irq = imx35_handle_irq,
.init_time = mx35pdk_timer_init,
.init_machine = mx35_3ds_init,
.reserve = mx35_3ds_reserve,
.restart = mxc_restart,
MACHINE_END
| gpl-2.0 |
arm10c/linux-stable | arch/arm/mach-s5pv210/setup-sdhci-gpio.c | 2639 | 3178 | /* linux/arch/arm/plat-s5pc1xx/setup-sdhci-gpio.c
*
* Copyright (c) 2009-2010 Samsung Electronics Co., Ltd.
* http://www.samsung.com/
*
* S5PV210 - Helper functions for setting up SDHCI device(s) GPIO (HSMMC)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/gpio.h>
#include <linux/mmc/host.h>
#include <linux/mmc/card.h>
#include <plat/gpio-cfg.h>
#include <plat/sdhci.h>
void s5pv210_setup_sdhci0_cfg_gpio(struct platform_device *dev, int width)
{
struct s3c_sdhci_platdata *pdata = dev->dev.platform_data;
/* Set all the necessary GPG0/GPG1 pins to special-function 2 */
s3c_gpio_cfgrange_nopull(S5PV210_GPG0(0), 2, S3C_GPIO_SFN(2));
switch (width) {
case 8:
/* GPG1[3:6] special-function 3 */
s3c_gpio_cfgrange_nopull(S5PV210_GPG1(3), 4, S3C_GPIO_SFN(3));
case 4:
/* GPG0[3:6] special-function 2 */
s3c_gpio_cfgrange_nopull(S5PV210_GPG0(3), 4, S3C_GPIO_SFN(2));
default:
break;
}
if (pdata->cd_type == S3C_SDHCI_CD_INTERNAL) {
s3c_gpio_setpull(S5PV210_GPG0(2), S3C_GPIO_PULL_UP);
s3c_gpio_cfgpin(S5PV210_GPG0(2), S3C_GPIO_SFN(2));
}
}
void s5pv210_setup_sdhci1_cfg_gpio(struct platform_device *dev, int width)
{
struct s3c_sdhci_platdata *pdata = dev->dev.platform_data;
/* Set all the necessary GPG1[0:1] pins to special-function 2 */
s3c_gpio_cfgrange_nopull(S5PV210_GPG1(0), 2, S3C_GPIO_SFN(2));
/* Data pin GPG1[3:6] to special-function 2 */
s3c_gpio_cfgrange_nopull(S5PV210_GPG1(3), 4, S3C_GPIO_SFN(2));
if (pdata->cd_type == S3C_SDHCI_CD_INTERNAL) {
s3c_gpio_setpull(S5PV210_GPG1(2), S3C_GPIO_PULL_UP);
s3c_gpio_cfgpin(S5PV210_GPG1(2), S3C_GPIO_SFN(2));
}
}
void s5pv210_setup_sdhci2_cfg_gpio(struct platform_device *dev, int width)
{
struct s3c_sdhci_platdata *pdata = dev->dev.platform_data;
/* Set all the necessary GPG2[0:1] pins to special-function 2 */
s3c_gpio_cfgrange_nopull(S5PV210_GPG2(0), 2, S3C_GPIO_SFN(2));
switch (width) {
case 8:
/* Data pin GPG3[3:6] to special-function 3 */
s3c_gpio_cfgrange_nopull(S5PV210_GPG3(3), 4, S3C_GPIO_SFN(3));
case 4:
/* Data pin GPG2[3:6] to special-function 2 */
s3c_gpio_cfgrange_nopull(S5PV210_GPG2(3), 4, S3C_GPIO_SFN(2));
default:
break;
}
if (pdata->cd_type == S3C_SDHCI_CD_INTERNAL) {
s3c_gpio_setpull(S5PV210_GPG2(2), S3C_GPIO_PULL_UP);
s3c_gpio_cfgpin(S5PV210_GPG2(2), S3C_GPIO_SFN(2));
}
}
void s5pv210_setup_sdhci3_cfg_gpio(struct platform_device *dev, int width)
{
struct s3c_sdhci_platdata *pdata = dev->dev.platform_data;
/* Set all the necessary GPG3[0:1] pins to special-function 2 */
s3c_gpio_cfgrange_nopull(S5PV210_GPG3(0), 2, S3C_GPIO_SFN(2));
/* Data pin GPG3[3:6] to special-function 2 */
s3c_gpio_cfgrange_nopull(S5PV210_GPG3(3), 4, S3C_GPIO_SFN(2));
if (pdata->cd_type == S3C_SDHCI_CD_INTERNAL) {
s3c_gpio_setpull(S5PV210_GPG3(2), S3C_GPIO_PULL_UP);
s3c_gpio_cfgpin(S5PV210_GPG3(2), S3C_GPIO_SFN(2));
}
}
| gpl-2.0 |
sxwzhw/Solid_Kernel-GPROJ-CAF | drivers/usb/host/ohci-ep93xx.c | 4943 | 4990 | /*
* OHCI HCD (Host Controller Driver) for USB.
*
* (C) Copyright 1999 Roman Weissgaerber <weissg@vienna.at>
* (C) Copyright 2000-2002 David Brownell <dbrownell@users.sourceforge.net>
* (C) Copyright 2002 Hewlett-Packard Company
*
* Bus Glue for ep93xx.
*
* Written by Christopher Hoover <ch@hpl.hp.com>
* Based on fragments of previous driver by Russell King et al.
*
* Modified for LH7A404 from ohci-sa1111.c
* by Durgesh Pattamatta <pattamattad@sharpsec.com>
*
* Modified for pxa27x from ohci-lh7a404.c
* by Nick Bane <nick@cecomputing.co.uk> 26-8-2004
*
* Modified for ep93xx from ohci-pxa27x.c
* by Lennert Buytenhek <buytenh@wantstofly.org> 28-2-2006
* Based on an earlier driver by Ray Lehtiniemi
*
* This file is licenced under the GPL.
*/
#include <linux/clk.h>
#include <linux/device.h>
#include <linux/signal.h>
#include <linux/platform_device.h>
static struct clk *usb_host_clock;
static void ep93xx_start_hc(struct device *dev)
{
clk_enable(usb_host_clock);
}
static void ep93xx_stop_hc(struct device *dev)
{
clk_disable(usb_host_clock);
}
static int usb_hcd_ep93xx_probe(const struct hc_driver *driver,
struct platform_device *pdev)
{
int retval;
struct usb_hcd *hcd;
if (pdev->resource[1].flags != IORESOURCE_IRQ) {
dbg("resource[1] is not IORESOURCE_IRQ");
return -ENOMEM;
}
hcd = usb_create_hcd(driver, &pdev->dev, "ep93xx");
if (hcd == NULL)
return -ENOMEM;
hcd->rsrc_start = pdev->resource[0].start;
hcd->rsrc_len = pdev->resource[0].end - pdev->resource[0].start + 1;
if (!request_mem_region(hcd->rsrc_start, hcd->rsrc_len, hcd_name)) {
usb_put_hcd(hcd);
retval = -EBUSY;
goto err1;
}
hcd->regs = ioremap(hcd->rsrc_start, hcd->rsrc_len);
if (hcd->regs == NULL) {
dbg("ioremap failed");
retval = -ENOMEM;
goto err2;
}
usb_host_clock = clk_get(&pdev->dev, NULL);
if (IS_ERR(usb_host_clock)) {
dbg("clk_get failed");
retval = PTR_ERR(usb_host_clock);
goto err3;
}
ep93xx_start_hc(&pdev->dev);
ohci_hcd_init(hcd_to_ohci(hcd));
retval = usb_add_hcd(hcd, pdev->resource[1].start, 0);
if (retval == 0)
return retval;
ep93xx_stop_hc(&pdev->dev);
err3:
iounmap(hcd->regs);
err2:
release_mem_region(hcd->rsrc_start, hcd->rsrc_len);
err1:
usb_put_hcd(hcd);
return retval;
}
static void usb_hcd_ep93xx_remove(struct usb_hcd *hcd,
struct platform_device *pdev)
{
usb_remove_hcd(hcd);
ep93xx_stop_hc(&pdev->dev);
clk_put(usb_host_clock);
iounmap(hcd->regs);
release_mem_region(hcd->rsrc_start, hcd->rsrc_len);
usb_put_hcd(hcd);
}
static int __devinit ohci_ep93xx_start(struct usb_hcd *hcd)
{
struct ohci_hcd *ohci = hcd_to_ohci(hcd);
int ret;
if ((ret = ohci_init(ohci)) < 0)
return ret;
if ((ret = ohci_run(ohci)) < 0) {
err("can't start %s", hcd->self.bus_name);
ohci_stop(hcd);
return ret;
}
return 0;
}
static struct hc_driver ohci_ep93xx_hc_driver = {
.description = hcd_name,
.product_desc = "EP93xx OHCI",
.hcd_priv_size = sizeof(struct ohci_hcd),
.irq = ohci_irq,
.flags = HCD_USB11 | HCD_MEMORY,
.start = ohci_ep93xx_start,
.stop = ohci_stop,
.shutdown = ohci_shutdown,
.urb_enqueue = ohci_urb_enqueue,
.urb_dequeue = ohci_urb_dequeue,
.endpoint_disable = ohci_endpoint_disable,
.get_frame_number = ohci_get_frame,
.hub_status_data = ohci_hub_status_data,
.hub_control = ohci_hub_control,
#ifdef CONFIG_PM
.bus_suspend = ohci_bus_suspend,
.bus_resume = ohci_bus_resume,
#endif
.start_port_reset = ohci_start_port_reset,
};
extern int usb_disabled(void);
static int ohci_hcd_ep93xx_drv_probe(struct platform_device *pdev)
{
int ret;
ret = -ENODEV;
if (!usb_disabled())
ret = usb_hcd_ep93xx_probe(&ohci_ep93xx_hc_driver, pdev);
return ret;
}
static int ohci_hcd_ep93xx_drv_remove(struct platform_device *pdev)
{
struct usb_hcd *hcd = platform_get_drvdata(pdev);
usb_hcd_ep93xx_remove(hcd, pdev);
return 0;
}
#ifdef CONFIG_PM
static int ohci_hcd_ep93xx_drv_suspend(struct platform_device *pdev, pm_message_t state)
{
struct usb_hcd *hcd = platform_get_drvdata(pdev);
struct ohci_hcd *ohci = hcd_to_ohci(hcd);
if (time_before(jiffies, ohci->next_statechange))
msleep(5);
ohci->next_statechange = jiffies;
ep93xx_stop_hc(&pdev->dev);
return 0;
}
static int ohci_hcd_ep93xx_drv_resume(struct platform_device *pdev)
{
struct usb_hcd *hcd = platform_get_drvdata(pdev);
struct ohci_hcd *ohci = hcd_to_ohci(hcd);
if (time_before(jiffies, ohci->next_statechange))
msleep(5);
ohci->next_statechange = jiffies;
ep93xx_start_hc(&pdev->dev);
ohci_finish_controller_resume(hcd);
return 0;
}
#endif
static struct platform_driver ohci_hcd_ep93xx_driver = {
.probe = ohci_hcd_ep93xx_drv_probe,
.remove = ohci_hcd_ep93xx_drv_remove,
.shutdown = usb_hcd_platform_shutdown,
#ifdef CONFIG_PM
.suspend = ohci_hcd_ep93xx_drv_suspend,
.resume = ohci_hcd_ep93xx_drv_resume,
#endif
.driver = {
.name = "ep93xx-ohci",
.owner = THIS_MODULE,
},
};
MODULE_ALIAS("platform:ep93xx-ohci");
| gpl-2.0 |
Snuzzo/B14CKB1RD_kernel_m8 | drivers/crypto/s5p-sss.c | 4943 | 18135 | /*
* Cryptographic API.
*
* Support for Samsung S5PV210 HW acceleration.
*
* Copyright (C) 2011 NetUP Inc. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
*/
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/clk.h>
#include <linux/platform_device.h>
#include <linux/scatterlist.h>
#include <linux/dma-mapping.h>
#include <linux/io.h>
#include <linux/crypto.h>
#include <linux/interrupt.h>
#include <crypto/algapi.h>
#include <crypto/aes.h>
#include <crypto/ctr.h>
#include <plat/cpu.h>
#include <plat/dma.h>
#define _SBF(s, v) ((v) << (s))
#define _BIT(b) _SBF(b, 1)
/* Feed control registers */
#define SSS_REG_FCINTSTAT 0x0000
#define SSS_FCINTSTAT_BRDMAINT _BIT(3)
#define SSS_FCINTSTAT_BTDMAINT _BIT(2)
#define SSS_FCINTSTAT_HRDMAINT _BIT(1)
#define SSS_FCINTSTAT_PKDMAINT _BIT(0)
#define SSS_REG_FCINTENSET 0x0004
#define SSS_FCINTENSET_BRDMAINTENSET _BIT(3)
#define SSS_FCINTENSET_BTDMAINTENSET _BIT(2)
#define SSS_FCINTENSET_HRDMAINTENSET _BIT(1)
#define SSS_FCINTENSET_PKDMAINTENSET _BIT(0)
#define SSS_REG_FCINTENCLR 0x0008
#define SSS_FCINTENCLR_BRDMAINTENCLR _BIT(3)
#define SSS_FCINTENCLR_BTDMAINTENCLR _BIT(2)
#define SSS_FCINTENCLR_HRDMAINTENCLR _BIT(1)
#define SSS_FCINTENCLR_PKDMAINTENCLR _BIT(0)
#define SSS_REG_FCINTPEND 0x000C
#define SSS_FCINTPEND_BRDMAINTP _BIT(3)
#define SSS_FCINTPEND_BTDMAINTP _BIT(2)
#define SSS_FCINTPEND_HRDMAINTP _BIT(1)
#define SSS_FCINTPEND_PKDMAINTP _BIT(0)
#define SSS_REG_FCFIFOSTAT 0x0010
#define SSS_FCFIFOSTAT_BRFIFOFUL _BIT(7)
#define SSS_FCFIFOSTAT_BRFIFOEMP _BIT(6)
#define SSS_FCFIFOSTAT_BTFIFOFUL _BIT(5)
#define SSS_FCFIFOSTAT_BTFIFOEMP _BIT(4)
#define SSS_FCFIFOSTAT_HRFIFOFUL _BIT(3)
#define SSS_FCFIFOSTAT_HRFIFOEMP _BIT(2)
#define SSS_FCFIFOSTAT_PKFIFOFUL _BIT(1)
#define SSS_FCFIFOSTAT_PKFIFOEMP _BIT(0)
#define SSS_REG_FCFIFOCTRL 0x0014
#define SSS_FCFIFOCTRL_DESSEL _BIT(2)
#define SSS_HASHIN_INDEPENDENT _SBF(0, 0x00)
#define SSS_HASHIN_CIPHER_INPUT _SBF(0, 0x01)
#define SSS_HASHIN_CIPHER_OUTPUT _SBF(0, 0x02)
#define SSS_REG_FCBRDMAS 0x0020
#define SSS_REG_FCBRDMAL 0x0024
#define SSS_REG_FCBRDMAC 0x0028
#define SSS_FCBRDMAC_BYTESWAP _BIT(1)
#define SSS_FCBRDMAC_FLUSH _BIT(0)
#define SSS_REG_FCBTDMAS 0x0030
#define SSS_REG_FCBTDMAL 0x0034
#define SSS_REG_FCBTDMAC 0x0038
#define SSS_FCBTDMAC_BYTESWAP _BIT(1)
#define SSS_FCBTDMAC_FLUSH _BIT(0)
#define SSS_REG_FCHRDMAS 0x0040
#define SSS_REG_FCHRDMAL 0x0044
#define SSS_REG_FCHRDMAC 0x0048
#define SSS_FCHRDMAC_BYTESWAP _BIT(1)
#define SSS_FCHRDMAC_FLUSH _BIT(0)
#define SSS_REG_FCPKDMAS 0x0050
#define SSS_REG_FCPKDMAL 0x0054
#define SSS_REG_FCPKDMAC 0x0058
#define SSS_FCPKDMAC_BYTESWAP _BIT(3)
#define SSS_FCPKDMAC_DESCEND _BIT(2)
#define SSS_FCPKDMAC_TRANSMIT _BIT(1)
#define SSS_FCPKDMAC_FLUSH _BIT(0)
#define SSS_REG_FCPKDMAO 0x005C
/* AES registers */
#define SSS_REG_AES_CONTROL 0x4000
#define SSS_AES_BYTESWAP_DI _BIT(11)
#define SSS_AES_BYTESWAP_DO _BIT(10)
#define SSS_AES_BYTESWAP_IV _BIT(9)
#define SSS_AES_BYTESWAP_CNT _BIT(8)
#define SSS_AES_BYTESWAP_KEY _BIT(7)
#define SSS_AES_KEY_CHANGE_MODE _BIT(6)
#define SSS_AES_KEY_SIZE_128 _SBF(4, 0x00)
#define SSS_AES_KEY_SIZE_192 _SBF(4, 0x01)
#define SSS_AES_KEY_SIZE_256 _SBF(4, 0x02)
#define SSS_AES_FIFO_MODE _BIT(3)
#define SSS_AES_CHAIN_MODE_ECB _SBF(1, 0x00)
#define SSS_AES_CHAIN_MODE_CBC _SBF(1, 0x01)
#define SSS_AES_CHAIN_MODE_CTR _SBF(1, 0x02)
#define SSS_AES_MODE_DECRYPT _BIT(0)
#define SSS_REG_AES_STATUS 0x4004
#define SSS_AES_BUSY _BIT(2)
#define SSS_AES_INPUT_READY _BIT(1)
#define SSS_AES_OUTPUT_READY _BIT(0)
#define SSS_REG_AES_IN_DATA(s) (0x4010 + (s << 2))
#define SSS_REG_AES_OUT_DATA(s) (0x4020 + (s << 2))
#define SSS_REG_AES_IV_DATA(s) (0x4030 + (s << 2))
#define SSS_REG_AES_CNT_DATA(s) (0x4040 + (s << 2))
#define SSS_REG_AES_KEY_DATA(s) (0x4080 + (s << 2))
#define SSS_REG(dev, reg) ((dev)->ioaddr + (SSS_REG_##reg))
#define SSS_READ(dev, reg) __raw_readl(SSS_REG(dev, reg))
#define SSS_WRITE(dev, reg, val) __raw_writel((val), SSS_REG(dev, reg))
/* HW engine modes */
#define FLAGS_AES_DECRYPT _BIT(0)
#define FLAGS_AES_MODE_MASK _SBF(1, 0x03)
#define FLAGS_AES_CBC _SBF(1, 0x01)
#define FLAGS_AES_CTR _SBF(1, 0x02)
#define AES_KEY_LEN 16
#define CRYPTO_QUEUE_LEN 1
struct s5p_aes_reqctx {
unsigned long mode;
};
struct s5p_aes_ctx {
struct s5p_aes_dev *dev;
uint8_t aes_key[AES_MAX_KEY_SIZE];
uint8_t nonce[CTR_RFC3686_NONCE_SIZE];
int keylen;
};
struct s5p_aes_dev {
struct device *dev;
struct clk *clk;
void __iomem *ioaddr;
int irq_hash;
int irq_fc;
struct ablkcipher_request *req;
struct s5p_aes_ctx *ctx;
struct scatterlist *sg_src;
struct scatterlist *sg_dst;
struct tasklet_struct tasklet;
struct crypto_queue queue;
bool busy;
spinlock_t lock;
};
static struct s5p_aes_dev *s5p_dev;
static void s5p_set_dma_indata(struct s5p_aes_dev *dev, struct scatterlist *sg)
{
SSS_WRITE(dev, FCBRDMAS, sg_dma_address(sg));
SSS_WRITE(dev, FCBRDMAL, sg_dma_len(sg));
}
static void s5p_set_dma_outdata(struct s5p_aes_dev *dev, struct scatterlist *sg)
{
SSS_WRITE(dev, FCBTDMAS, sg_dma_address(sg));
SSS_WRITE(dev, FCBTDMAL, sg_dma_len(sg));
}
static void s5p_aes_complete(struct s5p_aes_dev *dev, int err)
{
/* holding a lock outside */
dev->req->base.complete(&dev->req->base, err);
dev->busy = false;
}
static void s5p_unset_outdata(struct s5p_aes_dev *dev)
{
dma_unmap_sg(dev->dev, dev->sg_dst, 1, DMA_FROM_DEVICE);
}
static void s5p_unset_indata(struct s5p_aes_dev *dev)
{
dma_unmap_sg(dev->dev, dev->sg_src, 1, DMA_TO_DEVICE);
}
static int s5p_set_outdata(struct s5p_aes_dev *dev, struct scatterlist *sg)
{
int err;
if (!IS_ALIGNED(sg_dma_len(sg), AES_BLOCK_SIZE)) {
err = -EINVAL;
goto exit;
}
if (!sg_dma_len(sg)) {
err = -EINVAL;
goto exit;
}
err = dma_map_sg(dev->dev, sg, 1, DMA_FROM_DEVICE);
if (!err) {
err = -ENOMEM;
goto exit;
}
dev->sg_dst = sg;
err = 0;
exit:
return err;
}
static int s5p_set_indata(struct s5p_aes_dev *dev, struct scatterlist *sg)
{
int err;
if (!IS_ALIGNED(sg_dma_len(sg), AES_BLOCK_SIZE)) {
err = -EINVAL;
goto exit;
}
if (!sg_dma_len(sg)) {
err = -EINVAL;
goto exit;
}
err = dma_map_sg(dev->dev, sg, 1, DMA_TO_DEVICE);
if (!err) {
err = -ENOMEM;
goto exit;
}
dev->sg_src = sg;
err = 0;
exit:
return err;
}
static void s5p_aes_tx(struct s5p_aes_dev *dev)
{
int err = 0;
s5p_unset_outdata(dev);
if (!sg_is_last(dev->sg_dst)) {
err = s5p_set_outdata(dev, sg_next(dev->sg_dst));
if (err) {
s5p_aes_complete(dev, err);
return;
}
s5p_set_dma_outdata(dev, dev->sg_dst);
} else
s5p_aes_complete(dev, err);
}
static void s5p_aes_rx(struct s5p_aes_dev *dev)
{
int err;
s5p_unset_indata(dev);
if (!sg_is_last(dev->sg_src)) {
err = s5p_set_indata(dev, sg_next(dev->sg_src));
if (err) {
s5p_aes_complete(dev, err);
return;
}
s5p_set_dma_indata(dev, dev->sg_src);
}
}
static irqreturn_t s5p_aes_interrupt(int irq, void *dev_id)
{
struct platform_device *pdev = dev_id;
struct s5p_aes_dev *dev = platform_get_drvdata(pdev);
uint32_t status;
unsigned long flags;
spin_lock_irqsave(&dev->lock, flags);
if (irq == dev->irq_fc) {
status = SSS_READ(dev, FCINTSTAT);
if (status & SSS_FCINTSTAT_BRDMAINT)
s5p_aes_rx(dev);
if (status & SSS_FCINTSTAT_BTDMAINT)
s5p_aes_tx(dev);
SSS_WRITE(dev, FCINTPEND, status);
}
spin_unlock_irqrestore(&dev->lock, flags);
return IRQ_HANDLED;
}
static void s5p_set_aes(struct s5p_aes_dev *dev,
uint8_t *key, uint8_t *iv, unsigned int keylen)
{
void __iomem *keystart;
memcpy(dev->ioaddr + SSS_REG_AES_IV_DATA(0), iv, 0x10);
if (keylen == AES_KEYSIZE_256)
keystart = dev->ioaddr + SSS_REG_AES_KEY_DATA(0);
else if (keylen == AES_KEYSIZE_192)
keystart = dev->ioaddr + SSS_REG_AES_KEY_DATA(2);
else
keystart = dev->ioaddr + SSS_REG_AES_KEY_DATA(4);
memcpy(keystart, key, keylen);
}
static void s5p_aes_crypt_start(struct s5p_aes_dev *dev, unsigned long mode)
{
struct ablkcipher_request *req = dev->req;
uint32_t aes_control;
int err;
unsigned long flags;
aes_control = SSS_AES_KEY_CHANGE_MODE;
if (mode & FLAGS_AES_DECRYPT)
aes_control |= SSS_AES_MODE_DECRYPT;
if ((mode & FLAGS_AES_MODE_MASK) == FLAGS_AES_CBC)
aes_control |= SSS_AES_CHAIN_MODE_CBC;
else if ((mode & FLAGS_AES_MODE_MASK) == FLAGS_AES_CTR)
aes_control |= SSS_AES_CHAIN_MODE_CTR;
if (dev->ctx->keylen == AES_KEYSIZE_192)
aes_control |= SSS_AES_KEY_SIZE_192;
else if (dev->ctx->keylen == AES_KEYSIZE_256)
aes_control |= SSS_AES_KEY_SIZE_256;
aes_control |= SSS_AES_FIFO_MODE;
/* as a variant it is possible to use byte swapping on DMA side */
aes_control |= SSS_AES_BYTESWAP_DI
| SSS_AES_BYTESWAP_DO
| SSS_AES_BYTESWAP_IV
| SSS_AES_BYTESWAP_KEY
| SSS_AES_BYTESWAP_CNT;
spin_lock_irqsave(&dev->lock, flags);
SSS_WRITE(dev, FCINTENCLR,
SSS_FCINTENCLR_BTDMAINTENCLR | SSS_FCINTENCLR_BRDMAINTENCLR);
SSS_WRITE(dev, FCFIFOCTRL, 0x00);
err = s5p_set_indata(dev, req->src);
if (err)
goto indata_error;
err = s5p_set_outdata(dev, req->dst);
if (err)
goto outdata_error;
SSS_WRITE(dev, AES_CONTROL, aes_control);
s5p_set_aes(dev, dev->ctx->aes_key, req->info, dev->ctx->keylen);
s5p_set_dma_indata(dev, req->src);
s5p_set_dma_outdata(dev, req->dst);
SSS_WRITE(dev, FCINTENSET,
SSS_FCINTENSET_BTDMAINTENSET | SSS_FCINTENSET_BRDMAINTENSET);
spin_unlock_irqrestore(&dev->lock, flags);
return;
outdata_error:
s5p_unset_indata(dev);
indata_error:
s5p_aes_complete(dev, err);
spin_unlock_irqrestore(&dev->lock, flags);
}
static void s5p_tasklet_cb(unsigned long data)
{
struct s5p_aes_dev *dev = (struct s5p_aes_dev *)data;
struct crypto_async_request *async_req, *backlog;
struct s5p_aes_reqctx *reqctx;
unsigned long flags;
spin_lock_irqsave(&dev->lock, flags);
backlog = crypto_get_backlog(&dev->queue);
async_req = crypto_dequeue_request(&dev->queue);
spin_unlock_irqrestore(&dev->lock, flags);
if (!async_req)
return;
if (backlog)
backlog->complete(backlog, -EINPROGRESS);
dev->req = ablkcipher_request_cast(async_req);
dev->ctx = crypto_tfm_ctx(dev->req->base.tfm);
reqctx = ablkcipher_request_ctx(dev->req);
s5p_aes_crypt_start(dev, reqctx->mode);
}
static int s5p_aes_handle_req(struct s5p_aes_dev *dev,
struct ablkcipher_request *req)
{
unsigned long flags;
int err;
spin_lock_irqsave(&dev->lock, flags);
if (dev->busy) {
err = -EAGAIN;
spin_unlock_irqrestore(&dev->lock, flags);
goto exit;
}
dev->busy = true;
err = ablkcipher_enqueue_request(&dev->queue, req);
spin_unlock_irqrestore(&dev->lock, flags);
tasklet_schedule(&dev->tasklet);
exit:
return err;
}
static int s5p_aes_crypt(struct ablkcipher_request *req, unsigned long mode)
{
struct crypto_ablkcipher *tfm = crypto_ablkcipher_reqtfm(req);
struct s5p_aes_ctx *ctx = crypto_ablkcipher_ctx(tfm);
struct s5p_aes_reqctx *reqctx = ablkcipher_request_ctx(req);
struct s5p_aes_dev *dev = ctx->dev;
if (!IS_ALIGNED(req->nbytes, AES_BLOCK_SIZE)) {
pr_err("request size is not exact amount of AES blocks\n");
return -EINVAL;
}
reqctx->mode = mode;
return s5p_aes_handle_req(dev, req);
}
static int s5p_aes_setkey(struct crypto_ablkcipher *cipher,
const uint8_t *key, unsigned int keylen)
{
struct crypto_tfm *tfm = crypto_ablkcipher_tfm(cipher);
struct s5p_aes_ctx *ctx = crypto_tfm_ctx(tfm);
if (keylen != AES_KEYSIZE_128 &&
keylen != AES_KEYSIZE_192 &&
keylen != AES_KEYSIZE_256)
return -EINVAL;
memcpy(ctx->aes_key, key, keylen);
ctx->keylen = keylen;
return 0;
}
static int s5p_aes_ecb_encrypt(struct ablkcipher_request *req)
{
return s5p_aes_crypt(req, 0);
}
static int s5p_aes_ecb_decrypt(struct ablkcipher_request *req)
{
return s5p_aes_crypt(req, FLAGS_AES_DECRYPT);
}
static int s5p_aes_cbc_encrypt(struct ablkcipher_request *req)
{
return s5p_aes_crypt(req, FLAGS_AES_CBC);
}
static int s5p_aes_cbc_decrypt(struct ablkcipher_request *req)
{
return s5p_aes_crypt(req, FLAGS_AES_DECRYPT | FLAGS_AES_CBC);
}
static int s5p_aes_cra_init(struct crypto_tfm *tfm)
{
struct s5p_aes_ctx *ctx = crypto_tfm_ctx(tfm);
ctx->dev = s5p_dev;
tfm->crt_ablkcipher.reqsize = sizeof(struct s5p_aes_reqctx);
return 0;
}
static struct crypto_alg algs[] = {
{
.cra_name = "ecb(aes)",
.cra_driver_name = "ecb-aes-s5p",
.cra_priority = 100,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER |
CRYPTO_ALG_ASYNC |
CRYPTO_ALG_KERN_DRIVER_ONLY,
.cra_blocksize = AES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct s5p_aes_ctx),
.cra_alignmask = 0x0f,
.cra_type = &crypto_ablkcipher_type,
.cra_module = THIS_MODULE,
.cra_init = s5p_aes_cra_init,
.cra_u.ablkcipher = {
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.setkey = s5p_aes_setkey,
.encrypt = s5p_aes_ecb_encrypt,
.decrypt = s5p_aes_ecb_decrypt,
}
},
{
.cra_name = "cbc(aes)",
.cra_driver_name = "cbc-aes-s5p",
.cra_priority = 100,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER |
CRYPTO_ALG_ASYNC |
CRYPTO_ALG_KERN_DRIVER_ONLY,
.cra_blocksize = AES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct s5p_aes_ctx),
.cra_alignmask = 0x0f,
.cra_type = &crypto_ablkcipher_type,
.cra_module = THIS_MODULE,
.cra_init = s5p_aes_cra_init,
.cra_u.ablkcipher = {
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.ivsize = AES_BLOCK_SIZE,
.setkey = s5p_aes_setkey,
.encrypt = s5p_aes_cbc_encrypt,
.decrypt = s5p_aes_cbc_decrypt,
}
},
};
static int s5p_aes_probe(struct platform_device *pdev)
{
int i, j, err = -ENODEV;
struct s5p_aes_dev *pdata;
struct device *dev = &pdev->dev;
struct resource *res;
if (s5p_dev)
return -EEXIST;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res)
return -ENODEV;
pdata = devm_kzalloc(dev, sizeof(*pdata), GFP_KERNEL);
if (!pdata)
return -ENOMEM;
if (!devm_request_mem_region(dev, res->start,
resource_size(res), pdev->name))
return -EBUSY;
pdata->clk = clk_get(dev, "secss");
if (IS_ERR(pdata->clk)) {
dev_err(dev, "failed to find secss clock source\n");
return -ENOENT;
}
clk_enable(pdata->clk);
spin_lock_init(&pdata->lock);
pdata->ioaddr = devm_ioremap(dev, res->start,
resource_size(res));
pdata->irq_hash = platform_get_irq_byname(pdev, "hash");
if (pdata->irq_hash < 0) {
err = pdata->irq_hash;
dev_warn(dev, "hash interrupt is not available.\n");
goto err_irq;
}
err = devm_request_irq(dev, pdata->irq_hash, s5p_aes_interrupt,
IRQF_SHARED, pdev->name, pdev);
if (err < 0) {
dev_warn(dev, "hash interrupt is not available.\n");
goto err_irq;
}
pdata->irq_fc = platform_get_irq_byname(pdev, "feed control");
if (pdata->irq_fc < 0) {
err = pdata->irq_fc;
dev_warn(dev, "feed control interrupt is not available.\n");
goto err_irq;
}
err = devm_request_irq(dev, pdata->irq_fc, s5p_aes_interrupt,
IRQF_SHARED, pdev->name, pdev);
if (err < 0) {
dev_warn(dev, "feed control interrupt is not available.\n");
goto err_irq;
}
pdata->dev = dev;
platform_set_drvdata(pdev, pdata);
s5p_dev = pdata;
tasklet_init(&pdata->tasklet, s5p_tasklet_cb, (unsigned long)pdata);
crypto_init_queue(&pdata->queue, CRYPTO_QUEUE_LEN);
for (i = 0; i < ARRAY_SIZE(algs); i++) {
INIT_LIST_HEAD(&algs[i].cra_list);
err = crypto_register_alg(&algs[i]);
if (err)
goto err_algs;
}
pr_info("s5p-sss driver registered\n");
return 0;
err_algs:
dev_err(dev, "can't register '%s': %d\n", algs[i].cra_name, err);
for (j = 0; j < i; j++)
crypto_unregister_alg(&algs[j]);
tasklet_kill(&pdata->tasklet);
err_irq:
clk_disable(pdata->clk);
clk_put(pdata->clk);
s5p_dev = NULL;
platform_set_drvdata(pdev, NULL);
return err;
}
static int s5p_aes_remove(struct platform_device *pdev)
{
struct s5p_aes_dev *pdata = platform_get_drvdata(pdev);
int i;
if (!pdata)
return -ENODEV;
for (i = 0; i < ARRAY_SIZE(algs); i++)
crypto_unregister_alg(&algs[i]);
tasklet_kill(&pdata->tasklet);
clk_disable(pdata->clk);
clk_put(pdata->clk);
s5p_dev = NULL;
platform_set_drvdata(pdev, NULL);
return 0;
}
static struct platform_driver s5p_aes_crypto = {
.probe = s5p_aes_probe,
.remove = s5p_aes_remove,
.driver = {
.owner = THIS_MODULE,
.name = "s5p-secss",
},
};
module_platform_driver(s5p_aes_crypto);
MODULE_DESCRIPTION("S5PV210 AES hw acceleration support.");
MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("Vladimir Zapolskiy <vzapolskiy@gmail.com>");
| gpl-2.0 |
kykc/m7u-3.4.10-g4dad4ce | drivers/tty/nozomi.c | 4943 | 49454 | /*
* nozomi.c -- HSDPA driver Broadband Wireless Data Card - Globe Trotter
*
* Written by: Ulf Jakobsson,
* Jan Åkerfeldt,
* Stefan Thomasson,
*
* Maintained by: Paul Hardwick (p.hardwick@option.com)
*
* Patches:
* Locking code changes for Vodafone by Sphere Systems Ltd,
* Andrew Bird (ajb@spheresystems.co.uk )
* & Phil Sanderson
*
* Source has been ported from an implementation made by Filip Aben @ Option
*
* --------------------------------------------------------------------------
*
* Copyright (c) 2005,2006 Option Wireless Sweden AB
* Copyright (c) 2006 Sphere Systems Ltd
* Copyright (c) 2006 Option Wireless n/v
* All rights Reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* --------------------------------------------------------------------------
*/
/* Enable this to have a lot of debug printouts */
#define DEBUG
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/ioport.h>
#include <linux/tty.h>
#include <linux/tty_driver.h>
#include <linux/tty_flip.h>
#include <linux/sched.h>
#include <linux/serial.h>
#include <linux/interrupt.h>
#include <linux/kmod.h>
#include <linux/init.h>
#include <linux/kfifo.h>
#include <linux/uaccess.h>
#include <linux/slab.h>
#include <asm/byteorder.h>
#include <linux/delay.h>
#define VERSION_STRING DRIVER_DESC " 2.1d"
/* Macros definitions */
/* Default debug printout level */
#define NOZOMI_DEBUG_LEVEL 0x00
#define P_BUF_SIZE 128
#define NFO(_err_flag_, args...) \
do { \
char tmp[P_BUF_SIZE]; \
snprintf(tmp, sizeof(tmp), ##args); \
printk(_err_flag_ "[%d] %s(): %s\n", __LINE__, \
__func__, tmp); \
} while (0)
#define DBG1(args...) D_(0x01, ##args)
#define DBG2(args...) D_(0x02, ##args)
#define DBG3(args...) D_(0x04, ##args)
#define DBG4(args...) D_(0x08, ##args)
#define DBG5(args...) D_(0x10, ##args)
#define DBG6(args...) D_(0x20, ##args)
#define DBG7(args...) D_(0x40, ##args)
#define DBG8(args...) D_(0x80, ##args)
#ifdef DEBUG
/* Do we need this settable at runtime? */
static int debug = NOZOMI_DEBUG_LEVEL;
#define D(lvl, args...) do \
{if (lvl & debug) NFO(KERN_DEBUG, ##args); } \
while (0)
#define D_(lvl, args...) D(lvl, ##args)
/* These printouts are always printed */
#else
static int debug;
#define D_(lvl, args...)
#endif
/* TODO: rewrite to optimize macros... */
#define TMP_BUF_MAX 256
#define DUMP(buf__,len__) \
do { \
char tbuf[TMP_BUF_MAX] = {0};\
if (len__ > 1) {\
snprintf(tbuf, len__ > TMP_BUF_MAX ? TMP_BUF_MAX : len__, "%s", buf__);\
if (tbuf[len__-2] == '\r') {\
tbuf[len__-2] = 'r';\
} \
DBG1("SENDING: '%s' (%d+n)", tbuf, len__);\
} else {\
DBG1("SENDING: '%s' (%d)", tbuf, len__);\
} \
} while (0)
/* Defines */
#define NOZOMI_NAME "nozomi"
#define NOZOMI_NAME_TTY "nozomi_tty"
#define DRIVER_DESC "Nozomi driver"
#define NTTY_TTY_MAXMINORS 256
#define NTTY_FIFO_BUFFER_SIZE 8192
/* Must be power of 2 */
#define FIFO_BUFFER_SIZE_UL 8192
/* Size of tmp send buffer to card */
#define SEND_BUF_MAX 1024
#define RECEIVE_BUF_MAX 4
#define R_IIR 0x0000 /* Interrupt Identity Register */
#define R_FCR 0x0000 /* Flow Control Register */
#define R_IER 0x0004 /* Interrupt Enable Register */
#define CONFIG_MAGIC 0xEFEFFEFE
#define TOGGLE_VALID 0x0000
/* Definition of interrupt tokens */
#define MDM_DL1 0x0001
#define MDM_UL1 0x0002
#define MDM_DL2 0x0004
#define MDM_UL2 0x0008
#define DIAG_DL1 0x0010
#define DIAG_DL2 0x0020
#define DIAG_UL 0x0040
#define APP1_DL 0x0080
#define APP1_UL 0x0100
#define APP2_DL 0x0200
#define APP2_UL 0x0400
#define CTRL_DL 0x0800
#define CTRL_UL 0x1000
#define RESET 0x8000
#define MDM_DL (MDM_DL1 | MDM_DL2)
#define MDM_UL (MDM_UL1 | MDM_UL2)
#define DIAG_DL (DIAG_DL1 | DIAG_DL2)
/* modem signal definition */
#define CTRL_DSR 0x0001
#define CTRL_DCD 0x0002
#define CTRL_RI 0x0004
#define CTRL_CTS 0x0008
#define CTRL_DTR 0x0001
#define CTRL_RTS 0x0002
#define MAX_PORT 4
#define NOZOMI_MAX_PORTS 5
#define NOZOMI_MAX_CARDS (NTTY_TTY_MAXMINORS / MAX_PORT)
/* Type definitions */
/*
* There are two types of nozomi cards,
* one with 2048 memory and with 8192 memory
*/
enum card_type {
F32_2 = 2048, /* 512 bytes downlink + uplink * 2 -> 2048 */
F32_8 = 8192, /* 3072 bytes downl. + 1024 bytes uplink * 2 -> 8192 */
};
/* Initialization states a card can be in */
enum card_state {
NOZOMI_STATE_UKNOWN = 0,
NOZOMI_STATE_ENABLED = 1, /* pci device enabled */
NOZOMI_STATE_ALLOCATED = 2, /* config setup done */
NOZOMI_STATE_READY = 3, /* flowcontrols received */
};
/* Two different toggle channels exist */
enum channel_type {
CH_A = 0,
CH_B = 1,
};
/* Port definition for the card regarding flow control */
enum ctrl_port_type {
CTRL_CMD = 0,
CTRL_MDM = 1,
CTRL_DIAG = 2,
CTRL_APP1 = 3,
CTRL_APP2 = 4,
CTRL_ERROR = -1,
};
/* Ports that the nozomi has */
enum port_type {
PORT_MDM = 0,
PORT_DIAG = 1,
PORT_APP1 = 2,
PORT_APP2 = 3,
PORT_CTRL = 4,
PORT_ERROR = -1,
};
#ifdef __BIG_ENDIAN
/* Big endian */
struct toggles {
unsigned int enabled:5; /*
* Toggle fields are valid if enabled is 0,
* else A-channels must always be used.
*/
unsigned int diag_dl:1;
unsigned int mdm_dl:1;
unsigned int mdm_ul:1;
} __attribute__ ((packed));
/* Configuration table to read at startup of card */
/* Is for now only needed during initialization phase */
struct config_table {
u32 signature;
u16 product_information;
u16 version;
u8 pad3[3];
struct toggles toggle;
u8 pad1[4];
u16 dl_mdm_len1; /*
* If this is 64, it can hold
* 60 bytes + 4 that is length field
*/
u16 dl_start;
u16 dl_diag_len1;
u16 dl_mdm_len2; /*
* If this is 64, it can hold
* 60 bytes + 4 that is length field
*/
u16 dl_app1_len;
u16 dl_diag_len2;
u16 dl_ctrl_len;
u16 dl_app2_len;
u8 pad2[16];
u16 ul_mdm_len1;
u16 ul_start;
u16 ul_diag_len;
u16 ul_mdm_len2;
u16 ul_app1_len;
u16 ul_app2_len;
u16 ul_ctrl_len;
} __attribute__ ((packed));
/* This stores all control downlink flags */
struct ctrl_dl {
u8 port;
unsigned int reserved:4;
unsigned int CTS:1;
unsigned int RI:1;
unsigned int DCD:1;
unsigned int DSR:1;
} __attribute__ ((packed));
/* This stores all control uplink flags */
struct ctrl_ul {
u8 port;
unsigned int reserved:6;
unsigned int RTS:1;
unsigned int DTR:1;
} __attribute__ ((packed));
#else
/* Little endian */
/* This represents the toggle information */
struct toggles {
unsigned int mdm_ul:1;
unsigned int mdm_dl:1;
unsigned int diag_dl:1;
unsigned int enabled:5; /*
* Toggle fields are valid if enabled is 0,
* else A-channels must always be used.
*/
} __attribute__ ((packed));
/* Configuration table to read at startup of card */
struct config_table {
u32 signature;
u16 version;
u16 product_information;
struct toggles toggle;
u8 pad1[7];
u16 dl_start;
u16 dl_mdm_len1; /*
* If this is 64, it can hold
* 60 bytes + 4 that is length field
*/
u16 dl_mdm_len2;
u16 dl_diag_len1;
u16 dl_diag_len2;
u16 dl_app1_len;
u16 dl_app2_len;
u16 dl_ctrl_len;
u8 pad2[16];
u16 ul_start;
u16 ul_mdm_len2;
u16 ul_mdm_len1;
u16 ul_diag_len;
u16 ul_app1_len;
u16 ul_app2_len;
u16 ul_ctrl_len;
} __attribute__ ((packed));
/* This stores all control downlink flags */
struct ctrl_dl {
unsigned int DSR:1;
unsigned int DCD:1;
unsigned int RI:1;
unsigned int CTS:1;
unsigned int reserverd:4;
u8 port;
} __attribute__ ((packed));
/* This stores all control uplink flags */
struct ctrl_ul {
unsigned int DTR:1;
unsigned int RTS:1;
unsigned int reserved:6;
u8 port;
} __attribute__ ((packed));
#endif
/* This holds all information that is needed regarding a port */
struct port {
struct tty_port port;
u8 update_flow_control;
struct ctrl_ul ctrl_ul;
struct ctrl_dl ctrl_dl;
struct kfifo fifo_ul;
void __iomem *dl_addr[2];
u32 dl_size[2];
u8 toggle_dl;
void __iomem *ul_addr[2];
u32 ul_size[2];
u8 toggle_ul;
u16 token_dl;
wait_queue_head_t tty_wait;
struct async_icount tty_icount;
struct nozomi *dc;
};
/* Private data one for each card in the system */
struct nozomi {
void __iomem *base_addr;
unsigned long flip;
/* Pointers to registers */
void __iomem *reg_iir;
void __iomem *reg_fcr;
void __iomem *reg_ier;
u16 last_ier;
enum card_type card_type;
struct config_table config_table; /* Configuration table */
struct pci_dev *pdev;
struct port port[NOZOMI_MAX_PORTS];
u8 *send_buf;
spinlock_t spin_mutex; /* secures access to registers and tty */
unsigned int index_start;
enum card_state state;
u32 open_ttys;
};
/* This is a data packet that is read or written to/from card */
struct buffer {
u32 size; /* size is the length of the data buffer */
u8 *data;
} __attribute__ ((packed));
/* Global variables */
static const struct pci_device_id nozomi_pci_tbl[] __devinitconst = {
{PCI_DEVICE(0x1931, 0x000c)}, /* Nozomi HSDPA */
{},
};
MODULE_DEVICE_TABLE(pci, nozomi_pci_tbl);
static struct nozomi *ndevs[NOZOMI_MAX_CARDS];
static struct tty_driver *ntty_driver;
static const struct tty_port_operations noz_tty_port_ops;
/*
* find card by tty_index
*/
static inline struct nozomi *get_dc_by_tty(const struct tty_struct *tty)
{
return tty ? ndevs[tty->index / MAX_PORT] : NULL;
}
static inline struct port *get_port_by_tty(const struct tty_struct *tty)
{
struct nozomi *ndev = get_dc_by_tty(tty);
return ndev ? &ndev->port[tty->index % MAX_PORT] : NULL;
}
/*
* TODO:
* -Optimize
* -Rewrite cleaner
*/
static void read_mem32(u32 *buf, const void __iomem *mem_addr_start,
u32 size_bytes)
{
u32 i = 0;
const u32 __iomem *ptr = mem_addr_start;
u16 *buf16;
if (unlikely(!ptr || !buf))
goto out;
/* shortcut for extremely often used cases */
switch (size_bytes) {
case 2: /* 2 bytes */
buf16 = (u16 *) buf;
*buf16 = __le16_to_cpu(readw(ptr));
goto out;
break;
case 4: /* 4 bytes */
*(buf) = __le32_to_cpu(readl(ptr));
goto out;
break;
}
while (i < size_bytes) {
if (size_bytes - i == 2) {
/* Handle 2 bytes in the end */
buf16 = (u16 *) buf;
*(buf16) = __le16_to_cpu(readw(ptr));
i += 2;
} else {
/* Read 4 bytes */
*(buf) = __le32_to_cpu(readl(ptr));
i += 4;
}
buf++;
ptr++;
}
out:
return;
}
/*
* TODO:
* -Optimize
* -Rewrite cleaner
*/
static u32 write_mem32(void __iomem *mem_addr_start, const u32 *buf,
u32 size_bytes)
{
u32 i = 0;
u32 __iomem *ptr = mem_addr_start;
const u16 *buf16;
if (unlikely(!ptr || !buf))
return 0;
/* shortcut for extremely often used cases */
switch (size_bytes) {
case 2: /* 2 bytes */
buf16 = (const u16 *)buf;
writew(__cpu_to_le16(*buf16), ptr);
return 2;
break;
case 1: /*
* also needs to write 4 bytes in this case
* so falling through..
*/
case 4: /* 4 bytes */
writel(__cpu_to_le32(*buf), ptr);
return 4;
break;
}
while (i < size_bytes) {
if (size_bytes - i == 2) {
/* 2 bytes */
buf16 = (const u16 *)buf;
writew(__cpu_to_le16(*buf16), ptr);
i += 2;
} else {
/* 4 bytes */
writel(__cpu_to_le32(*buf), ptr);
i += 4;
}
buf++;
ptr++;
}
return i;
}
/* Setup pointers to different channels and also setup buffer sizes. */
static void setup_memory(struct nozomi *dc)
{
void __iomem *offset = dc->base_addr + dc->config_table.dl_start;
/* The length reported is including the length field of 4 bytes,
* hence subtract with 4.
*/
const u16 buff_offset = 4;
/* Modem port dl configuration */
dc->port[PORT_MDM].dl_addr[CH_A] = offset;
dc->port[PORT_MDM].dl_addr[CH_B] =
(offset += dc->config_table.dl_mdm_len1);
dc->port[PORT_MDM].dl_size[CH_A] =
dc->config_table.dl_mdm_len1 - buff_offset;
dc->port[PORT_MDM].dl_size[CH_B] =
dc->config_table.dl_mdm_len2 - buff_offset;
/* Diag port dl configuration */
dc->port[PORT_DIAG].dl_addr[CH_A] =
(offset += dc->config_table.dl_mdm_len2);
dc->port[PORT_DIAG].dl_size[CH_A] =
dc->config_table.dl_diag_len1 - buff_offset;
dc->port[PORT_DIAG].dl_addr[CH_B] =
(offset += dc->config_table.dl_diag_len1);
dc->port[PORT_DIAG].dl_size[CH_B] =
dc->config_table.dl_diag_len2 - buff_offset;
/* App1 port dl configuration */
dc->port[PORT_APP1].dl_addr[CH_A] =
(offset += dc->config_table.dl_diag_len2);
dc->port[PORT_APP1].dl_size[CH_A] =
dc->config_table.dl_app1_len - buff_offset;
/* App2 port dl configuration */
dc->port[PORT_APP2].dl_addr[CH_A] =
(offset += dc->config_table.dl_app1_len);
dc->port[PORT_APP2].dl_size[CH_A] =
dc->config_table.dl_app2_len - buff_offset;
/* Ctrl dl configuration */
dc->port[PORT_CTRL].dl_addr[CH_A] =
(offset += dc->config_table.dl_app2_len);
dc->port[PORT_CTRL].dl_size[CH_A] =
dc->config_table.dl_ctrl_len - buff_offset;
offset = dc->base_addr + dc->config_table.ul_start;
/* Modem Port ul configuration */
dc->port[PORT_MDM].ul_addr[CH_A] = offset;
dc->port[PORT_MDM].ul_size[CH_A] =
dc->config_table.ul_mdm_len1 - buff_offset;
dc->port[PORT_MDM].ul_addr[CH_B] =
(offset += dc->config_table.ul_mdm_len1);
dc->port[PORT_MDM].ul_size[CH_B] =
dc->config_table.ul_mdm_len2 - buff_offset;
/* Diag port ul configuration */
dc->port[PORT_DIAG].ul_addr[CH_A] =
(offset += dc->config_table.ul_mdm_len2);
dc->port[PORT_DIAG].ul_size[CH_A] =
dc->config_table.ul_diag_len - buff_offset;
/* App1 port ul configuration */
dc->port[PORT_APP1].ul_addr[CH_A] =
(offset += dc->config_table.ul_diag_len);
dc->port[PORT_APP1].ul_size[CH_A] =
dc->config_table.ul_app1_len - buff_offset;
/* App2 port ul configuration */
dc->port[PORT_APP2].ul_addr[CH_A] =
(offset += dc->config_table.ul_app1_len);
dc->port[PORT_APP2].ul_size[CH_A] =
dc->config_table.ul_app2_len - buff_offset;
/* Ctrl ul configuration */
dc->port[PORT_CTRL].ul_addr[CH_A] =
(offset += dc->config_table.ul_app2_len);
dc->port[PORT_CTRL].ul_size[CH_A] =
dc->config_table.ul_ctrl_len - buff_offset;
}
/* Dump config table under initalization phase */
#ifdef DEBUG
static void dump_table(const struct nozomi *dc)
{
DBG3("signature: 0x%08X", dc->config_table.signature);
DBG3("version: 0x%04X", dc->config_table.version);
DBG3("product_information: 0x%04X", \
dc->config_table.product_information);
DBG3("toggle enabled: %d", dc->config_table.toggle.enabled);
DBG3("toggle up_mdm: %d", dc->config_table.toggle.mdm_ul);
DBG3("toggle dl_mdm: %d", dc->config_table.toggle.mdm_dl);
DBG3("toggle dl_dbg: %d", dc->config_table.toggle.diag_dl);
DBG3("dl_start: 0x%04X", dc->config_table.dl_start);
DBG3("dl_mdm_len0: 0x%04X, %d", dc->config_table.dl_mdm_len1,
dc->config_table.dl_mdm_len1);
DBG3("dl_mdm_len1: 0x%04X, %d", dc->config_table.dl_mdm_len2,
dc->config_table.dl_mdm_len2);
DBG3("dl_diag_len0: 0x%04X, %d", dc->config_table.dl_diag_len1,
dc->config_table.dl_diag_len1);
DBG3("dl_diag_len1: 0x%04X, %d", dc->config_table.dl_diag_len2,
dc->config_table.dl_diag_len2);
DBG3("dl_app1_len: 0x%04X, %d", dc->config_table.dl_app1_len,
dc->config_table.dl_app1_len);
DBG3("dl_app2_len: 0x%04X, %d", dc->config_table.dl_app2_len,
dc->config_table.dl_app2_len);
DBG3("dl_ctrl_len: 0x%04X, %d", dc->config_table.dl_ctrl_len,
dc->config_table.dl_ctrl_len);
DBG3("ul_start: 0x%04X, %d", dc->config_table.ul_start,
dc->config_table.ul_start);
DBG3("ul_mdm_len[0]: 0x%04X, %d", dc->config_table.ul_mdm_len1,
dc->config_table.ul_mdm_len1);
DBG3("ul_mdm_len[1]: 0x%04X, %d", dc->config_table.ul_mdm_len2,
dc->config_table.ul_mdm_len2);
DBG3("ul_diag_len: 0x%04X, %d", dc->config_table.ul_diag_len,
dc->config_table.ul_diag_len);
DBG3("ul_app1_len: 0x%04X, %d", dc->config_table.ul_app1_len,
dc->config_table.ul_app1_len);
DBG3("ul_app2_len: 0x%04X, %d", dc->config_table.ul_app2_len,
dc->config_table.ul_app2_len);
DBG3("ul_ctrl_len: 0x%04X, %d", dc->config_table.ul_ctrl_len,
dc->config_table.ul_ctrl_len);
}
#else
static inline void dump_table(const struct nozomi *dc) { }
#endif
/*
* Read configuration table from card under intalization phase
* Returns 1 if ok, else 0
*/
static int nozomi_read_config_table(struct nozomi *dc)
{
read_mem32((u32 *) &dc->config_table, dc->base_addr + 0,
sizeof(struct config_table));
if (dc->config_table.signature != CONFIG_MAGIC) {
dev_err(&dc->pdev->dev, "ConfigTable Bad! 0x%08X != 0x%08X\n",
dc->config_table.signature, CONFIG_MAGIC);
return 0;
}
if ((dc->config_table.version == 0)
|| (dc->config_table.toggle.enabled == TOGGLE_VALID)) {
int i;
DBG1("Second phase, configuring card");
setup_memory(dc);
dc->port[PORT_MDM].toggle_ul = dc->config_table.toggle.mdm_ul;
dc->port[PORT_MDM].toggle_dl = dc->config_table.toggle.mdm_dl;
dc->port[PORT_DIAG].toggle_dl = dc->config_table.toggle.diag_dl;
DBG1("toggle ports: MDM UL:%d MDM DL:%d, DIAG DL:%d",
dc->port[PORT_MDM].toggle_ul,
dc->port[PORT_MDM].toggle_dl, dc->port[PORT_DIAG].toggle_dl);
dump_table(dc);
for (i = PORT_MDM; i < MAX_PORT; i++) {
memset(&dc->port[i].ctrl_dl, 0, sizeof(struct ctrl_dl));
memset(&dc->port[i].ctrl_ul, 0, sizeof(struct ctrl_ul));
}
/* Enable control channel */
dc->last_ier = dc->last_ier | CTRL_DL;
writew(dc->last_ier, dc->reg_ier);
dc->state = NOZOMI_STATE_ALLOCATED;
dev_info(&dc->pdev->dev, "Initialization OK!\n");
return 1;
}
if ((dc->config_table.version > 0)
&& (dc->config_table.toggle.enabled != TOGGLE_VALID)) {
u32 offset = 0;
DBG1("First phase: pushing upload buffers, clearing download");
dev_info(&dc->pdev->dev, "Version of card: %d\n",
dc->config_table.version);
/* Here we should disable all I/O over F32. */
setup_memory(dc);
/*
* We should send ALL channel pair tokens back along
* with reset token
*/
/* push upload modem buffers */
write_mem32(dc->port[PORT_MDM].ul_addr[CH_A],
(u32 *) &offset, 4);
write_mem32(dc->port[PORT_MDM].ul_addr[CH_B],
(u32 *) &offset, 4);
writew(MDM_UL | DIAG_DL | MDM_DL, dc->reg_fcr);
DBG1("First phase done");
}
return 1;
}
/* Enable uplink interrupts */
static void enable_transmit_ul(enum port_type port, struct nozomi *dc)
{
static const u16 mask[] = {MDM_UL, DIAG_UL, APP1_UL, APP2_UL, CTRL_UL};
if (port < NOZOMI_MAX_PORTS) {
dc->last_ier |= mask[port];
writew(dc->last_ier, dc->reg_ier);
} else {
dev_err(&dc->pdev->dev, "Called with wrong port?\n");
}
}
/* Disable uplink interrupts */
static void disable_transmit_ul(enum port_type port, struct nozomi *dc)
{
static const u16 mask[] =
{~MDM_UL, ~DIAG_UL, ~APP1_UL, ~APP2_UL, ~CTRL_UL};
if (port < NOZOMI_MAX_PORTS) {
dc->last_ier &= mask[port];
writew(dc->last_ier, dc->reg_ier);
} else {
dev_err(&dc->pdev->dev, "Called with wrong port?\n");
}
}
/* Enable downlink interrupts */
static void enable_transmit_dl(enum port_type port, struct nozomi *dc)
{
static const u16 mask[] = {MDM_DL, DIAG_DL, APP1_DL, APP2_DL, CTRL_DL};
if (port < NOZOMI_MAX_PORTS) {
dc->last_ier |= mask[port];
writew(dc->last_ier, dc->reg_ier);
} else {
dev_err(&dc->pdev->dev, "Called with wrong port?\n");
}
}
/* Disable downlink interrupts */
static void disable_transmit_dl(enum port_type port, struct nozomi *dc)
{
static const u16 mask[] =
{~MDM_DL, ~DIAG_DL, ~APP1_DL, ~APP2_DL, ~CTRL_DL};
if (port < NOZOMI_MAX_PORTS) {
dc->last_ier &= mask[port];
writew(dc->last_ier, dc->reg_ier);
} else {
dev_err(&dc->pdev->dev, "Called with wrong port?\n");
}
}
/*
* Return 1 - send buffer to card and ack.
* Return 0 - don't ack, don't send buffer to card.
*/
static int send_data(enum port_type index, struct nozomi *dc)
{
u32 size = 0;
struct port *port = &dc->port[index];
const u8 toggle = port->toggle_ul;
void __iomem *addr = port->ul_addr[toggle];
const u32 ul_size = port->ul_size[toggle];
struct tty_struct *tty = tty_port_tty_get(&port->port);
/* Get data from tty and place in buf for now */
size = kfifo_out(&port->fifo_ul, dc->send_buf,
ul_size < SEND_BUF_MAX ? ul_size : SEND_BUF_MAX);
if (size == 0) {
DBG4("No more data to send, disable link:");
tty_kref_put(tty);
return 0;
}
/* DUMP(buf, size); */
/* Write length + data */
write_mem32(addr, (u32 *) &size, 4);
write_mem32(addr + 4, (u32 *) dc->send_buf, size);
if (tty)
tty_wakeup(tty);
tty_kref_put(tty);
return 1;
}
/* If all data has been read, return 1, else 0 */
static int receive_data(enum port_type index, struct nozomi *dc)
{
u8 buf[RECEIVE_BUF_MAX] = { 0 };
int size;
u32 offset = 4;
struct port *port = &dc->port[index];
void __iomem *addr = port->dl_addr[port->toggle_dl];
struct tty_struct *tty = tty_port_tty_get(&port->port);
int i, ret;
if (unlikely(!tty)) {
DBG1("tty not open for port: %d?", index);
return 1;
}
read_mem32((u32 *) &size, addr, 4);
/* DBG1( "%d bytes port: %d", size, index); */
if (test_bit(TTY_THROTTLED, &tty->flags)) {
DBG1("No room in tty, don't read data, don't ack interrupt, "
"disable interrupt");
/* disable interrupt in downlink... */
disable_transmit_dl(index, dc);
ret = 0;
goto put;
}
if (unlikely(size == 0)) {
dev_err(&dc->pdev->dev, "size == 0?\n");
ret = 1;
goto put;
}
while (size > 0) {
read_mem32((u32 *) buf, addr + offset, RECEIVE_BUF_MAX);
if (size == 1) {
tty_insert_flip_char(tty, buf[0], TTY_NORMAL);
size = 0;
} else if (size < RECEIVE_BUF_MAX) {
size -= tty_insert_flip_string(tty, (char *) buf, size);
} else {
i = tty_insert_flip_string(tty, \
(char *) buf, RECEIVE_BUF_MAX);
size -= i;
offset += i;
}
}
set_bit(index, &dc->flip);
ret = 1;
put:
tty_kref_put(tty);
return ret;
}
/* Debug for interrupts */
#ifdef DEBUG
static char *interrupt2str(u16 interrupt)
{
static char buf[TMP_BUF_MAX];
char *p = buf;
interrupt & MDM_DL1 ? p += snprintf(p, TMP_BUF_MAX, "MDM_DL1 ") : NULL;
interrupt & MDM_DL2 ? p += snprintf(p, TMP_BUF_MAX - (p - buf),
"MDM_DL2 ") : NULL;
interrupt & MDM_UL1 ? p += snprintf(p, TMP_BUF_MAX - (p - buf),
"MDM_UL1 ") : NULL;
interrupt & MDM_UL2 ? p += snprintf(p, TMP_BUF_MAX - (p - buf),
"MDM_UL2 ") : NULL;
interrupt & DIAG_DL1 ? p += snprintf(p, TMP_BUF_MAX - (p - buf),
"DIAG_DL1 ") : NULL;
interrupt & DIAG_DL2 ? p += snprintf(p, TMP_BUF_MAX - (p - buf),
"DIAG_DL2 ") : NULL;
interrupt & DIAG_UL ? p += snprintf(p, TMP_BUF_MAX - (p - buf),
"DIAG_UL ") : NULL;
interrupt & APP1_DL ? p += snprintf(p, TMP_BUF_MAX - (p - buf),
"APP1_DL ") : NULL;
interrupt & APP2_DL ? p += snprintf(p, TMP_BUF_MAX - (p - buf),
"APP2_DL ") : NULL;
interrupt & APP1_UL ? p += snprintf(p, TMP_BUF_MAX - (p - buf),
"APP1_UL ") : NULL;
interrupt & APP2_UL ? p += snprintf(p, TMP_BUF_MAX - (p - buf),
"APP2_UL ") : NULL;
interrupt & CTRL_DL ? p += snprintf(p, TMP_BUF_MAX - (p - buf),
"CTRL_DL ") : NULL;
interrupt & CTRL_UL ? p += snprintf(p, TMP_BUF_MAX - (p - buf),
"CTRL_UL ") : NULL;
interrupt & RESET ? p += snprintf(p, TMP_BUF_MAX - (p - buf),
"RESET ") : NULL;
return buf;
}
#endif
/*
* Receive flow control
* Return 1 - If ok, else 0
*/
static int receive_flow_control(struct nozomi *dc)
{
enum port_type port = PORT_MDM;
struct ctrl_dl ctrl_dl;
struct ctrl_dl old_ctrl;
u16 enable_ier = 0;
read_mem32((u32 *) &ctrl_dl, dc->port[PORT_CTRL].dl_addr[CH_A], 2);
switch (ctrl_dl.port) {
case CTRL_CMD:
DBG1("The Base Band sends this value as a response to a "
"request for IMSI detach sent over the control "
"channel uplink (see section 7.6.1).");
break;
case CTRL_MDM:
port = PORT_MDM;
enable_ier = MDM_DL;
break;
case CTRL_DIAG:
port = PORT_DIAG;
enable_ier = DIAG_DL;
break;
case CTRL_APP1:
port = PORT_APP1;
enable_ier = APP1_DL;
break;
case CTRL_APP2:
port = PORT_APP2;
enable_ier = APP2_DL;
if (dc->state == NOZOMI_STATE_ALLOCATED) {
/*
* After card initialization the flow control
* received for APP2 is always the last
*/
dc->state = NOZOMI_STATE_READY;
dev_info(&dc->pdev->dev, "Device READY!\n");
}
break;
default:
dev_err(&dc->pdev->dev,
"ERROR: flow control received for non-existing port\n");
return 0;
};
DBG1("0x%04X->0x%04X", *((u16 *)&dc->port[port].ctrl_dl),
*((u16 *)&ctrl_dl));
old_ctrl = dc->port[port].ctrl_dl;
dc->port[port].ctrl_dl = ctrl_dl;
if (old_ctrl.CTS == 1 && ctrl_dl.CTS == 0) {
DBG1("Disable interrupt (0x%04X) on port: %d",
enable_ier, port);
disable_transmit_ul(port, dc);
} else if (old_ctrl.CTS == 0 && ctrl_dl.CTS == 1) {
if (kfifo_len(&dc->port[port].fifo_ul)) {
DBG1("Enable interrupt (0x%04X) on port: %d",
enable_ier, port);
DBG1("Data in buffer [%d], enable transmit! ",
kfifo_len(&dc->port[port].fifo_ul));
enable_transmit_ul(port, dc);
} else {
DBG1("No data in buffer...");
}
}
if (*(u16 *)&old_ctrl == *(u16 *)&ctrl_dl) {
DBG1(" No change in mctrl");
return 1;
}
/* Update statistics */
if (old_ctrl.CTS != ctrl_dl.CTS)
dc->port[port].tty_icount.cts++;
if (old_ctrl.DSR != ctrl_dl.DSR)
dc->port[port].tty_icount.dsr++;
if (old_ctrl.RI != ctrl_dl.RI)
dc->port[port].tty_icount.rng++;
if (old_ctrl.DCD != ctrl_dl.DCD)
dc->port[port].tty_icount.dcd++;
wake_up_interruptible(&dc->port[port].tty_wait);
DBG1("port: %d DCD(%d), CTS(%d), RI(%d), DSR(%d)",
port,
dc->port[port].tty_icount.dcd, dc->port[port].tty_icount.cts,
dc->port[port].tty_icount.rng, dc->port[port].tty_icount.dsr);
return 1;
}
static enum ctrl_port_type port2ctrl(enum port_type port,
const struct nozomi *dc)
{
switch (port) {
case PORT_MDM:
return CTRL_MDM;
case PORT_DIAG:
return CTRL_DIAG;
case PORT_APP1:
return CTRL_APP1;
case PORT_APP2:
return CTRL_APP2;
default:
dev_err(&dc->pdev->dev,
"ERROR: send flow control " \
"received for non-existing port\n");
};
return CTRL_ERROR;
}
/*
* Send flow control, can only update one channel at a time
* Return 0 - If we have updated all flow control
* Return 1 - If we need to update more flow control, ack current enable more
*/
static int send_flow_control(struct nozomi *dc)
{
u32 i, more_flow_control_to_be_updated = 0;
u16 *ctrl;
for (i = PORT_MDM; i < MAX_PORT; i++) {
if (dc->port[i].update_flow_control) {
if (more_flow_control_to_be_updated) {
/* We have more flow control to be updated */
return 1;
}
dc->port[i].ctrl_ul.port = port2ctrl(i, dc);
ctrl = (u16 *)&dc->port[i].ctrl_ul;
write_mem32(dc->port[PORT_CTRL].ul_addr[0], \
(u32 *) ctrl, 2);
dc->port[i].update_flow_control = 0;
more_flow_control_to_be_updated = 1;
}
}
return 0;
}
/*
* Handle downlink data, ports that are handled are modem and diagnostics
* Return 1 - ok
* Return 0 - toggle fields are out of sync
*/
static int handle_data_dl(struct nozomi *dc, enum port_type port, u8 *toggle,
u16 read_iir, u16 mask1, u16 mask2)
{
if (*toggle == 0 && read_iir & mask1) {
if (receive_data(port, dc)) {
writew(mask1, dc->reg_fcr);
*toggle = !(*toggle);
}
if (read_iir & mask2) {
if (receive_data(port, dc)) {
writew(mask2, dc->reg_fcr);
*toggle = !(*toggle);
}
}
} else if (*toggle == 1 && read_iir & mask2) {
if (receive_data(port, dc)) {
writew(mask2, dc->reg_fcr);
*toggle = !(*toggle);
}
if (read_iir & mask1) {
if (receive_data(port, dc)) {
writew(mask1, dc->reg_fcr);
*toggle = !(*toggle);
}
}
} else {
dev_err(&dc->pdev->dev, "port out of sync!, toggle:%d\n",
*toggle);
return 0;
}
return 1;
}
/*
* Handle uplink data, this is currently for the modem port
* Return 1 - ok
* Return 0 - toggle field are out of sync
*/
static int handle_data_ul(struct nozomi *dc, enum port_type port, u16 read_iir)
{
u8 *toggle = &(dc->port[port].toggle_ul);
if (*toggle == 0 && read_iir & MDM_UL1) {
dc->last_ier &= ~MDM_UL;
writew(dc->last_ier, dc->reg_ier);
if (send_data(port, dc)) {
writew(MDM_UL1, dc->reg_fcr);
dc->last_ier = dc->last_ier | MDM_UL;
writew(dc->last_ier, dc->reg_ier);
*toggle = !*toggle;
}
if (read_iir & MDM_UL2) {
dc->last_ier &= ~MDM_UL;
writew(dc->last_ier, dc->reg_ier);
if (send_data(port, dc)) {
writew(MDM_UL2, dc->reg_fcr);
dc->last_ier = dc->last_ier | MDM_UL;
writew(dc->last_ier, dc->reg_ier);
*toggle = !*toggle;
}
}
} else if (*toggle == 1 && read_iir & MDM_UL2) {
dc->last_ier &= ~MDM_UL;
writew(dc->last_ier, dc->reg_ier);
if (send_data(port, dc)) {
writew(MDM_UL2, dc->reg_fcr);
dc->last_ier = dc->last_ier | MDM_UL;
writew(dc->last_ier, dc->reg_ier);
*toggle = !*toggle;
}
if (read_iir & MDM_UL1) {
dc->last_ier &= ~MDM_UL;
writew(dc->last_ier, dc->reg_ier);
if (send_data(port, dc)) {
writew(MDM_UL1, dc->reg_fcr);
dc->last_ier = dc->last_ier | MDM_UL;
writew(dc->last_ier, dc->reg_ier);
*toggle = !*toggle;
}
}
} else {
writew(read_iir & MDM_UL, dc->reg_fcr);
dev_err(&dc->pdev->dev, "port out of sync!\n");
return 0;
}
return 1;
}
static irqreturn_t interrupt_handler(int irq, void *dev_id)
{
struct nozomi *dc = dev_id;
unsigned int a;
u16 read_iir;
if (!dc)
return IRQ_NONE;
spin_lock(&dc->spin_mutex);
read_iir = readw(dc->reg_iir);
/* Card removed */
if (read_iir == (u16)-1)
goto none;
/*
* Just handle interrupt enabled in IER
* (by masking with dc->last_ier)
*/
read_iir &= dc->last_ier;
if (read_iir == 0)
goto none;
DBG4("%s irq:0x%04X, prev:0x%04X", interrupt2str(read_iir), read_iir,
dc->last_ier);
if (read_iir & RESET) {
if (unlikely(!nozomi_read_config_table(dc))) {
dc->last_ier = 0x0;
writew(dc->last_ier, dc->reg_ier);
dev_err(&dc->pdev->dev, "Could not read status from "
"card, we should disable interface\n");
} else {
writew(RESET, dc->reg_fcr);
}
/* No more useful info if this was the reset interrupt. */
goto exit_handler;
}
if (read_iir & CTRL_UL) {
DBG1("CTRL_UL");
dc->last_ier &= ~CTRL_UL;
writew(dc->last_ier, dc->reg_ier);
if (send_flow_control(dc)) {
writew(CTRL_UL, dc->reg_fcr);
dc->last_ier = dc->last_ier | CTRL_UL;
writew(dc->last_ier, dc->reg_ier);
}
}
if (read_iir & CTRL_DL) {
receive_flow_control(dc);
writew(CTRL_DL, dc->reg_fcr);
}
if (read_iir & MDM_DL) {
if (!handle_data_dl(dc, PORT_MDM,
&(dc->port[PORT_MDM].toggle_dl), read_iir,
MDM_DL1, MDM_DL2)) {
dev_err(&dc->pdev->dev, "MDM_DL out of sync!\n");
goto exit_handler;
}
}
if (read_iir & MDM_UL) {
if (!handle_data_ul(dc, PORT_MDM, read_iir)) {
dev_err(&dc->pdev->dev, "MDM_UL out of sync!\n");
goto exit_handler;
}
}
if (read_iir & DIAG_DL) {
if (!handle_data_dl(dc, PORT_DIAG,
&(dc->port[PORT_DIAG].toggle_dl), read_iir,
DIAG_DL1, DIAG_DL2)) {
dev_err(&dc->pdev->dev, "DIAG_DL out of sync!\n");
goto exit_handler;
}
}
if (read_iir & DIAG_UL) {
dc->last_ier &= ~DIAG_UL;
writew(dc->last_ier, dc->reg_ier);
if (send_data(PORT_DIAG, dc)) {
writew(DIAG_UL, dc->reg_fcr);
dc->last_ier = dc->last_ier | DIAG_UL;
writew(dc->last_ier, dc->reg_ier);
}
}
if (read_iir & APP1_DL) {
if (receive_data(PORT_APP1, dc))
writew(APP1_DL, dc->reg_fcr);
}
if (read_iir & APP1_UL) {
dc->last_ier &= ~APP1_UL;
writew(dc->last_ier, dc->reg_ier);
if (send_data(PORT_APP1, dc)) {
writew(APP1_UL, dc->reg_fcr);
dc->last_ier = dc->last_ier | APP1_UL;
writew(dc->last_ier, dc->reg_ier);
}
}
if (read_iir & APP2_DL) {
if (receive_data(PORT_APP2, dc))
writew(APP2_DL, dc->reg_fcr);
}
if (read_iir & APP2_UL) {
dc->last_ier &= ~APP2_UL;
writew(dc->last_ier, dc->reg_ier);
if (send_data(PORT_APP2, dc)) {
writew(APP2_UL, dc->reg_fcr);
dc->last_ier = dc->last_ier | APP2_UL;
writew(dc->last_ier, dc->reg_ier);
}
}
exit_handler:
spin_unlock(&dc->spin_mutex);
for (a = 0; a < NOZOMI_MAX_PORTS; a++) {
struct tty_struct *tty;
if (test_and_clear_bit(a, &dc->flip)) {
tty = tty_port_tty_get(&dc->port[a].port);
if (tty)
tty_flip_buffer_push(tty);
tty_kref_put(tty);
}
}
return IRQ_HANDLED;
none:
spin_unlock(&dc->spin_mutex);
return IRQ_NONE;
}
static void nozomi_get_card_type(struct nozomi *dc)
{
int i;
u32 size = 0;
for (i = 0; i < 6; i++)
size += pci_resource_len(dc->pdev, i);
/* Assume card type F32_8 if no match */
dc->card_type = size == 2048 ? F32_2 : F32_8;
dev_info(&dc->pdev->dev, "Card type is: %d\n", dc->card_type);
}
static void nozomi_setup_private_data(struct nozomi *dc)
{
void __iomem *offset = dc->base_addr + dc->card_type / 2;
unsigned int i;
dc->reg_fcr = (void __iomem *)(offset + R_FCR);
dc->reg_iir = (void __iomem *)(offset + R_IIR);
dc->reg_ier = (void __iomem *)(offset + R_IER);
dc->last_ier = 0;
dc->flip = 0;
dc->port[PORT_MDM].token_dl = MDM_DL;
dc->port[PORT_DIAG].token_dl = DIAG_DL;
dc->port[PORT_APP1].token_dl = APP1_DL;
dc->port[PORT_APP2].token_dl = APP2_DL;
for (i = 0; i < MAX_PORT; i++)
init_waitqueue_head(&dc->port[i].tty_wait);
}
static ssize_t card_type_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
const struct nozomi *dc = pci_get_drvdata(to_pci_dev(dev));
return sprintf(buf, "%d\n", dc->card_type);
}
static DEVICE_ATTR(card_type, S_IRUGO, card_type_show, NULL);
static ssize_t open_ttys_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
const struct nozomi *dc = pci_get_drvdata(to_pci_dev(dev));
return sprintf(buf, "%u\n", dc->open_ttys);
}
static DEVICE_ATTR(open_ttys, S_IRUGO, open_ttys_show, NULL);
static void make_sysfs_files(struct nozomi *dc)
{
if (device_create_file(&dc->pdev->dev, &dev_attr_card_type))
dev_err(&dc->pdev->dev,
"Could not create sysfs file for card_type\n");
if (device_create_file(&dc->pdev->dev, &dev_attr_open_ttys))
dev_err(&dc->pdev->dev,
"Could not create sysfs file for open_ttys\n");
}
static void remove_sysfs_files(struct nozomi *dc)
{
device_remove_file(&dc->pdev->dev, &dev_attr_card_type);
device_remove_file(&dc->pdev->dev, &dev_attr_open_ttys);
}
/* Allocate memory for one device */
static int __devinit nozomi_card_init(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
resource_size_t start;
int ret;
struct nozomi *dc = NULL;
int ndev_idx;
int i;
dev_dbg(&pdev->dev, "Init, new card found\n");
for (ndev_idx = 0; ndev_idx < ARRAY_SIZE(ndevs); ndev_idx++)
if (!ndevs[ndev_idx])
break;
if (ndev_idx >= ARRAY_SIZE(ndevs)) {
dev_err(&pdev->dev, "no free tty range for this card left\n");
ret = -EIO;
goto err;
}
dc = kzalloc(sizeof(struct nozomi), GFP_KERNEL);
if (unlikely(!dc)) {
dev_err(&pdev->dev, "Could not allocate memory\n");
ret = -ENOMEM;
goto err_free;
}
dc->pdev = pdev;
ret = pci_enable_device(dc->pdev);
if (ret) {
dev_err(&pdev->dev, "Failed to enable PCI Device\n");
goto err_free;
}
ret = pci_request_regions(dc->pdev, NOZOMI_NAME);
if (ret) {
dev_err(&pdev->dev, "I/O address 0x%04x already in use\n",
(int) /* nozomi_private.io_addr */ 0);
goto err_disable_device;
}
start = pci_resource_start(dc->pdev, 0);
if (start == 0) {
dev_err(&pdev->dev, "No I/O address for card detected\n");
ret = -ENODEV;
goto err_rel_regs;
}
/* Find out what card type it is */
nozomi_get_card_type(dc);
dc->base_addr = ioremap_nocache(start, dc->card_type);
if (!dc->base_addr) {
dev_err(&pdev->dev, "Unable to map card MMIO\n");
ret = -ENODEV;
goto err_rel_regs;
}
dc->send_buf = kmalloc(SEND_BUF_MAX, GFP_KERNEL);
if (!dc->send_buf) {
dev_err(&pdev->dev, "Could not allocate send buffer?\n");
ret = -ENOMEM;
goto err_free_sbuf;
}
for (i = PORT_MDM; i < MAX_PORT; i++) {
if (kfifo_alloc(&dc->port[i].fifo_ul, FIFO_BUFFER_SIZE_UL,
GFP_KERNEL)) {
dev_err(&pdev->dev,
"Could not allocate kfifo buffer\n");
ret = -ENOMEM;
goto err_free_kfifo;
}
}
spin_lock_init(&dc->spin_mutex);
nozomi_setup_private_data(dc);
/* Disable all interrupts */
dc->last_ier = 0;
writew(dc->last_ier, dc->reg_ier);
ret = request_irq(pdev->irq, &interrupt_handler, IRQF_SHARED,
NOZOMI_NAME, dc);
if (unlikely(ret)) {
dev_err(&pdev->dev, "can't request irq %d\n", pdev->irq);
goto err_free_kfifo;
}
DBG1("base_addr: %p", dc->base_addr);
make_sysfs_files(dc);
dc->index_start = ndev_idx * MAX_PORT;
ndevs[ndev_idx] = dc;
pci_set_drvdata(pdev, dc);
/* Enable RESET interrupt */
dc->last_ier = RESET;
iowrite16(dc->last_ier, dc->reg_ier);
dc->state = NOZOMI_STATE_ENABLED;
for (i = 0; i < MAX_PORT; i++) {
struct device *tty_dev;
struct port *port = &dc->port[i];
port->dc = dc;
tty_port_init(&port->port);
port->port.ops = &noz_tty_port_ops;
tty_dev = tty_register_device(ntty_driver, dc->index_start + i,
&pdev->dev);
if (IS_ERR(tty_dev)) {
ret = PTR_ERR(tty_dev);
dev_err(&pdev->dev, "Could not allocate tty?\n");
goto err_free_tty;
}
}
return 0;
err_free_tty:
for (i = dc->index_start; i < dc->index_start + MAX_PORT; ++i)
tty_unregister_device(ntty_driver, i);
err_free_kfifo:
for (i = 0; i < MAX_PORT; i++)
kfifo_free(&dc->port[i].fifo_ul);
err_free_sbuf:
kfree(dc->send_buf);
iounmap(dc->base_addr);
err_rel_regs:
pci_release_regions(pdev);
err_disable_device:
pci_disable_device(pdev);
err_free:
kfree(dc);
err:
return ret;
}
static void __devexit tty_exit(struct nozomi *dc)
{
unsigned int i;
DBG1(" ");
for (i = 0; i < MAX_PORT; ++i) {
struct tty_struct *tty = tty_port_tty_get(&dc->port[i].port);
if (tty && list_empty(&tty->hangup_work.entry))
tty_hangup(tty);
tty_kref_put(tty);
}
/* Racy below - surely should wait for scheduled work to be done or
complete off a hangup method ? */
while (dc->open_ttys)
msleep(1);
for (i = dc->index_start; i < dc->index_start + MAX_PORT; ++i)
tty_unregister_device(ntty_driver, i);
}
/* Deallocate memory for one device */
static void __devexit nozomi_card_exit(struct pci_dev *pdev)
{
int i;
struct ctrl_ul ctrl;
struct nozomi *dc = pci_get_drvdata(pdev);
/* Disable all interrupts */
dc->last_ier = 0;
writew(dc->last_ier, dc->reg_ier);
tty_exit(dc);
/* Send 0x0001, command card to resend the reset token. */
/* This is to get the reset when the module is reloaded. */
ctrl.port = 0x00;
ctrl.reserved = 0;
ctrl.RTS = 0;
ctrl.DTR = 1;
DBG1("sending flow control 0x%04X", *((u16 *)&ctrl));
/* Setup dc->reg addresses to we can use defines here */
write_mem32(dc->port[PORT_CTRL].ul_addr[0], (u32 *)&ctrl, 2);
writew(CTRL_UL, dc->reg_fcr); /* push the token to the card. */
remove_sysfs_files(dc);
free_irq(pdev->irq, dc);
for (i = 0; i < MAX_PORT; i++)
kfifo_free(&dc->port[i].fifo_ul);
kfree(dc->send_buf);
iounmap(dc->base_addr);
pci_release_regions(pdev);
pci_disable_device(pdev);
ndevs[dc->index_start / MAX_PORT] = NULL;
kfree(dc);
}
static void set_rts(const struct tty_struct *tty, int rts)
{
struct port *port = get_port_by_tty(tty);
port->ctrl_ul.RTS = rts;
port->update_flow_control = 1;
enable_transmit_ul(PORT_CTRL, get_dc_by_tty(tty));
}
static void set_dtr(const struct tty_struct *tty, int dtr)
{
struct port *port = get_port_by_tty(tty);
DBG1("SETTING DTR index: %d, dtr: %d", tty->index, dtr);
port->ctrl_ul.DTR = dtr;
port->update_flow_control = 1;
enable_transmit_ul(PORT_CTRL, get_dc_by_tty(tty));
}
/*
* ----------------------------------------------------------------------------
* TTY code
* ----------------------------------------------------------------------------
*/
static int ntty_install(struct tty_driver *driver, struct tty_struct *tty)
{
struct port *port = get_port_by_tty(tty);
struct nozomi *dc = get_dc_by_tty(tty);
int ret;
if (!port || !dc || dc->state != NOZOMI_STATE_READY)
return -ENODEV;
ret = tty_standard_install(driver, tty);
if (ret == 0)
tty->driver_data = port;
return ret;
}
static void ntty_cleanup(struct tty_struct *tty)
{
tty->driver_data = NULL;
}
static int ntty_activate(struct tty_port *tport, struct tty_struct *tty)
{
struct port *port = container_of(tport, struct port, port);
struct nozomi *dc = port->dc;
unsigned long flags;
DBG1("open: %d", port->token_dl);
spin_lock_irqsave(&dc->spin_mutex, flags);
dc->last_ier = dc->last_ier | port->token_dl;
writew(dc->last_ier, dc->reg_ier);
dc->open_ttys++;
spin_unlock_irqrestore(&dc->spin_mutex, flags);
printk("noz: activated %d: %p\n", tty->index, tport);
return 0;
}
static int ntty_open(struct tty_struct *tty, struct file *filp)
{
struct port *port = tty->driver_data;
return tty_port_open(&port->port, tty, filp);
}
static void ntty_shutdown(struct tty_port *tport)
{
struct port *port = container_of(tport, struct port, port);
struct nozomi *dc = port->dc;
unsigned long flags;
DBG1("close: %d", port->token_dl);
spin_lock_irqsave(&dc->spin_mutex, flags);
dc->last_ier &= ~(port->token_dl);
writew(dc->last_ier, dc->reg_ier);
dc->open_ttys--;
spin_unlock_irqrestore(&dc->spin_mutex, flags);
printk("noz: shutdown %p\n", tport);
}
static void ntty_close(struct tty_struct *tty, struct file *filp)
{
struct port *port = tty->driver_data;
if (port)
tty_port_close(&port->port, tty, filp);
}
static void ntty_hangup(struct tty_struct *tty)
{
struct port *port = tty->driver_data;
tty_port_hangup(&port->port);
}
/*
* called when the userspace process writes to the tty (/dev/noz*).
* Data is inserted into a fifo, which is then read and transferred to the modem.
*/
static int ntty_write(struct tty_struct *tty, const unsigned char *buffer,
int count)
{
int rval = -EINVAL;
struct nozomi *dc = get_dc_by_tty(tty);
struct port *port = tty->driver_data;
unsigned long flags;
/* DBG1( "WRITEx: %d, index = %d", count, index); */
if (!dc || !port)
return -ENODEV;
rval = kfifo_in(&port->fifo_ul, (unsigned char *)buffer, count);
/* notify card */
if (unlikely(dc == NULL)) {
DBG1("No device context?");
goto exit;
}
spin_lock_irqsave(&dc->spin_mutex, flags);
/* CTS is only valid on the modem channel */
if (port == &(dc->port[PORT_MDM])) {
if (port->ctrl_dl.CTS) {
DBG4("Enable interrupt");
enable_transmit_ul(tty->index % MAX_PORT, dc);
} else {
dev_err(&dc->pdev->dev,
"CTS not active on modem port?\n");
}
} else {
enable_transmit_ul(tty->index % MAX_PORT, dc);
}
spin_unlock_irqrestore(&dc->spin_mutex, flags);
exit:
return rval;
}
/*
* Calculate how much is left in device
* This method is called by the upper tty layer.
* #according to sources N_TTY.c it expects a value >= 0 and
* does not check for negative values.
*
* If the port is unplugged report lots of room and let the bits
* dribble away so we don't block anything.
*/
static int ntty_write_room(struct tty_struct *tty)
{
struct port *port = tty->driver_data;
int room = 4096;
const struct nozomi *dc = get_dc_by_tty(tty);
if (dc)
room = kfifo_avail(&port->fifo_ul);
return room;
}
/* Gets io control parameters */
static int ntty_tiocmget(struct tty_struct *tty)
{
const struct port *port = tty->driver_data;
const struct ctrl_dl *ctrl_dl = &port->ctrl_dl;
const struct ctrl_ul *ctrl_ul = &port->ctrl_ul;
/* Note: these could change under us but it is not clear this
matters if so */
return (ctrl_ul->RTS ? TIOCM_RTS : 0) |
(ctrl_ul->DTR ? TIOCM_DTR : 0) |
(ctrl_dl->DCD ? TIOCM_CAR : 0) |
(ctrl_dl->RI ? TIOCM_RNG : 0) |
(ctrl_dl->DSR ? TIOCM_DSR : 0) |
(ctrl_dl->CTS ? TIOCM_CTS : 0);
}
/* Sets io controls parameters */
static int ntty_tiocmset(struct tty_struct *tty,
unsigned int set, unsigned int clear)
{
struct nozomi *dc = get_dc_by_tty(tty);
unsigned long flags;
spin_lock_irqsave(&dc->spin_mutex, flags);
if (set & TIOCM_RTS)
set_rts(tty, 1);
else if (clear & TIOCM_RTS)
set_rts(tty, 0);
if (set & TIOCM_DTR)
set_dtr(tty, 1);
else if (clear & TIOCM_DTR)
set_dtr(tty, 0);
spin_unlock_irqrestore(&dc->spin_mutex, flags);
return 0;
}
static int ntty_cflags_changed(struct port *port, unsigned long flags,
struct async_icount *cprev)
{
const struct async_icount cnow = port->tty_icount;
int ret;
ret = ((flags & TIOCM_RNG) && (cnow.rng != cprev->rng)) ||
((flags & TIOCM_DSR) && (cnow.dsr != cprev->dsr)) ||
((flags & TIOCM_CD) && (cnow.dcd != cprev->dcd)) ||
((flags & TIOCM_CTS) && (cnow.cts != cprev->cts));
*cprev = cnow;
return ret;
}
static int ntty_tiocgicount(struct tty_struct *tty,
struct serial_icounter_struct *icount)
{
struct port *port = tty->driver_data;
const struct async_icount cnow = port->tty_icount;
icount->cts = cnow.cts;
icount->dsr = cnow.dsr;
icount->rng = cnow.rng;
icount->dcd = cnow.dcd;
icount->rx = cnow.rx;
icount->tx = cnow.tx;
icount->frame = cnow.frame;
icount->overrun = cnow.overrun;
icount->parity = cnow.parity;
icount->brk = cnow.brk;
icount->buf_overrun = cnow.buf_overrun;
return 0;
}
static int ntty_ioctl(struct tty_struct *tty,
unsigned int cmd, unsigned long arg)
{
struct port *port = tty->driver_data;
int rval = -ENOIOCTLCMD;
DBG1("******** IOCTL, cmd: %d", cmd);
switch (cmd) {
case TIOCMIWAIT: {
struct async_icount cprev = port->tty_icount;
rval = wait_event_interruptible(port->tty_wait,
ntty_cflags_changed(port, arg, &cprev));
break;
}
default:
DBG1("ERR: 0x%08X, %d", cmd, cmd);
break;
};
return rval;
}
/*
* Called by the upper tty layer when tty buffers are ready
* to receive data again after a call to throttle.
*/
static void ntty_unthrottle(struct tty_struct *tty)
{
struct nozomi *dc = get_dc_by_tty(tty);
unsigned long flags;
DBG1("UNTHROTTLE");
spin_lock_irqsave(&dc->spin_mutex, flags);
enable_transmit_dl(tty->index % MAX_PORT, dc);
set_rts(tty, 1);
spin_unlock_irqrestore(&dc->spin_mutex, flags);
}
/*
* Called by the upper tty layer when the tty buffers are almost full.
* The driver should stop send more data.
*/
static void ntty_throttle(struct tty_struct *tty)
{
struct nozomi *dc = get_dc_by_tty(tty);
unsigned long flags;
DBG1("THROTTLE");
spin_lock_irqsave(&dc->spin_mutex, flags);
set_rts(tty, 0);
spin_unlock_irqrestore(&dc->spin_mutex, flags);
}
/* Returns number of chars in buffer, called by tty layer */
static s32 ntty_chars_in_buffer(struct tty_struct *tty)
{
struct port *port = tty->driver_data;
struct nozomi *dc = get_dc_by_tty(tty);
s32 rval = 0;
if (unlikely(!dc || !port)) {
goto exit_in_buffer;
}
rval = kfifo_len(&port->fifo_ul);
exit_in_buffer:
return rval;
}
static const struct tty_port_operations noz_tty_port_ops = {
.activate = ntty_activate,
.shutdown = ntty_shutdown,
};
static const struct tty_operations tty_ops = {
.ioctl = ntty_ioctl,
.open = ntty_open,
.close = ntty_close,
.hangup = ntty_hangup,
.write = ntty_write,
.write_room = ntty_write_room,
.unthrottle = ntty_unthrottle,
.throttle = ntty_throttle,
.chars_in_buffer = ntty_chars_in_buffer,
.tiocmget = ntty_tiocmget,
.tiocmset = ntty_tiocmset,
.get_icount = ntty_tiocgicount,
.install = ntty_install,
.cleanup = ntty_cleanup,
};
/* Module initialization */
static struct pci_driver nozomi_driver = {
.name = NOZOMI_NAME,
.id_table = nozomi_pci_tbl,
.probe = nozomi_card_init,
.remove = __devexit_p(nozomi_card_exit),
};
static __init int nozomi_init(void)
{
int ret;
printk(KERN_INFO "Initializing %s\n", VERSION_STRING);
ntty_driver = alloc_tty_driver(NTTY_TTY_MAXMINORS);
if (!ntty_driver)
return -ENOMEM;
ntty_driver->driver_name = NOZOMI_NAME_TTY;
ntty_driver->name = "noz";
ntty_driver->major = 0;
ntty_driver->type = TTY_DRIVER_TYPE_SERIAL;
ntty_driver->subtype = SERIAL_TYPE_NORMAL;
ntty_driver->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV;
ntty_driver->init_termios = tty_std_termios;
ntty_driver->init_termios.c_cflag = B115200 | CS8 | CREAD | \
HUPCL | CLOCAL;
ntty_driver->init_termios.c_ispeed = 115200;
ntty_driver->init_termios.c_ospeed = 115200;
tty_set_operations(ntty_driver, &tty_ops);
ret = tty_register_driver(ntty_driver);
if (ret) {
printk(KERN_ERR "Nozomi: failed to register ntty driver\n");
goto free_tty;
}
ret = pci_register_driver(&nozomi_driver);
if (ret) {
printk(KERN_ERR "Nozomi: can't register pci driver\n");
goto unr_tty;
}
return 0;
unr_tty:
tty_unregister_driver(ntty_driver);
free_tty:
put_tty_driver(ntty_driver);
return ret;
}
static __exit void nozomi_exit(void)
{
printk(KERN_INFO "Unloading %s\n", DRIVER_DESC);
pci_unregister_driver(&nozomi_driver);
tty_unregister_driver(ntty_driver);
put_tty_driver(ntty_driver);
}
module_init(nozomi_init);
module_exit(nozomi_exit);
module_param(debug, int, S_IRUGO | S_IWUSR);
MODULE_LICENSE("Dual BSD/GPL");
MODULE_DESCRIPTION(DRIVER_DESC);
| gpl-2.0 |
xenon1978/Xperia_T3_D5102 | drivers/w1/slaves/w1_ds2408.c | 5455 | 9764 | /*
* w1_ds2408.c - w1 family 29 (DS2408) driver
*
* Copyright (c) 2010 Jean-Francois Dagenais <dagenaisj@sonatest.com>
*
* This source code is licensed under the GNU General Public License,
* Version 2. See the file COPYING for more details.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/device.h>
#include <linux/types.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include "../w1.h"
#include "../w1_int.h"
#include "../w1_family.h"
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Jean-Francois Dagenais <dagenaisj@sonatest.com>");
MODULE_DESCRIPTION("w1 family 29 driver for DS2408 8 Pin IO");
#define W1_F29_RETRIES 3
#define W1_F29_REG_LOGIG_STATE 0x88 /* R */
#define W1_F29_REG_OUTPUT_LATCH_STATE 0x89 /* R */
#define W1_F29_REG_ACTIVITY_LATCH_STATE 0x8A /* R */
#define W1_F29_REG_COND_SEARCH_SELECT_MASK 0x8B /* RW */
#define W1_F29_REG_COND_SEARCH_POL_SELECT 0x8C /* RW */
#define W1_F29_REG_CONTROL_AND_STATUS 0x8D /* RW */
#define W1_F29_FUNC_READ_PIO_REGS 0xF0
#define W1_F29_FUNC_CHANN_ACCESS_READ 0xF5
#define W1_F29_FUNC_CHANN_ACCESS_WRITE 0x5A
/* also used to write the control/status reg (0x8D): */
#define W1_F29_FUNC_WRITE_COND_SEARCH_REG 0xCC
#define W1_F29_FUNC_RESET_ACTIVITY_LATCHES 0xC3
#define W1_F29_SUCCESS_CONFIRM_BYTE 0xAA
static int _read_reg(struct w1_slave *sl, u8 address, unsigned char* buf)
{
u8 wrbuf[3];
dev_dbg(&sl->dev,
"Reading with slave: %p, reg addr: %0#4x, buff addr: %p",
sl, (unsigned int)address, buf);
if (!buf)
return -EINVAL;
mutex_lock(&sl->master->mutex);
dev_dbg(&sl->dev, "mutex locked");
if (w1_reset_select_slave(sl)) {
mutex_unlock(&sl->master->mutex);
return -EIO;
}
wrbuf[0] = W1_F29_FUNC_READ_PIO_REGS;
wrbuf[1] = address;
wrbuf[2] = 0;
w1_write_block(sl->master, wrbuf, 3);
*buf = w1_read_8(sl->master);
mutex_unlock(&sl->master->mutex);
dev_dbg(&sl->dev, "mutex unlocked");
return 1;
}
static ssize_t w1_f29_read_state(
struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t off, size_t count)
{
dev_dbg(&kobj_to_w1_slave(kobj)->dev,
"Reading %s kobj: %p, off: %0#10x, count: %zu, buff addr: %p",
bin_attr->attr.name, kobj, (unsigned int)off, count, buf);
if (count != 1 || off != 0)
return -EFAULT;
return _read_reg(kobj_to_w1_slave(kobj), W1_F29_REG_LOGIG_STATE, buf);
}
static ssize_t w1_f29_read_output(
struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t off, size_t count)
{
dev_dbg(&kobj_to_w1_slave(kobj)->dev,
"Reading %s kobj: %p, off: %0#10x, count: %zu, buff addr: %p",
bin_attr->attr.name, kobj, (unsigned int)off, count, buf);
if (count != 1 || off != 0)
return -EFAULT;
return _read_reg(kobj_to_w1_slave(kobj),
W1_F29_REG_OUTPUT_LATCH_STATE, buf);
}
static ssize_t w1_f29_read_activity(
struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t off, size_t count)
{
dev_dbg(&kobj_to_w1_slave(kobj)->dev,
"Reading %s kobj: %p, off: %0#10x, count: %zu, buff addr: %p",
bin_attr->attr.name, kobj, (unsigned int)off, count, buf);
if (count != 1 || off != 0)
return -EFAULT;
return _read_reg(kobj_to_w1_slave(kobj),
W1_F29_REG_ACTIVITY_LATCH_STATE, buf);
}
static ssize_t w1_f29_read_cond_search_mask(
struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t off, size_t count)
{
dev_dbg(&kobj_to_w1_slave(kobj)->dev,
"Reading %s kobj: %p, off: %0#10x, count: %zu, buff addr: %p",
bin_attr->attr.name, kobj, (unsigned int)off, count, buf);
if (count != 1 || off != 0)
return -EFAULT;
return _read_reg(kobj_to_w1_slave(kobj),
W1_F29_REG_COND_SEARCH_SELECT_MASK, buf);
}
static ssize_t w1_f29_read_cond_search_polarity(
struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t off, size_t count)
{
if (count != 1 || off != 0)
return -EFAULT;
return _read_reg(kobj_to_w1_slave(kobj),
W1_F29_REG_COND_SEARCH_POL_SELECT, buf);
}
static ssize_t w1_f29_read_status_control(
struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t off, size_t count)
{
if (count != 1 || off != 0)
return -EFAULT;
return _read_reg(kobj_to_w1_slave(kobj),
W1_F29_REG_CONTROL_AND_STATUS, buf);
}
static ssize_t w1_f29_write_output(
struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t off, size_t count)
{
struct w1_slave *sl = kobj_to_w1_slave(kobj);
u8 w1_buf[3];
u8 readBack;
unsigned int retries = W1_F29_RETRIES;
if (count != 1 || off != 0)
return -EFAULT;
dev_dbg(&sl->dev, "locking mutex for write_output");
mutex_lock(&sl->master->mutex);
dev_dbg(&sl->dev, "mutex locked");
if (w1_reset_select_slave(sl))
goto error;
while (retries--) {
w1_buf[0] = W1_F29_FUNC_CHANN_ACCESS_WRITE;
w1_buf[1] = *buf;
w1_buf[2] = ~(*buf);
w1_write_block(sl->master, w1_buf, 3);
readBack = w1_read_8(sl->master);
/* here the master could read another byte which
would be the PIO reg (the actual pin logic state)
since in this driver we don't know which pins are
in and outs, there's no value to read the state and
compare. with (*buf) so end this command abruptly: */
if (w1_reset_resume_command(sl->master))
goto error;
if (readBack != 0xAA) {
/* try again, the slave is ready for a command */
continue;
}
/* go read back the output latches */
/* (the direct effect of the write above) */
w1_buf[0] = W1_F29_FUNC_READ_PIO_REGS;
w1_buf[1] = W1_F29_REG_OUTPUT_LATCH_STATE;
w1_buf[2] = 0;
w1_write_block(sl->master, w1_buf, 3);
/* read the result of the READ_PIO_REGS command */
if (w1_read_8(sl->master) == *buf) {
/* success! */
mutex_unlock(&sl->master->mutex);
dev_dbg(&sl->dev,
"mutex unlocked, retries:%d", retries);
return 1;
}
}
error:
mutex_unlock(&sl->master->mutex);
dev_dbg(&sl->dev, "mutex unlocked in error, retries:%d", retries);
return -EIO;
}
/**
* Writing to the activity file resets the activity latches.
*/
static ssize_t w1_f29_write_activity(
struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t off, size_t count)
{
struct w1_slave *sl = kobj_to_w1_slave(kobj);
unsigned int retries = W1_F29_RETRIES;
if (count != 1 || off != 0)
return -EFAULT;
mutex_lock(&sl->master->mutex);
if (w1_reset_select_slave(sl))
goto error;
while (retries--) {
w1_write_8(sl->master, W1_F29_FUNC_RESET_ACTIVITY_LATCHES);
if (w1_read_8(sl->master) == W1_F29_SUCCESS_CONFIRM_BYTE) {
mutex_unlock(&sl->master->mutex);
return 1;
}
if (w1_reset_resume_command(sl->master))
goto error;
}
error:
mutex_unlock(&sl->master->mutex);
return -EIO;
}
static ssize_t w1_f29_write_status_control(
struct file *filp,
struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf,
loff_t off,
size_t count)
{
struct w1_slave *sl = kobj_to_w1_slave(kobj);
u8 w1_buf[4];
unsigned int retries = W1_F29_RETRIES;
if (count != 1 || off != 0)
return -EFAULT;
mutex_lock(&sl->master->mutex);
if (w1_reset_select_slave(sl))
goto error;
while (retries--) {
w1_buf[0] = W1_F29_FUNC_WRITE_COND_SEARCH_REG;
w1_buf[1] = W1_F29_REG_CONTROL_AND_STATUS;
w1_buf[2] = 0;
w1_buf[3] = *buf;
w1_write_block(sl->master, w1_buf, 4);
if (w1_reset_resume_command(sl->master))
goto error;
w1_buf[0] = W1_F29_FUNC_READ_PIO_REGS;
w1_buf[1] = W1_F29_REG_CONTROL_AND_STATUS;
w1_buf[2] = 0;
w1_write_block(sl->master, w1_buf, 3);
if (w1_read_8(sl->master) == *buf) {
/* success! */
mutex_unlock(&sl->master->mutex);
return 1;
}
}
error:
mutex_unlock(&sl->master->mutex);
return -EIO;
}
#define NB_SYSFS_BIN_FILES 6
static struct bin_attribute w1_f29_sysfs_bin_files[NB_SYSFS_BIN_FILES] = {
{
.attr = {
.name = "state",
.mode = S_IRUGO,
},
.size = 1,
.read = w1_f29_read_state,
},
{
.attr = {
.name = "output",
.mode = S_IRUGO | S_IWUSR | S_IWGRP,
},
.size = 1,
.read = w1_f29_read_output,
.write = w1_f29_write_output,
},
{
.attr = {
.name = "activity",
.mode = S_IRUGO,
},
.size = 1,
.read = w1_f29_read_activity,
.write = w1_f29_write_activity,
},
{
.attr = {
.name = "cond_search_mask",
.mode = S_IRUGO,
},
.size = 1,
.read = w1_f29_read_cond_search_mask,
.write = 0,
},
{
.attr = {
.name = "cond_search_polarity",
.mode = S_IRUGO,
},
.size = 1,
.read = w1_f29_read_cond_search_polarity,
.write = 0,
},
{
.attr = {
.name = "status_control",
.mode = S_IRUGO | S_IWUSR | S_IWGRP,
},
.size = 1,
.read = w1_f29_read_status_control,
.write = w1_f29_write_status_control,
}
};
static int w1_f29_add_slave(struct w1_slave *sl)
{
int err = 0;
int i;
for (i = 0; i < NB_SYSFS_BIN_FILES && !err; ++i)
err = sysfs_create_bin_file(
&sl->dev.kobj,
&(w1_f29_sysfs_bin_files[i]));
if (err)
while (--i >= 0)
sysfs_remove_bin_file(&sl->dev.kobj,
&(w1_f29_sysfs_bin_files[i]));
return err;
}
static void w1_f29_remove_slave(struct w1_slave *sl)
{
int i;
for (i = NB_SYSFS_BIN_FILES - 1; i >= 0; --i)
sysfs_remove_bin_file(&sl->dev.kobj,
&(w1_f29_sysfs_bin_files[i]));
}
static struct w1_family_ops w1_f29_fops = {
.add_slave = w1_f29_add_slave,
.remove_slave = w1_f29_remove_slave,
};
static struct w1_family w1_family_29 = {
.fid = W1_FAMILY_DS2408,
.fops = &w1_f29_fops,
};
static int __init w1_f29_init(void)
{
return w1_register_family(&w1_family_29);
}
static void __exit w1_f29_exit(void)
{
w1_unregister_family(&w1_family_29);
}
module_init(w1_f29_init);
module_exit(w1_f29_exit);
| gpl-2.0 |
brymaster5000/m7-443 | drivers/w1/slaves/w1_ds2408.c | 5455 | 9764 | /*
* w1_ds2408.c - w1 family 29 (DS2408) driver
*
* Copyright (c) 2010 Jean-Francois Dagenais <dagenaisj@sonatest.com>
*
* This source code is licensed under the GNU General Public License,
* Version 2. See the file COPYING for more details.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/device.h>
#include <linux/types.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include "../w1.h"
#include "../w1_int.h"
#include "../w1_family.h"
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Jean-Francois Dagenais <dagenaisj@sonatest.com>");
MODULE_DESCRIPTION("w1 family 29 driver for DS2408 8 Pin IO");
#define W1_F29_RETRIES 3
#define W1_F29_REG_LOGIG_STATE 0x88 /* R */
#define W1_F29_REG_OUTPUT_LATCH_STATE 0x89 /* R */
#define W1_F29_REG_ACTIVITY_LATCH_STATE 0x8A /* R */
#define W1_F29_REG_COND_SEARCH_SELECT_MASK 0x8B /* RW */
#define W1_F29_REG_COND_SEARCH_POL_SELECT 0x8C /* RW */
#define W1_F29_REG_CONTROL_AND_STATUS 0x8D /* RW */
#define W1_F29_FUNC_READ_PIO_REGS 0xF0
#define W1_F29_FUNC_CHANN_ACCESS_READ 0xF5
#define W1_F29_FUNC_CHANN_ACCESS_WRITE 0x5A
/* also used to write the control/status reg (0x8D): */
#define W1_F29_FUNC_WRITE_COND_SEARCH_REG 0xCC
#define W1_F29_FUNC_RESET_ACTIVITY_LATCHES 0xC3
#define W1_F29_SUCCESS_CONFIRM_BYTE 0xAA
static int _read_reg(struct w1_slave *sl, u8 address, unsigned char* buf)
{
u8 wrbuf[3];
dev_dbg(&sl->dev,
"Reading with slave: %p, reg addr: %0#4x, buff addr: %p",
sl, (unsigned int)address, buf);
if (!buf)
return -EINVAL;
mutex_lock(&sl->master->mutex);
dev_dbg(&sl->dev, "mutex locked");
if (w1_reset_select_slave(sl)) {
mutex_unlock(&sl->master->mutex);
return -EIO;
}
wrbuf[0] = W1_F29_FUNC_READ_PIO_REGS;
wrbuf[1] = address;
wrbuf[2] = 0;
w1_write_block(sl->master, wrbuf, 3);
*buf = w1_read_8(sl->master);
mutex_unlock(&sl->master->mutex);
dev_dbg(&sl->dev, "mutex unlocked");
return 1;
}
static ssize_t w1_f29_read_state(
struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t off, size_t count)
{
dev_dbg(&kobj_to_w1_slave(kobj)->dev,
"Reading %s kobj: %p, off: %0#10x, count: %zu, buff addr: %p",
bin_attr->attr.name, kobj, (unsigned int)off, count, buf);
if (count != 1 || off != 0)
return -EFAULT;
return _read_reg(kobj_to_w1_slave(kobj), W1_F29_REG_LOGIG_STATE, buf);
}
static ssize_t w1_f29_read_output(
struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t off, size_t count)
{
dev_dbg(&kobj_to_w1_slave(kobj)->dev,
"Reading %s kobj: %p, off: %0#10x, count: %zu, buff addr: %p",
bin_attr->attr.name, kobj, (unsigned int)off, count, buf);
if (count != 1 || off != 0)
return -EFAULT;
return _read_reg(kobj_to_w1_slave(kobj),
W1_F29_REG_OUTPUT_LATCH_STATE, buf);
}
static ssize_t w1_f29_read_activity(
struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t off, size_t count)
{
dev_dbg(&kobj_to_w1_slave(kobj)->dev,
"Reading %s kobj: %p, off: %0#10x, count: %zu, buff addr: %p",
bin_attr->attr.name, kobj, (unsigned int)off, count, buf);
if (count != 1 || off != 0)
return -EFAULT;
return _read_reg(kobj_to_w1_slave(kobj),
W1_F29_REG_ACTIVITY_LATCH_STATE, buf);
}
static ssize_t w1_f29_read_cond_search_mask(
struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t off, size_t count)
{
dev_dbg(&kobj_to_w1_slave(kobj)->dev,
"Reading %s kobj: %p, off: %0#10x, count: %zu, buff addr: %p",
bin_attr->attr.name, kobj, (unsigned int)off, count, buf);
if (count != 1 || off != 0)
return -EFAULT;
return _read_reg(kobj_to_w1_slave(kobj),
W1_F29_REG_COND_SEARCH_SELECT_MASK, buf);
}
static ssize_t w1_f29_read_cond_search_polarity(
struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t off, size_t count)
{
if (count != 1 || off != 0)
return -EFAULT;
return _read_reg(kobj_to_w1_slave(kobj),
W1_F29_REG_COND_SEARCH_POL_SELECT, buf);
}
static ssize_t w1_f29_read_status_control(
struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t off, size_t count)
{
if (count != 1 || off != 0)
return -EFAULT;
return _read_reg(kobj_to_w1_slave(kobj),
W1_F29_REG_CONTROL_AND_STATUS, buf);
}
static ssize_t w1_f29_write_output(
struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t off, size_t count)
{
struct w1_slave *sl = kobj_to_w1_slave(kobj);
u8 w1_buf[3];
u8 readBack;
unsigned int retries = W1_F29_RETRIES;
if (count != 1 || off != 0)
return -EFAULT;
dev_dbg(&sl->dev, "locking mutex for write_output");
mutex_lock(&sl->master->mutex);
dev_dbg(&sl->dev, "mutex locked");
if (w1_reset_select_slave(sl))
goto error;
while (retries--) {
w1_buf[0] = W1_F29_FUNC_CHANN_ACCESS_WRITE;
w1_buf[1] = *buf;
w1_buf[2] = ~(*buf);
w1_write_block(sl->master, w1_buf, 3);
readBack = w1_read_8(sl->master);
/* here the master could read another byte which
would be the PIO reg (the actual pin logic state)
since in this driver we don't know which pins are
in and outs, there's no value to read the state and
compare. with (*buf) so end this command abruptly: */
if (w1_reset_resume_command(sl->master))
goto error;
if (readBack != 0xAA) {
/* try again, the slave is ready for a command */
continue;
}
/* go read back the output latches */
/* (the direct effect of the write above) */
w1_buf[0] = W1_F29_FUNC_READ_PIO_REGS;
w1_buf[1] = W1_F29_REG_OUTPUT_LATCH_STATE;
w1_buf[2] = 0;
w1_write_block(sl->master, w1_buf, 3);
/* read the result of the READ_PIO_REGS command */
if (w1_read_8(sl->master) == *buf) {
/* success! */
mutex_unlock(&sl->master->mutex);
dev_dbg(&sl->dev,
"mutex unlocked, retries:%d", retries);
return 1;
}
}
error:
mutex_unlock(&sl->master->mutex);
dev_dbg(&sl->dev, "mutex unlocked in error, retries:%d", retries);
return -EIO;
}
/**
* Writing to the activity file resets the activity latches.
*/
static ssize_t w1_f29_write_activity(
struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t off, size_t count)
{
struct w1_slave *sl = kobj_to_w1_slave(kobj);
unsigned int retries = W1_F29_RETRIES;
if (count != 1 || off != 0)
return -EFAULT;
mutex_lock(&sl->master->mutex);
if (w1_reset_select_slave(sl))
goto error;
while (retries--) {
w1_write_8(sl->master, W1_F29_FUNC_RESET_ACTIVITY_LATCHES);
if (w1_read_8(sl->master) == W1_F29_SUCCESS_CONFIRM_BYTE) {
mutex_unlock(&sl->master->mutex);
return 1;
}
if (w1_reset_resume_command(sl->master))
goto error;
}
error:
mutex_unlock(&sl->master->mutex);
return -EIO;
}
static ssize_t w1_f29_write_status_control(
struct file *filp,
struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf,
loff_t off,
size_t count)
{
struct w1_slave *sl = kobj_to_w1_slave(kobj);
u8 w1_buf[4];
unsigned int retries = W1_F29_RETRIES;
if (count != 1 || off != 0)
return -EFAULT;
mutex_lock(&sl->master->mutex);
if (w1_reset_select_slave(sl))
goto error;
while (retries--) {
w1_buf[0] = W1_F29_FUNC_WRITE_COND_SEARCH_REG;
w1_buf[1] = W1_F29_REG_CONTROL_AND_STATUS;
w1_buf[2] = 0;
w1_buf[3] = *buf;
w1_write_block(sl->master, w1_buf, 4);
if (w1_reset_resume_command(sl->master))
goto error;
w1_buf[0] = W1_F29_FUNC_READ_PIO_REGS;
w1_buf[1] = W1_F29_REG_CONTROL_AND_STATUS;
w1_buf[2] = 0;
w1_write_block(sl->master, w1_buf, 3);
if (w1_read_8(sl->master) == *buf) {
/* success! */
mutex_unlock(&sl->master->mutex);
return 1;
}
}
error:
mutex_unlock(&sl->master->mutex);
return -EIO;
}
#define NB_SYSFS_BIN_FILES 6
static struct bin_attribute w1_f29_sysfs_bin_files[NB_SYSFS_BIN_FILES] = {
{
.attr = {
.name = "state",
.mode = S_IRUGO,
},
.size = 1,
.read = w1_f29_read_state,
},
{
.attr = {
.name = "output",
.mode = S_IRUGO | S_IWUSR | S_IWGRP,
},
.size = 1,
.read = w1_f29_read_output,
.write = w1_f29_write_output,
},
{
.attr = {
.name = "activity",
.mode = S_IRUGO,
},
.size = 1,
.read = w1_f29_read_activity,
.write = w1_f29_write_activity,
},
{
.attr = {
.name = "cond_search_mask",
.mode = S_IRUGO,
},
.size = 1,
.read = w1_f29_read_cond_search_mask,
.write = 0,
},
{
.attr = {
.name = "cond_search_polarity",
.mode = S_IRUGO,
},
.size = 1,
.read = w1_f29_read_cond_search_polarity,
.write = 0,
},
{
.attr = {
.name = "status_control",
.mode = S_IRUGO | S_IWUSR | S_IWGRP,
},
.size = 1,
.read = w1_f29_read_status_control,
.write = w1_f29_write_status_control,
}
};
static int w1_f29_add_slave(struct w1_slave *sl)
{
int err = 0;
int i;
for (i = 0; i < NB_SYSFS_BIN_FILES && !err; ++i)
err = sysfs_create_bin_file(
&sl->dev.kobj,
&(w1_f29_sysfs_bin_files[i]));
if (err)
while (--i >= 0)
sysfs_remove_bin_file(&sl->dev.kobj,
&(w1_f29_sysfs_bin_files[i]));
return err;
}
static void w1_f29_remove_slave(struct w1_slave *sl)
{
int i;
for (i = NB_SYSFS_BIN_FILES - 1; i >= 0; --i)
sysfs_remove_bin_file(&sl->dev.kobj,
&(w1_f29_sysfs_bin_files[i]));
}
static struct w1_family_ops w1_f29_fops = {
.add_slave = w1_f29_add_slave,
.remove_slave = w1_f29_remove_slave,
};
static struct w1_family w1_family_29 = {
.fid = W1_FAMILY_DS2408,
.fops = &w1_f29_fops,
};
static int __init w1_f29_init(void)
{
return w1_register_family(&w1_family_29);
}
static void __exit w1_f29_exit(void)
{
w1_unregister_family(&w1_family_29);
}
module_init(w1_f29_init);
module_exit(w1_f29_exit);
| gpl-2.0 |
Silviumik/Silviu_Kernel_I9195_LTE_KitKat | drivers/media/dvb/ngene/ngene-core.c | 5455 | 44635 | /*
* ngene.c: nGene PCIe bridge driver
*
* Copyright (C) 2005-2007 Micronas
*
* Copyright (C) 2008-2009 Ralph Metzler <rjkm@metzlerbros.de>
* Modifications for new nGene firmware,
* support for EEPROM-copying,
* support for new dual DVB-S2 card prototype
*
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 only, as published by the Free Software Foundation.
*
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA
* Or, point your browser to http://www.gnu.org/copyleft/gpl.html
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/poll.h>
#include <linux/io.h>
#include <asm/div64.h>
#include <linux/pci.h>
#include <linux/timer.h>
#include <linux/byteorder/generic.h>
#include <linux/firmware.h>
#include <linux/vmalloc.h>
#include "ngene.h"
static int one_adapter;
module_param(one_adapter, int, 0444);
MODULE_PARM_DESC(one_adapter, "Use only one adapter.");
static int shutdown_workaround;
module_param(shutdown_workaround, int, 0644);
MODULE_PARM_DESC(shutdown_workaround, "Activate workaround for shutdown problem with some chipsets.");
static int debug;
module_param(debug, int, 0444);
MODULE_PARM_DESC(debug, "Print debugging information.");
DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr);
#define dprintk if (debug) printk
#define ngwriteb(dat, adr) writeb((dat), (char *)(dev->iomem + (adr)))
#define ngwritel(dat, adr) writel((dat), (char *)(dev->iomem + (adr)))
#define ngwriteb(dat, adr) writeb((dat), (char *)(dev->iomem + (adr)))
#define ngreadl(adr) readl(dev->iomem + (adr))
#define ngreadb(adr) readb(dev->iomem + (adr))
#define ngcpyto(adr, src, count) memcpy_toio((char *) \
(dev->iomem + (adr)), (src), (count))
#define ngcpyfrom(dst, adr, count) memcpy_fromio((dst), (char *) \
(dev->iomem + (adr)), (count))
/****************************************************************************/
/* nGene interrupt handler **************************************************/
/****************************************************************************/
static void event_tasklet(unsigned long data)
{
struct ngene *dev = (struct ngene *)data;
while (dev->EventQueueReadIndex != dev->EventQueueWriteIndex) {
struct EVENT_BUFFER Event =
dev->EventQueue[dev->EventQueueReadIndex];
dev->EventQueueReadIndex =
(dev->EventQueueReadIndex + 1) & (EVENT_QUEUE_SIZE - 1);
if ((Event.UARTStatus & 0x01) && (dev->TxEventNotify))
dev->TxEventNotify(dev, Event.TimeStamp);
if ((Event.UARTStatus & 0x02) && (dev->RxEventNotify))
dev->RxEventNotify(dev, Event.TimeStamp,
Event.RXCharacter);
}
}
static void demux_tasklet(unsigned long data)
{
struct ngene_channel *chan = (struct ngene_channel *)data;
struct SBufferHeader *Cur = chan->nextBuffer;
spin_lock_irq(&chan->state_lock);
while (Cur->ngeneBuffer.SR.Flags & 0x80) {
if (chan->mode & NGENE_IO_TSOUT) {
u32 Flags = chan->DataFormatFlags;
if (Cur->ngeneBuffer.SR.Flags & 0x20)
Flags |= BEF_OVERFLOW;
if (chan->pBufferExchange) {
if (!chan->pBufferExchange(chan,
Cur->Buffer1,
chan->Capture1Length,
Cur->ngeneBuffer.SR.
Clock, Flags)) {
/*
We didn't get data
Clear in service flag to make sure we
get called on next interrupt again.
leave fill/empty (0x80) flag alone
to avoid hardware running out of
buffers during startup, we hold only
in run state ( the source may be late
delivering data )
*/
if (chan->HWState == HWSTATE_RUN) {
Cur->ngeneBuffer.SR.Flags &=
~0x40;
break;
/* Stop processing stream */
}
} else {
/* We got a valid buffer,
so switch to run state */
chan->HWState = HWSTATE_RUN;
}
} else {
printk(KERN_ERR DEVICE_NAME ": OOPS\n");
if (chan->HWState == HWSTATE_RUN) {
Cur->ngeneBuffer.SR.Flags &= ~0x40;
break; /* Stop processing stream */
}
}
if (chan->AudioDTOUpdated) {
printk(KERN_INFO DEVICE_NAME
": Update AudioDTO = %d\n",
chan->AudioDTOValue);
Cur->ngeneBuffer.SR.DTOUpdate =
chan->AudioDTOValue;
chan->AudioDTOUpdated = 0;
}
} else {
if (chan->HWState == HWSTATE_RUN) {
u32 Flags = chan->DataFormatFlags;
IBufferExchange *exch1 = chan->pBufferExchange;
IBufferExchange *exch2 = chan->pBufferExchange2;
if (Cur->ngeneBuffer.SR.Flags & 0x01)
Flags |= BEF_EVEN_FIELD;
if (Cur->ngeneBuffer.SR.Flags & 0x20)
Flags |= BEF_OVERFLOW;
spin_unlock_irq(&chan->state_lock);
if (exch1)
exch1(chan, Cur->Buffer1,
chan->Capture1Length,
Cur->ngeneBuffer.SR.Clock,
Flags);
if (exch2)
exch2(chan, Cur->Buffer2,
chan->Capture2Length,
Cur->ngeneBuffer.SR.Clock,
Flags);
spin_lock_irq(&chan->state_lock);
} else if (chan->HWState != HWSTATE_STOP)
chan->HWState = HWSTATE_RUN;
}
Cur->ngeneBuffer.SR.Flags = 0x00;
Cur = Cur->Next;
}
chan->nextBuffer = Cur;
spin_unlock_irq(&chan->state_lock);
}
static irqreturn_t irq_handler(int irq, void *dev_id)
{
struct ngene *dev = (struct ngene *)dev_id;
u32 icounts = 0;
irqreturn_t rc = IRQ_NONE;
u32 i = MAX_STREAM;
u8 *tmpCmdDoneByte;
if (dev->BootFirmware) {
icounts = ngreadl(NGENE_INT_COUNTS);
if (icounts != dev->icounts) {
ngwritel(0, FORCE_NMI);
dev->cmd_done = 1;
wake_up(&dev->cmd_wq);
dev->icounts = icounts;
rc = IRQ_HANDLED;
}
return rc;
}
ngwritel(0, FORCE_NMI);
spin_lock(&dev->cmd_lock);
tmpCmdDoneByte = dev->CmdDoneByte;
if (tmpCmdDoneByte &&
(*tmpCmdDoneByte ||
(dev->ngenetohost[0] == 1 && dev->ngenetohost[1] != 0))) {
dev->CmdDoneByte = NULL;
dev->cmd_done = 1;
wake_up(&dev->cmd_wq);
rc = IRQ_HANDLED;
}
spin_unlock(&dev->cmd_lock);
if (dev->EventBuffer->EventStatus & 0x80) {
u8 nextWriteIndex =
(dev->EventQueueWriteIndex + 1) &
(EVENT_QUEUE_SIZE - 1);
if (nextWriteIndex != dev->EventQueueReadIndex) {
dev->EventQueue[dev->EventQueueWriteIndex] =
*(dev->EventBuffer);
dev->EventQueueWriteIndex = nextWriteIndex;
} else {
printk(KERN_ERR DEVICE_NAME ": event overflow\n");
dev->EventQueueOverflowCount += 1;
dev->EventQueueOverflowFlag = 1;
}
dev->EventBuffer->EventStatus &= ~0x80;
tasklet_schedule(&dev->event_tasklet);
rc = IRQ_HANDLED;
}
while (i > 0) {
i--;
spin_lock(&dev->channel[i].state_lock);
/* if (dev->channel[i].State>=KSSTATE_RUN) { */
if (dev->channel[i].nextBuffer) {
if ((dev->channel[i].nextBuffer->
ngeneBuffer.SR.Flags & 0xC0) == 0x80) {
dev->channel[i].nextBuffer->
ngeneBuffer.SR.Flags |= 0x40;
tasklet_schedule(
&dev->channel[i].demux_tasklet);
rc = IRQ_HANDLED;
}
}
spin_unlock(&dev->channel[i].state_lock);
}
/* Request might have been processed by a previous call. */
return IRQ_HANDLED;
}
/****************************************************************************/
/* nGene command interface **************************************************/
/****************************************************************************/
static void dump_command_io(struct ngene *dev)
{
u8 buf[8], *b;
ngcpyfrom(buf, HOST_TO_NGENE, 8);
printk(KERN_ERR "host_to_ngene (%04x): %02x %02x %02x %02x %02x %02x %02x %02x\n",
HOST_TO_NGENE, buf[0], buf[1], buf[2], buf[3],
buf[4], buf[5], buf[6], buf[7]);
ngcpyfrom(buf, NGENE_TO_HOST, 8);
printk(KERN_ERR "ngene_to_host (%04x): %02x %02x %02x %02x %02x %02x %02x %02x\n",
NGENE_TO_HOST, buf[0], buf[1], buf[2], buf[3],
buf[4], buf[5], buf[6], buf[7]);
b = dev->hosttongene;
printk(KERN_ERR "dev->hosttongene (%p): %02x %02x %02x %02x %02x %02x %02x %02x\n",
b, b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]);
b = dev->ngenetohost;
printk(KERN_ERR "dev->ngenetohost (%p): %02x %02x %02x %02x %02x %02x %02x %02x\n",
b, b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]);
}
static int ngene_command_mutex(struct ngene *dev, struct ngene_command *com)
{
int ret;
u8 *tmpCmdDoneByte;
dev->cmd_done = 0;
if (com->cmd.hdr.Opcode == CMD_FWLOAD_PREPARE) {
dev->BootFirmware = 1;
dev->icounts = ngreadl(NGENE_INT_COUNTS);
ngwritel(0, NGENE_COMMAND);
ngwritel(0, NGENE_COMMAND_HI);
ngwritel(0, NGENE_STATUS);
ngwritel(0, NGENE_STATUS_HI);
ngwritel(0, NGENE_EVENT);
ngwritel(0, NGENE_EVENT_HI);
} else if (com->cmd.hdr.Opcode == CMD_FWLOAD_FINISH) {
u64 fwio = dev->PAFWInterfaceBuffer;
ngwritel(fwio & 0xffffffff, NGENE_COMMAND);
ngwritel(fwio >> 32, NGENE_COMMAND_HI);
ngwritel((fwio + 256) & 0xffffffff, NGENE_STATUS);
ngwritel((fwio + 256) >> 32, NGENE_STATUS_HI);
ngwritel((fwio + 512) & 0xffffffff, NGENE_EVENT);
ngwritel((fwio + 512) >> 32, NGENE_EVENT_HI);
}
memcpy(dev->FWInterfaceBuffer, com->cmd.raw8, com->in_len + 2);
if (dev->BootFirmware)
ngcpyto(HOST_TO_NGENE, com->cmd.raw8, com->in_len + 2);
spin_lock_irq(&dev->cmd_lock);
tmpCmdDoneByte = dev->ngenetohost + com->out_len;
if (!com->out_len)
tmpCmdDoneByte++;
*tmpCmdDoneByte = 0;
dev->ngenetohost[0] = 0;
dev->ngenetohost[1] = 0;
dev->CmdDoneByte = tmpCmdDoneByte;
spin_unlock_irq(&dev->cmd_lock);
/* Notify 8051. */
ngwritel(1, FORCE_INT);
ret = wait_event_timeout(dev->cmd_wq, dev->cmd_done == 1, 2 * HZ);
if (!ret) {
/*ngwritel(0, FORCE_NMI);*/
printk(KERN_ERR DEVICE_NAME
": Command timeout cmd=%02x prev=%02x\n",
com->cmd.hdr.Opcode, dev->prev_cmd);
dump_command_io(dev);
return -1;
}
if (com->cmd.hdr.Opcode == CMD_FWLOAD_FINISH)
dev->BootFirmware = 0;
dev->prev_cmd = com->cmd.hdr.Opcode;
if (!com->out_len)
return 0;
memcpy(com->cmd.raw8, dev->ngenetohost, com->out_len);
return 0;
}
int ngene_command(struct ngene *dev, struct ngene_command *com)
{
int result;
down(&dev->cmd_mutex);
result = ngene_command_mutex(dev, com);
up(&dev->cmd_mutex);
return result;
}
static int ngene_command_load_firmware(struct ngene *dev,
u8 *ngene_fw, u32 size)
{
#define FIRSTCHUNK (1024)
u32 cleft;
struct ngene_command com;
com.cmd.hdr.Opcode = CMD_FWLOAD_PREPARE;
com.cmd.hdr.Length = 0;
com.in_len = 0;
com.out_len = 0;
ngene_command(dev, &com);
cleft = (size + 3) & ~3;
if (cleft > FIRSTCHUNK) {
ngcpyto(PROGRAM_SRAM + FIRSTCHUNK, ngene_fw + FIRSTCHUNK,
cleft - FIRSTCHUNK);
cleft = FIRSTCHUNK;
}
ngcpyto(DATA_FIFO_AREA, ngene_fw, cleft);
memset(&com, 0, sizeof(struct ngene_command));
com.cmd.hdr.Opcode = CMD_FWLOAD_FINISH;
com.cmd.hdr.Length = 4;
com.cmd.FWLoadFinish.Address = DATA_FIFO_AREA;
com.cmd.FWLoadFinish.Length = (unsigned short)cleft;
com.in_len = 4;
com.out_len = 0;
return ngene_command(dev, &com);
}
static int ngene_command_config_buf(struct ngene *dev, u8 config)
{
struct ngene_command com;
com.cmd.hdr.Opcode = CMD_CONFIGURE_BUFFER;
com.cmd.hdr.Length = 1;
com.cmd.ConfigureBuffers.config = config;
com.in_len = 1;
com.out_len = 0;
if (ngene_command(dev, &com) < 0)
return -EIO;
return 0;
}
static int ngene_command_config_free_buf(struct ngene *dev, u8 *config)
{
struct ngene_command com;
com.cmd.hdr.Opcode = CMD_CONFIGURE_FREE_BUFFER;
com.cmd.hdr.Length = 6;
memcpy(&com.cmd.ConfigureBuffers.config, config, 6);
com.in_len = 6;
com.out_len = 0;
if (ngene_command(dev, &com) < 0)
return -EIO;
return 0;
}
int ngene_command_gpio_set(struct ngene *dev, u8 select, u8 level)
{
struct ngene_command com;
com.cmd.hdr.Opcode = CMD_SET_GPIO_PIN;
com.cmd.hdr.Length = 1;
com.cmd.SetGpioPin.select = select | (level << 7);
com.in_len = 1;
com.out_len = 0;
return ngene_command(dev, &com);
}
/*
02000640 is sample on rising edge.
02000740 is sample on falling edge.
02000040 is ignore "valid" signal
0: FD_CTL1 Bit 7,6 must be 0,1
7 disable(fw controlled)
6 0-AUX,1-TS
5 0-par,1-ser
4 0-lsb/1-msb
3,2 reserved
1,0 0-no sync, 1-use ext. start, 2-use 0x47, 3-both
1: FD_CTL2 has 3-valid must be hi, 2-use valid, 1-edge
2: FD_STA is read-only. 0-sync
3: FD_INSYNC is number of 47s to trigger "in sync".
4: FD_OUTSYNC is number of 47s to trigger "out of sync".
5: FD_MAXBYTE1 is low-order of bytes per packet.
6: FD_MAXBYTE2 is high-order of bytes per packet.
7: Top byte is unused.
*/
/****************************************************************************/
static u8 TSFeatureDecoderSetup[8 * 5] = {
0x42, 0x00, 0x00, 0x02, 0x02, 0xbc, 0x00, 0x00,
0x40, 0x06, 0x00, 0x02, 0x02, 0xbc, 0x00, 0x00, /* DRXH */
0x71, 0x07, 0x00, 0x02, 0x02, 0xbc, 0x00, 0x00, /* DRXHser */
0x72, 0x00, 0x00, 0x02, 0x02, 0xbc, 0x00, 0x00, /* S2ser */
0x40, 0x07, 0x00, 0x02, 0x02, 0xbc, 0x00, 0x00, /* LGDT3303 */
};
/* Set NGENE I2S Config to 16 bit packed */
static u8 I2SConfiguration[] = {
0x00, 0x10, 0x00, 0x00,
0x80, 0x10, 0x00, 0x00,
};
static u8 SPDIFConfiguration[10] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
/* Set NGENE I2S Config to transport stream compatible mode */
static u8 TS_I2SConfiguration[4] = { 0x3E, 0x18, 0x00, 0x00 };
static u8 TS_I2SOutConfiguration[4] = { 0x80, 0x04, 0x00, 0x00 };
static u8 ITUDecoderSetup[4][16] = {
{0x1c, 0x13, 0x01, 0x68, 0x3d, 0x90, 0x14, 0x20, /* SDTV */
0x00, 0x00, 0x01, 0xb0, 0x9c, 0x00, 0x00, 0x00},
{0x9c, 0x03, 0x23, 0xC0, 0x60, 0x0E, 0x13, 0x00,
0x00, 0x00, 0x00, 0x01, 0xB0, 0x00, 0x00, 0x00},
{0x9f, 0x00, 0x23, 0xC0, 0x60, 0x0F, 0x13, 0x00, /* HDTV 1080i50 */
0x00, 0x00, 0x00, 0x01, 0xB0, 0x00, 0x00, 0x00},
{0x9c, 0x01, 0x23, 0xC0, 0x60, 0x0E, 0x13, 0x00, /* HDTV 1080i60 */
0x00, 0x00, 0x00, 0x01, 0xB0, 0x00, 0x00, 0x00},
};
/*
* 50 48 60 gleich
* 27p50 9f 00 22 80 42 69 18 ...
* 27p60 93 00 22 80 82 69 1c ...
*/
/* Maxbyte to 1144 (for raw data) */
static u8 ITUFeatureDecoderSetup[8] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x04, 0x00
};
void FillTSBuffer(void *Buffer, int Length, u32 Flags)
{
u32 *ptr = Buffer;
memset(Buffer, TS_FILLER, Length);
while (Length > 0) {
if (Flags & DF_SWAP32)
*ptr = 0x471FFF10;
else
*ptr = 0x10FF1F47;
ptr += (188 / 4);
Length -= 188;
}
}
static void flush_buffers(struct ngene_channel *chan)
{
u8 val;
do {
msleep(1);
spin_lock_irq(&chan->state_lock);
val = chan->nextBuffer->ngeneBuffer.SR.Flags & 0x80;
spin_unlock_irq(&chan->state_lock);
} while (val);
}
static void clear_buffers(struct ngene_channel *chan)
{
struct SBufferHeader *Cur = chan->nextBuffer;
do {
memset(&Cur->ngeneBuffer.SR, 0, sizeof(Cur->ngeneBuffer.SR));
if (chan->mode & NGENE_IO_TSOUT)
FillTSBuffer(Cur->Buffer1,
chan->Capture1Length,
chan->DataFormatFlags);
Cur = Cur->Next;
} while (Cur != chan->nextBuffer);
if (chan->mode & NGENE_IO_TSOUT) {
chan->nextBuffer->ngeneBuffer.SR.DTOUpdate =
chan->AudioDTOValue;
chan->AudioDTOUpdated = 0;
Cur = chan->TSIdleBuffer.Head;
do {
memset(&Cur->ngeneBuffer.SR, 0,
sizeof(Cur->ngeneBuffer.SR));
FillTSBuffer(Cur->Buffer1,
chan->Capture1Length,
chan->DataFormatFlags);
Cur = Cur->Next;
} while (Cur != chan->TSIdleBuffer.Head);
}
}
static int ngene_command_stream_control(struct ngene *dev, u8 stream,
u8 control, u8 mode, u8 flags)
{
struct ngene_channel *chan = &dev->channel[stream];
struct ngene_command com;
u16 BsUVI = ((stream & 1) ? 0x9400 : 0x9300);
u16 BsSDI = ((stream & 1) ? 0x9600 : 0x9500);
u16 BsSPI = ((stream & 1) ? 0x9800 : 0x9700);
u16 BsSDO = 0x9B00;
down(&dev->stream_mutex);
memset(&com, 0, sizeof(com));
com.cmd.hdr.Opcode = CMD_CONTROL;
com.cmd.hdr.Length = sizeof(struct FW_STREAM_CONTROL) - 2;
com.cmd.StreamControl.Stream = stream | (control ? 8 : 0);
if (chan->mode & NGENE_IO_TSOUT)
com.cmd.StreamControl.Stream |= 0x07;
com.cmd.StreamControl.Control = control |
(flags & SFLAG_ORDER_LUMA_CHROMA);
com.cmd.StreamControl.Mode = mode;
com.in_len = sizeof(struct FW_STREAM_CONTROL);
com.out_len = 0;
dprintk(KERN_INFO DEVICE_NAME
": Stream=%02x, Control=%02x, Mode=%02x\n",
com.cmd.StreamControl.Stream, com.cmd.StreamControl.Control,
com.cmd.StreamControl.Mode);
chan->Mode = mode;
if (!(control & 0x80)) {
spin_lock_irq(&chan->state_lock);
if (chan->State == KSSTATE_RUN) {
chan->State = KSSTATE_ACQUIRE;
chan->HWState = HWSTATE_STOP;
spin_unlock_irq(&chan->state_lock);
if (ngene_command(dev, &com) < 0) {
up(&dev->stream_mutex);
return -1;
}
/* clear_buffers(chan); */
flush_buffers(chan);
up(&dev->stream_mutex);
return 0;
}
spin_unlock_irq(&chan->state_lock);
up(&dev->stream_mutex);
return 0;
}
if (mode & SMODE_AUDIO_CAPTURE) {
com.cmd.StreamControl.CaptureBlockCount =
chan->Capture1Length / AUDIO_BLOCK_SIZE;
com.cmd.StreamControl.Buffer_Address = chan->RingBuffer.PAHead;
} else if (mode & SMODE_TRANSPORT_STREAM) {
com.cmd.StreamControl.CaptureBlockCount =
chan->Capture1Length / TS_BLOCK_SIZE;
com.cmd.StreamControl.MaxLinesPerField =
chan->Capture1Length / TS_BLOCK_SIZE;
com.cmd.StreamControl.Buffer_Address =
chan->TSRingBuffer.PAHead;
if (chan->mode & NGENE_IO_TSOUT) {
com.cmd.StreamControl.BytesPerVBILine =
chan->Capture1Length / TS_BLOCK_SIZE;
com.cmd.StreamControl.Stream |= 0x07;
}
} else {
com.cmd.StreamControl.BytesPerVideoLine = chan->nBytesPerLine;
com.cmd.StreamControl.MaxLinesPerField = chan->nLines;
com.cmd.StreamControl.MinLinesPerField = 100;
com.cmd.StreamControl.Buffer_Address = chan->RingBuffer.PAHead;
if (mode & SMODE_VBI_CAPTURE) {
com.cmd.StreamControl.MaxVBILinesPerField =
chan->nVBILines;
com.cmd.StreamControl.MinVBILinesPerField = 0;
com.cmd.StreamControl.BytesPerVBILine =
chan->nBytesPerVBILine;
}
if (flags & SFLAG_COLORBAR)
com.cmd.StreamControl.Stream |= 0x04;
}
spin_lock_irq(&chan->state_lock);
if (mode & SMODE_AUDIO_CAPTURE) {
chan->nextBuffer = chan->RingBuffer.Head;
if (mode & SMODE_AUDIO_SPDIF) {
com.cmd.StreamControl.SetupDataLen =
sizeof(SPDIFConfiguration);
com.cmd.StreamControl.SetupDataAddr = BsSPI;
memcpy(com.cmd.StreamControl.SetupData,
SPDIFConfiguration, sizeof(SPDIFConfiguration));
} else {
com.cmd.StreamControl.SetupDataLen = 4;
com.cmd.StreamControl.SetupDataAddr = BsSDI;
memcpy(com.cmd.StreamControl.SetupData,
I2SConfiguration +
4 * dev->card_info->i2s[stream], 4);
}
} else if (mode & SMODE_TRANSPORT_STREAM) {
chan->nextBuffer = chan->TSRingBuffer.Head;
if (stream >= STREAM_AUDIOIN1) {
if (chan->mode & NGENE_IO_TSOUT) {
com.cmd.StreamControl.SetupDataLen =
sizeof(TS_I2SOutConfiguration);
com.cmd.StreamControl.SetupDataAddr = BsSDO;
memcpy(com.cmd.StreamControl.SetupData,
TS_I2SOutConfiguration,
sizeof(TS_I2SOutConfiguration));
} else {
com.cmd.StreamControl.SetupDataLen =
sizeof(TS_I2SConfiguration);
com.cmd.StreamControl.SetupDataAddr = BsSDI;
memcpy(com.cmd.StreamControl.SetupData,
TS_I2SConfiguration,
sizeof(TS_I2SConfiguration));
}
} else {
com.cmd.StreamControl.SetupDataLen = 8;
com.cmd.StreamControl.SetupDataAddr = BsUVI + 0x10;
memcpy(com.cmd.StreamControl.SetupData,
TSFeatureDecoderSetup +
8 * dev->card_info->tsf[stream], 8);
}
} else {
chan->nextBuffer = chan->RingBuffer.Head;
com.cmd.StreamControl.SetupDataLen =
16 + sizeof(ITUFeatureDecoderSetup);
com.cmd.StreamControl.SetupDataAddr = BsUVI;
memcpy(com.cmd.StreamControl.SetupData,
ITUDecoderSetup[chan->itumode], 16);
memcpy(com.cmd.StreamControl.SetupData + 16,
ITUFeatureDecoderSetup, sizeof(ITUFeatureDecoderSetup));
}
clear_buffers(chan);
chan->State = KSSTATE_RUN;
if (mode & SMODE_TRANSPORT_STREAM)
chan->HWState = HWSTATE_RUN;
else
chan->HWState = HWSTATE_STARTUP;
spin_unlock_irq(&chan->state_lock);
if (ngene_command(dev, &com) < 0) {
up(&dev->stream_mutex);
return -1;
}
up(&dev->stream_mutex);
return 0;
}
void set_transfer(struct ngene_channel *chan, int state)
{
u8 control = 0, mode = 0, flags = 0;
struct ngene *dev = chan->dev;
int ret;
/*
printk(KERN_INFO DEVICE_NAME ": st %d\n", state);
msleep(100);
*/
if (state) {
if (chan->running) {
printk(KERN_INFO DEVICE_NAME ": already running\n");
return;
}
} else {
if (!chan->running) {
printk(KERN_INFO DEVICE_NAME ": already stopped\n");
return;
}
}
if (dev->card_info->switch_ctrl)
dev->card_info->switch_ctrl(chan, 1, state ^ 1);
if (state) {
spin_lock_irq(&chan->state_lock);
/* printk(KERN_INFO DEVICE_NAME ": lock=%08x\n",
ngreadl(0x9310)); */
dvb_ringbuffer_flush(&dev->tsout_rbuf);
control = 0x80;
if (chan->mode & (NGENE_IO_TSIN | NGENE_IO_TSOUT)) {
chan->Capture1Length = 512 * 188;
mode = SMODE_TRANSPORT_STREAM;
}
if (chan->mode & NGENE_IO_TSOUT) {
chan->pBufferExchange = tsout_exchange;
/* 0x66666666 = 50MHz *2^33 /250MHz */
chan->AudioDTOValue = 0x80000000;
chan->AudioDTOUpdated = 1;
}
if (chan->mode & NGENE_IO_TSIN)
chan->pBufferExchange = tsin_exchange;
spin_unlock_irq(&chan->state_lock);
} else
;/* printk(KERN_INFO DEVICE_NAME ": lock=%08x\n",
ngreadl(0x9310)); */
ret = ngene_command_stream_control(dev, chan->number,
control, mode, flags);
if (!ret)
chan->running = state;
else
printk(KERN_ERR DEVICE_NAME ": set_transfer %d failed\n",
state);
if (!state) {
spin_lock_irq(&chan->state_lock);
chan->pBufferExchange = NULL;
dvb_ringbuffer_flush(&dev->tsout_rbuf);
spin_unlock_irq(&chan->state_lock);
}
}
/****************************************************************************/
/* nGene hardware init and release functions ********************************/
/****************************************************************************/
static void free_ringbuffer(struct ngene *dev, struct SRingBufferDescriptor *rb)
{
struct SBufferHeader *Cur = rb->Head;
u32 j;
if (!Cur)
return;
for (j = 0; j < rb->NumBuffers; j++, Cur = Cur->Next) {
if (Cur->Buffer1)
pci_free_consistent(dev->pci_dev,
rb->Buffer1Length,
Cur->Buffer1,
Cur->scList1->Address);
if (Cur->Buffer2)
pci_free_consistent(dev->pci_dev,
rb->Buffer2Length,
Cur->Buffer2,
Cur->scList2->Address);
}
if (rb->SCListMem)
pci_free_consistent(dev->pci_dev, rb->SCListMemSize,
rb->SCListMem, rb->PASCListMem);
pci_free_consistent(dev->pci_dev, rb->MemSize, rb->Head, rb->PAHead);
}
static void free_idlebuffer(struct ngene *dev,
struct SRingBufferDescriptor *rb,
struct SRingBufferDescriptor *tb)
{
int j;
struct SBufferHeader *Cur = tb->Head;
if (!rb->Head)
return;
free_ringbuffer(dev, rb);
for (j = 0; j < tb->NumBuffers; j++, Cur = Cur->Next) {
Cur->Buffer2 = NULL;
Cur->scList2 = NULL;
Cur->ngeneBuffer.Address_of_first_entry_2 = 0;
Cur->ngeneBuffer.Number_of_entries_2 = 0;
}
}
static void free_common_buffers(struct ngene *dev)
{
u32 i;
struct ngene_channel *chan;
for (i = STREAM_VIDEOIN1; i < MAX_STREAM; i++) {
chan = &dev->channel[i];
free_idlebuffer(dev, &chan->TSIdleBuffer, &chan->TSRingBuffer);
free_ringbuffer(dev, &chan->RingBuffer);
free_ringbuffer(dev, &chan->TSRingBuffer);
}
if (dev->OverflowBuffer)
pci_free_consistent(dev->pci_dev,
OVERFLOW_BUFFER_SIZE,
dev->OverflowBuffer, dev->PAOverflowBuffer);
if (dev->FWInterfaceBuffer)
pci_free_consistent(dev->pci_dev,
4096,
dev->FWInterfaceBuffer,
dev->PAFWInterfaceBuffer);
}
/****************************************************************************/
/* Ring buffer handling *****************************************************/
/****************************************************************************/
static int create_ring_buffer(struct pci_dev *pci_dev,
struct SRingBufferDescriptor *descr, u32 NumBuffers)
{
dma_addr_t tmp;
struct SBufferHeader *Head;
u32 i;
u32 MemSize = SIZEOF_SBufferHeader * NumBuffers;
u64 PARingBufferHead;
u64 PARingBufferCur;
u64 PARingBufferNext;
struct SBufferHeader *Cur, *Next;
descr->Head = NULL;
descr->MemSize = 0;
descr->PAHead = 0;
descr->NumBuffers = 0;
if (MemSize < 4096)
MemSize = 4096;
Head = pci_alloc_consistent(pci_dev, MemSize, &tmp);
PARingBufferHead = tmp;
if (!Head)
return -ENOMEM;
memset(Head, 0, MemSize);
PARingBufferCur = PARingBufferHead;
Cur = Head;
for (i = 0; i < NumBuffers - 1; i++) {
Next = (struct SBufferHeader *)
(((u8 *) Cur) + SIZEOF_SBufferHeader);
PARingBufferNext = PARingBufferCur + SIZEOF_SBufferHeader;
Cur->Next = Next;
Cur->ngeneBuffer.Next = PARingBufferNext;
Cur = Next;
PARingBufferCur = PARingBufferNext;
}
/* Last Buffer points back to first one */
Cur->Next = Head;
Cur->ngeneBuffer.Next = PARingBufferHead;
descr->Head = Head;
descr->MemSize = MemSize;
descr->PAHead = PARingBufferHead;
descr->NumBuffers = NumBuffers;
return 0;
}
static int AllocateRingBuffers(struct pci_dev *pci_dev,
dma_addr_t of,
struct SRingBufferDescriptor *pRingBuffer,
u32 Buffer1Length, u32 Buffer2Length)
{
dma_addr_t tmp;
u32 i, j;
int status = 0;
u32 SCListMemSize = pRingBuffer->NumBuffers
* ((Buffer2Length != 0) ? (NUM_SCATTER_GATHER_ENTRIES * 2) :
NUM_SCATTER_GATHER_ENTRIES)
* sizeof(struct HW_SCATTER_GATHER_ELEMENT);
u64 PASCListMem;
struct HW_SCATTER_GATHER_ELEMENT *SCListEntry;
u64 PASCListEntry;
struct SBufferHeader *Cur;
void *SCListMem;
if (SCListMemSize < 4096)
SCListMemSize = 4096;
SCListMem = pci_alloc_consistent(pci_dev, SCListMemSize, &tmp);
PASCListMem = tmp;
if (SCListMem == NULL)
return -ENOMEM;
memset(SCListMem, 0, SCListMemSize);
pRingBuffer->SCListMem = SCListMem;
pRingBuffer->PASCListMem = PASCListMem;
pRingBuffer->SCListMemSize = SCListMemSize;
pRingBuffer->Buffer1Length = Buffer1Length;
pRingBuffer->Buffer2Length = Buffer2Length;
SCListEntry = SCListMem;
PASCListEntry = PASCListMem;
Cur = pRingBuffer->Head;
for (i = 0; i < pRingBuffer->NumBuffers; i += 1, Cur = Cur->Next) {
u64 PABuffer;
void *Buffer = pci_alloc_consistent(pci_dev, Buffer1Length,
&tmp);
PABuffer = tmp;
if (Buffer == NULL)
return -ENOMEM;
Cur->Buffer1 = Buffer;
SCListEntry->Address = PABuffer;
SCListEntry->Length = Buffer1Length;
Cur->scList1 = SCListEntry;
Cur->ngeneBuffer.Address_of_first_entry_1 = PASCListEntry;
Cur->ngeneBuffer.Number_of_entries_1 =
NUM_SCATTER_GATHER_ENTRIES;
SCListEntry += 1;
PASCListEntry += sizeof(struct HW_SCATTER_GATHER_ELEMENT);
#if NUM_SCATTER_GATHER_ENTRIES > 1
for (j = 0; j < NUM_SCATTER_GATHER_ENTRIES - 1; j += 1) {
SCListEntry->Address = of;
SCListEntry->Length = OVERFLOW_BUFFER_SIZE;
SCListEntry += 1;
PASCListEntry +=
sizeof(struct HW_SCATTER_GATHER_ELEMENT);
}
#endif
if (!Buffer2Length)
continue;
Buffer = pci_alloc_consistent(pci_dev, Buffer2Length, &tmp);
PABuffer = tmp;
if (Buffer == NULL)
return -ENOMEM;
Cur->Buffer2 = Buffer;
SCListEntry->Address = PABuffer;
SCListEntry->Length = Buffer2Length;
Cur->scList2 = SCListEntry;
Cur->ngeneBuffer.Address_of_first_entry_2 = PASCListEntry;
Cur->ngeneBuffer.Number_of_entries_2 =
NUM_SCATTER_GATHER_ENTRIES;
SCListEntry += 1;
PASCListEntry += sizeof(struct HW_SCATTER_GATHER_ELEMENT);
#if NUM_SCATTER_GATHER_ENTRIES > 1
for (j = 0; j < NUM_SCATTER_GATHER_ENTRIES - 1; j++) {
SCListEntry->Address = of;
SCListEntry->Length = OVERFLOW_BUFFER_SIZE;
SCListEntry += 1;
PASCListEntry +=
sizeof(struct HW_SCATTER_GATHER_ELEMENT);
}
#endif
}
return status;
}
static int FillTSIdleBuffer(struct SRingBufferDescriptor *pIdleBuffer,
struct SRingBufferDescriptor *pRingBuffer)
{
int status = 0;
/* Copy pointer to scatter gather list in TSRingbuffer
structure for buffer 2
Load number of buffer
*/
u32 n = pRingBuffer->NumBuffers;
/* Point to first buffer entry */
struct SBufferHeader *Cur = pRingBuffer->Head;
int i;
/* Loop thru all buffer and set Buffer 2 pointers to TSIdlebuffer */
for (i = 0; i < n; i++) {
Cur->Buffer2 = pIdleBuffer->Head->Buffer1;
Cur->scList2 = pIdleBuffer->Head->scList1;
Cur->ngeneBuffer.Address_of_first_entry_2 =
pIdleBuffer->Head->ngeneBuffer.
Address_of_first_entry_1;
Cur->ngeneBuffer.Number_of_entries_2 =
pIdleBuffer->Head->ngeneBuffer.Number_of_entries_1;
Cur = Cur->Next;
}
return status;
}
static u32 RingBufferSizes[MAX_STREAM] = {
RING_SIZE_VIDEO,
RING_SIZE_VIDEO,
RING_SIZE_AUDIO,
RING_SIZE_AUDIO,
RING_SIZE_AUDIO,
};
static u32 Buffer1Sizes[MAX_STREAM] = {
MAX_VIDEO_BUFFER_SIZE,
MAX_VIDEO_BUFFER_SIZE,
MAX_AUDIO_BUFFER_SIZE,
MAX_AUDIO_BUFFER_SIZE,
MAX_AUDIO_BUFFER_SIZE
};
static u32 Buffer2Sizes[MAX_STREAM] = {
MAX_VBI_BUFFER_SIZE,
MAX_VBI_BUFFER_SIZE,
0,
0,
0
};
static int AllocCommonBuffers(struct ngene *dev)
{
int status = 0, i;
dev->FWInterfaceBuffer = pci_alloc_consistent(dev->pci_dev, 4096,
&dev->PAFWInterfaceBuffer);
if (!dev->FWInterfaceBuffer)
return -ENOMEM;
dev->hosttongene = dev->FWInterfaceBuffer;
dev->ngenetohost = dev->FWInterfaceBuffer + 256;
dev->EventBuffer = dev->FWInterfaceBuffer + 512;
dev->OverflowBuffer = pci_alloc_consistent(dev->pci_dev,
OVERFLOW_BUFFER_SIZE,
&dev->PAOverflowBuffer);
if (!dev->OverflowBuffer)
return -ENOMEM;
memset(dev->OverflowBuffer, 0, OVERFLOW_BUFFER_SIZE);
for (i = STREAM_VIDEOIN1; i < MAX_STREAM; i++) {
int type = dev->card_info->io_type[i];
dev->channel[i].State = KSSTATE_STOP;
if (type & (NGENE_IO_TV | NGENE_IO_HDTV | NGENE_IO_AIN)) {
status = create_ring_buffer(dev->pci_dev,
&dev->channel[i].RingBuffer,
RingBufferSizes[i]);
if (status < 0)
break;
if (type & (NGENE_IO_TV | NGENE_IO_AIN)) {
status = AllocateRingBuffers(dev->pci_dev,
dev->
PAOverflowBuffer,
&dev->channel[i].
RingBuffer,
Buffer1Sizes[i],
Buffer2Sizes[i]);
if (status < 0)
break;
} else if (type & NGENE_IO_HDTV) {
status = AllocateRingBuffers(dev->pci_dev,
dev->
PAOverflowBuffer,
&dev->channel[i].
RingBuffer,
MAX_HDTV_BUFFER_SIZE,
0);
if (status < 0)
break;
}
}
if (type & (NGENE_IO_TSIN | NGENE_IO_TSOUT)) {
status = create_ring_buffer(dev->pci_dev,
&dev->channel[i].
TSRingBuffer, RING_SIZE_TS);
if (status < 0)
break;
status = AllocateRingBuffers(dev->pci_dev,
dev->PAOverflowBuffer,
&dev->channel[i].
TSRingBuffer,
MAX_TS_BUFFER_SIZE, 0);
if (status)
break;
}
if (type & NGENE_IO_TSOUT) {
status = create_ring_buffer(dev->pci_dev,
&dev->channel[i].
TSIdleBuffer, 1);
if (status < 0)
break;
status = AllocateRingBuffers(dev->pci_dev,
dev->PAOverflowBuffer,
&dev->channel[i].
TSIdleBuffer,
MAX_TS_BUFFER_SIZE, 0);
if (status)
break;
FillTSIdleBuffer(&dev->channel[i].TSIdleBuffer,
&dev->channel[i].TSRingBuffer);
}
}
return status;
}
static void ngene_release_buffers(struct ngene *dev)
{
if (dev->iomem)
iounmap(dev->iomem);
free_common_buffers(dev);
vfree(dev->tsout_buf);
vfree(dev->tsin_buf);
vfree(dev->ain_buf);
vfree(dev->vin_buf);
vfree(dev);
}
static int ngene_get_buffers(struct ngene *dev)
{
if (AllocCommonBuffers(dev))
return -ENOMEM;
if (dev->card_info->io_type[4] & NGENE_IO_TSOUT) {
dev->tsout_buf = vmalloc(TSOUT_BUF_SIZE);
if (!dev->tsout_buf)
return -ENOMEM;
dvb_ringbuffer_init(&dev->tsout_rbuf,
dev->tsout_buf, TSOUT_BUF_SIZE);
}
if (dev->card_info->io_type[2]&NGENE_IO_TSIN) {
dev->tsin_buf = vmalloc(TSIN_BUF_SIZE);
if (!dev->tsin_buf)
return -ENOMEM;
dvb_ringbuffer_init(&dev->tsin_rbuf,
dev->tsin_buf, TSIN_BUF_SIZE);
}
if (dev->card_info->io_type[2] & NGENE_IO_AIN) {
dev->ain_buf = vmalloc(AIN_BUF_SIZE);
if (!dev->ain_buf)
return -ENOMEM;
dvb_ringbuffer_init(&dev->ain_rbuf, dev->ain_buf, AIN_BUF_SIZE);
}
if (dev->card_info->io_type[0] & NGENE_IO_HDTV) {
dev->vin_buf = vmalloc(VIN_BUF_SIZE);
if (!dev->vin_buf)
return -ENOMEM;
dvb_ringbuffer_init(&dev->vin_rbuf, dev->vin_buf, VIN_BUF_SIZE);
}
dev->iomem = ioremap(pci_resource_start(dev->pci_dev, 0),
pci_resource_len(dev->pci_dev, 0));
if (!dev->iomem)
return -ENOMEM;
return 0;
}
static void ngene_init(struct ngene *dev)
{
int i;
tasklet_init(&dev->event_tasklet, event_tasklet, (unsigned long)dev);
memset_io(dev->iomem + 0xc000, 0x00, 0x220);
memset_io(dev->iomem + 0xc400, 0x00, 0x100);
for (i = 0; i < MAX_STREAM; i++) {
dev->channel[i].dev = dev;
dev->channel[i].number = i;
}
dev->fw_interface_version = 0;
ngwritel(0, NGENE_INT_ENABLE);
dev->icounts = ngreadl(NGENE_INT_COUNTS);
dev->device_version = ngreadl(DEV_VER) & 0x0f;
printk(KERN_INFO DEVICE_NAME ": Device version %d\n",
dev->device_version);
}
static int ngene_load_firm(struct ngene *dev)
{
u32 size;
const struct firmware *fw = NULL;
u8 *ngene_fw;
char *fw_name;
int err, version;
version = dev->card_info->fw_version;
switch (version) {
default:
case 15:
version = 15;
size = 23466;
fw_name = "ngene_15.fw";
dev->cmd_timeout_workaround = true;
break;
case 16:
size = 23498;
fw_name = "ngene_16.fw";
dev->cmd_timeout_workaround = true;
break;
case 17:
size = 24446;
fw_name = "ngene_17.fw";
dev->cmd_timeout_workaround = true;
break;
case 18:
size = 0;
fw_name = "ngene_18.fw";
break;
}
if (request_firmware(&fw, fw_name, &dev->pci_dev->dev) < 0) {
printk(KERN_ERR DEVICE_NAME
": Could not load firmware file %s.\n", fw_name);
printk(KERN_INFO DEVICE_NAME
": Copy %s to your hotplug directory!\n", fw_name);
return -1;
}
if (size == 0)
size = fw->size;
if (size != fw->size) {
printk(KERN_ERR DEVICE_NAME
": Firmware %s has invalid size!", fw_name);
err = -1;
} else {
printk(KERN_INFO DEVICE_NAME
": Loading firmware file %s.\n", fw_name);
ngene_fw = (u8 *) fw->data;
err = ngene_command_load_firmware(dev, ngene_fw, size);
}
release_firmware(fw);
return err;
}
static void ngene_stop(struct ngene *dev)
{
down(&dev->cmd_mutex);
i2c_del_adapter(&(dev->channel[0].i2c_adapter));
i2c_del_adapter(&(dev->channel[1].i2c_adapter));
ngwritel(0, NGENE_INT_ENABLE);
ngwritel(0, NGENE_COMMAND);
ngwritel(0, NGENE_COMMAND_HI);
ngwritel(0, NGENE_STATUS);
ngwritel(0, NGENE_STATUS_HI);
ngwritel(0, NGENE_EVENT);
ngwritel(0, NGENE_EVENT_HI);
free_irq(dev->pci_dev->irq, dev);
#ifdef CONFIG_PCI_MSI
if (dev->msi_enabled)
pci_disable_msi(dev->pci_dev);
#endif
}
static int ngene_buffer_config(struct ngene *dev)
{
int stat;
if (dev->card_info->fw_version >= 17) {
u8 tsin12_config[6] = { 0x60, 0x60, 0x00, 0x00, 0x00, 0x00 };
u8 tsin1234_config[6] = { 0x30, 0x30, 0x00, 0x30, 0x30, 0x00 };
u8 tsio1235_config[6] = { 0x30, 0x30, 0x00, 0x28, 0x00, 0x38 };
u8 *bconf = tsin12_config;
if (dev->card_info->io_type[2]&NGENE_IO_TSIN &&
dev->card_info->io_type[3]&NGENE_IO_TSIN) {
bconf = tsin1234_config;
if (dev->card_info->io_type[4]&NGENE_IO_TSOUT &&
dev->ci.en)
bconf = tsio1235_config;
}
stat = ngene_command_config_free_buf(dev, bconf);
} else {
int bconf = BUFFER_CONFIG_4422;
if (dev->card_info->io_type[3] == NGENE_IO_TSIN)
bconf = BUFFER_CONFIG_3333;
stat = ngene_command_config_buf(dev, bconf);
}
return stat;
}
static int ngene_start(struct ngene *dev)
{
int stat;
int i;
pci_set_master(dev->pci_dev);
ngene_init(dev);
stat = request_irq(dev->pci_dev->irq, irq_handler,
IRQF_SHARED, "nGene",
(void *)dev);
if (stat < 0)
return stat;
init_waitqueue_head(&dev->cmd_wq);
init_waitqueue_head(&dev->tx_wq);
init_waitqueue_head(&dev->rx_wq);
sema_init(&dev->cmd_mutex, 1);
sema_init(&dev->stream_mutex, 1);
sema_init(&dev->pll_mutex, 1);
sema_init(&dev->i2c_switch_mutex, 1);
spin_lock_init(&dev->cmd_lock);
for (i = 0; i < MAX_STREAM; i++)
spin_lock_init(&dev->channel[i].state_lock);
ngwritel(1, TIMESTAMPS);
ngwritel(1, NGENE_INT_ENABLE);
stat = ngene_load_firm(dev);
if (stat < 0)
goto fail;
#ifdef CONFIG_PCI_MSI
/* enable MSI if kernel and card support it */
if (pci_msi_enabled() && dev->card_info->msi_supported) {
unsigned long flags;
ngwritel(0, NGENE_INT_ENABLE);
free_irq(dev->pci_dev->irq, dev);
stat = pci_enable_msi(dev->pci_dev);
if (stat) {
printk(KERN_INFO DEVICE_NAME
": MSI not available\n");
flags = IRQF_SHARED;
} else {
flags = 0;
dev->msi_enabled = true;
}
stat = request_irq(dev->pci_dev->irq, irq_handler,
flags, "nGene", dev);
if (stat < 0)
goto fail2;
ngwritel(1, NGENE_INT_ENABLE);
}
#endif
stat = ngene_i2c_init(dev, 0);
if (stat < 0)
goto fail;
stat = ngene_i2c_init(dev, 1);
if (stat < 0)
goto fail;
if (!stat)
return stat;
/* otherwise error: fall through */
fail:
ngwritel(0, NGENE_INT_ENABLE);
free_irq(dev->pci_dev->irq, dev);
#ifdef CONFIG_PCI_MSI
fail2:
if (dev->msi_enabled)
pci_disable_msi(dev->pci_dev);
#endif
return stat;
}
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
static void release_channel(struct ngene_channel *chan)
{
struct dvb_demux *dvbdemux = &chan->demux;
struct ngene *dev = chan->dev;
if (chan->running)
set_transfer(chan, 0);
tasklet_kill(&chan->demux_tasklet);
if (chan->ci_dev) {
dvb_unregister_device(chan->ci_dev);
chan->ci_dev = NULL;
}
if (chan->fe2)
dvb_unregister_frontend(chan->fe2);
if (chan->fe) {
dvb_unregister_frontend(chan->fe);
dvb_frontend_detach(chan->fe);
chan->fe = NULL;
}
if (chan->has_demux) {
dvb_net_release(&chan->dvbnet);
dvbdemux->dmx.close(&dvbdemux->dmx);
dvbdemux->dmx.remove_frontend(&dvbdemux->dmx,
&chan->hw_frontend);
dvbdemux->dmx.remove_frontend(&dvbdemux->dmx,
&chan->mem_frontend);
dvb_dmxdev_release(&chan->dmxdev);
dvb_dmx_release(&chan->demux);
chan->has_demux = false;
}
if (chan->has_adapter) {
dvb_unregister_adapter(&dev->adapter[chan->number]);
chan->has_adapter = false;
}
}
static int init_channel(struct ngene_channel *chan)
{
int ret = 0, nr = chan->number;
struct dvb_adapter *adapter = NULL;
struct dvb_demux *dvbdemux = &chan->demux;
struct ngene *dev = chan->dev;
struct ngene_info *ni = dev->card_info;
int io = ni->io_type[nr];
tasklet_init(&chan->demux_tasklet, demux_tasklet, (unsigned long)chan);
chan->users = 0;
chan->type = io;
chan->mode = chan->type; /* for now only one mode */
if (io & NGENE_IO_TSIN) {
chan->fe = NULL;
if (ni->demod_attach[nr]) {
ret = ni->demod_attach[nr](chan);
if (ret < 0)
goto err;
}
if (chan->fe && ni->tuner_attach[nr]) {
ret = ni->tuner_attach[nr](chan);
if (ret < 0)
goto err;
}
}
if (!dev->ci.en && (io & NGENE_IO_TSOUT))
return 0;
if (io & (NGENE_IO_TSIN | NGENE_IO_TSOUT)) {
if (nr >= STREAM_AUDIOIN1)
chan->DataFormatFlags = DF_SWAP32;
if (nr == 0 || !one_adapter || dev->first_adapter == NULL) {
adapter = &dev->adapter[nr];
ret = dvb_register_adapter(adapter, "nGene",
THIS_MODULE,
&chan->dev->pci_dev->dev,
adapter_nr);
if (ret < 0)
goto err;
if (dev->first_adapter == NULL)
dev->first_adapter = adapter;
chan->has_adapter = true;
} else
adapter = dev->first_adapter;
}
if (dev->ci.en && (io & NGENE_IO_TSOUT)) {
dvb_ca_en50221_init(adapter, dev->ci.en, 0, 1);
set_transfer(chan, 1);
chan->dev->channel[2].DataFormatFlags = DF_SWAP32;
set_transfer(&chan->dev->channel[2], 1);
dvb_register_device(adapter, &chan->ci_dev,
&ngene_dvbdev_ci, (void *) chan,
DVB_DEVICE_SEC);
if (!chan->ci_dev)
goto err;
}
if (chan->fe) {
if (dvb_register_frontend(adapter, chan->fe) < 0)
goto err;
chan->has_demux = true;
}
if (chan->fe2) {
if (dvb_register_frontend(adapter, chan->fe2) < 0)
goto err;
chan->fe2->tuner_priv = chan->fe->tuner_priv;
memcpy(&chan->fe2->ops.tuner_ops,
&chan->fe->ops.tuner_ops,
sizeof(struct dvb_tuner_ops));
}
if (chan->has_demux) {
ret = my_dvb_dmx_ts_card_init(dvbdemux, "SW demux",
ngene_start_feed,
ngene_stop_feed, chan);
ret = my_dvb_dmxdev_ts_card_init(&chan->dmxdev, &chan->demux,
&chan->hw_frontend,
&chan->mem_frontend, adapter);
ret = dvb_net_init(adapter, &chan->dvbnet, &chan->demux.dmx);
}
return ret;
err:
if (chan->fe) {
dvb_frontend_detach(chan->fe);
chan->fe = NULL;
}
release_channel(chan);
return 0;
}
static int init_channels(struct ngene *dev)
{
int i, j;
for (i = 0; i < MAX_STREAM; i++) {
dev->channel[i].number = i;
if (init_channel(&dev->channel[i]) < 0) {
for (j = i - 1; j >= 0; j--)
release_channel(&dev->channel[j]);
return -1;
}
}
return 0;
}
static struct cxd2099_cfg cxd_cfg = {
.bitrate = 62000,
.adr = 0x40,
.polarity = 0,
.clock_mode = 0,
};
static void cxd_attach(struct ngene *dev)
{
struct ngene_ci *ci = &dev->ci;
ci->en = cxd2099_attach(&cxd_cfg, dev, &dev->channel[0].i2c_adapter);
ci->dev = dev;
return;
}
static void cxd_detach(struct ngene *dev)
{
struct ngene_ci *ci = &dev->ci;
dvb_ca_en50221_release(ci->en);
kfree(ci->en);
ci->en = 0;
}
/***********************************/
/* workaround for shutdown failure */
/***********************************/
static void ngene_unlink(struct ngene *dev)
{
struct ngene_command com;
com.cmd.hdr.Opcode = CMD_MEM_WRITE;
com.cmd.hdr.Length = 3;
com.cmd.MemoryWrite.address = 0x910c;
com.cmd.MemoryWrite.data = 0xff;
com.in_len = 3;
com.out_len = 1;
down(&dev->cmd_mutex);
ngwritel(0, NGENE_INT_ENABLE);
ngene_command_mutex(dev, &com);
up(&dev->cmd_mutex);
}
void ngene_shutdown(struct pci_dev *pdev)
{
struct ngene *dev = (struct ngene *)pci_get_drvdata(pdev);
if (!dev || !shutdown_workaround)
return;
printk(KERN_INFO DEVICE_NAME ": shutdown workaround...\n");
ngene_unlink(dev);
pci_disable_device(pdev);
}
/****************************************************************************/
/* device probe/remove calls ************************************************/
/****************************************************************************/
void __devexit ngene_remove(struct pci_dev *pdev)
{
struct ngene *dev = pci_get_drvdata(pdev);
int i;
tasklet_kill(&dev->event_tasklet);
for (i = MAX_STREAM - 1; i >= 0; i--)
release_channel(&dev->channel[i]);
if (dev->ci.en)
cxd_detach(dev);
ngene_stop(dev);
ngene_release_buffers(dev);
pci_set_drvdata(pdev, NULL);
pci_disable_device(pdev);
}
int __devinit ngene_probe(struct pci_dev *pci_dev,
const struct pci_device_id *id)
{
struct ngene *dev;
int stat = 0;
if (pci_enable_device(pci_dev) < 0)
return -ENODEV;
dev = vzalloc(sizeof(struct ngene));
if (dev == NULL) {
stat = -ENOMEM;
goto fail0;
}
dev->pci_dev = pci_dev;
dev->card_info = (struct ngene_info *)id->driver_data;
printk(KERN_INFO DEVICE_NAME ": Found %s\n", dev->card_info->name);
pci_set_drvdata(pci_dev, dev);
/* Alloc buffers and start nGene */
stat = ngene_get_buffers(dev);
if (stat < 0)
goto fail1;
stat = ngene_start(dev);
if (stat < 0)
goto fail1;
cxd_attach(dev);
stat = ngene_buffer_config(dev);
if (stat < 0)
goto fail1;
dev->i2c_current_bus = -1;
/* Register DVB adapters and devices for both channels */
if (init_channels(dev) < 0)
goto fail2;
return 0;
fail2:
ngene_stop(dev);
fail1:
ngene_release_buffers(dev);
fail0:
pci_disable_device(pci_dev);
pci_set_drvdata(pci_dev, NULL);
return stat;
}
| gpl-2.0 |
flexdroid/kernel | drivers/infiniband/core/uverbs_marshall.c | 8015 | 5319 | /*
* Copyright (c) 2005 Intel Corporation. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - 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.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/export.h>
#include <rdma/ib_marshall.h>
void ib_copy_ah_attr_to_user(struct ib_uverbs_ah_attr *dst,
struct ib_ah_attr *src)
{
memcpy(dst->grh.dgid, src->grh.dgid.raw, sizeof src->grh.dgid);
dst->grh.flow_label = src->grh.flow_label;
dst->grh.sgid_index = src->grh.sgid_index;
dst->grh.hop_limit = src->grh.hop_limit;
dst->grh.traffic_class = src->grh.traffic_class;
memset(&dst->grh.reserved, 0, sizeof(dst->grh.reserved));
dst->dlid = src->dlid;
dst->sl = src->sl;
dst->src_path_bits = src->src_path_bits;
dst->static_rate = src->static_rate;
dst->is_global = src->ah_flags & IB_AH_GRH ? 1 : 0;
dst->port_num = src->port_num;
dst->reserved = 0;
}
EXPORT_SYMBOL(ib_copy_ah_attr_to_user);
void ib_copy_qp_attr_to_user(struct ib_uverbs_qp_attr *dst,
struct ib_qp_attr *src)
{
dst->qp_state = src->qp_state;
dst->cur_qp_state = src->cur_qp_state;
dst->path_mtu = src->path_mtu;
dst->path_mig_state = src->path_mig_state;
dst->qkey = src->qkey;
dst->rq_psn = src->rq_psn;
dst->sq_psn = src->sq_psn;
dst->dest_qp_num = src->dest_qp_num;
dst->qp_access_flags = src->qp_access_flags;
dst->max_send_wr = src->cap.max_send_wr;
dst->max_recv_wr = src->cap.max_recv_wr;
dst->max_send_sge = src->cap.max_send_sge;
dst->max_recv_sge = src->cap.max_recv_sge;
dst->max_inline_data = src->cap.max_inline_data;
ib_copy_ah_attr_to_user(&dst->ah_attr, &src->ah_attr);
ib_copy_ah_attr_to_user(&dst->alt_ah_attr, &src->alt_ah_attr);
dst->pkey_index = src->pkey_index;
dst->alt_pkey_index = src->alt_pkey_index;
dst->en_sqd_async_notify = src->en_sqd_async_notify;
dst->sq_draining = src->sq_draining;
dst->max_rd_atomic = src->max_rd_atomic;
dst->max_dest_rd_atomic = src->max_dest_rd_atomic;
dst->min_rnr_timer = src->min_rnr_timer;
dst->port_num = src->port_num;
dst->timeout = src->timeout;
dst->retry_cnt = src->retry_cnt;
dst->rnr_retry = src->rnr_retry;
dst->alt_port_num = src->alt_port_num;
dst->alt_timeout = src->alt_timeout;
memset(dst->reserved, 0, sizeof(dst->reserved));
}
EXPORT_SYMBOL(ib_copy_qp_attr_to_user);
void ib_copy_path_rec_to_user(struct ib_user_path_rec *dst,
struct ib_sa_path_rec *src)
{
memcpy(dst->dgid, src->dgid.raw, sizeof src->dgid);
memcpy(dst->sgid, src->sgid.raw, sizeof src->sgid);
dst->dlid = src->dlid;
dst->slid = src->slid;
dst->raw_traffic = src->raw_traffic;
dst->flow_label = src->flow_label;
dst->hop_limit = src->hop_limit;
dst->traffic_class = src->traffic_class;
dst->reversible = src->reversible;
dst->numb_path = src->numb_path;
dst->pkey = src->pkey;
dst->sl = src->sl;
dst->mtu_selector = src->mtu_selector;
dst->mtu = src->mtu;
dst->rate_selector = src->rate_selector;
dst->rate = src->rate;
dst->packet_life_time = src->packet_life_time;
dst->preference = src->preference;
dst->packet_life_time_selector = src->packet_life_time_selector;
}
EXPORT_SYMBOL(ib_copy_path_rec_to_user);
void ib_copy_path_rec_from_user(struct ib_sa_path_rec *dst,
struct ib_user_path_rec *src)
{
memcpy(dst->dgid.raw, src->dgid, sizeof dst->dgid);
memcpy(dst->sgid.raw, src->sgid, sizeof dst->sgid);
dst->dlid = src->dlid;
dst->slid = src->slid;
dst->raw_traffic = src->raw_traffic;
dst->flow_label = src->flow_label;
dst->hop_limit = src->hop_limit;
dst->traffic_class = src->traffic_class;
dst->reversible = src->reversible;
dst->numb_path = src->numb_path;
dst->pkey = src->pkey;
dst->sl = src->sl;
dst->mtu_selector = src->mtu_selector;
dst->mtu = src->mtu;
dst->rate_selector = src->rate_selector;
dst->rate = src->rate;
dst->packet_life_time = src->packet_life_time;
dst->preference = src->preference;
dst->packet_life_time_selector = src->packet_life_time_selector;
}
EXPORT_SYMBOL(ib_copy_path_rec_from_user);
| gpl-2.0 |
Snuzzo/dlx_kernel | arch/cris/arch-v32/mach-fs/vcs_hook.c | 9295 | 2062 | /*
* Call simulator hook. This is the part running in the
* simulated program.
*/
#include "vcs_hook.h"
#include <stdarg.h>
#include <arch-v32/hwregs/reg_map.h>
#include <arch-v32/hwregs/intr_vect_defs.h>
#define HOOK_TRIG_ADDR 0xb7000000 /* hook cvlog model reg address */
#define HOOK_MEM_BASE_ADDR 0xa0000000 /* csp4 (shared mem) base addr */
#define HOOK_DATA(offset) ((unsigned *)HOOK_MEM_BASE_ADDR)[offset]
#define VHOOK_DATA(offset) ((volatile unsigned *)HOOK_MEM_BASE_ADDR)[offset]
#define HOOK_TRIG(funcid) \
do { \
*((unsigned *) HOOK_TRIG_ADDR) = funcid; \
} while (0)
#define HOOK_DATA_BYTE(offset) ((unsigned char *)HOOK_MEM_BASE_ADDR)[offset]
int hook_call(unsigned id, unsigned pcnt, ...)
{
va_list ap;
unsigned i;
unsigned ret;
#ifdef USING_SOS
PREEMPT_OFF_SAVE();
#endif
/* pass parameters */
HOOK_DATA(0) = id;
/* Have to make hook_print_str a special case since we call with a
* parameter of byte type. Should perhaps be a separate
* hook_call. */
if (id == hook_print_str) {
int i;
char *str;
HOOK_DATA(1) = pcnt;
va_start(ap, pcnt);
str = (char *)va_arg(ap, unsigned);
for (i = 0; i != pcnt; i++)
HOOK_DATA_BYTE(8 + i) = str[i];
HOOK_DATA_BYTE(8 + i) = 0; /* null byte */
} else {
va_start(ap, pcnt);
for (i = 1; i <= pcnt; i++)
HOOK_DATA(i) = va_arg(ap, unsigned);
va_end(ap);
}
/* read from mem to make sure data has propagated to memory before
* trigging */
ret = *((volatile unsigned *)HOOK_MEM_BASE_ADDR);
/* trigger hook */
HOOK_TRIG(id);
/* wait for call to finish */
while (VHOOK_DATA(0) > 0) ;
/* extract return value */
ret = VHOOK_DATA(1);
#ifdef USING_SOS
PREEMPT_RESTORE();
#endif
return ret;
}
unsigned hook_buf(unsigned i)
{
return (HOOK_DATA(i));
}
void print_str(const char *str)
{
int i;
/* find null at end of string */
for (i = 1; str[i]; i++) ;
hook_call(hook_print_str, i, str);
}
void CPU_KICK_DOG(void)
{
(void)hook_call(hook_kick_dog, 0);
}
void CPU_WATCHDOG_TIMEOUT(unsigned t)
{
(void)hook_call(hook_dog_timeout, 1, t);
}
| gpl-2.0 |
semdoc/kernel_lge_msm8974 | arch/mips/kernel/binfmt_elfo32.c | 9295 | 4508 | /*
* Support for o32 Linux/MIPS ELF binaries.
*
* Copyright (C) 1999, 2001 Ralf Baechle
* Copyright (C) 1999, 2001 Silicon Graphics, Inc.
*
* Heavily inspired by the 32-bit Sparc compat code which is
* Copyright (C) 1995, 1996, 1997, 1998 David S. Miller (davem@redhat.com)
* Copyright (C) 1995, 1996, 1997, 1998 Jakub Jelinek (jj@ultra.linux.cz)
*/
#define ELF_ARCH EM_MIPS
#define ELF_CLASS ELFCLASS32
#ifdef __MIPSEB__
#define ELF_DATA ELFDATA2MSB;
#else /* __MIPSEL__ */
#define ELF_DATA ELFDATA2LSB;
#endif
/* ELF register definitions */
#define ELF_NGREG 45
#define ELF_NFPREG 33
typedef unsigned int elf_greg_t;
typedef elf_greg_t elf_gregset_t[ELF_NGREG];
typedef double elf_fpreg_t;
typedef elf_fpreg_t elf_fpregset_t[ELF_NFPREG];
/*
* This is used to ensure we don't load something for the wrong architecture.
*/
#define elf_check_arch(hdr) \
({ \
int __res = 1; \
struct elfhdr *__h = (hdr); \
\
if (__h->e_machine != EM_MIPS) \
__res = 0; \
if (__h->e_ident[EI_CLASS] != ELFCLASS32) \
__res = 0; \
if ((__h->e_flags & EF_MIPS_ABI2) != 0) \
__res = 0; \
if (((__h->e_flags & EF_MIPS_ABI) != 0) && \
((__h->e_flags & EF_MIPS_ABI) != EF_MIPS_ABI_O32)) \
__res = 0; \
\
__res; \
})
#define TASK32_SIZE 0x7fff8000UL
#undef ELF_ET_DYN_BASE
#define ELF_ET_DYN_BASE (TASK32_SIZE / 3 * 2)
#include <asm/processor.h>
/*
* When this file is selected, we are definitely running a 64bit kernel.
* So using the right regs define in asm/reg.h
*/
#define WANT_COMPAT_REG_H
/* These MUST be defined before elf.h gets included */
extern void elf32_core_copy_regs(elf_gregset_t grp, struct pt_regs *regs);
#define ELF_CORE_COPY_REGS(_dest, _regs) elf32_core_copy_regs(_dest, _regs);
#define ELF_CORE_COPY_TASK_REGS(_tsk, _dest) \
({ \
int __res = 1; \
elf32_core_copy_regs(*(_dest), task_pt_regs(_tsk)); \
__res; \
})
#include <linux/module.h>
#include <linux/elfcore.h>
#include <linux/compat.h>
#include <linux/math64.h>
#define elf_prstatus elf_prstatus32
struct elf_prstatus32
{
struct elf_siginfo pr_info; /* Info associated with signal */
short pr_cursig; /* Current signal */
unsigned int pr_sigpend; /* Set of pending signals */
unsigned int pr_sighold; /* Set of held signals */
pid_t pr_pid;
pid_t pr_ppid;
pid_t pr_pgrp;
pid_t pr_sid;
struct compat_timeval pr_utime; /* User time */
struct compat_timeval pr_stime; /* System time */
struct compat_timeval pr_cutime;/* Cumulative user time */
struct compat_timeval pr_cstime;/* Cumulative system time */
elf_gregset_t pr_reg; /* GP registers */
int pr_fpvalid; /* True if math co-processor being used. */
};
#define elf_prpsinfo elf_prpsinfo32
struct elf_prpsinfo32
{
char pr_state; /* numeric process state */
char pr_sname; /* char for pr_state */
char pr_zomb; /* zombie */
char pr_nice; /* nice val */
unsigned int pr_flag; /* flags */
__kernel_uid_t pr_uid;
__kernel_gid_t pr_gid;
pid_t pr_pid, pr_ppid, pr_pgrp, pr_sid;
/* Lots missing */
char pr_fname[16]; /* filename of executable */
char pr_psargs[ELF_PRARGSZ]; /* initial part of arg list */
};
#define elf_caddr_t u32
#define init_elf_binfmt init_elf32_binfmt
#define jiffies_to_timeval jiffies_to_compat_timeval
static inline void
jiffies_to_compat_timeval(unsigned long jiffies, struct compat_timeval *value)
{
/*
* Convert jiffies to nanoseconds and separate with
* one divide.
*/
u64 nsec = (u64)jiffies * TICK_NSEC;
u32 rem;
value->tv_sec = div_u64_rem(nsec, NSEC_PER_SEC, &rem);
value->tv_usec = rem / NSEC_PER_USEC;
}
void elf32_core_copy_regs(elf_gregset_t grp, struct pt_regs *regs)
{
int i;
for (i = 0; i < EF_R0; i++)
grp[i] = 0;
grp[EF_R0] = 0;
for (i = 1; i <= 31; i++)
grp[EF_R0 + i] = (elf_greg_t) regs->regs[i];
grp[EF_R26] = 0;
grp[EF_R27] = 0;
grp[EF_LO] = (elf_greg_t) regs->lo;
grp[EF_HI] = (elf_greg_t) regs->hi;
grp[EF_CP0_EPC] = (elf_greg_t) regs->cp0_epc;
grp[EF_CP0_BADVADDR] = (elf_greg_t) regs->cp0_badvaddr;
grp[EF_CP0_STATUS] = (elf_greg_t) regs->cp0_status;
grp[EF_CP0_CAUSE] = (elf_greg_t) regs->cp0_cause;
#ifdef EF_UNUSED0
grp[EF_UNUSED0] = 0;
#endif
}
MODULE_DESCRIPTION("Binary format loader for compatibility with o32 Linux/MIPS binaries");
MODULE_AUTHOR("Ralf Baechle (ralf@linux-mips.org)");
#undef MODULE_DESCRIPTION
#undef MODULE_AUTHOR
#undef TASK_SIZE
#define TASK_SIZE TASK_SIZE32
#include "../../../fs/binfmt_elf.c"
| gpl-2.0 |
schmatzler/zte-kernel-smartchat | arch/cris/arch-v32/mach-fs/vcs_hook.c | 9295 | 2062 | /*
* Call simulator hook. This is the part running in the
* simulated program.
*/
#include "vcs_hook.h"
#include <stdarg.h>
#include <arch-v32/hwregs/reg_map.h>
#include <arch-v32/hwregs/intr_vect_defs.h>
#define HOOK_TRIG_ADDR 0xb7000000 /* hook cvlog model reg address */
#define HOOK_MEM_BASE_ADDR 0xa0000000 /* csp4 (shared mem) base addr */
#define HOOK_DATA(offset) ((unsigned *)HOOK_MEM_BASE_ADDR)[offset]
#define VHOOK_DATA(offset) ((volatile unsigned *)HOOK_MEM_BASE_ADDR)[offset]
#define HOOK_TRIG(funcid) \
do { \
*((unsigned *) HOOK_TRIG_ADDR) = funcid; \
} while (0)
#define HOOK_DATA_BYTE(offset) ((unsigned char *)HOOK_MEM_BASE_ADDR)[offset]
int hook_call(unsigned id, unsigned pcnt, ...)
{
va_list ap;
unsigned i;
unsigned ret;
#ifdef USING_SOS
PREEMPT_OFF_SAVE();
#endif
/* pass parameters */
HOOK_DATA(0) = id;
/* Have to make hook_print_str a special case since we call with a
* parameter of byte type. Should perhaps be a separate
* hook_call. */
if (id == hook_print_str) {
int i;
char *str;
HOOK_DATA(1) = pcnt;
va_start(ap, pcnt);
str = (char *)va_arg(ap, unsigned);
for (i = 0; i != pcnt; i++)
HOOK_DATA_BYTE(8 + i) = str[i];
HOOK_DATA_BYTE(8 + i) = 0; /* null byte */
} else {
va_start(ap, pcnt);
for (i = 1; i <= pcnt; i++)
HOOK_DATA(i) = va_arg(ap, unsigned);
va_end(ap);
}
/* read from mem to make sure data has propagated to memory before
* trigging */
ret = *((volatile unsigned *)HOOK_MEM_BASE_ADDR);
/* trigger hook */
HOOK_TRIG(id);
/* wait for call to finish */
while (VHOOK_DATA(0) > 0) ;
/* extract return value */
ret = VHOOK_DATA(1);
#ifdef USING_SOS
PREEMPT_RESTORE();
#endif
return ret;
}
unsigned hook_buf(unsigned i)
{
return (HOOK_DATA(i));
}
void print_str(const char *str)
{
int i;
/* find null at end of string */
for (i = 1; str[i]; i++) ;
hook_call(hook_print_str, i, str);
}
void CPU_KICK_DOG(void)
{
(void)hook_call(hook_kick_dog, 0);
}
void CPU_WATCHDOG_TIMEOUT(unsigned t)
{
(void)hook_call(hook_dog_timeout, 1, t);
}
| gpl-2.0 |
nit-in/android_kernel_htc_pico-1 | arch/arm/mach-shmobile/console.c | 11855 | 1043 | /*
* SH-Mobile Console
*
* Copyright (C) 2010 Magnus Damm
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <mach/common.h>
#include <asm/mach/map.h>
void __init shmobile_setup_console(void)
{
parse_early_param();
/* Let earlyprintk output early console messages */
early_platform_driver_probe("earlyprintk", 1, 1);
}
| gpl-2.0 |
nullpo-head/linux | net/netfilter/xt_sctp.c | 12879 | 5088 | #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/skbuff.h>
#include <net/ip.h>
#include <net/ipv6.h>
#include <net/sctp/sctp.h>
#include <linux/sctp.h>
#include <linux/netfilter/x_tables.h>
#include <linux/netfilter/xt_sctp.h>
#include <linux/netfilter_ipv4/ip_tables.h>
#include <linux/netfilter_ipv6/ip6_tables.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Kiran Kumar Immidi");
MODULE_DESCRIPTION("Xtables: SCTP protocol packet match");
MODULE_ALIAS("ipt_sctp");
MODULE_ALIAS("ip6t_sctp");
#define SCCHECK(cond, option, flag, invflag) (!((flag) & (option)) \
|| (!!((invflag) & (option)) ^ (cond)))
static bool
match_flags(const struct xt_sctp_flag_info *flag_info,
const int flag_count,
u_int8_t chunktype,
u_int8_t chunkflags)
{
int i;
for (i = 0; i < flag_count; i++)
if (flag_info[i].chunktype == chunktype)
return (chunkflags & flag_info[i].flag_mask) == flag_info[i].flag;
return true;
}
static inline bool
match_packet(const struct sk_buff *skb,
unsigned int offset,
const struct xt_sctp_info *info,
bool *hotdrop)
{
u_int32_t chunkmapcopy[256 / sizeof (u_int32_t)];
const sctp_chunkhdr_t *sch;
sctp_chunkhdr_t _sch;
int chunk_match_type = info->chunk_match_type;
const struct xt_sctp_flag_info *flag_info = info->flag_info;
int flag_count = info->flag_count;
#ifdef DEBUG
int i = 0;
#endif
if (chunk_match_type == SCTP_CHUNK_MATCH_ALL)
SCTP_CHUNKMAP_COPY(chunkmapcopy, info->chunkmap);
do {
sch = skb_header_pointer(skb, offset, sizeof(_sch), &_sch);
if (sch == NULL || sch->length == 0) {
pr_debug("Dropping invalid SCTP packet.\n");
*hotdrop = true;
return false;
}
#ifdef DEBUG
pr_debug("Chunk num: %d\toffset: %d\ttype: %d\tlength: %d"
"\tflags: %x\n",
++i, offset, sch->type, htons(sch->length),
sch->flags);
#endif
offset += WORD_ROUND(ntohs(sch->length));
pr_debug("skb->len: %d\toffset: %d\n", skb->len, offset);
if (SCTP_CHUNKMAP_IS_SET(info->chunkmap, sch->type)) {
switch (chunk_match_type) {
case SCTP_CHUNK_MATCH_ANY:
if (match_flags(flag_info, flag_count,
sch->type, sch->flags)) {
return true;
}
break;
case SCTP_CHUNK_MATCH_ALL:
if (match_flags(flag_info, flag_count,
sch->type, sch->flags))
SCTP_CHUNKMAP_CLEAR(chunkmapcopy, sch->type);
break;
case SCTP_CHUNK_MATCH_ONLY:
if (!match_flags(flag_info, flag_count,
sch->type, sch->flags))
return false;
break;
}
} else {
switch (chunk_match_type) {
case SCTP_CHUNK_MATCH_ONLY:
return false;
}
}
} while (offset < skb->len);
switch (chunk_match_type) {
case SCTP_CHUNK_MATCH_ALL:
return SCTP_CHUNKMAP_IS_CLEAR(chunkmapcopy);
case SCTP_CHUNK_MATCH_ANY:
return false;
case SCTP_CHUNK_MATCH_ONLY:
return true;
}
/* This will never be reached, but required to stop compiler whine */
return false;
}
static bool
sctp_mt(const struct sk_buff *skb, struct xt_action_param *par)
{
const struct xt_sctp_info *info = par->matchinfo;
const sctp_sctphdr_t *sh;
sctp_sctphdr_t _sh;
if (par->fragoff != 0) {
pr_debug("Dropping non-first fragment.. FIXME\n");
return false;
}
sh = skb_header_pointer(skb, par->thoff, sizeof(_sh), &_sh);
if (sh == NULL) {
pr_debug("Dropping evil TCP offset=0 tinygram.\n");
par->hotdrop = true;
return false;
}
pr_debug("spt: %d\tdpt: %d\n", ntohs(sh->source), ntohs(sh->dest));
return SCCHECK(ntohs(sh->source) >= info->spts[0]
&& ntohs(sh->source) <= info->spts[1],
XT_SCTP_SRC_PORTS, info->flags, info->invflags)
&& SCCHECK(ntohs(sh->dest) >= info->dpts[0]
&& ntohs(sh->dest) <= info->dpts[1],
XT_SCTP_DEST_PORTS, info->flags, info->invflags)
&& SCCHECK(match_packet(skb, par->thoff + sizeof(sctp_sctphdr_t),
info, &par->hotdrop),
XT_SCTP_CHUNK_TYPES, info->flags, info->invflags);
}
static int sctp_mt_check(const struct xt_mtchk_param *par)
{
const struct xt_sctp_info *info = par->matchinfo;
if (info->flags & ~XT_SCTP_VALID_FLAGS)
return -EINVAL;
if (info->invflags & ~XT_SCTP_VALID_FLAGS)
return -EINVAL;
if (info->invflags & ~info->flags)
return -EINVAL;
if (!(info->flags & XT_SCTP_CHUNK_TYPES))
return 0;
if (info->chunk_match_type & (SCTP_CHUNK_MATCH_ALL |
SCTP_CHUNK_MATCH_ANY | SCTP_CHUNK_MATCH_ONLY))
return 0;
return -EINVAL;
}
static struct xt_match sctp_mt_reg[] __read_mostly = {
{
.name = "sctp",
.family = NFPROTO_IPV4,
.checkentry = sctp_mt_check,
.match = sctp_mt,
.matchsize = sizeof(struct xt_sctp_info),
.proto = IPPROTO_SCTP,
.me = THIS_MODULE
},
{
.name = "sctp",
.family = NFPROTO_IPV6,
.checkentry = sctp_mt_check,
.match = sctp_mt,
.matchsize = sizeof(struct xt_sctp_info),
.proto = IPPROTO_SCTP,
.me = THIS_MODULE
},
};
static int __init sctp_mt_init(void)
{
return xt_register_matches(sctp_mt_reg, ARRAY_SIZE(sctp_mt_reg));
}
static void __exit sctp_mt_exit(void)
{
xt_unregister_matches(sctp_mt_reg, ARRAY_SIZE(sctp_mt_reg));
}
module_init(sctp_mt_init);
module_exit(sctp_mt_exit);
| gpl-2.0 |
xhteam/kernel_imx | lib/reed_solomon/reed_solomon.c | 14415 | 12018 | /*
* lib/reed_solomon/reed_solomon.c
*
* Overview:
* Generic Reed Solomon encoder / decoder library
*
* Copyright (C) 2004 Thomas Gleixner (tglx@linutronix.de)
*
* Reed Solomon code lifted from reed solomon library written by Phil Karn
* Copyright 2002 Phil Karn, KA9Q
*
* $Id: rslib.c,v 1.7 2005/11/07 11:14:59 gleixner Exp $
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* Description:
*
* The generic Reed Solomon library provides runtime configurable
* encoding / decoding of RS codes.
* Each user must call init_rs to get a pointer to a rs_control
* structure for the given rs parameters. This structure is either
* generated or a already available matching control structure is used.
* If a structure is generated then the polynomial arrays for
* fast encoding / decoding are built. This can take some time so
* make sure not to call this function from a time critical path.
* Usually a module / driver should initialize the necessary
* rs_control structure on module / driver init and release it
* on exit.
* The encoding puts the calculated syndrome into a given syndrome
* buffer.
* The decoding is a two step process. The first step calculates
* the syndrome over the received (data + syndrome) and calls the
* second stage, which does the decoding / error correction itself.
* Many hw encoders provide a syndrome calculation over the received
* data + syndrome and can call the second stage directly.
*
*/
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/rslib.h>
#include <linux/slab.h>
#include <linux/mutex.h>
/* This list holds all currently allocated rs control structures */
static LIST_HEAD (rslist);
/* Protection for the list */
static DEFINE_MUTEX(rslistlock);
/**
* rs_init - Initialize a Reed-Solomon codec
* @symsize: symbol size, bits (1-8)
* @gfpoly: Field generator polynomial coefficients
* @gffunc: Field generator function
* @fcr: first root of RS code generator polynomial, index form
* @prim: primitive element to generate polynomial roots
* @nroots: RS code generator polynomial degree (number of roots)
*
* Allocate a control structure and the polynom arrays for faster
* en/decoding. Fill the arrays according to the given parameters.
*/
static struct rs_control *rs_init(int symsize, int gfpoly, int (*gffunc)(int),
int fcr, int prim, int nroots)
{
struct rs_control *rs;
int i, j, sr, root, iprim;
/* Allocate the control structure */
rs = kmalloc(sizeof (struct rs_control), GFP_KERNEL);
if (rs == NULL)
return NULL;
INIT_LIST_HEAD(&rs->list);
rs->mm = symsize;
rs->nn = (1 << symsize) - 1;
rs->fcr = fcr;
rs->prim = prim;
rs->nroots = nroots;
rs->gfpoly = gfpoly;
rs->gffunc = gffunc;
/* Allocate the arrays */
rs->alpha_to = kmalloc(sizeof(uint16_t) * (rs->nn + 1), GFP_KERNEL);
if (rs->alpha_to == NULL)
goto errrs;
rs->index_of = kmalloc(sizeof(uint16_t) * (rs->nn + 1), GFP_KERNEL);
if (rs->index_of == NULL)
goto erralp;
rs->genpoly = kmalloc(sizeof(uint16_t) * (rs->nroots + 1), GFP_KERNEL);
if(rs->genpoly == NULL)
goto erridx;
/* Generate Galois field lookup tables */
rs->index_of[0] = rs->nn; /* log(zero) = -inf */
rs->alpha_to[rs->nn] = 0; /* alpha**-inf = 0 */
if (gfpoly) {
sr = 1;
for (i = 0; i < rs->nn; i++) {
rs->index_of[sr] = i;
rs->alpha_to[i] = sr;
sr <<= 1;
if (sr & (1 << symsize))
sr ^= gfpoly;
sr &= rs->nn;
}
} else {
sr = gffunc(0);
for (i = 0; i < rs->nn; i++) {
rs->index_of[sr] = i;
rs->alpha_to[i] = sr;
sr = gffunc(sr);
}
}
/* If it's not primitive, exit */
if(sr != rs->alpha_to[0])
goto errpol;
/* Find prim-th root of 1, used in decoding */
for(iprim = 1; (iprim % prim) != 0; iprim += rs->nn);
/* prim-th root of 1, index form */
rs->iprim = iprim / prim;
/* Form RS code generator polynomial from its roots */
rs->genpoly[0] = 1;
for (i = 0, root = fcr * prim; i < nroots; i++, root += prim) {
rs->genpoly[i + 1] = 1;
/* Multiply rs->genpoly[] by @**(root + x) */
for (j = i; j > 0; j--) {
if (rs->genpoly[j] != 0) {
rs->genpoly[j] = rs->genpoly[j -1] ^
rs->alpha_to[rs_modnn(rs,
rs->index_of[rs->genpoly[j]] + root)];
} else
rs->genpoly[j] = rs->genpoly[j - 1];
}
/* rs->genpoly[0] can never be zero */
rs->genpoly[0] =
rs->alpha_to[rs_modnn(rs,
rs->index_of[rs->genpoly[0]] + root)];
}
/* convert rs->genpoly[] to index form for quicker encoding */
for (i = 0; i <= nroots; i++)
rs->genpoly[i] = rs->index_of[rs->genpoly[i]];
return rs;
/* Error exit */
errpol:
kfree(rs->genpoly);
erridx:
kfree(rs->index_of);
erralp:
kfree(rs->alpha_to);
errrs:
kfree(rs);
return NULL;
}
/**
* free_rs - Free the rs control structure, if it is no longer used
* @rs: the control structure which is not longer used by the
* caller
*/
void free_rs(struct rs_control *rs)
{
mutex_lock(&rslistlock);
rs->users--;
if(!rs->users) {
list_del(&rs->list);
kfree(rs->alpha_to);
kfree(rs->index_of);
kfree(rs->genpoly);
kfree(rs);
}
mutex_unlock(&rslistlock);
}
/**
* init_rs_internal - Find a matching or allocate a new rs control structure
* @symsize: the symbol size (number of bits)
* @gfpoly: the extended Galois field generator polynomial coefficients,
* with the 0th coefficient in the low order bit. The polynomial
* must be primitive;
* @gffunc: pointer to function to generate the next field element,
* or the multiplicative identity element if given 0. Used
* instead of gfpoly if gfpoly is 0
* @fcr: the first consecutive root of the rs code generator polynomial
* in index form
* @prim: primitive element to generate polynomial roots
* @nroots: RS code generator polynomial degree (number of roots)
*/
static struct rs_control *init_rs_internal(int symsize, int gfpoly,
int (*gffunc)(int), int fcr,
int prim, int nroots)
{
struct list_head *tmp;
struct rs_control *rs;
/* Sanity checks */
if (symsize < 1)
return NULL;
if (fcr < 0 || fcr >= (1<<symsize))
return NULL;
if (prim <= 0 || prim >= (1<<symsize))
return NULL;
if (nroots < 0 || nroots >= (1<<symsize))
return NULL;
mutex_lock(&rslistlock);
/* Walk through the list and look for a matching entry */
list_for_each(tmp, &rslist) {
rs = list_entry(tmp, struct rs_control, list);
if (symsize != rs->mm)
continue;
if (gfpoly != rs->gfpoly)
continue;
if (gffunc != rs->gffunc)
continue;
if (fcr != rs->fcr)
continue;
if (prim != rs->prim)
continue;
if (nroots != rs->nroots)
continue;
/* We have a matching one already */
rs->users++;
goto out;
}
/* Create a new one */
rs = rs_init(symsize, gfpoly, gffunc, fcr, prim, nroots);
if (rs) {
rs->users = 1;
list_add(&rs->list, &rslist);
}
out:
mutex_unlock(&rslistlock);
return rs;
}
/**
* init_rs - Find a matching or allocate a new rs control structure
* @symsize: the symbol size (number of bits)
* @gfpoly: the extended Galois field generator polynomial coefficients,
* with the 0th coefficient in the low order bit. The polynomial
* must be primitive;
* @fcr: the first consecutive root of the rs code generator polynomial
* in index form
* @prim: primitive element to generate polynomial roots
* @nroots: RS code generator polynomial degree (number of roots)
*/
struct rs_control *init_rs(int symsize, int gfpoly, int fcr, int prim,
int nroots)
{
return init_rs_internal(symsize, gfpoly, NULL, fcr, prim, nroots);
}
/**
* init_rs_non_canonical - Find a matching or allocate a new rs control
* structure, for fields with non-canonical
* representation
* @symsize: the symbol size (number of bits)
* @gffunc: pointer to function to generate the next field element,
* or the multiplicative identity element if given 0. Used
* instead of gfpoly if gfpoly is 0
* @fcr: the first consecutive root of the rs code generator polynomial
* in index form
* @prim: primitive element to generate polynomial roots
* @nroots: RS code generator polynomial degree (number of roots)
*/
struct rs_control *init_rs_non_canonical(int symsize, int (*gffunc)(int),
int fcr, int prim, int nroots)
{
return init_rs_internal(symsize, 0, gffunc, fcr, prim, nroots);
}
#ifdef CONFIG_REED_SOLOMON_ENC8
/**
* encode_rs8 - Calculate the parity for data values (8bit data width)
* @rs: the rs control structure
* @data: data field of a given type
* @len: data length
* @par: parity data, must be initialized by caller (usually all 0)
* @invmsk: invert data mask (will be xored on data)
*
* The parity uses a uint16_t data type to enable
* symbol size > 8. The calling code must take care of encoding of the
* syndrome result for storage itself.
*/
int encode_rs8(struct rs_control *rs, uint8_t *data, int len, uint16_t *par,
uint16_t invmsk)
{
#include "encode_rs.c"
}
EXPORT_SYMBOL_GPL(encode_rs8);
#endif
#ifdef CONFIG_REED_SOLOMON_DEC8
/**
* decode_rs8 - Decode codeword (8bit data width)
* @rs: the rs control structure
* @data: data field of a given type
* @par: received parity data field
* @len: data length
* @s: syndrome data field (if NULL, syndrome is calculated)
* @no_eras: number of erasures
* @eras_pos: position of erasures, can be NULL
* @invmsk: invert data mask (will be xored on data, not on parity!)
* @corr: buffer to store correction bitmask on eras_pos
*
* The syndrome and parity uses a uint16_t data type to enable
* symbol size > 8. The calling code must take care of decoding of the
* syndrome result and the received parity before calling this code.
* Returns the number of corrected bits or -EBADMSG for uncorrectable errors.
*/
int decode_rs8(struct rs_control *rs, uint8_t *data, uint16_t *par, int len,
uint16_t *s, int no_eras, int *eras_pos, uint16_t invmsk,
uint16_t *corr)
{
#include "decode_rs.c"
}
EXPORT_SYMBOL_GPL(decode_rs8);
#endif
#ifdef CONFIG_REED_SOLOMON_ENC16
/**
* encode_rs16 - Calculate the parity for data values (16bit data width)
* @rs: the rs control structure
* @data: data field of a given type
* @len: data length
* @par: parity data, must be initialized by caller (usually all 0)
* @invmsk: invert data mask (will be xored on data, not on parity!)
*
* Each field in the data array contains up to symbol size bits of valid data.
*/
int encode_rs16(struct rs_control *rs, uint16_t *data, int len, uint16_t *par,
uint16_t invmsk)
{
#include "encode_rs.c"
}
EXPORT_SYMBOL_GPL(encode_rs16);
#endif
#ifdef CONFIG_REED_SOLOMON_DEC16
/**
* decode_rs16 - Decode codeword (16bit data width)
* @rs: the rs control structure
* @data: data field of a given type
* @par: received parity data field
* @len: data length
* @s: syndrome data field (if NULL, syndrome is calculated)
* @no_eras: number of erasures
* @eras_pos: position of erasures, can be NULL
* @invmsk: invert data mask (will be xored on data, not on parity!)
* @corr: buffer to store correction bitmask on eras_pos
*
* Each field in the data array contains up to symbol size bits of valid data.
* Returns the number of corrected bits or -EBADMSG for uncorrectable errors.
*/
int decode_rs16(struct rs_control *rs, uint16_t *data, uint16_t *par, int len,
uint16_t *s, int no_eras, int *eras_pos, uint16_t invmsk,
uint16_t *corr)
{
#include "decode_rs.c"
}
EXPORT_SYMBOL_GPL(decode_rs16);
#endif
EXPORT_SYMBOL_GPL(init_rs);
EXPORT_SYMBOL_GPL(init_rs_non_canonical);
EXPORT_SYMBOL_GPL(free_rs);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Reed Solomon encoder/decoder");
MODULE_AUTHOR("Phil Karn, Thomas Gleixner");
| gpl-2.0 |
binkybear/furnace_kernel_caf_hammerhead | sound/soc/msm/qdsp6/q6voice.c | 80 | 122039 | /* Copyright (c) 2011-2013, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/slab.h>
#include <linux/kthread.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/uaccess.h>
#include <linux/wait.h>
#include <linux/mutex.h>
#include <asm/mach-types.h>
#include <mach/qdsp6v2/audio_acdb.h>
#include <mach/qdsp6v2/rtac.h>
#include "sound/apr_audio.h"
#include "sound/q6afe.h"
#include "q6voice.h"
#define TIMEOUT_MS 3000
#define CMD_STATUS_SUCCESS 0
#define CMD_STATUS_FAIL 1
#define CAL_BUFFER_SIZE 4096
#define NUM_CVP_CAL_BLOCKS 75
#define NUM_CVS_CAL_BLOCKS 15
#define CVP_CAL_SIZE (NUM_CVP_CAL_BLOCKS * CAL_BUFFER_SIZE)
#define CVS_CAL_SIZE (NUM_CVS_CAL_BLOCKS * CAL_BUFFER_SIZE)
#define VOICE_CAL_BUFFER_SIZE (CVP_CAL_SIZE + CVS_CAL_SIZE)
/* Total cal needed to support concurrent VOIP & VOLTE sessions */
/* Due to memory map issue on Q6 separate memory has to be used */
/* for VOIP & VOLTE */
#define TOTAL_VOICE_CAL_SIZE (NUM_VOICE_CAL_BUFFERS * VOICE_CAL_BUFFER_SIZE)
static struct common_data common;
static int voice_send_enable_vocproc_cmd(struct voice_data *v);
static int voice_send_netid_timing_cmd(struct voice_data *v);
static int voice_send_attach_vocproc_cmd(struct voice_data *v);
static int voice_send_set_device_cmd(struct voice_data *v);
static int voice_send_disable_vocproc_cmd(struct voice_data *v);
static int voice_send_vol_index_cmd(struct voice_data *v);
static int voice_send_cvp_map_memory_cmd(struct voice_data *v,
uint32_t paddr, uint32_t mem_size);
static int voice_send_cvp_unmap_memory_cmd(struct voice_data *v,
uint32_t paddr);
static int voice_send_cvs_map_memory_cmd(struct voice_data *v);
static int voice_send_cvs_unmap_memory_cmd(struct voice_data *v);
static int voice_send_cvs_register_cal_cmd(struct voice_data *v);
static int voice_send_cvs_deregister_cal_cmd(struct voice_data *v);
static int voice_send_cvp_register_cal_cmd(struct voice_data *v);
static int voice_send_cvp_deregister_cal_cmd(struct voice_data *v);
static int voice_send_cvp_register_vol_cal_table_cmd(struct voice_data *v);
static int voice_send_cvp_deregister_vol_cal_table_cmd(struct voice_data *v);
static int voice_send_set_widevoice_enable_cmd(struct voice_data *v);
static int voice_send_set_pp_enable_cmd(struct voice_data *v,
uint32_t module_id, int enable);
static int voice_cvs_stop_playback(struct voice_data *v);
static int voice_cvs_start_playback(struct voice_data *v);
static int voice_cvs_start_record(struct voice_data *v, uint32_t rec_mode);
static int voice_cvs_stop_record(struct voice_data *v);
static int32_t qdsp_mvm_callback(struct apr_client_data *data, void *priv);
static int32_t qdsp_cvs_callback(struct apr_client_data *data, void *priv);
static int32_t qdsp_cvp_callback(struct apr_client_data *data, void *priv);
static int voice_send_set_device_cmd_v2(struct voice_data *v);
static u16 voice_get_mvm_handle(struct voice_data *v)
{
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return 0;
}
pr_debug("%s: mvm_handle %d\n", __func__, v->mvm_handle);
return v->mvm_handle;
}
static void voice_set_mvm_handle(struct voice_data *v, u16 mvm_handle)
{
pr_debug("%s: mvm_handle %d\n", __func__, mvm_handle);
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return;
}
v->mvm_handle = mvm_handle;
}
static u16 voice_get_cvs_handle(struct voice_data *v)
{
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return 0;
}
pr_debug("%s: cvs_handle %d\n", __func__, v->cvs_handle);
return v->cvs_handle;
}
static void voice_set_cvs_handle(struct voice_data *v, u16 cvs_handle)
{
pr_debug("%s: cvs_handle %d\n", __func__, cvs_handle);
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return;
}
v->cvs_handle = cvs_handle;
}
static u16 voice_get_cvp_handle(struct voice_data *v)
{
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return 0;
}
pr_debug("%s: cvp_handle %d\n", __func__, v->cvp_handle);
return v->cvp_handle;
}
static void voice_set_cvp_handle(struct voice_data *v, u16 cvp_handle)
{
pr_debug("%s: cvp_handle %d\n", __func__, cvp_handle);
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return;
}
v->cvp_handle = cvp_handle;
}
char *voc_get_session_name(u16 session_id)
{
char *session_name = NULL;
if (session_id == common.voice[VOC_PATH_PASSIVE].session_id) {
session_name = VOICE_SESSION_NAME;
} else if (session_id ==
common.voice[VOC_PATH_VOLTE_PASSIVE].session_id) {
session_name = VOLTE_SESSION_NAME;
} else if (session_id == common.voice[VOC_PATH_FULL].session_id) {
session_name = VOIP_SESSION_NAME;
}
return session_name;
}
uint16_t voc_get_session_id(char *name)
{
u16 session_id = 0;
if (name != NULL) {
if (!strncmp(name, "Voice session", 13))
session_id = common.voice[VOC_PATH_PASSIVE].session_id;
else if (!strncmp(name, "VoLTE session", 13))
session_id =
common.voice[VOC_PATH_VOLTE_PASSIVE].session_id;
else if (!strncmp(name, "Voice2 session", 14))
session_id =
common.voice[VOC_PATH_VOICE2_PASSIVE].session_id;
else
session_id = common.voice[VOC_PATH_FULL].session_id;
pr_debug("%s: %s has session id 0x%x\n", __func__, name,
session_id);
}
return session_id;
}
static struct voice_data *voice_get_session(u16 session_id)
{
struct voice_data *v = NULL;
if ((session_id >= SESSION_ID_BASE) &&
(session_id < SESSION_ID_BASE + MAX_VOC_SESSIONS)) {
v = &common.voice[session_id - SESSION_ID_BASE];
}
pr_debug("%s: session_id 0x%x session handle 0x%x\n",
__func__, session_id, (unsigned int)v);
return v;
}
static bool is_voice_session(u16 session_id)
{
return (session_id == common.voice[VOC_PATH_PASSIVE].session_id);
}
static bool is_voip_session(u16 session_id)
{
return (session_id == common.voice[VOC_PATH_FULL].session_id);
}
static bool is_volte_session(u16 session_id)
{
return (session_id == common.voice[VOC_PATH_VOLTE_PASSIVE].session_id);
}
static bool is_voice2_session(u16 session_id)
{
return (session_id == common.voice[VOC_PATH_VOICE2_PASSIVE].session_id);
}
/* Only for memory allocated in the voice driver */
/* which includes voip & volte */
static int voice_get_cal_kernel_addr(int16_t session_id, int cal_type,
uint32_t *kvaddr)
{
int i, result = 0;
pr_debug("%s\n", __func__);
if (kvaddr == NULL) {
pr_err("%s: NULL pointer sent to function\n", __func__);
result = -EINVAL;
goto done;
} else if (is_voip_session(session_id)) {
i = VOIP_CAL;
} else if (is_volte_session(session_id)) {
i = VOLTE_CAL;
} else {
result = -EINVAL;
goto done;
}
if (common.voice_cal[i].cal_data[cal_type].kvaddr == 0) {
pr_err("%s: NULL pointer for session_id %d, type %d, cal_type %d\n",
__func__, session_id, i, cal_type);
result = -EFAULT;
goto done;
}
*kvaddr = common.voice_cal[i].cal_data[cal_type].kvaddr;
done:
return result;
}
/* Only for memory allocated in the voice driver */
/* which includes voip & volte */
static int voice_get_cal_phys_addr(int16_t session_id, int cal_type,
uint32_t *paddr)
{
int i, result = 0;
pr_debug("%s\n", __func__);
if (paddr == NULL) {
pr_err("%s: NULL pointer sent to function\n", __func__);
result = -EINVAL;
goto done;
} else if (is_voip_session(session_id)) {
i = VOIP_CAL;
} else if (is_volte_session(session_id)) {
i = VOLTE_CAL;
} else {
result = -EINVAL;
goto done;
}
if (common.voice_cal[i].cal_data[cal_type].paddr == 0) {
pr_err("%s: No addr for session_id %d, type %d, cal_type %d\n",
__func__, session_id, i, cal_type);
result = -EFAULT;
goto done;
}
*paddr = common.voice_cal[i].cal_data[cal_type].paddr;
done:
return result;
}
static int voice_apr_register(void)
{
pr_debug("%s\n", __func__);
mutex_lock(&common.common_lock);
/* register callback to APR */
if (common.apr_q6_mvm == NULL) {
pr_debug("%s: Start to register MVM callback\n", __func__);
common.apr_q6_mvm = apr_register("ADSP", "MVM",
qdsp_mvm_callback,
0xFFFFFFFF, &common);
if (common.apr_q6_mvm == NULL) {
pr_err("%s: Unable to register MVM\n", __func__);
goto err;
}
}
if (common.apr_q6_cvs == NULL) {
pr_debug("%s: Start to register CVS callback\n", __func__);
common.apr_q6_cvs = apr_register("ADSP", "CVS",
qdsp_cvs_callback,
0xFFFFFFFF, &common);
if (common.apr_q6_cvs == NULL) {
pr_err("%s: Unable to register CVS\n", __func__);
goto err;
}
rtac_set_voice_handle(RTAC_CVS, common.apr_q6_cvs);
}
if (common.apr_q6_cvp == NULL) {
pr_debug("%s: Start to register CVP callback\n", __func__);
common.apr_q6_cvp = apr_register("ADSP", "CVP",
qdsp_cvp_callback,
0xFFFFFFFF, &common);
if (common.apr_q6_cvp == NULL) {
pr_err("%s: Unable to register CVP\n", __func__);
goto err;
}
rtac_set_voice_handle(RTAC_CVP, common.apr_q6_cvp);
}
mutex_unlock(&common.common_lock);
return 0;
err:
if (common.apr_q6_cvs != NULL) {
apr_deregister(common.apr_q6_cvs);
common.apr_q6_cvs = NULL;
rtac_set_voice_handle(RTAC_CVS, NULL);
}
if (common.apr_q6_mvm != NULL) {
apr_deregister(common.apr_q6_mvm);
common.apr_q6_mvm = NULL;
}
mutex_unlock(&common.common_lock);
return -ENODEV;
}
static int voice_send_dual_control_cmd(struct voice_data *v)
{
int ret = 0;
struct mvm_modem_dual_control_session_cmd mvm_voice_ctl_cmd;
void *apr_mvm;
u16 mvm_handle;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_mvm = common.apr_q6_mvm;
if (!apr_mvm) {
pr_err("%s: apr_mvm is NULL.\n", __func__);
return -EINVAL;
}
pr_debug("%s: VoLTE/Voice2 command to MVM\n", __func__);
if (is_volte_session(v->session_id) ||
is_voice2_session(v->session_id)) {
mvm_handle = voice_get_mvm_handle(v);
mvm_voice_ctl_cmd.hdr.hdr_field = APR_HDR_FIELD(
APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
mvm_voice_ctl_cmd.hdr.pkt_size = APR_PKT_SIZE(
APR_HDR_SIZE,
sizeof(mvm_voice_ctl_cmd) -
APR_HDR_SIZE);
pr_debug("%s: send mvm Voice Ctl pkt size = %d\n",
__func__, mvm_voice_ctl_cmd.hdr.pkt_size);
mvm_voice_ctl_cmd.hdr.src_port = v->session_id;
mvm_voice_ctl_cmd.hdr.dest_port = mvm_handle;
mvm_voice_ctl_cmd.hdr.token = 0;
mvm_voice_ctl_cmd.hdr.opcode =
VSS_IMVM_CMD_SET_POLICY_DUAL_CONTROL;
mvm_voice_ctl_cmd.voice_ctl.enable_flag = true;
v->mvm_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_voice_ctl_cmd);
if (ret < 0) {
pr_err("%s: Error sending MVM Voice CTL CMD\n",
__func__);
ret = -EINVAL;
goto fail;
}
ret = wait_event_timeout(v->mvm_wait,
(v->mvm_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
ret = -EINVAL;
goto fail;
}
}
ret = 0;
fail:
return ret;
}
static int voice_create_mvm_cvs_session(struct voice_data *v)
{
int ret = 0;
struct mvm_create_ctl_session_cmd mvm_session_cmd;
struct cvs_create_passive_ctl_session_cmd cvs_session_cmd;
struct cvs_create_full_ctl_session_cmd cvs_full_ctl_cmd;
struct mvm_attach_stream_cmd attach_stream_cmd;
void *apr_mvm, *apr_cvs, *apr_cvp;
u16 mvm_handle, cvs_handle, cvp_handle;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_mvm = common.apr_q6_mvm;
apr_cvs = common.apr_q6_cvs;
apr_cvp = common.apr_q6_cvp;
if (!apr_mvm || !apr_cvs || !apr_cvp) {
pr_err("%s: apr_mvm or apr_cvs or apr_cvp is NULL\n", __func__);
return -EINVAL;
}
mvm_handle = voice_get_mvm_handle(v);
cvs_handle = voice_get_cvs_handle(v);
cvp_handle = voice_get_cvp_handle(v);
pr_debug("%s: mvm_hdl=%d, cvs_hdl=%d\n", __func__,
mvm_handle, cvs_handle);
/* send cmd to create mvm session and wait for response */
if (!mvm_handle) {
if (is_voice_session(v->session_id) ||
is_volte_session(v->session_id) ||
is_voice2_session(v->session_id)) {
mvm_session_cmd.hdr.hdr_field = APR_HDR_FIELD(
APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
mvm_session_cmd.hdr.pkt_size = APR_PKT_SIZE(
APR_HDR_SIZE,
sizeof(mvm_session_cmd) -
APR_HDR_SIZE);
pr_debug("%s: send mvm create session pkt size = %d\n",
__func__, mvm_session_cmd.hdr.pkt_size);
mvm_session_cmd.hdr.src_port = v->session_id;
mvm_session_cmd.hdr.dest_port = 0;
mvm_session_cmd.hdr.token = 0;
mvm_session_cmd.hdr.opcode =
VSS_IMVM_CMD_CREATE_PASSIVE_CONTROL_SESSION;
if (is_volte_session(v->session_id)) {
strlcpy(mvm_session_cmd.mvm_session.name,
"default volte voice",
sizeof(mvm_session_cmd.mvm_session.name) - 1);
} else if (is_voice2_session(v->session_id)) {
strlcpy(mvm_session_cmd.mvm_session.name,
"default modem voice2",
sizeof(mvm_session_cmd.mvm_session.name));
} else {
strlcpy(mvm_session_cmd.mvm_session.name,
"default modem voice",
sizeof(mvm_session_cmd.mvm_session.name) - 1);
}
v->mvm_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_mvm,
(uint32_t *) &mvm_session_cmd);
if (ret < 0) {
pr_err("%s: Error sending MVM_CONTROL_SESSION\n",
__func__);
goto fail;
}
ret = wait_event_timeout(v->mvm_wait,
(v->mvm_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
} else {
pr_debug("%s: creating MVM full ctrl\n", __func__);
mvm_session_cmd.hdr.hdr_field =
APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
mvm_session_cmd.hdr.pkt_size =
APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(mvm_session_cmd) -
APR_HDR_SIZE);
mvm_session_cmd.hdr.src_port = v->session_id;
mvm_session_cmd.hdr.dest_port = 0;
mvm_session_cmd.hdr.token = 0;
mvm_session_cmd.hdr.opcode =
VSS_IMVM_CMD_CREATE_FULL_CONTROL_SESSION;
strlcpy(mvm_session_cmd.mvm_session.name,
"default voip",
sizeof(mvm_session_cmd.mvm_session.name));
v->mvm_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_mvm,
(uint32_t *) &mvm_session_cmd);
if (ret < 0) {
pr_err("Fail in sending MVM_CONTROL_SESSION\n");
goto fail;
}
ret = wait_event_timeout(v->mvm_wait,
(v->mvm_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
}
/* Get the created MVM handle. */
mvm_handle = voice_get_mvm_handle(v);
}
/* send cmd to create cvs session */
if (!cvs_handle) {
if (is_voice_session(v->session_id) ||
is_volte_session(v->session_id) ||
is_voice2_session(v->session_id)) {
pr_debug("%s: creating CVS passive session\n",
__func__);
cvs_session_cmd.hdr.hdr_field = APR_HDR_FIELD(
APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
cvs_session_cmd.hdr.pkt_size =
APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvs_session_cmd) -
APR_HDR_SIZE);
cvs_session_cmd.hdr.src_port = v->session_id;
cvs_session_cmd.hdr.dest_port = 0;
cvs_session_cmd.hdr.token = 0;
cvs_session_cmd.hdr.opcode =
VSS_ISTREAM_CMD_CREATE_PASSIVE_CONTROL_SESSION;
if (is_volte_session(v->session_id)) {
strlcpy(cvs_session_cmd.cvs_session.name,
"default volte voice",
sizeof(cvs_session_cmd.cvs_session.name) - 1);
} else if (is_voice2_session(v->session_id)) {
strlcpy(cvs_session_cmd.cvs_session.name,
"default modem voice2",
sizeof(cvs_session_cmd.cvs_session.name));
} else {
strlcpy(cvs_session_cmd.cvs_session.name,
"default modem voice",
sizeof(cvs_session_cmd.cvs_session.name) - 1);
}
v->cvs_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvs,
(uint32_t *) &cvs_session_cmd);
if (ret < 0) {
pr_err("Fail in sending STREAM_CONTROL_SESSION\n");
goto fail;
}
ret = wait_event_timeout(v->cvs_wait,
(v->cvs_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
/* Get the created CVS handle. */
cvs_handle = voice_get_cvs_handle(v);
} else {
pr_debug("%s: creating CVS full session\n", __func__);
cvs_full_ctl_cmd.hdr.hdr_field =
APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
cvs_full_ctl_cmd.hdr.pkt_size =
APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvs_full_ctl_cmd) -
APR_HDR_SIZE);
cvs_full_ctl_cmd.hdr.src_port = v->session_id;
cvs_full_ctl_cmd.hdr.dest_port = 0;
cvs_full_ctl_cmd.hdr.token = 0;
cvs_full_ctl_cmd.hdr.opcode =
VSS_ISTREAM_CMD_CREATE_FULL_CONTROL_SESSION;
cvs_full_ctl_cmd.cvs_session.direction = 2;
cvs_full_ctl_cmd.cvs_session.enc_media_type =
common.mvs_info.media_type;
cvs_full_ctl_cmd.cvs_session.dec_media_type =
common.mvs_info.media_type;
cvs_full_ctl_cmd.cvs_session.network_id =
common.mvs_info.network_type;
strlcpy(cvs_full_ctl_cmd.cvs_session.name,
"default q6 voice",
sizeof(cvs_full_ctl_cmd.cvs_session.name));
v->cvs_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvs,
(uint32_t *) &cvs_full_ctl_cmd);
if (ret < 0) {
pr_err("%s: Err %d sending CREATE_FULL_CTRL\n",
__func__, ret);
goto fail;
}
ret = wait_event_timeout(v->cvs_wait,
(v->cvs_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
/* Get the created CVS handle. */
cvs_handle = voice_get_cvs_handle(v);
/* Attach MVM to CVS. */
pr_debug("%s: Attach MVM to stream\n", __func__);
attach_stream_cmd.hdr.hdr_field =
APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
attach_stream_cmd.hdr.pkt_size =
APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(attach_stream_cmd) -
APR_HDR_SIZE);
attach_stream_cmd.hdr.src_port = v->session_id;
attach_stream_cmd.hdr.dest_port = mvm_handle;
attach_stream_cmd.hdr.token = 0;
attach_stream_cmd.hdr.opcode =
VSS_IMVM_CMD_ATTACH_STREAM;
attach_stream_cmd.attach_stream.handle = cvs_handle;
v->mvm_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_mvm,
(uint32_t *) &attach_stream_cmd);
if (ret < 0) {
pr_err("%s: Error %d sending ATTACH_STREAM\n",
__func__, ret);
goto fail;
}
ret = wait_event_timeout(v->mvm_wait,
(v->mvm_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
}
}
return 0;
fail:
return -EINVAL;
}
static int voice_destroy_mvm_cvs_session(struct voice_data *v)
{
int ret = 0;
struct mvm_detach_stream_cmd detach_stream;
struct apr_hdr mvm_destroy;
struct apr_hdr cvs_destroy;
void *apr_mvm, *apr_cvs;
u16 mvm_handle, cvs_handle;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_mvm = common.apr_q6_mvm;
apr_cvs = common.apr_q6_cvs;
if (!apr_mvm || !apr_cvs) {
pr_err("%s: apr_mvm or apr_cvs is NULL\n", __func__);
return -EINVAL;
}
mvm_handle = voice_get_mvm_handle(v);
cvs_handle = voice_get_cvs_handle(v);
/* MVM, CVS sessions are destroyed only for Full control sessions. */
if (is_voip_session(v->session_id)) {
pr_debug("%s: MVM detach stream\n", __func__);
/* Detach voice stream. */
detach_stream.hdr.hdr_field =
APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
detach_stream.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(detach_stream) - APR_HDR_SIZE);
detach_stream.hdr.src_port = v->session_id;
detach_stream.hdr.dest_port = mvm_handle;
detach_stream.hdr.token = 0;
detach_stream.hdr.opcode = VSS_IMVM_CMD_DETACH_STREAM;
detach_stream.detach_stream.handle = cvs_handle;
v->mvm_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_mvm, (uint32_t *) &detach_stream);
if (ret < 0) {
pr_err("%s: Error %d sending DETACH_STREAM\n",
__func__, ret);
goto fail;
}
ret = wait_event_timeout(v->mvm_wait,
(v->mvm_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait event timeout\n", __func__);
goto fail;
}
/* Destroy CVS. */
pr_debug("%s: CVS destroy session\n", __func__);
cvs_destroy.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
cvs_destroy.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvs_destroy) - APR_HDR_SIZE);
cvs_destroy.src_port = v->session_id;
cvs_destroy.dest_port = cvs_handle;
cvs_destroy.token = 0;
cvs_destroy.opcode = APRV2_IBASIC_CMD_DESTROY_SESSION;
v->cvs_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_destroy);
if (ret < 0) {
pr_err("%s: Error %d sending CVS DESTROY\n",
__func__, ret);
goto fail;
}
ret = wait_event_timeout(v->cvs_wait,
(v->cvs_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait event timeout\n", __func__);
goto fail;
}
cvs_handle = 0;
voice_set_cvs_handle(v, cvs_handle);
/* Destroy MVM. */
pr_debug("MVM destroy session\n");
mvm_destroy.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
mvm_destroy.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(mvm_destroy) - APR_HDR_SIZE);
mvm_destroy.src_port = v->session_id;
mvm_destroy.dest_port = mvm_handle;
mvm_destroy.token = 0;
mvm_destroy.opcode = APRV2_IBASIC_CMD_DESTROY_SESSION;
v->mvm_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_destroy);
if (ret < 0) {
pr_err("%s: Error %d sending MVM DESTROY\n",
__func__, ret);
goto fail;
}
ret = wait_event_timeout(v->mvm_wait,
(v->mvm_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait event timeout\n", __func__);
goto fail;
}
mvm_handle = 0;
voice_set_mvm_handle(v, mvm_handle);
}
return 0;
fail:
return -EINVAL;
}
static int voice_send_tty_mode_cmd(struct voice_data *v)
{
int ret = 0;
struct mvm_set_tty_mode_cmd mvm_tty_mode_cmd;
void *apr_mvm;
u16 mvm_handle;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_mvm = common.apr_q6_mvm;
if (!apr_mvm) {
pr_err("%s: apr_mvm is NULL.\n", __func__);
return -EINVAL;
}
mvm_handle = voice_get_mvm_handle(v);
if (v->tty_mode) {
/* send tty mode cmd to mvm */
mvm_tty_mode_cmd.hdr.hdr_field = APR_HDR_FIELD(
APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
mvm_tty_mode_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(mvm_tty_mode_cmd) -
APR_HDR_SIZE);
pr_debug("%s: pkt size = %d\n",
__func__, mvm_tty_mode_cmd.hdr.pkt_size);
mvm_tty_mode_cmd.hdr.src_port = v->session_id;
mvm_tty_mode_cmd.hdr.dest_port = mvm_handle;
mvm_tty_mode_cmd.hdr.token = 0;
mvm_tty_mode_cmd.hdr.opcode = VSS_ISTREAM_CMD_SET_TTY_MODE;
mvm_tty_mode_cmd.tty_mode.mode = v->tty_mode;
pr_debug("tty mode =%d\n", mvm_tty_mode_cmd.tty_mode.mode);
v->mvm_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_tty_mode_cmd);
if (ret < 0) {
pr_err("%s: Error %d sending SET_TTY_MODE\n",
__func__, ret);
goto fail;
}
ret = wait_event_timeout(v->mvm_wait,
(v->mvm_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
}
return 0;
fail:
return -EINVAL;
}
static int voice_set_dtx(struct voice_data *v)
{
int ret = 0;
void *apr_cvs;
u16 cvs_handle;
struct cvs_set_enc_dtx_mode_cmd cvs_set_dtx;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_cvs = common.apr_q6_cvs;
if (!apr_cvs) {
pr_err("%s: apr_cvs is NULL.\n", __func__);
return -EINVAL;
}
cvs_handle = voice_get_cvs_handle(v);
/* Set DTX */
cvs_set_dtx.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
cvs_set_dtx.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvs_set_dtx) - APR_HDR_SIZE);
cvs_set_dtx.hdr.src_port = v->session_id;
cvs_set_dtx.hdr.dest_port = cvs_handle;
cvs_set_dtx.hdr.token = 0;
cvs_set_dtx.hdr.opcode = VSS_ISTREAM_CMD_SET_ENC_DTX_MODE;
cvs_set_dtx.dtx_mode.enable = common.mvs_info.dtx_mode;
pr_debug("%s: Setting DTX %d\n", __func__, common.mvs_info.dtx_mode);
v->cvs_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_set_dtx);
if (ret < 0) {
pr_err("%s: Error %d sending SET_DTX\n", __func__, ret);
return -EINVAL;
}
ret = wait_event_timeout(v->cvs_wait,
(v->cvs_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
return -EINVAL;
}
return 0;
}
static int voice_send_dtmf_rx_detection_cmd(struct voice_data *v,
uint32_t enable)
{
int ret = 0;
void *apr_cvs;
u16 cvs_handle;
struct cvs_set_rx_dtmf_detection_cmd cvs_dtmf_rx_detection;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_cvs = common.apr_q6_cvs;
if (!apr_cvs) {
pr_err("%s: apr_cvs is NULL.\n", __func__);
return -EINVAL;
}
cvs_handle = voice_get_cvs_handle(v);
/* Set SET_DTMF_RX_DETECTION */
cvs_dtmf_rx_detection.hdr.hdr_field =
APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
cvs_dtmf_rx_detection.hdr.pkt_size =
APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvs_dtmf_rx_detection) - APR_HDR_SIZE);
cvs_dtmf_rx_detection.hdr.src_port = v->session_id;
cvs_dtmf_rx_detection.hdr.dest_port = cvs_handle;
cvs_dtmf_rx_detection.hdr.token = 0;
cvs_dtmf_rx_detection.hdr.opcode =
VSS_ISTREAM_CMD_SET_RX_DTMF_DETECTION;
cvs_dtmf_rx_detection.cvs_dtmf_det.enable = enable;
v->cvs_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_dtmf_rx_detection);
if (ret < 0) {
pr_err("%s: Error %d sending SET_DTMF_RX_DETECTION\n",
__func__,
ret);
return -EINVAL;
}
ret = wait_event_timeout(v->cvs_wait,
(v->cvs_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
return -EINVAL;
}
return ret;
}
void voc_disable_dtmf_det_on_active_sessions(void)
{
struct voice_data *v = NULL;
int i;
for (i = 0; i < MAX_VOC_SESSIONS; i++) {
v = &common.voice[i];
if ((v->dtmf_rx_detect_en) &&
((v->voc_state == VOC_RUN) ||
(v->voc_state == VOC_CHANGE) ||
(v->voc_state == VOC_STANDBY))) {
pr_debug("disable dtmf det on ses_id=%d\n",
v->session_id);
voice_send_dtmf_rx_detection_cmd(v, 0);
}
}
}
int voc_enable_dtmf_rx_detection(uint16_t session_id, uint32_t enable)
{
struct voice_data *v = voice_get_session(session_id);
int ret = 0;
if (v == NULL) {
pr_err("%s: invalid session_id 0x%x\n", __func__, session_id);
return -EINVAL;
}
mutex_lock(&v->lock);
v->dtmf_rx_detect_en = enable;
if ((v->voc_state == VOC_RUN) ||
(v->voc_state == VOC_CHANGE) ||
(v->voc_state == VOC_STANDBY))
ret = voice_send_dtmf_rx_detection_cmd(v,
v->dtmf_rx_detect_en);
mutex_unlock(&v->lock);
return ret;
}
static int voice_config_cvs_vocoder(struct voice_data *v)
{
int ret = 0;
void *apr_cvs;
u16 cvs_handle;
/* Set media type. */
struct cvs_set_media_type_cmd cvs_set_media_cmd;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_cvs = common.apr_q6_cvs;
if (!apr_cvs) {
pr_err("%s: apr_cvs is NULL.\n", __func__);
return -EINVAL;
}
cvs_handle = voice_get_cvs_handle(v);
cvs_set_media_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
cvs_set_media_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvs_set_media_cmd) - APR_HDR_SIZE);
cvs_set_media_cmd.hdr.src_port = v->session_id;
cvs_set_media_cmd.hdr.dest_port = cvs_handle;
cvs_set_media_cmd.hdr.token = 0;
cvs_set_media_cmd.hdr.opcode = VSS_ISTREAM_CMD_SET_MEDIA_TYPE;
cvs_set_media_cmd.media_type.tx_media_id = common.mvs_info.media_type;
cvs_set_media_cmd.media_type.rx_media_id = common.mvs_info.media_type;
v->cvs_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_set_media_cmd);
if (ret < 0) {
pr_err("%s: Error %d sending SET_MEDIA_TYPE\n",
__func__, ret);
goto fail;
}
ret = wait_event_timeout(v->cvs_wait,
(v->cvs_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
/* Set encoder properties. */
switch (common.mvs_info.media_type) {
case VSS_MEDIA_ID_EVRC_MODEM:
case VSS_MEDIA_ID_4GV_NB_MODEM:
case VSS_MEDIA_ID_4GV_WB_MODEM: {
struct cvs_set_cdma_enc_minmax_rate_cmd cvs_set_cdma_rate;
pr_debug("Setting EVRC min-max rate\n");
cvs_set_cdma_rate.hdr.hdr_field =
APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
cvs_set_cdma_rate.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvs_set_cdma_rate) - APR_HDR_SIZE);
cvs_set_cdma_rate.hdr.src_port = v->session_id;
cvs_set_cdma_rate.hdr.dest_port = cvs_handle;
cvs_set_cdma_rate.hdr.token = 0;
cvs_set_cdma_rate.hdr.opcode =
VSS_ISTREAM_CMD_CDMA_SET_ENC_MINMAX_RATE;
cvs_set_cdma_rate.cdma_rate.min_rate = common.mvs_info.rate;
cvs_set_cdma_rate.cdma_rate.max_rate = common.mvs_info.rate;
v->cvs_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_set_cdma_rate);
if (ret < 0) {
pr_err("%s: Error %d sending SET_EVRC_MINMAX_RATE\n",
__func__, ret);
goto fail;
}
ret = wait_event_timeout(v->cvs_wait,
(v->cvs_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
break;
}
case VSS_MEDIA_ID_AMR_NB_MODEM: {
struct cvs_set_amr_enc_rate_cmd cvs_set_amr_rate;
pr_debug("Setting AMR rate\n");
cvs_set_amr_rate.hdr.hdr_field =
APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
cvs_set_amr_rate.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvs_set_amr_rate) - APR_HDR_SIZE);
cvs_set_amr_rate.hdr.src_port = v->session_id;
cvs_set_amr_rate.hdr.dest_port = cvs_handle;
cvs_set_amr_rate.hdr.token = 0;
cvs_set_amr_rate.hdr.opcode =
VSS_ISTREAM_CMD_VOC_AMR_SET_ENC_RATE;
cvs_set_amr_rate.amr_rate.mode = common.mvs_info.rate;
v->cvs_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_set_amr_rate);
if (ret < 0) {
pr_err("%s: Error %d sending SET_AMR_RATE\n",
__func__, ret);
goto fail;
}
ret = wait_event_timeout(v->cvs_wait,
(v->cvs_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
ret = voice_set_dtx(v);
if (ret < 0)
goto fail;
break;
}
case VSS_MEDIA_ID_AMR_WB_MODEM: {
struct cvs_set_amrwb_enc_rate_cmd cvs_set_amrwb_rate;
pr_debug("Setting AMR WB rate\n");
cvs_set_amrwb_rate.hdr.hdr_field =
APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
cvs_set_amrwb_rate.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvs_set_amrwb_rate) -
APR_HDR_SIZE);
cvs_set_amrwb_rate.hdr.src_port = v->session_id;
cvs_set_amrwb_rate.hdr.dest_port = cvs_handle;
cvs_set_amrwb_rate.hdr.token = 0;
cvs_set_amrwb_rate.hdr.opcode =
VSS_ISTREAM_CMD_VOC_AMRWB_SET_ENC_RATE;
cvs_set_amrwb_rate.amrwb_rate.mode = common.mvs_info.rate;
v->cvs_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_set_amrwb_rate);
if (ret < 0) {
pr_err("%s: Error %d sending SET_AMRWB_RATE\n",
__func__, ret);
goto fail;
}
ret = wait_event_timeout(v->cvs_wait,
(v->cvs_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
ret = voice_set_dtx(v);
if (ret < 0)
goto fail;
break;
}
case VSS_MEDIA_ID_G729:
case VSS_MEDIA_ID_G711_ALAW:
case VSS_MEDIA_ID_G711_MULAW: {
ret = voice_set_dtx(v);
break;
}
default:
/* Do nothing. */
break;
}
return 0;
fail:
return -EINVAL;
}
static int voice_send_start_voice_cmd(struct voice_data *v)
{
struct apr_hdr mvm_start_voice_cmd;
int ret = 0;
void *apr_mvm;
u16 mvm_handle;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_mvm = common.apr_q6_mvm;
if (!apr_mvm) {
pr_err("%s: apr_mvm is NULL.\n", __func__);
return -EINVAL;
}
mvm_handle = voice_get_mvm_handle(v);
mvm_start_voice_cmd.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
mvm_start_voice_cmd.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(mvm_start_voice_cmd) - APR_HDR_SIZE);
pr_debug("send mvm_start_voice_cmd pkt size = %d\n",
mvm_start_voice_cmd.pkt_size);
mvm_start_voice_cmd.src_port = v->session_id;
mvm_start_voice_cmd.dest_port = mvm_handle;
mvm_start_voice_cmd.token = 0;
mvm_start_voice_cmd.opcode = VSS_IMVM_CMD_START_VOICE;
v->mvm_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_start_voice_cmd);
if (ret < 0) {
pr_err("Fail in sending VSS_IMVM_CMD_START_VOICE\n");
goto fail;
}
ret = wait_event_timeout(v->mvm_wait,
(v->mvm_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
return 0;
fail:
return -EINVAL;
}
static int voice_send_disable_vocproc_cmd(struct voice_data *v)
{
struct apr_hdr cvp_disable_cmd;
int ret = 0;
void *apr_cvp;
u16 cvp_handle;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_cvp = common.apr_q6_cvp;
if (!apr_cvp) {
pr_err("%s: apr regist failed\n", __func__);
return -EINVAL;
}
cvp_handle = voice_get_cvp_handle(v);
/* disable vocproc and wait for respose */
cvp_disable_cmd.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
cvp_disable_cmd.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvp_disable_cmd) - APR_HDR_SIZE);
pr_debug("cvp_disable_cmd pkt size = %d, cvp_handle=%d\n",
cvp_disable_cmd.pkt_size, cvp_handle);
cvp_disable_cmd.src_port = v->session_id;
cvp_disable_cmd.dest_port = cvp_handle;
cvp_disable_cmd.token = 0;
cvp_disable_cmd.opcode = VSS_IVOCPROC_CMD_DISABLE;
v->cvp_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_disable_cmd);
if (ret < 0) {
pr_err("Fail in sending VSS_IVOCPROC_CMD_DISABLE\n");
goto fail;
}
ret = wait_event_timeout(v->cvp_wait,
(v->cvp_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
return 0;
fail:
return -EINVAL;
}
static void voc_get_tx_rx_topology(struct voice_data *v,
uint32_t *tx_topology_id,
uint32_t *rx_topology_id)
{
uint32_t tx_id = 0;
uint32_t rx_id = 0;
if (v->disable_topology) {
tx_id = VSS_IVOCPROC_TOPOLOGY_ID_NONE;
rx_id = VSS_IVOCPROC_TOPOLOGY_ID_NONE;
} else {
/* Use default topology if invalid value in ACDB */
tx_id = get_voice_tx_topology();
if (tx_id == 0)
tx_id = VSS_IVOCPROC_TOPOLOGY_ID_TX_SM_ECNS;
rx_id = get_voice_rx_topology();
if (rx_id == 0)
rx_id = VSS_IVOCPROC_TOPOLOGY_ID_RX_DEFAULT;
}
*tx_topology_id = tx_id;
*rx_topology_id = rx_id;
}
static int voice_send_set_device_cmd(struct voice_data *v)
{
struct cvp_set_device_cmd cvp_setdev_cmd;
int ret = 0;
void *apr_cvp;
u16 cvp_handle;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_cvp = common.apr_q6_cvp;
if (!apr_cvp) {
pr_err("%s: apr_cvp is NULL.\n", __func__);
return -EINVAL;
}
cvp_handle = voice_get_cvp_handle(v);
/* set device and wait for response */
cvp_setdev_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
cvp_setdev_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvp_setdev_cmd) - APR_HDR_SIZE);
pr_debug(" send create cvp setdev, pkt size = %d\n",
cvp_setdev_cmd.hdr.pkt_size);
cvp_setdev_cmd.hdr.src_port = v->session_id;
cvp_setdev_cmd.hdr.dest_port = cvp_handle;
cvp_setdev_cmd.hdr.token = 0;
cvp_setdev_cmd.hdr.opcode = VSS_IVOCPROC_CMD_SET_DEVICE;
voc_get_tx_rx_topology(v, &cvp_setdev_cmd.cvp_set_device.tx_topology_id,
&cvp_setdev_cmd.cvp_set_device.rx_topology_id);
cvp_setdev_cmd.cvp_set_device.tx_port_id = v->dev_tx.port_id;
cvp_setdev_cmd.cvp_set_device.rx_port_id = v->dev_rx.port_id;
pr_debug("topology=%d , tx_port_id=%d, rx_port_id=%d\n",
cvp_setdev_cmd.cvp_set_device.tx_topology_id,
cvp_setdev_cmd.cvp_set_device.tx_port_id,
cvp_setdev_cmd.cvp_set_device.rx_port_id);
v->cvp_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_setdev_cmd);
if (ret < 0) {
pr_err("Fail in sending VOCPROC_FULL_CONTROL_SESSION\n");
goto fail;
}
pr_debug("wait for cvp create session event\n");
ret = wait_event_timeout(v->cvp_wait,
(v->cvp_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
return 0;
fail:
return -EINVAL;
}
static int voice_send_set_device_cmd_v2(struct voice_data *v)
{
struct cvp_set_device_cmd_v2 cvp_setdev_cmd_v2;
int ret = 0;
void *apr_cvp;
u16 cvp_handle;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_cvp = common.apr_q6_cvp;
if (!apr_cvp) {
pr_err("%s: apr_cvp is NULL.\n", __func__);
return -EINVAL;
}
cvp_handle = voice_get_cvp_handle(v);
/* set device and wait for response */
cvp_setdev_cmd_v2.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
cvp_setdev_cmd_v2.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvp_setdev_cmd_v2) - APR_HDR_SIZE);
cvp_setdev_cmd_v2.hdr.src_port = v->session_id;
cvp_setdev_cmd_v2.hdr.dest_port = cvp_handle;
cvp_setdev_cmd_v2.hdr.token = 0;
cvp_setdev_cmd_v2.hdr.opcode = VSS_IVOCPROC_CMD_SET_DEVICE_V2;
voc_get_tx_rx_topology(v,
&cvp_setdev_cmd_v2.cvp_set_device_v2.tx_topology_id,
&cvp_setdev_cmd_v2.cvp_set_device_v2.rx_topology_id);
cvp_setdev_cmd_v2.cvp_set_device_v2.tx_port_id = v->dev_tx.port_id;
cvp_setdev_cmd_v2.cvp_set_device_v2.rx_port_id = v->dev_rx.port_id;
if (common.ec_ref_ext == true) {
cvp_setdev_cmd_v2.cvp_set_device_v2.vocproc_mode =
VSS_IVOCPROC_VOCPROC_MODE_EC_EXT_MIXING;
cvp_setdev_cmd_v2.cvp_set_device_v2.ec_ref_port_id =
common.ec_port_id;
} else {
cvp_setdev_cmd_v2.cvp_set_device_v2.vocproc_mode =
VSS_IVOCPROC_VOCPROC_MODE_EC_INT_MIXING;
cvp_setdev_cmd_v2.cvp_set_device_v2.ec_ref_port_id =
VSS_IVOCPROC_PORT_ID_NONE;
}
pr_debug("%s:topology=%d , tx_port_id=%d, rx_port_id=%d\n"
"ec_ref_port_id = %x\n", __func__,
cvp_setdev_cmd_v2.cvp_set_device_v2.tx_topology_id,
cvp_setdev_cmd_v2.cvp_set_device_v2.tx_port_id,
cvp_setdev_cmd_v2.cvp_set_device_v2.rx_port_id,
cvp_setdev_cmd_v2.cvp_set_device_v2.ec_ref_port_id);
v->cvp_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_setdev_cmd_v2);
if (ret < 0) {
pr_err("Fail in sending VOCPROC_FULL_CONTROL_SESSION\n");
goto fail;
}
pr_debug("wait for cvp create session event\n");
ret = wait_event_timeout(v->cvp_wait,
(v->cvp_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
return 0;
fail:
return -EINVAL;
}
static int voice_send_stop_voice_cmd(struct voice_data *v)
{
struct apr_hdr mvm_stop_voice_cmd;
int ret = 0;
void *apr_mvm;
u16 mvm_handle;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_mvm = common.apr_q6_mvm;
if (!apr_mvm) {
pr_err("%s: apr_mvm is NULL.\n", __func__);
return -EINVAL;
}
mvm_handle = voice_get_mvm_handle(v);
mvm_stop_voice_cmd.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
mvm_stop_voice_cmd.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(mvm_stop_voice_cmd) - APR_HDR_SIZE);
pr_debug("send mvm_stop_voice_cmd pkt size = %d\n",
mvm_stop_voice_cmd.pkt_size);
mvm_stop_voice_cmd.src_port = v->session_id;
mvm_stop_voice_cmd.dest_port = mvm_handle;
mvm_stop_voice_cmd.token = 0;
mvm_stop_voice_cmd.opcode = VSS_IMVM_CMD_STOP_VOICE;
v->mvm_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_stop_voice_cmd);
if (ret < 0) {
pr_err("Fail in sending VSS_IMVM_CMD_STOP_VOICE\n");
goto fail;
}
ret = wait_event_timeout(v->mvm_wait,
(v->mvm_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
return 0;
fail:
return -EINVAL;
}
static int voice_send_cvs_register_cal_cmd(struct voice_data *v)
{
struct cvs_register_cal_data_cmd cvs_reg_cal_cmd;
struct acdb_cal_block cal_block;
int ret = 0;
void *apr_cvs;
u16 cvs_handle;
uint32_t cal_paddr = 0;
uint32_t cal_buf = 0;
/* get the cvs cal data */
get_all_vocstrm_cal(&cal_block);
if (cal_block.cal_size == 0)
goto fail;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_cvs = common.apr_q6_cvs;
if (!apr_cvs) {
pr_err("%s: apr_cvs is NULL.\n", __func__);
return -EINVAL;
}
if (is_volte_session(v->session_id) ||
is_voip_session(v->session_id)) {
ret = voice_get_cal_phys_addr(v->session_id, CVS_CAL,
&cal_paddr);
if (ret < 0)
return ret;
ret = voice_get_cal_kernel_addr(v->session_id, CVS_CAL,
&cal_buf);
if (ret < 0)
return ret;
memcpy((void *)cal_buf, (void *)cal_block.cal_kvaddr,
cal_block.cal_size);
} else {
cal_paddr = cal_block.cal_paddr;
}
cvs_handle = voice_get_cvs_handle(v);
/* fill in the header */
cvs_reg_cal_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
cvs_reg_cal_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvs_reg_cal_cmd) - APR_HDR_SIZE);
cvs_reg_cal_cmd.hdr.src_port = v->session_id;
cvs_reg_cal_cmd.hdr.dest_port = cvs_handle;
cvs_reg_cal_cmd.hdr.token = 0;
cvs_reg_cal_cmd.hdr.opcode = VSS_ISTREAM_CMD_REGISTER_CALIBRATION_DATA;
cvs_reg_cal_cmd.cvs_cal_data.phys_addr = cal_paddr;
cvs_reg_cal_cmd.cvs_cal_data.mem_size = cal_block.cal_size;
v->cvs_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_reg_cal_cmd);
if (ret < 0) {
pr_err("Fail: sending cvs cal,\n");
goto fail;
}
ret = wait_event_timeout(v->cvs_wait,
(v->cvs_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
return 0;
fail:
return -EINVAL;
}
static int voice_send_cvs_deregister_cal_cmd(struct voice_data *v)
{
struct cvs_deregister_cal_data_cmd cvs_dereg_cal_cmd;
struct acdb_cal_block cal_block;
int ret = 0;
void *apr_cvs;
u16 cvs_handle;
get_all_vocstrm_cal(&cal_block);
if (cal_block.cal_size == 0)
return 0;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_cvs = common.apr_q6_cvs;
if (!apr_cvs) {
pr_err("%s: apr_cvs is NULL.\n", __func__);
return -EINVAL;
}
cvs_handle = voice_get_cvs_handle(v);
/* fill in the header */
cvs_dereg_cal_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
cvs_dereg_cal_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvs_dereg_cal_cmd) - APR_HDR_SIZE);
cvs_dereg_cal_cmd.hdr.src_port = v->session_id;
cvs_dereg_cal_cmd.hdr.dest_port = cvs_handle;
cvs_dereg_cal_cmd.hdr.token = 0;
cvs_dereg_cal_cmd.hdr.opcode =
VSS_ISTREAM_CMD_DEREGISTER_CALIBRATION_DATA;
v->cvs_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_dereg_cal_cmd);
if (ret < 0) {
pr_err("Fail: sending cvs cal,\n");
goto fail;
}
ret = wait_event_timeout(v->cvs_wait,
(v->cvs_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
return 0;
fail:
return -EINVAL;
}
static int voice_get_cal_paddr_size(struct voice_data *v, uint32_t *cal_paddr,
uint32_t *cal_size)
{
int ret = 0;
struct acdb_cal_block cal_block;
/* get all cvp cal data */
get_all_cvp_cal(&cal_block);
if (cal_block.cal_size == 0)
goto fail;
if (is_volte_session(v->session_id) ||
is_voip_session(v->session_id)) {
ret = voice_get_cal_phys_addr(v->session_id, CVP_CAL,
cal_paddr);
if (ret < 0)
return ret;
} else {
*cal_paddr = cal_block.cal_paddr;
}
if (cal_size)
*cal_size = cal_block.cal_size;
return 0;
fail:
return -EINVAL;
}
static int voice_send_cvp_map_memory_cmd(struct voice_data *v,
uint32_t paddr, uint32_t mem_size)
{
struct vss_map_memory_cmd cvp_map_mem_cmd;
int ret = 0;
void *apr_cvp;
u16 cvp_handle;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_cvp = common.apr_q6_cvp;
if (!apr_cvp) {
pr_err("%s: apr_cvp is NULL.\n", __func__);
return -EINVAL;
}
cvp_handle = voice_get_cvp_handle(v);
/* fill in the header */
cvp_map_mem_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
cvp_map_mem_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvp_map_mem_cmd) - APR_HDR_SIZE);
cvp_map_mem_cmd.hdr.src_port = v->session_id;
cvp_map_mem_cmd.hdr.dest_port = cvp_handle;
cvp_map_mem_cmd.hdr.token = 0;
cvp_map_mem_cmd.hdr.opcode = VSS_ICOMMON_CMD_MAP_MEMORY;
pr_debug("%s, phys_addr: 0x%x, mem_size: %d\n", __func__,
paddr, mem_size);
cvp_map_mem_cmd.vss_map_mem.phys_addr = paddr;
cvp_map_mem_cmd.vss_map_mem.mem_size = mem_size;
cvp_map_mem_cmd.vss_map_mem.mem_pool_id =
VSS_ICOMMON_MAP_MEMORY_SHMEM8_4K_POOL;
v->cvp_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_map_mem_cmd);
if (ret < 0) {
pr_err("Fail: mapping cvp memory,\n");
goto fail;
}
ret = wait_event_timeout(v->cvp_wait,
(v->cvp_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
return 0;
fail:
return -EINVAL;
}
static int voice_send_cvp_unmap_memory_cmd(struct voice_data *v,
uint32_t paddr)
{
struct vss_unmap_memory_cmd cvp_unmap_mem_cmd;
int ret = 0;
void *apr_cvp;
u16 cvp_handle;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_cvp = common.apr_q6_cvp;
if (!apr_cvp) {
pr_err("%s: apr_cvp is NULL.\n", __func__);
return -EINVAL;
}
cvp_handle = voice_get_cvp_handle(v);
/* fill in the header */
cvp_unmap_mem_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
cvp_unmap_mem_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvp_unmap_mem_cmd) - APR_HDR_SIZE);
cvp_unmap_mem_cmd.hdr.src_port = v->session_id;
cvp_unmap_mem_cmd.hdr.dest_port = cvp_handle;
cvp_unmap_mem_cmd.hdr.token = 0;
cvp_unmap_mem_cmd.hdr.opcode = VSS_ICOMMON_CMD_UNMAP_MEMORY;
cvp_unmap_mem_cmd.vss_unmap_mem.phys_addr = paddr;
v->cvp_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_unmap_mem_cmd);
if (ret < 0) {
pr_err("Fail: sending cvp cal,\n");
goto fail;
}
ret = wait_event_timeout(v->cvp_wait,
(v->cvp_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
return 0;
fail:
return -EINVAL;
}
static int voice_send_cvs_map_memory_cmd(struct voice_data *v)
{
struct vss_map_memory_cmd cvs_map_mem_cmd;
struct acdb_cal_block cal_block;
int ret = 0;
void *apr_cvs;
u16 cvs_handle;
uint32_t cal_paddr = 0;
/* get all cvs cal data */
get_all_vocstrm_cal(&cal_block);
if (cal_block.cal_size == 0)
goto fail;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_cvs = common.apr_q6_cvs;
if (!apr_cvs) {
pr_err("%s: apr_cvs is NULL.\n", __func__);
return -EINVAL;
}
if (is_volte_session(v->session_id) ||
is_voip_session(v->session_id)) {
ret = voice_get_cal_phys_addr(v->session_id, CVS_CAL,
&cal_paddr);
if (ret < 0)
return ret;
} else {
cal_paddr = cal_block.cal_paddr;
}
cvs_handle = voice_get_cvs_handle(v);
/* fill in the header */
cvs_map_mem_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
cvs_map_mem_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvs_map_mem_cmd) - APR_HDR_SIZE);
cvs_map_mem_cmd.hdr.src_port = v->session_id;
cvs_map_mem_cmd.hdr.dest_port = cvs_handle;
cvs_map_mem_cmd.hdr.token = 0;
cvs_map_mem_cmd.hdr.opcode = VSS_ICOMMON_CMD_MAP_MEMORY;
pr_debug("%s, phys_addr: 0x%x, mem_size: %d\n", __func__,
cal_paddr, cal_block.cal_size);
cvs_map_mem_cmd.vss_map_mem.phys_addr = cal_paddr;
cvs_map_mem_cmd.vss_map_mem.mem_size = cal_block.cal_size;
cvs_map_mem_cmd.vss_map_mem.mem_pool_id =
VSS_ICOMMON_MAP_MEMORY_SHMEM8_4K_POOL;
v->cvs_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_map_mem_cmd);
if (ret < 0) {
pr_err("Fail: sending cvs cal,\n");
goto fail;
}
ret = wait_event_timeout(v->cvs_wait,
(v->cvs_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
return 0;
fail:
return -EINVAL;
}
static int voice_send_cvs_unmap_memory_cmd(struct voice_data *v)
{
struct vss_unmap_memory_cmd cvs_unmap_mem_cmd;
struct acdb_cal_block cal_block;
int ret = 0;
void *apr_cvs;
u16 cvs_handle;
uint32_t cal_paddr = 0;
get_all_vocstrm_cal(&cal_block);
if (cal_block.cal_size == 0)
return 0;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_cvs = common.apr_q6_cvs;
if (!apr_cvs) {
pr_err("%s: apr_cvs is NULL.\n", __func__);
return -EINVAL;
}
if (is_volte_session(v->session_id) ||
is_voip_session(v->session_id)) {
ret = voice_get_cal_phys_addr(v->session_id, CVS_CAL,
&cal_paddr);
if (ret < 0)
return ret;
} else {
cal_paddr = cal_block.cal_paddr;
}
cvs_handle = voice_get_cvs_handle(v);
/* fill in the header */
cvs_unmap_mem_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
cvs_unmap_mem_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvs_unmap_mem_cmd) - APR_HDR_SIZE);
cvs_unmap_mem_cmd.hdr.src_port = v->session_id;
cvs_unmap_mem_cmd.hdr.dest_port = cvs_handle;
cvs_unmap_mem_cmd.hdr.token = 0;
cvs_unmap_mem_cmd.hdr.opcode = VSS_ICOMMON_CMD_UNMAP_MEMORY;
cvs_unmap_mem_cmd.vss_unmap_mem.phys_addr = cal_paddr;
v->cvs_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_unmap_mem_cmd);
if (ret < 0) {
pr_err("Fail: sending cvs cal,\n");
goto fail;
}
ret = wait_event_timeout(v->cvs_wait,
(v->cvs_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
return 0;
fail:
return -EINVAL;
}
static int voice_send_cvp_register_cal_cmd(struct voice_data *v)
{
struct cvp_register_cal_data_cmd cvp_reg_cal_cmd;
struct acdb_cal_block cal_block;
int ret = 0;
void *apr_cvp;
u16 cvp_handle;
uint32_t cal_paddr = 0;
uint32_t cal_buf = 0;
/* get the cvp cal data */
get_all_vocproc_cal(&cal_block);
if (cal_block.cal_size == 0)
goto fail;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_cvp = common.apr_q6_cvp;
if (!apr_cvp) {
pr_err("%s: apr_cvp is NULL.\n", __func__);
return -EINVAL;
}
if (is_volte_session(v->session_id) ||
is_voip_session(v->session_id)) {
ret = voice_get_cal_phys_addr(v->session_id, CVP_CAL,
&cal_paddr);
if (ret < 0)
return ret;
ret = voice_get_cal_kernel_addr(v->session_id, CVP_CAL,
&cal_buf);
if (ret < 0)
return ret;
memcpy((void *)cal_buf, (void *)cal_block.cal_kvaddr,
cal_block.cal_size);
} else {
cal_paddr = cal_block.cal_paddr;
}
cvp_handle = voice_get_cvp_handle(v);
/* fill in the header */
cvp_reg_cal_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
cvp_reg_cal_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvp_reg_cal_cmd) - APR_HDR_SIZE);
cvp_reg_cal_cmd.hdr.src_port = v->session_id;
cvp_reg_cal_cmd.hdr.dest_port = cvp_handle;
cvp_reg_cal_cmd.hdr.token = 0;
cvp_reg_cal_cmd.hdr.opcode = VSS_IVOCPROC_CMD_REGISTER_CALIBRATION_DATA;
cvp_reg_cal_cmd.cvp_cal_data.phys_addr = cal_paddr;
cvp_reg_cal_cmd.cvp_cal_data.mem_size = cal_block.cal_size;
v->cvp_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_reg_cal_cmd);
if (ret < 0) {
pr_err("Fail: sending cvp cal,\n");
goto fail;
}
ret = wait_event_timeout(v->cvp_wait,
(v->cvp_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
return 0;
fail:
return -EINVAL;
}
static int voice_send_cvp_deregister_cal_cmd(struct voice_data *v)
{
struct cvp_deregister_cal_data_cmd cvp_dereg_cal_cmd;
struct acdb_cal_block cal_block;
int ret = 0;
void *apr_cvp;
u16 cvp_handle;
get_all_vocproc_cal(&cal_block);
if (cal_block.cal_size == 0)
return 0;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_cvp = common.apr_q6_cvp;
if (!apr_cvp) {
pr_err("%s: apr_cvp is NULL.\n", __func__);
return -EINVAL;
}
cvp_handle = voice_get_cvp_handle(v);
/* fill in the header */
cvp_dereg_cal_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
cvp_dereg_cal_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvp_dereg_cal_cmd) - APR_HDR_SIZE);
cvp_dereg_cal_cmd.hdr.src_port = v->session_id;
cvp_dereg_cal_cmd.hdr.dest_port = cvp_handle;
cvp_dereg_cal_cmd.hdr.token = 0;
cvp_dereg_cal_cmd.hdr.opcode =
VSS_IVOCPROC_CMD_DEREGISTER_CALIBRATION_DATA;
v->cvp_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_dereg_cal_cmd);
if (ret < 0) {
pr_err("Fail: sending cvp cal,\n");
goto fail;
}
ret = wait_event_timeout(v->cvp_wait,
(v->cvp_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
return 0;
fail:
return -EINVAL;
}
static int voice_send_cvp_register_vol_cal_table_cmd(struct voice_data *v)
{
struct cvp_register_vol_cal_table_cmd cvp_reg_cal_tbl_cmd;
struct acdb_cal_block vol_block;
struct acdb_cal_block voc_block;
int ret = 0;
void *apr_cvp;
u16 cvp_handle;
uint32_t cal_paddr = 0;
uint32_t cal_buf = 0;
/* get the cvp vol cal data */
get_all_vocvol_cal(&vol_block);
get_all_vocproc_cal(&voc_block);
if (vol_block.cal_size == 0)
goto fail;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_cvp = common.apr_q6_cvp;
if (!apr_cvp) {
pr_err("%s: apr_cvp is NULL.\n", __func__);
return -EINVAL;
}
if (is_volte_session(v->session_id) ||
is_voip_session(v->session_id)) {
ret = voice_get_cal_phys_addr(v->session_id, CVP_CAL,
&cal_paddr);
if (ret < 0)
return ret;
cal_paddr += voc_block.cal_size;
ret = voice_get_cal_kernel_addr(v->session_id, CVP_CAL,
&cal_buf);
if (ret < 0)
return ret;
memcpy((void *)(cal_buf + voc_block.cal_size),
(void *)vol_block.cal_kvaddr, vol_block.cal_size);
} else {
cal_paddr = vol_block.cal_paddr;
}
cvp_handle = voice_get_cvp_handle(v);
/* fill in the header */
cvp_reg_cal_tbl_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
cvp_reg_cal_tbl_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvp_reg_cal_tbl_cmd) - APR_HDR_SIZE);
cvp_reg_cal_tbl_cmd.hdr.src_port = v->session_id;
cvp_reg_cal_tbl_cmd.hdr.dest_port = cvp_handle;
cvp_reg_cal_tbl_cmd.hdr.token = 0;
cvp_reg_cal_tbl_cmd.hdr.opcode =
VSS_IVOCPROC_CMD_REGISTER_VOLUME_CAL_TABLE;
cvp_reg_cal_tbl_cmd.cvp_vol_cal_tbl.phys_addr = cal_paddr;
cvp_reg_cal_tbl_cmd.cvp_vol_cal_tbl.mem_size = vol_block.cal_size;
v->cvp_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_reg_cal_tbl_cmd);
if (ret < 0) {
pr_err("Fail: sending cvp cal table,\n");
goto fail;
}
ret = wait_event_timeout(v->cvp_wait,
(v->cvp_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
return 0;
fail:
return -EINVAL;
}
static int voice_send_cvp_deregister_vol_cal_table_cmd(struct voice_data *v)
{
struct cvp_deregister_vol_cal_table_cmd cvp_dereg_cal_tbl_cmd;
struct acdb_cal_block cal_block;
int ret = 0;
void *apr_cvp;
u16 cvp_handle;
get_all_vocvol_cal(&cal_block);
if (cal_block.cal_size == 0)
return 0;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_cvp = common.apr_q6_cvp;
if (!apr_cvp) {
pr_err("%s: apr_cvp is NULL.\n", __func__);
return -EINVAL;
}
cvp_handle = voice_get_cvp_handle(v);
/* fill in the header */
cvp_dereg_cal_tbl_cmd.hdr.hdr_field = APR_HDR_FIELD(
APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
cvp_dereg_cal_tbl_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvp_dereg_cal_tbl_cmd) - APR_HDR_SIZE);
cvp_dereg_cal_tbl_cmd.hdr.src_port = v->session_id;
cvp_dereg_cal_tbl_cmd.hdr.dest_port = cvp_handle;
cvp_dereg_cal_tbl_cmd.hdr.token = 0;
cvp_dereg_cal_tbl_cmd.hdr.opcode =
VSS_IVOCPROC_CMD_DEREGISTER_VOLUME_CAL_TABLE;
v->cvp_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_dereg_cal_tbl_cmd);
if (ret < 0) {
pr_err("Fail: sending cvp cal table,\n");
goto fail;
}
ret = wait_event_timeout(v->cvp_wait,
(v->cvp_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
return 0;
fail:
return -EINVAL;
}
static int voice_send_set_widevoice_enable_cmd(struct voice_data *v)
{
struct mvm_set_widevoice_enable_cmd mvm_set_wv_cmd;
int ret = 0;
void *apr_mvm;
u16 mvm_handle;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_mvm = common.apr_q6_mvm;
if (!apr_mvm) {
pr_err("%s: apr_mvm is NULL.\n", __func__);
return -EINVAL;
}
mvm_handle = voice_get_mvm_handle(v);
/* fill in the header */
mvm_set_wv_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
mvm_set_wv_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(mvm_set_wv_cmd) - APR_HDR_SIZE);
mvm_set_wv_cmd.hdr.src_port = v->session_id;
mvm_set_wv_cmd.hdr.dest_port = mvm_handle;
mvm_set_wv_cmd.hdr.token = 0;
mvm_set_wv_cmd.hdr.opcode = VSS_IWIDEVOICE_CMD_SET_WIDEVOICE;
mvm_set_wv_cmd.vss_set_wv.enable = v->wv_enable;
v->mvm_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_set_wv_cmd);
if (ret < 0) {
pr_err("Fail: sending mvm set widevoice enable,\n");
goto fail;
}
ret = wait_event_timeout(v->mvm_wait,
(v->mvm_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
return 0;
fail:
return -EINVAL;
}
static int voice_send_set_pp_enable_cmd(struct voice_data *v,
uint32_t module_id, int enable)
{
struct cvs_set_pp_enable_cmd cvs_set_pp_cmd;
int ret = 0;
void *apr_cvs;
u16 cvs_handle;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_cvs = common.apr_q6_cvs;
if (!apr_cvs) {
pr_err("%s: apr_cvs is NULL.\n", __func__);
return -EINVAL;
}
cvs_handle = voice_get_cvs_handle(v);
/* fill in the header */
cvs_set_pp_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
cvs_set_pp_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvs_set_pp_cmd) - APR_HDR_SIZE);
cvs_set_pp_cmd.hdr.src_port = v->session_id;
cvs_set_pp_cmd.hdr.dest_port = cvs_handle;
cvs_set_pp_cmd.hdr.token = 0;
cvs_set_pp_cmd.hdr.opcode = VSS_ICOMMON_CMD_SET_UI_PROPERTY;
cvs_set_pp_cmd.vss_set_pp.module_id = module_id;
cvs_set_pp_cmd.vss_set_pp.param_id = VOICE_PARAM_MOD_ENABLE;
cvs_set_pp_cmd.vss_set_pp.param_size = MOD_ENABLE_PARAM_LEN;
cvs_set_pp_cmd.vss_set_pp.reserved = 0;
cvs_set_pp_cmd.vss_set_pp.enable = enable;
cvs_set_pp_cmd.vss_set_pp.reserved_field = 0;
pr_debug("voice_send_set_pp_enable_cmd, module_id=%d, enable=%d\n",
module_id, enable);
v->cvs_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_set_pp_cmd);
if (ret < 0) {
pr_err("Fail: sending cvs set slowtalk enable,\n");
goto fail;
}
ret = wait_event_timeout(v->cvs_wait,
(v->cvs_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
return 0;
fail:
return -EINVAL;
}
static int voice_setup_vocproc(struct voice_data *v)
{
struct cvp_create_full_ctl_session_cmd cvp_session_cmd;
int ret = 0;
void *apr_cvp;
uint32_t cal_paddr = 0;
uint32_t cal_size = 0;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_cvp = common.apr_q6_cvp;
if (!apr_cvp) {
pr_err("%s: apr_cvp is NULL.\n", __func__);
return -EINVAL;
}
/* create cvp session and wait for response */
cvp_session_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
cvp_session_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvp_session_cmd) - APR_HDR_SIZE);
pr_debug(" send create cvp session, pkt size = %d\n",
cvp_session_cmd.hdr.pkt_size);
cvp_session_cmd.hdr.src_port = v->session_id;
cvp_session_cmd.hdr.dest_port = 0;
cvp_session_cmd.hdr.token = 0;
cvp_session_cmd.hdr.opcode =
VSS_IVOCPROC_CMD_CREATE_FULL_CONTROL_SESSION;
voc_get_tx_rx_topology(v, &cvp_session_cmd.cvp_session.tx_topology_id,
&cvp_session_cmd.cvp_session.rx_topology_id);
cvp_session_cmd.cvp_session.direction = 2; /*tx and rx*/
cvp_session_cmd.cvp_session.network_id = VSS_NETWORK_ID_DEFAULT;
cvp_session_cmd.cvp_session.tx_port_id = v->dev_tx.port_id;
cvp_session_cmd.cvp_session.rx_port_id = v->dev_rx.port_id;
pr_debug("topology=%d net_id=%d, dir=%d tx_port_id=%d, rx_port_id=%d\n",
cvp_session_cmd.cvp_session.tx_topology_id,
cvp_session_cmd.cvp_session.network_id,
cvp_session_cmd.cvp_session.direction,
cvp_session_cmd.cvp_session.tx_port_id,
cvp_session_cmd.cvp_session.rx_port_id);
v->cvp_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_session_cmd);
if (ret < 0) {
pr_err("Fail in sending VOCPROC_FULL_CONTROL_SESSION\n");
goto fail;
}
ret = wait_event_timeout(v->cvp_wait,
(v->cvp_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
if (common.ec_ref_ext == true) {
ret = voice_send_set_device_cmd_v2(v);
if (ret < 0) {
pr_err("%s: set device V2 failed rc =%x\n",
__func__, ret);
goto fail;
}
}
/* send cvs cal */
ret = voice_send_cvs_map_memory_cmd(v);
if (!ret)
voice_send_cvs_register_cal_cmd(v);
/* send cvp and vol cal */
if (!voice_get_cal_paddr_size(v, &cal_paddr, &cal_size) &&
!voice_send_cvp_map_memory_cmd(v, cal_paddr, cal_size)) {
voice_send_cvp_register_cal_cmd(v);
voice_send_cvp_register_vol_cal_table_cmd(v);
}
/* enable vocproc */
ret = voice_send_enable_vocproc_cmd(v);
if (ret < 0)
goto fail;
/* attach vocproc */
ret = voice_send_attach_vocproc_cmd(v);
if (ret < 0)
goto fail;
/* send tty mode if tty device is used */
voice_send_tty_mode_cmd(v);
/* enable widevoice if wv_enable is set */
if (v->wv_enable)
voice_send_set_widevoice_enable_cmd(v);
/* enable slowtalk if st_enable is set */
if (v->st_enable)
voice_send_set_pp_enable_cmd(v, MODULE_ID_VOICE_MODULE_ST,
v->st_enable);
voice_send_set_pp_enable_cmd(v, MODULE_ID_VOICE_MODULE_FENS,
v->fens_enable);
if (is_voip_session(v->session_id))
voice_send_netid_timing_cmd(v);
/* Start in-call music delivery if this feature is enabled */
if (v->music_info.play_enable)
voice_cvs_start_playback(v);
/* Start in-call recording if this feature is enabled */
if (v->rec_info.rec_enable)
voice_cvs_start_record(v, v->rec_info.rec_mode);
if (v->dtmf_rx_detect_en)
voice_send_dtmf_rx_detection_cmd(v, v->dtmf_rx_detect_en);
rtac_add_voice(voice_get_cvs_handle(v),
voice_get_cvp_handle(v),
v->dev_rx.port_id, v->dev_tx.port_id,
v->session_id);
return 0;
fail:
return -EINVAL;
}
static int voice_send_enable_vocproc_cmd(struct voice_data *v)
{
int ret = 0;
struct apr_hdr cvp_enable_cmd;
void *apr_cvp;
u16 cvp_handle;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_cvp = common.apr_q6_cvp;
if (!apr_cvp) {
pr_err("%s: apr_cvp is NULL.\n", __func__);
return -EINVAL;
}
cvp_handle = voice_get_cvp_handle(v);
/* enable vocproc and wait for respose */
cvp_enable_cmd.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
cvp_enable_cmd.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvp_enable_cmd) - APR_HDR_SIZE);
pr_debug("cvp_enable_cmd pkt size = %d, cvp_handle=%d\n",
cvp_enable_cmd.pkt_size, cvp_handle);
cvp_enable_cmd.src_port = v->session_id;
cvp_enable_cmd.dest_port = cvp_handle;
cvp_enable_cmd.token = 0;
cvp_enable_cmd.opcode = VSS_IVOCPROC_CMD_ENABLE;
v->cvp_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_enable_cmd);
if (ret < 0) {
pr_err("Fail in sending VSS_IVOCPROC_CMD_ENABLE\n");
goto fail;
}
ret = wait_event_timeout(v->cvp_wait,
(v->cvp_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
return 0;
fail:
return -EINVAL;
}
static int voice_send_netid_timing_cmd(struct voice_data *v)
{
int ret = 0;
void *apr_mvm;
u16 mvm_handle;
struct mvm_set_network_cmd mvm_set_network;
struct mvm_set_voice_timing_cmd mvm_set_voice_timing;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_mvm = common.apr_q6_mvm;
if (!apr_mvm) {
pr_err("%s: apr_mvm is NULL.\n", __func__);
return -EINVAL;
}
mvm_handle = voice_get_mvm_handle(v);
ret = voice_config_cvs_vocoder(v);
if (ret < 0) {
pr_err("%s: Error %d configuring CVS voc",
__func__, ret);
goto fail;
}
/* Set network ID. */
pr_debug("Setting network ID\n");
mvm_set_network.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
mvm_set_network.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(mvm_set_network) - APR_HDR_SIZE);
mvm_set_network.hdr.src_port = v->session_id;
mvm_set_network.hdr.dest_port = mvm_handle;
mvm_set_network.hdr.token = 0;
mvm_set_network.hdr.opcode = VSS_ICOMMON_CMD_SET_NETWORK;
mvm_set_network.network.network_id = common.mvs_info.network_type;
v->mvm_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_set_network);
if (ret < 0) {
pr_err("%s: Error %d sending SET_NETWORK\n", __func__, ret);
goto fail;
}
ret = wait_event_timeout(v->mvm_wait,
(v->mvm_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
/* Set voice timing. */
pr_debug("Setting voice timing\n");
mvm_set_voice_timing.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
mvm_set_voice_timing.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(mvm_set_voice_timing) -
APR_HDR_SIZE);
mvm_set_voice_timing.hdr.src_port = v->session_id;
mvm_set_voice_timing.hdr.dest_port = mvm_handle;
mvm_set_voice_timing.hdr.token = 0;
mvm_set_voice_timing.hdr.opcode = VSS_ICOMMON_CMD_SET_VOICE_TIMING;
mvm_set_voice_timing.timing.mode = 0;
mvm_set_voice_timing.timing.enc_offset = 8000;
mvm_set_voice_timing.timing.dec_req_offset = 3300;
mvm_set_voice_timing.timing.dec_offset = 8300;
v->mvm_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_set_voice_timing);
if (ret < 0) {
pr_err("%s: Error %d sending SET_TIMING\n", __func__, ret);
goto fail;
}
ret = wait_event_timeout(v->mvm_wait,
(v->mvm_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
return 0;
fail:
return -EINVAL;
}
static int voice_send_attach_vocproc_cmd(struct voice_data *v)
{
int ret = 0;
struct mvm_attach_vocproc_cmd mvm_a_vocproc_cmd;
void *apr_mvm;
u16 mvm_handle, cvp_handle;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_mvm = common.apr_q6_mvm;
if (!apr_mvm) {
pr_err("%s: apr_mvm is NULL.\n", __func__);
return -EINVAL;
}
mvm_handle = voice_get_mvm_handle(v);
cvp_handle = voice_get_cvp_handle(v);
/* attach vocproc and wait for response */
mvm_a_vocproc_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
mvm_a_vocproc_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(mvm_a_vocproc_cmd) - APR_HDR_SIZE);
pr_debug("send mvm_a_vocproc_cmd pkt size = %d\n",
mvm_a_vocproc_cmd.hdr.pkt_size);
mvm_a_vocproc_cmd.hdr.src_port = v->session_id;
mvm_a_vocproc_cmd.hdr.dest_port = mvm_handle;
mvm_a_vocproc_cmd.hdr.token = 0;
mvm_a_vocproc_cmd.hdr.opcode = VSS_IMVM_CMD_ATTACH_VOCPROC;
mvm_a_vocproc_cmd.mvm_attach_cvp_handle.handle = cvp_handle;
v->mvm_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_a_vocproc_cmd);
if (ret < 0) {
pr_err("Fail in sending VSS_IMVM_CMD_ATTACH_VOCPROC\n");
goto fail;
}
ret = wait_event_timeout(v->mvm_wait,
(v->mvm_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
return 0;
fail:
return -EINVAL;
}
static int voice_destroy_vocproc(struct voice_data *v)
{
struct mvm_detach_vocproc_cmd mvm_d_vocproc_cmd;
struct apr_hdr cvp_destroy_session_cmd;
int ret = 0;
void *apr_mvm, *apr_cvp;
u16 mvm_handle, cvp_handle;
uint32_t paddr = 0;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_mvm = common.apr_q6_mvm;
apr_cvp = common.apr_q6_cvp;
if (!apr_mvm || !apr_cvp) {
pr_err("%s: apr_mvm or apr_cvp is NULL.\n", __func__);
return -EINVAL;
}
mvm_handle = voice_get_mvm_handle(v);
cvp_handle = voice_get_cvp_handle(v);
/* stop playback or recording */
v->music_info.force = 1;
voice_cvs_stop_playback(v);
voice_cvs_stop_record(v);
/* send stop voice cmd */
voice_send_stop_voice_cmd(v);
/* send stop dtmf detecton cmd */
if (v->dtmf_rx_detect_en)
voice_send_dtmf_rx_detection_cmd(v, 0);
/* Clear mute setting */
v->dev_tx.mute = common.default_mute_val;
/* clear disable topology setting */
v->disable_topology = false;
/* detach VOCPROC and wait for response from mvm */
mvm_d_vocproc_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
mvm_d_vocproc_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(mvm_d_vocproc_cmd) - APR_HDR_SIZE);
pr_debug("mvm_d_vocproc_cmd pkt size = %d\n",
mvm_d_vocproc_cmd.hdr.pkt_size);
mvm_d_vocproc_cmd.hdr.src_port = v->session_id;
mvm_d_vocproc_cmd.hdr.dest_port = mvm_handle;
mvm_d_vocproc_cmd.hdr.token = 0;
mvm_d_vocproc_cmd.hdr.opcode = VSS_IMVM_CMD_DETACH_VOCPROC;
mvm_d_vocproc_cmd.mvm_detach_cvp_handle.handle = cvp_handle;
v->mvm_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_d_vocproc_cmd);
if (ret < 0) {
pr_err("Fail in sending VSS_IMVM_CMD_DETACH_VOCPROC\n");
goto fail;
}
ret = wait_event_timeout(v->mvm_wait,
(v->mvm_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
/* deregister cvp and vol cal */
voice_send_cvp_deregister_vol_cal_table_cmd(v);
voice_send_cvp_deregister_cal_cmd(v);
if (!voice_get_cal_paddr_size(v, &paddr, NULL))
voice_send_cvp_unmap_memory_cmd(v, paddr);
/* deregister cvs cal */
voice_send_cvs_deregister_cal_cmd(v);
voice_send_cvs_unmap_memory_cmd(v);
/* destrop cvp session */
cvp_destroy_session_cmd.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
cvp_destroy_session_cmd.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvp_destroy_session_cmd) - APR_HDR_SIZE);
pr_debug("cvp_destroy_session_cmd pkt size = %d\n",
cvp_destroy_session_cmd.pkt_size);
cvp_destroy_session_cmd.src_port = v->session_id;
cvp_destroy_session_cmd.dest_port = cvp_handle;
cvp_destroy_session_cmd.token = 0;
cvp_destroy_session_cmd.opcode = APRV2_IBASIC_CMD_DESTROY_SESSION;
v->cvp_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_destroy_session_cmd);
if (ret < 0) {
pr_err("Fail in sending APRV2_IBASIC_CMD_DESTROY_SESSION\n");
goto fail;
}
ret = wait_event_timeout(v->cvp_wait,
(v->cvp_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
rtac_remove_voice(voice_get_cvs_handle(v));
cvp_handle = 0;
voice_set_cvp_handle(v, cvp_handle);
return 0;
fail:
return -EINVAL;
}
static int voice_send_mute_cmd(struct voice_data *v)
{
struct cvs_set_mute_cmd cvs_mute_cmd;
int ret = 0;
void *apr_cvs;
u16 cvs_handle;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_cvs = common.apr_q6_cvs;
if (!apr_cvs) {
pr_err("%s: apr_cvs is NULL.\n", __func__);
return -EINVAL;
}
cvs_handle = voice_get_cvs_handle(v);
/* send mute/unmute to cvs */
cvs_mute_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
cvs_mute_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvs_mute_cmd) - APR_HDR_SIZE);
cvs_mute_cmd.hdr.src_port = v->session_id;
cvs_mute_cmd.hdr.dest_port = cvs_handle;
cvs_mute_cmd.hdr.token = 0;
cvs_mute_cmd.hdr.opcode = VSS_ISTREAM_CMD_SET_MUTE;
cvs_mute_cmd.cvs_set_mute.direction = 0; /*tx*/
cvs_mute_cmd.cvs_set_mute.mute_flag = v->dev_tx.mute;
pr_info(" mute value =%d\n", cvs_mute_cmd.cvs_set_mute.mute_flag);
v->cvs_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_mute_cmd);
if (ret < 0) {
pr_err("Fail: send STREAM SET MUTE\n");
goto fail;
}
ret = wait_event_timeout(v->cvs_wait,
(v->cvs_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret)
pr_err("%s: wait_event timeout\n", __func__);
return 0;
fail:
return -EINVAL;
}
static int voice_send_rx_device_mute_cmd(struct voice_data *v)
{
struct cvp_set_mute_cmd cvp_mute_cmd;
int ret = 0;
void *apr_cvp;
u16 cvp_handle;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_cvp = common.apr_q6_cvp;
if (!apr_cvp) {
pr_err("%s: apr_cvp is NULL.\n", __func__);
return -EINVAL;
}
cvp_handle = voice_get_cvp_handle(v);
cvp_mute_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
cvp_mute_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvp_mute_cmd) - APR_HDR_SIZE);
cvp_mute_cmd.hdr.src_port = v->session_id;
cvp_mute_cmd.hdr.dest_port = cvp_handle;
cvp_mute_cmd.hdr.token = 0;
cvp_mute_cmd.hdr.opcode = VSS_IVOCPROC_CMD_SET_MUTE;
cvp_mute_cmd.cvp_set_mute.direction = 1;
cvp_mute_cmd.cvp_set_mute.mute_flag = v->dev_rx.mute;
v->cvp_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_mute_cmd);
if (ret < 0) {
pr_err("Fail in sending RX device mute cmd\n");
return -EINVAL;
}
ret = wait_event_timeout(v->cvp_wait,
(v->cvp_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
return -EINVAL;
}
return 0;
}
static int voice_send_vol_index_cmd(struct voice_data *v)
{
struct cvp_set_rx_volume_index_cmd cvp_vol_cmd;
int ret = 0;
void *apr_cvp;
u16 cvp_handle;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_cvp = common.apr_q6_cvp;
if (!apr_cvp) {
pr_err("%s: apr_cvp is NULL.\n", __func__);
return -EINVAL;
}
cvp_handle = voice_get_cvp_handle(v);
/* send volume index to cvp */
cvp_vol_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
cvp_vol_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvp_vol_cmd) - APR_HDR_SIZE);
cvp_vol_cmd.hdr.src_port = v->session_id;
cvp_vol_cmd.hdr.dest_port = cvp_handle;
cvp_vol_cmd.hdr.token = 0;
cvp_vol_cmd.hdr.opcode = VSS_IVOCPROC_CMD_SET_RX_VOLUME_INDEX;
cvp_vol_cmd.cvp_set_vol_idx.vol_index = v->dev_rx.volume;
v->cvp_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_vol_cmd);
if (ret < 0) {
pr_err("Fail in sending RX VOL INDEX\n");
return -EINVAL;
}
ret = wait_event_timeout(v->cvp_wait,
(v->cvp_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
return -EINVAL;
}
return 0;
}
static int voice_cvs_start_record(struct voice_data *v, uint32_t rec_mode)
{
int ret = 0;
void *apr_cvs;
u16 cvs_handle;
struct cvs_start_record_cmd cvs_start_record;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_cvs = common.apr_q6_cvs;
if (!apr_cvs) {
pr_err("%s: apr_cvs is NULL.\n", __func__);
return -EINVAL;
}
cvs_handle = voice_get_cvs_handle(v);
if (!v->rec_info.recording) {
cvs_start_record.hdr.hdr_field = APR_HDR_FIELD(
APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
cvs_start_record.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvs_start_record) - APR_HDR_SIZE);
cvs_start_record.hdr.src_port = v->session_id;
cvs_start_record.hdr.dest_port = cvs_handle;
cvs_start_record.hdr.token = 0;
cvs_start_record.hdr.opcode = VSS_ISTREAM_CMD_START_RECORD;
if (rec_mode == VOC_REC_UPLINK) {
cvs_start_record.rec_mode.rx_tap_point =
VSS_TAP_POINT_NONE;
cvs_start_record.rec_mode.tx_tap_point =
VSS_TAP_POINT_STREAM_END;
} else if (rec_mode == VOC_REC_DOWNLINK) {
cvs_start_record.rec_mode.rx_tap_point =
VSS_TAP_POINT_STREAM_END;
cvs_start_record.rec_mode.tx_tap_point =
VSS_TAP_POINT_NONE;
} else if (rec_mode == VOC_REC_BOTH) {
cvs_start_record.rec_mode.rx_tap_point =
VSS_TAP_POINT_STREAM_END;
cvs_start_record.rec_mode.tx_tap_point =
VSS_TAP_POINT_STREAM_END;
} else {
pr_err("%s: Invalid in-call rec_mode %d\n", __func__,
rec_mode);
ret = -EINVAL;
goto fail;
}
v->cvs_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_start_record);
if (ret < 0) {
pr_err("%s: Error %d sending START_RECORD\n", __func__,
ret);
goto fail;
}
ret = wait_event_timeout(v->cvs_wait,
(v->cvs_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
v->rec_info.recording = 1;
} else {
pr_debug("%s: Start record already sent\n", __func__);
}
return 0;
fail:
return ret;
}
static int voice_cvs_stop_record(struct voice_data *v)
{
int ret = 0;
void *apr_cvs;
u16 cvs_handle;
struct apr_hdr cvs_stop_record;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_cvs = common.apr_q6_cvs;
if (!apr_cvs) {
pr_err("%s: apr_cvs is NULL.\n", __func__);
return -EINVAL;
}
cvs_handle = voice_get_cvs_handle(v);
if (v->rec_info.recording) {
cvs_stop_record.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
cvs_stop_record.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvs_stop_record) - APR_HDR_SIZE);
cvs_stop_record.src_port = v->session_id;
cvs_stop_record.dest_port = cvs_handle;
cvs_stop_record.token = 0;
cvs_stop_record.opcode = VSS_ISTREAM_CMD_STOP_RECORD;
v->cvs_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_stop_record);
if (ret < 0) {
pr_err("%s: Error %d sending STOP_RECORD\n",
__func__, ret);
goto fail;
}
ret = wait_event_timeout(v->cvs_wait,
(v->cvs_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
v->rec_info.recording = 0;
} else {
pr_debug("%s: Stop record already sent\n", __func__);
}
return 0;
fail:
return ret;
}
int voc_start_record(uint32_t port_id, uint32_t set)
{
int ret = 0;
int rec_mode = 0;
u16 cvs_handle;
int i, rec_set = 0;
for (i = 0; i < MAX_VOC_SESSIONS; i++) {
struct voice_data *v = &common.voice[i];
pr_debug("%s: i:%d port_id: %d, set: %d\n",
__func__, i, port_id, set);
mutex_lock(&v->lock);
rec_mode = v->rec_info.rec_mode;
rec_set = set;
if (set) {
if ((v->rec_route_state.ul_flag != 0) &&
(v->rec_route_state.dl_flag != 0)) {
pr_debug("%s: i=%d, rec mode already set.\n",
__func__, i);
mutex_unlock(&v->lock);
if (i < MAX_VOC_SESSIONS)
continue;
else
return 0;
}
if (port_id == VOICE_RECORD_TX) {
if ((v->rec_route_state.ul_flag == 0)
&& (v->rec_route_state.dl_flag == 0)) {
rec_mode = VOC_REC_UPLINK;
v->rec_route_state.ul_flag = 1;
} else if ((v->rec_route_state.ul_flag == 0)
&& (v->rec_route_state.dl_flag != 0)) {
voice_cvs_stop_record(v);
rec_mode = VOC_REC_BOTH;
v->rec_route_state.ul_flag = 1;
}
} else if (port_id == VOICE_RECORD_RX) {
if ((v->rec_route_state.ul_flag == 0)
&& (v->rec_route_state.dl_flag == 0)) {
rec_mode = VOC_REC_DOWNLINK;
v->rec_route_state.dl_flag = 1;
} else if ((v->rec_route_state.ul_flag != 0)
&& (v->rec_route_state.dl_flag == 0)) {
voice_cvs_stop_record(v);
rec_mode = VOC_REC_BOTH;
v->rec_route_state.dl_flag = 1;
}
}
rec_set = 1;
} else {
if ((v->rec_route_state.ul_flag == 0) &&
(v->rec_route_state.dl_flag == 0)) {
pr_debug("%s: i=%d, rec already stops.\n",
__func__, i);
mutex_unlock(&v->lock);
if (i < MAX_VOC_SESSIONS)
continue;
else
return 0;
}
if (port_id == VOICE_RECORD_TX) {
if ((v->rec_route_state.ul_flag != 0)
&& (v->rec_route_state.dl_flag == 0)) {
v->rec_route_state.ul_flag = 0;
rec_set = 0;
} else if ((v->rec_route_state.ul_flag != 0)
&& (v->rec_route_state.dl_flag != 0)) {
voice_cvs_stop_record(v);
v->rec_route_state.ul_flag = 0;
rec_mode = VOC_REC_DOWNLINK;
rec_set = 1;
}
} else if (port_id == VOICE_RECORD_RX) {
if ((v->rec_route_state.ul_flag == 0)
&& (v->rec_route_state.dl_flag != 0)) {
v->rec_route_state.dl_flag = 0;
rec_set = 0;
} else if ((v->rec_route_state.ul_flag != 0)
&& (v->rec_route_state.dl_flag != 0)) {
voice_cvs_stop_record(v);
v->rec_route_state.dl_flag = 0;
rec_mode = VOC_REC_UPLINK;
rec_set = 1;
}
}
}
pr_debug("%s: i=%d, mode =%d, set =%d\n", __func__,
i, rec_mode, rec_set);
cvs_handle = voice_get_cvs_handle(v);
if (cvs_handle != 0) {
if (rec_set)
ret = voice_cvs_start_record(v, rec_mode);
else
ret = voice_cvs_stop_record(v);
}
/* Cache the value */
v->rec_info.rec_enable = rec_set;
v->rec_info.rec_mode = rec_mode;
mutex_unlock(&v->lock);
}
return ret;
}
static int voice_cvs_start_playback(struct voice_data *v)
{
int ret = 0;
struct apr_hdr cvs_start_playback;
void *apr_cvs;
u16 cvs_handle;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_cvs = common.apr_q6_cvs;
if (!apr_cvs) {
pr_err("%s: apr_cvs is NULL.\n", __func__);
return -EINVAL;
}
cvs_handle = voice_get_cvs_handle(v);
if (!v->music_info.playing && v->music_info.count) {
cvs_start_playback.hdr_field = APR_HDR_FIELD(
APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
cvs_start_playback.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvs_start_playback) - APR_HDR_SIZE);
cvs_start_playback.src_port = v->session_id;
cvs_start_playback.dest_port = cvs_handle;
cvs_start_playback.token = 0;
cvs_start_playback.opcode = VSS_ISTREAM_CMD_START_PLAYBACK;
v->cvs_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_start_playback);
if (ret < 0) {
pr_err("%s: Error %d sending START_PLAYBACK\n",
__func__, ret);
goto fail;
}
ret = wait_event_timeout(v->cvs_wait,
(v->cvs_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
v->music_info.playing = 1;
} else {
pr_debug("%s: Start playback already sent\n", __func__);
}
return 0;
fail:
return ret;
}
static int voice_cvs_stop_playback(struct voice_data *v)
{
int ret = 0;
struct apr_hdr cvs_stop_playback;
void *apr_cvs;
u16 cvs_handle;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_cvs = common.apr_q6_cvs;
if (!apr_cvs) {
pr_err("%s: apr_cvs is NULL.\n", __func__);
return -EINVAL;
}
cvs_handle = voice_get_cvs_handle(v);
if (v->music_info.playing && ((!v->music_info.count) ||
(v->music_info.force))) {
cvs_stop_playback.hdr_field =
APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
cvs_stop_playback.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(cvs_stop_playback) - APR_HDR_SIZE);
cvs_stop_playback.src_port = v->session_id;
cvs_stop_playback.dest_port = cvs_handle;
cvs_stop_playback.token = 0;
cvs_stop_playback.opcode = VSS_ISTREAM_CMD_STOP_PLAYBACK;
v->cvs_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_stop_playback);
if (ret < 0) {
pr_err("%s: Error %d sending STOP_PLAYBACK\n",
__func__, ret);
goto fail;
}
ret = wait_event_timeout(v->cvs_wait,
(v->cvs_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
v->music_info.playing = 0;
v->music_info.force = 0;
} else {
pr_debug("%s: Stop playback already sent\n", __func__);
}
return 0;
fail:
return ret;
}
int voc_start_playback(uint32_t set)
{
int ret = 0;
u16 cvs_handle;
int i;
for (i = 0; i < MAX_VOC_SESSIONS; i++) {
struct voice_data *v = &common.voice[i];
mutex_lock(&v->lock);
v->music_info.play_enable = set;
if (set)
v->music_info.count++;
else
v->music_info.count--;
pr_debug("%s: music_info count =%d\n", __func__,
v->music_info.count);
cvs_handle = voice_get_cvs_handle(v);
if (cvs_handle != 0) {
if (set)
ret = voice_cvs_start_playback(v);
else
ret = voice_cvs_stop_playback(v);
}
mutex_unlock(&v->lock);
}
return ret;
}
int voc_disable_cvp(uint16_t session_id)
{
struct voice_data *v = voice_get_session(session_id);
uint32_t paddr = 0;
int ret = 0;
if (v == NULL) {
pr_err("%s: invalid session_id 0x%x\n", __func__, session_id);
return -EINVAL;
}
mutex_lock(&v->lock);
if (v->voc_state == VOC_RUN) {
if (v->dev_tx.port_id != RT_PROXY_PORT_001_TX &&
v->dev_rx.port_id != RT_PROXY_PORT_001_RX)
afe_sidetone(v->dev_tx.port_id, v->dev_rx.port_id,
0, 0);
rtac_remove_voice(voice_get_cvs_handle(v));
/* send cmd to dsp to disable vocproc */
ret = voice_send_disable_vocproc_cmd(v);
if (ret < 0) {
pr_err("%s: disable vocproc failed\n", __func__);
goto fail;
}
/* deregister cvp and vol cal */
voice_send_cvp_deregister_vol_cal_table_cmd(v);
voice_send_cvp_deregister_cal_cmd(v);
voice_get_cal_paddr_size(v, &paddr, NULL);
voice_send_cvp_unmap_memory_cmd(v, paddr);
if (common.ec_ref_ext == true)
voc_set_ext_ec_ref(AFE_PORT_INVALID, false);
v->voc_state = VOC_CHANGE;
}
fail: mutex_unlock(&v->lock);
return ret;
}
int voc_enable_cvp(uint16_t session_id)
{
struct voice_data *v = voice_get_session(session_id);
struct sidetone_cal sidetone_cal_data;
uint32_t cal_paddr = 0;
uint32_t cal_size = 0;
int ret = 0;
if (v == NULL) {
pr_err("%s: invalid session_id 0x%x\n", __func__, session_id);
return -EINVAL;
}
mutex_lock(&v->lock);
if (v->voc_state == VOC_CHANGE) {
if (common.ec_ref_ext == true) {
ret = voice_send_set_device_cmd_v2(v);
if (ret < 0) {
pr_err("%s: set device V2 failed\n"
"rc =%x\n", __func__, ret);
goto fail;
}
} else {
ret = voice_send_set_device_cmd(v);
if (ret < 0) {
pr_err("%s: set device failed rc=%x\n",
__func__, ret);
goto fail;
}
}
/* send cvp and vol cal */
if (!voice_get_cal_paddr_size(v, &cal_paddr, &cal_size) &&
!voice_send_cvp_map_memory_cmd(v, cal_paddr, cal_size)) {
voice_send_cvp_register_cal_cmd(v);
voice_send_cvp_register_vol_cal_table_cmd(v);
}
ret = voice_send_enable_vocproc_cmd(v);
if (ret < 0) {
pr_err("%s: enable vocproc failed\n", __func__);
goto fail;
}
/* send tty mode if tty device is used */
voice_send_tty_mode_cmd(v);
/* enable widevoice if wv_enable is set */
if (v->wv_enable)
voice_send_set_widevoice_enable_cmd(v);
/* enable slowtalk */
if (v->st_enable)
voice_send_set_pp_enable_cmd(v,
MODULE_ID_VOICE_MODULE_ST,
v->st_enable);
/* enable FENS */
if (v->fens_enable)
voice_send_set_pp_enable_cmd(v,
MODULE_ID_VOICE_MODULE_FENS,
v->fens_enable);
get_sidetone_cal(&sidetone_cal_data);
if (v->dev_tx.port_id != RT_PROXY_PORT_001_TX &&
v->dev_rx.port_id != RT_PROXY_PORT_001_RX) {
ret = afe_sidetone(v->dev_tx.port_id,
v->dev_rx.port_id,
sidetone_cal_data.enable,
sidetone_cal_data.gain);
if (ret < 0)
pr_err("%s: AFE command sidetone failed\n",
__func__);
}
rtac_add_voice(voice_get_cvs_handle(v),
voice_get_cvp_handle(v),
v->dev_rx.port_id, v->dev_tx.port_id,
v->session_id);
v->voc_state = VOC_RUN;
}
fail:
mutex_unlock(&v->lock);
return ret;
}
int voc_disable_topology(uint16_t session_id, uint32_t disable)
{
struct voice_data *v = voice_get_session(session_id);
int ret = 0;
if (v == NULL) {
pr_err("%s: invalid session_id 0x%x\n", __func__, session_id);
return -EINVAL;
}
mutex_lock(&v->lock);
v->disable_topology = disable;
mutex_unlock(&v->lock);
return ret;
}
int voc_set_tx_mute(uint16_t session_id, uint32_t dir, uint32_t mute)
{
struct voice_data *v = voice_get_session(session_id);
int ret = 0;
if (v == NULL) {
pr_err("%s: invalid session_id 0x%x\n", __func__, session_id);
return -EINVAL;
}
mutex_lock(&v->lock);
v->dev_tx.mute = mute;
if ((v->voc_state == VOC_RUN) ||
(v->voc_state == VOC_CHANGE) ||
(v->voc_state == VOC_STANDBY))
ret = voice_send_mute_cmd(v);
mutex_unlock(&v->lock);
return ret;
}
int voc_set_rx_device_mute(uint16_t session_id, uint32_t mute)
{
struct voice_data *v = voice_get_session(session_id);
int ret = 0;
if (v == NULL) {
pr_err("%s: invalid session_id 0x%x\n", __func__, session_id);
return -EINVAL;
}
mutex_lock(&v->lock);
v->dev_rx.mute = mute;
if (v->voc_state == VOC_RUN)
ret = voice_send_rx_device_mute_cmd(v);
mutex_unlock(&v->lock);
return ret;
}
int voc_get_rx_device_mute(uint16_t session_id)
{
struct voice_data *v = voice_get_session(session_id);
int ret = 0;
if (v == NULL) {
pr_err("%s: invalid session_id 0x%x\n", __func__, session_id);
return -EINVAL;
}
mutex_lock(&v->lock);
ret = v->dev_rx.mute;
mutex_unlock(&v->lock);
return ret;
}
int voc_set_tty_mode(uint16_t session_id, uint8_t tty_mode)
{
struct voice_data *v = voice_get_session(session_id);
int ret = 0;
if (v == NULL) {
pr_err("%s: invalid session_id 0x%x\n", __func__, session_id);
return -EINVAL;
}
mutex_lock(&v->lock);
v->tty_mode = tty_mode;
mutex_unlock(&v->lock);
return ret;
}
uint8_t voc_get_tty_mode(uint16_t session_id)
{
struct voice_data *v = voice_get_session(session_id);
int ret = 0;
if (v == NULL) {
pr_err("%s: invalid session_id 0x%x\n", __func__, session_id);
return -EINVAL;
}
mutex_lock(&v->lock);
ret = v->tty_mode;
mutex_unlock(&v->lock);
return ret;
}
int voc_set_widevoice_enable(uint16_t session_id, uint32_t wv_enable)
{
struct voice_data *v = voice_get_session(session_id);
u16 mvm_handle;
int ret = 0;
if (v == NULL) {
pr_err("%s: invalid session_id 0x%x\n", __func__, session_id);
return -EINVAL;
}
mutex_lock(&v->lock);
v->wv_enable = wv_enable;
mvm_handle = voice_get_mvm_handle(v);
if (mvm_handle != 0)
voice_send_set_widevoice_enable_cmd(v);
mutex_unlock(&v->lock);
return ret;
}
uint32_t voc_get_widevoice_enable(uint16_t session_id)
{
struct voice_data *v = voice_get_session(session_id);
int ret = 0;
if (v == NULL) {
pr_err("%s: invalid session_id 0x%x\n", __func__, session_id);
return -EINVAL;
}
mutex_lock(&v->lock);
ret = v->wv_enable;
mutex_unlock(&v->lock);
return ret;
}
int voc_set_pp_enable(uint16_t session_id, uint32_t module_id, uint32_t enable)
{
struct voice_data *v = voice_get_session(session_id);
int ret = 0;
if (v == NULL) {
pr_err("%s: invalid session_id 0x%x\n", __func__, session_id);
return -EINVAL;
}
mutex_lock(&v->lock);
if (module_id == MODULE_ID_VOICE_MODULE_ST)
v->st_enable = enable;
else if (module_id == MODULE_ID_VOICE_MODULE_FENS)
v->fens_enable = enable;
if (v->voc_state == VOC_RUN) {
if (module_id == MODULE_ID_VOICE_MODULE_ST)
ret = voice_send_set_pp_enable_cmd(v,
MODULE_ID_VOICE_MODULE_ST,
enable);
else if (module_id == MODULE_ID_VOICE_MODULE_FENS)
ret = voice_send_set_pp_enable_cmd(v,
MODULE_ID_VOICE_MODULE_FENS,
enable);
}
mutex_unlock(&v->lock);
return ret;
}
int voc_get_pp_enable(uint16_t session_id, uint32_t module_id)
{
struct voice_data *v = voice_get_session(session_id);
int ret = 0;
if (v == NULL) {
pr_err("%s: invalid session_id 0x%x\n", __func__, session_id);
return -EINVAL;
}
mutex_lock(&v->lock);
if (module_id == MODULE_ID_VOICE_MODULE_ST)
ret = v->st_enable;
else if (module_id == MODULE_ID_VOICE_MODULE_FENS)
ret = v->fens_enable;
mutex_unlock(&v->lock);
return ret;
}
int voc_set_rx_vol_index(uint16_t session_id, uint32_t dir, uint32_t vol_idx)
{
struct voice_data *v = voice_get_session(session_id);
int ret = 0;
if (v == NULL) {
pr_err("%s: invalid session_id 0x%x\n", __func__, session_id);
return -EINVAL;
}
mutex_lock(&v->lock);
v->dev_rx.volume = vol_idx;
if ((v->voc_state == VOC_RUN) ||
(v->voc_state == VOC_CHANGE) ||
(v->voc_state == VOC_STANDBY))
ret = voice_send_vol_index_cmd(v);
mutex_unlock(&v->lock);
return ret;
}
int voc_set_rxtx_port(uint16_t session_id, uint32_t port_id, uint32_t dev_type)
{
struct voice_data *v = voice_get_session(session_id);
if (v == NULL) {
pr_err("%s: invalid session_id 0x%x\n", __func__, session_id);
return -EINVAL;
}
pr_debug("%s: port_id=%d, type=%d\n", __func__, port_id, dev_type);
mutex_lock(&v->lock);
if (dev_type == DEV_RX)
v->dev_rx.port_id = port_id;
else
v->dev_tx.port_id = port_id;
mutex_unlock(&v->lock);
return 0;
}
int voc_set_route_flag(uint16_t session_id, uint8_t path_dir, uint8_t set)
{
struct voice_data *v = voice_get_session(session_id);
if (v == NULL) {
pr_err("%s: invalid session_id 0x%x\n", __func__, session_id);
return -EINVAL;
}
pr_debug("%s: path_dir=%d, set=%d\n", __func__, path_dir, set);
mutex_lock(&v->lock);
if (path_dir == RX_PATH)
v->voc_route_state.rx_route_flag = set;
else
v->voc_route_state.tx_route_flag = set;
mutex_unlock(&v->lock);
return 0;
}
uint8_t voc_get_route_flag(uint16_t session_id, uint8_t path_dir)
{
struct voice_data *v = voice_get_session(session_id);
int ret = 0;
if (v == NULL) {
pr_err("%s: invalid session_id 0x%x\n", __func__, session_id);
return 0;
}
mutex_lock(&v->lock);
if (path_dir == RX_PATH)
ret = v->voc_route_state.rx_route_flag;
else
ret = v->voc_route_state.tx_route_flag;
mutex_unlock(&v->lock);
return ret;
}
int voc_end_voice_call(uint16_t session_id)
{
struct voice_data *v = voice_get_session(session_id);
int ret = 0;
if (v == NULL) {
pr_err("%s: invalid session_id 0x%x\n", __func__, session_id);
return -EINVAL;
}
mutex_lock(&v->lock);
if (v->voc_state == VOC_RUN || v->voc_state == VOC_STANDBY) {
if (v->dev_tx.port_id != RT_PROXY_PORT_001_TX &&
v->dev_rx.port_id != RT_PROXY_PORT_001_RX)
afe_sidetone(v->dev_tx.port_id, v->dev_rx.port_id,
0, 0);
ret = voice_destroy_vocproc(v);
if (ret < 0)
pr_err("%s: destroy voice failed\n", __func__);
voice_destroy_mvm_cvs_session(v);
if (common.ec_ref_ext == true)
voc_set_ext_ec_ref(AFE_PORT_INVALID, false);
v->voc_state = VOC_RELEASE;
}
mutex_unlock(&v->lock);
return ret;
}
int voc_resume_voice_call(uint16_t session_id)
{
struct voice_data *v = voice_get_session(session_id);
struct apr_hdr mvm_start_voice_cmd;
int ret = 0;
void *apr_mvm;
u16 mvm_handle;
pr_debug("%s:\n", __func__);
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_mvm = common.apr_q6_mvm;
if (!apr_mvm) {
pr_err("%s: apr_mvm is NULL.\n", __func__);
return -EINVAL;
}
mvm_handle = voice_get_mvm_handle(v);
mvm_start_voice_cmd.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
mvm_start_voice_cmd.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(mvm_start_voice_cmd) - APR_HDR_SIZE);
pr_debug("send mvm_start_voice_cmd pkt size = %d\n",
mvm_start_voice_cmd.pkt_size);
mvm_start_voice_cmd.src_port = v->session_id;
mvm_start_voice_cmd.dest_port = mvm_handle;
mvm_start_voice_cmd.token = 0;
mvm_start_voice_cmd.opcode = VSS_IMVM_CMD_START_VOICE;
v->mvm_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_start_voice_cmd);
if (ret < 0) {
pr_err("Fail in sending VSS_IMVM_CMD_START_VOICE\n");
goto fail;
}
v->voc_state = VOC_RUN;
return 0;
fail:
return -EINVAL;
}
int voc_start_voice_call(uint16_t session_id)
{
struct voice_data *v = voice_get_session(session_id);
struct sidetone_cal sidetone_cal_data;
int ret = 0;
if (v == NULL) {
pr_err("%s: invalid session_id 0x%x\n", __func__, session_id);
return -EINVAL;
}
mutex_lock(&v->lock);
if ((v->voc_state == VOC_INIT) ||
(v->voc_state == VOC_RELEASE)) {
ret = voice_apr_register();
if (ret < 0) {
pr_err("%s: apr register failed\n", __func__);
goto fail;
}
ret = voice_create_mvm_cvs_session(v);
if (ret < 0) {
pr_err("create mvm and cvs failed\n");
goto fail;
}
ret = voice_send_dual_control_cmd(v);
if (ret < 0) {
pr_err("Err Dual command failed\n");
goto fail;
}
ret = voice_setup_vocproc(v);
if (ret < 0) {
pr_err("setup voice failed\n");
goto fail;
}
ret = voice_send_vol_index_cmd(v);
if (ret < 0)
pr_err("voice volume failed\n");
ret = voice_send_mute_cmd(v);
if (ret < 0)
pr_err("voice mute failed\n");
ret = voice_send_start_voice_cmd(v);
if (ret < 0) {
pr_err("start voice failed\n");
goto fail;
}
get_sidetone_cal(&sidetone_cal_data);
if (v->dev_tx.port_id != RT_PROXY_PORT_001_TX &&
v->dev_rx.port_id != RT_PROXY_PORT_001_RX) {
ret = afe_sidetone(v->dev_tx.port_id,
v->dev_rx.port_id,
sidetone_cal_data.enable,
sidetone_cal_data.gain);
if (ret < 0)
pr_err("AFE command sidetone failed\n");
}
v->voc_state = VOC_RUN;
} else if (v->voc_state == VOC_STANDBY) {
pr_err("Error: PCM Prepare when in Standby\n");
ret = -EINVAL;
goto fail;
}
fail: mutex_unlock(&v->lock);
return ret;
}
int voc_standby_voice_call(uint16_t session_id)
{
struct voice_data *v = voice_get_session(session_id);
struct apr_hdr mvm_standby_voice_cmd;
void *apr_mvm;
u16 mvm_handle;
int ret = 0;
pr_debug("%s: voc state=%d", __func__, v->voc_state);
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
if (v->voc_state == VOC_RUN) {
apr_mvm = common.apr_q6_mvm;
if (!apr_mvm) {
pr_err("%s: apr_mvm is NULL.\n", __func__);
ret = -EINVAL;
goto fail;
}
mvm_handle = voice_get_mvm_handle(v);
mvm_standby_voice_cmd.hdr_field =
APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
mvm_standby_voice_cmd.pkt_size =
APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(mvm_standby_voice_cmd) - APR_HDR_SIZE);
pr_debug("send mvm_standby_voice_cmd pkt size = %d\n",
mvm_standby_voice_cmd.pkt_size);
mvm_standby_voice_cmd.src_port = v->session_id;
mvm_standby_voice_cmd.dest_port = mvm_handle;
mvm_standby_voice_cmd.token = 0;
mvm_standby_voice_cmd.opcode = VSS_IMVM_CMD_STANDBY_VOICE;
v->mvm_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_mvm,
(uint32_t *)&mvm_standby_voice_cmd);
if (ret < 0) {
pr_err("Fail in sending VSS_IMVM_CMD_STANDBY_VOICE\n");
ret = -EINVAL;
goto fail;
}
v->voc_state = VOC_STANDBY;
}
fail:
return ret;
}
int voc_set_ext_ec_ref(uint16_t port_id, bool state)
{
int ret = 0;
mutex_lock(&common.common_lock);
if (state == true) {
if (port_id == AFE_PORT_INVALID) {
pr_err("%s: Invalid port id", __func__);
ret = -EINVAL;
goto fail;
}
common.ec_port_id = port_id;
common.ec_ref_ext = true;
} else {
common.ec_ref_ext = false;
common.ec_port_id = port_id;
}
fail:
mutex_unlock(&common.common_lock);
return ret;
}
void voc_register_mvs_cb(ul_cb_fn ul_cb,
dl_cb_fn dl_cb,
void *private_data)
{
common.mvs_info.ul_cb = ul_cb;
common.mvs_info.dl_cb = dl_cb;
common.mvs_info.private_data = private_data;
}
void voc_register_dtmf_rx_detection_cb(dtmf_rx_det_cb_fn dtmf_rx_ul_cb,
void *private_data)
{
common.dtmf_info.dtmf_rx_ul_cb = dtmf_rx_ul_cb;
common.dtmf_info.private_data = private_data;
}
void voc_register_hpcm_evt_cb(hostpcm_cb_fn hostpcm_cb,
void *private_data)
{
common.hostpcm_info.hostpcm_evt_cb = hostpcm_cb;
common.hostpcm_info.private_data = private_data;
}
void voc_config_vocoder(uint32_t media_type,
uint32_t rate,
uint32_t network_type,
uint32_t dtx_mode)
{
common.mvs_info.media_type = media_type;
common.mvs_info.rate = rate;
common.mvs_info.network_type = network_type;
common.mvs_info.dtx_mode = dtx_mode;
}
static int32_t qdsp_mvm_callback(struct apr_client_data *data, void *priv)
{
uint32_t *ptr = NULL;
struct common_data *c = NULL;
struct voice_data *v = NULL;
int i = 0;
if ((data == NULL) || (priv == NULL)) {
pr_err("%s: data or priv is NULL\n", __func__);
return -EINVAL;
}
c = priv;
pr_debug("%s: session_id 0x%x\n", __func__, data->dest_port);
v = voice_get_session(data->dest_port);
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
pr_debug("%s: Payload Length = %d, opcode=%x\n", __func__,
data->payload_size, data->opcode);
if (data->opcode == RESET_EVENTS) {
pr_debug("%s: Reset event received in Voice service\n",
__func__);
apr_reset(c->apr_q6_mvm);
c->apr_q6_mvm = NULL;
/* Sub-system restart is applicable to all sessions. */
for (i = 0; i < MAX_VOC_SESSIONS; i++)
c->voice[i].mvm_handle = 0;
return 0;
}
if (data->opcode == APR_BASIC_RSP_RESULT) {
if (data->payload_size) {
ptr = data->payload;
pr_info("%x %x\n", ptr[0], ptr[1]);
/* ping mvm service ACK */
switch (ptr[0]) {
case VSS_IMVM_CMD_CREATE_PASSIVE_CONTROL_SESSION:
case VSS_IMVM_CMD_CREATE_FULL_CONTROL_SESSION:
/* Passive session is used for CS call
* Full session is used for VoIP call. */
pr_debug("%s: cmd = 0x%x\n", __func__, ptr[0]);
if (!ptr[1]) {
pr_debug("%s: MVM handle is %d\n",
__func__, data->src_port);
voice_set_mvm_handle(v, data->src_port);
} else
pr_err("got NACK for sending \
MVM create session \n");
v->mvm_state = CMD_STATUS_SUCCESS;
wake_up(&v->mvm_wait);
break;
case VSS_IMVM_CMD_START_VOICE:
case VSS_IMVM_CMD_ATTACH_VOCPROC:
case VSS_IMVM_CMD_STOP_VOICE:
case VSS_IMVM_CMD_DETACH_VOCPROC:
case VSS_ISTREAM_CMD_SET_TTY_MODE:
case APRV2_IBASIC_CMD_DESTROY_SESSION:
case VSS_IMVM_CMD_ATTACH_STREAM:
case VSS_IMVM_CMD_DETACH_STREAM:
case VSS_ICOMMON_CMD_SET_NETWORK:
case VSS_ICOMMON_CMD_SET_VOICE_TIMING:
case VSS_IWIDEVOICE_CMD_SET_WIDEVOICE:
case VSS_IMVM_CMD_SET_POLICY_DUAL_CONTROL:
case VSS_IMVM_CMD_STANDBY_VOICE:
pr_debug("%s: cmd = 0x%x\n", __func__, ptr[0]);
v->mvm_state = CMD_STATUS_SUCCESS;
wake_up(&v->mvm_wait);
break;
default:
pr_debug("%s: not match cmd = 0x%x\n",
__func__, ptr[0]);
break;
}
}
}
return 0;
}
static int32_t qdsp_cvs_callback(struct apr_client_data *data, void *priv)
{
uint32_t *ptr = NULL;
struct common_data *c = NULL;
struct voice_data *v = NULL;
int i = 0;
if ((data == NULL) || (priv == NULL)) {
pr_err("%s: data or priv is NULL\n", __func__);
return -EINVAL;
}
c = priv;
pr_debug("%s: session_id 0x%x\n", __func__, data->dest_port);
v = voice_get_session(data->dest_port);
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
pr_debug("%s: Payload Length = %d, opcode=%x\n", __func__,
data->payload_size, data->opcode);
if (data->opcode == RESET_EVENTS) {
pr_debug("%s: Reset event received in Voice service\n",
__func__);
apr_reset(c->apr_q6_cvs);
c->apr_q6_cvs = NULL;
/* Sub-system restart is applicable to all sessions. */
for (i = 0; i < MAX_VOC_SESSIONS; i++)
c->voice[i].cvs_handle = 0;
return 0;
}
if (data->opcode == APR_BASIC_RSP_RESULT) {
if (data->payload_size) {
ptr = data->payload;
pr_info("%x %x\n", ptr[0], ptr[1]);
/*response from CVS */
switch (ptr[0]) {
case VSS_ISTREAM_CMD_CREATE_PASSIVE_CONTROL_SESSION:
case VSS_ISTREAM_CMD_CREATE_FULL_CONTROL_SESSION:
if (!ptr[1]) {
pr_debug("%s: CVS handle is %d\n",
__func__, data->src_port);
voice_set_cvs_handle(v, data->src_port);
} else
pr_err("got NACK for sending \
CVS create session \n");
v->cvs_state = CMD_STATUS_SUCCESS;
wake_up(&v->cvs_wait);
break;
case VSS_ISTREAM_CMD_SET_MUTE:
case VSS_ISTREAM_CMD_SET_MEDIA_TYPE:
case VSS_ISTREAM_CMD_VOC_AMR_SET_ENC_RATE:
case VSS_ISTREAM_CMD_VOC_AMRWB_SET_ENC_RATE:
case VSS_ISTREAM_CMD_SET_ENC_DTX_MODE:
case VSS_ISTREAM_CMD_CDMA_SET_ENC_MINMAX_RATE:
case APRV2_IBASIC_CMD_DESTROY_SESSION:
case VSS_ISTREAM_CMD_REGISTER_CALIBRATION_DATA:
case VSS_ISTREAM_CMD_DEREGISTER_CALIBRATION_DATA:
case VSS_ICOMMON_CMD_MAP_MEMORY:
case VSS_ICOMMON_CMD_UNMAP_MEMORY:
case VSS_ICOMMON_CMD_SET_UI_PROPERTY:
case VSS_ISTREAM_CMD_START_PLAYBACK:
case VSS_ISTREAM_CMD_STOP_PLAYBACK:
case VSS_ISTREAM_CMD_START_RECORD:
case VSS_ISTREAM_CMD_STOP_RECORD:
case VSS_ISTREAM_CMD_SET_RX_DTMF_DETECTION:
pr_debug("%s: cmd = 0x%x\n", __func__, ptr[0]);
v->cvs_state = CMD_STATUS_SUCCESS;
wake_up(&v->cvs_wait);
break;
case VOICE_CMD_SET_PARAM:
rtac_make_voice_callback(RTAC_CVS, ptr,
data->payload_size);
break;
default:
pr_debug("%s: cmd = 0x%x\n", __func__, ptr[0]);
break;
}
}
} else if (data->opcode == VSS_ISTREAM_EVT_SEND_ENC_BUFFER) {
uint32_t *voc_pkt = data->payload;
uint32_t pkt_len = data->payload_size;
if (voc_pkt != NULL && c->mvs_info.ul_cb != NULL) {
pr_debug("%s: Media type is 0x%x\n",
__func__, voc_pkt[0]);
/* Remove media ID from payload. */
voc_pkt++;
pkt_len = pkt_len - 4;
c->mvs_info.ul_cb((uint8_t *)voc_pkt,
pkt_len,
c->mvs_info.private_data);
} else
pr_err("%s: voc_pkt is 0x%x ul_cb is 0x%x\n",
__func__, (unsigned int)voc_pkt,
(unsigned int) c->mvs_info.ul_cb);
} else if (data->opcode == VSS_ISTREAM_EVT_REQUEST_DEC_BUFFER) {
struct cvs_send_dec_buf_cmd send_dec_buf;
int ret = 0;
uint32_t pkt_len = 0;
if (c->mvs_info.dl_cb != NULL) {
send_dec_buf.dec_buf.media_id = c->mvs_info.media_type;
c->mvs_info.dl_cb(
(uint8_t *)&send_dec_buf.dec_buf.packet_data,
&pkt_len,
c->mvs_info.private_data);
send_dec_buf.hdr.hdr_field =
APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
send_dec_buf.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(send_dec_buf.dec_buf.media_id) + pkt_len);
send_dec_buf.hdr.src_port = v->session_id;
send_dec_buf.hdr.dest_port = voice_get_cvs_handle(v);
send_dec_buf.hdr.token = 0;
send_dec_buf.hdr.opcode =
VSS_ISTREAM_EVT_SEND_DEC_BUFFER;
ret = apr_send_pkt(c->apr_q6_cvs,
(uint32_t *) &send_dec_buf);
if (ret < 0) {
pr_err("%s: Error %d sending DEC_BUF\n",
__func__, ret);
goto fail;
}
} else
pr_debug("%s: dl_cb is NULL\n", __func__);
} else if (data->opcode == VSS_ISTREAM_EVT_SEND_DEC_BUFFER) {
pr_debug("Send dec buf resp\n");
} else if (data->opcode == VOICE_EVT_GET_PARAM_ACK) {
rtac_make_voice_callback(RTAC_CVS, data->payload,
data->payload_size);
} else if (data->opcode == VSS_ISTREAM_EVT_RX_DTMF_DETECTED) {
struct vss_istream_evt_rx_dtmf_detected *dtmf_rx_detected;
uint32_t *voc_pkt = data->payload;
uint32_t pkt_len = data->payload_size;
if ((voc_pkt != NULL) &&
(pkt_len ==
sizeof(struct vss_istream_evt_rx_dtmf_detected))) {
dtmf_rx_detected =
(struct vss_istream_evt_rx_dtmf_detected *) voc_pkt;
pr_debug("RX_DTMF_DETECTED low_freq=%d high_freq=%d\n",
dtmf_rx_detected->low_freq,
dtmf_rx_detected->high_freq);
if (c->dtmf_info.dtmf_rx_ul_cb)
c->dtmf_info.dtmf_rx_ul_cb((uint8_t *)voc_pkt,
voc_get_session_name(v->session_id),
c->dtmf_info.private_data);
} else {
pr_err("Invalid packet\n");
}
} else {
pr_debug("Unknown opcode 0x%x\n", data->opcode);
}
fail:
return 0;
}
static int32_t qdsp_cvp_callback(struct apr_client_data *data, void *priv)
{
uint32_t *ptr = NULL;
struct common_data *c = NULL;
struct voice_data *v = NULL;
int i = 0;
if ((data == NULL) || (priv == NULL)) {
pr_err("%s: data or priv is NULL\n", __func__);
return -EINVAL;
}
c = priv;
v = voice_get_session(data->dest_port);
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
pr_debug("%s: Payload Length = %d, opcode=%x\n", __func__,
data->payload_size, data->opcode);
if (data->opcode == RESET_EVENTS) {
pr_debug("%s: Reset event received in Voice service\n",
__func__);
apr_reset(c->apr_q6_cvp);
c->apr_q6_cvp = NULL;
/* Sub-system restart is applicable to all sessions. */
for (i = 0; i < MAX_VOC_SESSIONS; i++)
c->voice[i].cvp_handle = 0;
return 0;
}
if (data->opcode == APR_BASIC_RSP_RESULT) {
if (data->payload_size) {
ptr = data->payload;
pr_info("%x %x\n", ptr[0], ptr[1]);
switch (ptr[0]) {
case VSS_IVOCPROC_CMD_CREATE_FULL_CONTROL_SESSION:
/*response from CVP */
pr_debug("%s: cmd = 0x%x\n", __func__, ptr[0]);
if (!ptr[1]) {
voice_set_cvp_handle(v, data->src_port);
pr_debug("cvphdl=%d\n", data->src_port);
} else
pr_err("got NACK from CVP create \
session response\n");
v->cvp_state = CMD_STATUS_SUCCESS;
wake_up(&v->cvp_wait);
break;
case VSS_IVOCPROC_CMD_SET_DEVICE_V2:
case VSS_IVOCPROC_CMD_SET_DEVICE:
case VSS_IVOCPROC_CMD_SET_RX_VOLUME_INDEX:
case VSS_IVOCPROC_CMD_ENABLE:
case VSS_IVOCPROC_CMD_DISABLE:
case APRV2_IBASIC_CMD_DESTROY_SESSION:
case VSS_IVOCPROC_CMD_REGISTER_VOLUME_CAL_TABLE:
case VSS_IVOCPROC_CMD_DEREGISTER_VOLUME_CAL_TABLE:
case VSS_IVOCPROC_CMD_REGISTER_CALIBRATION_DATA:
case VSS_IVOCPROC_CMD_DEREGISTER_CALIBRATION_DATA:
case VSS_ICOMMON_CMD_MAP_MEMORY:
case VSS_ICOMMON_CMD_UNMAP_MEMORY:
case VSS_IVOCPROC_CMD_SET_MUTE:
case VSS_IVPCM_CMD_START:
case VSS_IVPCM_CMD_STOP:
v->cvp_state = CMD_STATUS_SUCCESS;
wake_up(&v->cvp_wait);
break;
case VSS_IVPCM_EVT_PUSH_BUFFER:
break;
case VOICE_CMD_SET_PARAM:
rtac_make_voice_callback(RTAC_CVP, ptr,
data->payload_size);
break;
default:
pr_debug("%s: not match cmd = 0x%x\n",
__func__, ptr[0]);
break;
}
}
} else if (data->opcode == VOICE_EVT_GET_PARAM_ACK) {
rtac_make_voice_callback(RTAC_CVP, data->payload,
data->payload_size);
} else if (data->opcode == VSS_IVPCM_EVT_NOTIFY) {
struct vss_ivpcm_evt_notify *notify_evt;
if ((data->payload != NULL) &&
data->payload_size == sizeof(struct vss_ivpcm_evt_notify)) {
notify_evt =
(struct vss_ivpcm_evt_notify *)data->payload;
c->hostpcm_info.hostpcm_evt_cb(data->payload,
voc_get_session_name(v->session_id),
c->hostpcm_info.private_data);
}
}
return 0;
}
int voc_send_cvp_vocpcm_push_buf_evt(u16 session_id,
struct vss_ivpcm_evt_push_buffer *push_buff_evt)
{
struct cvp_push_buf_cmd vpcm_push_buf_cmd;
int ret = 0;
void *apr_cvp;
u16 cvp_handle;
struct voice_data *v = voice_get_session(session_id);
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_cvp = common.apr_q6_cvp;
if (!apr_cvp) {
pr_err("%s: apr_cvp is NULL.\n", __func__);
return -EINVAL;
}
cvp_handle = voice_get_cvp_handle(v);
/* fill in the header */
vpcm_push_buf_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
vpcm_push_buf_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(vpcm_push_buf_cmd) - APR_HDR_SIZE);
vpcm_push_buf_cmd.hdr.src_port = v->session_id;
vpcm_push_buf_cmd.hdr.dest_port = cvp_handle;
vpcm_push_buf_cmd.hdr.token = 0;
vpcm_push_buf_cmd.hdr.opcode = VSS_IVPCM_EVT_PUSH_BUFFER;
vpcm_push_buf_cmd.vpcm_evt_push_buffer.tap_point =
push_buff_evt->tap_point;
vpcm_push_buf_cmd.vpcm_evt_push_buffer.push_buf_mask =
push_buff_evt->push_buf_mask;
vpcm_push_buf_cmd.vpcm_evt_push_buffer.out_buf_addr =
push_buff_evt->out_buf_addr;
vpcm_push_buf_cmd.vpcm_evt_push_buffer.in_buf_addr =
push_buff_evt->in_buf_addr;
vpcm_push_buf_cmd.vpcm_evt_push_buffer.out_buf_size =
push_buff_evt->out_buf_size;
vpcm_push_buf_cmd.vpcm_evt_push_buffer.in_buf_size =
push_buff_evt->in_buf_size;
vpcm_push_buf_cmd.vpcm_evt_push_buffer.sampling_rate =
push_buff_evt->sampling_rate;
vpcm_push_buf_cmd.vpcm_evt_push_buffer.num_in_channels =
push_buff_evt->num_in_channels;
ret = apr_send_pkt(apr_cvp, (uint32_t *) &vpcm_push_buf_cmd);
if (ret < 0) {
pr_err("Fail: sending vocpcm map memory,\n");
goto fail;
}
return 0;
fail:
return -EINVAL;
}
int voc_send_cvp_stop_vocpcm(u16 session_id)
{
struct cvp_stop_cmd vpcm_stop_cmd;
int ret = 0;
void *apr_cvp;
u16 cvp_handle;
struct voice_data *v = voice_get_session(session_id);
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_cvp = common.apr_q6_cvp;
if (!apr_cvp) {
pr_err("%s: apr_cvp is NULL.\n", __func__);
return -EINVAL;
}
cvp_handle = voice_get_cvp_handle(v);
/* fill in the header */
vpcm_stop_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
vpcm_stop_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(vpcm_stop_cmd) - APR_HDR_SIZE);
vpcm_stop_cmd.hdr.src_port = v->session_id;
vpcm_stop_cmd.hdr.dest_port = cvp_handle;
vpcm_stop_cmd.hdr.token = 0;
vpcm_stop_cmd.hdr.opcode = VSS_IVPCM_CMD_STOP;
v->cvp_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvp, (uint32_t *) &vpcm_stop_cmd);
if (ret < 0) {
pr_err("Fail: sending vocpcm stop,\n");
goto fail;
}
ret = wait_event_timeout(v->cvp_wait,
(v->cvp_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
return 0;
fail:
return -EINVAL;
}
int voc_send_cvp_start_vocpcm(u16 session_id,
struct vss_ivpcm_tap_point *vpcm_tp,
uint32_t no_of_tp)
{
struct cvp_start_cmd cvp_start_cmd;
int ret = 0;
void *apr_cvp;
u16 cvp_handle;
struct voice_data *v = voice_get_session(session_id);
int i = 0;
if (v == NULL) {
pr_err("%s: v is NULL\n", __func__);
return -EINVAL;
}
apr_cvp = common.apr_q6_cvp;
if (!apr_cvp) {
pr_err("%s: apr_cvp is NULL.\n", __func__);
return -EINVAL;
}
cvp_handle = voice_get_cvp_handle(v);
/* fill in the header */
cvp_start_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
cvp_start_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(struct vss_ivpcm_tap_point) * no_of_tp) + sizeof(no_of_tp);
cvp_start_cmd.hdr.src_port = v->session_id;
cvp_start_cmd.hdr.dest_port = cvp_handle;
cvp_start_cmd.hdr.token = 0;
cvp_start_cmd.hdr.opcode = VSS_IVPCM_CMD_START;
for (i = 0; i < no_of_tp; i++) {
cvp_start_cmd.vpcm_start_cmd.tap_points[i].tap_point =
vpcm_tp[i].tap_point;
cvp_start_cmd.vpcm_start_cmd.tap_points[i].direction =
vpcm_tp[i].direction;
cvp_start_cmd.vpcm_start_cmd.tap_points[i].sampling_rate =
vpcm_tp[i].sampling_rate;
cvp_start_cmd.vpcm_start_cmd.tap_points[i].duration = 0;
}
cvp_start_cmd.vpcm_start_cmd.num_tap_points = no_of_tp;
v->cvp_state = CMD_STATUS_FAIL;
ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_start_cmd);
if (ret < 0) {
pr_err("Fail: sending vocpcm map memory,\n");
goto fail;
}
ret = wait_event_timeout(v->cvp_wait,
(v->cvp_state == CMD_STATUS_SUCCESS),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
pr_err("%s: wait_event timeout\n", __func__);
goto fail;
}
return 0;
fail:
return -EINVAL;
}
int voc_send_cvp_unmap_vocpcm_memory(u16 session_id, uint32_t paddr)
{
return voice_send_cvp_unmap_memory_cmd(
voice_get_session(session_id), paddr);
}
int voc_send_cvp_map_vocpcm_memory(u16 session_id,
uint32_t paddr, uint32_t bufsize)
{
return voice_send_cvp_map_memory_cmd(voice_get_session(session_id),
paddr,
bufsize);
}
static void voice_allocate_shared_memory(void)
{
int i, j, result;
int offset = 0;
int mem_len;
unsigned long paddr;
void *kvptr;
pr_debug("%s\n", __func__);
common.ion_client = msm_ion_client_create(UINT_MAX, "q6voice_client");
if (IS_ERR_OR_NULL((void *)common.ion_client)) {
pr_err("%s: ION create client failed\n", __func__);
goto err;
}
common.ion_handle = ion_alloc(common.ion_client,
TOTAL_VOICE_CAL_SIZE,
SZ_4K, ION_HEAP(ION_AUDIO_HEAP_ID), 0);
if (IS_ERR_OR_NULL((void *) common.ion_handle)) {
pr_err("%s: ION memory allocation failed\n",
__func__);
goto err_ion_client;
}
result = ion_phys(common.ion_client, common.ion_handle,
&paddr, (size_t *)&mem_len);
if (result) {
pr_err("%s: ION Get Physical failed, rc = %d\n",
__func__, result);
goto err_ion_handle;
}
kvptr = ion_map_kernel(common.ion_client, common.ion_handle);
if (IS_ERR_OR_NULL(kvptr)) {
pr_err("%s: ION memory mapping failed\n", __func__);
goto err_ion_handle;
}
/* Make all phys & buf point to the correct address */
for (i = 0; i < NUM_VOICE_CAL_BUFFERS; i++) {
for (j = 0; j < NUM_VOICE_CAL_TYPES; j++) {
common.voice_cal[i].cal_data[j].paddr =
(uint32_t)(paddr + offset);
common.voice_cal[i].cal_data[j].kvaddr =
(uint32_t)((uint8_t *)kvptr + offset);
if (j == CVP_CAL)
offset += CVP_CAL_SIZE;
else
offset += CVS_CAL_SIZE;
pr_debug("%s: kernel addr = 0x%x, phys addr = 0x%x\n",
__func__,
common.voice_cal[i].cal_data[j].kvaddr,
common.voice_cal[i].cal_data[j].paddr);
}
}
return;
err_ion_handle:
ion_free(common.ion_client, common.ion_handle);
err_ion_client:
ion_client_destroy(common.ion_client);
err:
return;
}
static int __init voice_init(void)
{
int rc = 0, i = 0;
memset(&common, 0, sizeof(struct common_data));
/* Allocate shared memory */
voice_allocate_shared_memory();
/* set default value */
common.default_mute_val = 0; /* default is un-mute */
common.default_vol_val = 0;
common.default_sample_val = 8000;
common.ec_ref_ext = false;
/* Initialize MVS info. */
common.mvs_info.network_type = VSS_NETWORK_ID_DEFAULT;
mutex_init(&common.common_lock);
for (i = 0; i < MAX_VOC_SESSIONS; i++) {
common.voice[i].session_id = SESSION_ID_BASE + i;
/* initialize dev_rx and dev_tx */
common.voice[i].dev_rx.volume = common.default_vol_val;
common.voice[i].dev_rx.mute = 0;
common.voice[i].dev_tx.mute = common.default_mute_val;
common.voice[i].dev_tx.port_id = 1;
common.voice[i].dev_rx.port_id = 0;
common.voice[i].sidetone_gain = 0x512;
common.voice[i].dtmf_rx_detect_en = 0;
common.voice[i].disable_topology = false;
common.voice[i].voc_state = VOC_INIT;
init_waitqueue_head(&common.voice[i].mvm_wait);
init_waitqueue_head(&common.voice[i].cvs_wait);
init_waitqueue_head(&common.voice[i].cvp_wait);
mutex_init(&common.voice[i].lock);
}
return rc;
}
device_initcall(voice_init);
| gpl-2.0 |
CyanogenMod/android_external_hostapd | src/eap_peer/eap_fast_pac.c | 80 | 21322 | /*
* EAP peer method: EAP-FAST PAC file processing
* Copyright (c) 2004-2006, Jouni Malinen <j@w1.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* Alternatively, this software may be distributed under the terms of BSD
* license.
*
* See README and COPYING for more details.
*/
#include "includes.h"
#include "common.h"
#include "eap_config.h"
#include "eap_i.h"
#include "eap_fast_pac.h"
/* TODO: encrypt PAC-Key in the PAC file */
/* Text data format */
static const char *pac_file_hdr =
"wpa_supplicant EAP-FAST PAC file - version 1";
/*
* Binary data format
* 4-octet magic value: 6A E4 92 0C
* 2-octet version (big endian)
* <version specific data>
*
* version=0:
* Sequence of PAC entries:
* 2-octet PAC-Type (big endian)
* 32-octet PAC-Key
* 2-octet PAC-Opaque length (big endian)
* <variable len> PAC-Opaque data (length bytes)
* 2-octet PAC-Info length (big endian)
* <variable len> PAC-Info data (length bytes)
*/
#define EAP_FAST_PAC_BINARY_MAGIC 0x6ae4920c
#define EAP_FAST_PAC_BINARY_FORMAT_VERSION 0
/**
* eap_fast_free_pac - Free PAC data
* @pac: Pointer to the PAC entry
*
* Note that the PAC entry must not be in a list since this function does not
* remove the list links.
*/
void eap_fast_free_pac(struct eap_fast_pac *pac)
{
os_free(pac->pac_opaque);
os_free(pac->pac_info);
os_free(pac->a_id);
os_free(pac->i_id);
os_free(pac->a_id_info);
os_free(pac);
}
/**
* eap_fast_get_pac - Get a PAC entry based on A-ID
* @pac_root: Pointer to root of the PAC list
* @a_id: A-ID to search for
* @a_id_len: Length of A-ID
* @pac_type: PAC-Type to search for
* Returns: Pointer to the PAC entry, or %NULL if A-ID not found
*/
struct eap_fast_pac * eap_fast_get_pac(struct eap_fast_pac *pac_root,
const u8 *a_id, size_t a_id_len,
u16 pac_type)
{
struct eap_fast_pac *pac = pac_root;
while (pac) {
if (pac->pac_type == pac_type && pac->a_id_len == a_id_len &&
os_memcmp(pac->a_id, a_id, a_id_len) == 0) {
return pac;
}
pac = pac->next;
}
return NULL;
}
static void eap_fast_remove_pac(struct eap_fast_pac **pac_root,
struct eap_fast_pac **pac_current,
const u8 *a_id, size_t a_id_len, u16 pac_type)
{
struct eap_fast_pac *pac, *prev;
pac = *pac_root;
prev = NULL;
while (pac) {
if (pac->pac_type == pac_type && pac->a_id_len == a_id_len &&
os_memcmp(pac->a_id, a_id, a_id_len) == 0) {
if (prev == NULL)
*pac_root = pac->next;
else
prev->next = pac->next;
if (*pac_current == pac)
*pac_current = NULL;
eap_fast_free_pac(pac);
break;
}
prev = pac;
pac = pac->next;
}
}
static int eap_fast_copy_buf(u8 **dst, size_t *dst_len,
const u8 *src, size_t src_len)
{
if (src) {
*dst = os_malloc(src_len);
if (*dst == NULL)
return -1;
os_memcpy(*dst, src, src_len);
*dst_len = src_len;
}
return 0;
}
/**
* eap_fast_add_pac - Add a copy of a PAC entry to a list
* @pac_root: Pointer to PAC list root pointer
* @pac_current: Pointer to the current PAC pointer
* @entry: New entry to clone and add to the list
* Returns: 0 on success, -1 on failure
*
* This function makes a clone of the given PAC entry and adds this copied
* entry to the list (pac_root). If an old entry for the same A-ID is found,
* it will be removed from the PAC list and in this case, pac_current entry
* is set to %NULL if it was the removed entry.
*/
int eap_fast_add_pac(struct eap_fast_pac **pac_root,
struct eap_fast_pac **pac_current,
struct eap_fast_pac *entry)
{
struct eap_fast_pac *pac;
if (entry == NULL || entry->a_id == NULL)
return -1;
/* Remove a possible old entry for the matching A-ID. */
eap_fast_remove_pac(pac_root, pac_current,
entry->a_id, entry->a_id_len, entry->pac_type);
/* Allocate a new entry and add it to the list of PACs. */
pac = os_zalloc(sizeof(*pac));
if (pac == NULL)
return -1;
pac->pac_type = entry->pac_type;
os_memcpy(pac->pac_key, entry->pac_key, EAP_FAST_PAC_KEY_LEN);
if (eap_fast_copy_buf(&pac->pac_opaque, &pac->pac_opaque_len,
entry->pac_opaque, entry->pac_opaque_len) < 0 ||
eap_fast_copy_buf(&pac->pac_info, &pac->pac_info_len,
entry->pac_info, entry->pac_info_len) < 0 ||
eap_fast_copy_buf(&pac->a_id, &pac->a_id_len,
entry->a_id, entry->a_id_len) < 0 ||
eap_fast_copy_buf(&pac->i_id, &pac->i_id_len,
entry->i_id, entry->i_id_len) < 0 ||
eap_fast_copy_buf(&pac->a_id_info, &pac->a_id_info_len,
entry->a_id_info, entry->a_id_info_len) < 0) {
eap_fast_free_pac(pac);
return -1;
}
pac->next = *pac_root;
*pac_root = pac;
return 0;
}
struct eap_fast_read_ctx {
FILE *f;
const char *pos;
const char *end;
int line;
char *buf;
size_t buf_len;
};
static int eap_fast_read_line(struct eap_fast_read_ctx *rc, char **value)
{
char *pos;
rc->line++;
if (rc->f) {
if (fgets(rc->buf, rc->buf_len, rc->f) == NULL)
return -1;
} else {
const char *l_end;
size_t len;
if (rc->pos >= rc->end)
return -1;
l_end = rc->pos;
while (l_end < rc->end && *l_end != '\n')
l_end++;
len = l_end - rc->pos;
if (len >= rc->buf_len)
len = rc->buf_len - 1;
os_memcpy(rc->buf, rc->pos, len);
rc->buf[len] = '\0';
rc->pos = l_end + 1;
}
rc->buf[rc->buf_len - 1] = '\0';
pos = rc->buf;
while (*pos != '\0') {
if (*pos == '\n' || *pos == '\r') {
*pos = '\0';
break;
}
pos++;
}
pos = os_strchr(rc->buf, '=');
if (pos)
*pos++ = '\0';
*value = pos;
return 0;
}
static u8 * eap_fast_parse_hex(const char *value, size_t *len)
{
int hlen;
u8 *buf;
if (value == NULL)
return NULL;
hlen = os_strlen(value);
if (hlen & 1)
return NULL;
*len = hlen / 2;
buf = os_malloc(*len);
if (buf == NULL)
return NULL;
if (hexstr2bin(value, buf, *len)) {
os_free(buf);
return NULL;
}
return buf;
}
static int eap_fast_init_pac_data(struct eap_sm *sm, const char *pac_file,
struct eap_fast_read_ctx *rc)
{
os_memset(rc, 0, sizeof(*rc));
rc->buf_len = 2048;
rc->buf = os_malloc(rc->buf_len);
if (rc->buf == NULL)
return -1;
if (os_strncmp(pac_file, "blob://", 7) == 0) {
const struct wpa_config_blob *blob;
blob = eap_get_config_blob(sm, pac_file + 7);
if (blob == NULL) {
wpa_printf(MSG_INFO, "EAP-FAST: No PAC blob '%s' - "
"assume no PAC entries have been "
"provisioned", pac_file + 7);
os_free(rc->buf);
return -1;
}
rc->pos = (char *) blob->data;
rc->end = (char *) blob->data + blob->len;
} else {
rc->f = fopen(pac_file, "rb");
if (rc->f == NULL) {
wpa_printf(MSG_INFO, "EAP-FAST: No PAC file '%s' - "
"assume no PAC entries have been "
"provisioned", pac_file);
os_free(rc->buf);
return -1;
}
}
return 0;
}
static void eap_fast_deinit_pac_data(struct eap_fast_read_ctx *rc)
{
os_free(rc->buf);
if (rc->f)
fclose(rc->f);
}
static const char * eap_fast_parse_start(struct eap_fast_pac **pac)
{
if (*pac)
return "START line without END";
*pac = os_zalloc(sizeof(struct eap_fast_pac));
if (*pac == NULL)
return "No memory for PAC entry";
(*pac)->pac_type = PAC_TYPE_TUNNEL_PAC;
return NULL;
}
static const char * eap_fast_parse_end(struct eap_fast_pac **pac_root,
struct eap_fast_pac **pac)
{
if (*pac == NULL)
return "END line without START";
if (*pac_root) {
struct eap_fast_pac *end = *pac_root;
while (end->next)
end = end->next;
end->next = *pac;
} else
*pac_root = *pac;
*pac = NULL;
return NULL;
}
static const char * eap_fast_parse_pac_type(struct eap_fast_pac *pac,
char *pos)
{
pac->pac_type = atoi(pos);
if (pac->pac_type != PAC_TYPE_TUNNEL_PAC &&
pac->pac_type != PAC_TYPE_USER_AUTHORIZATION &&
pac->pac_type != PAC_TYPE_MACHINE_AUTHENTICATION)
return "Unrecognized PAC-Type";
return NULL;
}
static const char * eap_fast_parse_pac_key(struct eap_fast_pac *pac, char *pos)
{
u8 *key;
size_t key_len;
key = eap_fast_parse_hex(pos, &key_len);
if (key == NULL || key_len != EAP_FAST_PAC_KEY_LEN) {
os_free(key);
return "Invalid PAC-Key";
}
os_memcpy(pac->pac_key, key, EAP_FAST_PAC_KEY_LEN);
os_free(key);
return NULL;
}
static const char * eap_fast_parse_pac_opaque(struct eap_fast_pac *pac,
char *pos)
{
os_free(pac->pac_opaque);
pac->pac_opaque = eap_fast_parse_hex(pos, &pac->pac_opaque_len);
if (pac->pac_opaque == NULL)
return "Invalid PAC-Opaque";
return NULL;
}
static const char * eap_fast_parse_a_id(struct eap_fast_pac *pac, char *pos)
{
os_free(pac->a_id);
pac->a_id = eap_fast_parse_hex(pos, &pac->a_id_len);
if (pac->a_id == NULL)
return "Invalid A-ID";
return NULL;
}
static const char * eap_fast_parse_i_id(struct eap_fast_pac *pac, char *pos)
{
os_free(pac->i_id);
pac->i_id = eap_fast_parse_hex(pos, &pac->i_id_len);
if (pac->i_id == NULL)
return "Invalid I-ID";
return NULL;
}
static const char * eap_fast_parse_a_id_info(struct eap_fast_pac *pac,
char *pos)
{
os_free(pac->a_id_info);
pac->a_id_info = eap_fast_parse_hex(pos, &pac->a_id_info_len);
if (pac->a_id_info == NULL)
return "Invalid A-ID-Info";
return NULL;
}
/**
* eap_fast_load_pac - Load PAC entries (text format)
* @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
* @pac_root: Pointer to root of the PAC list (to be filled)
* @pac_file: Name of the PAC file/blob to load
* Returns: 0 on success, -1 on failure
*/
int eap_fast_load_pac(struct eap_sm *sm, struct eap_fast_pac **pac_root,
const char *pac_file)
{
struct eap_fast_read_ctx rc;
struct eap_fast_pac *pac = NULL;
int count = 0;
char *pos;
const char *err = NULL;
if (pac_file == NULL)
return -1;
if (eap_fast_init_pac_data(sm, pac_file, &rc) < 0)
return 0;
if (eap_fast_read_line(&rc, &pos) < 0 ||
os_strcmp(pac_file_hdr, rc.buf) != 0)
err = "Unrecognized header line";
while (!err && eap_fast_read_line(&rc, &pos) == 0) {
if (os_strcmp(rc.buf, "START") == 0)
err = eap_fast_parse_start(&pac);
else if (os_strcmp(rc.buf, "END") == 0) {
err = eap_fast_parse_end(pac_root, &pac);
count++;
} else if (!pac)
err = "Unexpected line outside START/END block";
else if (os_strcmp(rc.buf, "PAC-Type") == 0)
err = eap_fast_parse_pac_type(pac, pos);
else if (os_strcmp(rc.buf, "PAC-Key") == 0)
err = eap_fast_parse_pac_key(pac, pos);
else if (os_strcmp(rc.buf, "PAC-Opaque") == 0)
err = eap_fast_parse_pac_opaque(pac, pos);
else if (os_strcmp(rc.buf, "A-ID") == 0)
err = eap_fast_parse_a_id(pac, pos);
else if (os_strcmp(rc.buf, "I-ID") == 0)
err = eap_fast_parse_i_id(pac, pos);
else if (os_strcmp(rc.buf, "A-ID-Info") == 0)
err = eap_fast_parse_a_id_info(pac, pos);
}
if (pac) {
err = "PAC block not terminated with END";
eap_fast_free_pac(pac);
}
eap_fast_deinit_pac_data(&rc);
if (err) {
wpa_printf(MSG_INFO, "EAP-FAST: %s in '%s:%d'",
err, pac_file, rc.line);
return -1;
}
wpa_printf(MSG_DEBUG, "EAP-FAST: Read %d PAC entries from '%s'",
count, pac_file);
return 0;
}
static void eap_fast_write(char **buf, char **pos, size_t *buf_len,
const char *field, const u8 *data,
size_t len, int txt)
{
size_t i, need;
int ret;
if (data == NULL || *buf == NULL)
return;
need = os_strlen(field) + len * 2 + 30;
if (txt)
need += os_strlen(field) + len + 20;
if (*pos - *buf + need > *buf_len) {
char *nbuf = os_realloc(*buf, *buf_len + need);
if (nbuf == NULL) {
os_free(*buf);
*buf = NULL;
return;
}
*buf = nbuf;
*buf_len += need;
}
ret = os_snprintf(*pos, *buf + *buf_len - *pos, "%s=", field);
if (ret < 0 || ret >= *buf + *buf_len - *pos)
return;
*pos += ret;
*pos += wpa_snprintf_hex(*pos, *buf + *buf_len - *pos, data, len);
ret = os_snprintf(*pos, *buf + *buf_len - *pos, "\n");
if (ret < 0 || ret >= *buf + *buf_len - *pos)
return;
*pos += ret;
if (txt) {
ret = os_snprintf(*pos, *buf + *buf_len - *pos,
"%s-txt=", field);
if (ret < 0 || ret >= *buf + *buf_len - *pos)
return;
*pos += ret;
for (i = 0; i < len; i++) {
ret = os_snprintf(*pos, *buf + *buf_len - *pos,
"%c", data[i]);
if (ret < 0 || ret >= *buf + *buf_len - *pos)
return;
*pos += ret;
}
ret = os_snprintf(*pos, *buf + *buf_len - *pos, "\n");
if (ret < 0 || ret >= *buf + *buf_len - *pos)
return;
*pos += ret;
}
}
static int eap_fast_write_pac(struct eap_sm *sm, const char *pac_file,
char *buf, size_t len)
{
if (os_strncmp(pac_file, "blob://", 7) == 0) {
struct wpa_config_blob *blob;
blob = os_zalloc(sizeof(*blob));
if (blob == NULL)
return -1;
blob->data = (u8 *) buf;
blob->len = len;
buf = NULL;
blob->name = os_strdup(pac_file + 7);
if (blob->name == NULL) {
os_free(blob);
return -1;
}
eap_set_config_blob(sm, blob);
} else {
FILE *f;
f = fopen(pac_file, "wb");
if (f == NULL) {
wpa_printf(MSG_INFO, "EAP-FAST: Failed to open PAC "
"file '%s' for writing", pac_file);
return -1;
}
if (fwrite(buf, 1, len, f) != len) {
wpa_printf(MSG_INFO, "EAP-FAST: Failed to write all "
"PACs into '%s'", pac_file);
fclose(f);
return -1;
}
os_free(buf);
fclose(f);
}
return 0;
}
static int eap_fast_add_pac_data(struct eap_fast_pac *pac, char **buf,
char **pos, size_t *buf_len)
{
int ret;
ret = os_snprintf(*pos, *buf + *buf_len - *pos,
"START\nPAC-Type=%d\n", pac->pac_type);
if (ret < 0 || ret >= *buf + *buf_len - *pos)
return -1;
*pos += ret;
eap_fast_write(buf, pos, buf_len, "PAC-Key",
pac->pac_key, EAP_FAST_PAC_KEY_LEN, 0);
eap_fast_write(buf, pos, buf_len, "PAC-Opaque",
pac->pac_opaque, pac->pac_opaque_len, 0);
eap_fast_write(buf, pos, buf_len, "PAC-Info",
pac->pac_info, pac->pac_info_len, 0);
eap_fast_write(buf, pos, buf_len, "A-ID",
pac->a_id, pac->a_id_len, 0);
eap_fast_write(buf, pos, buf_len, "I-ID",
pac->i_id, pac->i_id_len, 1);
eap_fast_write(buf, pos, buf_len, "A-ID-Info",
pac->a_id_info, pac->a_id_info_len, 1);
if (*buf == NULL) {
wpa_printf(MSG_DEBUG, "EAP-FAST: No memory for PAC "
"data");
return -1;
}
ret = os_snprintf(*pos, *buf + *buf_len - *pos, "END\n");
if (ret < 0 || ret >= *buf + *buf_len - *pos)
return -1;
*pos += ret;
return 0;
}
/**
* eap_fast_save_pac - Save PAC entries (text format)
* @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
* @pac_root: Root of the PAC list
* @pac_file: Name of the PAC file/blob
* Returns: 0 on success, -1 on failure
*/
int eap_fast_save_pac(struct eap_sm *sm, struct eap_fast_pac *pac_root,
const char *pac_file)
{
struct eap_fast_pac *pac;
int ret, count = 0;
char *buf, *pos;
size_t buf_len;
if (pac_file == NULL)
return -1;
buf_len = 1024;
pos = buf = os_malloc(buf_len);
if (buf == NULL)
return -1;
ret = os_snprintf(pos, buf + buf_len - pos, "%s\n", pac_file_hdr);
if (ret < 0 || ret >= buf + buf_len - pos) {
os_free(buf);
return -1;
}
pos += ret;
pac = pac_root;
while (pac) {
if (eap_fast_add_pac_data(pac, &buf, &pos, &buf_len)) {
os_free(buf);
return -1;
}
count++;
pac = pac->next;
}
if (eap_fast_write_pac(sm, pac_file, buf, pos - buf)) {
os_free(buf);
return -1;
}
wpa_printf(MSG_DEBUG, "EAP-FAST: Wrote %d PAC entries into '%s'",
count, pac_file);
return 0;
}
/**
* eap_fast_pac_list_truncate - Truncate a PAC list to the given length
* @pac_root: Root of the PAC list
* @max_len: Maximum length of the list (>= 1)
* Returns: Number of PAC entries removed
*/
size_t eap_fast_pac_list_truncate(struct eap_fast_pac *pac_root,
size_t max_len)
{
struct eap_fast_pac *pac, *prev;
size_t count;
pac = pac_root;
prev = NULL;
count = 0;
while (pac) {
count++;
if (count > max_len)
break;
prev = pac;
pac = pac->next;
}
if (count <= max_len || prev == NULL)
return 0;
count = 0;
prev->next = NULL;
while (pac) {
prev = pac;
pac = pac->next;
eap_fast_free_pac(prev);
count++;
}
return count;
}
static void eap_fast_pac_get_a_id(struct eap_fast_pac *pac)
{
u8 *pos, *end;
u16 type, len;
pos = pac->pac_info;
end = pos + pac->pac_info_len;
while (pos + 4 < end) {
type = WPA_GET_BE16(pos);
pos += 2;
len = WPA_GET_BE16(pos);
pos += 2;
if (pos + len > end)
break;
if (type == PAC_TYPE_A_ID) {
os_free(pac->a_id);
pac->a_id = os_malloc(len);
if (pac->a_id == NULL)
break;
os_memcpy(pac->a_id, pos, len);
pac->a_id_len = len;
}
if (type == PAC_TYPE_A_ID_INFO) {
os_free(pac->a_id_info);
pac->a_id_info = os_malloc(len);
if (pac->a_id_info == NULL)
break;
os_memcpy(pac->a_id_info, pos, len);
pac->a_id_info_len = len;
}
pos += len;
}
}
/**
* eap_fast_load_pac_bin - Load PAC entries (binary format)
* @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
* @pac_root: Pointer to root of the PAC list (to be filled)
* @pac_file: Name of the PAC file/blob to load
* Returns: 0 on success, -1 on failure
*/
int eap_fast_load_pac_bin(struct eap_sm *sm, struct eap_fast_pac **pac_root,
const char *pac_file)
{
const struct wpa_config_blob *blob = NULL;
u8 *buf, *end, *pos;
size_t len, count = 0;
struct eap_fast_pac *pac, *prev;
*pac_root = NULL;
if (pac_file == NULL)
return -1;
if (os_strncmp(pac_file, "blob://", 7) == 0) {
blob = eap_get_config_blob(sm, pac_file + 7);
if (blob == NULL) {
wpa_printf(MSG_INFO, "EAP-FAST: No PAC blob '%s' - "
"assume no PAC entries have been "
"provisioned", pac_file + 7);
return 0;
}
buf = blob->data;
len = blob->len;
} else {
buf = (u8 *) os_readfile(pac_file, &len);
if (buf == NULL) {
wpa_printf(MSG_INFO, "EAP-FAST: No PAC file '%s' - "
"assume no PAC entries have been "
"provisioned", pac_file);
return 0;
}
}
if (len == 0) {
if (blob == NULL)
os_free(buf);
return 0;
}
if (len < 6 || WPA_GET_BE32(buf) != EAP_FAST_PAC_BINARY_MAGIC ||
WPA_GET_BE16(buf + 4) != EAP_FAST_PAC_BINARY_FORMAT_VERSION) {
wpa_printf(MSG_INFO, "EAP-FAST: Invalid PAC file '%s' (bin)",
pac_file);
if (blob == NULL)
os_free(buf);
return -1;
}
pac = prev = NULL;
pos = buf + 6;
end = buf + len;
while (pos < end) {
if (end - pos < 2 + 32 + 2 + 2)
goto parse_fail;
pac = os_zalloc(sizeof(*pac));
if (pac == NULL)
goto parse_fail;
pac->pac_type = WPA_GET_BE16(pos);
pos += 2;
os_memcpy(pac->pac_key, pos, EAP_FAST_PAC_KEY_LEN);
pos += EAP_FAST_PAC_KEY_LEN;
pac->pac_opaque_len = WPA_GET_BE16(pos);
pos += 2;
if (pos + pac->pac_opaque_len + 2 > end)
goto parse_fail;
pac->pac_opaque = os_malloc(pac->pac_opaque_len);
if (pac->pac_opaque == NULL)
goto parse_fail;
os_memcpy(pac->pac_opaque, pos, pac->pac_opaque_len);
pos += pac->pac_opaque_len;
pac->pac_info_len = WPA_GET_BE16(pos);
pos += 2;
if (pos + pac->pac_info_len > end)
goto parse_fail;
pac->pac_info = os_malloc(pac->pac_info_len);
if (pac->pac_info == NULL)
goto parse_fail;
os_memcpy(pac->pac_info, pos, pac->pac_info_len);
pos += pac->pac_info_len;
eap_fast_pac_get_a_id(pac);
count++;
if (prev)
prev->next = pac;
else
*pac_root = pac;
prev = pac;
}
if (blob == NULL)
os_free(buf);
wpa_printf(MSG_DEBUG, "EAP-FAST: Read %lu PAC entries from '%s' (bin)",
(unsigned long) count, pac_file);
return 0;
parse_fail:
wpa_printf(MSG_INFO, "EAP-FAST: Failed to parse PAC file '%s' (bin)",
pac_file);
if (blob == NULL)
os_free(buf);
if (pac)
eap_fast_free_pac(pac);
return -1;
}
/**
* eap_fast_save_pac_bin - Save PAC entries (binary format)
* @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
* @pac_root: Root of the PAC list
* @pac_file: Name of the PAC file/blob
* Returns: 0 on success, -1 on failure
*/
int eap_fast_save_pac_bin(struct eap_sm *sm, struct eap_fast_pac *pac_root,
const char *pac_file)
{
size_t len, count = 0;
struct eap_fast_pac *pac;
u8 *buf, *pos;
len = 6;
pac = pac_root;
while (pac) {
if (pac->pac_opaque_len > 65535 ||
pac->pac_info_len > 65535)
return -1;
len += 2 + EAP_FAST_PAC_KEY_LEN + 2 + pac->pac_opaque_len +
2 + pac->pac_info_len;
pac = pac->next;
}
buf = os_malloc(len);
if (buf == NULL)
return -1;
pos = buf;
WPA_PUT_BE32(pos, EAP_FAST_PAC_BINARY_MAGIC);
pos += 4;
WPA_PUT_BE16(pos, EAP_FAST_PAC_BINARY_FORMAT_VERSION);
pos += 2;
pac = pac_root;
while (pac) {
WPA_PUT_BE16(pos, pac->pac_type);
pos += 2;
os_memcpy(pos, pac->pac_key, EAP_FAST_PAC_KEY_LEN);
pos += EAP_FAST_PAC_KEY_LEN;
WPA_PUT_BE16(pos, pac->pac_opaque_len);
pos += 2;
os_memcpy(pos, pac->pac_opaque, pac->pac_opaque_len);
pos += pac->pac_opaque_len;
WPA_PUT_BE16(pos, pac->pac_info_len);
pos += 2;
os_memcpy(pos, pac->pac_info, pac->pac_info_len);
pos += pac->pac_info_len;
pac = pac->next;
count++;
}
if (eap_fast_write_pac(sm, pac_file, (char *) buf, len)) {
os_free(buf);
return -1;
}
wpa_printf(MSG_DEBUG, "EAP-FAST: Wrote %lu PAC entries into '%s' "
"(bin)", (unsigned long) count, pac_file);
return 0;
}
| gpl-2.0 |
DerArtem/folio100-kernel-2.6.32-toshiba | drivers/hwmon/tmp421.c | 336 | 8790 | /* tmp421.c
*
* Copyright (C) 2009 Andre Prendel <andre.prendel@gmx.de>
* Preliminary support by:
* Melvin Rook, Raymond Ng
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* Driver for the Texas Instruments TMP421 SMBus temperature sensor IC.
* Supported models: TMP421, TMP422, TMP423
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <linux/i2c.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/err.h>
#include <linux/mutex.h>
#include <linux/sysfs.h>
/* Addresses to scan */
static unsigned short normal_i2c[] = { 0x2a, 0x4c, 0x4d, 0x4e, 0x4f,
I2C_CLIENT_END };
/* Insmod parameters */
I2C_CLIENT_INSMOD_3(tmp421, tmp422, tmp423);
/* The TMP421 registers */
#define TMP421_CONFIG_REG_1 0x09
#define TMP421_CONVERSION_RATE_REG 0x0B
#define TMP421_MANUFACTURER_ID_REG 0xFE
#define TMP421_DEVICE_ID_REG 0xFF
static const u8 TMP421_TEMP_MSB[4] = { 0x00, 0x01, 0x02, 0x03 };
static const u8 TMP421_TEMP_LSB[4] = { 0x10, 0x11, 0x12, 0x13 };
/* Flags */
#define TMP421_CONFIG_SHUTDOWN 0x40
#define TMP421_CONFIG_RANGE 0x04
/* Manufacturer / Device ID's */
#define TMP421_MANUFACTURER_ID 0x55
#define TMP421_DEVICE_ID 0x21
#define TMP422_DEVICE_ID 0x22
#define TMP423_DEVICE_ID 0x23
static const struct i2c_device_id tmp421_id[] = {
{ "tmp421", tmp421 },
{ "tmp422", tmp422 },
{ "tmp423", tmp423 },
{ }
};
MODULE_DEVICE_TABLE(i2c, tmp421_id);
struct tmp421_data {
struct device *hwmon_dev;
struct mutex update_lock;
char valid;
unsigned long last_updated;
int kind;
u8 config;
s16 temp[4];
};
static int temp_from_s16(s16 reg)
{
int temp = reg;
return (temp * 1000 + 128) / 256;
}
static int temp_from_u16(u16 reg)
{
int temp = reg;
/* Add offset for extended temperature range. */
temp -= 64 * 256;
return (temp * 1000 + 128) / 256;
}
static struct tmp421_data *tmp421_update_device(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct tmp421_data *data = i2c_get_clientdata(client);
int i;
mutex_lock(&data->update_lock);
if (time_after(jiffies, data->last_updated + 2 * HZ) || !data->valid) {
data->config = i2c_smbus_read_byte_data(client,
TMP421_CONFIG_REG_1);
for (i = 0; i <= data->kind; i++) {
data->temp[i] = i2c_smbus_read_byte_data(client,
TMP421_TEMP_MSB[i]) << 8;
data->temp[i] |= i2c_smbus_read_byte_data(client,
TMP421_TEMP_LSB[i]);
}
data->last_updated = jiffies;
data->valid = 1;
}
mutex_unlock(&data->update_lock);
return data;
}
static ssize_t show_temp_value(struct device *dev,
struct device_attribute *devattr, char *buf)
{
int index = to_sensor_dev_attr(devattr)->index;
struct tmp421_data *data = tmp421_update_device(dev);
int temp;
mutex_lock(&data->update_lock);
if (data->config & TMP421_CONFIG_RANGE)
temp = temp_from_u16(data->temp[index]);
else
temp = temp_from_s16(data->temp[index]);
mutex_unlock(&data->update_lock);
return sprintf(buf, "%d\n", temp);
}
static ssize_t show_fault(struct device *dev,
struct device_attribute *devattr, char *buf)
{
int index = to_sensor_dev_attr(devattr)->index;
struct tmp421_data *data = tmp421_update_device(dev);
/*
* The OPEN bit signals a fault. This is bit 0 of the temperature
* register (low byte).
*/
if (data->temp[index] & 0x01)
return sprintf(buf, "1\n");
else
return sprintf(buf, "0\n");
}
static mode_t tmp421_is_visible(struct kobject *kobj, struct attribute *a,
int n)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct tmp421_data *data = dev_get_drvdata(dev);
struct device_attribute *devattr;
unsigned int index;
devattr = container_of(a, struct device_attribute, attr);
index = to_sensor_dev_attr(devattr)->index;
if (data->kind > index)
return a->mode;
return 0;
}
static SENSOR_DEVICE_ATTR(temp1_input, S_IRUGO, show_temp_value, NULL, 0);
static SENSOR_DEVICE_ATTR(temp2_input, S_IRUGO, show_temp_value, NULL, 1);
static SENSOR_DEVICE_ATTR(temp2_fault, S_IRUGO, show_fault, NULL, 1);
static SENSOR_DEVICE_ATTR(temp3_input, S_IRUGO, show_temp_value, NULL, 2);
static SENSOR_DEVICE_ATTR(temp3_fault, S_IRUGO, show_fault, NULL, 2);
static SENSOR_DEVICE_ATTR(temp4_input, S_IRUGO, show_temp_value, NULL, 3);
static SENSOR_DEVICE_ATTR(temp4_fault, S_IRUGO, show_fault, NULL, 3);
static struct attribute *tmp421_attr[] = {
&sensor_dev_attr_temp1_input.dev_attr.attr,
&sensor_dev_attr_temp2_input.dev_attr.attr,
&sensor_dev_attr_temp2_fault.dev_attr.attr,
&sensor_dev_attr_temp3_input.dev_attr.attr,
&sensor_dev_attr_temp3_fault.dev_attr.attr,
&sensor_dev_attr_temp4_input.dev_attr.attr,
&sensor_dev_attr_temp4_fault.dev_attr.attr,
NULL
};
static const struct attribute_group tmp421_group = {
.attrs = tmp421_attr,
.is_visible = tmp421_is_visible,
};
static int tmp421_init_client(struct i2c_client *client)
{
int config, config_orig;
/* Set the conversion rate to 2 Hz */
i2c_smbus_write_byte_data(client, TMP421_CONVERSION_RATE_REG, 0x05);
/* Start conversions (disable shutdown if necessary) */
config = i2c_smbus_read_byte_data(client, TMP421_CONFIG_REG_1);
if (config < 0) {
dev_err(&client->dev, "Could not read configuration"
" register (%d)\n", config);
return -ENODEV;
}
config_orig = config;
config &= ~TMP421_CONFIG_SHUTDOWN;
if (config != config_orig) {
dev_info(&client->dev, "Enable monitoring chip\n");
i2c_smbus_write_byte_data(client, TMP421_CONFIG_REG_1, config);
}
return 0;
}
static int tmp421_detect(struct i2c_client *client, int kind,
struct i2c_board_info *info)
{
struct i2c_adapter *adapter = client->adapter;
const char *names[] = { "TMP421", "TMP422", "TMP423" };
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA))
return -ENODEV;
if (kind <= 0) {
u8 reg;
reg = i2c_smbus_read_byte_data(client,
TMP421_MANUFACTURER_ID_REG);
if (reg != TMP421_MANUFACTURER_ID)
return -ENODEV;
reg = i2c_smbus_read_byte_data(client,
TMP421_DEVICE_ID_REG);
switch (reg) {
case TMP421_DEVICE_ID:
kind = tmp421;
break;
case TMP422_DEVICE_ID:
kind = tmp422;
break;
case TMP423_DEVICE_ID:
kind = tmp423;
break;
default:
return -ENODEV;
}
}
strlcpy(info->type, tmp421_id[kind - 1].name, I2C_NAME_SIZE);
dev_info(&adapter->dev, "Detected TI %s chip at 0x%02x\n",
names[kind - 1], client->addr);
return 0;
}
static int tmp421_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct tmp421_data *data;
int err;
data = kzalloc(sizeof(struct tmp421_data), GFP_KERNEL);
if (!data)
return -ENOMEM;
i2c_set_clientdata(client, data);
mutex_init(&data->update_lock);
data->kind = id->driver_data;
err = tmp421_init_client(client);
if (err)
goto exit_free;
err = sysfs_create_group(&client->dev.kobj, &tmp421_group);
if (err)
goto exit_free;
data->hwmon_dev = hwmon_device_register(&client->dev);
if (IS_ERR(data->hwmon_dev)) {
err = PTR_ERR(data->hwmon_dev);
data->hwmon_dev = NULL;
goto exit_remove;
}
return 0;
exit_remove:
sysfs_remove_group(&client->dev.kobj, &tmp421_group);
exit_free:
i2c_set_clientdata(client, NULL);
kfree(data);
return err;
}
static int tmp421_remove(struct i2c_client *client)
{
struct tmp421_data *data = i2c_get_clientdata(client);
hwmon_device_unregister(data->hwmon_dev);
sysfs_remove_group(&client->dev.kobj, &tmp421_group);
i2c_set_clientdata(client, NULL);
kfree(data);
return 0;
}
static struct i2c_driver tmp421_driver = {
.class = I2C_CLASS_HWMON,
.driver = {
.name = "tmp421",
},
.probe = tmp421_probe,
.remove = tmp421_remove,
.id_table = tmp421_id,
.detect = tmp421_detect,
.address_data = &addr_data,
};
static int __init tmp421_init(void)
{
return i2c_add_driver(&tmp421_driver);
}
static void __exit tmp421_exit(void)
{
i2c_del_driver(&tmp421_driver);
}
MODULE_AUTHOR("Andre Prendel <andre.prendel@gmx.de>");
MODULE_DESCRIPTION("Texas Instruments TMP421/422/423 temperature sensor"
" driver");
MODULE_LICENSE("GPL");
module_init(tmp421_init);
module_exit(tmp421_exit);
| gpl-2.0 |
daedae1112/kernel | sound/isa/opl3sa2.c | 592 | 29942 | /*
* Driver for Yamaha OPL3-SA[2,3] soundcards
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/init.h>
#include <linux/err.h>
#include <linux/isa.h>
#include <linux/interrupt.h>
#include <linux/pm.h>
#include <linux/slab.h>
#include <linux/pnp.h>
#include <linux/moduleparam.h>
#include <sound/core.h>
#include <sound/wss.h>
#include <sound/mpu401.h>
#include <sound/opl3.h>
#include <sound/initval.h>
#include <sound/tlv.h>
#include <asm/io.h>
MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>");
MODULE_DESCRIPTION("Yamaha OPL3SA2+");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("{{Yamaha,YMF719E-S},"
"{Genius,Sound Maker 3DX},"
"{Yamaha,OPL3SA3},"
"{Intel,AL440LX sound},"
"{NeoMagic,MagicWave 3DX}}");
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */
static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_ISAPNP; /* Enable this card */
#ifdef CONFIG_PNP
static int isapnp[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 1};
#endif
static long port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* 0xf86,0x370,0x100 */
static long sb_port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* 0x220,0x240,0x260 */
static long wss_port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT;/* 0x530,0xe80,0xf40,0x604 */
static long fm_port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* 0x388 */
static long midi_port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT;/* 0x330,0x300 */
static int irq[SNDRV_CARDS] = SNDRV_DEFAULT_IRQ; /* 0,1,3,5,9,11,12,15 */
static int dma1[SNDRV_CARDS] = SNDRV_DEFAULT_DMA; /* 1,3,5,6,7 */
static int dma2[SNDRV_CARDS] = SNDRV_DEFAULT_DMA; /* 1,3,5,6,7 */
static int opl3sa3_ymode[SNDRV_CARDS]; /* 0,1,2,3 */ /*SL Added*/
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for OPL3-SA soundcard.");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for OPL3-SA soundcard.");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable OPL3-SA soundcard.");
#ifdef CONFIG_PNP
module_param_array(isapnp, bool, NULL, 0444);
MODULE_PARM_DESC(isapnp, "PnP detection for specified soundcard.");
#endif
module_param_array(port, long, NULL, 0444);
MODULE_PARM_DESC(port, "Port # for OPL3-SA driver.");
module_param_array(sb_port, long, NULL, 0444);
MODULE_PARM_DESC(sb_port, "SB port # for OPL3-SA driver.");
module_param_array(wss_port, long, NULL, 0444);
MODULE_PARM_DESC(wss_port, "WSS port # for OPL3-SA driver.");
module_param_array(fm_port, long, NULL, 0444);
MODULE_PARM_DESC(fm_port, "FM port # for OPL3-SA driver.");
module_param_array(midi_port, long, NULL, 0444);
MODULE_PARM_DESC(midi_port, "MIDI port # for OPL3-SA driver.");
module_param_array(irq, int, NULL, 0444);
MODULE_PARM_DESC(irq, "IRQ # for OPL3-SA driver.");
module_param_array(dma1, int, NULL, 0444);
MODULE_PARM_DESC(dma1, "DMA1 # for OPL3-SA driver.");
module_param_array(dma2, int, NULL, 0444);
MODULE_PARM_DESC(dma2, "DMA2 # for OPL3-SA driver.");
module_param_array(opl3sa3_ymode, int, NULL, 0444);
MODULE_PARM_DESC(opl3sa3_ymode, "Speaker size selection for 3D Enhancement mode: Desktop/Large Notebook/Small Notebook/HiFi.");
#ifdef CONFIG_PNP
static int isa_registered;
static int pnp_registered;
static int pnpc_registered;
#endif
/* control ports */
#define OPL3SA2_PM_CTRL 0x01
#define OPL3SA2_SYS_CTRL 0x02
#define OPL3SA2_IRQ_CONFIG 0x03
#define OPL3SA2_IRQ_STATUS 0x04
#define OPL3SA2_DMA_CONFIG 0x06
#define OPL3SA2_MASTER_LEFT 0x07
#define OPL3SA2_MASTER_RIGHT 0x08
#define OPL3SA2_MIC 0x09
#define OPL3SA2_MISC 0x0A
/* opl3sa3 only */
#define OPL3SA3_DGTL_DOWN 0x12
#define OPL3SA3_ANLG_DOWN 0x13
#define OPL3SA3_WIDE 0x14
#define OPL3SA3_BASS 0x15
#define OPL3SA3_TREBLE 0x16
/* power management bits */
#define OPL3SA2_PM_ADOWN 0x20
#define OPL3SA2_PM_PSV 0x04
#define OPL3SA2_PM_PDN 0x02
#define OPL3SA2_PM_PDX 0x01
#define OPL3SA2_PM_D0 0x00
#define OPL3SA2_PM_D3 (OPL3SA2_PM_ADOWN|OPL3SA2_PM_PSV|OPL3SA2_PM_PDN|OPL3SA2_PM_PDX)
struct snd_opl3sa2 {
int version; /* 2 or 3 */
unsigned long port; /* control port */
struct resource *res_port; /* control port resource */
int irq;
int single_dma;
spinlock_t reg_lock;
struct snd_hwdep *synth;
struct snd_rawmidi *rmidi;
struct snd_wss *wss;
unsigned char ctlregs[0x20];
int ymode; /* SL added */
struct snd_kcontrol *master_switch;
struct snd_kcontrol *master_volume;
};
#define PFX "opl3sa2: "
#ifdef CONFIG_PNP
static struct pnp_device_id snd_opl3sa2_pnpbiosids[] = {
{ .id = "YMH0021" },
{ .id = "NMX2210" }, /* Gateway Solo 2500 */
{ .id = "" } /* end */
};
MODULE_DEVICE_TABLE(pnp, snd_opl3sa2_pnpbiosids);
static struct pnp_card_device_id snd_opl3sa2_pnpids[] = {
/* Yamaha YMF719E-S (Genius Sound Maker 3DX) */
{ .id = "YMH0020", .devs = { { "YMH0021" } } },
/* Yamaha OPL3-SA3 (integrated on Intel's Pentium II AL440LX motherboard) */
{ .id = "YMH0030", .devs = { { "YMH0021" } } },
/* Yamaha OPL3-SA2 */
{ .id = "YMH0800", .devs = { { "YMH0021" } } },
/* Yamaha OPL3-SA2 */
{ .id = "YMH0801", .devs = { { "YMH0021" } } },
/* NeoMagic MagicWave 3DX */
{ .id = "NMX2200", .devs = { { "YMH2210" } } },
/* NeoMagic MagicWave 3D */
{ .id = "NMX2200", .devs = { { "NMX2210" } } },
/* --- */
{ .id = "" } /* end */
};
MODULE_DEVICE_TABLE(pnp_card, snd_opl3sa2_pnpids);
#endif /* CONFIG_PNP */
/* read control port (w/o spinlock) */
static unsigned char __snd_opl3sa2_read(struct snd_opl3sa2 *chip, unsigned char reg)
{
unsigned char result;
#if 0
outb(0x1d, port); /* password */
printk(KERN_DEBUG "read [0x%lx] = 0x%x\n", port, inb(port));
#endif
outb(reg, chip->port); /* register */
result = inb(chip->port + 1);
#if 0
printk(KERN_DEBUG "read [0x%lx] = 0x%x [0x%x]\n",
port, result, inb(port));
#endif
return result;
}
/* read control port (with spinlock) */
static unsigned char snd_opl3sa2_read(struct snd_opl3sa2 *chip, unsigned char reg)
{
unsigned long flags;
unsigned char result;
spin_lock_irqsave(&chip->reg_lock, flags);
result = __snd_opl3sa2_read(chip, reg);
spin_unlock_irqrestore(&chip->reg_lock, flags);
return result;
}
/* write control port (w/o spinlock) */
static void __snd_opl3sa2_write(struct snd_opl3sa2 *chip, unsigned char reg, unsigned char value)
{
#if 0
outb(0x1d, port); /* password */
#endif
outb(reg, chip->port); /* register */
outb(value, chip->port + 1);
chip->ctlregs[reg] = value;
}
/* write control port (with spinlock) */
static void snd_opl3sa2_write(struct snd_opl3sa2 *chip, unsigned char reg, unsigned char value)
{
unsigned long flags;
spin_lock_irqsave(&chip->reg_lock, flags);
__snd_opl3sa2_write(chip, reg, value);
spin_unlock_irqrestore(&chip->reg_lock, flags);
}
static int __devinit snd_opl3sa2_detect(struct snd_card *card)
{
struct snd_opl3sa2 *chip = card->private_data;
unsigned long port;
unsigned char tmp, tmp1;
char str[2];
port = chip->port;
if ((chip->res_port = request_region(port, 2, "OPL3-SA control")) == NULL) {
snd_printk(KERN_ERR PFX "can't grab port 0x%lx\n", port);
return -EBUSY;
}
/*
snd_printk(KERN_DEBUG "REG 0A = 0x%x\n",
snd_opl3sa2_read(chip, 0x0a));
*/
chip->version = 0;
tmp = snd_opl3sa2_read(chip, OPL3SA2_MISC);
if (tmp == 0xff) {
snd_printd("OPL3-SA [0x%lx] detect = 0x%x\n", port, tmp);
return -ENODEV;
}
switch (tmp & 0x07) {
case 0x01:
chip->version = 2; /* YMF711 */
break;
default:
chip->version = 3;
/* 0x02 - standard */
/* 0x03 - YM715B */
/* 0x04 - YM719 - OPL-SA4? */
/* 0x05 - OPL3-SA3 - Libretto 100 */
/* 0x07 - unknown - Neomagic MagicWave 3D */
break;
}
str[0] = chip->version + '0';
str[1] = 0;
strcat(card->shortname, str);
snd_opl3sa2_write(chip, OPL3SA2_MISC, tmp ^ 7);
if ((tmp1 = snd_opl3sa2_read(chip, OPL3SA2_MISC)) != tmp) {
snd_printd("OPL3-SA [0x%lx] detect (1) = 0x%x (0x%x)\n", port, tmp, tmp1);
return -ENODEV;
}
/* try if the MIC register is accesible */
tmp = snd_opl3sa2_read(chip, OPL3SA2_MIC);
snd_opl3sa2_write(chip, OPL3SA2_MIC, 0x8a);
if (((tmp1 = snd_opl3sa2_read(chip, OPL3SA2_MIC)) & 0x9f) != 0x8a) {
snd_printd("OPL3-SA [0x%lx] detect (2) = 0x%x (0x%x)\n", port, tmp, tmp1);
return -ENODEV;
}
snd_opl3sa2_write(chip, OPL3SA2_MIC, 0x9f);
/* initialization */
/* Power Management - full on */
snd_opl3sa2_write(chip, OPL3SA2_PM_CTRL, OPL3SA2_PM_D0);
if (chip->version > 2) {
/* ymode is bits 4&5 (of 0 to 7) on all but opl3sa2 versions */
snd_opl3sa2_write(chip, OPL3SA2_SYS_CTRL, (chip->ymode << 4));
} else {
/* default for opl3sa2 versions */
snd_opl3sa2_write(chip, OPL3SA2_SYS_CTRL, 0x00);
}
snd_opl3sa2_write(chip, OPL3SA2_IRQ_CONFIG, 0x0d); /* Interrupt Channel Configuration - IRQ A = OPL3 + MPU + WSS */
if (chip->single_dma) {
snd_opl3sa2_write(chip, OPL3SA2_DMA_CONFIG, 0x03); /* DMA Configuration - DMA A = WSS-R + WSS-P */
} else {
snd_opl3sa2_write(chip, OPL3SA2_DMA_CONFIG, 0x21); /* DMA Configuration - DMA B = WSS-R, DMA A = WSS-P */
}
snd_opl3sa2_write(chip, OPL3SA2_MISC, 0x80 | (tmp & 7)); /* Miscellaneous - default */
if (chip->version > 2) {
snd_opl3sa2_write(chip, OPL3SA3_DGTL_DOWN, 0x00); /* Digital Block Partial Power Down - default */
snd_opl3sa2_write(chip, OPL3SA3_ANLG_DOWN, 0x00); /* Analog Block Partial Power Down - default */
}
return 0;
}
static irqreturn_t snd_opl3sa2_interrupt(int irq, void *dev_id)
{
unsigned short status;
struct snd_card *card = dev_id;
struct snd_opl3sa2 *chip;
int handled = 0;
if (card == NULL)
return IRQ_NONE;
chip = card->private_data;
status = snd_opl3sa2_read(chip, OPL3SA2_IRQ_STATUS);
if (status & 0x20) {
handled = 1;
snd_opl3_interrupt(chip->synth);
}
if ((status & 0x10) && chip->rmidi != NULL) {
handled = 1;
snd_mpu401_uart_interrupt(irq, chip->rmidi->private_data);
}
if (status & 0x07) { /* TI,CI,PI */
handled = 1;
snd_wss_interrupt(irq, chip->wss);
}
if (status & 0x40) { /* hardware volume change */
handled = 1;
/* reading from Master Lch register at 0x07 clears this bit */
snd_opl3sa2_read(chip, OPL3SA2_MASTER_RIGHT);
snd_opl3sa2_read(chip, OPL3SA2_MASTER_LEFT);
if (chip->master_switch && chip->master_volume) {
snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE,
&chip->master_switch->id);
snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE,
&chip->master_volume->id);
}
}
return IRQ_RETVAL(handled);
}
#define OPL3SA2_SINGLE(xname, xindex, reg, shift, mask, invert) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, .index = xindex, \
.info = snd_wss_info_single, \
.get = snd_opl3sa2_get_single, .put = snd_opl3sa2_put_single, \
.private_value = reg | (shift << 8) | (mask << 16) | (invert << 24) }
#define OPL3SA2_SINGLE_TLV(xname, xindex, reg, shift, mask, invert, xtlv) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, \
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE | SNDRV_CTL_ELEM_ACCESS_TLV_READ, \
.name = xname, .index = xindex, \
.info = snd_wss_info_single, \
.get = snd_opl3sa2_get_single, .put = snd_opl3sa2_put_single, \
.private_value = reg | (shift << 8) | (mask << 16) | (invert << 24), \
.tlv = { .p = (xtlv) } }
static int snd_opl3sa2_get_single(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_opl3sa2 *chip = snd_kcontrol_chip(kcontrol);
unsigned long flags;
int reg = kcontrol->private_value & 0xff;
int shift = (kcontrol->private_value >> 8) & 0xff;
int mask = (kcontrol->private_value >> 16) & 0xff;
int invert = (kcontrol->private_value >> 24) & 0xff;
spin_lock_irqsave(&chip->reg_lock, flags);
ucontrol->value.integer.value[0] = (chip->ctlregs[reg] >> shift) & mask;
spin_unlock_irqrestore(&chip->reg_lock, flags);
if (invert)
ucontrol->value.integer.value[0] = mask - ucontrol->value.integer.value[0];
return 0;
}
static int snd_opl3sa2_put_single(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_opl3sa2 *chip = snd_kcontrol_chip(kcontrol);
unsigned long flags;
int reg = kcontrol->private_value & 0xff;
int shift = (kcontrol->private_value >> 8) & 0xff;
int mask = (kcontrol->private_value >> 16) & 0xff;
int invert = (kcontrol->private_value >> 24) & 0xff;
int change;
unsigned short val, oval;
val = (ucontrol->value.integer.value[0] & mask);
if (invert)
val = mask - val;
val <<= shift;
spin_lock_irqsave(&chip->reg_lock, flags);
oval = chip->ctlregs[reg];
val = (oval & ~(mask << shift)) | val;
change = val != oval;
__snd_opl3sa2_write(chip, reg, val);
spin_unlock_irqrestore(&chip->reg_lock, flags);
return change;
}
#define OPL3SA2_DOUBLE(xname, xindex, left_reg, right_reg, shift_left, shift_right, mask, invert) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, .index = xindex, \
.info = snd_wss_info_double, \
.get = snd_opl3sa2_get_double, .put = snd_opl3sa2_put_double, \
.private_value = left_reg | (right_reg << 8) | (shift_left << 16) | (shift_right << 19) | (mask << 24) | (invert << 22) }
#define OPL3SA2_DOUBLE_TLV(xname, xindex, left_reg, right_reg, shift_left, shift_right, mask, invert, xtlv) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, \
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE | SNDRV_CTL_ELEM_ACCESS_TLV_READ, \
.name = xname, .index = xindex, \
.info = snd_wss_info_double, \
.get = snd_opl3sa2_get_double, .put = snd_opl3sa2_put_double, \
.private_value = left_reg | (right_reg << 8) | (shift_left << 16) | (shift_right << 19) | (mask << 24) | (invert << 22), \
.tlv = { .p = (xtlv) } }
static int snd_opl3sa2_get_double(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_opl3sa2 *chip = snd_kcontrol_chip(kcontrol);
unsigned long flags;
int left_reg = kcontrol->private_value & 0xff;
int right_reg = (kcontrol->private_value >> 8) & 0xff;
int shift_left = (kcontrol->private_value >> 16) & 0x07;
int shift_right = (kcontrol->private_value >> 19) & 0x07;
int mask = (kcontrol->private_value >> 24) & 0xff;
int invert = (kcontrol->private_value >> 22) & 1;
spin_lock_irqsave(&chip->reg_lock, flags);
ucontrol->value.integer.value[0] = (chip->ctlregs[left_reg] >> shift_left) & mask;
ucontrol->value.integer.value[1] = (chip->ctlregs[right_reg] >> shift_right) & mask;
spin_unlock_irqrestore(&chip->reg_lock, flags);
if (invert) {
ucontrol->value.integer.value[0] = mask - ucontrol->value.integer.value[0];
ucontrol->value.integer.value[1] = mask - ucontrol->value.integer.value[1];
}
return 0;
}
static int snd_opl3sa2_put_double(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_opl3sa2 *chip = snd_kcontrol_chip(kcontrol);
unsigned long flags;
int left_reg = kcontrol->private_value & 0xff;
int right_reg = (kcontrol->private_value >> 8) & 0xff;
int shift_left = (kcontrol->private_value >> 16) & 0x07;
int shift_right = (kcontrol->private_value >> 19) & 0x07;
int mask = (kcontrol->private_value >> 24) & 0xff;
int invert = (kcontrol->private_value >> 22) & 1;
int change;
unsigned short val1, val2, oval1, oval2;
val1 = ucontrol->value.integer.value[0] & mask;
val2 = ucontrol->value.integer.value[1] & mask;
if (invert) {
val1 = mask - val1;
val2 = mask - val2;
}
val1 <<= shift_left;
val2 <<= shift_right;
spin_lock_irqsave(&chip->reg_lock, flags);
if (left_reg != right_reg) {
oval1 = chip->ctlregs[left_reg];
oval2 = chip->ctlregs[right_reg];
val1 = (oval1 & ~(mask << shift_left)) | val1;
val2 = (oval2 & ~(mask << shift_right)) | val2;
change = val1 != oval1 || val2 != oval2;
__snd_opl3sa2_write(chip, left_reg, val1);
__snd_opl3sa2_write(chip, right_reg, val2);
} else {
oval1 = chip->ctlregs[left_reg];
val1 = (oval1 & ~((mask << shift_left) | (mask << shift_right))) | val1 | val2;
change = val1 != oval1;
__snd_opl3sa2_write(chip, left_reg, val1);
}
spin_unlock_irqrestore(&chip->reg_lock, flags);
return change;
}
static const DECLARE_TLV_DB_SCALE(db_scale_master, -3000, 200, 0);
static const DECLARE_TLV_DB_SCALE(db_scale_5bit_12db_max, -3450, 150, 0);
static struct snd_kcontrol_new snd_opl3sa2_controls[] = {
OPL3SA2_DOUBLE("Master Playback Switch", 0, 0x07, 0x08, 7, 7, 1, 1),
OPL3SA2_DOUBLE_TLV("Master Playback Volume", 0, 0x07, 0x08, 0, 0, 15, 1,
db_scale_master),
OPL3SA2_SINGLE("Mic Playback Switch", 0, 0x09, 7, 1, 1),
OPL3SA2_SINGLE_TLV("Mic Playback Volume", 0, 0x09, 0, 31, 1,
db_scale_5bit_12db_max),
OPL3SA2_SINGLE("ZV Port Switch", 0, 0x02, 0, 1, 0),
};
static struct snd_kcontrol_new snd_opl3sa2_tone_controls[] = {
OPL3SA2_DOUBLE("3D Control - Wide", 0, 0x14, 0x14, 4, 0, 7, 0),
OPL3SA2_DOUBLE("Tone Control - Bass", 0, 0x15, 0x15, 4, 0, 7, 0),
OPL3SA2_DOUBLE("Tone Control - Treble", 0, 0x16, 0x16, 4, 0, 7, 0)
};
static void snd_opl3sa2_master_free(struct snd_kcontrol *kcontrol)
{
struct snd_opl3sa2 *chip = snd_kcontrol_chip(kcontrol);
chip->master_switch = NULL;
chip->master_volume = NULL;
}
static int __devinit snd_opl3sa2_mixer(struct snd_card *card)
{
struct snd_opl3sa2 *chip = card->private_data;
struct snd_ctl_elem_id id1, id2;
struct snd_kcontrol *kctl;
unsigned int idx;
int err;
memset(&id1, 0, sizeof(id1));
memset(&id2, 0, sizeof(id2));
id1.iface = id2.iface = SNDRV_CTL_ELEM_IFACE_MIXER;
/* reassign AUX0 to CD */
strcpy(id1.name, "Aux Playback Switch");
strcpy(id2.name, "CD Playback Switch");
if ((err = snd_ctl_rename_id(card, &id1, &id2)) < 0) {
snd_printk(KERN_ERR "Cannot rename opl3sa2 control\n");
return err;
}
strcpy(id1.name, "Aux Playback Volume");
strcpy(id2.name, "CD Playback Volume");
if ((err = snd_ctl_rename_id(card, &id1, &id2)) < 0) {
snd_printk(KERN_ERR "Cannot rename opl3sa2 control\n");
return err;
}
/* reassign AUX1 to FM */
strcpy(id1.name, "Aux Playback Switch"); id1.index = 1;
strcpy(id2.name, "FM Playback Switch");
if ((err = snd_ctl_rename_id(card, &id1, &id2)) < 0) {
snd_printk(KERN_ERR "Cannot rename opl3sa2 control\n");
return err;
}
strcpy(id1.name, "Aux Playback Volume");
strcpy(id2.name, "FM Playback Volume");
if ((err = snd_ctl_rename_id(card, &id1, &id2)) < 0) {
snd_printk(KERN_ERR "Cannot rename opl3sa2 control\n");
return err;
}
/* add OPL3SA2 controls */
for (idx = 0; idx < ARRAY_SIZE(snd_opl3sa2_controls); idx++) {
if ((err = snd_ctl_add(card, kctl = snd_ctl_new1(&snd_opl3sa2_controls[idx], chip))) < 0)
return err;
switch (idx) {
case 0: chip->master_switch = kctl; kctl->private_free = snd_opl3sa2_master_free; break;
case 1: chip->master_volume = kctl; kctl->private_free = snd_opl3sa2_master_free; break;
}
}
if (chip->version > 2) {
for (idx = 0; idx < ARRAY_SIZE(snd_opl3sa2_tone_controls); idx++)
if ((err = snd_ctl_add(card, snd_ctl_new1(&snd_opl3sa2_tone_controls[idx], chip))) < 0)
return err;
}
return 0;
}
/* Power Management support functions */
#ifdef CONFIG_PM
static int snd_opl3sa2_suspend(struct snd_card *card, pm_message_t state)
{
if (card) {
struct snd_opl3sa2 *chip = card->private_data;
snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);
chip->wss->suspend(chip->wss);
/* power down */
snd_opl3sa2_write(chip, OPL3SA2_PM_CTRL, OPL3SA2_PM_D3);
}
return 0;
}
static int snd_opl3sa2_resume(struct snd_card *card)
{
struct snd_opl3sa2 *chip;
int i;
if (!card)
return 0;
chip = card->private_data;
/* power up */
snd_opl3sa2_write(chip, OPL3SA2_PM_CTRL, OPL3SA2_PM_D0);
/* restore registers */
for (i = 2; i <= 0x0a; i++) {
if (i != OPL3SA2_IRQ_STATUS)
snd_opl3sa2_write(chip, i, chip->ctlregs[i]);
}
if (chip->version > 2) {
for (i = 0x12; i <= 0x16; i++)
snd_opl3sa2_write(chip, i, chip->ctlregs[i]);
}
/* restore wss */
chip->wss->resume(chip->wss);
snd_power_change_state(card, SNDRV_CTL_POWER_D0);
return 0;
}
#endif /* CONFIG_PM */
#ifdef CONFIG_PNP
static int __devinit snd_opl3sa2_pnp(int dev, struct snd_opl3sa2 *chip,
struct pnp_dev *pdev)
{
if (pnp_activate_dev(pdev) < 0) {
snd_printk(KERN_ERR "PnP configure failure (out of resources?)\n");
return -EBUSY;
}
sb_port[dev] = pnp_port_start(pdev, 0);
wss_port[dev] = pnp_port_start(pdev, 1);
fm_port[dev] = pnp_port_start(pdev, 2);
midi_port[dev] = pnp_port_start(pdev, 3);
port[dev] = pnp_port_start(pdev, 4);
dma1[dev] = pnp_dma(pdev, 0);
dma2[dev] = pnp_dma(pdev, 1);
irq[dev] = pnp_irq(pdev, 0);
snd_printdd("%sPnP OPL3-SA: sb port=0x%lx, wss port=0x%lx, fm port=0x%lx, midi port=0x%lx\n",
pnp_device_is_pnpbios(pdev) ? "BIOS" : "ISA", sb_port[dev], wss_port[dev], fm_port[dev], midi_port[dev]);
snd_printdd("%sPnP OPL3-SA: control port=0x%lx, dma1=%i, dma2=%i, irq=%i\n",
pnp_device_is_pnpbios(pdev) ? "BIOS" : "ISA", port[dev], dma1[dev], dma2[dev], irq[dev]);
return 0;
}
#endif /* CONFIG_PNP */
static void snd_opl3sa2_free(struct snd_card *card)
{
struct snd_opl3sa2 *chip = card->private_data;
if (chip->irq >= 0)
free_irq(chip->irq, card);
release_and_free_resource(chip->res_port);
}
static int snd_opl3sa2_card_new(int dev, struct snd_card **cardp)
{
struct snd_card *card;
struct snd_opl3sa2 *chip;
int err;
err = snd_card_create(index[dev], id[dev], THIS_MODULE,
sizeof(struct snd_opl3sa2), &card);
if (err < 0)
return err;
strcpy(card->driver, "OPL3SA2");
strcpy(card->shortname, "Yamaha OPL3-SA");
chip = card->private_data;
spin_lock_init(&chip->reg_lock);
chip->irq = -1;
card->private_free = snd_opl3sa2_free;
*cardp = card;
return 0;
}
static int __devinit snd_opl3sa2_probe(struct snd_card *card, int dev)
{
int xirq, xdma1, xdma2;
struct snd_opl3sa2 *chip;
struct snd_wss *wss;
struct snd_opl3 *opl3;
int err;
/* initialise this card from supplied (or default) parameter*/
chip = card->private_data;
chip->ymode = opl3sa3_ymode[dev] & 0x03 ;
chip->port = port[dev];
xirq = irq[dev];
xdma1 = dma1[dev];
xdma2 = dma2[dev];
if (xdma2 < 0)
chip->single_dma = 1;
err = snd_opl3sa2_detect(card);
if (err < 0)
return err;
err = request_irq(xirq, snd_opl3sa2_interrupt, IRQF_DISABLED,
"OPL3-SA2", card);
if (err) {
snd_printk(KERN_ERR PFX "can't grab IRQ %d\n", xirq);
return -ENODEV;
}
chip->irq = xirq;
err = snd_wss_create(card,
wss_port[dev] + 4, -1,
xirq, xdma1, xdma2,
WSS_HW_OPL3SA2, WSS_HWSHARE_IRQ, &wss);
if (err < 0) {
snd_printd("Oops, WSS not detected at 0x%lx\n", wss_port[dev] + 4);
return err;
}
chip->wss = wss;
err = snd_wss_pcm(wss, 0, NULL);
if (err < 0)
return err;
err = snd_wss_mixer(wss);
if (err < 0)
return err;
err = snd_opl3sa2_mixer(card);
if (err < 0)
return err;
err = snd_wss_timer(wss, 0, NULL);
if (err < 0)
return err;
if (fm_port[dev] >= 0x340 && fm_port[dev] < 0x400) {
if ((err = snd_opl3_create(card, fm_port[dev],
fm_port[dev] + 2,
OPL3_HW_OPL3, 0, &opl3)) < 0)
return err;
if ((err = snd_opl3_timer_new(opl3, 1, 2)) < 0)
return err;
if ((err = snd_opl3_hwdep_new(opl3, 0, 1, &chip->synth)) < 0)
return err;
}
if (midi_port[dev] >= 0x300 && midi_port[dev] < 0x340) {
if ((err = snd_mpu401_uart_new(card, 0, MPU401_HW_OPL3SA2,
midi_port[dev], 0,
xirq, 0, &chip->rmidi)) < 0)
return err;
}
sprintf(card->longname, "%s at 0x%lx, irq %d, dma %d",
card->shortname, chip->port, xirq, xdma1);
if (xdma2 >= 0)
sprintf(card->longname + strlen(card->longname), "&%d", xdma2);
return snd_card_register(card);
}
#ifdef CONFIG_PNP
static int __devinit snd_opl3sa2_pnp_detect(struct pnp_dev *pdev,
const struct pnp_device_id *id)
{
static int dev;
int err;
struct snd_card *card;
if (pnp_device_is_isapnp(pdev))
return -ENOENT; /* we have another procedure - card */
for (; dev < SNDRV_CARDS; dev++) {
if (enable[dev] && isapnp[dev])
break;
}
if (dev >= SNDRV_CARDS)
return -ENODEV;
err = snd_opl3sa2_card_new(dev, &card);
if (err < 0)
return err;
if ((err = snd_opl3sa2_pnp(dev, card->private_data, pdev)) < 0) {
snd_card_free(card);
return err;
}
snd_card_set_dev(card, &pdev->dev);
if ((err = snd_opl3sa2_probe(card, dev)) < 0) {
snd_card_free(card);
return err;
}
pnp_set_drvdata(pdev, card);
dev++;
return 0;
}
static void __devexit snd_opl3sa2_pnp_remove(struct pnp_dev * pdev)
{
snd_card_free(pnp_get_drvdata(pdev));
pnp_set_drvdata(pdev, NULL);
}
#ifdef CONFIG_PM
static int snd_opl3sa2_pnp_suspend(struct pnp_dev *pdev, pm_message_t state)
{
return snd_opl3sa2_suspend(pnp_get_drvdata(pdev), state);
}
static int snd_opl3sa2_pnp_resume(struct pnp_dev *pdev)
{
return snd_opl3sa2_resume(pnp_get_drvdata(pdev));
}
#endif
static struct pnp_driver opl3sa2_pnp_driver = {
.name = "snd-opl3sa2-pnpbios",
.id_table = snd_opl3sa2_pnpbiosids,
.probe = snd_opl3sa2_pnp_detect,
.remove = __devexit_p(snd_opl3sa2_pnp_remove),
#ifdef CONFIG_PM
.suspend = snd_opl3sa2_pnp_suspend,
.resume = snd_opl3sa2_pnp_resume,
#endif
};
static int __devinit snd_opl3sa2_pnp_cdetect(struct pnp_card_link *pcard,
const struct pnp_card_device_id *id)
{
static int dev;
struct pnp_dev *pdev;
int err;
struct snd_card *card;
pdev = pnp_request_card_device(pcard, id->devs[0].id, NULL);
if (pdev == NULL) {
snd_printk(KERN_ERR PFX "can't get pnp device from id '%s'\n",
id->devs[0].id);
return -EBUSY;
}
for (; dev < SNDRV_CARDS; dev++) {
if (enable[dev] && isapnp[dev])
break;
}
if (dev >= SNDRV_CARDS)
return -ENODEV;
err = snd_opl3sa2_card_new(dev, &card);
if (err < 0)
return err;
if ((err = snd_opl3sa2_pnp(dev, card->private_data, pdev)) < 0) {
snd_card_free(card);
return err;
}
snd_card_set_dev(card, &pdev->dev);
if ((err = snd_opl3sa2_probe(card, dev)) < 0) {
snd_card_free(card);
return err;
}
pnp_set_card_drvdata(pcard, card);
dev++;
return 0;
}
static void __devexit snd_opl3sa2_pnp_cremove(struct pnp_card_link * pcard)
{
snd_card_free(pnp_get_card_drvdata(pcard));
pnp_set_card_drvdata(pcard, NULL);
}
#ifdef CONFIG_PM
static int snd_opl3sa2_pnp_csuspend(struct pnp_card_link *pcard, pm_message_t state)
{
return snd_opl3sa2_suspend(pnp_get_card_drvdata(pcard), state);
}
static int snd_opl3sa2_pnp_cresume(struct pnp_card_link *pcard)
{
return snd_opl3sa2_resume(pnp_get_card_drvdata(pcard));
}
#endif
static struct pnp_card_driver opl3sa2_pnpc_driver = {
.flags = PNP_DRIVER_RES_DISABLE,
.name = "snd-opl3sa2-cpnp",
.id_table = snd_opl3sa2_pnpids,
.probe = snd_opl3sa2_pnp_cdetect,
.remove = __devexit_p(snd_opl3sa2_pnp_cremove),
#ifdef CONFIG_PM
.suspend = snd_opl3sa2_pnp_csuspend,
.resume = snd_opl3sa2_pnp_cresume,
#endif
};
#endif /* CONFIG_PNP */
static int __devinit snd_opl3sa2_isa_match(struct device *pdev,
unsigned int dev)
{
if (!enable[dev])
return 0;
#ifdef CONFIG_PNP
if (isapnp[dev])
return 0;
#endif
if (port[dev] == SNDRV_AUTO_PORT) {
snd_printk(KERN_ERR PFX "specify port\n");
return 0;
}
if (wss_port[dev] == SNDRV_AUTO_PORT) {
snd_printk(KERN_ERR PFX "specify wss_port\n");
return 0;
}
if (fm_port[dev] == SNDRV_AUTO_PORT) {
snd_printk(KERN_ERR PFX "specify fm_port\n");
return 0;
}
if (midi_port[dev] == SNDRV_AUTO_PORT) {
snd_printk(KERN_ERR PFX "specify midi_port\n");
return 0;
}
return 1;
}
static int __devinit snd_opl3sa2_isa_probe(struct device *pdev,
unsigned int dev)
{
struct snd_card *card;
int err;
err = snd_opl3sa2_card_new(dev, &card);
if (err < 0)
return err;
snd_card_set_dev(card, pdev);
if ((err = snd_opl3sa2_probe(card, dev)) < 0) {
snd_card_free(card);
return err;
}
dev_set_drvdata(pdev, card);
return 0;
}
static int __devexit snd_opl3sa2_isa_remove(struct device *devptr,
unsigned int dev)
{
snd_card_free(dev_get_drvdata(devptr));
dev_set_drvdata(devptr, NULL);
return 0;
}
#ifdef CONFIG_PM
static int snd_opl3sa2_isa_suspend(struct device *dev, unsigned int n,
pm_message_t state)
{
return snd_opl3sa2_suspend(dev_get_drvdata(dev), state);
}
static int snd_opl3sa2_isa_resume(struct device *dev, unsigned int n)
{
return snd_opl3sa2_resume(dev_get_drvdata(dev));
}
#endif
#define DEV_NAME "opl3sa2"
static struct isa_driver snd_opl3sa2_isa_driver = {
.match = snd_opl3sa2_isa_match,
.probe = snd_opl3sa2_isa_probe,
.remove = __devexit_p(snd_opl3sa2_isa_remove),
#ifdef CONFIG_PM
.suspend = snd_opl3sa2_isa_suspend,
.resume = snd_opl3sa2_isa_resume,
#endif
.driver = {
.name = DEV_NAME
},
};
static int __init alsa_card_opl3sa2_init(void)
{
int err;
err = isa_register_driver(&snd_opl3sa2_isa_driver, SNDRV_CARDS);
#ifdef CONFIG_PNP
if (!err)
isa_registered = 1;
err = pnp_register_driver(&opl3sa2_pnp_driver);
if (!err)
pnp_registered = 1;
err = pnp_register_card_driver(&opl3sa2_pnpc_driver);
if (!err)
pnpc_registered = 1;
if (isa_registered || pnp_registered)
err = 0;
#endif
return err;
}
static void __exit alsa_card_opl3sa2_exit(void)
{
#ifdef CONFIG_PNP
if (pnpc_registered)
pnp_unregister_card_driver(&opl3sa2_pnpc_driver);
if (pnp_registered)
pnp_unregister_driver(&opl3sa2_pnp_driver);
if (isa_registered)
#endif
isa_unregister_driver(&snd_opl3sa2_isa_driver);
}
module_init(alsa_card_opl3sa2_init)
module_exit(alsa_card_opl3sa2_exit)
| gpl-2.0 |
sudipm-mukherjee/parport | drivers/media/dvb-frontends/atbm8830.c | 592 | 11905 | /*
* Support for AltoBeam GB20600 (a.k.a DMB-TH) demodulator
* ATBM8830, ATBM8831
*
* Copyright (C) 2009 David T.L. Wong <davidtlwong@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <asm/div64.h>
#include "dvb_frontend.h"
#include "atbm8830.h"
#include "atbm8830_priv.h"
#define dprintk(args...) \
do { \
if (debug) \
printk(KERN_DEBUG "atbm8830: " args); \
} while (0)
static int debug;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "Turn on/off frontend debugging (default:off).");
static int atbm8830_write_reg(struct atbm_state *priv, u16 reg, u8 data)
{
int ret = 0;
u8 dev_addr;
u8 buf1[] = { reg >> 8, reg & 0xFF };
u8 buf2[] = { data };
struct i2c_msg msg1 = { .flags = 0, .buf = buf1, .len = 2 };
struct i2c_msg msg2 = { .flags = 0, .buf = buf2, .len = 1 };
dev_addr = priv->config->demod_address;
msg1.addr = dev_addr;
msg2.addr = dev_addr;
if (debug >= 2)
dprintk("%s: reg=0x%04X, data=0x%02X\n", __func__, reg, data);
ret = i2c_transfer(priv->i2c, &msg1, 1);
if (ret != 1)
return -EIO;
ret = i2c_transfer(priv->i2c, &msg2, 1);
return (ret != 1) ? -EIO : 0;
}
static int atbm8830_read_reg(struct atbm_state *priv, u16 reg, u8 *p_data)
{
int ret;
u8 dev_addr;
u8 buf1[] = { reg >> 8, reg & 0xFF };
u8 buf2[] = { 0 };
struct i2c_msg msg1 = { .flags = 0, .buf = buf1, .len = 2 };
struct i2c_msg msg2 = { .flags = I2C_M_RD, .buf = buf2, .len = 1 };
dev_addr = priv->config->demod_address;
msg1.addr = dev_addr;
msg2.addr = dev_addr;
ret = i2c_transfer(priv->i2c, &msg1, 1);
if (ret != 1) {
dprintk("%s: error reg=0x%04x, ret=%i\n", __func__, reg, ret);
return -EIO;
}
ret = i2c_transfer(priv->i2c, &msg2, 1);
if (ret != 1)
return -EIO;
*p_data = buf2[0];
if (debug >= 2)
dprintk("%s: reg=0x%04X, data=0x%02X\n",
__func__, reg, buf2[0]);
return 0;
}
/* Lock register latch so that multi-register read is atomic */
static inline int atbm8830_reglatch_lock(struct atbm_state *priv, int lock)
{
return atbm8830_write_reg(priv, REG_READ_LATCH, lock ? 1 : 0);
}
static int set_osc_freq(struct atbm_state *priv, u32 freq /*in kHz*/)
{
u32 val;
u64 t;
/* 0x100000 * freq / 30.4MHz */
t = (u64)0x100000 * freq;
do_div(t, 30400);
val = t;
atbm8830_write_reg(priv, REG_OSC_CLK, val);
atbm8830_write_reg(priv, REG_OSC_CLK + 1, val >> 8);
atbm8830_write_reg(priv, REG_OSC_CLK + 2, val >> 16);
return 0;
}
static int set_if_freq(struct atbm_state *priv, u32 freq /*in kHz*/)
{
u32 fs = priv->config->osc_clk_freq;
u64 t;
u32 val;
u8 dat;
if (freq != 0) {
/* 2 * PI * (freq - fs) / fs * (2 ^ 22) */
t = (u64) 2 * 31416 * (freq - fs);
t <<= 22;
do_div(t, fs);
do_div(t, 1000);
val = t;
atbm8830_write_reg(priv, REG_TUNER_BASEBAND, 1);
atbm8830_write_reg(priv, REG_IF_FREQ, val);
atbm8830_write_reg(priv, REG_IF_FREQ+1, val >> 8);
atbm8830_write_reg(priv, REG_IF_FREQ+2, val >> 16);
atbm8830_read_reg(priv, REG_ADC_CONFIG, &dat);
dat &= 0xFC;
atbm8830_write_reg(priv, REG_ADC_CONFIG, dat);
} else {
/* Zero IF */
atbm8830_write_reg(priv, REG_TUNER_BASEBAND, 0);
atbm8830_read_reg(priv, REG_ADC_CONFIG, &dat);
dat &= 0xFC;
dat |= 0x02;
atbm8830_write_reg(priv, REG_ADC_CONFIG, dat);
if (priv->config->zif_swap_iq)
atbm8830_write_reg(priv, REG_SWAP_I_Q, 0x03);
else
atbm8830_write_reg(priv, REG_SWAP_I_Q, 0x01);
}
return 0;
}
static int is_locked(struct atbm_state *priv, u8 *locked)
{
u8 status;
atbm8830_read_reg(priv, REG_LOCK_STATUS, &status);
if (locked != NULL)
*locked = (status == 1);
return 0;
}
static int set_agc_config(struct atbm_state *priv,
u8 min, u8 max, u8 hold_loop)
{
/* no effect if both min and max are zero */
if (!min && !max)
return 0;
atbm8830_write_reg(priv, REG_AGC_MIN, min);
atbm8830_write_reg(priv, REG_AGC_MAX, max);
atbm8830_write_reg(priv, REG_AGC_HOLD_LOOP, hold_loop);
return 0;
}
static int set_static_channel_mode(struct atbm_state *priv)
{
int i;
for (i = 0; i < 5; i++)
atbm8830_write_reg(priv, 0x099B + i, 0x08);
atbm8830_write_reg(priv, 0x095B, 0x7F);
atbm8830_write_reg(priv, 0x09CB, 0x01);
atbm8830_write_reg(priv, 0x09CC, 0x7F);
atbm8830_write_reg(priv, 0x09CD, 0x7F);
atbm8830_write_reg(priv, 0x0E01, 0x20);
/* For single carrier */
atbm8830_write_reg(priv, 0x0B03, 0x0A);
atbm8830_write_reg(priv, 0x0935, 0x10);
atbm8830_write_reg(priv, 0x0936, 0x08);
atbm8830_write_reg(priv, 0x093E, 0x08);
atbm8830_write_reg(priv, 0x096E, 0x06);
/* frame_count_max0 */
atbm8830_write_reg(priv, 0x0B09, 0x00);
/* frame_count_max1 */
atbm8830_write_reg(priv, 0x0B0A, 0x08);
return 0;
}
static int set_ts_config(struct atbm_state *priv)
{
const struct atbm8830_config *cfg = priv->config;
/*Set parallel/serial ts mode*/
atbm8830_write_reg(priv, REG_TS_SERIAL, cfg->serial_ts ? 1 : 0);
atbm8830_write_reg(priv, REG_TS_CLK_MODE, cfg->serial_ts ? 1 : 0);
/*Set ts sampling edge*/
atbm8830_write_reg(priv, REG_TS_SAMPLE_EDGE,
cfg->ts_sampling_edge ? 1 : 0);
/*Set ts clock freerun*/
atbm8830_write_reg(priv, REG_TS_CLK_FREERUN,
cfg->ts_clk_gated ? 0 : 1);
return 0;
}
static int atbm8830_init(struct dvb_frontend *fe)
{
struct atbm_state *priv = fe->demodulator_priv;
const struct atbm8830_config *cfg = priv->config;
/*Set oscillator frequency*/
set_osc_freq(priv, cfg->osc_clk_freq);
/*Set IF frequency*/
set_if_freq(priv, cfg->if_freq);
/*Set AGC Config*/
set_agc_config(priv, cfg->agc_min, cfg->agc_max,
cfg->agc_hold_loop);
/*Set static channel mode*/
set_static_channel_mode(priv);
set_ts_config(priv);
/*Turn off DSP reset*/
atbm8830_write_reg(priv, 0x000A, 0);
/*SW version test*/
atbm8830_write_reg(priv, 0x020C, 11);
/* Run */
atbm8830_write_reg(priv, REG_DEMOD_RUN, 1);
return 0;
}
static void atbm8830_release(struct dvb_frontend *fe)
{
struct atbm_state *state = fe->demodulator_priv;
dprintk("%s\n", __func__);
kfree(state);
}
static int atbm8830_set_fe(struct dvb_frontend *fe)
{
struct atbm_state *priv = fe->demodulator_priv;
int i;
u8 locked = 0;
dprintk("%s\n", __func__);
/* set frequency */
if (fe->ops.tuner_ops.set_params) {
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 1);
fe->ops.tuner_ops.set_params(fe);
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 0);
}
/* start auto lock */
for (i = 0; i < 10; i++) {
mdelay(100);
dprintk("Try %d\n", i);
is_locked(priv, &locked);
if (locked != 0) {
dprintk("ATBM8830 locked!\n");
break;
}
}
return 0;
}
static int atbm8830_get_fe(struct dvb_frontend *fe)
{
struct dtv_frontend_properties *c = &fe->dtv_property_cache;
dprintk("%s\n", __func__);
/* TODO: get real readings from device */
/* inversion status */
c->inversion = INVERSION_OFF;
/* bandwidth */
c->bandwidth_hz = 8000000;
c->code_rate_HP = FEC_AUTO;
c->code_rate_LP = FEC_AUTO;
c->modulation = QAM_AUTO;
/* transmission mode */
c->transmission_mode = TRANSMISSION_MODE_AUTO;
/* guard interval */
c->guard_interval = GUARD_INTERVAL_AUTO;
/* hierarchy */
c->hierarchy = HIERARCHY_NONE;
return 0;
}
static int atbm8830_get_tune_settings(struct dvb_frontend *fe,
struct dvb_frontend_tune_settings *fesettings)
{
fesettings->min_delay_ms = 0;
fesettings->step_size = 0;
fesettings->max_drift = 0;
return 0;
}
static int atbm8830_read_status(struct dvb_frontend *fe,
enum fe_status *fe_status)
{
struct atbm_state *priv = fe->demodulator_priv;
u8 locked = 0;
u8 agc_locked = 0;
dprintk("%s\n", __func__);
*fe_status = 0;
is_locked(priv, &locked);
if (locked) {
*fe_status |= FE_HAS_SIGNAL | FE_HAS_CARRIER |
FE_HAS_VITERBI | FE_HAS_SYNC | FE_HAS_LOCK;
}
dprintk("%s: fe_status=0x%x\n", __func__, *fe_status);
atbm8830_read_reg(priv, REG_AGC_LOCK, &agc_locked);
dprintk("AGC Lock: %d\n", agc_locked);
return 0;
}
static int atbm8830_read_ber(struct dvb_frontend *fe, u32 *ber)
{
struct atbm_state *priv = fe->demodulator_priv;
u32 frame_err;
u8 t;
dprintk("%s\n", __func__);
atbm8830_reglatch_lock(priv, 1);
atbm8830_read_reg(priv, REG_FRAME_ERR_CNT + 1, &t);
frame_err = t & 0x7F;
frame_err <<= 8;
atbm8830_read_reg(priv, REG_FRAME_ERR_CNT, &t);
frame_err |= t;
atbm8830_reglatch_lock(priv, 0);
*ber = frame_err * 100 / 32767;
dprintk("%s: ber=0x%x\n", __func__, *ber);
return 0;
}
static int atbm8830_read_signal_strength(struct dvb_frontend *fe, u16 *signal)
{
struct atbm_state *priv = fe->demodulator_priv;
u32 pwm;
u8 t;
dprintk("%s\n", __func__);
atbm8830_reglatch_lock(priv, 1);
atbm8830_read_reg(priv, REG_AGC_PWM_VAL + 1, &t);
pwm = t & 0x03;
pwm <<= 8;
atbm8830_read_reg(priv, REG_AGC_PWM_VAL, &t);
pwm |= t;
atbm8830_reglatch_lock(priv, 0);
dprintk("AGC PWM = 0x%02X\n", pwm);
pwm = 0x400 - pwm;
*signal = pwm * 0x10000 / 0x400;
return 0;
}
static int atbm8830_read_snr(struct dvb_frontend *fe, u16 *snr)
{
dprintk("%s\n", __func__);
*snr = 0;
return 0;
}
static int atbm8830_read_ucblocks(struct dvb_frontend *fe, u32 *ucblocks)
{
dprintk("%s\n", __func__);
*ucblocks = 0;
return 0;
}
static int atbm8830_i2c_gate_ctrl(struct dvb_frontend *fe, int enable)
{
struct atbm_state *priv = fe->demodulator_priv;
return atbm8830_write_reg(priv, REG_I2C_GATE, enable ? 1 : 0);
}
static struct dvb_frontend_ops atbm8830_ops = {
.delsys = { SYS_DTMB },
.info = {
.name = "AltoBeam ATBM8830/8831 DMB-TH",
.frequency_min = 474000000,
.frequency_max = 858000000,
.frequency_stepsize = 10000,
.caps =
FE_CAN_FEC_AUTO |
FE_CAN_QAM_AUTO |
FE_CAN_TRANSMISSION_MODE_AUTO |
FE_CAN_GUARD_INTERVAL_AUTO
},
.release = atbm8830_release,
.init = atbm8830_init,
.sleep = NULL,
.write = NULL,
.i2c_gate_ctrl = atbm8830_i2c_gate_ctrl,
.set_frontend = atbm8830_set_fe,
.get_frontend = atbm8830_get_fe,
.get_tune_settings = atbm8830_get_tune_settings,
.read_status = atbm8830_read_status,
.read_ber = atbm8830_read_ber,
.read_signal_strength = atbm8830_read_signal_strength,
.read_snr = atbm8830_read_snr,
.read_ucblocks = atbm8830_read_ucblocks,
};
struct dvb_frontend *atbm8830_attach(const struct atbm8830_config *config,
struct i2c_adapter *i2c)
{
struct atbm_state *priv = NULL;
u8 data = 0;
dprintk("%s()\n", __func__);
if (config == NULL || i2c == NULL)
return NULL;
priv = kzalloc(sizeof(struct atbm_state), GFP_KERNEL);
if (priv == NULL)
goto error_out;
priv->config = config;
priv->i2c = i2c;
/* check if the demod is there */
if (atbm8830_read_reg(priv, REG_CHIP_ID, &data) != 0) {
dprintk("%s atbm8830/8831 not found at i2c addr 0x%02X\n",
__func__, priv->config->demod_address);
goto error_out;
}
dprintk("atbm8830 chip id: 0x%02X\n", data);
memcpy(&priv->frontend.ops, &atbm8830_ops,
sizeof(struct dvb_frontend_ops));
priv->frontend.demodulator_priv = priv;
atbm8830_init(&priv->frontend);
atbm8830_i2c_gate_ctrl(&priv->frontend, 1);
return &priv->frontend;
error_out:
dprintk("%s() error_out\n", __func__);
kfree(priv);
return NULL;
}
EXPORT_SYMBOL(atbm8830_attach);
MODULE_DESCRIPTION("AltoBeam ATBM8830/8831 GB20600 demodulator driver");
MODULE_AUTHOR("David T. L. Wong <davidtlwong@gmail.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
project-voodoo-vibrant/linux_sgh-t759 | drivers/zorro/zorro.c | 848 | 5111 | /*
* Zorro Bus Services
*
* Copyright (C) 1995-2003 Geert Uytterhoeven
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive
* for more details.
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/zorro.h>
#include <linux/bitops.h>
#include <linux/string.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <asm/setup.h>
#include <asm/amigahw.h>
#include "zorro.h"
/*
* Zorro Expansion Devices
*/
unsigned int zorro_num_autocon;
struct zorro_dev zorro_autocon[ZORRO_NUM_AUTO];
/*
* Zorro bus
*/
struct zorro_bus {
struct list_head devices; /* list of devices on this bus */
struct device dev;
};
/*
* Find Zorro Devices
*/
struct zorro_dev *zorro_find_device(zorro_id id, struct zorro_dev *from)
{
struct zorro_dev *z;
if (!zorro_num_autocon)
return NULL;
for (z = from ? from+1 : &zorro_autocon[0];
z < zorro_autocon+zorro_num_autocon;
z++)
if (id == ZORRO_WILDCARD || id == z->id)
return z;
return NULL;
}
EXPORT_SYMBOL(zorro_find_device);
/*
* Bitmask indicating portions of available Zorro II RAM that are unused
* by the system. Every bit represents a 64K chunk, for a maximum of 8MB
* (128 chunks, physical 0x00200000-0x009fffff).
*
* If you want to use (= allocate) portions of this RAM, you should clear
* the corresponding bits.
*
* Possible uses:
* - z2ram device
* - SCSI DMA bounce buffers
*
* FIXME: use the normal resource management
*/
DECLARE_BITMAP(zorro_unused_z2ram, 128);
EXPORT_SYMBOL(zorro_unused_z2ram);
static void __init mark_region(unsigned long start, unsigned long end,
int flag)
{
if (flag)
start += Z2RAM_CHUNKMASK;
else
end += Z2RAM_CHUNKMASK;
start &= ~Z2RAM_CHUNKMASK;
end &= ~Z2RAM_CHUNKMASK;
if (end <= Z2RAM_START || start >= Z2RAM_END)
return;
start = start < Z2RAM_START ? 0x00000000 : start-Z2RAM_START;
end = end > Z2RAM_END ? Z2RAM_SIZE : end-Z2RAM_START;
while (start < end) {
u32 chunk = start>>Z2RAM_CHUNKSHIFT;
if (flag)
set_bit(chunk, zorro_unused_z2ram);
else
clear_bit(chunk, zorro_unused_z2ram);
start += Z2RAM_CHUNKSIZE;
}
}
static struct resource __init *zorro_find_parent_resource(
struct platform_device *bridge, struct zorro_dev *z)
{
int i;
for (i = 0; i < bridge->num_resources; i++) {
struct resource *r = &bridge->resource[i];
if (zorro_resource_start(z) >= r->start &&
zorro_resource_end(z) <= r->end)
return r;
}
return &iomem_resource;
}
static int __init amiga_zorro_probe(struct platform_device *pdev)
{
struct zorro_bus *bus;
struct zorro_dev *z;
struct resource *r;
unsigned int i;
int error;
/* Initialize the Zorro bus */
bus = kzalloc(sizeof(*bus), GFP_KERNEL);
if (!bus)
return -ENOMEM;
INIT_LIST_HEAD(&bus->devices);
bus->dev.parent = &pdev->dev;
dev_set_name(&bus->dev, "zorro");
error = device_register(&bus->dev);
if (error) {
pr_err("Zorro: Error registering zorro_bus\n");
kfree(bus);
return error;
}
platform_set_drvdata(pdev, bus);
/* Register all devices */
pr_info("Zorro: Probing AutoConfig expansion devices: %u device%s\n",
zorro_num_autocon, zorro_num_autocon == 1 ? "" : "s");
for (i = 0; i < zorro_num_autocon; i++) {
z = &zorro_autocon[i];
z->id = (z->rom.er_Manufacturer<<16) | (z->rom.er_Product<<8);
if (z->id == ZORRO_PROD_GVP_EPC_BASE) {
/* GVP quirk */
unsigned long magic = zorro_resource_start(z)+0x8000;
z->id |= *(u16 *)ZTWO_VADDR(magic) & GVP_PRODMASK;
}
sprintf(z->name, "Zorro device %08x", z->id);
zorro_name_device(z);
z->resource.name = z->name;
r = zorro_find_parent_resource(pdev, z);
error = request_resource(r, &z->resource);
if (error)
dev_err(&bus->dev,
"Address space collision on device %s %pR\n",
z->name, &z->resource);
dev_set_name(&z->dev, "%02x", i);
z->dev.parent = &bus->dev;
z->dev.bus = &zorro_bus_type;
error = device_register(&z->dev);
if (error) {
dev_err(&bus->dev, "Error registering device %s\n",
z->name);
continue;
}
error = zorro_create_sysfs_dev_files(z);
if (error)
dev_err(&z->dev, "Error creating sysfs files\n");
}
/* Mark all available Zorro II memory */
zorro_for_each_dev(z) {
if (z->rom.er_Type & ERTF_MEMLIST)
mark_region(zorro_resource_start(z),
zorro_resource_end(z)+1, 1);
}
/* Unmark all used Zorro II memory */
for (i = 0; i < m68k_num_memory; i++)
if (m68k_memory[i].addr < 16*1024*1024)
mark_region(m68k_memory[i].addr,
m68k_memory[i].addr+m68k_memory[i].size,
0);
return 0;
}
static struct platform_driver amiga_zorro_driver = {
.driver = {
.name = "amiga-zorro",
.owner = THIS_MODULE,
},
};
static int __init amiga_zorro_init(void)
{
return platform_driver_probe(&amiga_zorro_driver, amiga_zorro_probe);
}
module_init(amiga_zorro_init);
MODULE_LICENSE("GPL");
| gpl-2.0 |
lsigithub/axxia_yocto_linux_4.1 | fs/befs/datastream.c | 848 | 15914 | /*
* linux/fs/befs/datastream.c
*
* Copyright (C) 2001 Will Dyson <will_dyson@pobox.com>
*
* Based on portions of file.c by Makoto Kato <m_kato@ga2.so-net.ne.jp>
*
* Many thanks to Dominic Giampaolo, author of "Practical File System
* Design with the Be File System", for such a helpful book.
*
*/
#include <linux/kernel.h>
#include <linux/buffer_head.h>
#include <linux/string.h>
#include "befs.h"
#include "datastream.h"
#include "io.h"
const befs_inode_addr BAD_IADDR = { 0, 0, 0 };
static int befs_find_brun_direct(struct super_block *sb,
befs_data_stream * data,
befs_blocknr_t blockno, befs_block_run * run);
static int befs_find_brun_indirect(struct super_block *sb,
befs_data_stream * data,
befs_blocknr_t blockno,
befs_block_run * run);
static int befs_find_brun_dblindirect(struct super_block *sb,
befs_data_stream * data,
befs_blocknr_t blockno,
befs_block_run * run);
/**
* befs_read_datastream - get buffer_head containing data, starting from pos.
* @sb: Filesystem superblock
* @ds: datastrem to find data with
* @pos: start of data
* @off: offset of data in buffer_head->b_data
*
* Returns pointer to buffer_head containing data starting with offset @off,
* if you don't need to know offset just set @off = NULL.
*/
struct buffer_head *
befs_read_datastream(struct super_block *sb, befs_data_stream * ds,
befs_off_t pos, uint * off)
{
struct buffer_head *bh = NULL;
befs_block_run run;
befs_blocknr_t block; /* block coresponding to pos */
befs_debug(sb, "---> %s %llu", __func__, pos);
block = pos >> BEFS_SB(sb)->block_shift;
if (off)
*off = pos - (block << BEFS_SB(sb)->block_shift);
if (befs_fblock2brun(sb, ds, block, &run) != BEFS_OK) {
befs_error(sb, "BeFS: Error finding disk addr of block %lu",
(unsigned long)block);
befs_debug(sb, "<--- %s ERROR", __func__);
return NULL;
}
bh = befs_bread_iaddr(sb, run);
if (!bh) {
befs_error(sb, "BeFS: Error reading block %lu from datastream",
(unsigned long)block);
return NULL;
}
befs_debug(sb, "<--- %s read data, starting at %llu", __func__, pos);
return bh;
}
/*
* Takes a file position and gives back a brun who's starting block
* is block number fblock of the file.
*
* Returns BEFS_OK or BEFS_ERR.
*
* Calls specialized functions for each of the three possible
* datastream regions.
*
* 2001-11-15 Will Dyson
*/
int
befs_fblock2brun(struct super_block *sb, befs_data_stream * data,
befs_blocknr_t fblock, befs_block_run * run)
{
int err;
befs_off_t pos = fblock << BEFS_SB(sb)->block_shift;
if (pos < data->max_direct_range) {
err = befs_find_brun_direct(sb, data, fblock, run);
} else if (pos < data->max_indirect_range) {
err = befs_find_brun_indirect(sb, data, fblock, run);
} else if (pos < data->max_double_indirect_range) {
err = befs_find_brun_dblindirect(sb, data, fblock, run);
} else {
befs_error(sb,
"befs_fblock2brun() was asked to find block %lu, "
"which is not mapped by the datastream\n",
(unsigned long)fblock);
err = BEFS_ERR;
}
return err;
}
/**
* befs_read_lsmylink - read long symlink from datastream.
* @sb: Filesystem superblock
* @ds: Datastrem to read from
* @buff: Buffer in which to place long symlink data
* @len: Length of the long symlink in bytes
*
* Returns the number of bytes read
*/
size_t
befs_read_lsymlink(struct super_block * sb, befs_data_stream * ds, void *buff,
befs_off_t len)
{
befs_off_t bytes_read = 0; /* bytes readed */
u16 plen;
struct buffer_head *bh = NULL;
befs_debug(sb, "---> %s length: %llu", __func__, len);
while (bytes_read < len) {
bh = befs_read_datastream(sb, ds, bytes_read, NULL);
if (!bh) {
befs_error(sb, "BeFS: Error reading datastream block "
"starting from %llu", bytes_read);
befs_debug(sb, "<--- %s ERROR", __func__);
return bytes_read;
}
plen = ((bytes_read + BEFS_SB(sb)->block_size) < len) ?
BEFS_SB(sb)->block_size : len - bytes_read;
memcpy(buff + bytes_read, bh->b_data, plen);
brelse(bh);
bytes_read += plen;
}
befs_debug(sb, "<--- %s read %u bytes", __func__, (unsigned int)
bytes_read);
return bytes_read;
}
/**
* befs_count_blocks - blocks used by a file
* @sb: Filesystem superblock
* @ds: Datastream of the file
*
* Counts the number of fs blocks that the file represented by
* inode occupies on the filesystem, counting both regular file
* data and filesystem metadata (and eventually attribute data
* when we support attributes)
*/
befs_blocknr_t
befs_count_blocks(struct super_block * sb, befs_data_stream * ds)
{
befs_blocknr_t blocks;
befs_blocknr_t datablocks; /* File data blocks */
befs_blocknr_t metablocks; /* FS metadata blocks */
struct befs_sb_info *befs_sb = BEFS_SB(sb);
befs_debug(sb, "---> %s", __func__);
datablocks = ds->size >> befs_sb->block_shift;
if (ds->size & (befs_sb->block_size - 1))
datablocks += 1;
metablocks = 1; /* Start with 1 block for inode */
/* Size of indirect block */
if (ds->size > ds->max_direct_range)
metablocks += ds->indirect.len;
/*
Double indir block, plus all the indirect blocks it mapps
In the double-indirect range, all block runs of data are
BEFS_DBLINDIR_BRUN_LEN blocks long. Therefore, we know
how many data block runs are in the double-indirect region,
and from that we know how many indirect blocks it takes to
map them. We assume that the indirect blocks are also
BEFS_DBLINDIR_BRUN_LEN blocks long.
*/
if (ds->size > ds->max_indirect_range && ds->max_indirect_range != 0) {
uint dbl_bytes;
uint dbl_bruns;
uint indirblocks;
dbl_bytes =
ds->max_double_indirect_range - ds->max_indirect_range;
dbl_bruns =
dbl_bytes / (befs_sb->block_size * BEFS_DBLINDIR_BRUN_LEN);
indirblocks = dbl_bruns / befs_iaddrs_per_block(sb);
metablocks += ds->double_indirect.len;
metablocks += indirblocks;
}
blocks = datablocks + metablocks;
befs_debug(sb, "<--- %s %u blocks", __func__, (unsigned int)blocks);
return blocks;
}
/*
Finds the block run that starts at file block number blockno
in the file represented by the datastream data, if that
blockno is in the direct region of the datastream.
sb: the superblock
data: the datastream
blockno: the blocknumber to find
run: The found run is passed back through this pointer
Return value is BEFS_OK if the blockrun is found, BEFS_ERR
otherwise.
Algorithm:
Linear search. Checks each element of array[] to see if it
contains the blockno-th filesystem block. This is necessary
because the block runs map variable amounts of data. Simply
keeps a count of the number of blocks searched so far (sum),
incrementing this by the length of each block run as we come
across it. Adds sum to *count before returning (this is so
you can search multiple arrays that are logicaly one array,
as in the indirect region code).
When/if blockno is found, if blockno is inside of a block
run as stored on disk, we offset the start and length members
of the block run, so that blockno is the start and len is
still valid (the run ends in the same place).
2001-11-15 Will Dyson
*/
static int
befs_find_brun_direct(struct super_block *sb, befs_data_stream * data,
befs_blocknr_t blockno, befs_block_run * run)
{
int i;
befs_block_run *array = data->direct;
befs_blocknr_t sum;
befs_blocknr_t max_block =
data->max_direct_range >> BEFS_SB(sb)->block_shift;
befs_debug(sb, "---> %s, find %lu", __func__, (unsigned long)blockno);
if (blockno > max_block) {
befs_error(sb, "%s passed block outside of direct region",
__func__);
return BEFS_ERR;
}
for (i = 0, sum = 0; i < BEFS_NUM_DIRECT_BLOCKS;
sum += array[i].len, i++) {
if (blockno >= sum && blockno < sum + (array[i].len)) {
int offset = blockno - sum;
run->allocation_group = array[i].allocation_group;
run->start = array[i].start + offset;
run->len = array[i].len - offset;
befs_debug(sb, "---> %s, "
"found %lu at direct[%d]", __func__,
(unsigned long)blockno, i);
return BEFS_OK;
}
}
befs_debug(sb, "---> %s ERROR", __func__);
return BEFS_ERR;
}
/*
Finds the block run that starts at file block number blockno
in the file represented by the datastream data, if that
blockno is in the indirect region of the datastream.
sb: the superblock
data: the datastream
blockno: the blocknumber to find
run: The found run is passed back through this pointer
Return value is BEFS_OK if the blockrun is found, BEFS_ERR
otherwise.
Algorithm:
For each block in the indirect run of the datastream, read
it in and search through it for search_blk.
XXX:
Really should check to make sure blockno is inside indirect
region.
2001-11-15 Will Dyson
*/
static int
befs_find_brun_indirect(struct super_block *sb,
befs_data_stream * data, befs_blocknr_t blockno,
befs_block_run * run)
{
int i, j;
befs_blocknr_t sum = 0;
befs_blocknr_t indir_start_blk;
befs_blocknr_t search_blk;
struct buffer_head *indirblock;
befs_disk_block_run *array;
befs_block_run indirect = data->indirect;
befs_blocknr_t indirblockno = iaddr2blockno(sb, &indirect);
int arraylen = befs_iaddrs_per_block(sb);
befs_debug(sb, "---> %s, find %lu", __func__, (unsigned long)blockno);
indir_start_blk = data->max_direct_range >> BEFS_SB(sb)->block_shift;
search_blk = blockno - indir_start_blk;
/* Examine blocks of the indirect run one at a time */
for (i = 0; i < indirect.len; i++) {
indirblock = befs_bread(sb, indirblockno + i);
if (indirblock == NULL) {
befs_debug(sb, "---> %s failed to read "
"disk block %lu from the indirect brun",
__func__, (unsigned long)indirblockno + i);
return BEFS_ERR;
}
array = (befs_disk_block_run *) indirblock->b_data;
for (j = 0; j < arraylen; ++j) {
int len = fs16_to_cpu(sb, array[j].len);
if (search_blk >= sum && search_blk < sum + len) {
int offset = search_blk - sum;
run->allocation_group =
fs32_to_cpu(sb, array[j].allocation_group);
run->start =
fs16_to_cpu(sb, array[j].start) + offset;
run->len =
fs16_to_cpu(sb, array[j].len) - offset;
brelse(indirblock);
befs_debug(sb,
"<--- %s found file block "
"%lu at indirect[%d]", __func__,
(unsigned long)blockno,
j + (i * arraylen));
return BEFS_OK;
}
sum += len;
}
brelse(indirblock);
}
/* Only fallthrough is an error */
befs_error(sb, "BeFS: %s failed to find "
"file block %lu", __func__, (unsigned long)blockno);
befs_debug(sb, "<--- %s ERROR", __func__);
return BEFS_ERR;
}
/*
Finds the block run that starts at file block number blockno
in the file represented by the datastream data, if that
blockno is in the double-indirect region of the datastream.
sb: the superblock
data: the datastream
blockno: the blocknumber to find
run: The found run is passed back through this pointer
Return value is BEFS_OK if the blockrun is found, BEFS_ERR
otherwise.
Algorithm:
The block runs in the double-indirect region are different.
They are always allocated 4 fs blocks at a time, so each
block run maps a constant amount of file data. This means
that we can directly calculate how many block runs into the
double-indirect region we need to go to get to the one that
maps a particular filesystem block.
We do this in two stages. First we calculate which of the
inode addresses in the double-indirect block will point us
to the indirect block that contains the mapping for the data,
then we calculate which of the inode addresses in that
indirect block maps the data block we are after.
Oh, and once we've done that, we actually read in the blocks
that contain the inode addresses we calculated above. Even
though the double-indirect run may be several blocks long,
we can calculate which of those blocks will contain the index
we are after and only read that one. We then follow it to
the indirect block and perform a similar process to find
the actual block run that maps the data block we are interested
in.
Then we offset the run as in befs_find_brun_array() and we are
done.
2001-11-15 Will Dyson
*/
static int
befs_find_brun_dblindirect(struct super_block *sb,
befs_data_stream * data, befs_blocknr_t blockno,
befs_block_run * run)
{
int dblindir_indx;
int indir_indx;
int offset;
int dbl_which_block;
int which_block;
int dbl_block_indx;
int block_indx;
off_t dblindir_leftover;
befs_blocknr_t blockno_at_run_start;
struct buffer_head *dbl_indir_block;
struct buffer_head *indir_block;
befs_block_run indir_run;
befs_disk_inode_addr *iaddr_array = NULL;
struct befs_sb_info *befs_sb = BEFS_SB(sb);
befs_blocknr_t indir_start_blk =
data->max_indirect_range >> befs_sb->block_shift;
off_t dbl_indir_off = blockno - indir_start_blk;
/* number of data blocks mapped by each of the iaddrs in
* the indirect block pointed to by the double indirect block
*/
size_t iblklen = BEFS_DBLINDIR_BRUN_LEN;
/* number of data blocks mapped by each of the iaddrs in
* the double indirect block
*/
size_t diblklen = iblklen * befs_iaddrs_per_block(sb)
* BEFS_DBLINDIR_BRUN_LEN;
befs_debug(sb, "---> %s find %lu", __func__, (unsigned long)blockno);
/* First, discover which of the double_indir->indir blocks
* contains pos. Then figure out how much of pos that
* accounted for. Then discover which of the iaddrs in
* the indirect block contains pos.
*/
dblindir_indx = dbl_indir_off / diblklen;
dblindir_leftover = dbl_indir_off % diblklen;
indir_indx = dblindir_leftover / diblklen;
/* Read double indirect block */
dbl_which_block = dblindir_indx / befs_iaddrs_per_block(sb);
if (dbl_which_block > data->double_indirect.len) {
befs_error(sb, "The double-indirect index calculated by "
"%s, %d, is outside the range "
"of the double-indirect block", __func__,
dblindir_indx);
return BEFS_ERR;
}
dbl_indir_block =
befs_bread(sb, iaddr2blockno(sb, &data->double_indirect) +
dbl_which_block);
if (dbl_indir_block == NULL) {
befs_error(sb, "%s couldn't read the "
"double-indirect block at blockno %lu", __func__,
(unsigned long)
iaddr2blockno(sb, &data->double_indirect) +
dbl_which_block);
brelse(dbl_indir_block);
return BEFS_ERR;
}
dbl_block_indx =
dblindir_indx - (dbl_which_block * befs_iaddrs_per_block(sb));
iaddr_array = (befs_disk_inode_addr *) dbl_indir_block->b_data;
indir_run = fsrun_to_cpu(sb, iaddr_array[dbl_block_indx]);
brelse(dbl_indir_block);
iaddr_array = NULL;
/* Read indirect block */
which_block = indir_indx / befs_iaddrs_per_block(sb);
if (which_block > indir_run.len) {
befs_error(sb, "The indirect index calculated by "
"%s, %d, is outside the range "
"of the indirect block", __func__, indir_indx);
return BEFS_ERR;
}
indir_block =
befs_bread(sb, iaddr2blockno(sb, &indir_run) + which_block);
if (indir_block == NULL) {
befs_error(sb, "%s couldn't read the indirect block "
"at blockno %lu", __func__, (unsigned long)
iaddr2blockno(sb, &indir_run) + which_block);
brelse(indir_block);
return BEFS_ERR;
}
block_indx = indir_indx - (which_block * befs_iaddrs_per_block(sb));
iaddr_array = (befs_disk_inode_addr *) indir_block->b_data;
*run = fsrun_to_cpu(sb, iaddr_array[block_indx]);
brelse(indir_block);
iaddr_array = NULL;
blockno_at_run_start = indir_start_blk;
blockno_at_run_start += diblklen * dblindir_indx;
blockno_at_run_start += iblklen * indir_indx;
offset = blockno - blockno_at_run_start;
run->start += offset;
run->len -= offset;
befs_debug(sb, "Found file block %lu in double_indirect[%d][%d],"
" double_indirect_leftover = %lu", (unsigned long)
blockno, dblindir_indx, indir_indx, dblindir_leftover);
return BEFS_OK;
}
| gpl-2.0 |
virtuous/kernel-7x30-gingerbread-v3 | arch/cris/arch-v32/drivers/pcf8563.c | 848 | 8685 | /*
* PCF8563 RTC
*
* From Phillips' datasheet:
*
* The PCF8563 is a CMOS real-time clock/calendar optimized for low power
* consumption. A programmable clock output, interrupt output and voltage
* low detector are also provided. All address and data are transferred
* serially via two-line bidirectional I2C-bus. Maximum bus speed is
* 400 kbits/s. The built-in word address register is incremented
* automatically after each written or read byte.
*
* Copyright (c) 2002-2007, Axis Communications AB
* All rights reserved.
*
* Author: Tobias Anderberg <tobiasa@axis.com>.
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/ioctl.h>
#include <linux/smp_lock.h>
#include <linux/delay.h>
#include <linux/bcd.h>
#include <linux/mutex.h>
#include <asm/uaccess.h>
#include <asm/system.h>
#include <asm/io.h>
#include <asm/rtc.h>
#include "i2c.h"
#define PCF8563_MAJOR 121 /* Local major number. */
#define DEVICE_NAME "rtc" /* Name which is registered in /proc/devices. */
#define PCF8563_NAME "PCF8563"
#define DRIVER_VERSION "$Revision: 1.17 $"
/* Two simple wrapper macros, saves a few keystrokes. */
#define rtc_read(x) i2c_readreg(RTC_I2C_READ, x)
#define rtc_write(x,y) i2c_writereg(RTC_I2C_WRITE, x, y)
static DEFINE_MUTEX(rtc_lock); /* Protect state etc */
static const unsigned char days_in_month[] =
{ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
static long pcf8563_unlocked_ioctl(struct file *filp, unsigned int cmd, unsigned long arg);
/* Cache VL bit value read at driver init since writing the RTC_SECOND
* register clears the VL status.
*/
static int voltage_low;
static const struct file_operations pcf8563_fops = {
.owner = THIS_MODULE,
.unlocked_ioctl = pcf8563_unlocked_ioctl,
};
unsigned char
pcf8563_readreg(int reg)
{
unsigned char res = rtc_read(reg);
/* The PCF8563 does not return 0 for unimplemented bits. */
switch (reg) {
case RTC_SECONDS:
case RTC_MINUTES:
res &= 0x7F;
break;
case RTC_HOURS:
case RTC_DAY_OF_MONTH:
res &= 0x3F;
break;
case RTC_WEEKDAY:
res &= 0x07;
break;
case RTC_MONTH:
res &= 0x1F;
break;
case RTC_CONTROL1:
res &= 0xA8;
break;
case RTC_CONTROL2:
res &= 0x1F;
break;
case RTC_CLOCKOUT_FREQ:
case RTC_TIMER_CONTROL:
res &= 0x83;
break;
}
return res;
}
void
pcf8563_writereg(int reg, unsigned char val)
{
rtc_write(reg, val);
}
void
get_rtc_time(struct rtc_time *tm)
{
tm->tm_sec = rtc_read(RTC_SECONDS);
tm->tm_min = rtc_read(RTC_MINUTES);
tm->tm_hour = rtc_read(RTC_HOURS);
tm->tm_mday = rtc_read(RTC_DAY_OF_MONTH);
tm->tm_wday = rtc_read(RTC_WEEKDAY);
tm->tm_mon = rtc_read(RTC_MONTH);
tm->tm_year = rtc_read(RTC_YEAR);
if (tm->tm_sec & 0x80) {
printk(KERN_ERR "%s: RTC Voltage Low - reliable date/time "
"information is no longer guaranteed!\n", PCF8563_NAME);
}
tm->tm_year = bcd2bin(tm->tm_year) +
((tm->tm_mon & 0x80) ? 100 : 0);
tm->tm_sec &= 0x7F;
tm->tm_min &= 0x7F;
tm->tm_hour &= 0x3F;
tm->tm_mday &= 0x3F;
tm->tm_wday &= 0x07; /* Not coded in BCD. */
tm->tm_mon &= 0x1F;
tm->tm_sec = bcd2bin(tm->tm_sec);
tm->tm_min = bcd2bin(tm->tm_min);
tm->tm_hour = bcd2bin(tm->tm_hour);
tm->tm_mday = bcd2bin(tm->tm_mday);
tm->tm_mon = bcd2bin(tm->tm_mon);
tm->tm_mon--; /* Month is 1..12 in RTC but 0..11 in linux */
}
int __init
pcf8563_init(void)
{
static int res;
static int first = 1;
if (!first)
return res;
first = 0;
/* Initiate the i2c protocol. */
res = i2c_init();
if (res < 0) {
printk(KERN_CRIT "pcf8563_init: Failed to init i2c.\n");
return res;
}
/*
* First of all we need to reset the chip. This is done by
* clearing control1, control2 and clk freq and resetting
* all alarms.
*/
if (rtc_write(RTC_CONTROL1, 0x00) < 0)
goto err;
if (rtc_write(RTC_CONTROL2, 0x00) < 0)
goto err;
if (rtc_write(RTC_CLOCKOUT_FREQ, 0x00) < 0)
goto err;
if (rtc_write(RTC_TIMER_CONTROL, 0x03) < 0)
goto err;
/* Reset the alarms. */
if (rtc_write(RTC_MINUTE_ALARM, 0x80) < 0)
goto err;
if (rtc_write(RTC_HOUR_ALARM, 0x80) < 0)
goto err;
if (rtc_write(RTC_DAY_ALARM, 0x80) < 0)
goto err;
if (rtc_write(RTC_WEEKDAY_ALARM, 0x80) < 0)
goto err;
/* Check for low voltage, and warn about it. */
if (rtc_read(RTC_SECONDS) & 0x80) {
voltage_low = 1;
printk(KERN_WARNING "%s: RTC Voltage Low - reliable "
"date/time information is no longer guaranteed!\n",
PCF8563_NAME);
}
return res;
err:
printk(KERN_INFO "%s: Error initializing chip.\n", PCF8563_NAME);
res = -1;
return res;
}
void __exit
pcf8563_exit(void)
{
unregister_chrdev(PCF8563_MAJOR, DEVICE_NAME);
}
/*
* ioctl calls for this driver. Why return -ENOTTY upon error? Because
* POSIX says so!
*/
static int pcf8563_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
/* Some sanity checks. */
if (_IOC_TYPE(cmd) != RTC_MAGIC)
return -ENOTTY;
if (_IOC_NR(cmd) > RTC_MAX_IOCTL)
return -ENOTTY;
switch (cmd) {
case RTC_RD_TIME:
{
struct rtc_time tm;
mutex_lock(&rtc_lock);
memset(&tm, 0, sizeof tm);
get_rtc_time(&tm);
if (copy_to_user((struct rtc_time *) arg, &tm,
sizeof tm)) {
mutex_unlock(&rtc_lock);
return -EFAULT;
}
mutex_unlock(&rtc_lock);
return 0;
}
case RTC_SET_TIME:
{
int leap;
int year;
int century;
struct rtc_time tm;
memset(&tm, 0, sizeof tm);
if (!capable(CAP_SYS_TIME))
return -EPERM;
if (copy_from_user(&tm, (struct rtc_time *) arg,
sizeof tm))
return -EFAULT;
/* Convert from struct tm to struct rtc_time. */
tm.tm_year += 1900;
tm.tm_mon += 1;
/*
* Check if tm.tm_year is a leap year. A year is a leap
* year if it is divisible by 4 but not 100, except
* that years divisible by 400 _are_ leap years.
*/
year = tm.tm_year;
leap = (tm.tm_mon == 2) &&
((year % 4 == 0 && year % 100 != 0) || year % 400 == 0);
/* Perform some sanity checks. */
if ((tm.tm_year < 1970) ||
(tm.tm_mon > 12) ||
(tm.tm_mday == 0) ||
(tm.tm_mday > days_in_month[tm.tm_mon] + leap) ||
(tm.tm_wday >= 7) ||
(tm.tm_hour >= 24) ||
(tm.tm_min >= 60) ||
(tm.tm_sec >= 60))
return -EINVAL;
century = (tm.tm_year >= 2000) ? 0x80 : 0;
tm.tm_year = tm.tm_year % 100;
tm.tm_year = bin2bcd(tm.tm_year);
tm.tm_mon = bin2bcd(tm.tm_mon);
tm.tm_mday = bin2bcd(tm.tm_mday);
tm.tm_hour = bin2bcd(tm.tm_hour);
tm.tm_min = bin2bcd(tm.tm_min);
tm.tm_sec = bin2bcd(tm.tm_sec);
tm.tm_mon |= century;
mutex_lock(&rtc_lock);
rtc_write(RTC_YEAR, tm.tm_year);
rtc_write(RTC_MONTH, tm.tm_mon);
rtc_write(RTC_WEEKDAY, tm.tm_wday); /* Not coded in BCD. */
rtc_write(RTC_DAY_OF_MONTH, tm.tm_mday);
rtc_write(RTC_HOURS, tm.tm_hour);
rtc_write(RTC_MINUTES, tm.tm_min);
rtc_write(RTC_SECONDS, tm.tm_sec);
mutex_unlock(&rtc_lock);
return 0;
}
case RTC_VL_READ:
if (voltage_low)
printk(KERN_ERR "%s: RTC Voltage Low - "
"reliable date/time information is no "
"longer guaranteed!\n", PCF8563_NAME);
if (copy_to_user((int *) arg, &voltage_low, sizeof(int)))
return -EFAULT;
return 0;
case RTC_VL_CLR:
{
/* Clear the VL bit in the seconds register in case
* the time has not been set already (which would
* have cleared it). This does not really matter
* because of the cached voltage_low value but do it
* anyway for consistency. */
int ret = rtc_read(RTC_SECONDS);
rtc_write(RTC_SECONDS, (ret & 0x7F));
/* Clear the cached value. */
voltage_low = 0;
return 0;
}
default:
return -ENOTTY;
}
return 0;
}
static long pcf8563_unlocked_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
int ret;
lock_kernel();
return pcf8563_ioctl(filp, cmd, arg);
unlock_kernel();
return ret;
}
static int __init pcf8563_register(void)
{
if (pcf8563_init() < 0) {
printk(KERN_INFO "%s: Unable to initialize Real-Time Clock "
"Driver, %s\n", PCF8563_NAME, DRIVER_VERSION);
return -1;
}
if (register_chrdev(PCF8563_MAJOR, DEVICE_NAME, &pcf8563_fops) < 0) {
printk(KERN_INFO "%s: Unable to get major numer %d for RTC "
"device.\n", PCF8563_NAME, PCF8563_MAJOR);
return -1;
}
printk(KERN_INFO "%s Real-Time Clock Driver, %s\n", PCF8563_NAME,
DRIVER_VERSION);
/* Check for low voltage, and warn about it. */
if (voltage_low) {
printk(KERN_WARNING "%s: RTC Voltage Low - reliable date/time "
"information is no longer guaranteed!\n", PCF8563_NAME);
}
return 0;
}
module_init(pcf8563_register);
module_exit(pcf8563_exit);
| gpl-2.0 |
joeyli/linux-acpitad | sound/soc/pxa/pxa2xx-i2s.c | 848 | 10177 | /*
* pxa2xx-i2s.c -- ALSA Soc Audio Layer
*
* Copyright 2005 Wolfson Microelectronics PLC.
* Author: Liam Girdwood
* lrg@slimlogic.co.uk
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/delay.h>
#include <linux/clk.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/initval.h>
#include <sound/soc.h>
#include <sound/pxa2xx-lib.h>
#include <sound/dmaengine_pcm.h>
#include <mach/hardware.h>
#include <mach/audio.h>
#include "pxa2xx-i2s.h"
/*
* I2S Controller Register and Bit Definitions
*/
#define SACR0 __REG(0x40400000) /* Global Control Register */
#define SACR1 __REG(0x40400004) /* Serial Audio I 2 S/MSB-Justified Control Register */
#define SASR0 __REG(0x4040000C) /* Serial Audio I 2 S/MSB-Justified Interface and FIFO Status Register */
#define SAIMR __REG(0x40400014) /* Serial Audio Interrupt Mask Register */
#define SAICR __REG(0x40400018) /* Serial Audio Interrupt Clear Register */
#define SADIV __REG(0x40400060) /* Audio Clock Divider Register. */
#define SADR __REG(0x40400080) /* Serial Audio Data Register (TX and RX FIFO access Register). */
#define SACR0_RFTH(x) ((x) << 12) /* Rx FIFO Interrupt or DMA Trigger Threshold */
#define SACR0_TFTH(x) ((x) << 8) /* Tx FIFO Interrupt or DMA Trigger Threshold */
#define SACR0_STRF (1 << 5) /* FIFO Select for EFWR Special Function */
#define SACR0_EFWR (1 << 4) /* Enable EFWR Function */
#define SACR0_RST (1 << 3) /* FIFO, i2s Register Reset */
#define SACR0_BCKD (1 << 2) /* Bit Clock Direction */
#define SACR0_ENB (1 << 0) /* Enable I2S Link */
#define SACR1_ENLBF (1 << 5) /* Enable Loopback */
#define SACR1_DRPL (1 << 4) /* Disable Replaying Function */
#define SACR1_DREC (1 << 3) /* Disable Recording Function */
#define SACR1_AMSL (1 << 0) /* Specify Alternate Mode */
#define SASR0_I2SOFF (1 << 7) /* Controller Status */
#define SASR0_ROR (1 << 6) /* Rx FIFO Overrun */
#define SASR0_TUR (1 << 5) /* Tx FIFO Underrun */
#define SASR0_RFS (1 << 4) /* Rx FIFO Service Request */
#define SASR0_TFS (1 << 3) /* Tx FIFO Service Request */
#define SASR0_BSY (1 << 2) /* I2S Busy */
#define SASR0_RNE (1 << 1) /* Rx FIFO Not Empty */
#define SASR0_TNF (1 << 0) /* Tx FIFO Not Empty */
#define SAICR_ROR (1 << 6) /* Clear Rx FIFO Overrun Interrupt */
#define SAICR_TUR (1 << 5) /* Clear Tx FIFO Underrun Interrupt */
#define SAIMR_ROR (1 << 6) /* Enable Rx FIFO Overrun Condition Interrupt */
#define SAIMR_TUR (1 << 5) /* Enable Tx FIFO Underrun Condition Interrupt */
#define SAIMR_RFS (1 << 4) /* Enable Rx FIFO Service Interrupt */
#define SAIMR_TFS (1 << 3) /* Enable Tx FIFO Service Interrupt */
struct pxa_i2s_port {
u32 sadiv;
u32 sacr0;
u32 sacr1;
u32 saimr;
int master;
u32 fmt;
};
static struct pxa_i2s_port pxa_i2s;
static struct clk *clk_i2s;
static int clk_ena = 0;
static unsigned long pxa2xx_i2s_pcm_stereo_out_req = 3;
static struct snd_dmaengine_dai_dma_data pxa2xx_i2s_pcm_stereo_out = {
.addr = __PREG(SADR),
.addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES,
.maxburst = 32,
.filter_data = &pxa2xx_i2s_pcm_stereo_out_req,
};
static unsigned long pxa2xx_i2s_pcm_stereo_in_req = 2;
static struct snd_dmaengine_dai_dma_data pxa2xx_i2s_pcm_stereo_in = {
.addr = __PREG(SADR),
.addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES,
.maxburst = 32,
.filter_data = &pxa2xx_i2s_pcm_stereo_in_req,
};
static int pxa2xx_i2s_startup(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
if (IS_ERR(clk_i2s))
return PTR_ERR(clk_i2s);
if (!cpu_dai->active)
SACR0 = 0;
return 0;
}
/* wait for I2S controller to be ready */
static int pxa_i2s_wait(void)
{
int i;
/* flush the Rx FIFO */
for(i = 0; i < 16; i++)
SADR;
return 0;
}
static int pxa2xx_i2s_set_dai_fmt(struct snd_soc_dai *cpu_dai,
unsigned int fmt)
{
/* interface format */
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_I2S:
pxa_i2s.fmt = 0;
break;
case SND_SOC_DAIFMT_LEFT_J:
pxa_i2s.fmt = SACR1_AMSL;
break;
}
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBS_CFS:
pxa_i2s.master = 1;
break;
case SND_SOC_DAIFMT_CBM_CFS:
pxa_i2s.master = 0;
break;
default:
break;
}
return 0;
}
static int pxa2xx_i2s_set_dai_sysclk(struct snd_soc_dai *cpu_dai,
int clk_id, unsigned int freq, int dir)
{
if (clk_id != PXA2XX_I2S_SYSCLK)
return -ENODEV;
return 0;
}
static int pxa2xx_i2s_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct snd_dmaengine_dai_dma_data *dma_data;
if (WARN_ON(IS_ERR(clk_i2s)))
return -EINVAL;
clk_prepare_enable(clk_i2s);
clk_ena = 1;
pxa_i2s_wait();
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
dma_data = &pxa2xx_i2s_pcm_stereo_out;
else
dma_data = &pxa2xx_i2s_pcm_stereo_in;
snd_soc_dai_set_dma_data(dai, substream, dma_data);
/* is port used by another stream */
if (!(SACR0 & SACR0_ENB)) {
SACR0 = 0;
if (pxa_i2s.master)
SACR0 |= SACR0_BCKD;
SACR0 |= SACR0_RFTH(14) | SACR0_TFTH(1);
SACR1 |= pxa_i2s.fmt;
}
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
SAIMR |= SAIMR_TFS;
else
SAIMR |= SAIMR_RFS;
switch (params_rate(params)) {
case 8000:
SADIV = 0x48;
break;
case 11025:
SADIV = 0x34;
break;
case 16000:
SADIV = 0x24;
break;
case 22050:
SADIV = 0x1a;
break;
case 44100:
SADIV = 0xd;
break;
case 48000:
SADIV = 0xc;
break;
case 96000: /* not in manual and possibly slightly inaccurate */
SADIV = 0x6;
break;
}
return 0;
}
static int pxa2xx_i2s_trigger(struct snd_pcm_substream *substream, int cmd,
struct snd_soc_dai *dai)
{
int ret = 0;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
SACR1 &= ~SACR1_DRPL;
else
SACR1 &= ~SACR1_DREC;
SACR0 |= SACR0_ENB;
break;
case SNDRV_PCM_TRIGGER_RESUME:
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
break;
default:
ret = -EINVAL;
}
return ret;
}
static void pxa2xx_i2s_shutdown(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
SACR1 |= SACR1_DRPL;
SAIMR &= ~SAIMR_TFS;
} else {
SACR1 |= SACR1_DREC;
SAIMR &= ~SAIMR_RFS;
}
if ((SACR1 & (SACR1_DREC | SACR1_DRPL)) == (SACR1_DREC | SACR1_DRPL)) {
SACR0 &= ~SACR0_ENB;
pxa_i2s_wait();
if (clk_ena) {
clk_disable_unprepare(clk_i2s);
clk_ena = 0;
}
}
}
#ifdef CONFIG_PM
static int pxa2xx_i2s_suspend(struct snd_soc_dai *dai)
{
/* store registers */
pxa_i2s.sacr0 = SACR0;
pxa_i2s.sacr1 = SACR1;
pxa_i2s.saimr = SAIMR;
pxa_i2s.sadiv = SADIV;
/* deactivate link */
SACR0 &= ~SACR0_ENB;
pxa_i2s_wait();
return 0;
}
static int pxa2xx_i2s_resume(struct snd_soc_dai *dai)
{
pxa_i2s_wait();
SACR0 = pxa_i2s.sacr0 & ~SACR0_ENB;
SACR1 = pxa_i2s.sacr1;
SAIMR = pxa_i2s.saimr;
SADIV = pxa_i2s.sadiv;
SACR0 = pxa_i2s.sacr0;
return 0;
}
#else
#define pxa2xx_i2s_suspend NULL
#define pxa2xx_i2s_resume NULL
#endif
static int pxa2xx_i2s_probe(struct snd_soc_dai *dai)
{
clk_i2s = clk_get(dai->dev, "I2SCLK");
if (IS_ERR(clk_i2s))
return PTR_ERR(clk_i2s);
/*
* PXA Developer's Manual:
* If SACR0[ENB] is toggled in the middle of a normal operation,
* the SACR0[RST] bit must also be set and cleared to reset all
* I2S controller registers.
*/
SACR0 = SACR0_RST;
SACR0 = 0;
/* Make sure RPL and REC are disabled */
SACR1 = SACR1_DRPL | SACR1_DREC;
/* Along with FIFO servicing */
SAIMR &= ~(SAIMR_RFS | SAIMR_TFS);
return 0;
}
static int pxa2xx_i2s_remove(struct snd_soc_dai *dai)
{
clk_put(clk_i2s);
clk_i2s = ERR_PTR(-ENOENT);
return 0;
}
#define PXA2XX_I2S_RATES (SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_11025 |\
SNDRV_PCM_RATE_16000 | SNDRV_PCM_RATE_22050 | SNDRV_PCM_RATE_44100 | \
SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_96000)
static const struct snd_soc_dai_ops pxa_i2s_dai_ops = {
.startup = pxa2xx_i2s_startup,
.shutdown = pxa2xx_i2s_shutdown,
.trigger = pxa2xx_i2s_trigger,
.hw_params = pxa2xx_i2s_hw_params,
.set_fmt = pxa2xx_i2s_set_dai_fmt,
.set_sysclk = pxa2xx_i2s_set_dai_sysclk,
};
static struct snd_soc_dai_driver pxa_i2s_dai = {
.probe = pxa2xx_i2s_probe,
.remove = pxa2xx_i2s_remove,
.suspend = pxa2xx_i2s_suspend,
.resume = pxa2xx_i2s_resume,
.playback = {
.channels_min = 2,
.channels_max = 2,
.rates = PXA2XX_I2S_RATES,
.formats = SNDRV_PCM_FMTBIT_S16_LE,},
.capture = {
.channels_min = 2,
.channels_max = 2,
.rates = PXA2XX_I2S_RATES,
.formats = SNDRV_PCM_FMTBIT_S16_LE,},
.ops = &pxa_i2s_dai_ops,
.symmetric_rates = 1,
};
static const struct snd_soc_component_driver pxa_i2s_component = {
.name = "pxa-i2s",
};
static int pxa2xx_i2s_drv_probe(struct platform_device *pdev)
{
return snd_soc_register_component(&pdev->dev, &pxa_i2s_component,
&pxa_i2s_dai, 1);
}
static int pxa2xx_i2s_drv_remove(struct platform_device *pdev)
{
snd_soc_unregister_component(&pdev->dev);
return 0;
}
static struct platform_driver pxa2xx_i2s_driver = {
.probe = pxa2xx_i2s_drv_probe,
.remove = pxa2xx_i2s_drv_remove,
.driver = {
.name = "pxa2xx-i2s",
.owner = THIS_MODULE,
},
};
static int __init pxa2xx_i2s_init(void)
{
clk_i2s = ERR_PTR(-ENOENT);
return platform_driver_register(&pxa2xx_i2s_driver);
}
static void __exit pxa2xx_i2s_exit(void)
{
platform_driver_unregister(&pxa2xx_i2s_driver);
}
module_init(pxa2xx_i2s_init);
module_exit(pxa2xx_i2s_exit);
/* Module information */
MODULE_AUTHOR("Liam Girdwood, lrg@slimlogic.co.uk");
MODULE_DESCRIPTION("pxa2xx I2S SoC Interface");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:pxa2xx-i2s");
| gpl-2.0 |
AOKP-SGS2/android_kernel_samsung_espresso | drivers/mtd/devices/slram.c | 2128 | 9281 | /*======================================================================
This driver provides a method to access memory not used by the kernel
itself (i.e. if the kernel commandline mem=xxx is used). To actually
use slram at least mtdblock or mtdchar is required (for block or
character device access).
Usage:
if compiled as loadable module:
modprobe slram map=<name>,<start>,<end/offset>
if statically linked into the kernel use the following kernel cmd.line
slram=<name>,<start>,<end/offset>
<name>: name of the device that will be listed in /proc/mtd
<start>: start of the memory region, decimal or hex (0xabcdef)
<end/offset>: end of the memory region. It's possible to use +0x1234
to specify the offset instead of the absolute address
NOTE:
With slram it's only possible to map a contiguous memory region. Therefore
if there's a device mapped somewhere in the region specified slram will
fail to load (see kernel log if modprobe fails).
-
Jochen Schaeuble <psionic@psionic.de>
======================================================================*/
#include <linux/module.h>
#include <asm/uaccess.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/ptrace.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/timer.h>
#include <linux/major.h>
#include <linux/fs.h>
#include <linux/ioctl.h>
#include <linux/init.h>
#include <asm/io.h>
#include <asm/system.h>
#include <linux/mtd/mtd.h>
#define SLRAM_MAX_DEVICES_PARAMS 6 /* 3 parameters / device */
#define SLRAM_BLK_SZ 0x4000
#define T(fmt, args...) printk(KERN_DEBUG fmt, ## args)
#define E(fmt, args...) printk(KERN_NOTICE fmt, ## args)
typedef struct slram_priv {
u_char *start;
u_char *end;
} slram_priv_t;
typedef struct slram_mtd_list {
struct mtd_info *mtdinfo;
struct slram_mtd_list *next;
} slram_mtd_list_t;
#ifdef MODULE
static char *map[SLRAM_MAX_DEVICES_PARAMS];
module_param_array(map, charp, NULL, 0);
MODULE_PARM_DESC(map, "List of memory regions to map. \"map=<name>, <start>, <length / end>\"");
#else
static char *map;
#endif
static slram_mtd_list_t *slram_mtdlist = NULL;
static int slram_erase(struct mtd_info *, struct erase_info *);
static int slram_point(struct mtd_info *, loff_t, size_t, size_t *, void **,
resource_size_t *);
static void slram_unpoint(struct mtd_info *, loff_t, size_t);
static int slram_read(struct mtd_info *, loff_t, size_t, size_t *, u_char *);
static int slram_write(struct mtd_info *, loff_t, size_t, size_t *, const u_char *);
static int slram_erase(struct mtd_info *mtd, struct erase_info *instr)
{
slram_priv_t *priv = mtd->priv;
if (instr->addr + instr->len > mtd->size) {
return(-EINVAL);
}
memset(priv->start + instr->addr, 0xff, instr->len);
/* This'll catch a few races. Free the thing before returning :)
* I don't feel at all ashamed. This kind of thing is possible anyway
* with flash, but unlikely.
*/
instr->state = MTD_ERASE_DONE;
mtd_erase_callback(instr);
return(0);
}
static int slram_point(struct mtd_info *mtd, loff_t from, size_t len,
size_t *retlen, void **virt, resource_size_t *phys)
{
slram_priv_t *priv = mtd->priv;
/* can we return a physical address with this driver? */
if (phys)
return -EINVAL;
if (from + len > mtd->size)
return -EINVAL;
*virt = priv->start + from;
*retlen = len;
return(0);
}
static void slram_unpoint(struct mtd_info *mtd, loff_t from, size_t len)
{
}
static int slram_read(struct mtd_info *mtd, loff_t from, size_t len,
size_t *retlen, u_char *buf)
{
slram_priv_t *priv = mtd->priv;
if (from > mtd->size)
return -EINVAL;
if (from + len > mtd->size)
len = mtd->size - from;
memcpy(buf, priv->start + from, len);
*retlen = len;
return(0);
}
static int slram_write(struct mtd_info *mtd, loff_t to, size_t len,
size_t *retlen, const u_char *buf)
{
slram_priv_t *priv = mtd->priv;
if (to + len > mtd->size)
return -EINVAL;
memcpy(priv->start + to, buf, len);
*retlen = len;
return(0);
}
/*====================================================================*/
static int register_device(char *name, unsigned long start, unsigned long length)
{
slram_mtd_list_t **curmtd;
curmtd = &slram_mtdlist;
while (*curmtd) {
curmtd = &(*curmtd)->next;
}
*curmtd = kmalloc(sizeof(slram_mtd_list_t), GFP_KERNEL);
if (!(*curmtd)) {
E("slram: Cannot allocate new MTD device.\n");
return(-ENOMEM);
}
(*curmtd)->mtdinfo = kzalloc(sizeof(struct mtd_info), GFP_KERNEL);
(*curmtd)->next = NULL;
if ((*curmtd)->mtdinfo) {
(*curmtd)->mtdinfo->priv =
kzalloc(sizeof(slram_priv_t), GFP_KERNEL);
if (!(*curmtd)->mtdinfo->priv) {
kfree((*curmtd)->mtdinfo);
(*curmtd)->mtdinfo = NULL;
}
}
if (!(*curmtd)->mtdinfo) {
E("slram: Cannot allocate new MTD device.\n");
return(-ENOMEM);
}
if (!(((slram_priv_t *)(*curmtd)->mtdinfo->priv)->start =
ioremap(start, length))) {
E("slram: ioremap failed\n");
return -EIO;
}
((slram_priv_t *)(*curmtd)->mtdinfo->priv)->end =
((slram_priv_t *)(*curmtd)->mtdinfo->priv)->start + length;
(*curmtd)->mtdinfo->name = name;
(*curmtd)->mtdinfo->size = length;
(*curmtd)->mtdinfo->flags = MTD_CAP_RAM;
(*curmtd)->mtdinfo->erase = slram_erase;
(*curmtd)->mtdinfo->point = slram_point;
(*curmtd)->mtdinfo->unpoint = slram_unpoint;
(*curmtd)->mtdinfo->read = slram_read;
(*curmtd)->mtdinfo->write = slram_write;
(*curmtd)->mtdinfo->owner = THIS_MODULE;
(*curmtd)->mtdinfo->type = MTD_RAM;
(*curmtd)->mtdinfo->erasesize = SLRAM_BLK_SZ;
(*curmtd)->mtdinfo->writesize = 1;
if (mtd_device_register((*curmtd)->mtdinfo, NULL, 0)) {
E("slram: Failed to register new device\n");
iounmap(((slram_priv_t *)(*curmtd)->mtdinfo->priv)->start);
kfree((*curmtd)->mtdinfo->priv);
kfree((*curmtd)->mtdinfo);
return(-EAGAIN);
}
T("slram: Registered device %s from %luKiB to %luKiB\n", name,
(start / 1024), ((start + length) / 1024));
T("slram: Mapped from 0x%p to 0x%p\n",
((slram_priv_t *)(*curmtd)->mtdinfo->priv)->start,
((slram_priv_t *)(*curmtd)->mtdinfo->priv)->end);
return(0);
}
static void unregister_devices(void)
{
slram_mtd_list_t *nextitem;
while (slram_mtdlist) {
nextitem = slram_mtdlist->next;
mtd_device_unregister(slram_mtdlist->mtdinfo);
iounmap(((slram_priv_t *)slram_mtdlist->mtdinfo->priv)->start);
kfree(slram_mtdlist->mtdinfo->priv);
kfree(slram_mtdlist->mtdinfo);
kfree(slram_mtdlist);
slram_mtdlist = nextitem;
}
}
static unsigned long handle_unit(unsigned long value, char *unit)
{
if ((*unit == 'M') || (*unit == 'm')) {
return(value * 1024 * 1024);
} else if ((*unit == 'K') || (*unit == 'k')) {
return(value * 1024);
}
return(value);
}
static int parse_cmdline(char *devname, char *szstart, char *szlength)
{
char *buffer;
unsigned long devstart;
unsigned long devlength;
if ((!devname) || (!szstart) || (!szlength)) {
unregister_devices();
return(-EINVAL);
}
devstart = simple_strtoul(szstart, &buffer, 0);
devstart = handle_unit(devstart, buffer);
if (*(szlength) != '+') {
devlength = simple_strtoul(szlength, &buffer, 0);
devlength = handle_unit(devlength, buffer) - devstart;
if (devlength < devstart)
goto err_out;
devlength -= devstart;
} else {
devlength = simple_strtoul(szlength + 1, &buffer, 0);
devlength = handle_unit(devlength, buffer);
}
T("slram: devname=%s, devstart=0x%lx, devlength=0x%lx\n",
devname, devstart, devlength);
if (devlength % SLRAM_BLK_SZ != 0)
goto err_out;
if ((devstart = register_device(devname, devstart, devlength))){
unregister_devices();
return((int)devstart);
}
return(0);
err_out:
E("slram: Illegal length parameter.\n");
return(-EINVAL);
}
#ifndef MODULE
static int __init mtd_slram_setup(char *str)
{
map = str;
return(1);
}
__setup("slram=", mtd_slram_setup);
#endif
static int __init init_slram(void)
{
char *devname;
int i;
#ifndef MODULE
char *devstart;
char *devlength;
i = 0;
if (!map) {
E("slram: not enough parameters.\n");
return(-EINVAL);
}
while (map) {
devname = devstart = devlength = NULL;
if (!(devname = strsep(&map, ","))) {
E("slram: No devicename specified.\n");
break;
}
T("slram: devname = %s\n", devname);
if ((!map) || (!(devstart = strsep(&map, ",")))) {
E("slram: No devicestart specified.\n");
}
T("slram: devstart = %s\n", devstart);
if ((!map) || (!(devlength = strsep(&map, ",")))) {
E("slram: No devicelength / -end specified.\n");
}
T("slram: devlength = %s\n", devlength);
if (parse_cmdline(devname, devstart, devlength) != 0) {
return(-EINVAL);
}
}
#else
int count;
for (count = 0; count < SLRAM_MAX_DEVICES_PARAMS && map[count];
count++) {
}
if ((count % 3 != 0) || (count == 0)) {
E("slram: not enough parameters.\n");
return(-EINVAL);
}
for (i = 0; i < (count / 3); i++) {
devname = map[i * 3];
if (parse_cmdline(devname, map[i * 3 + 1], map[i * 3 + 2])!=0) {
return(-EINVAL);
}
}
#endif /* !MODULE */
return(0);
}
static void __exit cleanup_slram(void)
{
unregister_devices();
}
module_init(init_slram);
module_exit(cleanup_slram);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Jochen Schaeuble <psionic@psionic.de>");
MODULE_DESCRIPTION("MTD driver for uncached system RAM");
| gpl-2.0 |
padovan/bluetooth-next | arch/microblaze/kernel/reset.c | 3152 | 2849 | /*
* Copyright (C) 2009 Michal Simek <monstr@monstr.eu>
* Copyright (C) 2009 PetaLogix
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/init.h>
#include <linux/of_platform.h>
#include <asm/prom.h>
/* Trigger specific functions */
#ifdef CONFIG_GPIOLIB
#include <linux/of_gpio.h>
static int handle; /* reset pin handle */
static unsigned int reset_val;
static int of_reset_gpio_handle(void)
{
int ret; /* variable which stored handle reset gpio pin */
struct device_node *root; /* root node */
struct device_node *gpio; /* gpio node */
struct gpio_chip *gc;
u32 flags;
const void *gpio_spec;
/* find out root node */
root = of_find_node_by_path("/");
/* give me handle for gpio node to be possible allocate pin */
ret = of_parse_phandles_with_args(root, "hard-reset-gpios",
"#gpio-cells", 0, &gpio, &gpio_spec);
if (ret) {
pr_debug("%s: can't parse gpios property\n", __func__);
goto err0;
}
gc = of_node_to_gpiochip(gpio);
if (!gc) {
pr_debug("%s: gpio controller %s isn't registered\n",
root->full_name, gpio->full_name);
ret = -ENODEV;
goto err1;
}
ret = gc->of_xlate(gc, root, gpio_spec, &flags);
if (ret < 0)
goto err1;
ret += gc->base;
err1:
of_node_put(gpio);
err0:
pr_debug("%s exited with status %d\n", __func__, ret);
return ret;
}
void of_platform_reset_gpio_probe(void)
{
int ret;
handle = of_reset_gpio_handle();
if (!gpio_is_valid(handle)) {
printk(KERN_INFO "Skipping unavailable RESET gpio %d (%s)\n",
handle, "reset");
}
ret = gpio_request(handle, "reset");
if (ret < 0) {
printk(KERN_INFO "GPIO pin is already allocated\n");
return;
}
/* get current setup value */
reset_val = gpio_get_value(handle);
/* FIXME maybe worth to perform any action */
pr_debug("Reset: Gpio output state: 0x%x\n", reset_val);
/* Setup GPIO as output */
ret = gpio_direction_output(handle, 0);
if (ret < 0)
goto err;
/* Setup output direction */
gpio_set_value(handle, 0);
printk(KERN_INFO "RESET: Registered gpio device: %d, current val: %d\n",
handle, reset_val);
return;
err:
gpio_free(handle);
return;
}
static void gpio_system_reset(void)
{
gpio_set_value(handle, 1 - reset_val);
}
#else
#define gpio_system_reset() do {} while (0)
void of_platform_reset_gpio_probe(void)
{
return;
}
#endif
void machine_restart(char *cmd)
{
printk(KERN_NOTICE "Machine restart...\n");
gpio_system_reset();
dump_stack();
while (1)
;
}
void machine_shutdown(void)
{
printk(KERN_NOTICE "Machine shutdown...\n");
while (1)
;
}
void machine_halt(void)
{
printk(KERN_NOTICE "Machine halt...\n");
while (1)
;
}
void machine_power_off(void)
{
printk(KERN_NOTICE "Machine power off...\n");
while (1)
;
}
| gpl-2.0 |
blackb1rd/android_kernel_samsung_d2 | drivers/net/phy/phy.c | 4688 | 23422 | /*
* drivers/net/phy/phy.c
*
* Framework for configuring and reading PHY devices
* Based on code in sungem_phy.c and gianfar_phy.c
*
* Author: Andy Fleming
*
* Copyright (c) 2004 Freescale Semiconductor, Inc.
* Copyright (c) 2006, 2007 Maciej W. Rozycki
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
*/
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/unistd.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/mii.h>
#include <linux/ethtool.h>
#include <linux/phy.h>
#include <linux/timer.h>
#include <linux/workqueue.h>
#include <linux/atomic.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/uaccess.h>
/**
* phy_print_status - Convenience function to print out the current phy status
* @phydev: the phy_device struct
*/
void phy_print_status(struct phy_device *phydev)
{
pr_info("PHY: %s - Link is %s", dev_name(&phydev->dev),
phydev->link ? "Up" : "Down");
if (phydev->link)
printk(KERN_CONT " - %d/%s", phydev->speed,
DUPLEX_FULL == phydev->duplex ?
"Full" : "Half");
printk(KERN_CONT "\n");
}
EXPORT_SYMBOL(phy_print_status);
/**
* phy_clear_interrupt - Ack the phy device's interrupt
* @phydev: the phy_device struct
*
* If the @phydev driver has an ack_interrupt function, call it to
* ack and clear the phy device's interrupt.
*
* Returns 0 on success on < 0 on error.
*/
static int phy_clear_interrupt(struct phy_device *phydev)
{
int err = 0;
if (phydev->drv->ack_interrupt)
err = phydev->drv->ack_interrupt(phydev);
return err;
}
/**
* phy_config_interrupt - configure the PHY device for the requested interrupts
* @phydev: the phy_device struct
* @interrupts: interrupt flags to configure for this @phydev
*
* Returns 0 on success on < 0 on error.
*/
static int phy_config_interrupt(struct phy_device *phydev, u32 interrupts)
{
int err = 0;
phydev->interrupts = interrupts;
if (phydev->drv->config_intr)
err = phydev->drv->config_intr(phydev);
return err;
}
/**
* phy_aneg_done - return auto-negotiation status
* @phydev: target phy_device struct
*
* Description: Reads the status register and returns 0 either if
* auto-negotiation is incomplete, or if there was an error.
* Returns BMSR_ANEGCOMPLETE if auto-negotiation is done.
*/
static inline int phy_aneg_done(struct phy_device *phydev)
{
int retval;
retval = phy_read(phydev, MII_BMSR);
return (retval < 0) ? retval : (retval & BMSR_ANEGCOMPLETE);
}
/* A structure for mapping a particular speed and duplex
* combination to a particular SUPPORTED and ADVERTISED value */
struct phy_setting {
int speed;
int duplex;
u32 setting;
};
/* A mapping of all SUPPORTED settings to speed/duplex */
static const struct phy_setting settings[] = {
{
.speed = 10000,
.duplex = DUPLEX_FULL,
.setting = SUPPORTED_10000baseT_Full,
},
{
.speed = SPEED_1000,
.duplex = DUPLEX_FULL,
.setting = SUPPORTED_1000baseT_Full,
},
{
.speed = SPEED_1000,
.duplex = DUPLEX_HALF,
.setting = SUPPORTED_1000baseT_Half,
},
{
.speed = SPEED_100,
.duplex = DUPLEX_FULL,
.setting = SUPPORTED_100baseT_Full,
},
{
.speed = SPEED_100,
.duplex = DUPLEX_HALF,
.setting = SUPPORTED_100baseT_Half,
},
{
.speed = SPEED_10,
.duplex = DUPLEX_FULL,
.setting = SUPPORTED_10baseT_Full,
},
{
.speed = SPEED_10,
.duplex = DUPLEX_HALF,
.setting = SUPPORTED_10baseT_Half,
},
};
#define MAX_NUM_SETTINGS ARRAY_SIZE(settings)
/**
* phy_find_setting - find a PHY settings array entry that matches speed & duplex
* @speed: speed to match
* @duplex: duplex to match
*
* Description: Searches the settings array for the setting which
* matches the desired speed and duplex, and returns the index
* of that setting. Returns the index of the last setting if
* none of the others match.
*/
static inline int phy_find_setting(int speed, int duplex)
{
int idx = 0;
while (idx < ARRAY_SIZE(settings) &&
(settings[idx].speed != speed ||
settings[idx].duplex != duplex))
idx++;
return idx < MAX_NUM_SETTINGS ? idx : MAX_NUM_SETTINGS - 1;
}
/**
* phy_find_valid - find a PHY setting that matches the requested features mask
* @idx: The first index in settings[] to search
* @features: A mask of the valid settings
*
* Description: Returns the index of the first valid setting less
* than or equal to the one pointed to by idx, as determined by
* the mask in features. Returns the index of the last setting
* if nothing else matches.
*/
static inline int phy_find_valid(int idx, u32 features)
{
while (idx < MAX_NUM_SETTINGS && !(settings[idx].setting & features))
idx++;
return idx < MAX_NUM_SETTINGS ? idx : MAX_NUM_SETTINGS - 1;
}
/**
* phy_sanitize_settings - make sure the PHY is set to supported speed and duplex
* @phydev: the target phy_device struct
*
* Description: Make sure the PHY is set to supported speeds and
* duplexes. Drop down by one in this order: 1000/FULL,
* 1000/HALF, 100/FULL, 100/HALF, 10/FULL, 10/HALF.
*/
static void phy_sanitize_settings(struct phy_device *phydev)
{
u32 features = phydev->supported;
int idx;
/* Sanitize settings based on PHY capabilities */
if ((features & SUPPORTED_Autoneg) == 0)
phydev->autoneg = AUTONEG_DISABLE;
idx = phy_find_valid(phy_find_setting(phydev->speed, phydev->duplex),
features);
phydev->speed = settings[idx].speed;
phydev->duplex = settings[idx].duplex;
}
/**
* phy_ethtool_sset - generic ethtool sset function, handles all the details
* @phydev: target phy_device struct
* @cmd: ethtool_cmd
*
* A few notes about parameter checking:
* - We don't set port or transceiver, so we don't care what they
* were set to.
* - phy_start_aneg() will make sure forced settings are sane, and
* choose the next best ones from the ones selected, so we don't
* care if ethtool tries to give us bad values.
*/
int phy_ethtool_sset(struct phy_device *phydev, struct ethtool_cmd *cmd)
{
u32 speed = ethtool_cmd_speed(cmd);
if (cmd->phy_address != phydev->addr)
return -EINVAL;
/* We make sure that we don't pass unsupported
* values in to the PHY */
cmd->advertising &= phydev->supported;
/* Verify the settings we care about. */
if (cmd->autoneg != AUTONEG_ENABLE && cmd->autoneg != AUTONEG_DISABLE)
return -EINVAL;
if (cmd->autoneg == AUTONEG_ENABLE && cmd->advertising == 0)
return -EINVAL;
if (cmd->autoneg == AUTONEG_DISABLE &&
((speed != SPEED_1000 &&
speed != SPEED_100 &&
speed != SPEED_10) ||
(cmd->duplex != DUPLEX_HALF &&
cmd->duplex != DUPLEX_FULL)))
return -EINVAL;
phydev->autoneg = cmd->autoneg;
phydev->speed = speed;
phydev->advertising = cmd->advertising;
if (AUTONEG_ENABLE == cmd->autoneg)
phydev->advertising |= ADVERTISED_Autoneg;
else
phydev->advertising &= ~ADVERTISED_Autoneg;
phydev->duplex = cmd->duplex;
/* Restart the PHY */
phy_start_aneg(phydev);
return 0;
}
EXPORT_SYMBOL(phy_ethtool_sset);
int phy_ethtool_gset(struct phy_device *phydev, struct ethtool_cmd *cmd)
{
cmd->supported = phydev->supported;
cmd->advertising = phydev->advertising;
ethtool_cmd_speed_set(cmd, phydev->speed);
cmd->duplex = phydev->duplex;
cmd->port = PORT_MII;
cmd->phy_address = phydev->addr;
cmd->transceiver = XCVR_EXTERNAL;
cmd->autoneg = phydev->autoneg;
return 0;
}
EXPORT_SYMBOL(phy_ethtool_gset);
/**
* phy_mii_ioctl - generic PHY MII ioctl interface
* @phydev: the phy_device struct
* @ifr: &struct ifreq for socket ioctl's
* @cmd: ioctl cmd to execute
*
* Note that this function is currently incompatible with the
* PHYCONTROL layer. It changes registers without regard to
* current state. Use at own risk.
*/
int phy_mii_ioctl(struct phy_device *phydev,
struct ifreq *ifr, int cmd)
{
struct mii_ioctl_data *mii_data = if_mii(ifr);
u16 val = mii_data->val_in;
switch (cmd) {
case SIOCGMIIPHY:
mii_data->phy_id = phydev->addr;
/* fall through */
case SIOCGMIIREG:
mii_data->val_out = mdiobus_read(phydev->bus, mii_data->phy_id,
mii_data->reg_num);
break;
case SIOCSMIIREG:
if (mii_data->phy_id == phydev->addr) {
switch(mii_data->reg_num) {
case MII_BMCR:
if ((val & (BMCR_RESET|BMCR_ANENABLE)) == 0)
phydev->autoneg = AUTONEG_DISABLE;
else
phydev->autoneg = AUTONEG_ENABLE;
if ((!phydev->autoneg) && (val & BMCR_FULLDPLX))
phydev->duplex = DUPLEX_FULL;
else
phydev->duplex = DUPLEX_HALF;
if ((!phydev->autoneg) &&
(val & BMCR_SPEED1000))
phydev->speed = SPEED_1000;
else if ((!phydev->autoneg) &&
(val & BMCR_SPEED100))
phydev->speed = SPEED_100;
break;
case MII_ADVERTISE:
phydev->advertising = val;
break;
default:
/* do nothing */
break;
}
}
mdiobus_write(phydev->bus, mii_data->phy_id,
mii_data->reg_num, val);
if (mii_data->reg_num == MII_BMCR &&
val & BMCR_RESET &&
phydev->drv->config_init) {
phy_scan_fixups(phydev);
phydev->drv->config_init(phydev);
}
break;
case SIOCSHWTSTAMP:
if (phydev->drv->hwtstamp)
return phydev->drv->hwtstamp(phydev, ifr);
/* fall through */
default:
return -EOPNOTSUPP;
}
return 0;
}
EXPORT_SYMBOL(phy_mii_ioctl);
/**
* phy_start_aneg - start auto-negotiation for this PHY device
* @phydev: the phy_device struct
*
* Description: Sanitizes the settings (if we're not autonegotiating
* them), and then calls the driver's config_aneg function.
* If the PHYCONTROL Layer is operating, we change the state to
* reflect the beginning of Auto-negotiation or forcing.
*/
int phy_start_aneg(struct phy_device *phydev)
{
int err;
mutex_lock(&phydev->lock);
if (AUTONEG_DISABLE == phydev->autoneg)
phy_sanitize_settings(phydev);
err = phydev->drv->config_aneg(phydev);
if (err < 0)
goto out_unlock;
if (phydev->state != PHY_HALTED) {
if (AUTONEG_ENABLE == phydev->autoneg) {
phydev->state = PHY_AN;
phydev->link_timeout = PHY_AN_TIMEOUT;
} else {
phydev->state = PHY_FORCING;
phydev->link_timeout = PHY_FORCE_TIMEOUT;
}
}
out_unlock:
mutex_unlock(&phydev->lock);
return err;
}
EXPORT_SYMBOL(phy_start_aneg);
static void phy_change(struct work_struct *work);
/**
* phy_start_machine - start PHY state machine tracking
* @phydev: the phy_device struct
* @handler: callback function for state change notifications
*
* Description: The PHY infrastructure can run a state machine
* which tracks whether the PHY is starting up, negotiating,
* etc. This function starts the timer which tracks the state
* of the PHY. If you want to be notified when the state changes,
* pass in the callback @handler, otherwise, pass NULL. If you
* want to maintain your own state machine, do not call this
* function.
*/
void phy_start_machine(struct phy_device *phydev,
void (*handler)(struct net_device *))
{
phydev->adjust_state = handler;
schedule_delayed_work(&phydev->state_queue, HZ);
}
/**
* phy_stop_machine - stop the PHY state machine tracking
* @phydev: target phy_device struct
*
* Description: Stops the state machine timer, sets the state to UP
* (unless it wasn't up yet). This function must be called BEFORE
* phy_detach.
*/
void phy_stop_machine(struct phy_device *phydev)
{
cancel_delayed_work_sync(&phydev->state_queue);
mutex_lock(&phydev->lock);
if (phydev->state > PHY_UP)
phydev->state = PHY_UP;
mutex_unlock(&phydev->lock);
phydev->adjust_state = NULL;
}
/**
* phy_force_reduction - reduce PHY speed/duplex settings by one step
* @phydev: target phy_device struct
*
* Description: Reduces the speed/duplex settings by one notch,
* in this order--
* 1000/FULL, 1000/HALF, 100/FULL, 100/HALF, 10/FULL, 10/HALF.
* The function bottoms out at 10/HALF.
*/
static void phy_force_reduction(struct phy_device *phydev)
{
int idx;
idx = phy_find_setting(phydev->speed, phydev->duplex);
idx++;
idx = phy_find_valid(idx, phydev->supported);
phydev->speed = settings[idx].speed;
phydev->duplex = settings[idx].duplex;
pr_info("Trying %d/%s\n", phydev->speed,
DUPLEX_FULL == phydev->duplex ?
"FULL" : "HALF");
}
/**
* phy_error - enter HALTED state for this PHY device
* @phydev: target phy_device struct
*
* Moves the PHY to the HALTED state in response to a read
* or write error, and tells the controller the link is down.
* Must not be called from interrupt context, or while the
* phydev->lock is held.
*/
static void phy_error(struct phy_device *phydev)
{
mutex_lock(&phydev->lock);
phydev->state = PHY_HALTED;
mutex_unlock(&phydev->lock);
}
/**
* phy_interrupt - PHY interrupt handler
* @irq: interrupt line
* @phy_dat: phy_device pointer
*
* Description: When a PHY interrupt occurs, the handler disables
* interrupts, and schedules a work task to clear the interrupt.
*/
static irqreturn_t phy_interrupt(int irq, void *phy_dat)
{
struct phy_device *phydev = phy_dat;
if (PHY_HALTED == phydev->state)
return IRQ_NONE; /* It can't be ours. */
/* The MDIO bus is not allowed to be written in interrupt
* context, so we need to disable the irq here. A work
* queue will write the PHY to disable and clear the
* interrupt, and then reenable the irq line. */
disable_irq_nosync(irq);
atomic_inc(&phydev->irq_disable);
schedule_work(&phydev->phy_queue);
return IRQ_HANDLED;
}
/**
* phy_enable_interrupts - Enable the interrupts from the PHY side
* @phydev: target phy_device struct
*/
static int phy_enable_interrupts(struct phy_device *phydev)
{
int err;
err = phy_clear_interrupt(phydev);
if (err < 0)
return err;
err = phy_config_interrupt(phydev, PHY_INTERRUPT_ENABLED);
return err;
}
/**
* phy_disable_interrupts - Disable the PHY interrupts from the PHY side
* @phydev: target phy_device struct
*/
static int phy_disable_interrupts(struct phy_device *phydev)
{
int err;
/* Disable PHY interrupts */
err = phy_config_interrupt(phydev, PHY_INTERRUPT_DISABLED);
if (err)
goto phy_err;
/* Clear the interrupt */
err = phy_clear_interrupt(phydev);
if (err)
goto phy_err;
return 0;
phy_err:
phy_error(phydev);
return err;
}
/**
* phy_start_interrupts - request and enable interrupts for a PHY device
* @phydev: target phy_device struct
*
* Description: Request the interrupt for the given PHY.
* If this fails, then we set irq to PHY_POLL.
* Otherwise, we enable the interrupts in the PHY.
* This should only be called with a valid IRQ number.
* Returns 0 on success or < 0 on error.
*/
int phy_start_interrupts(struct phy_device *phydev)
{
int err = 0;
INIT_WORK(&phydev->phy_queue, phy_change);
atomic_set(&phydev->irq_disable, 0);
if (request_irq(phydev->irq, phy_interrupt,
IRQF_SHARED,
"phy_interrupt",
phydev) < 0) {
printk(KERN_WARNING "%s: Can't get IRQ %d (PHY)\n",
phydev->bus->name,
phydev->irq);
phydev->irq = PHY_POLL;
return 0;
}
err = phy_enable_interrupts(phydev);
return err;
}
EXPORT_SYMBOL(phy_start_interrupts);
/**
* phy_stop_interrupts - disable interrupts from a PHY device
* @phydev: target phy_device struct
*/
int phy_stop_interrupts(struct phy_device *phydev)
{
int err;
err = phy_disable_interrupts(phydev);
if (err)
phy_error(phydev);
free_irq(phydev->irq, phydev);
/*
* Cannot call flush_scheduled_work() here as desired because
* of rtnl_lock(), but we do not really care about what would
* be done, except from enable_irq(), so cancel any work
* possibly pending and take care of the matter below.
*/
cancel_work_sync(&phydev->phy_queue);
/*
* If work indeed has been cancelled, disable_irq() will have
* been left unbalanced from phy_interrupt() and enable_irq()
* has to be called so that other devices on the line work.
*/
while (atomic_dec_return(&phydev->irq_disable) >= 0)
enable_irq(phydev->irq);
return err;
}
EXPORT_SYMBOL(phy_stop_interrupts);
/**
* phy_change - Scheduled by the phy_interrupt/timer to handle PHY changes
* @work: work_struct that describes the work to be done
*/
static void phy_change(struct work_struct *work)
{
int err;
struct phy_device *phydev =
container_of(work, struct phy_device, phy_queue);
if (phydev->drv->did_interrupt &&
!phydev->drv->did_interrupt(phydev))
goto ignore;
err = phy_disable_interrupts(phydev);
if (err)
goto phy_err;
mutex_lock(&phydev->lock);
if ((PHY_RUNNING == phydev->state) || (PHY_NOLINK == phydev->state))
phydev->state = PHY_CHANGELINK;
mutex_unlock(&phydev->lock);
atomic_dec(&phydev->irq_disable);
enable_irq(phydev->irq);
/* Reenable interrupts */
if (PHY_HALTED != phydev->state)
err = phy_config_interrupt(phydev, PHY_INTERRUPT_ENABLED);
if (err)
goto irq_enable_err;
/* reschedule state queue work to run as soon as possible */
cancel_delayed_work_sync(&phydev->state_queue);
schedule_delayed_work(&phydev->state_queue, 0);
return;
ignore:
atomic_dec(&phydev->irq_disable);
enable_irq(phydev->irq);
return;
irq_enable_err:
disable_irq(phydev->irq);
atomic_inc(&phydev->irq_disable);
phy_err:
phy_error(phydev);
}
/**
* phy_stop - Bring down the PHY link, and stop checking the status
* @phydev: target phy_device struct
*/
void phy_stop(struct phy_device *phydev)
{
mutex_lock(&phydev->lock);
if (PHY_HALTED == phydev->state)
goto out_unlock;
if (phydev->irq != PHY_POLL) {
/* Disable PHY Interrupts */
phy_config_interrupt(phydev, PHY_INTERRUPT_DISABLED);
/* Clear any pending interrupts */
phy_clear_interrupt(phydev);
}
phydev->state = PHY_HALTED;
out_unlock:
mutex_unlock(&phydev->lock);
/*
* Cannot call flush_scheduled_work() here as desired because
* of rtnl_lock(), but PHY_HALTED shall guarantee phy_change()
* will not reenable interrupts.
*/
}
/**
* phy_start - start or restart a PHY device
* @phydev: target phy_device struct
*
* Description: Indicates the attached device's readiness to
* handle PHY-related work. Used during startup to start the
* PHY, and after a call to phy_stop() to resume operation.
* Also used to indicate the MDIO bus has cleared an error
* condition.
*/
void phy_start(struct phy_device *phydev)
{
mutex_lock(&phydev->lock);
switch (phydev->state) {
case PHY_STARTING:
phydev->state = PHY_PENDING;
break;
case PHY_READY:
phydev->state = PHY_UP;
break;
case PHY_HALTED:
phydev->state = PHY_RESUMING;
default:
break;
}
mutex_unlock(&phydev->lock);
}
EXPORT_SYMBOL(phy_stop);
EXPORT_SYMBOL(phy_start);
/**
* phy_state_machine - Handle the state machine
* @work: work_struct that describes the work to be done
*/
void phy_state_machine(struct work_struct *work)
{
struct delayed_work *dwork = to_delayed_work(work);
struct phy_device *phydev =
container_of(dwork, struct phy_device, state_queue);
int needs_aneg = 0;
int err = 0;
mutex_lock(&phydev->lock);
if (phydev->adjust_state)
phydev->adjust_state(phydev->attached_dev);
switch(phydev->state) {
case PHY_DOWN:
case PHY_STARTING:
case PHY_READY:
case PHY_PENDING:
break;
case PHY_UP:
needs_aneg = 1;
phydev->link_timeout = PHY_AN_TIMEOUT;
break;
case PHY_AN:
err = phy_read_status(phydev);
if (err < 0)
break;
/* If the link is down, give up on
* negotiation for now */
if (!phydev->link) {
phydev->state = PHY_NOLINK;
netif_carrier_off(phydev->attached_dev);
phydev->adjust_link(phydev->attached_dev);
break;
}
/* Check if negotiation is done. Break
* if there's an error */
err = phy_aneg_done(phydev);
if (err < 0)
break;
/* If AN is done, we're running */
if (err > 0) {
phydev->state = PHY_RUNNING;
netif_carrier_on(phydev->attached_dev);
phydev->adjust_link(phydev->attached_dev);
} else if (0 == phydev->link_timeout--) {
int idx;
needs_aneg = 1;
/* If we have the magic_aneg bit,
* we try again */
if (phydev->drv->flags & PHY_HAS_MAGICANEG)
break;
/* The timer expired, and we still
* don't have a setting, so we try
* forcing it until we find one that
* works, starting from the fastest speed,
* and working our way down */
idx = phy_find_valid(0, phydev->supported);
phydev->speed = settings[idx].speed;
phydev->duplex = settings[idx].duplex;
phydev->autoneg = AUTONEG_DISABLE;
pr_info("Trying %d/%s\n", phydev->speed,
DUPLEX_FULL ==
phydev->duplex ?
"FULL" : "HALF");
}
break;
case PHY_NOLINK:
err = phy_read_status(phydev);
if (err)
break;
if (phydev->link) {
phydev->state = PHY_RUNNING;
netif_carrier_on(phydev->attached_dev);
phydev->adjust_link(phydev->attached_dev);
}
break;
case PHY_FORCING:
err = genphy_update_link(phydev);
if (err)
break;
if (phydev->link) {
phydev->state = PHY_RUNNING;
netif_carrier_on(phydev->attached_dev);
} else {
if (0 == phydev->link_timeout--) {
phy_force_reduction(phydev);
needs_aneg = 1;
}
}
phydev->adjust_link(phydev->attached_dev);
break;
case PHY_RUNNING:
/* Only register a CHANGE if we are
* polling */
if (PHY_POLL == phydev->irq)
phydev->state = PHY_CHANGELINK;
break;
case PHY_CHANGELINK:
err = phy_read_status(phydev);
if (err)
break;
if (phydev->link) {
phydev->state = PHY_RUNNING;
netif_carrier_on(phydev->attached_dev);
} else {
phydev->state = PHY_NOLINK;
netif_carrier_off(phydev->attached_dev);
}
phydev->adjust_link(phydev->attached_dev);
if (PHY_POLL != phydev->irq)
err = phy_config_interrupt(phydev,
PHY_INTERRUPT_ENABLED);
break;
case PHY_HALTED:
if (phydev->link) {
phydev->link = 0;
netif_carrier_off(phydev->attached_dev);
phydev->adjust_link(phydev->attached_dev);
}
break;
case PHY_RESUMING:
err = phy_clear_interrupt(phydev);
if (err)
break;
err = phy_config_interrupt(phydev,
PHY_INTERRUPT_ENABLED);
if (err)
break;
if (AUTONEG_ENABLE == phydev->autoneg) {
err = phy_aneg_done(phydev);
if (err < 0)
break;
/* err > 0 if AN is done.
* Otherwise, it's 0, and we're
* still waiting for AN */
if (err > 0) {
err = phy_read_status(phydev);
if (err)
break;
if (phydev->link) {
phydev->state = PHY_RUNNING;
netif_carrier_on(phydev->attached_dev);
} else
phydev->state = PHY_NOLINK;
phydev->adjust_link(phydev->attached_dev);
} else {
phydev->state = PHY_AN;
phydev->link_timeout = PHY_AN_TIMEOUT;
}
} else {
err = phy_read_status(phydev);
if (err)
break;
if (phydev->link) {
phydev->state = PHY_RUNNING;
netif_carrier_on(phydev->attached_dev);
} else
phydev->state = PHY_NOLINK;
phydev->adjust_link(phydev->attached_dev);
}
break;
}
mutex_unlock(&phydev->lock);
if (needs_aneg)
err = phy_start_aneg(phydev);
if (err < 0)
phy_error(phydev);
schedule_delayed_work(&phydev->state_queue, PHY_STATE_TIME * HZ);
}
| gpl-2.0 |
sycolon/lge_g3_kernel | arch/x86/kernel/devicetree.c | 4688 | 7740 | /*
* Architecture specific OF callbacks.
*/
#include <linux/bootmem.h>
#include <linux/export.h>
#include <linux/io.h>
#include <linux/irqdomain.h>
#include <linux/interrupt.h>
#include <linux/list.h>
#include <linux/of.h>
#include <linux/of_fdt.h>
#include <linux/of_address.h>
#include <linux/of_platform.h>
#include <linux/of_irq.h>
#include <linux/slab.h>
#include <linux/pci.h>
#include <linux/of_pci.h>
#include <linux/initrd.h>
#include <asm/hpet.h>
#include <asm/apic.h>
#include <asm/pci_x86.h>
__initdata u64 initial_dtb;
char __initdata cmd_line[COMMAND_LINE_SIZE];
int __initdata of_ioapic;
unsigned long pci_address_to_pio(phys_addr_t address)
{
/*
* The ioport address can be directly used by inX / outX
*/
BUG_ON(address >= (1 << 16));
return (unsigned long)address;
}
EXPORT_SYMBOL_GPL(pci_address_to_pio);
void __init early_init_dt_scan_chosen_arch(unsigned long node)
{
BUG();
}
void __init early_init_dt_add_memory_arch(u64 base, u64 size)
{
BUG();
}
void * __init early_init_dt_alloc_memory_arch(u64 size, u64 align)
{
return __alloc_bootmem(size, align, __pa(MAX_DMA_ADDRESS));
}
#ifdef CONFIG_BLK_DEV_INITRD
void __init early_init_dt_setup_initrd_arch(unsigned long start,
unsigned long end)
{
initrd_start = (unsigned long)__va(start);
initrd_end = (unsigned long)__va(end);
initrd_below_start_ok = 1;
}
#endif
void __init add_dtb(u64 data)
{
initial_dtb = data + offsetof(struct setup_data, data);
}
/*
* CE4100 ids. Will be moved to machine_device_initcall() once we have it.
*/
static struct of_device_id __initdata ce4100_ids[] = {
{ .compatible = "intel,ce4100-cp", },
{ .compatible = "isa", },
{ .compatible = "pci", },
{},
};
static int __init add_bus_probe(void)
{
if (!of_have_populated_dt())
return 0;
return of_platform_bus_probe(NULL, ce4100_ids, NULL);
}
module_init(add_bus_probe);
#ifdef CONFIG_PCI
struct device_node *pcibios_get_phb_of_node(struct pci_bus *bus)
{
struct device_node *np;
for_each_node_by_type(np, "pci") {
const void *prop;
unsigned int bus_min;
prop = of_get_property(np, "bus-range", NULL);
if (!prop)
continue;
bus_min = be32_to_cpup(prop);
if (bus->number == bus_min)
return np;
}
return NULL;
}
static int x86_of_pci_irq_enable(struct pci_dev *dev)
{
struct of_irq oirq;
u32 virq;
int ret;
u8 pin;
ret = pci_read_config_byte(dev, PCI_INTERRUPT_PIN, &pin);
if (ret)
return ret;
if (!pin)
return 0;
ret = of_irq_map_pci(dev, &oirq);
if (ret)
return ret;
virq = irq_create_of_mapping(oirq.controller, oirq.specifier,
oirq.size);
if (virq == 0)
return -EINVAL;
dev->irq = virq;
return 0;
}
static void x86_of_pci_irq_disable(struct pci_dev *dev)
{
}
void __cpuinit x86_of_pci_init(void)
{
pcibios_enable_irq = x86_of_pci_irq_enable;
pcibios_disable_irq = x86_of_pci_irq_disable;
}
#endif
static void __init dtb_setup_hpet(void)
{
#ifdef CONFIG_HPET_TIMER
struct device_node *dn;
struct resource r;
int ret;
dn = of_find_compatible_node(NULL, NULL, "intel,ce4100-hpet");
if (!dn)
return;
ret = of_address_to_resource(dn, 0, &r);
if (ret) {
WARN_ON(1);
return;
}
hpet_address = r.start;
#endif
}
static void __init dtb_lapic_setup(void)
{
#ifdef CONFIG_X86_LOCAL_APIC
struct device_node *dn;
struct resource r;
int ret;
dn = of_find_compatible_node(NULL, NULL, "intel,ce4100-lapic");
if (!dn)
return;
ret = of_address_to_resource(dn, 0, &r);
if (WARN_ON(ret))
return;
/* Did the boot loader setup the local APIC ? */
if (!cpu_has_apic) {
if (apic_force_enable(r.start))
return;
}
smp_found_config = 1;
pic_mode = 1;
register_lapic_address(r.start);
generic_processor_info(boot_cpu_physical_apicid,
GET_APIC_VERSION(apic_read(APIC_LVR)));
#endif
}
#ifdef CONFIG_X86_IO_APIC
static unsigned int ioapic_id;
static void __init dtb_add_ioapic(struct device_node *dn)
{
struct resource r;
int ret;
ret = of_address_to_resource(dn, 0, &r);
if (ret) {
printk(KERN_ERR "Can't obtain address from node %s.\n",
dn->full_name);
return;
}
mp_register_ioapic(++ioapic_id, r.start, gsi_top);
}
static void __init dtb_ioapic_setup(void)
{
struct device_node *dn;
for_each_compatible_node(dn, NULL, "intel,ce4100-ioapic")
dtb_add_ioapic(dn);
if (nr_ioapics) {
of_ioapic = 1;
return;
}
printk(KERN_ERR "Error: No information about IO-APIC in OF.\n");
}
#else
static void __init dtb_ioapic_setup(void) {}
#endif
static void __init dtb_apic_setup(void)
{
dtb_lapic_setup();
dtb_ioapic_setup();
}
#ifdef CONFIG_OF_FLATTREE
static void __init x86_flattree_get_config(void)
{
u32 size, map_len;
void *new_dtb;
if (!initial_dtb)
return;
map_len = max(PAGE_SIZE - (initial_dtb & ~PAGE_MASK),
(u64)sizeof(struct boot_param_header));
initial_boot_params = early_memremap(initial_dtb, map_len);
size = be32_to_cpu(initial_boot_params->totalsize);
if (map_len < size) {
early_iounmap(initial_boot_params, map_len);
initial_boot_params = early_memremap(initial_dtb, size);
map_len = size;
}
new_dtb = alloc_bootmem(size);
memcpy(new_dtb, initial_boot_params, size);
early_iounmap(initial_boot_params, map_len);
initial_boot_params = new_dtb;
/* root level address cells */
of_scan_flat_dt(early_init_dt_scan_root, NULL);
unflatten_device_tree();
}
#else
static inline void x86_flattree_get_config(void) { }
#endif
void __init x86_dtb_init(void)
{
x86_flattree_get_config();
if (!of_have_populated_dt())
return;
dtb_setup_hpet();
dtb_apic_setup();
}
#ifdef CONFIG_X86_IO_APIC
struct of_ioapic_type {
u32 out_type;
u32 trigger;
u32 polarity;
};
static struct of_ioapic_type of_ioapic_type[] =
{
{
.out_type = IRQ_TYPE_EDGE_RISING,
.trigger = IOAPIC_EDGE,
.polarity = 1,
},
{
.out_type = IRQ_TYPE_LEVEL_LOW,
.trigger = IOAPIC_LEVEL,
.polarity = 0,
},
{
.out_type = IRQ_TYPE_LEVEL_HIGH,
.trigger = IOAPIC_LEVEL,
.polarity = 1,
},
{
.out_type = IRQ_TYPE_EDGE_FALLING,
.trigger = IOAPIC_EDGE,
.polarity = 0,
},
};
static int ioapic_xlate(struct irq_domain *domain,
struct device_node *controller,
const u32 *intspec, u32 intsize,
irq_hw_number_t *out_hwirq, u32 *out_type)
{
struct io_apic_irq_attr attr;
struct of_ioapic_type *it;
u32 line, idx;
int rc;
if (WARN_ON(intsize < 2))
return -EINVAL;
line = intspec[0];
if (intspec[1] >= ARRAY_SIZE(of_ioapic_type))
return -EINVAL;
it = &of_ioapic_type[intspec[1]];
idx = (u32) domain->host_data;
set_io_apic_irq_attr(&attr, idx, line, it->trigger, it->polarity);
rc = io_apic_setup_irq_pin_once(irq_find_mapping(domain, line),
cpu_to_node(0), &attr);
if (rc)
return rc;
*out_hwirq = line;
*out_type = it->out_type;
return 0;
}
const struct irq_domain_ops ioapic_irq_domain_ops = {
.xlate = ioapic_xlate,
};
static void __init ioapic_add_ofnode(struct device_node *np)
{
struct resource r;
int i, ret;
ret = of_address_to_resource(np, 0, &r);
if (ret) {
printk(KERN_ERR "Failed to obtain address for %s\n",
np->full_name);
return;
}
for (i = 0; i < nr_ioapics; i++) {
if (r.start == mpc_ioapic_addr(i)) {
struct irq_domain *id;
struct mp_ioapic_gsi *gsi_cfg;
gsi_cfg = mp_ioapic_gsi_routing(i);
id = irq_domain_add_legacy(np, 32, gsi_cfg->gsi_base, 0,
&ioapic_irq_domain_ops,
(void*)i);
BUG_ON(!id);
return;
}
}
printk(KERN_ERR "IOxAPIC at %s is not registered.\n", np->full_name);
}
void __init x86_add_irq_domains(void)
{
struct device_node *dp;
if (!of_have_populated_dt())
return;
for_each_node_with_property(dp, "interrupt-controller") {
if (of_device_is_compatible(dp, "intel,ce4100-ioapic"))
ioapic_add_ofnode(dp);
}
}
#else
void __init x86_add_irq_domains(void) { }
#endif
| gpl-2.0 |
jollaman999/msm-mako-lollipop-mr1 | sound/soc/samsung/s3c24xx_simtec.c | 4944 | 9344 | /* sound/soc/samsung/s3c24xx_simtec.c
*
* Copyright 2009 Simtec Electronics
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/gpio.h>
#include <linux/clk.h>
#include <linux/module.h>
#include <sound/soc.h>
#include <plat/audio-simtec.h>
#include "s3c24xx-i2s.h"
#include "s3c24xx_simtec.h"
static struct s3c24xx_audio_simtec_pdata *pdata;
static struct clk *xtal_clk;
static int spk_gain;
static int spk_unmute;
/**
* speaker_gain_get - read the speaker gain setting.
* @kcontrol: The control for the speaker gain.
* @ucontrol: The value that needs to be updated.
*
* Read the value for the AMP gain control.
*/
static int speaker_gain_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
ucontrol->value.integer.value[0] = spk_gain;
return 0;
}
/**
* speaker_gain_set - set the value of the speaker amp gain
* @value: The value to write.
*/
static void speaker_gain_set(int value)
{
gpio_set_value_cansleep(pdata->amp_gain[0], value & 1);
gpio_set_value_cansleep(pdata->amp_gain[1], value >> 1);
}
/**
* speaker_gain_put - set the speaker gain setting.
* @kcontrol: The control for the speaker gain.
* @ucontrol: The value that needs to be set.
*
* Set the value of the speaker gain from the specified
* @ucontrol setting.
*
* Note, if the speaker amp is muted, then we do not set a gain value
* as at-least one of the ICs that is fitted will try and power up even
* if the main control is set to off.
*/
static int speaker_gain_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int value = ucontrol->value.integer.value[0];
spk_gain = value;
if (!spk_unmute)
speaker_gain_set(value);
return 0;
}
static const struct snd_kcontrol_new amp_gain_controls[] = {
SOC_SINGLE_EXT("Speaker Gain", 0, 0, 3, 0,
speaker_gain_get, speaker_gain_put),
};
/**
* spk_unmute_state - set the unmute state of the speaker
* @to: zero to unmute, non-zero to ununmute.
*/
static void spk_unmute_state(int to)
{
pr_debug("%s: to=%d\n", __func__, to);
spk_unmute = to;
gpio_set_value(pdata->amp_gpio, to);
/* if we're umuting, also re-set the gain */
if (to && pdata->amp_gain[0] > 0)
speaker_gain_set(spk_gain);
}
/**
* speaker_unmute_get - read the speaker unmute setting.
* @kcontrol: The control for the speaker gain.
* @ucontrol: The value that needs to be updated.
*
* Read the value for the AMP gain control.
*/
static int speaker_unmute_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
ucontrol->value.integer.value[0] = spk_unmute;
return 0;
}
/**
* speaker_unmute_put - set the speaker unmute setting.
* @kcontrol: The control for the speaker gain.
* @ucontrol: The value that needs to be set.
*
* Set the value of the speaker gain from the specified
* @ucontrol setting.
*/
static int speaker_unmute_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
spk_unmute_state(ucontrol->value.integer.value[0]);
return 0;
}
/* This is added as a manual control as the speaker amps create clicks
* when their power state is changed, which are far more noticeable than
* anything produced by the CODEC itself.
*/
static const struct snd_kcontrol_new amp_unmute_controls[] = {
SOC_SINGLE_EXT("Speaker Switch", 0, 0, 1, 0,
speaker_unmute_get, speaker_unmute_put),
};
void simtec_audio_init(struct snd_soc_pcm_runtime *rtd)
{
struct snd_soc_card *card = rtd->card;
if (pdata->amp_gpio > 0) {
pr_debug("%s: adding amp routes\n", __func__);
snd_soc_add_card_controls(card, amp_unmute_controls,
ARRAY_SIZE(amp_unmute_controls));
}
if (pdata->amp_gain[0] > 0) {
pr_debug("%s: adding amp controls\n", __func__);
snd_soc_add_card_controls(card, amp_gain_controls,
ARRAY_SIZE(amp_gain_controls));
}
}
EXPORT_SYMBOL_GPL(simtec_audio_init);
#define CODEC_CLOCK 12000000
/**
* simtec_hw_params - update hardware parameters
* @substream: The audio substream instance.
* @params: The parameters requested.
*
* Update the codec data routing and configuration settings
* from the supplied data.
*/
static int simtec_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *codec_dai = rtd->codec_dai;
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
int ret;
/* Set the CODEC as the bus clock master, I2S */
ret = snd_soc_dai_set_fmt(cpu_dai, SND_SOC_DAIFMT_I2S |
SND_SOC_DAIFMT_NB_NF |
SND_SOC_DAIFMT_CBM_CFM);
if (ret) {
pr_err("%s: failed set cpu dai format\n", __func__);
return ret;
}
/* Set the CODEC as the bus clock master */
ret = snd_soc_dai_set_fmt(codec_dai, SND_SOC_DAIFMT_I2S |
SND_SOC_DAIFMT_NB_NF |
SND_SOC_DAIFMT_CBM_CFM);
if (ret) {
pr_err("%s: failed set codec dai format\n", __func__);
return ret;
}
ret = snd_soc_dai_set_sysclk(codec_dai, 0,
CODEC_CLOCK, SND_SOC_CLOCK_IN);
if (ret) {
pr_err( "%s: failed setting codec sysclk\n", __func__);
return ret;
}
if (pdata->use_mpllin) {
ret = snd_soc_dai_set_sysclk(cpu_dai, S3C24XX_CLKSRC_MPLL,
0, SND_SOC_CLOCK_OUT);
if (ret) {
pr_err("%s: failed to set MPLLin as clksrc\n",
__func__);
return ret;
}
}
if (pdata->output_cdclk) {
int cdclk_scale;
cdclk_scale = clk_get_rate(xtal_clk) / CODEC_CLOCK;
cdclk_scale--;
ret = snd_soc_dai_set_clkdiv(cpu_dai, S3C24XX_DIV_PRESCALER,
cdclk_scale);
}
return 0;
}
static int simtec_call_startup(struct s3c24xx_audio_simtec_pdata *pd)
{
/* call any board supplied startup code, this currently only
* covers the bast/vr1000 which have a CPLD in the way of the
* LRCLK */
if (pd->startup)
pd->startup();
return 0;
}
static struct snd_soc_ops simtec_snd_ops = {
.hw_params = simtec_hw_params,
};
/**
* attach_gpio_amp - get and configure the necessary gpios
* @dev: The device we're probing.
* @pd: The platform data supplied by the board.
*
* If there is a GPIO based amplifier attached to the board, claim
* the necessary GPIO lines for it, and set default values.
*/
static int attach_gpio_amp(struct device *dev,
struct s3c24xx_audio_simtec_pdata *pd)
{
int ret;
/* attach gpio amp gain (if any) */
if (pdata->amp_gain[0] > 0) {
ret = gpio_request(pd->amp_gain[0], "gpio-amp-gain0");
if (ret) {
dev_err(dev, "cannot get amp gpio gain0\n");
return ret;
}
ret = gpio_request(pd->amp_gain[1], "gpio-amp-gain1");
if (ret) {
dev_err(dev, "cannot get amp gpio gain1\n");
gpio_free(pdata->amp_gain[0]);
return ret;
}
gpio_direction_output(pd->amp_gain[0], 0);
gpio_direction_output(pd->amp_gain[1], 0);
}
/* note, currently we assume GPA0 isn't valid amp */
if (pdata->amp_gpio > 0) {
ret = gpio_request(pd->amp_gpio, "gpio-amp");
if (ret) {
dev_err(dev, "cannot get amp gpio %d (%d)\n",
pd->amp_gpio, ret);
goto err_amp;
}
/* set the amp off at startup */
spk_unmute_state(0);
}
return 0;
err_amp:
if (pd->amp_gain[0] > 0) {
gpio_free(pd->amp_gain[0]);
gpio_free(pd->amp_gain[1]);
}
return ret;
}
static void detach_gpio_amp(struct s3c24xx_audio_simtec_pdata *pd)
{
if (pd->amp_gain[0] > 0) {
gpio_free(pd->amp_gain[0]);
gpio_free(pd->amp_gain[1]);
}
if (pd->amp_gpio > 0)
gpio_free(pd->amp_gpio);
}
#ifdef CONFIG_PM
static int simtec_audio_resume(struct device *dev)
{
simtec_call_startup(pdata);
return 0;
}
const struct dev_pm_ops simtec_audio_pmops = {
.resume = simtec_audio_resume,
};
EXPORT_SYMBOL_GPL(simtec_audio_pmops);
#endif
int __devinit simtec_audio_core_probe(struct platform_device *pdev,
struct snd_soc_card *card)
{
struct platform_device *snd_dev;
int ret;
card->dai_link->ops = &simtec_snd_ops;
pdata = pdev->dev.platform_data;
if (!pdata) {
dev_err(&pdev->dev, "no platform data supplied\n");
return -EINVAL;
}
simtec_call_startup(pdata);
xtal_clk = clk_get(&pdev->dev, "xtal");
if (IS_ERR(xtal_clk)) {
dev_err(&pdev->dev, "could not get clkout0\n");
return -EINVAL;
}
dev_info(&pdev->dev, "xtal rate is %ld\n", clk_get_rate(xtal_clk));
ret = attach_gpio_amp(&pdev->dev, pdata);
if (ret)
goto err_clk;
snd_dev = platform_device_alloc("soc-audio", -1);
if (!snd_dev) {
dev_err(&pdev->dev, "failed to alloc soc-audio devicec\n");
ret = -ENOMEM;
goto err_gpio;
}
platform_set_drvdata(snd_dev, card);
ret = platform_device_add(snd_dev);
if (ret) {
dev_err(&pdev->dev, "failed to add soc-audio dev\n");
goto err_pdev;
}
platform_set_drvdata(pdev, snd_dev);
return 0;
err_pdev:
platform_device_put(snd_dev);
err_gpio:
detach_gpio_amp(pdata);
err_clk:
clk_put(xtal_clk);
return ret;
}
EXPORT_SYMBOL_GPL(simtec_audio_core_probe);
int __devexit simtec_audio_remove(struct platform_device *pdev)
{
struct platform_device *snd_dev = platform_get_drvdata(pdev);
platform_device_unregister(snd_dev);
detach_gpio_amp(pdata);
clk_put(xtal_clk);
return 0;
}
EXPORT_SYMBOL_GPL(simtec_audio_remove);
MODULE_AUTHOR("Ben Dooks <ben@simtec.co.uk>");
MODULE_DESCRIPTION("ALSA SoC Simtec Audio common support");
MODULE_LICENSE("GPL");
| gpl-2.0 |
ztemt/NX507J_5.1_kernel | arch/mips/rb532/gpio.c | 4944 | 5370 | /*
* Miscellaneous functions for IDT EB434 board
*
* Copyright 2004 IDT Inc. (rischelp@idt.com)
* Copyright 2006 Phil Sutter <n0-1@freewrt.org>
* Copyright 2007 Florian Fainelli <florian@openwrt.org>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* THIS SOFTWARE IS PROVIDED ``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.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/export.h>
#include <linux/spinlock.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <asm/mach-rc32434/rb.h>
#include <asm/mach-rc32434/gpio.h>
struct rb532_gpio_chip {
struct gpio_chip chip;
void __iomem *regbase;
};
static struct resource rb532_gpio_reg0_res[] = {
{
.name = "gpio_reg0",
.start = REGBASE + GPIOBASE,
.end = REGBASE + GPIOBASE + sizeof(struct rb532_gpio_reg) - 1,
.flags = IORESOURCE_MEM,
}
};
/* rb532_set_bit - sanely set a bit
*
* bitval: new value for the bit
* offset: bit index in the 4 byte address range
* ioaddr: 4 byte aligned address being altered
*/
static inline void rb532_set_bit(unsigned bitval,
unsigned offset, void __iomem *ioaddr)
{
unsigned long flags;
u32 val;
local_irq_save(flags);
val = readl(ioaddr);
val &= ~(!bitval << offset); /* unset bit if bitval == 0 */
val |= (!!bitval << offset); /* set bit if bitval == 1 */
writel(val, ioaddr);
local_irq_restore(flags);
}
/* rb532_get_bit - read a bit
*
* returns the boolean state of the bit, which may be > 1
*/
static inline int rb532_get_bit(unsigned offset, void __iomem *ioaddr)
{
return (readl(ioaddr) & (1 << offset));
}
/*
* Return GPIO level */
static int rb532_gpio_get(struct gpio_chip *chip, unsigned offset)
{
struct rb532_gpio_chip *gpch;
gpch = container_of(chip, struct rb532_gpio_chip, chip);
return rb532_get_bit(offset, gpch->regbase + GPIOD);
}
/*
* Set output GPIO level
*/
static void rb532_gpio_set(struct gpio_chip *chip,
unsigned offset, int value)
{
struct rb532_gpio_chip *gpch;
gpch = container_of(chip, struct rb532_gpio_chip, chip);
rb532_set_bit(value, offset, gpch->regbase + GPIOD);
}
/*
* Set GPIO direction to input
*/
static int rb532_gpio_direction_input(struct gpio_chip *chip, unsigned offset)
{
struct rb532_gpio_chip *gpch;
gpch = container_of(chip, struct rb532_gpio_chip, chip);
/* disable alternate function in case it's set */
rb532_set_bit(0, offset, gpch->regbase + GPIOFUNC);
rb532_set_bit(0, offset, gpch->regbase + GPIOCFG);
return 0;
}
/*
* Set GPIO direction to output
*/
static int rb532_gpio_direction_output(struct gpio_chip *chip,
unsigned offset, int value)
{
struct rb532_gpio_chip *gpch;
gpch = container_of(chip, struct rb532_gpio_chip, chip);
/* disable alternate function in case it's set */
rb532_set_bit(0, offset, gpch->regbase + GPIOFUNC);
/* set the initial output value */
rb532_set_bit(value, offset, gpch->regbase + GPIOD);
rb532_set_bit(1, offset, gpch->regbase + GPIOCFG);
return 0;
}
static struct rb532_gpio_chip rb532_gpio_chip[] = {
[0] = {
.chip = {
.label = "gpio0",
.direction_input = rb532_gpio_direction_input,
.direction_output = rb532_gpio_direction_output,
.get = rb532_gpio_get,
.set = rb532_gpio_set,
.base = 0,
.ngpio = 32,
},
},
};
/*
* Set GPIO interrupt level
*/
void rb532_gpio_set_ilevel(int bit, unsigned gpio)
{
rb532_set_bit(bit, gpio, rb532_gpio_chip->regbase + GPIOILEVEL);
}
EXPORT_SYMBOL(rb532_gpio_set_ilevel);
/*
* Set GPIO interrupt status
*/
void rb532_gpio_set_istat(int bit, unsigned gpio)
{
rb532_set_bit(bit, gpio, rb532_gpio_chip->regbase + GPIOISTAT);
}
EXPORT_SYMBOL(rb532_gpio_set_istat);
/*
* Configure GPIO alternate function
*/
void rb532_gpio_set_func(unsigned gpio)
{
rb532_set_bit(1, gpio, rb532_gpio_chip->regbase + GPIOFUNC);
}
EXPORT_SYMBOL(rb532_gpio_set_func);
int __init rb532_gpio_init(void)
{
struct resource *r;
r = rb532_gpio_reg0_res;
rb532_gpio_chip->regbase = ioremap_nocache(r->start, resource_size(r));
if (!rb532_gpio_chip->regbase) {
printk(KERN_ERR "rb532: cannot remap GPIO register 0\n");
return -ENXIO;
}
/* Register our GPIO chip */
gpiochip_add(&rb532_gpio_chip->chip);
return 0;
}
arch_initcall(rb532_gpio_init);
| gpl-2.0 |
nimon/GPSense_1 | drivers/leds/leds-max8997.c | 4944 | 9237 | /*
* leds-max8997.c - LED class driver for MAX8997 LEDs.
*
* Copyright (C) 2011 Samsung Electronics
* Donggeun Kim <dg77.kim@samsung.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/module.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/workqueue.h>
#include <linux/leds.h>
#include <linux/mfd/max8997.h>
#include <linux/mfd/max8997-private.h>
#include <linux/platform_device.h>
#define MAX8997_LED_FLASH_SHIFT 3
#define MAX8997_LED_FLASH_CUR_MASK 0xf8
#define MAX8997_LED_MOVIE_SHIFT 4
#define MAX8997_LED_MOVIE_CUR_MASK 0xf0
#define MAX8997_LED_FLASH_MAX_BRIGHTNESS 0x1f
#define MAX8997_LED_MOVIE_MAX_BRIGHTNESS 0xf
#define MAX8997_LED_NONE_MAX_BRIGHTNESS 0
#define MAX8997_LED0_FLASH_MASK 0x1
#define MAX8997_LED0_FLASH_PIN_MASK 0x5
#define MAX8997_LED0_MOVIE_MASK 0x8
#define MAX8997_LED0_MOVIE_PIN_MASK 0x28
#define MAX8997_LED1_FLASH_MASK 0x2
#define MAX8997_LED1_FLASH_PIN_MASK 0x6
#define MAX8997_LED1_MOVIE_MASK 0x10
#define MAX8997_LED1_MOVIE_PIN_MASK 0x30
#define MAX8997_LED_BOOST_ENABLE_MASK (1 << 6)
struct max8997_led {
struct max8997_dev *iodev;
struct led_classdev cdev;
bool enabled;
int id;
enum max8997_led_mode led_mode;
struct mutex mutex;
};
static void max8997_led_clear_mode(struct max8997_led *led,
enum max8997_led_mode mode)
{
struct i2c_client *client = led->iodev->i2c;
u8 val = 0, mask = 0;
int ret;
switch (mode) {
case MAX8997_FLASH_MODE:
mask = led->id ?
MAX8997_LED1_FLASH_MASK : MAX8997_LED0_FLASH_MASK;
break;
case MAX8997_MOVIE_MODE:
mask = led->id ?
MAX8997_LED1_MOVIE_MASK : MAX8997_LED0_MOVIE_MASK;
break;
case MAX8997_FLASH_PIN_CONTROL_MODE:
mask = led->id ?
MAX8997_LED1_FLASH_PIN_MASK : MAX8997_LED0_FLASH_PIN_MASK;
break;
case MAX8997_MOVIE_PIN_CONTROL_MODE:
mask = led->id ?
MAX8997_LED1_MOVIE_PIN_MASK : MAX8997_LED0_MOVIE_PIN_MASK;
break;
default:
break;
}
if (mask) {
ret = max8997_update_reg(client,
MAX8997_REG_LEN_CNTL, val, mask);
if (ret)
dev_err(led->iodev->dev,
"failed to update register(%d)\n", ret);
}
}
static void max8997_led_set_mode(struct max8997_led *led,
enum max8997_led_mode mode)
{
int ret;
struct i2c_client *client = led->iodev->i2c;
u8 mask = 0;
/* First, clear the previous mode */
max8997_led_clear_mode(led, led->led_mode);
switch (mode) {
case MAX8997_FLASH_MODE:
mask = led->id ?
MAX8997_LED1_FLASH_MASK : MAX8997_LED0_FLASH_MASK;
led->cdev.max_brightness = MAX8997_LED_FLASH_MAX_BRIGHTNESS;
break;
case MAX8997_MOVIE_MODE:
mask = led->id ?
MAX8997_LED1_MOVIE_MASK : MAX8997_LED0_MOVIE_MASK;
led->cdev.max_brightness = MAX8997_LED_MOVIE_MAX_BRIGHTNESS;
break;
case MAX8997_FLASH_PIN_CONTROL_MODE:
mask = led->id ?
MAX8997_LED1_FLASH_PIN_MASK : MAX8997_LED0_FLASH_PIN_MASK;
led->cdev.max_brightness = MAX8997_LED_FLASH_MAX_BRIGHTNESS;
break;
case MAX8997_MOVIE_PIN_CONTROL_MODE:
mask = led->id ?
MAX8997_LED1_MOVIE_PIN_MASK : MAX8997_LED0_MOVIE_PIN_MASK;
led->cdev.max_brightness = MAX8997_LED_MOVIE_MAX_BRIGHTNESS;
break;
default:
led->cdev.max_brightness = MAX8997_LED_NONE_MAX_BRIGHTNESS;
break;
}
if (mask) {
ret = max8997_update_reg(client,
MAX8997_REG_LEN_CNTL, mask, mask);
if (ret)
dev_err(led->iodev->dev,
"failed to update register(%d)\n", ret);
}
led->led_mode = mode;
}
static void max8997_led_enable(struct max8997_led *led, bool enable)
{
int ret;
struct i2c_client *client = led->iodev->i2c;
u8 val = 0, mask = MAX8997_LED_BOOST_ENABLE_MASK;
if (led->enabled == enable)
return;
val = enable ? MAX8997_LED_BOOST_ENABLE_MASK : 0;
ret = max8997_update_reg(client, MAX8997_REG_BOOST_CNTL, val, mask);
if (ret)
dev_err(led->iodev->dev,
"failed to update register(%d)\n", ret);
led->enabled = enable;
}
static void max8997_led_set_current(struct max8997_led *led,
enum led_brightness value)
{
int ret;
struct i2c_client *client = led->iodev->i2c;
u8 val = 0, mask = 0, reg = 0;
switch (led->led_mode) {
case MAX8997_FLASH_MODE:
case MAX8997_FLASH_PIN_CONTROL_MODE:
val = value << MAX8997_LED_FLASH_SHIFT;
mask = MAX8997_LED_FLASH_CUR_MASK;
reg = led->id ? MAX8997_REG_FLASH2_CUR : MAX8997_REG_FLASH1_CUR;
break;
case MAX8997_MOVIE_MODE:
case MAX8997_MOVIE_PIN_CONTROL_MODE:
val = value << MAX8997_LED_MOVIE_SHIFT;
mask = MAX8997_LED_MOVIE_CUR_MASK;
reg = MAX8997_REG_MOVIE_CUR;
break;
default:
break;
}
if (mask) {
ret = max8997_update_reg(client, reg, val, mask);
if (ret)
dev_err(led->iodev->dev,
"failed to update register(%d)\n", ret);
}
}
static void max8997_led_brightness_set(struct led_classdev *led_cdev,
enum led_brightness value)
{
struct max8997_led *led =
container_of(led_cdev, struct max8997_led, cdev);
if (value) {
max8997_led_set_current(led, value);
max8997_led_enable(led, true);
} else {
max8997_led_set_current(led, value);
max8997_led_enable(led, false);
}
}
static ssize_t max8997_led_show_mode(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct led_classdev *led_cdev = dev_get_drvdata(dev);
struct max8997_led *led =
container_of(led_cdev, struct max8997_led, cdev);
ssize_t ret = 0;
mutex_lock(&led->mutex);
switch (led->led_mode) {
case MAX8997_FLASH_MODE:
ret += sprintf(buf, "FLASH\n");
break;
case MAX8997_MOVIE_MODE:
ret += sprintf(buf, "MOVIE\n");
break;
case MAX8997_FLASH_PIN_CONTROL_MODE:
ret += sprintf(buf, "FLASH_PIN_CONTROL\n");
break;
case MAX8997_MOVIE_PIN_CONTROL_MODE:
ret += sprintf(buf, "MOVIE_PIN_CONTROL\n");
break;
default:
ret += sprintf(buf, "NONE\n");
break;
}
mutex_unlock(&led->mutex);
return ret;
}
static ssize_t max8997_led_store_mode(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t size)
{
struct led_classdev *led_cdev = dev_get_drvdata(dev);
struct max8997_led *led =
container_of(led_cdev, struct max8997_led, cdev);
enum max8997_led_mode mode;
mutex_lock(&led->mutex);
if (!strncmp(buf, "FLASH_PIN_CONTROL", 17))
mode = MAX8997_FLASH_PIN_CONTROL_MODE;
else if (!strncmp(buf, "MOVIE_PIN_CONTROL", 17))
mode = MAX8997_MOVIE_PIN_CONTROL_MODE;
else if (!strncmp(buf, "FLASH", 5))
mode = MAX8997_FLASH_MODE;
else if (!strncmp(buf, "MOVIE", 5))
mode = MAX8997_MOVIE_MODE;
else
mode = MAX8997_NONE;
max8997_led_set_mode(led, mode);
mutex_unlock(&led->mutex);
return size;
}
static DEVICE_ATTR(mode, 0644, max8997_led_show_mode, max8997_led_store_mode);
static int __devinit max8997_led_probe(struct platform_device *pdev)
{
struct max8997_dev *iodev = dev_get_drvdata(pdev->dev.parent);
struct max8997_platform_data *pdata = dev_get_platdata(iodev->dev);
struct max8997_led *led;
char name[20];
int ret = 0;
if (pdata == NULL) {
dev_err(&pdev->dev, "no platform data\n");
return -ENODEV;
}
led = kzalloc(sizeof(*led), GFP_KERNEL);
if (led == NULL) {
ret = -ENOMEM;
goto err_mem;
}
led->id = pdev->id;
snprintf(name, sizeof(name), "max8997-led%d", pdev->id);
led->cdev.name = name;
led->cdev.brightness_set = max8997_led_brightness_set;
led->cdev.flags |= LED_CORE_SUSPENDRESUME;
led->cdev.brightness = 0;
led->iodev = iodev;
/* initialize mode and brightness according to platform_data */
if (pdata->led_pdata) {
u8 mode = 0, brightness = 0;
mode = pdata->led_pdata->mode[led->id];
brightness = pdata->led_pdata->brightness[led->id];
max8997_led_set_mode(led, pdata->led_pdata->mode[led->id]);
if (brightness > led->cdev.max_brightness)
brightness = led->cdev.max_brightness;
max8997_led_set_current(led, brightness);
led->cdev.brightness = brightness;
} else {
max8997_led_set_mode(led, MAX8997_NONE);
max8997_led_set_current(led, 0);
}
mutex_init(&led->mutex);
platform_set_drvdata(pdev, led);
ret = led_classdev_register(&pdev->dev, &led->cdev);
if (ret < 0)
goto err_led;
ret = device_create_file(led->cdev.dev, &dev_attr_mode);
if (ret != 0) {
dev_err(&pdev->dev,
"failed to create file: %d\n", ret);
goto err_file;
}
return 0;
err_file:
led_classdev_unregister(&led->cdev);
err_led:
kfree(led);
err_mem:
return ret;
}
static int __devexit max8997_led_remove(struct platform_device *pdev)
{
struct max8997_led *led = platform_get_drvdata(pdev);
device_remove_file(led->cdev.dev, &dev_attr_mode);
led_classdev_unregister(&led->cdev);
kfree(led);
return 0;
}
static struct platform_driver max8997_led_driver = {
.driver = {
.name = "max8997-led",
.owner = THIS_MODULE,
},
.probe = max8997_led_probe,
.remove = __devexit_p(max8997_led_remove),
};
static int __init max8997_led_init(void)
{
return platform_driver_register(&max8997_led_driver);
}
module_init(max8997_led_init);
static void __exit max8997_led_exit(void)
{
platform_driver_unregister(&max8997_led_driver);
}
module_exit(max8997_led_exit);
MODULE_AUTHOR("Donggeun Kim <dg77.kim@samsung.com>");
MODULE_DESCRIPTION("MAX8997 LED driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:max8997-led");
| gpl-2.0 |
tidatida/linux-stable-grsec | drivers/leds/leds-max8997.c | 4944 | 9237 | /*
* leds-max8997.c - LED class driver for MAX8997 LEDs.
*
* Copyright (C) 2011 Samsung Electronics
* Donggeun Kim <dg77.kim@samsung.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/module.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/workqueue.h>
#include <linux/leds.h>
#include <linux/mfd/max8997.h>
#include <linux/mfd/max8997-private.h>
#include <linux/platform_device.h>
#define MAX8997_LED_FLASH_SHIFT 3
#define MAX8997_LED_FLASH_CUR_MASK 0xf8
#define MAX8997_LED_MOVIE_SHIFT 4
#define MAX8997_LED_MOVIE_CUR_MASK 0xf0
#define MAX8997_LED_FLASH_MAX_BRIGHTNESS 0x1f
#define MAX8997_LED_MOVIE_MAX_BRIGHTNESS 0xf
#define MAX8997_LED_NONE_MAX_BRIGHTNESS 0
#define MAX8997_LED0_FLASH_MASK 0x1
#define MAX8997_LED0_FLASH_PIN_MASK 0x5
#define MAX8997_LED0_MOVIE_MASK 0x8
#define MAX8997_LED0_MOVIE_PIN_MASK 0x28
#define MAX8997_LED1_FLASH_MASK 0x2
#define MAX8997_LED1_FLASH_PIN_MASK 0x6
#define MAX8997_LED1_MOVIE_MASK 0x10
#define MAX8997_LED1_MOVIE_PIN_MASK 0x30
#define MAX8997_LED_BOOST_ENABLE_MASK (1 << 6)
struct max8997_led {
struct max8997_dev *iodev;
struct led_classdev cdev;
bool enabled;
int id;
enum max8997_led_mode led_mode;
struct mutex mutex;
};
static void max8997_led_clear_mode(struct max8997_led *led,
enum max8997_led_mode mode)
{
struct i2c_client *client = led->iodev->i2c;
u8 val = 0, mask = 0;
int ret;
switch (mode) {
case MAX8997_FLASH_MODE:
mask = led->id ?
MAX8997_LED1_FLASH_MASK : MAX8997_LED0_FLASH_MASK;
break;
case MAX8997_MOVIE_MODE:
mask = led->id ?
MAX8997_LED1_MOVIE_MASK : MAX8997_LED0_MOVIE_MASK;
break;
case MAX8997_FLASH_PIN_CONTROL_MODE:
mask = led->id ?
MAX8997_LED1_FLASH_PIN_MASK : MAX8997_LED0_FLASH_PIN_MASK;
break;
case MAX8997_MOVIE_PIN_CONTROL_MODE:
mask = led->id ?
MAX8997_LED1_MOVIE_PIN_MASK : MAX8997_LED0_MOVIE_PIN_MASK;
break;
default:
break;
}
if (mask) {
ret = max8997_update_reg(client,
MAX8997_REG_LEN_CNTL, val, mask);
if (ret)
dev_err(led->iodev->dev,
"failed to update register(%d)\n", ret);
}
}
static void max8997_led_set_mode(struct max8997_led *led,
enum max8997_led_mode mode)
{
int ret;
struct i2c_client *client = led->iodev->i2c;
u8 mask = 0;
/* First, clear the previous mode */
max8997_led_clear_mode(led, led->led_mode);
switch (mode) {
case MAX8997_FLASH_MODE:
mask = led->id ?
MAX8997_LED1_FLASH_MASK : MAX8997_LED0_FLASH_MASK;
led->cdev.max_brightness = MAX8997_LED_FLASH_MAX_BRIGHTNESS;
break;
case MAX8997_MOVIE_MODE:
mask = led->id ?
MAX8997_LED1_MOVIE_MASK : MAX8997_LED0_MOVIE_MASK;
led->cdev.max_brightness = MAX8997_LED_MOVIE_MAX_BRIGHTNESS;
break;
case MAX8997_FLASH_PIN_CONTROL_MODE:
mask = led->id ?
MAX8997_LED1_FLASH_PIN_MASK : MAX8997_LED0_FLASH_PIN_MASK;
led->cdev.max_brightness = MAX8997_LED_FLASH_MAX_BRIGHTNESS;
break;
case MAX8997_MOVIE_PIN_CONTROL_MODE:
mask = led->id ?
MAX8997_LED1_MOVIE_PIN_MASK : MAX8997_LED0_MOVIE_PIN_MASK;
led->cdev.max_brightness = MAX8997_LED_MOVIE_MAX_BRIGHTNESS;
break;
default:
led->cdev.max_brightness = MAX8997_LED_NONE_MAX_BRIGHTNESS;
break;
}
if (mask) {
ret = max8997_update_reg(client,
MAX8997_REG_LEN_CNTL, mask, mask);
if (ret)
dev_err(led->iodev->dev,
"failed to update register(%d)\n", ret);
}
led->led_mode = mode;
}
static void max8997_led_enable(struct max8997_led *led, bool enable)
{
int ret;
struct i2c_client *client = led->iodev->i2c;
u8 val = 0, mask = MAX8997_LED_BOOST_ENABLE_MASK;
if (led->enabled == enable)
return;
val = enable ? MAX8997_LED_BOOST_ENABLE_MASK : 0;
ret = max8997_update_reg(client, MAX8997_REG_BOOST_CNTL, val, mask);
if (ret)
dev_err(led->iodev->dev,
"failed to update register(%d)\n", ret);
led->enabled = enable;
}
static void max8997_led_set_current(struct max8997_led *led,
enum led_brightness value)
{
int ret;
struct i2c_client *client = led->iodev->i2c;
u8 val = 0, mask = 0, reg = 0;
switch (led->led_mode) {
case MAX8997_FLASH_MODE:
case MAX8997_FLASH_PIN_CONTROL_MODE:
val = value << MAX8997_LED_FLASH_SHIFT;
mask = MAX8997_LED_FLASH_CUR_MASK;
reg = led->id ? MAX8997_REG_FLASH2_CUR : MAX8997_REG_FLASH1_CUR;
break;
case MAX8997_MOVIE_MODE:
case MAX8997_MOVIE_PIN_CONTROL_MODE:
val = value << MAX8997_LED_MOVIE_SHIFT;
mask = MAX8997_LED_MOVIE_CUR_MASK;
reg = MAX8997_REG_MOVIE_CUR;
break;
default:
break;
}
if (mask) {
ret = max8997_update_reg(client, reg, val, mask);
if (ret)
dev_err(led->iodev->dev,
"failed to update register(%d)\n", ret);
}
}
static void max8997_led_brightness_set(struct led_classdev *led_cdev,
enum led_brightness value)
{
struct max8997_led *led =
container_of(led_cdev, struct max8997_led, cdev);
if (value) {
max8997_led_set_current(led, value);
max8997_led_enable(led, true);
} else {
max8997_led_set_current(led, value);
max8997_led_enable(led, false);
}
}
static ssize_t max8997_led_show_mode(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct led_classdev *led_cdev = dev_get_drvdata(dev);
struct max8997_led *led =
container_of(led_cdev, struct max8997_led, cdev);
ssize_t ret = 0;
mutex_lock(&led->mutex);
switch (led->led_mode) {
case MAX8997_FLASH_MODE:
ret += sprintf(buf, "FLASH\n");
break;
case MAX8997_MOVIE_MODE:
ret += sprintf(buf, "MOVIE\n");
break;
case MAX8997_FLASH_PIN_CONTROL_MODE:
ret += sprintf(buf, "FLASH_PIN_CONTROL\n");
break;
case MAX8997_MOVIE_PIN_CONTROL_MODE:
ret += sprintf(buf, "MOVIE_PIN_CONTROL\n");
break;
default:
ret += sprintf(buf, "NONE\n");
break;
}
mutex_unlock(&led->mutex);
return ret;
}
static ssize_t max8997_led_store_mode(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t size)
{
struct led_classdev *led_cdev = dev_get_drvdata(dev);
struct max8997_led *led =
container_of(led_cdev, struct max8997_led, cdev);
enum max8997_led_mode mode;
mutex_lock(&led->mutex);
if (!strncmp(buf, "FLASH_PIN_CONTROL", 17))
mode = MAX8997_FLASH_PIN_CONTROL_MODE;
else if (!strncmp(buf, "MOVIE_PIN_CONTROL", 17))
mode = MAX8997_MOVIE_PIN_CONTROL_MODE;
else if (!strncmp(buf, "FLASH", 5))
mode = MAX8997_FLASH_MODE;
else if (!strncmp(buf, "MOVIE", 5))
mode = MAX8997_MOVIE_MODE;
else
mode = MAX8997_NONE;
max8997_led_set_mode(led, mode);
mutex_unlock(&led->mutex);
return size;
}
static DEVICE_ATTR(mode, 0644, max8997_led_show_mode, max8997_led_store_mode);
static int __devinit max8997_led_probe(struct platform_device *pdev)
{
struct max8997_dev *iodev = dev_get_drvdata(pdev->dev.parent);
struct max8997_platform_data *pdata = dev_get_platdata(iodev->dev);
struct max8997_led *led;
char name[20];
int ret = 0;
if (pdata == NULL) {
dev_err(&pdev->dev, "no platform data\n");
return -ENODEV;
}
led = kzalloc(sizeof(*led), GFP_KERNEL);
if (led == NULL) {
ret = -ENOMEM;
goto err_mem;
}
led->id = pdev->id;
snprintf(name, sizeof(name), "max8997-led%d", pdev->id);
led->cdev.name = name;
led->cdev.brightness_set = max8997_led_brightness_set;
led->cdev.flags |= LED_CORE_SUSPENDRESUME;
led->cdev.brightness = 0;
led->iodev = iodev;
/* initialize mode and brightness according to platform_data */
if (pdata->led_pdata) {
u8 mode = 0, brightness = 0;
mode = pdata->led_pdata->mode[led->id];
brightness = pdata->led_pdata->brightness[led->id];
max8997_led_set_mode(led, pdata->led_pdata->mode[led->id]);
if (brightness > led->cdev.max_brightness)
brightness = led->cdev.max_brightness;
max8997_led_set_current(led, brightness);
led->cdev.brightness = brightness;
} else {
max8997_led_set_mode(led, MAX8997_NONE);
max8997_led_set_current(led, 0);
}
mutex_init(&led->mutex);
platform_set_drvdata(pdev, led);
ret = led_classdev_register(&pdev->dev, &led->cdev);
if (ret < 0)
goto err_led;
ret = device_create_file(led->cdev.dev, &dev_attr_mode);
if (ret != 0) {
dev_err(&pdev->dev,
"failed to create file: %d\n", ret);
goto err_file;
}
return 0;
err_file:
led_classdev_unregister(&led->cdev);
err_led:
kfree(led);
err_mem:
return ret;
}
static int __devexit max8997_led_remove(struct platform_device *pdev)
{
struct max8997_led *led = platform_get_drvdata(pdev);
device_remove_file(led->cdev.dev, &dev_attr_mode);
led_classdev_unregister(&led->cdev);
kfree(led);
return 0;
}
static struct platform_driver max8997_led_driver = {
.driver = {
.name = "max8997-led",
.owner = THIS_MODULE,
},
.probe = max8997_led_probe,
.remove = __devexit_p(max8997_led_remove),
};
static int __init max8997_led_init(void)
{
return platform_driver_register(&max8997_led_driver);
}
module_init(max8997_led_init);
static void __exit max8997_led_exit(void)
{
platform_driver_unregister(&max8997_led_driver);
}
module_exit(max8997_led_exit);
MODULE_AUTHOR("Donggeun Kim <dg77.kim@samsung.com>");
MODULE_DESCRIPTION("MAX8997 LED driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:max8997-led");
| gpl-2.0 |
chevanlol360/Android_Kernel_LGE_Fx1 | drivers/staging/comedi/drivers/ni_daq_700.c | 5456 | 13602 | /*
* comedi/drivers/ni_daq_700.c
* Driver for DAQCard-700 DIO only
* copied from 8255
*
* COMEDI - Linux Control and Measurement Device Interface
* Copyright (C) 1998 David A. Schleef <ds@schleef.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
/*
Driver: ni_daq_700
Description: National Instruments PCMCIA DAQCard-700 DIO only
Author: Fred Brooks <nsaspook@nsaspook.com>,
based on ni_daq_dio24 by Daniel Vecino Castel <dvecino@able.es>
Devices: [National Instruments] PCMCIA DAQ-Card-700 (ni_daq_700)
Status: works
Updated: Thu, 21 Feb 2008 12:07:20 +0000
The daqcard-700 appears in Comedi as a single digital I/O subdevice with
16 channels. The channel 0 corresponds to the daqcard-700's output
port, bit 0; channel 8 corresponds to the input port, bit 0.
Direction configuration: channels 0-7 output, 8-15 input (8225 device
emu as port A output, port B input, port C N/A).
IRQ is assigned but not used.
*/
#include <linux/interrupt.h>
#include <linux/slab.h>
#include "../comedidev.h"
#include <linux/ioport.h>
#include <pcmcia/cistpl.h>
#include <pcmcia/cisreg.h>
#include <pcmcia/ds.h>
static struct pcmcia_device *pcmcia_cur_dev;
#define DIO700_SIZE 8 /* size of io region used by board */
static int dio700_attach(struct comedi_device *dev,
struct comedi_devconfig *it);
static int dio700_detach(struct comedi_device *dev);
enum dio700_bustype { pcmcia_bustype };
struct dio700_board {
const char *name;
int device_id; /* device id for pcmcia board */
enum dio700_bustype bustype; /* PCMCIA */
int have_dio; /* have daqcard-700 dio */
/* function pointers so we can use inb/outb or readb/writeb */
/* as appropriate */
unsigned int (*read_byte) (unsigned int address);
void (*write_byte) (unsigned int byte, unsigned int address);
};
static const struct dio700_board dio700_boards[] = {
{
.name = "daqcard-700",
/* 0x10b is manufacturer id, 0x4743 is device id */
.device_id = 0x4743,
.bustype = pcmcia_bustype,
.have_dio = 1,
},
{
.name = "ni_daq_700",
/* 0x10b is manufacturer id, 0x4743 is device id */
.device_id = 0x4743,
.bustype = pcmcia_bustype,
.have_dio = 1,
},
};
/*
* Useful for shorthand access to the particular board structure
*/
#define thisboard ((const struct dio700_board *)dev->board_ptr)
struct dio700_private {
int data; /* number of data points left to be taken */
};
#define devpriv ((struct dio700_private *)dev->private)
static struct comedi_driver driver_dio700 = {
.driver_name = "ni_daq_700",
.module = THIS_MODULE,
.attach = dio700_attach,
.detach = dio700_detach,
.num_names = ARRAY_SIZE(dio700_boards),
.board_name = &dio700_boards[0].name,
.offset = sizeof(struct dio700_board),
};
/* the real driver routines */
#define _700_SIZE 8
#define _700_DATA 0
#define DIO_W 0x04
#define DIO_R 0x05
struct subdev_700_struct {
unsigned long cb_arg;
int (*cb_func) (int, int, int, unsigned long);
int have_irq;
};
#define CALLBACK_ARG (((struct subdev_700_struct *)s->private)->cb_arg)
#define CALLBACK_FUNC (((struct subdev_700_struct *)s->private)->cb_func)
#define subdevpriv ((struct subdev_700_struct *)s->private)
static void do_config(struct comedi_device *dev, struct comedi_subdevice *s);
void subdev_700_interrupt(struct comedi_device *dev, struct comedi_subdevice *s)
{
short d;
d = CALLBACK_FUNC(0, _700_DATA, 0, CALLBACK_ARG);
comedi_buf_put(s->async, d);
s->async->events |= COMEDI_CB_EOS;
comedi_event(dev, s);
}
EXPORT_SYMBOL(subdev_700_interrupt);
static int subdev_700_cb(int dir, int port, int data, unsigned long arg)
{
/* port is always A for output and B for input (8255 emu) */
unsigned long iobase = arg;
if (dir) {
outb(data, iobase + DIO_W);
return 0;
} else {
return inb(iobase + DIO_R);
}
}
static int subdev_700_insn(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_insn *insn,
unsigned int *data)
{
if (data[0]) {
s->state &= ~data[0];
s->state |= (data[0] & data[1]);
if (data[0] & 0xff)
CALLBACK_FUNC(1, _700_DATA, s->state & 0xff,
CALLBACK_ARG);
}
data[1] = s->state & 0xff;
data[1] |= CALLBACK_FUNC(0, _700_DATA, 0, CALLBACK_ARG) << 8;
return 2;
}
static int subdev_700_insn_config(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
switch (data[0]) {
case INSN_CONFIG_DIO_INPUT:
break;
case INSN_CONFIG_DIO_OUTPUT:
break;
case INSN_CONFIG_DIO_QUERY:
data[1] =
(s->
io_bits & (1 << CR_CHAN(insn->chanspec))) ? COMEDI_OUTPUT :
COMEDI_INPUT;
return insn->n;
break;
default:
return -EINVAL;
}
return 1;
}
static void do_config(struct comedi_device *dev, struct comedi_subdevice *s)
{ /* use powerup defaults */
return;
}
static int subdev_700_cmdtest(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_cmd *cmd)
{
int err = 0;
unsigned int tmp;
/* step 1 */
tmp = cmd->start_src;
cmd->start_src &= TRIG_NOW;
if (!cmd->start_src || tmp != cmd->start_src)
err++;
tmp = cmd->scan_begin_src;
cmd->scan_begin_src &= TRIG_EXT;
if (!cmd->scan_begin_src || tmp != cmd->scan_begin_src)
err++;
tmp = cmd->convert_src;
cmd->convert_src &= TRIG_FOLLOW;
if (!cmd->convert_src || tmp != cmd->convert_src)
err++;
tmp = cmd->scan_end_src;
cmd->scan_end_src &= TRIG_COUNT;
if (!cmd->scan_end_src || tmp != cmd->scan_end_src)
err++;
tmp = cmd->stop_src;
cmd->stop_src &= TRIG_NONE;
if (!cmd->stop_src || tmp != cmd->stop_src)
err++;
if (err)
return 1;
/* step 2 */
if (err)
return 2;
/* step 3 */
if (cmd->start_arg != 0) {
cmd->start_arg = 0;
err++;
}
if (cmd->scan_begin_arg != 0) {
cmd->scan_begin_arg = 0;
err++;
}
if (cmd->convert_arg != 0) {
cmd->convert_arg = 0;
err++;
}
if (cmd->scan_end_arg != 1) {
cmd->scan_end_arg = 1;
err++;
}
if (cmd->stop_arg != 0) {
cmd->stop_arg = 0;
err++;
}
if (err)
return 3;
/* step 4 */
if (err)
return 4;
return 0;
}
static int subdev_700_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
{
/* FIXME */
return 0;
}
static int subdev_700_cancel(struct comedi_device *dev,
struct comedi_subdevice *s)
{
/* FIXME */
return 0;
}
int subdev_700_init(struct comedi_device *dev, struct comedi_subdevice *s,
int (*cb) (int, int, int, unsigned long), unsigned long arg)
{
s->type = COMEDI_SUBD_DIO;
s->subdev_flags = SDF_READABLE | SDF_WRITABLE;
s->n_chan = 16;
s->range_table = &range_digital;
s->maxdata = 1;
s->private = kmalloc(sizeof(struct subdev_700_struct), GFP_KERNEL);
if (!s->private)
return -ENOMEM;
CALLBACK_ARG = arg;
if (cb == NULL)
CALLBACK_FUNC = subdev_700_cb;
else
CALLBACK_FUNC = cb;
s->insn_bits = subdev_700_insn;
s->insn_config = subdev_700_insn_config;
s->state = 0;
s->io_bits = 0x00ff;
do_config(dev, s);
return 0;
}
EXPORT_SYMBOL(subdev_700_init);
int subdev_700_init_irq(struct comedi_device *dev, struct comedi_subdevice *s,
int (*cb) (int, int, int, unsigned long),
unsigned long arg)
{
int ret;
ret = subdev_700_init(dev, s, cb, arg);
if (ret < 0)
return ret;
s->do_cmdtest = subdev_700_cmdtest;
s->do_cmd = subdev_700_cmd;
s->cancel = subdev_700_cancel;
subdevpriv->have_irq = 1;
return 0;
}
EXPORT_SYMBOL(subdev_700_init_irq);
void subdev_700_cleanup(struct comedi_device *dev, struct comedi_subdevice *s)
{
if (s->private)
if (subdevpriv->have_irq)
kfree(s->private);
}
EXPORT_SYMBOL(subdev_700_cleanup);
static int dio700_attach(struct comedi_device *dev, struct comedi_devconfig *it)
{
struct comedi_subdevice *s;
unsigned long iobase = 0;
#ifdef incomplete
unsigned int irq = 0;
#endif
struct pcmcia_device *link;
/* allocate and initialize dev->private */
if (alloc_private(dev, sizeof(struct dio700_private)) < 0)
return -ENOMEM;
/* get base address, irq etc. based on bustype */
switch (thisboard->bustype) {
case pcmcia_bustype:
link = pcmcia_cur_dev; /* XXX hack */
if (!link)
return -EIO;
iobase = link->resource[0]->start;
#ifdef incomplete
irq = link->irq;
#endif
break;
default:
printk(KERN_ERR "bug! couldn't determine board type\n");
return -EINVAL;
break;
}
printk(KERN_ERR "comedi%d: ni_daq_700: %s, io 0x%lx", dev->minor,
thisboard->name, iobase);
#ifdef incomplete
if (irq)
printk(", irq %u", irq);
#endif
printk("\n");
if (iobase == 0) {
printk(KERN_ERR "io base address is zero!\n");
return -EINVAL;
}
dev->iobase = iobase;
#ifdef incomplete
/* grab our IRQ */
dev->irq = irq;
#endif
dev->board_name = thisboard->name;
if (alloc_subdevices(dev, 1) < 0)
return -ENOMEM;
/* DAQCard-700 dio */
s = dev->subdevices + 0;
subdev_700_init(dev, s, NULL, dev->iobase);
return 0;
};
static int dio700_detach(struct comedi_device *dev)
{
printk(KERN_ERR "comedi%d: ni_daq_700: cs-remove\n", dev->minor);
if (dev->subdevices)
subdev_700_cleanup(dev, dev->subdevices + 0);
if (thisboard->bustype != pcmcia_bustype && dev->iobase)
release_region(dev->iobase, DIO700_SIZE);
if (dev->irq)
free_irq(dev->irq, dev);
return 0;
};
static void dio700_config(struct pcmcia_device *link);
static void dio700_release(struct pcmcia_device *link);
static int dio700_cs_suspend(struct pcmcia_device *p_dev);
static int dio700_cs_resume(struct pcmcia_device *p_dev);
static int dio700_cs_attach(struct pcmcia_device *);
static void dio700_cs_detach(struct pcmcia_device *);
struct local_info_t {
struct pcmcia_device *link;
int stop;
struct bus_operations *bus;
};
static int dio700_cs_attach(struct pcmcia_device *link)
{
struct local_info_t *local;
printk(KERN_INFO "ni_daq_700: cs-attach\n");
dev_dbg(&link->dev, "dio700_cs_attach()\n");
/* Allocate space for private device-specific data */
local = kzalloc(sizeof(struct local_info_t), GFP_KERNEL);
if (!local)
return -ENOMEM;
local->link = link;
link->priv = local;
pcmcia_cur_dev = link;
dio700_config(link);
return 0;
} /* dio700_cs_attach */
static void dio700_cs_detach(struct pcmcia_device *link)
{
printk(KERN_INFO "ni_daq_700: cs-detach!\n");
dev_dbg(&link->dev, "dio700_cs_detach\n");
((struct local_info_t *)link->priv)->stop = 1;
dio700_release(link);
/* This points to the parent struct local_info_t struct */
kfree(link->priv);
} /* dio700_cs_detach */
static int dio700_pcmcia_config_loop(struct pcmcia_device *p_dev,
void *priv_data)
{
if (p_dev->config_index == 0)
return -EINVAL;
return pcmcia_request_io(p_dev);
}
static void dio700_config(struct pcmcia_device *link)
{
int ret;
printk(KERN_INFO "ni_daq_700: cs-config\n");
dev_dbg(&link->dev, "dio700_config\n");
link->config_flags |= CONF_ENABLE_IRQ | CONF_AUTO_AUDIO |
CONF_AUTO_SET_IO;
ret = pcmcia_loop_config(link, dio700_pcmcia_config_loop, NULL);
if (ret) {
dev_warn(&link->dev, "no configuration found\n");
goto failed;
}
if (!link->irq)
goto failed;
ret = pcmcia_enable_device(link);
if (ret != 0)
goto failed;
return;
failed:
printk(KERN_INFO "ni_daq_700 cs failed");
dio700_release(link);
} /* dio700_config */
static void dio700_release(struct pcmcia_device *link)
{
dev_dbg(&link->dev, "dio700_release\n");
pcmcia_disable_device(link);
} /* dio700_release */
static int dio700_cs_suspend(struct pcmcia_device *link)
{
struct local_info_t *local = link->priv;
/* Mark the device as stopped, to block IO until later */
local->stop = 1;
return 0;
} /* dio700_cs_suspend */
static int dio700_cs_resume(struct pcmcia_device *link)
{
struct local_info_t *local = link->priv;
local->stop = 0;
return 0;
} /* dio700_cs_resume */
/*====================================================================*/
static const struct pcmcia_device_id dio700_cs_ids[] = {
/* N.B. These IDs should match those in dio700_boards */
PCMCIA_DEVICE_MANF_CARD(0x010b, 0x4743), /* daqcard-700 */
PCMCIA_DEVICE_NULL
};
MODULE_DEVICE_TABLE(pcmcia, dio700_cs_ids);
MODULE_AUTHOR("Fred Brooks <nsaspook@nsaspook.com>");
MODULE_DESCRIPTION("Comedi driver for National Instruments "
"PCMCIA DAQCard-700 DIO");
MODULE_LICENSE("GPL");
struct pcmcia_driver dio700_cs_driver = {
.probe = dio700_cs_attach,
.remove = dio700_cs_detach,
.suspend = dio700_cs_suspend,
.resume = dio700_cs_resume,
.id_table = dio700_cs_ids,
.owner = THIS_MODULE,
.name = "ni_daq_700",
};
static int __init init_dio700_cs(void)
{
pcmcia_register_driver(&dio700_cs_driver);
return 0;
}
static void __exit exit_dio700_cs(void)
{
pr_debug("ni_daq_700: unloading\n");
pcmcia_unregister_driver(&dio700_cs_driver);
}
int __init init_module(void)
{
int ret;
ret = init_dio700_cs();
if (ret < 0)
return ret;
return comedi_driver_register(&driver_dio700);
}
void __exit cleanup_module(void)
{
exit_dio700_cs();
comedi_driver_unregister(&driver_dio700);
}
| gpl-2.0 |
jxxhwy/NewWorld_f160_JB_kernel | arch/sh/boards/mach-se/7206/setup.c | 7504 | 2043 | /*
*
* linux/arch/sh/boards/se/7206/setup.c
*
* Copyright (C) 2006 Yoshinori Sato
* Copyright (C) 2007 - 2008 Paul Mundt
*
* Hitachi 7206 SolutionEngine Support.
*/
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/smc91x.h>
#include <mach-se/mach/se7206.h>
#include <asm/io.h>
#include <asm/machvec.h>
#include <asm/heartbeat.h>
static struct resource smc91x_resources[] = {
[0] = {
.name = "smc91x-regs",
.start = PA_SMSC + 0x300,
.end = PA_SMSC + 0x300 + 0x020 - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 64,
.end = 64,
.flags = IORESOURCE_IRQ,
},
};
static struct smc91x_platdata smc91x_info = {
.flags = SMC91X_USE_16BIT,
};
static struct platform_device smc91x_device = {
.name = "smc91x",
.id = -1,
.dev = {
.dma_mask = NULL,
.coherent_dma_mask = 0xffffffff,
.platform_data = &smc91x_info,
},
.num_resources = ARRAY_SIZE(smc91x_resources),
.resource = smc91x_resources,
};
static unsigned char heartbeat_bit_pos[] = { 8, 9, 10, 11, 12, 13, 14, 15 };
static struct heartbeat_data heartbeat_data = {
.bit_pos = heartbeat_bit_pos,
.nr_bits = ARRAY_SIZE(heartbeat_bit_pos),
};
static struct resource heartbeat_resource = {
.start = PA_LED,
.end = PA_LED,
.flags = IORESOURCE_MEM | IORESOURCE_MEM_32BIT,
};
static struct platform_device heartbeat_device = {
.name = "heartbeat",
.id = -1,
.dev = {
.platform_data = &heartbeat_data,
},
.num_resources = 1,
.resource = &heartbeat_resource,
};
static struct platform_device *se7206_devices[] __initdata = {
&smc91x_device,
&heartbeat_device,
};
static int __init se7206_devices_setup(void)
{
return platform_add_devices(se7206_devices, ARRAY_SIZE(se7206_devices));
}
device_initcall(se7206_devices_setup);
static int se7206_mode_pins(void)
{
return MODE_PIN1 | MODE_PIN2;
}
/*
* The Machine Vector
*/
static struct sh_machine_vector mv_se __initmv = {
.mv_name = "SolutionEngine",
.mv_nr_irqs = 256,
.mv_init_irq = init_se7206_IRQ,
.mv_mode_pins = se7206_mode_pins,
};
| gpl-2.0 |
derekhe-hardware/huawei-g330d-u8825d-kernel | arch/sh/boards/mach-sh03/setup.c | 7504 | 2444 | /*
* linux/arch/sh/boards/sh03/setup.c
*
* Copyright (C) 2004 Interface Co.,Ltd. Saito.K
*
*/
#include <linux/init.h>
#include <linux/irq.h>
#include <linux/pci.h>
#include <linux/platform_device.h>
#include <linux/ata_platform.h>
#include <asm/io.h>
#include <asm/rtc.h>
#include <mach-sh03/mach/io.h>
#include <mach-sh03/mach/sh03.h>
#include <asm/addrspace.h>
static void __init init_sh03_IRQ(void)
{
plat_irq_setup_pins(IRQ_MODE_IRQ);
}
/* arch/sh/boards/sh03/rtc.c */
void sh03_time_init(void);
static void __init sh03_setup(char **cmdline_p)
{
board_time_init = sh03_time_init;
}
static struct resource cf_ide_resources[] = {
[0] = {
.start = 0x1f0,
.end = 0x1f0 + 8,
.flags = IORESOURCE_IO,
},
[1] = {
.start = 0x1f0 + 0x206,
.end = 0x1f0 +8 + 0x206 + 8,
.flags = IORESOURCE_IO,
},
[2] = {
.start = IRL2_IRQ,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device cf_ide_device = {
.name = "pata_platform",
.id = -1,
.num_resources = ARRAY_SIZE(cf_ide_resources),
.resource = cf_ide_resources,
};
static struct resource heartbeat_resources[] = {
[0] = {
.start = 0xa0800000,
.end = 0xa0800000,
.flags = IORESOURCE_MEM,
},
};
static struct platform_device heartbeat_device = {
.name = "heartbeat",
.id = -1,
.num_resources = ARRAY_SIZE(heartbeat_resources),
.resource = heartbeat_resources,
};
static struct platform_device *sh03_devices[] __initdata = {
&heartbeat_device,
&cf_ide_device,
};
static int __init sh03_devices_setup(void)
{
pgprot_t prot;
unsigned long paddrbase;
void *cf_ide_base;
/* open I/O area window */
paddrbase = virt_to_phys((void *)PA_AREA5_IO);
prot = PAGE_KERNEL_PCC(1, _PAGE_PCC_IO16);
cf_ide_base = ioremap_prot(paddrbase, PAGE_SIZE, pgprot_val(prot));
if (!cf_ide_base) {
printk("allocate_cf_area : can't open CF I/O window!\n");
return -ENOMEM;
}
/* IDE cmd address : 0x1f0-0x1f7 and 0x3f6 */
cf_ide_resources[0].start += (unsigned long)cf_ide_base;
cf_ide_resources[0].end += (unsigned long)cf_ide_base;
cf_ide_resources[1].start += (unsigned long)cf_ide_base;
cf_ide_resources[1].end += (unsigned long)cf_ide_base;
return platform_add_devices(sh03_devices, ARRAY_SIZE(sh03_devices));
}
device_initcall(sh03_devices_setup);
static struct sh_machine_vector mv_sh03 __initmv = {
.mv_name = "Interface (CTP/PCI-SH03)",
.mv_setup = sh03_setup,
.mv_nr_irqs = 48,
.mv_init_irq = init_sh03_IRQ,
};
| gpl-2.0 |
agat63/AGAT_L720_kernel | arch/mips/pnx833x/common/prom.c | 8784 | 1588 | /*
* prom.c:
*
* Copyright 2008 NXP Semiconductors
* Chris Steel <chris.steel@nxp.com>
* Daniel Laird <daniel.j.laird@nxp.com>
*
* Based on software written by:
* Nikita Youshchenko <yoush@debian.org>, based on PNX8550 code.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/init.h>
#include <asm/bootinfo.h>
#include <linux/string.h>
void __init prom_init_cmdline(void)
{
int argc = fw_arg0;
char **argv = (char **)fw_arg1;
char *c = &(arcs_cmdline[0]);
int i;
for (i = 1; i < argc; i++) {
strcpy(c, argv[i]);
c += strlen(argv[i]);
if (i < argc-1)
*c++ = ' ';
}
*c = 0;
}
char __init *prom_getenv(char *envname)
{
extern char **prom_envp;
char **env = prom_envp;
int i;
i = strlen(envname);
while (*env) {
if (strncmp(envname, *env, i) == 0 && *(*env+i) == '=')
return *env + i + 1;
env++;
}
return 0;
}
void __init prom_free_prom_memory(void)
{
}
| gpl-2.0 |
mkborg/linux-olimex-som | drivers/infiniband/hw/qib/qib_file_ops.c | 337 | 62473 | /*
* Copyright (c) 2012, 2013 Intel Corporation. All rights reserved.
* Copyright (c) 2006 - 2012 QLogic Corporation. All rights reserved.
* Copyright (c) 2003, 2004, 2005, 2006 PathScale, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - 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.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/pci.h>
#include <linux/poll.h>
#include <linux/cdev.h>
#include <linux/swap.h>
#include <linux/vmalloc.h>
#include <linux/highmem.h>
#include <linux/io.h>
#include <linux/jiffies.h>
#include <asm/pgtable.h>
#include <linux/delay.h>
#include <linux/export.h>
#include <linux/uio.h>
#include "qib.h"
#include "qib_common.h"
#include "qib_user_sdma.h"
#undef pr_fmt
#define pr_fmt(fmt) QIB_DRV_NAME ": " fmt
static int qib_open(struct inode *, struct file *);
static int qib_close(struct inode *, struct file *);
static ssize_t qib_write(struct file *, const char __user *, size_t, loff_t *);
static ssize_t qib_write_iter(struct kiocb *, struct iov_iter *);
static unsigned int qib_poll(struct file *, struct poll_table_struct *);
static int qib_mmapf(struct file *, struct vm_area_struct *);
/*
* This is really, really weird shit - write() and writev() here
* have completely unrelated semantics. Sucky userland ABI,
* film at 11.
*/
static const struct file_operations qib_file_ops = {
.owner = THIS_MODULE,
.write = qib_write,
.write_iter = qib_write_iter,
.open = qib_open,
.release = qib_close,
.poll = qib_poll,
.mmap = qib_mmapf,
.llseek = noop_llseek,
};
/*
* Convert kernel virtual addresses to physical addresses so they don't
* potentially conflict with the chip addresses used as mmap offsets.
* It doesn't really matter what mmap offset we use as long as we can
* interpret it correctly.
*/
static u64 cvt_kvaddr(void *p)
{
struct page *page;
u64 paddr = 0;
page = vmalloc_to_page(p);
if (page)
paddr = page_to_pfn(page) << PAGE_SHIFT;
return paddr;
}
static int qib_get_base_info(struct file *fp, void __user *ubase,
size_t ubase_size)
{
struct qib_ctxtdata *rcd = ctxt_fp(fp);
int ret = 0;
struct qib_base_info *kinfo = NULL;
struct qib_devdata *dd = rcd->dd;
struct qib_pportdata *ppd = rcd->ppd;
unsigned subctxt_cnt;
int shared, master;
size_t sz;
subctxt_cnt = rcd->subctxt_cnt;
if (!subctxt_cnt) {
shared = 0;
master = 0;
subctxt_cnt = 1;
} else {
shared = 1;
master = !subctxt_fp(fp);
}
sz = sizeof(*kinfo);
/* If context sharing is not requested, allow the old size structure */
if (!shared)
sz -= 7 * sizeof(u64);
if (ubase_size < sz) {
ret = -EINVAL;
goto bail;
}
kinfo = kzalloc(sizeof(*kinfo), GFP_KERNEL);
if (kinfo == NULL) {
ret = -ENOMEM;
goto bail;
}
ret = dd->f_get_base_info(rcd, kinfo);
if (ret < 0)
goto bail;
kinfo->spi_rcvhdr_cnt = dd->rcvhdrcnt;
kinfo->spi_rcvhdrent_size = dd->rcvhdrentsize;
kinfo->spi_tidegrcnt = rcd->rcvegrcnt;
kinfo->spi_rcv_egrbufsize = dd->rcvegrbufsize;
/*
* have to mmap whole thing
*/
kinfo->spi_rcv_egrbuftotlen =
rcd->rcvegrbuf_chunks * rcd->rcvegrbuf_size;
kinfo->spi_rcv_egrperchunk = rcd->rcvegrbufs_perchunk;
kinfo->spi_rcv_egrchunksize = kinfo->spi_rcv_egrbuftotlen /
rcd->rcvegrbuf_chunks;
kinfo->spi_tidcnt = dd->rcvtidcnt / subctxt_cnt;
if (master)
kinfo->spi_tidcnt += dd->rcvtidcnt % subctxt_cnt;
/*
* for this use, may be cfgctxts summed over all chips that
* are are configured and present
*/
kinfo->spi_nctxts = dd->cfgctxts;
/* unit (chip/board) our context is on */
kinfo->spi_unit = dd->unit;
kinfo->spi_port = ppd->port;
/* for now, only a single page */
kinfo->spi_tid_maxsize = PAGE_SIZE;
/*
* Doing this per context, and based on the skip value, etc. This has
* to be the actual buffer size, since the protocol code treats it
* as an array.
*
* These have to be set to user addresses in the user code via mmap.
* These values are used on return to user code for the mmap target
* addresses only. For 32 bit, same 44 bit address problem, so use
* the physical address, not virtual. Before 2.6.11, using the
* page_address() macro worked, but in 2.6.11, even that returns the
* full 64 bit address (upper bits all 1's). So far, using the
* physical addresses (or chip offsets, for chip mapping) works, but
* no doubt some future kernel release will change that, and we'll be
* on to yet another method of dealing with this.
* Normally only one of rcvhdr_tailaddr or rhf_offset is useful
* since the chips with non-zero rhf_offset don't normally
* enable tail register updates to host memory, but for testing,
* both can be enabled and used.
*/
kinfo->spi_rcvhdr_base = (u64) rcd->rcvhdrq_phys;
kinfo->spi_rcvhdr_tailaddr = (u64) rcd->rcvhdrqtailaddr_phys;
kinfo->spi_rhf_offset = dd->rhf_offset;
kinfo->spi_rcv_egrbufs = (u64) rcd->rcvegr_phys;
kinfo->spi_pioavailaddr = (u64) dd->pioavailregs_phys;
/* setup per-unit (not port) status area for user programs */
kinfo->spi_status = (u64) kinfo->spi_pioavailaddr +
(char *) ppd->statusp -
(char *) dd->pioavailregs_dma;
kinfo->spi_uregbase = (u64) dd->uregbase + dd->ureg_align * rcd->ctxt;
if (!shared) {
kinfo->spi_piocnt = rcd->piocnt;
kinfo->spi_piobufbase = (u64) rcd->piobufs;
kinfo->spi_sendbuf_status = cvt_kvaddr(rcd->user_event_mask);
} else if (master) {
kinfo->spi_piocnt = (rcd->piocnt / subctxt_cnt) +
(rcd->piocnt % subctxt_cnt);
/* Master's PIO buffers are after all the slave's */
kinfo->spi_piobufbase = (u64) rcd->piobufs +
dd->palign *
(rcd->piocnt - kinfo->spi_piocnt);
} else {
unsigned slave = subctxt_fp(fp) - 1;
kinfo->spi_piocnt = rcd->piocnt / subctxt_cnt;
kinfo->spi_piobufbase = (u64) rcd->piobufs +
dd->palign * kinfo->spi_piocnt * slave;
}
if (shared) {
kinfo->spi_sendbuf_status =
cvt_kvaddr(&rcd->user_event_mask[subctxt_fp(fp)]);
/* only spi_subctxt_* fields should be set in this block! */
kinfo->spi_subctxt_uregbase = cvt_kvaddr(rcd->subctxt_uregbase);
kinfo->spi_subctxt_rcvegrbuf =
cvt_kvaddr(rcd->subctxt_rcvegrbuf);
kinfo->spi_subctxt_rcvhdr_base =
cvt_kvaddr(rcd->subctxt_rcvhdr_base);
}
/*
* All user buffers are 2KB buffers. If we ever support
* giving 4KB buffers to user processes, this will need some
* work. Can't use piobufbase directly, because it has
* both 2K and 4K buffer base values.
*/
kinfo->spi_pioindex = (kinfo->spi_piobufbase - dd->pio2k_bufbase) /
dd->palign;
kinfo->spi_pioalign = dd->palign;
kinfo->spi_qpair = QIB_KD_QP;
/*
* user mode PIO buffers are always 2KB, even when 4KB can
* be received, and sent via the kernel; this is ibmaxlen
* for 2K MTU.
*/
kinfo->spi_piosize = dd->piosize2k - 2 * sizeof(u32);
kinfo->spi_mtu = ppd->ibmaxlen; /* maxlen, not ibmtu */
kinfo->spi_ctxt = rcd->ctxt;
kinfo->spi_subctxt = subctxt_fp(fp);
kinfo->spi_sw_version = QIB_KERN_SWVERSION;
kinfo->spi_sw_version |= 1U << 31; /* QLogic-built, not kernel.org */
kinfo->spi_hw_version = dd->revision;
if (master)
kinfo->spi_runtime_flags |= QIB_RUNTIME_MASTER;
sz = (ubase_size < sizeof(*kinfo)) ? ubase_size : sizeof(*kinfo);
if (copy_to_user(ubase, kinfo, sz))
ret = -EFAULT;
bail:
kfree(kinfo);
return ret;
}
/**
* qib_tid_update - update a context TID
* @rcd: the context
* @fp: the qib device file
* @ti: the TID information
*
* The new implementation as of Oct 2004 is that the driver assigns
* the tid and returns it to the caller. To reduce search time, we
* keep a cursor for each context, walking the shadow tid array to find
* one that's not in use.
*
* For now, if we can't allocate the full list, we fail, although
* in the long run, we'll allocate as many as we can, and the
* caller will deal with that by trying the remaining pages later.
* That means that when we fail, we have to mark the tids as not in
* use again, in our shadow copy.
*
* It's up to the caller to free the tids when they are done.
* We'll unlock the pages as they free them.
*
* Also, right now we are locking one page at a time, but since
* the intended use of this routine is for a single group of
* virtually contiguous pages, that should change to improve
* performance.
*/
static int qib_tid_update(struct qib_ctxtdata *rcd, struct file *fp,
const struct qib_tid_info *ti)
{
int ret = 0, ntids;
u32 tid, ctxttid, cnt, i, tidcnt, tidoff;
u16 *tidlist;
struct qib_devdata *dd = rcd->dd;
u64 physaddr;
unsigned long vaddr;
u64 __iomem *tidbase;
unsigned long tidmap[8];
struct page **pagep = NULL;
unsigned subctxt = subctxt_fp(fp);
if (!dd->pageshadow) {
ret = -ENOMEM;
goto done;
}
cnt = ti->tidcnt;
if (!cnt) {
ret = -EFAULT;
goto done;
}
ctxttid = rcd->ctxt * dd->rcvtidcnt;
if (!rcd->subctxt_cnt) {
tidcnt = dd->rcvtidcnt;
tid = rcd->tidcursor;
tidoff = 0;
} else if (!subctxt) {
tidcnt = (dd->rcvtidcnt / rcd->subctxt_cnt) +
(dd->rcvtidcnt % rcd->subctxt_cnt);
tidoff = dd->rcvtidcnt - tidcnt;
ctxttid += tidoff;
tid = tidcursor_fp(fp);
} else {
tidcnt = dd->rcvtidcnt / rcd->subctxt_cnt;
tidoff = tidcnt * (subctxt - 1);
ctxttid += tidoff;
tid = tidcursor_fp(fp);
}
if (cnt > tidcnt) {
/* make sure it all fits in tid_pg_list */
qib_devinfo(dd->pcidev,
"Process tried to allocate %u TIDs, only trying max (%u)\n",
cnt, tidcnt);
cnt = tidcnt;
}
pagep = (struct page **) rcd->tid_pg_list;
tidlist = (u16 *) &pagep[dd->rcvtidcnt];
pagep += tidoff;
tidlist += tidoff;
memset(tidmap, 0, sizeof(tidmap));
/* before decrement; chip actual # */
ntids = tidcnt;
tidbase = (u64 __iomem *) (((char __iomem *) dd->kregbase) +
dd->rcvtidbase +
ctxttid * sizeof(*tidbase));
/* virtual address of first page in transfer */
vaddr = ti->tidvaddr;
if (!access_ok(VERIFY_WRITE, (void __user *) vaddr,
cnt * PAGE_SIZE)) {
ret = -EFAULT;
goto done;
}
ret = qib_get_user_pages(vaddr, cnt, pagep);
if (ret) {
/*
* if (ret == -EBUSY)
* We can't continue because the pagep array won't be
* initialized. This should never happen,
* unless perhaps the user has mpin'ed the pages
* themselves.
*/
qib_devinfo(
dd->pcidev,
"Failed to lock addr %p, %u pages: errno %d\n",
(void *) vaddr, cnt, -ret);
goto done;
}
for (i = 0; i < cnt; i++, vaddr += PAGE_SIZE) {
for (; ntids--; tid++) {
if (tid == tidcnt)
tid = 0;
if (!dd->pageshadow[ctxttid + tid])
break;
}
if (ntids < 0) {
/*
* Oops, wrapped all the way through their TIDs,
* and didn't have enough free; see comments at
* start of routine
*/
i--; /* last tidlist[i] not filled in */
ret = -ENOMEM;
break;
}
tidlist[i] = tid + tidoff;
/* we "know" system pages and TID pages are same size */
dd->pageshadow[ctxttid + tid] = pagep[i];
dd->physshadow[ctxttid + tid] =
qib_map_page(dd->pcidev, pagep[i], 0, PAGE_SIZE,
PCI_DMA_FROMDEVICE);
/*
* don't need atomic or it's overhead
*/
__set_bit(tid, tidmap);
physaddr = dd->physshadow[ctxttid + tid];
/* PERFORMANCE: below should almost certainly be cached */
dd->f_put_tid(dd, &tidbase[tid],
RCVHQ_RCV_TYPE_EXPECTED, physaddr);
/*
* don't check this tid in qib_ctxtshadow, since we
* just filled it in; start with the next one.
*/
tid++;
}
if (ret) {
u32 limit;
cleanup:
/* jump here if copy out of updated info failed... */
/* same code that's in qib_free_tid() */
limit = sizeof(tidmap) * BITS_PER_BYTE;
if (limit > tidcnt)
/* just in case size changes in future */
limit = tidcnt;
tid = find_first_bit((const unsigned long *)tidmap, limit);
for (; tid < limit; tid++) {
if (!test_bit(tid, tidmap))
continue;
if (dd->pageshadow[ctxttid + tid]) {
dma_addr_t phys;
phys = dd->physshadow[ctxttid + tid];
dd->physshadow[ctxttid + tid] = dd->tidinvalid;
/* PERFORMANCE: below should almost certainly
* be cached
*/
dd->f_put_tid(dd, &tidbase[tid],
RCVHQ_RCV_TYPE_EXPECTED,
dd->tidinvalid);
pci_unmap_page(dd->pcidev, phys, PAGE_SIZE,
PCI_DMA_FROMDEVICE);
dd->pageshadow[ctxttid + tid] = NULL;
}
}
qib_release_user_pages(pagep, cnt);
} else {
/*
* Copy the updated array, with qib_tid's filled in, back
* to user. Since we did the copy in already, this "should
* never fail" If it does, we have to clean up...
*/
if (copy_to_user((void __user *)
(unsigned long) ti->tidlist,
tidlist, cnt * sizeof(*tidlist))) {
ret = -EFAULT;
goto cleanup;
}
if (copy_to_user((void __user *) (unsigned long) ti->tidmap,
tidmap, sizeof(tidmap))) {
ret = -EFAULT;
goto cleanup;
}
if (tid == tidcnt)
tid = 0;
if (!rcd->subctxt_cnt)
rcd->tidcursor = tid;
else
tidcursor_fp(fp) = tid;
}
done:
return ret;
}
/**
* qib_tid_free - free a context TID
* @rcd: the context
* @subctxt: the subcontext
* @ti: the TID info
*
* right now we are unlocking one page at a time, but since
* the intended use of this routine is for a single group of
* virtually contiguous pages, that should change to improve
* performance. We check that the TID is in range for this context
* but otherwise don't check validity; if user has an error and
* frees the wrong tid, it's only their own data that can thereby
* be corrupted. We do check that the TID was in use, for sanity
* We always use our idea of the saved address, not the address that
* they pass in to us.
*/
static int qib_tid_free(struct qib_ctxtdata *rcd, unsigned subctxt,
const struct qib_tid_info *ti)
{
int ret = 0;
u32 tid, ctxttid, cnt, limit, tidcnt;
struct qib_devdata *dd = rcd->dd;
u64 __iomem *tidbase;
unsigned long tidmap[8];
if (!dd->pageshadow) {
ret = -ENOMEM;
goto done;
}
if (copy_from_user(tidmap, (void __user *)(unsigned long)ti->tidmap,
sizeof(tidmap))) {
ret = -EFAULT;
goto done;
}
ctxttid = rcd->ctxt * dd->rcvtidcnt;
if (!rcd->subctxt_cnt)
tidcnt = dd->rcvtidcnt;
else if (!subctxt) {
tidcnt = (dd->rcvtidcnt / rcd->subctxt_cnt) +
(dd->rcvtidcnt % rcd->subctxt_cnt);
ctxttid += dd->rcvtidcnt - tidcnt;
} else {
tidcnt = dd->rcvtidcnt / rcd->subctxt_cnt;
ctxttid += tidcnt * (subctxt - 1);
}
tidbase = (u64 __iomem *) ((char __iomem *)(dd->kregbase) +
dd->rcvtidbase +
ctxttid * sizeof(*tidbase));
limit = sizeof(tidmap) * BITS_PER_BYTE;
if (limit > tidcnt)
/* just in case size changes in future */
limit = tidcnt;
tid = find_first_bit(tidmap, limit);
for (cnt = 0; tid < limit; tid++) {
/*
* small optimization; if we detect a run of 3 or so without
* any set, use find_first_bit again. That's mainly to
* accelerate the case where we wrapped, so we have some at
* the beginning, and some at the end, and a big gap
* in the middle.
*/
if (!test_bit(tid, tidmap))
continue;
cnt++;
if (dd->pageshadow[ctxttid + tid]) {
struct page *p;
dma_addr_t phys;
p = dd->pageshadow[ctxttid + tid];
dd->pageshadow[ctxttid + tid] = NULL;
phys = dd->physshadow[ctxttid + tid];
dd->physshadow[ctxttid + tid] = dd->tidinvalid;
/* PERFORMANCE: below should almost certainly be
* cached
*/
dd->f_put_tid(dd, &tidbase[tid],
RCVHQ_RCV_TYPE_EXPECTED, dd->tidinvalid);
pci_unmap_page(dd->pcidev, phys, PAGE_SIZE,
PCI_DMA_FROMDEVICE);
qib_release_user_pages(&p, 1);
}
}
done:
return ret;
}
/**
* qib_set_part_key - set a partition key
* @rcd: the context
* @key: the key
*
* We can have up to 4 active at a time (other than the default, which is
* always allowed). This is somewhat tricky, since multiple contexts may set
* the same key, so we reference count them, and clean up at exit. All 4
* partition keys are packed into a single qlogic_ib register. It's an
* error for a process to set the same pkey multiple times. We provide no
* mechanism to de-allocate a pkey at this time, we may eventually need to
* do that. I've used the atomic operations, and no locking, and only make
* a single pass through what's available. This should be more than
* adequate for some time. I'll think about spinlocks or the like if and as
* it's necessary.
*/
static int qib_set_part_key(struct qib_ctxtdata *rcd, u16 key)
{
struct qib_pportdata *ppd = rcd->ppd;
int i, any = 0, pidx = -1;
u16 lkey = key & 0x7FFF;
int ret;
if (lkey == (QIB_DEFAULT_P_KEY & 0x7FFF)) {
/* nothing to do; this key always valid */
ret = 0;
goto bail;
}
if (!lkey) {
ret = -EINVAL;
goto bail;
}
/*
* Set the full membership bit, because it has to be
* set in the register or the packet, and it seems
* cleaner to set in the register than to force all
* callers to set it.
*/
key |= 0x8000;
for (i = 0; i < ARRAY_SIZE(rcd->pkeys); i++) {
if (!rcd->pkeys[i] && pidx == -1)
pidx = i;
if (rcd->pkeys[i] == key) {
ret = -EEXIST;
goto bail;
}
}
if (pidx == -1) {
ret = -EBUSY;
goto bail;
}
for (any = i = 0; i < ARRAY_SIZE(ppd->pkeys); i++) {
if (!ppd->pkeys[i]) {
any++;
continue;
}
if (ppd->pkeys[i] == key) {
atomic_t *pkrefs = &ppd->pkeyrefs[i];
if (atomic_inc_return(pkrefs) > 1) {
rcd->pkeys[pidx] = key;
ret = 0;
goto bail;
} else {
/*
* lost race, decrement count, catch below
*/
atomic_dec(pkrefs);
any++;
}
}
if ((ppd->pkeys[i] & 0x7FFF) == lkey) {
/*
* It makes no sense to have both the limited and
* full membership PKEY set at the same time since
* the unlimited one will disable the limited one.
*/
ret = -EEXIST;
goto bail;
}
}
if (!any) {
ret = -EBUSY;
goto bail;
}
for (any = i = 0; i < ARRAY_SIZE(ppd->pkeys); i++) {
if (!ppd->pkeys[i] &&
atomic_inc_return(&ppd->pkeyrefs[i]) == 1) {
rcd->pkeys[pidx] = key;
ppd->pkeys[i] = key;
(void) ppd->dd->f_set_ib_cfg(ppd, QIB_IB_CFG_PKEYS, 0);
ret = 0;
goto bail;
}
}
ret = -EBUSY;
bail:
return ret;
}
/**
* qib_manage_rcvq - manage a context's receive queue
* @rcd: the context
* @subctxt: the subcontext
* @start_stop: action to carry out
*
* start_stop == 0 disables receive on the context, for use in queue
* overflow conditions. start_stop==1 re-enables, to be used to
* re-init the software copy of the head register
*/
static int qib_manage_rcvq(struct qib_ctxtdata *rcd, unsigned subctxt,
int start_stop)
{
struct qib_devdata *dd = rcd->dd;
unsigned int rcvctrl_op;
if (subctxt)
goto bail;
/* atomically clear receive enable ctxt. */
if (start_stop) {
/*
* On enable, force in-memory copy of the tail register to
* 0, so that protocol code doesn't have to worry about
* whether or not the chip has yet updated the in-memory
* copy or not on return from the system call. The chip
* always resets it's tail register back to 0 on a
* transition from disabled to enabled.
*/
if (rcd->rcvhdrtail_kvaddr)
qib_clear_rcvhdrtail(rcd);
rcvctrl_op = QIB_RCVCTRL_CTXT_ENB;
} else
rcvctrl_op = QIB_RCVCTRL_CTXT_DIS;
dd->f_rcvctrl(rcd->ppd, rcvctrl_op, rcd->ctxt);
/* always; new head should be equal to new tail; see above */
bail:
return 0;
}
static void qib_clean_part_key(struct qib_ctxtdata *rcd,
struct qib_devdata *dd)
{
int i, j, pchanged = 0;
u64 oldpkey;
struct qib_pportdata *ppd = rcd->ppd;
/* for debugging only */
oldpkey = (u64) ppd->pkeys[0] |
((u64) ppd->pkeys[1] << 16) |
((u64) ppd->pkeys[2] << 32) |
((u64) ppd->pkeys[3] << 48);
for (i = 0; i < ARRAY_SIZE(rcd->pkeys); i++) {
if (!rcd->pkeys[i])
continue;
for (j = 0; j < ARRAY_SIZE(ppd->pkeys); j++) {
/* check for match independent of the global bit */
if ((ppd->pkeys[j] & 0x7fff) !=
(rcd->pkeys[i] & 0x7fff))
continue;
if (atomic_dec_and_test(&ppd->pkeyrefs[j])) {
ppd->pkeys[j] = 0;
pchanged++;
}
break;
}
rcd->pkeys[i] = 0;
}
if (pchanged)
(void) ppd->dd->f_set_ib_cfg(ppd, QIB_IB_CFG_PKEYS, 0);
}
/* common code for the mappings on dma_alloc_coherent mem */
static int qib_mmap_mem(struct vm_area_struct *vma, struct qib_ctxtdata *rcd,
unsigned len, void *kvaddr, u32 write_ok, char *what)
{
struct qib_devdata *dd = rcd->dd;
unsigned long pfn;
int ret;
if ((vma->vm_end - vma->vm_start) > len) {
qib_devinfo(dd->pcidev,
"FAIL on %s: len %lx > %x\n", what,
vma->vm_end - vma->vm_start, len);
ret = -EFAULT;
goto bail;
}
/*
* shared context user code requires rcvhdrq mapped r/w, others
* only allowed readonly mapping.
*/
if (!write_ok) {
if (vma->vm_flags & VM_WRITE) {
qib_devinfo(dd->pcidev,
"%s must be mapped readonly\n", what);
ret = -EPERM;
goto bail;
}
/* don't allow them to later change with mprotect */
vma->vm_flags &= ~VM_MAYWRITE;
}
pfn = virt_to_phys(kvaddr) >> PAGE_SHIFT;
ret = remap_pfn_range(vma, vma->vm_start, pfn,
len, vma->vm_page_prot);
if (ret)
qib_devinfo(dd->pcidev,
"%s ctxt%u mmap of %lx, %x bytes failed: %d\n",
what, rcd->ctxt, pfn, len, ret);
bail:
return ret;
}
static int mmap_ureg(struct vm_area_struct *vma, struct qib_devdata *dd,
u64 ureg)
{
unsigned long phys;
unsigned long sz;
int ret;
/*
* This is real hardware, so use io_remap. This is the mechanism
* for the user process to update the head registers for their ctxt
* in the chip.
*/
sz = dd->flags & QIB_HAS_HDRSUPP ? 2 * PAGE_SIZE : PAGE_SIZE;
if ((vma->vm_end - vma->vm_start) > sz) {
qib_devinfo(dd->pcidev,
"FAIL mmap userreg: reqlen %lx > PAGE\n",
vma->vm_end - vma->vm_start);
ret = -EFAULT;
} else {
phys = dd->physaddr + ureg;
vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND;
ret = io_remap_pfn_range(vma, vma->vm_start,
phys >> PAGE_SHIFT,
vma->vm_end - vma->vm_start,
vma->vm_page_prot);
}
return ret;
}
static int mmap_piobufs(struct vm_area_struct *vma,
struct qib_devdata *dd,
struct qib_ctxtdata *rcd,
unsigned piobufs, unsigned piocnt)
{
unsigned long phys;
int ret;
/*
* When we map the PIO buffers in the chip, we want to map them as
* writeonly, no read possible; unfortunately, x86 doesn't allow
* for this in hardware, but we still prevent users from asking
* for it.
*/
if ((vma->vm_end - vma->vm_start) > (piocnt * dd->palign)) {
qib_devinfo(dd->pcidev,
"FAIL mmap piobufs: reqlen %lx > PAGE\n",
vma->vm_end - vma->vm_start);
ret = -EINVAL;
goto bail;
}
phys = dd->physaddr + piobufs;
#if defined(__powerpc__)
/* There isn't a generic way to specify writethrough mappings */
pgprot_val(vma->vm_page_prot) |= _PAGE_NO_CACHE;
pgprot_val(vma->vm_page_prot) |= _PAGE_WRITETHRU;
pgprot_val(vma->vm_page_prot) &= ~_PAGE_GUARDED;
#endif
/*
* don't allow them to later change to readable with mprotect (for when
* not initially mapped readable, as is normally the case)
*/
vma->vm_flags &= ~VM_MAYREAD;
vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND;
/* We used PAT if wc_cookie == 0 */
if (!dd->wc_cookie)
vma->vm_page_prot = pgprot_writecombine(vma->vm_page_prot);
ret = io_remap_pfn_range(vma, vma->vm_start, phys >> PAGE_SHIFT,
vma->vm_end - vma->vm_start,
vma->vm_page_prot);
bail:
return ret;
}
static int mmap_rcvegrbufs(struct vm_area_struct *vma,
struct qib_ctxtdata *rcd)
{
struct qib_devdata *dd = rcd->dd;
unsigned long start, size;
size_t total_size, i;
unsigned long pfn;
int ret;
size = rcd->rcvegrbuf_size;
total_size = rcd->rcvegrbuf_chunks * size;
if ((vma->vm_end - vma->vm_start) > total_size) {
qib_devinfo(dd->pcidev,
"FAIL on egr bufs: reqlen %lx > actual %lx\n",
vma->vm_end - vma->vm_start,
(unsigned long) total_size);
ret = -EINVAL;
goto bail;
}
if (vma->vm_flags & VM_WRITE) {
qib_devinfo(dd->pcidev,
"Can't map eager buffers as writable (flags=%lx)\n",
vma->vm_flags);
ret = -EPERM;
goto bail;
}
/* don't allow them to later change to writeable with mprotect */
vma->vm_flags &= ~VM_MAYWRITE;
start = vma->vm_start;
for (i = 0; i < rcd->rcvegrbuf_chunks; i++, start += size) {
pfn = virt_to_phys(rcd->rcvegrbuf[i]) >> PAGE_SHIFT;
ret = remap_pfn_range(vma, start, pfn, size,
vma->vm_page_prot);
if (ret < 0)
goto bail;
}
ret = 0;
bail:
return ret;
}
/*
* qib_file_vma_fault - handle a VMA page fault.
*/
static int qib_file_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
struct page *page;
page = vmalloc_to_page((void *)(vmf->pgoff << PAGE_SHIFT));
if (!page)
return VM_FAULT_SIGBUS;
get_page(page);
vmf->page = page;
return 0;
}
static const struct vm_operations_struct qib_file_vm_ops = {
.fault = qib_file_vma_fault,
};
static int mmap_kvaddr(struct vm_area_struct *vma, u64 pgaddr,
struct qib_ctxtdata *rcd, unsigned subctxt)
{
struct qib_devdata *dd = rcd->dd;
unsigned subctxt_cnt;
unsigned long len;
void *addr;
size_t size;
int ret = 0;
subctxt_cnt = rcd->subctxt_cnt;
size = rcd->rcvegrbuf_chunks * rcd->rcvegrbuf_size;
/*
* Each process has all the subctxt uregbase, rcvhdrq, and
* rcvegrbufs mmapped - as an array for all the processes,
* and also separately for this process.
*/
if (pgaddr == cvt_kvaddr(rcd->subctxt_uregbase)) {
addr = rcd->subctxt_uregbase;
size = PAGE_SIZE * subctxt_cnt;
} else if (pgaddr == cvt_kvaddr(rcd->subctxt_rcvhdr_base)) {
addr = rcd->subctxt_rcvhdr_base;
size = rcd->rcvhdrq_size * subctxt_cnt;
} else if (pgaddr == cvt_kvaddr(rcd->subctxt_rcvegrbuf)) {
addr = rcd->subctxt_rcvegrbuf;
size *= subctxt_cnt;
} else if (pgaddr == cvt_kvaddr(rcd->subctxt_uregbase +
PAGE_SIZE * subctxt)) {
addr = rcd->subctxt_uregbase + PAGE_SIZE * subctxt;
size = PAGE_SIZE;
} else if (pgaddr == cvt_kvaddr(rcd->subctxt_rcvhdr_base +
rcd->rcvhdrq_size * subctxt)) {
addr = rcd->subctxt_rcvhdr_base +
rcd->rcvhdrq_size * subctxt;
size = rcd->rcvhdrq_size;
} else if (pgaddr == cvt_kvaddr(&rcd->user_event_mask[subctxt])) {
addr = rcd->user_event_mask;
size = PAGE_SIZE;
} else if (pgaddr == cvt_kvaddr(rcd->subctxt_rcvegrbuf +
size * subctxt)) {
addr = rcd->subctxt_rcvegrbuf + size * subctxt;
/* rcvegrbufs are read-only on the slave */
if (vma->vm_flags & VM_WRITE) {
qib_devinfo(dd->pcidev,
"Can't map eager buffers as writable (flags=%lx)\n",
vma->vm_flags);
ret = -EPERM;
goto bail;
}
/*
* Don't allow permission to later change to writeable
* with mprotect.
*/
vma->vm_flags &= ~VM_MAYWRITE;
} else
goto bail;
len = vma->vm_end - vma->vm_start;
if (len > size) {
ret = -EINVAL;
goto bail;
}
vma->vm_pgoff = (unsigned long) addr >> PAGE_SHIFT;
vma->vm_ops = &qib_file_vm_ops;
vma->vm_flags |= VM_DONTEXPAND | VM_DONTDUMP;
ret = 1;
bail:
return ret;
}
/**
* qib_mmapf - mmap various structures into user space
* @fp: the file pointer
* @vma: the VM area
*
* We use this to have a shared buffer between the kernel and the user code
* for the rcvhdr queue, egr buffers, and the per-context user regs and pio
* buffers in the chip. We have the open and close entries so we can bump
* the ref count and keep the driver from being unloaded while still mapped.
*/
static int qib_mmapf(struct file *fp, struct vm_area_struct *vma)
{
struct qib_ctxtdata *rcd;
struct qib_devdata *dd;
u64 pgaddr, ureg;
unsigned piobufs, piocnt;
int ret, match = 1;
rcd = ctxt_fp(fp);
if (!rcd || !(vma->vm_flags & VM_SHARED)) {
ret = -EINVAL;
goto bail;
}
dd = rcd->dd;
/*
* This is the qib_do_user_init() code, mapping the shared buffers
* and per-context user registers into the user process. The address
* referred to by vm_pgoff is the file offset passed via mmap().
* For shared contexts, this is the kernel vmalloc() address of the
* pages to share with the master.
* For non-shared or master ctxts, this is a physical address.
* We only do one mmap for each space mapped.
*/
pgaddr = vma->vm_pgoff << PAGE_SHIFT;
/*
* Check for 0 in case one of the allocations failed, but user
* called mmap anyway.
*/
if (!pgaddr) {
ret = -EINVAL;
goto bail;
}
/*
* Physical addresses must fit in 40 bits for our hardware.
* Check for kernel virtual addresses first, anything else must
* match a HW or memory address.
*/
ret = mmap_kvaddr(vma, pgaddr, rcd, subctxt_fp(fp));
if (ret) {
if (ret > 0)
ret = 0;
goto bail;
}
ureg = dd->uregbase + dd->ureg_align * rcd->ctxt;
if (!rcd->subctxt_cnt) {
/* ctxt is not shared */
piocnt = rcd->piocnt;
piobufs = rcd->piobufs;
} else if (!subctxt_fp(fp)) {
/* caller is the master */
piocnt = (rcd->piocnt / rcd->subctxt_cnt) +
(rcd->piocnt % rcd->subctxt_cnt);
piobufs = rcd->piobufs +
dd->palign * (rcd->piocnt - piocnt);
} else {
unsigned slave = subctxt_fp(fp) - 1;
/* caller is a slave */
piocnt = rcd->piocnt / rcd->subctxt_cnt;
piobufs = rcd->piobufs + dd->palign * piocnt * slave;
}
if (pgaddr == ureg)
ret = mmap_ureg(vma, dd, ureg);
else if (pgaddr == piobufs)
ret = mmap_piobufs(vma, dd, rcd, piobufs, piocnt);
else if (pgaddr == dd->pioavailregs_phys)
/* in-memory copy of pioavail registers */
ret = qib_mmap_mem(vma, rcd, PAGE_SIZE,
(void *) dd->pioavailregs_dma, 0,
"pioavail registers");
else if (pgaddr == rcd->rcvegr_phys)
ret = mmap_rcvegrbufs(vma, rcd);
else if (pgaddr == (u64) rcd->rcvhdrq_phys)
/*
* The rcvhdrq itself; multiple pages, contiguous
* from an i/o perspective. Shared contexts need
* to map r/w, so we allow writing.
*/
ret = qib_mmap_mem(vma, rcd, rcd->rcvhdrq_size,
rcd->rcvhdrq, 1, "rcvhdrq");
else if (pgaddr == (u64) rcd->rcvhdrqtailaddr_phys)
/* in-memory copy of rcvhdrq tail register */
ret = qib_mmap_mem(vma, rcd, PAGE_SIZE,
rcd->rcvhdrtail_kvaddr, 0,
"rcvhdrq tail");
else
match = 0;
if (!match)
ret = -EINVAL;
vma->vm_private_data = NULL;
if (ret < 0)
qib_devinfo(dd->pcidev,
"mmap Failure %d: off %llx len %lx\n",
-ret, (unsigned long long)pgaddr,
vma->vm_end - vma->vm_start);
bail:
return ret;
}
static unsigned int qib_poll_urgent(struct qib_ctxtdata *rcd,
struct file *fp,
struct poll_table_struct *pt)
{
struct qib_devdata *dd = rcd->dd;
unsigned pollflag;
poll_wait(fp, &rcd->wait, pt);
spin_lock_irq(&dd->uctxt_lock);
if (rcd->urgent != rcd->urgent_poll) {
pollflag = POLLIN | POLLRDNORM;
rcd->urgent_poll = rcd->urgent;
} else {
pollflag = 0;
set_bit(QIB_CTXT_WAITING_URG, &rcd->flag);
}
spin_unlock_irq(&dd->uctxt_lock);
return pollflag;
}
static unsigned int qib_poll_next(struct qib_ctxtdata *rcd,
struct file *fp,
struct poll_table_struct *pt)
{
struct qib_devdata *dd = rcd->dd;
unsigned pollflag;
poll_wait(fp, &rcd->wait, pt);
spin_lock_irq(&dd->uctxt_lock);
if (dd->f_hdrqempty(rcd)) {
set_bit(QIB_CTXT_WAITING_RCV, &rcd->flag);
dd->f_rcvctrl(rcd->ppd, QIB_RCVCTRL_INTRAVAIL_ENB, rcd->ctxt);
pollflag = 0;
} else
pollflag = POLLIN | POLLRDNORM;
spin_unlock_irq(&dd->uctxt_lock);
return pollflag;
}
static unsigned int qib_poll(struct file *fp, struct poll_table_struct *pt)
{
struct qib_ctxtdata *rcd;
unsigned pollflag;
rcd = ctxt_fp(fp);
if (!rcd)
pollflag = POLLERR;
else if (rcd->poll_type == QIB_POLL_TYPE_URGENT)
pollflag = qib_poll_urgent(rcd, fp, pt);
else if (rcd->poll_type == QIB_POLL_TYPE_ANYRCV)
pollflag = qib_poll_next(rcd, fp, pt);
else /* invalid */
pollflag = POLLERR;
return pollflag;
}
static void assign_ctxt_affinity(struct file *fp, struct qib_devdata *dd)
{
struct qib_filedata *fd = fp->private_data;
const unsigned int weight = cpumask_weight(¤t->cpus_allowed);
const struct cpumask *local_mask = cpumask_of_pcibus(dd->pcidev->bus);
int local_cpu;
/*
* If process has NOT already set it's affinity, select and
* reserve a processor for it on the local NUMA node.
*/
if ((weight >= qib_cpulist_count) &&
(cpumask_weight(local_mask) <= qib_cpulist_count)) {
for_each_cpu(local_cpu, local_mask)
if (!test_and_set_bit(local_cpu, qib_cpulist)) {
fd->rec_cpu_num = local_cpu;
return;
}
}
/*
* If process has NOT already set it's affinity, select and
* reserve a processor for it, as a rendevous for all
* users of the driver. If they don't actually later
* set affinity to this cpu, or set it to some other cpu,
* it just means that sooner or later we don't recommend
* a cpu, and let the scheduler do it's best.
*/
if (weight >= qib_cpulist_count) {
int cpu;
cpu = find_first_zero_bit(qib_cpulist,
qib_cpulist_count);
if (cpu == qib_cpulist_count)
qib_dev_err(dd,
"no cpus avail for affinity PID %u\n",
current->pid);
else {
__set_bit(cpu, qib_cpulist);
fd->rec_cpu_num = cpu;
}
}
}
/*
* Check that userland and driver are compatible for subcontexts.
*/
static int qib_compatible_subctxts(int user_swmajor, int user_swminor)
{
/* this code is written long-hand for clarity */
if (QIB_USER_SWMAJOR != user_swmajor) {
/* no promise of compatibility if major mismatch */
return 0;
}
if (QIB_USER_SWMAJOR == 1) {
switch (QIB_USER_SWMINOR) {
case 0:
case 1:
case 2:
/* no subctxt implementation so cannot be compatible */
return 0;
case 3:
/* 3 is only compatible with itself */
return user_swminor == 3;
default:
/* >= 4 are compatible (or are expected to be) */
return user_swminor <= QIB_USER_SWMINOR;
}
}
/* make no promises yet for future major versions */
return 0;
}
static int init_subctxts(struct qib_devdata *dd,
struct qib_ctxtdata *rcd,
const struct qib_user_info *uinfo)
{
int ret = 0;
unsigned num_subctxts;
size_t size;
/*
* If the user is requesting zero subctxts,
* skip the subctxt allocation.
*/
if (uinfo->spu_subctxt_cnt <= 0)
goto bail;
num_subctxts = uinfo->spu_subctxt_cnt;
/* Check for subctxt compatibility */
if (!qib_compatible_subctxts(uinfo->spu_userversion >> 16,
uinfo->spu_userversion & 0xffff)) {
qib_devinfo(dd->pcidev,
"Mismatched user version (%d.%d) and driver version (%d.%d) while context sharing. Ensure that driver and library are from the same release.\n",
(int) (uinfo->spu_userversion >> 16),
(int) (uinfo->spu_userversion & 0xffff),
QIB_USER_SWMAJOR, QIB_USER_SWMINOR);
goto bail;
}
if (num_subctxts > QLOGIC_IB_MAX_SUBCTXT) {
ret = -EINVAL;
goto bail;
}
rcd->subctxt_uregbase = vmalloc_user(PAGE_SIZE * num_subctxts);
if (!rcd->subctxt_uregbase) {
ret = -ENOMEM;
goto bail;
}
/* Note: rcd->rcvhdrq_size isn't initialized yet. */
size = ALIGN(dd->rcvhdrcnt * dd->rcvhdrentsize *
sizeof(u32), PAGE_SIZE) * num_subctxts;
rcd->subctxt_rcvhdr_base = vmalloc_user(size);
if (!rcd->subctxt_rcvhdr_base) {
ret = -ENOMEM;
goto bail_ureg;
}
rcd->subctxt_rcvegrbuf = vmalloc_user(rcd->rcvegrbuf_chunks *
rcd->rcvegrbuf_size *
num_subctxts);
if (!rcd->subctxt_rcvegrbuf) {
ret = -ENOMEM;
goto bail_rhdr;
}
rcd->subctxt_cnt = uinfo->spu_subctxt_cnt;
rcd->subctxt_id = uinfo->spu_subctxt_id;
rcd->active_slaves = 1;
rcd->redirect_seq_cnt = 1;
set_bit(QIB_CTXT_MASTER_UNINIT, &rcd->flag);
goto bail;
bail_rhdr:
vfree(rcd->subctxt_rcvhdr_base);
bail_ureg:
vfree(rcd->subctxt_uregbase);
rcd->subctxt_uregbase = NULL;
bail:
return ret;
}
static int setup_ctxt(struct qib_pportdata *ppd, int ctxt,
struct file *fp, const struct qib_user_info *uinfo)
{
struct qib_filedata *fd = fp->private_data;
struct qib_devdata *dd = ppd->dd;
struct qib_ctxtdata *rcd;
void *ptmp = NULL;
int ret;
int numa_id;
assign_ctxt_affinity(fp, dd);
numa_id = qib_numa_aware ? ((fd->rec_cpu_num != -1) ?
cpu_to_node(fd->rec_cpu_num) :
numa_node_id()) : dd->assigned_node_id;
rcd = qib_create_ctxtdata(ppd, ctxt, numa_id);
/*
* Allocate memory for use in qib_tid_update() at open to
* reduce cost of expected send setup per message segment
*/
if (rcd)
ptmp = kmalloc(dd->rcvtidcnt * sizeof(u16) +
dd->rcvtidcnt * sizeof(struct page **),
GFP_KERNEL);
if (!rcd || !ptmp) {
qib_dev_err(dd,
"Unable to allocate ctxtdata memory, failing open\n");
ret = -ENOMEM;
goto bailerr;
}
rcd->userversion = uinfo->spu_userversion;
ret = init_subctxts(dd, rcd, uinfo);
if (ret)
goto bailerr;
rcd->tid_pg_list = ptmp;
rcd->pid = current->pid;
init_waitqueue_head(&dd->rcd[ctxt]->wait);
strlcpy(rcd->comm, current->comm, sizeof(rcd->comm));
ctxt_fp(fp) = rcd;
qib_stats.sps_ctxts++;
dd->freectxts--;
ret = 0;
goto bail;
bailerr:
if (fd->rec_cpu_num != -1)
__clear_bit(fd->rec_cpu_num, qib_cpulist);
dd->rcd[ctxt] = NULL;
kfree(rcd);
kfree(ptmp);
bail:
return ret;
}
static inline int usable(struct qib_pportdata *ppd)
{
struct qib_devdata *dd = ppd->dd;
return dd && (dd->flags & QIB_PRESENT) && dd->kregbase && ppd->lid &&
(ppd->lflags & QIBL_LINKACTIVE);
}
/*
* Select a context on the given device, either using a requested port
* or the port based on the context number.
*/
static int choose_port_ctxt(struct file *fp, struct qib_devdata *dd, u32 port,
const struct qib_user_info *uinfo)
{
struct qib_pportdata *ppd = NULL;
int ret, ctxt;
if (port) {
if (!usable(dd->pport + port - 1)) {
ret = -ENETDOWN;
goto done;
} else
ppd = dd->pport + port - 1;
}
for (ctxt = dd->first_user_ctxt; ctxt < dd->cfgctxts && dd->rcd[ctxt];
ctxt++)
;
if (ctxt == dd->cfgctxts) {
ret = -EBUSY;
goto done;
}
if (!ppd) {
u32 pidx = ctxt % dd->num_pports;
if (usable(dd->pport + pidx))
ppd = dd->pport + pidx;
else {
for (pidx = 0; pidx < dd->num_pports && !ppd;
pidx++)
if (usable(dd->pport + pidx))
ppd = dd->pport + pidx;
}
}
ret = ppd ? setup_ctxt(ppd, ctxt, fp, uinfo) : -ENETDOWN;
done:
return ret;
}
static int find_free_ctxt(int unit, struct file *fp,
const struct qib_user_info *uinfo)
{
struct qib_devdata *dd = qib_lookup(unit);
int ret;
if (!dd || (uinfo->spu_port && uinfo->spu_port > dd->num_pports))
ret = -ENODEV;
else
ret = choose_port_ctxt(fp, dd, uinfo->spu_port, uinfo);
return ret;
}
static int get_a_ctxt(struct file *fp, const struct qib_user_info *uinfo,
unsigned alg)
{
struct qib_devdata *udd = NULL;
int ret = 0, devmax, npresent, nup, ndev, dusable = 0, i;
u32 port = uinfo->spu_port, ctxt;
devmax = qib_count_units(&npresent, &nup);
if (!npresent) {
ret = -ENXIO;
goto done;
}
if (nup == 0) {
ret = -ENETDOWN;
goto done;
}
if (alg == QIB_PORT_ALG_ACROSS) {
unsigned inuse = ~0U;
/* find device (with ACTIVE ports) with fewest ctxts in use */
for (ndev = 0; ndev < devmax; ndev++) {
struct qib_devdata *dd = qib_lookup(ndev);
unsigned cused = 0, cfree = 0, pusable = 0;
if (!dd)
continue;
if (port && port <= dd->num_pports &&
usable(dd->pport + port - 1))
pusable = 1;
else
for (i = 0; i < dd->num_pports; i++)
if (usable(dd->pport + i))
pusable++;
if (!pusable)
continue;
for (ctxt = dd->first_user_ctxt; ctxt < dd->cfgctxts;
ctxt++)
if (dd->rcd[ctxt])
cused++;
else
cfree++;
if (cfree && cused < inuse) {
udd = dd;
inuse = cused;
}
}
if (udd) {
ret = choose_port_ctxt(fp, udd, port, uinfo);
goto done;
}
} else {
for (ndev = 0; ndev < devmax; ndev++) {
struct qib_devdata *dd = qib_lookup(ndev);
if (dd) {
ret = choose_port_ctxt(fp, dd, port, uinfo);
if (!ret)
goto done;
if (ret == -EBUSY)
dusable++;
}
}
}
ret = dusable ? -EBUSY : -ENETDOWN;
done:
return ret;
}
static int find_shared_ctxt(struct file *fp,
const struct qib_user_info *uinfo)
{
int devmax, ndev, i;
int ret = 0;
devmax = qib_count_units(NULL, NULL);
for (ndev = 0; ndev < devmax; ndev++) {
struct qib_devdata *dd = qib_lookup(ndev);
/* device portion of usable() */
if (!(dd && (dd->flags & QIB_PRESENT) && dd->kregbase))
continue;
for (i = dd->first_user_ctxt; i < dd->cfgctxts; i++) {
struct qib_ctxtdata *rcd = dd->rcd[i];
/* Skip ctxts which are not yet open */
if (!rcd || !rcd->cnt)
continue;
/* Skip ctxt if it doesn't match the requested one */
if (rcd->subctxt_id != uinfo->spu_subctxt_id)
continue;
/* Verify the sharing process matches the master */
if (rcd->subctxt_cnt != uinfo->spu_subctxt_cnt ||
rcd->userversion != uinfo->spu_userversion ||
rcd->cnt >= rcd->subctxt_cnt) {
ret = -EINVAL;
goto done;
}
ctxt_fp(fp) = rcd;
subctxt_fp(fp) = rcd->cnt++;
rcd->subpid[subctxt_fp(fp)] = current->pid;
tidcursor_fp(fp) = 0;
rcd->active_slaves |= 1 << subctxt_fp(fp);
ret = 1;
goto done;
}
}
done:
return ret;
}
static int qib_open(struct inode *in, struct file *fp)
{
/* The real work is performed later in qib_assign_ctxt() */
fp->private_data = kzalloc(sizeof(struct qib_filedata), GFP_KERNEL);
if (fp->private_data) /* no cpu affinity by default */
((struct qib_filedata *)fp->private_data)->rec_cpu_num = -1;
return fp->private_data ? 0 : -ENOMEM;
}
static int find_hca(unsigned int cpu, int *unit)
{
int ret = 0, devmax, npresent, nup, ndev;
*unit = -1;
devmax = qib_count_units(&npresent, &nup);
if (!npresent) {
ret = -ENXIO;
goto done;
}
if (!nup) {
ret = -ENETDOWN;
goto done;
}
for (ndev = 0; ndev < devmax; ndev++) {
struct qib_devdata *dd = qib_lookup(ndev);
if (dd) {
if (pcibus_to_node(dd->pcidev->bus) < 0) {
ret = -EINVAL;
goto done;
}
if (cpu_to_node(cpu) ==
pcibus_to_node(dd->pcidev->bus)) {
*unit = ndev;
goto done;
}
}
}
done:
return ret;
}
static int do_qib_user_sdma_queue_create(struct file *fp)
{
struct qib_filedata *fd = fp->private_data;
struct qib_ctxtdata *rcd = fd->rcd;
struct qib_devdata *dd = rcd->dd;
if (dd->flags & QIB_HAS_SEND_DMA) {
fd->pq = qib_user_sdma_queue_create(&dd->pcidev->dev,
dd->unit,
rcd->ctxt,
fd->subctxt);
if (!fd->pq)
return -ENOMEM;
}
return 0;
}
/*
* Get ctxt early, so can set affinity prior to memory allocation.
*/
static int qib_assign_ctxt(struct file *fp, const struct qib_user_info *uinfo)
{
int ret;
int i_minor;
unsigned swmajor, swminor, alg = QIB_PORT_ALG_ACROSS;
/* Check to be sure we haven't already initialized this file */
if (ctxt_fp(fp)) {
ret = -EINVAL;
goto done;
}
/* for now, if major version is different, bail */
swmajor = uinfo->spu_userversion >> 16;
if (swmajor != QIB_USER_SWMAJOR) {
ret = -ENODEV;
goto done;
}
swminor = uinfo->spu_userversion & 0xffff;
if (swminor >= 11 && uinfo->spu_port_alg < QIB_PORT_ALG_COUNT)
alg = uinfo->spu_port_alg;
mutex_lock(&qib_mutex);
if (qib_compatible_subctxts(swmajor, swminor) &&
uinfo->spu_subctxt_cnt) {
ret = find_shared_ctxt(fp, uinfo);
if (ret > 0) {
ret = do_qib_user_sdma_queue_create(fp);
if (!ret)
assign_ctxt_affinity(fp, (ctxt_fp(fp))->dd);
goto done_ok;
}
}
i_minor = iminor(file_inode(fp)) - QIB_USER_MINOR_BASE;
if (i_minor)
ret = find_free_ctxt(i_minor - 1, fp, uinfo);
else {
int unit;
const unsigned int cpu = cpumask_first(¤t->cpus_allowed);
const unsigned int weight =
cpumask_weight(¤t->cpus_allowed);
if (weight == 1 && !test_bit(cpu, qib_cpulist))
if (!find_hca(cpu, &unit) && unit >= 0)
if (!find_free_ctxt(unit, fp, uinfo)) {
ret = 0;
goto done_chk_sdma;
}
ret = get_a_ctxt(fp, uinfo, alg);
}
done_chk_sdma:
if (!ret)
ret = do_qib_user_sdma_queue_create(fp);
done_ok:
mutex_unlock(&qib_mutex);
done:
return ret;
}
static int qib_do_user_init(struct file *fp,
const struct qib_user_info *uinfo)
{
int ret;
struct qib_ctxtdata *rcd = ctxt_fp(fp);
struct qib_devdata *dd;
unsigned uctxt;
/* Subctxts don't need to initialize anything since master did it. */
if (subctxt_fp(fp)) {
ret = wait_event_interruptible(rcd->wait,
!test_bit(QIB_CTXT_MASTER_UNINIT, &rcd->flag));
goto bail;
}
dd = rcd->dd;
/* some ctxts may get extra buffers, calculate that here */
uctxt = rcd->ctxt - dd->first_user_ctxt;
if (uctxt < dd->ctxts_extrabuf) {
rcd->piocnt = dd->pbufsctxt + 1;
rcd->pio_base = rcd->piocnt * uctxt;
} else {
rcd->piocnt = dd->pbufsctxt;
rcd->pio_base = rcd->piocnt * uctxt +
dd->ctxts_extrabuf;
}
/*
* All user buffers are 2KB buffers. If we ever support
* giving 4KB buffers to user processes, this will need some
* work. Can't use piobufbase directly, because it has
* both 2K and 4K buffer base values. So check and handle.
*/
if ((rcd->pio_base + rcd->piocnt) > dd->piobcnt2k) {
if (rcd->pio_base >= dd->piobcnt2k) {
qib_dev_err(dd,
"%u:ctxt%u: no 2KB buffers available\n",
dd->unit, rcd->ctxt);
ret = -ENOBUFS;
goto bail;
}
rcd->piocnt = dd->piobcnt2k - rcd->pio_base;
qib_dev_err(dd, "Ctxt%u: would use 4KB bufs, using %u\n",
rcd->ctxt, rcd->piocnt);
}
rcd->piobufs = dd->pio2k_bufbase + rcd->pio_base * dd->palign;
qib_chg_pioavailkernel(dd, rcd->pio_base, rcd->piocnt,
TXCHK_CHG_TYPE_USER, rcd);
/*
* try to ensure that processes start up with consistent avail update
* for their own range, at least. If system very quiet, it might
* have the in-memory copy out of date at startup for this range of
* buffers, when a context gets re-used. Do after the chg_pioavail
* and before the rest of setup, so it's "almost certain" the dma
* will have occurred (can't 100% guarantee, but should be many
* decimals of 9s, with this ordering), given how much else happens
* after this.
*/
dd->f_sendctrl(dd->pport, QIB_SENDCTRL_AVAIL_BLIP);
/*
* Now allocate the rcvhdr Q and eager TIDs; skip the TID
* array for time being. If rcd->ctxt > chip-supported,
* we need to do extra stuff here to handle by handling overflow
* through ctxt 0, someday
*/
ret = qib_create_rcvhdrq(dd, rcd);
if (!ret)
ret = qib_setup_eagerbufs(rcd);
if (ret)
goto bail_pio;
rcd->tidcursor = 0; /* start at beginning after open */
/* initialize poll variables... */
rcd->urgent = 0;
rcd->urgent_poll = 0;
/*
* Now enable the ctxt for receive.
* For chips that are set to DMA the tail register to memory
* when they change (and when the update bit transitions from
* 0 to 1. So for those chips, we turn it off and then back on.
* This will (very briefly) affect any other open ctxts, but the
* duration is very short, and therefore isn't an issue. We
* explicitly set the in-memory tail copy to 0 beforehand, so we
* don't have to wait to be sure the DMA update has happened
* (chip resets head/tail to 0 on transition to enable).
*/
if (rcd->rcvhdrtail_kvaddr)
qib_clear_rcvhdrtail(rcd);
dd->f_rcvctrl(rcd->ppd, QIB_RCVCTRL_CTXT_ENB | QIB_RCVCTRL_TIDFLOW_ENB,
rcd->ctxt);
/* Notify any waiting slaves */
if (rcd->subctxt_cnt) {
clear_bit(QIB_CTXT_MASTER_UNINIT, &rcd->flag);
wake_up(&rcd->wait);
}
return 0;
bail_pio:
qib_chg_pioavailkernel(dd, rcd->pio_base, rcd->piocnt,
TXCHK_CHG_TYPE_KERN, rcd);
bail:
return ret;
}
/**
* unlock_exptid - unlock any expected TID entries context still had in use
* @rcd: ctxt
*
* We don't actually update the chip here, because we do a bulk update
* below, using f_clear_tids.
*/
static void unlock_expected_tids(struct qib_ctxtdata *rcd)
{
struct qib_devdata *dd = rcd->dd;
int ctxt_tidbase = rcd->ctxt * dd->rcvtidcnt;
int i, cnt = 0, maxtid = ctxt_tidbase + dd->rcvtidcnt;
for (i = ctxt_tidbase; i < maxtid; i++) {
struct page *p = dd->pageshadow[i];
dma_addr_t phys;
if (!p)
continue;
phys = dd->physshadow[i];
dd->physshadow[i] = dd->tidinvalid;
dd->pageshadow[i] = NULL;
pci_unmap_page(dd->pcidev, phys, PAGE_SIZE,
PCI_DMA_FROMDEVICE);
qib_release_user_pages(&p, 1);
cnt++;
}
}
static int qib_close(struct inode *in, struct file *fp)
{
int ret = 0;
struct qib_filedata *fd;
struct qib_ctxtdata *rcd;
struct qib_devdata *dd;
unsigned long flags;
unsigned ctxt;
pid_t pid;
mutex_lock(&qib_mutex);
fd = fp->private_data;
fp->private_data = NULL;
rcd = fd->rcd;
if (!rcd) {
mutex_unlock(&qib_mutex);
goto bail;
}
dd = rcd->dd;
/* ensure all pio buffer writes in progress are flushed */
qib_flush_wc();
/* drain user sdma queue */
if (fd->pq) {
qib_user_sdma_queue_drain(rcd->ppd, fd->pq);
qib_user_sdma_queue_destroy(fd->pq);
}
if (fd->rec_cpu_num != -1)
__clear_bit(fd->rec_cpu_num, qib_cpulist);
if (--rcd->cnt) {
/*
* XXX If the master closes the context before the slave(s),
* revoke the mmap for the eager receive queue so
* the slave(s) don't wait for receive data forever.
*/
rcd->active_slaves &= ~(1 << fd->subctxt);
rcd->subpid[fd->subctxt] = 0;
mutex_unlock(&qib_mutex);
goto bail;
}
/* early; no interrupt users after this */
spin_lock_irqsave(&dd->uctxt_lock, flags);
ctxt = rcd->ctxt;
dd->rcd[ctxt] = NULL;
pid = rcd->pid;
rcd->pid = 0;
spin_unlock_irqrestore(&dd->uctxt_lock, flags);
if (rcd->rcvwait_to || rcd->piowait_to ||
rcd->rcvnowait || rcd->pionowait) {
rcd->rcvwait_to = 0;
rcd->piowait_to = 0;
rcd->rcvnowait = 0;
rcd->pionowait = 0;
}
if (rcd->flag)
rcd->flag = 0;
if (dd->kregbase) {
/* atomically clear receive enable ctxt and intr avail. */
dd->f_rcvctrl(rcd->ppd, QIB_RCVCTRL_CTXT_DIS |
QIB_RCVCTRL_INTRAVAIL_DIS, ctxt);
/* clean up the pkeys for this ctxt user */
qib_clean_part_key(rcd, dd);
qib_disarm_piobufs(dd, rcd->pio_base, rcd->piocnt);
qib_chg_pioavailkernel(dd, rcd->pio_base,
rcd->piocnt, TXCHK_CHG_TYPE_KERN, NULL);
dd->f_clear_tids(dd, rcd);
if (dd->pageshadow)
unlock_expected_tids(rcd);
qib_stats.sps_ctxts--;
dd->freectxts++;
}
mutex_unlock(&qib_mutex);
qib_free_ctxtdata(dd, rcd); /* after releasing the mutex */
bail:
kfree(fd);
return ret;
}
static int qib_ctxt_info(struct file *fp, struct qib_ctxt_info __user *uinfo)
{
struct qib_ctxt_info info;
int ret;
size_t sz;
struct qib_ctxtdata *rcd = ctxt_fp(fp);
struct qib_filedata *fd;
fd = fp->private_data;
info.num_active = qib_count_active_units();
info.unit = rcd->dd->unit;
info.port = rcd->ppd->port;
info.ctxt = rcd->ctxt;
info.subctxt = subctxt_fp(fp);
/* Number of user ctxts available for this device. */
info.num_ctxts = rcd->dd->cfgctxts - rcd->dd->first_user_ctxt;
info.num_subctxts = rcd->subctxt_cnt;
info.rec_cpu = fd->rec_cpu_num;
sz = sizeof(info);
if (copy_to_user(uinfo, &info, sz)) {
ret = -EFAULT;
goto bail;
}
ret = 0;
bail:
return ret;
}
static int qib_sdma_get_inflight(struct qib_user_sdma_queue *pq,
u32 __user *inflightp)
{
const u32 val = qib_user_sdma_inflight_counter(pq);
if (put_user(val, inflightp))
return -EFAULT;
return 0;
}
static int qib_sdma_get_complete(struct qib_pportdata *ppd,
struct qib_user_sdma_queue *pq,
u32 __user *completep)
{
u32 val;
int err;
if (!pq)
return -EINVAL;
err = qib_user_sdma_make_progress(ppd, pq);
if (err < 0)
return err;
val = qib_user_sdma_complete_counter(pq);
if (put_user(val, completep))
return -EFAULT;
return 0;
}
static int disarm_req_delay(struct qib_ctxtdata *rcd)
{
int ret = 0;
if (!usable(rcd->ppd)) {
int i;
/*
* if link is down, or otherwise not usable, delay
* the caller up to 30 seconds, so we don't thrash
* in trying to get the chip back to ACTIVE, and
* set flag so they make the call again.
*/
if (rcd->user_event_mask) {
/*
* subctxt_cnt is 0 if not shared, so do base
* separately, first, then remaining subctxt, if any
*/
set_bit(_QIB_EVENT_DISARM_BUFS_BIT,
&rcd->user_event_mask[0]);
for (i = 1; i < rcd->subctxt_cnt; i++)
set_bit(_QIB_EVENT_DISARM_BUFS_BIT,
&rcd->user_event_mask[i]);
}
for (i = 0; !usable(rcd->ppd) && i < 300; i++)
msleep(100);
ret = -ENETDOWN;
}
return ret;
}
/*
* Find all user contexts in use, and set the specified bit in their
* event mask.
* See also find_ctxt() for a similar use, that is specific to send buffers.
*/
int qib_set_uevent_bits(struct qib_pportdata *ppd, const int evtbit)
{
struct qib_ctxtdata *rcd;
unsigned ctxt;
int ret = 0;
unsigned long flags;
spin_lock_irqsave(&ppd->dd->uctxt_lock, flags);
for (ctxt = ppd->dd->first_user_ctxt; ctxt < ppd->dd->cfgctxts;
ctxt++) {
rcd = ppd->dd->rcd[ctxt];
if (!rcd)
continue;
if (rcd->user_event_mask) {
int i;
/*
* subctxt_cnt is 0 if not shared, so do base
* separately, first, then remaining subctxt, if any
*/
set_bit(evtbit, &rcd->user_event_mask[0]);
for (i = 1; i < rcd->subctxt_cnt; i++)
set_bit(evtbit, &rcd->user_event_mask[i]);
}
ret = 1;
break;
}
spin_unlock_irqrestore(&ppd->dd->uctxt_lock, flags);
return ret;
}
/*
* clear the event notifier events for this context.
* For the DISARM_BUFS case, we also take action (this obsoletes
* the older QIB_CMD_DISARM_BUFS, but we keep it for backwards
* compatibility.
* Other bits don't currently require actions, just atomically clear.
* User process then performs actions appropriate to bit having been
* set, if desired, and checks again in future.
*/
static int qib_user_event_ack(struct qib_ctxtdata *rcd, int subctxt,
unsigned long events)
{
int ret = 0, i;
for (i = 0; i <= _QIB_MAX_EVENT_BIT; i++) {
if (!test_bit(i, &events))
continue;
if (i == _QIB_EVENT_DISARM_BUFS_BIT) {
(void)qib_disarm_piobufs_ifneeded(rcd);
ret = disarm_req_delay(rcd);
} else
clear_bit(i, &rcd->user_event_mask[subctxt]);
}
return ret;
}
static ssize_t qib_write(struct file *fp, const char __user *data,
size_t count, loff_t *off)
{
const struct qib_cmd __user *ucmd;
struct qib_ctxtdata *rcd;
const void __user *src;
size_t consumed, copy = 0;
struct qib_cmd cmd;
ssize_t ret = 0;
void *dest;
if (count < sizeof(cmd.type)) {
ret = -EINVAL;
goto bail;
}
ucmd = (const struct qib_cmd __user *) data;
if (copy_from_user(&cmd.type, &ucmd->type, sizeof(cmd.type))) {
ret = -EFAULT;
goto bail;
}
consumed = sizeof(cmd.type);
switch (cmd.type) {
case QIB_CMD_ASSIGN_CTXT:
case QIB_CMD_USER_INIT:
copy = sizeof(cmd.cmd.user_info);
dest = &cmd.cmd.user_info;
src = &ucmd->cmd.user_info;
break;
case QIB_CMD_RECV_CTRL:
copy = sizeof(cmd.cmd.recv_ctrl);
dest = &cmd.cmd.recv_ctrl;
src = &ucmd->cmd.recv_ctrl;
break;
case QIB_CMD_CTXT_INFO:
copy = sizeof(cmd.cmd.ctxt_info);
dest = &cmd.cmd.ctxt_info;
src = &ucmd->cmd.ctxt_info;
break;
case QIB_CMD_TID_UPDATE:
case QIB_CMD_TID_FREE:
copy = sizeof(cmd.cmd.tid_info);
dest = &cmd.cmd.tid_info;
src = &ucmd->cmd.tid_info;
break;
case QIB_CMD_SET_PART_KEY:
copy = sizeof(cmd.cmd.part_key);
dest = &cmd.cmd.part_key;
src = &ucmd->cmd.part_key;
break;
case QIB_CMD_DISARM_BUFS:
case QIB_CMD_PIOAVAILUPD: /* force an update of PIOAvail reg */
copy = 0;
src = NULL;
dest = NULL;
break;
case QIB_CMD_POLL_TYPE:
copy = sizeof(cmd.cmd.poll_type);
dest = &cmd.cmd.poll_type;
src = &ucmd->cmd.poll_type;
break;
case QIB_CMD_ARMLAUNCH_CTRL:
copy = sizeof(cmd.cmd.armlaunch_ctrl);
dest = &cmd.cmd.armlaunch_ctrl;
src = &ucmd->cmd.armlaunch_ctrl;
break;
case QIB_CMD_SDMA_INFLIGHT:
copy = sizeof(cmd.cmd.sdma_inflight);
dest = &cmd.cmd.sdma_inflight;
src = &ucmd->cmd.sdma_inflight;
break;
case QIB_CMD_SDMA_COMPLETE:
copy = sizeof(cmd.cmd.sdma_complete);
dest = &cmd.cmd.sdma_complete;
src = &ucmd->cmd.sdma_complete;
break;
case QIB_CMD_ACK_EVENT:
copy = sizeof(cmd.cmd.event_mask);
dest = &cmd.cmd.event_mask;
src = &ucmd->cmd.event_mask;
break;
default:
ret = -EINVAL;
goto bail;
}
if (copy) {
if ((count - consumed) < copy) {
ret = -EINVAL;
goto bail;
}
if (copy_from_user(dest, src, copy)) {
ret = -EFAULT;
goto bail;
}
consumed += copy;
}
rcd = ctxt_fp(fp);
if (!rcd && cmd.type != QIB_CMD_ASSIGN_CTXT) {
ret = -EINVAL;
goto bail;
}
switch (cmd.type) {
case QIB_CMD_ASSIGN_CTXT:
ret = qib_assign_ctxt(fp, &cmd.cmd.user_info);
if (ret)
goto bail;
break;
case QIB_CMD_USER_INIT:
ret = qib_do_user_init(fp, &cmd.cmd.user_info);
if (ret)
goto bail;
ret = qib_get_base_info(fp, (void __user *) (unsigned long)
cmd.cmd.user_info.spu_base_info,
cmd.cmd.user_info.spu_base_info_size);
break;
case QIB_CMD_RECV_CTRL:
ret = qib_manage_rcvq(rcd, subctxt_fp(fp), cmd.cmd.recv_ctrl);
break;
case QIB_CMD_CTXT_INFO:
ret = qib_ctxt_info(fp, (struct qib_ctxt_info __user *)
(unsigned long) cmd.cmd.ctxt_info);
break;
case QIB_CMD_TID_UPDATE:
ret = qib_tid_update(rcd, fp, &cmd.cmd.tid_info);
break;
case QIB_CMD_TID_FREE:
ret = qib_tid_free(rcd, subctxt_fp(fp), &cmd.cmd.tid_info);
break;
case QIB_CMD_SET_PART_KEY:
ret = qib_set_part_key(rcd, cmd.cmd.part_key);
break;
case QIB_CMD_DISARM_BUFS:
(void)qib_disarm_piobufs_ifneeded(rcd);
ret = disarm_req_delay(rcd);
break;
case QIB_CMD_PIOAVAILUPD:
qib_force_pio_avail_update(rcd->dd);
break;
case QIB_CMD_POLL_TYPE:
rcd->poll_type = cmd.cmd.poll_type;
break;
case QIB_CMD_ARMLAUNCH_CTRL:
rcd->dd->f_set_armlaunch(rcd->dd, cmd.cmd.armlaunch_ctrl);
break;
case QIB_CMD_SDMA_INFLIGHT:
ret = qib_sdma_get_inflight(user_sdma_queue_fp(fp),
(u32 __user *) (unsigned long)
cmd.cmd.sdma_inflight);
break;
case QIB_CMD_SDMA_COMPLETE:
ret = qib_sdma_get_complete(rcd->ppd,
user_sdma_queue_fp(fp),
(u32 __user *) (unsigned long)
cmd.cmd.sdma_complete);
break;
case QIB_CMD_ACK_EVENT:
ret = qib_user_event_ack(rcd, subctxt_fp(fp),
cmd.cmd.event_mask);
break;
}
if (ret >= 0)
ret = consumed;
bail:
return ret;
}
static ssize_t qib_write_iter(struct kiocb *iocb, struct iov_iter *from)
{
struct qib_filedata *fp = iocb->ki_filp->private_data;
struct qib_ctxtdata *rcd = ctxt_fp(iocb->ki_filp);
struct qib_user_sdma_queue *pq = fp->pq;
if (!iter_is_iovec(from) || !from->nr_segs || !pq)
return -EINVAL;
return qib_user_sdma_writev(rcd, pq, from->iov, from->nr_segs);
}
static struct class *qib_class;
static dev_t qib_dev;
int qib_cdev_init(int minor, const char *name,
const struct file_operations *fops,
struct cdev **cdevp, struct device **devp)
{
const dev_t dev = MKDEV(MAJOR(qib_dev), minor);
struct cdev *cdev;
struct device *device = NULL;
int ret;
cdev = cdev_alloc();
if (!cdev) {
pr_err("Could not allocate cdev for minor %d, %s\n",
minor, name);
ret = -ENOMEM;
goto done;
}
cdev->owner = THIS_MODULE;
cdev->ops = fops;
kobject_set_name(&cdev->kobj, name);
ret = cdev_add(cdev, dev, 1);
if (ret < 0) {
pr_err("Could not add cdev for minor %d, %s (err %d)\n",
minor, name, -ret);
goto err_cdev;
}
device = device_create(qib_class, NULL, dev, NULL, "%s", name);
if (!IS_ERR(device))
goto done;
ret = PTR_ERR(device);
device = NULL;
pr_err("Could not create device for minor %d, %s (err %d)\n",
minor, name, -ret);
err_cdev:
cdev_del(cdev);
cdev = NULL;
done:
*cdevp = cdev;
*devp = device;
return ret;
}
void qib_cdev_cleanup(struct cdev **cdevp, struct device **devp)
{
struct device *device = *devp;
if (device) {
device_unregister(device);
*devp = NULL;
}
if (*cdevp) {
cdev_del(*cdevp);
*cdevp = NULL;
}
}
static struct cdev *wildcard_cdev;
static struct device *wildcard_device;
int __init qib_dev_init(void)
{
int ret;
ret = alloc_chrdev_region(&qib_dev, 0, QIB_NMINORS, QIB_DRV_NAME);
if (ret < 0) {
pr_err("Could not allocate chrdev region (err %d)\n", -ret);
goto done;
}
qib_class = class_create(THIS_MODULE, "ipath");
if (IS_ERR(qib_class)) {
ret = PTR_ERR(qib_class);
pr_err("Could not create device class (err %d)\n", -ret);
unregister_chrdev_region(qib_dev, QIB_NMINORS);
}
done:
return ret;
}
void qib_dev_cleanup(void)
{
if (qib_class) {
class_destroy(qib_class);
qib_class = NULL;
}
unregister_chrdev_region(qib_dev, QIB_NMINORS);
}
static atomic_t user_count = ATOMIC_INIT(0);
static void qib_user_remove(struct qib_devdata *dd)
{
if (atomic_dec_return(&user_count) == 0)
qib_cdev_cleanup(&wildcard_cdev, &wildcard_device);
qib_cdev_cleanup(&dd->user_cdev, &dd->user_device);
}
static int qib_user_add(struct qib_devdata *dd)
{
char name[10];
int ret;
if (atomic_inc_return(&user_count) == 1) {
ret = qib_cdev_init(0, "ipath", &qib_file_ops,
&wildcard_cdev, &wildcard_device);
if (ret)
goto done;
}
snprintf(name, sizeof(name), "ipath%d", dd->unit);
ret = qib_cdev_init(dd->unit + 1, name, &qib_file_ops,
&dd->user_cdev, &dd->user_device);
if (ret)
qib_user_remove(dd);
done:
return ret;
}
/*
* Create per-unit files in /dev
*/
int qib_device_create(struct qib_devdata *dd)
{
int r, ret;
r = qib_user_add(dd);
ret = qib_diag_add(dd);
if (r && !ret)
ret = r;
return ret;
}
/*
* Remove per-unit files in /dev
* void, core kernel returns no errors for this stuff
*/
void qib_device_remove(struct qib_devdata *dd)
{
qib_user_remove(dd);
qib_diag_remove(dd);
}
| gpl-2.0 |
gnehzuil/ali_kernel | drivers/infiniband/core/mad_rmpp.c | 593 | 27594 | /*
* Copyright (c) 2005 Intel Inc. All rights reserved.
* Copyright (c) 2005-2006 Voltaire, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - 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.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "mad_priv.h"
#include "mad_rmpp.h"
enum rmpp_state {
RMPP_STATE_ACTIVE,
RMPP_STATE_TIMEOUT,
RMPP_STATE_COMPLETE,
RMPP_STATE_CANCELING
};
struct mad_rmpp_recv {
struct ib_mad_agent_private *agent;
struct list_head list;
struct delayed_work timeout_work;
struct delayed_work cleanup_work;
struct completion comp;
enum rmpp_state state;
spinlock_t lock;
atomic_t refcount;
struct ib_ah *ah;
struct ib_mad_recv_wc *rmpp_wc;
struct ib_mad_recv_buf *cur_seg_buf;
int last_ack;
int seg_num;
int newwin;
int repwin;
__be64 tid;
u32 src_qp;
u16 slid;
u8 mgmt_class;
u8 class_version;
u8 method;
};
static inline void deref_rmpp_recv(struct mad_rmpp_recv *rmpp_recv)
{
if (atomic_dec_and_test(&rmpp_recv->refcount))
complete(&rmpp_recv->comp);
}
static void destroy_rmpp_recv(struct mad_rmpp_recv *rmpp_recv)
{
deref_rmpp_recv(rmpp_recv);
wait_for_completion(&rmpp_recv->comp);
ib_destroy_ah(rmpp_recv->ah);
kfree(rmpp_recv);
}
void ib_cancel_rmpp_recvs(struct ib_mad_agent_private *agent)
{
struct mad_rmpp_recv *rmpp_recv, *temp_rmpp_recv;
unsigned long flags;
spin_lock_irqsave(&agent->lock, flags);
list_for_each_entry(rmpp_recv, &agent->rmpp_list, list) {
if (rmpp_recv->state != RMPP_STATE_COMPLETE)
ib_free_recv_mad(rmpp_recv->rmpp_wc);
rmpp_recv->state = RMPP_STATE_CANCELING;
}
spin_unlock_irqrestore(&agent->lock, flags);
list_for_each_entry(rmpp_recv, &agent->rmpp_list, list) {
cancel_delayed_work(&rmpp_recv->timeout_work);
cancel_delayed_work(&rmpp_recv->cleanup_work);
}
flush_workqueue(agent->qp_info->port_priv->wq);
list_for_each_entry_safe(rmpp_recv, temp_rmpp_recv,
&agent->rmpp_list, list) {
list_del(&rmpp_recv->list);
destroy_rmpp_recv(rmpp_recv);
}
}
static void format_ack(struct ib_mad_send_buf *msg,
struct ib_rmpp_mad *data,
struct mad_rmpp_recv *rmpp_recv)
{
struct ib_rmpp_mad *ack = msg->mad;
unsigned long flags;
memcpy(ack, &data->mad_hdr, msg->hdr_len);
ack->mad_hdr.method ^= IB_MGMT_METHOD_RESP;
ack->rmpp_hdr.rmpp_type = IB_MGMT_RMPP_TYPE_ACK;
ib_set_rmpp_flags(&ack->rmpp_hdr, IB_MGMT_RMPP_FLAG_ACTIVE);
spin_lock_irqsave(&rmpp_recv->lock, flags);
rmpp_recv->last_ack = rmpp_recv->seg_num;
ack->rmpp_hdr.seg_num = cpu_to_be32(rmpp_recv->seg_num);
ack->rmpp_hdr.paylen_newwin = cpu_to_be32(rmpp_recv->newwin);
spin_unlock_irqrestore(&rmpp_recv->lock, flags);
}
static void ack_recv(struct mad_rmpp_recv *rmpp_recv,
struct ib_mad_recv_wc *recv_wc)
{
struct ib_mad_send_buf *msg;
int ret, hdr_len;
hdr_len = ib_get_mad_data_offset(recv_wc->recv_buf.mad->mad_hdr.mgmt_class);
msg = ib_create_send_mad(&rmpp_recv->agent->agent, recv_wc->wc->src_qp,
recv_wc->wc->pkey_index, 1, hdr_len,
0, GFP_KERNEL);
if (IS_ERR(msg))
return;
format_ack(msg, (struct ib_rmpp_mad *) recv_wc->recv_buf.mad, rmpp_recv);
msg->ah = rmpp_recv->ah;
ret = ib_post_send_mad(msg, NULL);
if (ret)
ib_free_send_mad(msg);
}
static struct ib_mad_send_buf *alloc_response_msg(struct ib_mad_agent *agent,
struct ib_mad_recv_wc *recv_wc)
{
struct ib_mad_send_buf *msg;
struct ib_ah *ah;
int hdr_len;
ah = ib_create_ah_from_wc(agent->qp->pd, recv_wc->wc,
recv_wc->recv_buf.grh, agent->port_num);
if (IS_ERR(ah))
return (void *) ah;
hdr_len = ib_get_mad_data_offset(recv_wc->recv_buf.mad->mad_hdr.mgmt_class);
msg = ib_create_send_mad(agent, recv_wc->wc->src_qp,
recv_wc->wc->pkey_index, 1,
hdr_len, 0, GFP_KERNEL);
if (IS_ERR(msg))
ib_destroy_ah(ah);
else {
msg->ah = ah;
msg->context[0] = ah;
}
return msg;
}
static void ack_ds_ack(struct ib_mad_agent_private *agent,
struct ib_mad_recv_wc *recv_wc)
{
struct ib_mad_send_buf *msg;
struct ib_rmpp_mad *rmpp_mad;
int ret;
msg = alloc_response_msg(&agent->agent, recv_wc);
if (IS_ERR(msg))
return;
rmpp_mad = msg->mad;
memcpy(rmpp_mad, recv_wc->recv_buf.mad, msg->hdr_len);
rmpp_mad->mad_hdr.method ^= IB_MGMT_METHOD_RESP;
ib_set_rmpp_flags(&rmpp_mad->rmpp_hdr, IB_MGMT_RMPP_FLAG_ACTIVE);
rmpp_mad->rmpp_hdr.seg_num = 0;
rmpp_mad->rmpp_hdr.paylen_newwin = cpu_to_be32(1);
ret = ib_post_send_mad(msg, NULL);
if (ret) {
ib_destroy_ah(msg->ah);
ib_free_send_mad(msg);
}
}
void ib_rmpp_send_handler(struct ib_mad_send_wc *mad_send_wc)
{
if (mad_send_wc->send_buf->context[0] == mad_send_wc->send_buf->ah)
ib_destroy_ah(mad_send_wc->send_buf->ah);
ib_free_send_mad(mad_send_wc->send_buf);
}
static void nack_recv(struct ib_mad_agent_private *agent,
struct ib_mad_recv_wc *recv_wc, u8 rmpp_status)
{
struct ib_mad_send_buf *msg;
struct ib_rmpp_mad *rmpp_mad;
int ret;
msg = alloc_response_msg(&agent->agent, recv_wc);
if (IS_ERR(msg))
return;
rmpp_mad = msg->mad;
memcpy(rmpp_mad, recv_wc->recv_buf.mad, msg->hdr_len);
rmpp_mad->mad_hdr.method ^= IB_MGMT_METHOD_RESP;
rmpp_mad->rmpp_hdr.rmpp_version = IB_MGMT_RMPP_VERSION;
rmpp_mad->rmpp_hdr.rmpp_type = IB_MGMT_RMPP_TYPE_ABORT;
ib_set_rmpp_flags(&rmpp_mad->rmpp_hdr, IB_MGMT_RMPP_FLAG_ACTIVE);
rmpp_mad->rmpp_hdr.rmpp_status = rmpp_status;
rmpp_mad->rmpp_hdr.seg_num = 0;
rmpp_mad->rmpp_hdr.paylen_newwin = 0;
ret = ib_post_send_mad(msg, NULL);
if (ret) {
ib_destroy_ah(msg->ah);
ib_free_send_mad(msg);
}
}
static void recv_timeout_handler(struct work_struct *work)
{
struct mad_rmpp_recv *rmpp_recv =
container_of(work, struct mad_rmpp_recv, timeout_work.work);
struct ib_mad_recv_wc *rmpp_wc;
unsigned long flags;
spin_lock_irqsave(&rmpp_recv->agent->lock, flags);
if (rmpp_recv->state != RMPP_STATE_ACTIVE) {
spin_unlock_irqrestore(&rmpp_recv->agent->lock, flags);
return;
}
rmpp_recv->state = RMPP_STATE_TIMEOUT;
list_del(&rmpp_recv->list);
spin_unlock_irqrestore(&rmpp_recv->agent->lock, flags);
rmpp_wc = rmpp_recv->rmpp_wc;
nack_recv(rmpp_recv->agent, rmpp_wc, IB_MGMT_RMPP_STATUS_T2L);
destroy_rmpp_recv(rmpp_recv);
ib_free_recv_mad(rmpp_wc);
}
static void recv_cleanup_handler(struct work_struct *work)
{
struct mad_rmpp_recv *rmpp_recv =
container_of(work, struct mad_rmpp_recv, cleanup_work.work);
unsigned long flags;
spin_lock_irqsave(&rmpp_recv->agent->lock, flags);
if (rmpp_recv->state == RMPP_STATE_CANCELING) {
spin_unlock_irqrestore(&rmpp_recv->agent->lock, flags);
return;
}
list_del(&rmpp_recv->list);
spin_unlock_irqrestore(&rmpp_recv->agent->lock, flags);
destroy_rmpp_recv(rmpp_recv);
}
static struct mad_rmpp_recv *
create_rmpp_recv(struct ib_mad_agent_private *agent,
struct ib_mad_recv_wc *mad_recv_wc)
{
struct mad_rmpp_recv *rmpp_recv;
struct ib_mad_hdr *mad_hdr;
rmpp_recv = kmalloc(sizeof *rmpp_recv, GFP_KERNEL);
if (!rmpp_recv)
return NULL;
rmpp_recv->ah = ib_create_ah_from_wc(agent->agent.qp->pd,
mad_recv_wc->wc,
mad_recv_wc->recv_buf.grh,
agent->agent.port_num);
if (IS_ERR(rmpp_recv->ah))
goto error;
rmpp_recv->agent = agent;
init_completion(&rmpp_recv->comp);
INIT_DELAYED_WORK(&rmpp_recv->timeout_work, recv_timeout_handler);
INIT_DELAYED_WORK(&rmpp_recv->cleanup_work, recv_cleanup_handler);
spin_lock_init(&rmpp_recv->lock);
rmpp_recv->state = RMPP_STATE_ACTIVE;
atomic_set(&rmpp_recv->refcount, 1);
rmpp_recv->rmpp_wc = mad_recv_wc;
rmpp_recv->cur_seg_buf = &mad_recv_wc->recv_buf;
rmpp_recv->newwin = 1;
rmpp_recv->seg_num = 1;
rmpp_recv->last_ack = 0;
rmpp_recv->repwin = 1;
mad_hdr = &mad_recv_wc->recv_buf.mad->mad_hdr;
rmpp_recv->tid = mad_hdr->tid;
rmpp_recv->src_qp = mad_recv_wc->wc->src_qp;
rmpp_recv->slid = mad_recv_wc->wc->slid;
rmpp_recv->mgmt_class = mad_hdr->mgmt_class;
rmpp_recv->class_version = mad_hdr->class_version;
rmpp_recv->method = mad_hdr->method;
return rmpp_recv;
error: kfree(rmpp_recv);
return NULL;
}
static struct mad_rmpp_recv *
find_rmpp_recv(struct ib_mad_agent_private *agent,
struct ib_mad_recv_wc *mad_recv_wc)
{
struct mad_rmpp_recv *rmpp_recv;
struct ib_mad_hdr *mad_hdr = &mad_recv_wc->recv_buf.mad->mad_hdr;
list_for_each_entry(rmpp_recv, &agent->rmpp_list, list) {
if (rmpp_recv->tid == mad_hdr->tid &&
rmpp_recv->src_qp == mad_recv_wc->wc->src_qp &&
rmpp_recv->slid == mad_recv_wc->wc->slid &&
rmpp_recv->mgmt_class == mad_hdr->mgmt_class &&
rmpp_recv->class_version == mad_hdr->class_version &&
rmpp_recv->method == mad_hdr->method)
return rmpp_recv;
}
return NULL;
}
static struct mad_rmpp_recv *
acquire_rmpp_recv(struct ib_mad_agent_private *agent,
struct ib_mad_recv_wc *mad_recv_wc)
{
struct mad_rmpp_recv *rmpp_recv;
unsigned long flags;
spin_lock_irqsave(&agent->lock, flags);
rmpp_recv = find_rmpp_recv(agent, mad_recv_wc);
if (rmpp_recv)
atomic_inc(&rmpp_recv->refcount);
spin_unlock_irqrestore(&agent->lock, flags);
return rmpp_recv;
}
static struct mad_rmpp_recv *
insert_rmpp_recv(struct ib_mad_agent_private *agent,
struct mad_rmpp_recv *rmpp_recv)
{
struct mad_rmpp_recv *cur_rmpp_recv;
cur_rmpp_recv = find_rmpp_recv(agent, rmpp_recv->rmpp_wc);
if (!cur_rmpp_recv)
list_add_tail(&rmpp_recv->list, &agent->rmpp_list);
return cur_rmpp_recv;
}
static inline int get_last_flag(struct ib_mad_recv_buf *seg)
{
struct ib_rmpp_mad *rmpp_mad;
rmpp_mad = (struct ib_rmpp_mad *) seg->mad;
return ib_get_rmpp_flags(&rmpp_mad->rmpp_hdr) & IB_MGMT_RMPP_FLAG_LAST;
}
static inline int get_seg_num(struct ib_mad_recv_buf *seg)
{
struct ib_rmpp_mad *rmpp_mad;
rmpp_mad = (struct ib_rmpp_mad *) seg->mad;
return be32_to_cpu(rmpp_mad->rmpp_hdr.seg_num);
}
static inline struct ib_mad_recv_buf * get_next_seg(struct list_head *rmpp_list,
struct ib_mad_recv_buf *seg)
{
if (seg->list.next == rmpp_list)
return NULL;
return container_of(seg->list.next, struct ib_mad_recv_buf, list);
}
static inline int window_size(struct ib_mad_agent_private *agent)
{
return max(agent->qp_info->recv_queue.max_active >> 3, 1);
}
static struct ib_mad_recv_buf * find_seg_location(struct list_head *rmpp_list,
int seg_num)
{
struct ib_mad_recv_buf *seg_buf;
int cur_seg_num;
list_for_each_entry_reverse(seg_buf, rmpp_list, list) {
cur_seg_num = get_seg_num(seg_buf);
if (seg_num > cur_seg_num)
return seg_buf;
if (seg_num == cur_seg_num)
break;
}
return NULL;
}
static void update_seg_num(struct mad_rmpp_recv *rmpp_recv,
struct ib_mad_recv_buf *new_buf)
{
struct list_head *rmpp_list = &rmpp_recv->rmpp_wc->rmpp_list;
while (new_buf && (get_seg_num(new_buf) == rmpp_recv->seg_num + 1)) {
rmpp_recv->cur_seg_buf = new_buf;
rmpp_recv->seg_num++;
new_buf = get_next_seg(rmpp_list, new_buf);
}
}
static inline int get_mad_len(struct mad_rmpp_recv *rmpp_recv)
{
struct ib_rmpp_mad *rmpp_mad;
int hdr_size, data_size, pad;
rmpp_mad = (struct ib_rmpp_mad *)rmpp_recv->cur_seg_buf->mad;
hdr_size = ib_get_mad_data_offset(rmpp_mad->mad_hdr.mgmt_class);
data_size = sizeof(struct ib_rmpp_mad) - hdr_size;
pad = IB_MGMT_RMPP_DATA - be32_to_cpu(rmpp_mad->rmpp_hdr.paylen_newwin);
if (pad > IB_MGMT_RMPP_DATA || pad < 0)
pad = 0;
return hdr_size + rmpp_recv->seg_num * data_size - pad;
}
static struct ib_mad_recv_wc * complete_rmpp(struct mad_rmpp_recv *rmpp_recv)
{
struct ib_mad_recv_wc *rmpp_wc;
ack_recv(rmpp_recv, rmpp_recv->rmpp_wc);
if (rmpp_recv->seg_num > 1)
cancel_delayed_work(&rmpp_recv->timeout_work);
rmpp_wc = rmpp_recv->rmpp_wc;
rmpp_wc->mad_len = get_mad_len(rmpp_recv);
/* 10 seconds until we can find the packet lifetime */
queue_delayed_work(rmpp_recv->agent->qp_info->port_priv->wq,
&rmpp_recv->cleanup_work, msecs_to_jiffies(10000));
return rmpp_wc;
}
static struct ib_mad_recv_wc *
continue_rmpp(struct ib_mad_agent_private *agent,
struct ib_mad_recv_wc *mad_recv_wc)
{
struct mad_rmpp_recv *rmpp_recv;
struct ib_mad_recv_buf *prev_buf;
struct ib_mad_recv_wc *done_wc;
int seg_num;
unsigned long flags;
rmpp_recv = acquire_rmpp_recv(agent, mad_recv_wc);
if (!rmpp_recv)
goto drop1;
seg_num = get_seg_num(&mad_recv_wc->recv_buf);
spin_lock_irqsave(&rmpp_recv->lock, flags);
if ((rmpp_recv->state == RMPP_STATE_TIMEOUT) ||
(seg_num > rmpp_recv->newwin))
goto drop3;
if ((seg_num <= rmpp_recv->last_ack) ||
(rmpp_recv->state == RMPP_STATE_COMPLETE)) {
spin_unlock_irqrestore(&rmpp_recv->lock, flags);
ack_recv(rmpp_recv, mad_recv_wc);
goto drop2;
}
prev_buf = find_seg_location(&rmpp_recv->rmpp_wc->rmpp_list, seg_num);
if (!prev_buf)
goto drop3;
done_wc = NULL;
list_add(&mad_recv_wc->recv_buf.list, &prev_buf->list);
if (rmpp_recv->cur_seg_buf == prev_buf) {
update_seg_num(rmpp_recv, &mad_recv_wc->recv_buf);
if (get_last_flag(rmpp_recv->cur_seg_buf)) {
rmpp_recv->state = RMPP_STATE_COMPLETE;
spin_unlock_irqrestore(&rmpp_recv->lock, flags);
done_wc = complete_rmpp(rmpp_recv);
goto out;
} else if (rmpp_recv->seg_num == rmpp_recv->newwin) {
rmpp_recv->newwin += window_size(agent);
spin_unlock_irqrestore(&rmpp_recv->lock, flags);
ack_recv(rmpp_recv, mad_recv_wc);
goto out;
}
}
spin_unlock_irqrestore(&rmpp_recv->lock, flags);
out:
deref_rmpp_recv(rmpp_recv);
return done_wc;
drop3: spin_unlock_irqrestore(&rmpp_recv->lock, flags);
drop2: deref_rmpp_recv(rmpp_recv);
drop1: ib_free_recv_mad(mad_recv_wc);
return NULL;
}
static struct ib_mad_recv_wc *
start_rmpp(struct ib_mad_agent_private *agent,
struct ib_mad_recv_wc *mad_recv_wc)
{
struct mad_rmpp_recv *rmpp_recv;
unsigned long flags;
rmpp_recv = create_rmpp_recv(agent, mad_recv_wc);
if (!rmpp_recv) {
ib_free_recv_mad(mad_recv_wc);
return NULL;
}
spin_lock_irqsave(&agent->lock, flags);
if (insert_rmpp_recv(agent, rmpp_recv)) {
spin_unlock_irqrestore(&agent->lock, flags);
/* duplicate first MAD */
destroy_rmpp_recv(rmpp_recv);
return continue_rmpp(agent, mad_recv_wc);
}
atomic_inc(&rmpp_recv->refcount);
if (get_last_flag(&mad_recv_wc->recv_buf)) {
rmpp_recv->state = RMPP_STATE_COMPLETE;
spin_unlock_irqrestore(&agent->lock, flags);
complete_rmpp(rmpp_recv);
} else {
spin_unlock_irqrestore(&agent->lock, flags);
/* 40 seconds until we can find the packet lifetimes */
queue_delayed_work(agent->qp_info->port_priv->wq,
&rmpp_recv->timeout_work,
msecs_to_jiffies(40000));
rmpp_recv->newwin += window_size(agent);
ack_recv(rmpp_recv, mad_recv_wc);
mad_recv_wc = NULL;
}
deref_rmpp_recv(rmpp_recv);
return mad_recv_wc;
}
static int send_next_seg(struct ib_mad_send_wr_private *mad_send_wr)
{
struct ib_rmpp_mad *rmpp_mad;
int timeout;
u32 paylen = 0;
rmpp_mad = mad_send_wr->send_buf.mad;
ib_set_rmpp_flags(&rmpp_mad->rmpp_hdr, IB_MGMT_RMPP_FLAG_ACTIVE);
rmpp_mad->rmpp_hdr.seg_num = cpu_to_be32(++mad_send_wr->seg_num);
if (mad_send_wr->seg_num == 1) {
rmpp_mad->rmpp_hdr.rmpp_rtime_flags |= IB_MGMT_RMPP_FLAG_FIRST;
paylen = mad_send_wr->send_buf.seg_count * IB_MGMT_RMPP_DATA -
mad_send_wr->pad;
}
if (mad_send_wr->seg_num == mad_send_wr->send_buf.seg_count) {
rmpp_mad->rmpp_hdr.rmpp_rtime_flags |= IB_MGMT_RMPP_FLAG_LAST;
paylen = IB_MGMT_RMPP_DATA - mad_send_wr->pad;
}
rmpp_mad->rmpp_hdr.paylen_newwin = cpu_to_be32(paylen);
/* 2 seconds for an ACK until we can find the packet lifetime */
timeout = mad_send_wr->send_buf.timeout_ms;
if (!timeout || timeout > 2000)
mad_send_wr->timeout = msecs_to_jiffies(2000);
return ib_send_mad(mad_send_wr);
}
static void abort_send(struct ib_mad_agent_private *agent,
struct ib_mad_recv_wc *mad_recv_wc, u8 rmpp_status)
{
struct ib_mad_send_wr_private *mad_send_wr;
struct ib_mad_send_wc wc;
unsigned long flags;
spin_lock_irqsave(&agent->lock, flags);
mad_send_wr = ib_find_send_mad(agent, mad_recv_wc);
if (!mad_send_wr)
goto out; /* Unmatched send */
if ((mad_send_wr->last_ack == mad_send_wr->send_buf.seg_count) ||
(!mad_send_wr->timeout) || (mad_send_wr->status != IB_WC_SUCCESS))
goto out; /* Send is already done */
ib_mark_mad_done(mad_send_wr);
spin_unlock_irqrestore(&agent->lock, flags);
wc.status = IB_WC_REM_ABORT_ERR;
wc.vendor_err = rmpp_status;
wc.send_buf = &mad_send_wr->send_buf;
ib_mad_complete_send_wr(mad_send_wr, &wc);
return;
out:
spin_unlock_irqrestore(&agent->lock, flags);
}
static inline void adjust_last_ack(struct ib_mad_send_wr_private *wr,
int seg_num)
{
struct list_head *list;
wr->last_ack = seg_num;
list = &wr->last_ack_seg->list;
list_for_each_entry(wr->last_ack_seg, list, list)
if (wr->last_ack_seg->num == seg_num)
break;
}
static void process_ds_ack(struct ib_mad_agent_private *agent,
struct ib_mad_recv_wc *mad_recv_wc, int newwin)
{
struct mad_rmpp_recv *rmpp_recv;
rmpp_recv = find_rmpp_recv(agent, mad_recv_wc);
if (rmpp_recv && rmpp_recv->state == RMPP_STATE_COMPLETE)
rmpp_recv->repwin = newwin;
}
static void process_rmpp_ack(struct ib_mad_agent_private *agent,
struct ib_mad_recv_wc *mad_recv_wc)
{
struct ib_mad_send_wr_private *mad_send_wr;
struct ib_rmpp_mad *rmpp_mad;
unsigned long flags;
int seg_num, newwin, ret;
rmpp_mad = (struct ib_rmpp_mad *)mad_recv_wc->recv_buf.mad;
if (rmpp_mad->rmpp_hdr.rmpp_status) {
abort_send(agent, mad_recv_wc, IB_MGMT_RMPP_STATUS_BAD_STATUS);
nack_recv(agent, mad_recv_wc, IB_MGMT_RMPP_STATUS_BAD_STATUS);
return;
}
seg_num = be32_to_cpu(rmpp_mad->rmpp_hdr.seg_num);
newwin = be32_to_cpu(rmpp_mad->rmpp_hdr.paylen_newwin);
if (newwin < seg_num) {
abort_send(agent, mad_recv_wc, IB_MGMT_RMPP_STATUS_W2S);
nack_recv(agent, mad_recv_wc, IB_MGMT_RMPP_STATUS_W2S);
return;
}
spin_lock_irqsave(&agent->lock, flags);
mad_send_wr = ib_find_send_mad(agent, mad_recv_wc);
if (!mad_send_wr) {
if (!seg_num)
process_ds_ack(agent, mad_recv_wc, newwin);
goto out; /* Unmatched or DS RMPP ACK */
}
if ((mad_send_wr->last_ack == mad_send_wr->send_buf.seg_count) &&
(mad_send_wr->timeout)) {
spin_unlock_irqrestore(&agent->lock, flags);
ack_ds_ack(agent, mad_recv_wc);
return; /* Repeated ACK for DS RMPP transaction */
}
if ((mad_send_wr->last_ack == mad_send_wr->send_buf.seg_count) ||
(!mad_send_wr->timeout) || (mad_send_wr->status != IB_WC_SUCCESS))
goto out; /* Send is already done */
if (seg_num > mad_send_wr->send_buf.seg_count ||
seg_num > mad_send_wr->newwin) {
spin_unlock_irqrestore(&agent->lock, flags);
abort_send(agent, mad_recv_wc, IB_MGMT_RMPP_STATUS_S2B);
nack_recv(agent, mad_recv_wc, IB_MGMT_RMPP_STATUS_S2B);
return;
}
if (newwin < mad_send_wr->newwin || seg_num < mad_send_wr->last_ack)
goto out; /* Old ACK */
if (seg_num > mad_send_wr->last_ack) {
adjust_last_ack(mad_send_wr, seg_num);
mad_send_wr->retries_left = mad_send_wr->max_retries;
}
mad_send_wr->newwin = newwin;
if (mad_send_wr->last_ack == mad_send_wr->send_buf.seg_count) {
/* If no response is expected, the ACK completes the send */
if (!mad_send_wr->send_buf.timeout_ms) {
struct ib_mad_send_wc wc;
ib_mark_mad_done(mad_send_wr);
spin_unlock_irqrestore(&agent->lock, flags);
wc.status = IB_WC_SUCCESS;
wc.vendor_err = 0;
wc.send_buf = &mad_send_wr->send_buf;
ib_mad_complete_send_wr(mad_send_wr, &wc);
return;
}
if (mad_send_wr->refcount == 1)
ib_reset_mad_timeout(mad_send_wr,
mad_send_wr->send_buf.timeout_ms);
spin_unlock_irqrestore(&agent->lock, flags);
ack_ds_ack(agent, mad_recv_wc);
return;
} else if (mad_send_wr->refcount == 1 &&
mad_send_wr->seg_num < mad_send_wr->newwin &&
mad_send_wr->seg_num < mad_send_wr->send_buf.seg_count) {
/* Send failure will just result in a timeout/retry */
ret = send_next_seg(mad_send_wr);
if (ret)
goto out;
mad_send_wr->refcount++;
list_move_tail(&mad_send_wr->agent_list,
&mad_send_wr->mad_agent_priv->send_list);
}
out:
spin_unlock_irqrestore(&agent->lock, flags);
}
static struct ib_mad_recv_wc *
process_rmpp_data(struct ib_mad_agent_private *agent,
struct ib_mad_recv_wc *mad_recv_wc)
{
struct ib_rmpp_hdr *rmpp_hdr;
u8 rmpp_status;
rmpp_hdr = &((struct ib_rmpp_mad *)mad_recv_wc->recv_buf.mad)->rmpp_hdr;
if (rmpp_hdr->rmpp_status) {
rmpp_status = IB_MGMT_RMPP_STATUS_BAD_STATUS;
goto bad;
}
if (rmpp_hdr->seg_num == cpu_to_be32(1)) {
if (!(ib_get_rmpp_flags(rmpp_hdr) & IB_MGMT_RMPP_FLAG_FIRST)) {
rmpp_status = IB_MGMT_RMPP_STATUS_BAD_SEG;
goto bad;
}
return start_rmpp(agent, mad_recv_wc);
} else {
if (ib_get_rmpp_flags(rmpp_hdr) & IB_MGMT_RMPP_FLAG_FIRST) {
rmpp_status = IB_MGMT_RMPP_STATUS_BAD_SEG;
goto bad;
}
return continue_rmpp(agent, mad_recv_wc);
}
bad:
nack_recv(agent, mad_recv_wc, rmpp_status);
ib_free_recv_mad(mad_recv_wc);
return NULL;
}
static void process_rmpp_stop(struct ib_mad_agent_private *agent,
struct ib_mad_recv_wc *mad_recv_wc)
{
struct ib_rmpp_mad *rmpp_mad;
rmpp_mad = (struct ib_rmpp_mad *)mad_recv_wc->recv_buf.mad;
if (rmpp_mad->rmpp_hdr.rmpp_status != IB_MGMT_RMPP_STATUS_RESX) {
abort_send(agent, mad_recv_wc, IB_MGMT_RMPP_STATUS_BAD_STATUS);
nack_recv(agent, mad_recv_wc, IB_MGMT_RMPP_STATUS_BAD_STATUS);
} else
abort_send(agent, mad_recv_wc, rmpp_mad->rmpp_hdr.rmpp_status);
}
static void process_rmpp_abort(struct ib_mad_agent_private *agent,
struct ib_mad_recv_wc *mad_recv_wc)
{
struct ib_rmpp_mad *rmpp_mad;
rmpp_mad = (struct ib_rmpp_mad *)mad_recv_wc->recv_buf.mad;
if (rmpp_mad->rmpp_hdr.rmpp_status < IB_MGMT_RMPP_STATUS_ABORT_MIN ||
rmpp_mad->rmpp_hdr.rmpp_status > IB_MGMT_RMPP_STATUS_ABORT_MAX) {
abort_send(agent, mad_recv_wc, IB_MGMT_RMPP_STATUS_BAD_STATUS);
nack_recv(agent, mad_recv_wc, IB_MGMT_RMPP_STATUS_BAD_STATUS);
} else
abort_send(agent, mad_recv_wc, rmpp_mad->rmpp_hdr.rmpp_status);
}
struct ib_mad_recv_wc *
ib_process_rmpp_recv_wc(struct ib_mad_agent_private *agent,
struct ib_mad_recv_wc *mad_recv_wc)
{
struct ib_rmpp_mad *rmpp_mad;
rmpp_mad = (struct ib_rmpp_mad *)mad_recv_wc->recv_buf.mad;
if (!(rmpp_mad->rmpp_hdr.rmpp_rtime_flags & IB_MGMT_RMPP_FLAG_ACTIVE))
return mad_recv_wc;
if (rmpp_mad->rmpp_hdr.rmpp_version != IB_MGMT_RMPP_VERSION) {
abort_send(agent, mad_recv_wc, IB_MGMT_RMPP_STATUS_UNV);
nack_recv(agent, mad_recv_wc, IB_MGMT_RMPP_STATUS_UNV);
goto out;
}
switch (rmpp_mad->rmpp_hdr.rmpp_type) {
case IB_MGMT_RMPP_TYPE_DATA:
return process_rmpp_data(agent, mad_recv_wc);
case IB_MGMT_RMPP_TYPE_ACK:
process_rmpp_ack(agent, mad_recv_wc);
break;
case IB_MGMT_RMPP_TYPE_STOP:
process_rmpp_stop(agent, mad_recv_wc);
break;
case IB_MGMT_RMPP_TYPE_ABORT:
process_rmpp_abort(agent, mad_recv_wc);
break;
default:
abort_send(agent, mad_recv_wc, IB_MGMT_RMPP_STATUS_BADT);
nack_recv(agent, mad_recv_wc, IB_MGMT_RMPP_STATUS_BADT);
break;
}
out:
ib_free_recv_mad(mad_recv_wc);
return NULL;
}
static int init_newwin(struct ib_mad_send_wr_private *mad_send_wr)
{
struct ib_mad_agent_private *agent = mad_send_wr->mad_agent_priv;
struct ib_mad_hdr *mad_hdr = mad_send_wr->send_buf.mad;
struct mad_rmpp_recv *rmpp_recv;
struct ib_ah_attr ah_attr;
unsigned long flags;
int newwin = 1;
if (!(mad_hdr->method & IB_MGMT_METHOD_RESP))
goto out;
spin_lock_irqsave(&agent->lock, flags);
list_for_each_entry(rmpp_recv, &agent->rmpp_list, list) {
if (rmpp_recv->tid != mad_hdr->tid ||
rmpp_recv->mgmt_class != mad_hdr->mgmt_class ||
rmpp_recv->class_version != mad_hdr->class_version ||
(rmpp_recv->method & IB_MGMT_METHOD_RESP))
continue;
if (ib_query_ah(mad_send_wr->send_buf.ah, &ah_attr))
continue;
if (rmpp_recv->slid == ah_attr.dlid) {
newwin = rmpp_recv->repwin;
break;
}
}
spin_unlock_irqrestore(&agent->lock, flags);
out:
return newwin;
}
int ib_send_rmpp_mad(struct ib_mad_send_wr_private *mad_send_wr)
{
struct ib_rmpp_mad *rmpp_mad;
int ret;
rmpp_mad = mad_send_wr->send_buf.mad;
if (!(ib_get_rmpp_flags(&rmpp_mad->rmpp_hdr) &
IB_MGMT_RMPP_FLAG_ACTIVE))
return IB_RMPP_RESULT_UNHANDLED;
if (rmpp_mad->rmpp_hdr.rmpp_type != IB_MGMT_RMPP_TYPE_DATA) {
mad_send_wr->seg_num = 1;
return IB_RMPP_RESULT_INTERNAL;
}
mad_send_wr->newwin = init_newwin(mad_send_wr);
/* We need to wait for the final ACK even if there isn't a response */
mad_send_wr->refcount += (mad_send_wr->timeout == 0);
ret = send_next_seg(mad_send_wr);
if (!ret)
return IB_RMPP_RESULT_CONSUMED;
return ret;
}
int ib_process_rmpp_send_wc(struct ib_mad_send_wr_private *mad_send_wr,
struct ib_mad_send_wc *mad_send_wc)
{
struct ib_rmpp_mad *rmpp_mad;
int ret;
rmpp_mad = mad_send_wr->send_buf.mad;
if (!(ib_get_rmpp_flags(&rmpp_mad->rmpp_hdr) &
IB_MGMT_RMPP_FLAG_ACTIVE))
return IB_RMPP_RESULT_UNHANDLED; /* RMPP not active */
if (rmpp_mad->rmpp_hdr.rmpp_type != IB_MGMT_RMPP_TYPE_DATA)
return IB_RMPP_RESULT_INTERNAL; /* ACK, STOP, or ABORT */
if (mad_send_wc->status != IB_WC_SUCCESS ||
mad_send_wr->status != IB_WC_SUCCESS)
return IB_RMPP_RESULT_PROCESSED; /* Canceled or send error */
if (!mad_send_wr->timeout)
return IB_RMPP_RESULT_PROCESSED; /* Response received */
if (mad_send_wr->last_ack == mad_send_wr->send_buf.seg_count) {
mad_send_wr->timeout =
msecs_to_jiffies(mad_send_wr->send_buf.timeout_ms);
return IB_RMPP_RESULT_PROCESSED; /* Send done */
}
if (mad_send_wr->seg_num == mad_send_wr->newwin ||
mad_send_wr->seg_num == mad_send_wr->send_buf.seg_count)
return IB_RMPP_RESULT_PROCESSED; /* Wait for ACK */
ret = send_next_seg(mad_send_wr);
if (ret) {
mad_send_wc->status = IB_WC_GENERAL_ERR;
return IB_RMPP_RESULT_PROCESSED;
}
return IB_RMPP_RESULT_CONSUMED;
}
int ib_retry_rmpp(struct ib_mad_send_wr_private *mad_send_wr)
{
struct ib_rmpp_mad *rmpp_mad;
int ret;
rmpp_mad = mad_send_wr->send_buf.mad;
if (!(ib_get_rmpp_flags(&rmpp_mad->rmpp_hdr) &
IB_MGMT_RMPP_FLAG_ACTIVE))
return IB_RMPP_RESULT_UNHANDLED; /* RMPP not active */
if (mad_send_wr->last_ack == mad_send_wr->send_buf.seg_count)
return IB_RMPP_RESULT_PROCESSED;
mad_send_wr->seg_num = mad_send_wr->last_ack;
mad_send_wr->cur_seg = mad_send_wr->last_ack_seg;
ret = send_next_seg(mad_send_wr);
if (ret)
return IB_RMPP_RESULT_PROCESSED;
return IB_RMPP_RESULT_CONSUMED;
}
| gpl-2.0 |
CyanogenMod/android_kernel_htc_msm8660 | arch/arm/mach-msm/sysmon.c | 593 | 4144 | /*
* Copyright (c) 2011, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#define pr_fmt(fmt) "%s: " fmt, __func__
#undef DEBUG
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/string.h>
#include <linux/completion.h>
#include <linux/platform_device.h>
#include <mach/msm_smd.h>
#include <mach/subsystem_notif.h>
#include "sysmon.h"
#define MAX_MSG_LENGTH 50
#define TIMEOUT_MS 5000
struct sysmon_subsys {
struct mutex lock;
struct smd_channel *chan;
bool chan_open;
struct completion resp_ready;
char rx_buf[MAX_MSG_LENGTH];
};
static struct sysmon_subsys subsys[SYSMON_NUM_SS];
static const char *notif_name[SUBSYS_NOTIF_TYPE_COUNT] = {
[SUBSYS_BEFORE_SHUTDOWN] = "before_shutdown",
[SUBSYS_AFTER_SHUTDOWN] = "after_shutdown",
[SUBSYS_BEFORE_POWERUP] = "before_powerup",
[SUBSYS_AFTER_POWERUP] = "after_powerup",
};
int sysmon_send_event(enum subsys_id dest_ss, const char *event_ss,
enum subsys_notif_type notif)
{
struct sysmon_subsys *ss = &subsys[dest_ss];
char tx_buf[MAX_MSG_LENGTH];
int ret;
if (dest_ss < 0 || dest_ss >= SYSMON_NUM_SS ||
notif < 0 || notif >= SUBSYS_NOTIF_TYPE_COUNT ||
event_ss == NULL)
return -EINVAL;
if (!ss->chan_open)
return -ENODEV;
mutex_lock(&ss->lock);
init_completion(&ss->resp_ready);
snprintf(tx_buf, ARRAY_SIZE(tx_buf), "ssr:%s:%s", event_ss,
notif_name[notif]);
pr_debug("Sending message: %s\n", tx_buf);
smd_write(ss->chan, tx_buf, ARRAY_SIZE(tx_buf));
ret = wait_for_completion_timeout(&ss->resp_ready,
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
ret = -ETIMEDOUT;
} else if (strncmp(ss->rx_buf, "ssr:ack", ARRAY_SIZE(ss->rx_buf))) {
pr_debug("Received response: %s\n", ss->rx_buf);
ret = -ENOSYS;
} else {
ret = 0;
}
mutex_unlock(&ss->lock);
return ret;
}
static void sysmon_notify(void *priv, unsigned int smd_event)
{
struct sysmon_subsys *ss = priv;
switch (smd_event) {
case SMD_EVENT_DATA: {
if (smd_read_avail(ss->chan) > 0) {
smd_read_from_cb(ss->chan, ss->rx_buf,
ARRAY_SIZE(ss->rx_buf));
complete(&ss->resp_ready);
}
break;
}
case SMD_EVENT_OPEN:
ss->chan_open = true;
break;
case SMD_EVENT_CLOSE:
ss->chan_open = false;
break;
}
}
static int sysmon_probe(struct platform_device *pdev)
{
static const uint32_t ss_map[SMD_NUM_TYPE] = {
[SMD_APPS_MODEM] = SYSMON_SS_MODEM,
[SMD_APPS_QDSP] = SYSMON_SS_LPASS,
[SMD_APPS_WCNSS] = SYSMON_SS_WCNSS,
[SMD_APPS_DSPS] = SYSMON_SS_DSPS,
[SMD_APPS_Q6FW] = SYSMON_SS_Q6FW,
};
struct sysmon_subsys *ss;
int ret;
if (pdev == NULL)
return -EINVAL;
if (pdev->id < 0 || pdev->id >= SMD_NUM_TYPE ||
ss_map[pdev->id] < 0 || ss_map[pdev->id] >= SYSMON_NUM_SS)
return -ENODEV;
ss = &subsys[ss_map[pdev->id]];
mutex_init(&ss->lock);
/* Open and configure the SMD channel */
ret = smd_named_open_on_edge("sys_mon", pdev->id, &ss->chan,
ss, sysmon_notify);
if (ret) {
pr_err("SMD open failed\n");
return -ENOSYS;
}
smd_disable_read_intr(ss->chan);
return 0;
}
static int __devexit sysmon_remove(struct platform_device *pdev)
{
smd_close(subsys[pdev->id].chan);
return 0;
}
static struct platform_driver sysmon_driver = {
.probe = sysmon_probe,
.remove = __devexit_p(sysmon_remove),
.driver = {
.name = "sys_mon",
.owner = THIS_MODULE,
},
};
static int __init sysmon_init(void)
{
return platform_driver_register(&sysmon_driver);
}
subsys_initcall(sysmon_init);
static void __exit sysmon_exit(void)
{
platform_driver_unregister(&sysmon_driver);
}
module_exit(sysmon_exit);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("system monitor communication library");
MODULE_ALIAS("platform:sys_mon");
| gpl-2.0 |
daniel-ortiz/linux | drivers/fmc/fmc-sdb.c | 1873 | 7433 | /*
* Copyright (C) 2012 CERN (www.cern.ch)
* Author: Alessandro Rubini <rubini@gnudd.com>
*
* Released according to the GNU GPL, version 2 or any later version.
*
* This work is part of the White Rabbit project, a research effort led
* by CERN, the European Institute for Nuclear Research.
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/fmc.h>
#include <linux/sdb.h>
#include <linux/err.h>
#include <linux/fmc-sdb.h>
#include <asm/byteorder.h>
static uint32_t __sdb_rd(struct fmc_device *fmc, unsigned long address,
int convert)
{
uint32_t res = fmc_readl(fmc, address);
if (convert)
return __be32_to_cpu(res);
return res;
}
static struct sdb_array *__fmc_scan_sdb_tree(struct fmc_device *fmc,
unsigned long sdb_addr,
unsigned long reg_base, int level)
{
uint32_t onew;
int i, j, n, convert = 0;
struct sdb_array *arr, *sub;
onew = fmc_readl(fmc, sdb_addr);
if (onew == SDB_MAGIC) {
/* Uh! If we are little-endian, we must convert */
if (SDB_MAGIC != __be32_to_cpu(SDB_MAGIC))
convert = 1;
} else if (onew == __be32_to_cpu(SDB_MAGIC)) {
/* ok, don't convert */
} else {
return ERR_PTR(-ENOENT);
}
/* So, the magic was there: get the count from offset 4*/
onew = __sdb_rd(fmc, sdb_addr + 4, convert);
n = __be16_to_cpu(*(uint16_t *)&onew);
arr = kzalloc(sizeof(*arr), GFP_KERNEL);
if (!arr)
return ERR_PTR(-ENOMEM);
arr->record = kzalloc(sizeof(arr->record[0]) * n, GFP_KERNEL);
arr->subtree = kzalloc(sizeof(arr->subtree[0]) * n, GFP_KERNEL);
if (!arr->record || !arr->subtree) {
kfree(arr->record);
kfree(arr->subtree);
kfree(arr);
return ERR_PTR(-ENOMEM);
}
arr->len = n;
arr->level = level;
arr->fmc = fmc;
for (i = 0; i < n; i++) {
union sdb_record *r;
for (j = 0; j < sizeof(arr->record[0]); j += 4) {
*(uint32_t *)((void *)(arr->record + i) + j) =
__sdb_rd(fmc, sdb_addr + (i * 64) + j, convert);
}
r = &arr->record[i];
arr->subtree[i] = ERR_PTR(-ENODEV);
if (r->empty.record_type == sdb_type_bridge) {
struct sdb_component *c = &r->bridge.sdb_component;
uint64_t subaddr = __be64_to_cpu(r->bridge.sdb_child);
uint64_t newbase = __be64_to_cpu(c->addr_first);
subaddr += reg_base;
newbase += reg_base;
sub = __fmc_scan_sdb_tree(fmc, subaddr, newbase,
level + 1);
arr->subtree[i] = sub; /* may be error */
if (IS_ERR(sub))
continue;
sub->parent = arr;
sub->baseaddr = newbase;
}
}
return arr;
}
int fmc_scan_sdb_tree(struct fmc_device *fmc, unsigned long address)
{
struct sdb_array *ret;
if (fmc->sdb)
return -EBUSY;
ret = __fmc_scan_sdb_tree(fmc, address, 0 /* regs */, 0);
if (IS_ERR(ret))
return PTR_ERR(ret);
fmc->sdb = ret;
return 0;
}
EXPORT_SYMBOL(fmc_scan_sdb_tree);
static void __fmc_sdb_free(struct sdb_array *arr)
{
int i, n;
if (!arr)
return;
n = arr->len;
for (i = 0; i < n; i++) {
if (IS_ERR(arr->subtree[i]))
continue;
__fmc_sdb_free(arr->subtree[i]);
}
kfree(arr->record);
kfree(arr->subtree);
kfree(arr);
}
int fmc_free_sdb_tree(struct fmc_device *fmc)
{
__fmc_sdb_free(fmc->sdb);
fmc->sdb = NULL;
return 0;
}
EXPORT_SYMBOL(fmc_free_sdb_tree);
/* This helper calls reprogram and inizialized sdb as well */
int fmc_reprogram(struct fmc_device *fmc, struct fmc_driver *d, char *gw,
int sdb_entry)
{
int ret;
ret = fmc->op->reprogram(fmc, d, gw);
if (ret < 0)
return ret;
if (sdb_entry < 0)
return ret;
/* We are required to find SDB at a given offset */
ret = fmc_scan_sdb_tree(fmc, sdb_entry);
if (ret < 0) {
dev_err(&fmc->dev, "Can't find SDB at address 0x%x\n",
sdb_entry);
return -ENODEV;
}
fmc_dump_sdb(fmc);
return 0;
}
EXPORT_SYMBOL(fmc_reprogram);
static char *__strip_trailing_space(char *buf, char *str, int len)
{
int i = len - 1;
memcpy(buf, str, len);
while(i >= 0 && buf[i] == ' ')
buf[i--] = '\0';
return buf;
}
#define __sdb_string(buf, field) ({ \
BUILD_BUG_ON(sizeof(buf) < sizeof(field)); \
__strip_trailing_space(buf, (void *)(field), sizeof(field)); \
})
static void __fmc_show_sdb_tree(const struct fmc_device *fmc,
const struct sdb_array *arr)
{
unsigned long base = arr->baseaddr;
int i, j, n = arr->len, level = arr->level;
char buf[64];
for (i = 0; i < n; i++) {
union sdb_record *r;
struct sdb_product *p;
struct sdb_component *c;
r = &arr->record[i];
c = &r->dev.sdb_component;
p = &c->product;
dev_info(&fmc->dev, "SDB: ");
for (j = 0; j < level; j++)
printk(KERN_CONT " ");
switch (r->empty.record_type) {
case sdb_type_interconnect:
printk(KERN_CONT "%08llx:%08x %.19s\n",
__be64_to_cpu(p->vendor_id),
__be32_to_cpu(p->device_id),
p->name);
break;
case sdb_type_device:
printk(KERN_CONT "%08llx:%08x %.19s (%08llx-%08llx)\n",
__be64_to_cpu(p->vendor_id),
__be32_to_cpu(p->device_id),
p->name,
__be64_to_cpu(c->addr_first) + base,
__be64_to_cpu(c->addr_last) + base);
break;
case sdb_type_bridge:
printk(KERN_CONT "%08llx:%08x %.19s (bridge: %08llx)\n",
__be64_to_cpu(p->vendor_id),
__be32_to_cpu(p->device_id),
p->name,
__be64_to_cpu(c->addr_first) + base);
if (IS_ERR(arr->subtree[i])) {
dev_info(&fmc->dev, "SDB: (bridge error %li)\n",
PTR_ERR(arr->subtree[i]));
break;
}
__fmc_show_sdb_tree(fmc, arr->subtree[i]);
break;
case sdb_type_integration:
printk(KERN_CONT "integration\n");
break;
case sdb_type_repo_url:
printk(KERN_CONT "Synthesis repository: %s\n",
__sdb_string(buf, r->repo_url.repo_url));
break;
case sdb_type_synthesis:
printk(KERN_CONT "Bitstream '%s' ",
__sdb_string(buf, r->synthesis.syn_name));
printk(KERN_CONT "synthesized %08x by %s ",
__be32_to_cpu(r->synthesis.date),
__sdb_string(buf, r->synthesis.user_name));
printk(KERN_CONT "(%s version %x), ",
__sdb_string(buf, r->synthesis.tool_name),
__be32_to_cpu(r->synthesis.tool_version));
printk(KERN_CONT "commit %pm\n",
r->synthesis.commit_id);
break;
case sdb_type_empty:
printk(KERN_CONT "empty\n");
break;
default:
printk(KERN_CONT "UNKNOWN TYPE 0x%02x\n",
r->empty.record_type);
break;
}
}
}
void fmc_show_sdb_tree(const struct fmc_device *fmc)
{
if (!fmc->sdb)
return;
__fmc_show_sdb_tree(fmc, fmc->sdb);
}
EXPORT_SYMBOL(fmc_show_sdb_tree);
signed long fmc_find_sdb_device(struct sdb_array *tree,
uint64_t vid, uint32_t did, unsigned long *sz)
{
signed long res = -ENODEV;
union sdb_record *r;
struct sdb_product *p;
struct sdb_component *c;
int i, n = tree->len;
uint64_t last, first;
/* FIXME: what if the first interconnect is not at zero? */
for (i = 0; i < n; i++) {
r = &tree->record[i];
c = &r->dev.sdb_component;
p = &c->product;
if (!IS_ERR(tree->subtree[i]))
res = fmc_find_sdb_device(tree->subtree[i],
vid, did, sz);
if (res >= 0)
return res + tree->baseaddr;
if (r->empty.record_type != sdb_type_device)
continue;
if (__be64_to_cpu(p->vendor_id) != vid)
continue;
if (__be32_to_cpu(p->device_id) != did)
continue;
/* found */
last = __be64_to_cpu(c->addr_last);
first = __be64_to_cpu(c->addr_first);
if (sz)
*sz = (typeof(*sz))(last + 1 - first);
return first + tree->baseaddr;
}
return res;
}
EXPORT_SYMBOL(fmc_find_sdb_device);
| gpl-2.0 |
webore/lenovo | drivers/media/video/saa7134/saa7134-dvb.c | 2385 | 54094 | /*
*
* (c) 2004 Gerd Knorr <kraxel@bytesex.org> [SuSE Labs]
*
* Extended 3 / 2005 by Hartmut Hackmann to support various
* cards with the tda10046 DVB-T channel decoder
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/init.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/kthread.h>
#include <linux/suspend.h>
#include "saa7134-reg.h"
#include "saa7134.h"
#include <media/v4l2-common.h>
#include "dvb-pll.h"
#include <dvb_frontend.h>
#include "mt352.h"
#include "mt352_priv.h" /* FIXME */
#include "tda1004x.h"
#include "nxt200x.h"
#include "tuner-xc2028.h"
#include "xc5000.h"
#include "tda10086.h"
#include "tda826x.h"
#include "tda827x.h"
#include "isl6421.h"
#include "isl6405.h"
#include "lnbp21.h"
#include "tuner-simple.h"
#include "tda10048.h"
#include "tda18271.h"
#include "lgdt3305.h"
#include "tda8290.h"
#include "mb86a20s.h"
#include "lgs8gxx.h"
#include "zl10353.h"
#include "zl10036.h"
#include "zl10039.h"
#include "mt312.h"
MODULE_AUTHOR("Gerd Knorr <kraxel@bytesex.org> [SuSE Labs]");
MODULE_LICENSE("GPL");
static unsigned int antenna_pwr;
module_param(antenna_pwr, int, 0444);
MODULE_PARM_DESC(antenna_pwr,"enable antenna power (Pinnacle 300i)");
static int use_frontend;
module_param(use_frontend, int, 0644);
MODULE_PARM_DESC(use_frontend,"for cards with multiple frontends (0: terrestrial, 1: satellite)");
static int debug;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "Turn on/off module debugging (default:off).");
DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr);
#define dprintk(fmt, arg...) do { if (debug) \
printk(KERN_DEBUG "%s/dvb: " fmt, dev->name , ## arg); } while(0)
/* Print a warning */
#define wprintk(fmt, arg...) \
printk(KERN_WARNING "%s/dvb: " fmt, dev->name, ## arg)
/* ------------------------------------------------------------------
* mt352 based DVB-T cards
*/
static int pinnacle_antenna_pwr(struct saa7134_dev *dev, int on)
{
u32 ok;
if (!on) {
saa_setl(SAA7134_GPIO_GPMODE0 >> 2, (1 << 26));
saa_clearl(SAA7134_GPIO_GPSTATUS0 >> 2, (1 << 26));
return 0;
}
saa_setl(SAA7134_GPIO_GPMODE0 >> 2, (1 << 26));
saa_setl(SAA7134_GPIO_GPSTATUS0 >> 2, (1 << 26));
udelay(10);
saa_setl(SAA7134_GPIO_GPMODE0 >> 2, (1 << 28));
saa_clearl(SAA7134_GPIO_GPSTATUS0 >> 2, (1 << 28));
udelay(10);
saa_setl(SAA7134_GPIO_GPSTATUS0 >> 2, (1 << 28));
udelay(10);
ok = saa_readl(SAA7134_GPIO_GPSTATUS0) & (1 << 27);
dprintk("%s %s\n", __func__, ok ? "on" : "off");
if (!ok)
saa_clearl(SAA7134_GPIO_GPSTATUS0 >> 2, (1 << 26));
return ok;
}
static int mt352_pinnacle_init(struct dvb_frontend* fe)
{
static u8 clock_config [] = { CLOCK_CTL, 0x3d, 0x28 };
static u8 reset [] = { RESET, 0x80 };
static u8 adc_ctl_1_cfg [] = { ADC_CTL_1, 0x40 };
static u8 agc_cfg [] = { AGC_TARGET, 0x28, 0xa0 };
static u8 capt_range_cfg[] = { CAPT_RANGE, 0x31 };
static u8 fsm_ctl_cfg[] = { 0x7b, 0x04 };
static u8 gpp_ctl_cfg [] = { GPP_CTL, 0x0f };
static u8 scan_ctl_cfg [] = { SCAN_CTL, 0x0d };
static u8 irq_cfg [] = { INTERRUPT_EN_0, 0x00, 0x00, 0x00, 0x00 };
struct saa7134_dev *dev= fe->dvb->priv;
dprintk("%s called\n", __func__);
mt352_write(fe, clock_config, sizeof(clock_config));
udelay(200);
mt352_write(fe, reset, sizeof(reset));
mt352_write(fe, adc_ctl_1_cfg, sizeof(adc_ctl_1_cfg));
mt352_write(fe, agc_cfg, sizeof(agc_cfg));
mt352_write(fe, capt_range_cfg, sizeof(capt_range_cfg));
mt352_write(fe, gpp_ctl_cfg, sizeof(gpp_ctl_cfg));
mt352_write(fe, fsm_ctl_cfg, sizeof(fsm_ctl_cfg));
mt352_write(fe, scan_ctl_cfg, sizeof(scan_ctl_cfg));
mt352_write(fe, irq_cfg, sizeof(irq_cfg));
return 0;
}
static int mt352_aver777_init(struct dvb_frontend* fe)
{
static u8 clock_config [] = { CLOCK_CTL, 0x38, 0x2d };
static u8 reset [] = { RESET, 0x80 };
static u8 adc_ctl_1_cfg [] = { ADC_CTL_1, 0x40 };
static u8 agc_cfg [] = { AGC_TARGET, 0x28, 0xa0 };
static u8 capt_range_cfg[] = { CAPT_RANGE, 0x33 };
mt352_write(fe, clock_config, sizeof(clock_config));
udelay(200);
mt352_write(fe, reset, sizeof(reset));
mt352_write(fe, adc_ctl_1_cfg, sizeof(adc_ctl_1_cfg));
mt352_write(fe, agc_cfg, sizeof(agc_cfg));
mt352_write(fe, capt_range_cfg, sizeof(capt_range_cfg));
return 0;
}
static int mt352_avermedia_xc3028_init(struct dvb_frontend *fe)
{
static u8 clock_config [] = { CLOCK_CTL, 0x38, 0x2d };
static u8 reset [] = { RESET, 0x80 };
static u8 adc_ctl_1_cfg [] = { ADC_CTL_1, 0x40 };
static u8 agc_cfg [] = { AGC_TARGET, 0xe };
static u8 capt_range_cfg[] = { CAPT_RANGE, 0x33 };
mt352_write(fe, clock_config, sizeof(clock_config));
udelay(200);
mt352_write(fe, reset, sizeof(reset));
mt352_write(fe, adc_ctl_1_cfg, sizeof(adc_ctl_1_cfg));
mt352_write(fe, agc_cfg, sizeof(agc_cfg));
mt352_write(fe, capt_range_cfg, sizeof(capt_range_cfg));
return 0;
}
static int mt352_pinnacle_tuner_set_params(struct dvb_frontend* fe,
struct dvb_frontend_parameters* params)
{
u8 off[] = { 0x00, 0xf1};
u8 on[] = { 0x00, 0x71};
struct i2c_msg msg = {.addr=0x43, .flags=0, .buf=off, .len = sizeof(off)};
struct saa7134_dev *dev = fe->dvb->priv;
struct v4l2_frequency f;
/* set frequency (mt2050) */
f.tuner = 0;
f.type = V4L2_TUNER_DIGITAL_TV;
f.frequency = params->frequency / 1000 * 16 / 1000;
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 1);
i2c_transfer(&dev->i2c_adap, &msg, 1);
saa_call_all(dev, tuner, s_frequency, &f);
msg.buf = on;
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 1);
i2c_transfer(&dev->i2c_adap, &msg, 1);
pinnacle_antenna_pwr(dev, antenna_pwr);
/* mt352 setup */
return mt352_pinnacle_init(fe);
}
static struct mt352_config pinnacle_300i = {
.demod_address = 0x3c >> 1,
.adc_clock = 20333,
.if2 = 36150,
.no_tuner = 1,
.demod_init = mt352_pinnacle_init,
};
static struct mt352_config avermedia_777 = {
.demod_address = 0xf,
.demod_init = mt352_aver777_init,
};
static struct mt352_config avermedia_xc3028_mt352_dev = {
.demod_address = (0x1e >> 1),
.no_tuner = 1,
.demod_init = mt352_avermedia_xc3028_init,
};
static struct tda18271_std_map mb86a20s_tda18271_std_map = {
.dvbt_6 = { .if_freq = 3300, .agc_mode = 3, .std = 4,
.if_lvl = 7, .rfagc_top = 0x37, },
};
static struct tda18271_config kworld_tda18271_config = {
.std_map = &mb86a20s_tda18271_std_map,
.gate = TDA18271_GATE_DIGITAL,
.config = 3, /* Use tuner callback for AGC */
};
static const struct mb86a20s_config kworld_mb86a20s_config = {
.demod_address = 0x10,
};
static int kworld_sbtvd_gate_ctrl(struct dvb_frontend* fe, int enable)
{
struct saa7134_dev *dev = fe->dvb->priv;
unsigned char initmsg[] = {0x45, 0x97};
unsigned char msg_enable[] = {0x45, 0xc1};
unsigned char msg_disable[] = {0x45, 0x81};
struct i2c_msg msg = {.addr = 0x4b, .flags = 0, .buf = initmsg, .len = 2};
if (i2c_transfer(&dev->i2c_adap, &msg, 1) != 1) {
wprintk("could not access the I2C gate\n");
return -EIO;
}
if (enable)
msg.buf = msg_enable;
else
msg.buf = msg_disable;
if (i2c_transfer(&dev->i2c_adap, &msg, 1) != 1) {
wprintk("could not access the I2C gate\n");
return -EIO;
}
msleep(20);
return 0;
}
/* ==================================================================
* tda1004x based DVB-T cards, helper functions
*/
static int philips_tda1004x_request_firmware(struct dvb_frontend *fe,
const struct firmware **fw, char *name)
{
struct saa7134_dev *dev = fe->dvb->priv;
return request_firmware(fw, name, &dev->pci->dev);
}
/* ------------------------------------------------------------------
* these tuners are tu1216, td1316(a)
*/
static int philips_tda6651_pll_set(struct dvb_frontend *fe, struct dvb_frontend_parameters *params)
{
struct saa7134_dev *dev = fe->dvb->priv;
struct tda1004x_state *state = fe->demodulator_priv;
u8 addr = state->config->tuner_address;
u8 tuner_buf[4];
struct i2c_msg tuner_msg = {.addr = addr,.flags = 0,.buf = tuner_buf,.len =
sizeof(tuner_buf) };
int tuner_frequency = 0;
u8 band, cp, filter;
/* determine charge pump */
tuner_frequency = params->frequency + 36166000;
if (tuner_frequency < 87000000)
return -EINVAL;
else if (tuner_frequency < 130000000)
cp = 3;
else if (tuner_frequency < 160000000)
cp = 5;
else if (tuner_frequency < 200000000)
cp = 6;
else if (tuner_frequency < 290000000)
cp = 3;
else if (tuner_frequency < 420000000)
cp = 5;
else if (tuner_frequency < 480000000)
cp = 6;
else if (tuner_frequency < 620000000)
cp = 3;
else if (tuner_frequency < 830000000)
cp = 5;
else if (tuner_frequency < 895000000)
cp = 7;
else
return -EINVAL;
/* determine band */
if (params->frequency < 49000000)
return -EINVAL;
else if (params->frequency < 161000000)
band = 1;
else if (params->frequency < 444000000)
band = 2;
else if (params->frequency < 861000000)
band = 4;
else
return -EINVAL;
/* setup PLL filter */
switch (params->u.ofdm.bandwidth) {
case BANDWIDTH_6_MHZ:
filter = 0;
break;
case BANDWIDTH_7_MHZ:
filter = 0;
break;
case BANDWIDTH_8_MHZ:
filter = 1;
break;
default:
return -EINVAL;
}
/* calculate divisor
* ((36166000+((1000000/6)/2)) + Finput)/(1000000/6)
*/
tuner_frequency = (((params->frequency / 1000) * 6) + 217496) / 1000;
/* setup tuner buffer */
tuner_buf[0] = (tuner_frequency >> 8) & 0x7f;
tuner_buf[1] = tuner_frequency & 0xff;
tuner_buf[2] = 0xca;
tuner_buf[3] = (cp << 5) | (filter << 3) | band;
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 1);
if (i2c_transfer(&dev->i2c_adap, &tuner_msg, 1) != 1) {
wprintk("could not write to tuner at addr: 0x%02x\n",
addr << 1);
return -EIO;
}
msleep(1);
return 0;
}
static int philips_tu1216_init(struct dvb_frontend *fe)
{
struct saa7134_dev *dev = fe->dvb->priv;
struct tda1004x_state *state = fe->demodulator_priv;
u8 addr = state->config->tuner_address;
static u8 tu1216_init[] = { 0x0b, 0xf5, 0x85, 0xab };
struct i2c_msg tuner_msg = {.addr = addr,.flags = 0,.buf = tu1216_init,.len = sizeof(tu1216_init) };
/* setup PLL configuration */
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 1);
if (i2c_transfer(&dev->i2c_adap, &tuner_msg, 1) != 1)
return -EIO;
msleep(1);
return 0;
}
/* ------------------------------------------------------------------ */
static struct tda1004x_config philips_tu1216_60_config = {
.demod_address = 0x8,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_4M,
.agc_config = TDA10046_AGC_DEFAULT,
.if_freq = TDA10046_FREQ_3617,
.tuner_address = 0x60,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config philips_tu1216_61_config = {
.demod_address = 0x8,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_4M,
.agc_config = TDA10046_AGC_DEFAULT,
.if_freq = TDA10046_FREQ_3617,
.tuner_address = 0x61,
.request_firmware = philips_tda1004x_request_firmware
};
/* ------------------------------------------------------------------ */
static int philips_td1316_tuner_init(struct dvb_frontend *fe)
{
struct saa7134_dev *dev = fe->dvb->priv;
struct tda1004x_state *state = fe->demodulator_priv;
u8 addr = state->config->tuner_address;
static u8 msg[] = { 0x0b, 0xf5, 0x86, 0xab };
struct i2c_msg init_msg = {.addr = addr,.flags = 0,.buf = msg,.len = sizeof(msg) };
/* setup PLL configuration */
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 1);
if (i2c_transfer(&dev->i2c_adap, &init_msg, 1) != 1)
return -EIO;
return 0;
}
static int philips_td1316_tuner_set_params(struct dvb_frontend *fe, struct dvb_frontend_parameters *params)
{
return philips_tda6651_pll_set(fe, params);
}
static int philips_td1316_tuner_sleep(struct dvb_frontend *fe)
{
struct saa7134_dev *dev = fe->dvb->priv;
struct tda1004x_state *state = fe->demodulator_priv;
u8 addr = state->config->tuner_address;
static u8 msg[] = { 0x0b, 0xdc, 0x86, 0xa4 };
struct i2c_msg analog_msg = {.addr = addr,.flags = 0,.buf = msg,.len = sizeof(msg) };
/* switch the tuner to analog mode */
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 1);
if (i2c_transfer(&dev->i2c_adap, &analog_msg, 1) != 1)
return -EIO;
return 0;
}
/* ------------------------------------------------------------------ */
static int philips_europa_tuner_init(struct dvb_frontend *fe)
{
struct saa7134_dev *dev = fe->dvb->priv;
static u8 msg[] = { 0x00, 0x40};
struct i2c_msg init_msg = {.addr = 0x43,.flags = 0,.buf = msg,.len = sizeof(msg) };
if (philips_td1316_tuner_init(fe))
return -EIO;
msleep(1);
if (i2c_transfer(&dev->i2c_adap, &init_msg, 1) != 1)
return -EIO;
return 0;
}
static int philips_europa_tuner_sleep(struct dvb_frontend *fe)
{
struct saa7134_dev *dev = fe->dvb->priv;
static u8 msg[] = { 0x00, 0x14 };
struct i2c_msg analog_msg = {.addr = 0x43,.flags = 0,.buf = msg,.len = sizeof(msg) };
if (philips_td1316_tuner_sleep(fe))
return -EIO;
/* switch the board to analog mode */
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 1);
i2c_transfer(&dev->i2c_adap, &analog_msg, 1);
return 0;
}
static int philips_europa_demod_sleep(struct dvb_frontend *fe)
{
struct saa7134_dev *dev = fe->dvb->priv;
if (dev->original_demod_sleep)
dev->original_demod_sleep(fe);
fe->ops.i2c_gate_ctrl(fe, 1);
return 0;
}
static struct tda1004x_config philips_europa_config = {
.demod_address = 0x8,
.invert = 0,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_4M,
.agc_config = TDA10046_AGC_IFO_AUTO_POS,
.if_freq = TDA10046_FREQ_052,
.tuner_address = 0x61,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config medion_cardbus = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_IFO_AUTO_NEG,
.if_freq = TDA10046_FREQ_3613,
.tuner_address = 0x61,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config technotrend_budget_t3000_config = {
.demod_address = 0x8,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_4M,
.agc_config = TDA10046_AGC_DEFAULT,
.if_freq = TDA10046_FREQ_3617,
.tuner_address = 0x63,
.request_firmware = philips_tda1004x_request_firmware
};
/* ------------------------------------------------------------------
* tda 1004x based cards with philips silicon tuner
*/
static int tda8290_i2c_gate_ctrl( struct dvb_frontend* fe, int enable)
{
struct tda1004x_state *state = fe->demodulator_priv;
u8 addr = state->config->i2c_gate;
static u8 tda8290_close[] = { 0x21, 0xc0};
static u8 tda8290_open[] = { 0x21, 0x80};
struct i2c_msg tda8290_msg = {.addr = addr,.flags = 0, .len = 2};
if (enable) {
tda8290_msg.buf = tda8290_close;
} else {
tda8290_msg.buf = tda8290_open;
}
if (i2c_transfer(state->i2c, &tda8290_msg, 1) != 1) {
struct saa7134_dev *dev = fe->dvb->priv;
wprintk("could not access tda8290 I2C gate\n");
return -EIO;
}
msleep(20);
return 0;
}
static int philips_tda827x_tuner_init(struct dvb_frontend *fe)
{
struct saa7134_dev *dev = fe->dvb->priv;
struct tda1004x_state *state = fe->demodulator_priv;
switch (state->config->antenna_switch) {
case 0: break;
case 1: dprintk("setting GPIO21 to 0 (TV antenna?)\n");
saa7134_set_gpio(dev, 21, 0);
break;
case 2: dprintk("setting GPIO21 to 1 (Radio antenna?)\n");
saa7134_set_gpio(dev, 21, 1);
break;
}
return 0;
}
static int philips_tda827x_tuner_sleep(struct dvb_frontend *fe)
{
struct saa7134_dev *dev = fe->dvb->priv;
struct tda1004x_state *state = fe->demodulator_priv;
switch (state->config->antenna_switch) {
case 0: break;
case 1: dprintk("setting GPIO21 to 1 (Radio antenna?)\n");
saa7134_set_gpio(dev, 21, 1);
break;
case 2: dprintk("setting GPIO21 to 0 (TV antenna?)\n");
saa7134_set_gpio(dev, 21, 0);
break;
}
return 0;
}
static int configure_tda827x_fe(struct saa7134_dev *dev,
struct tda1004x_config *cdec_conf,
struct tda827x_config *tuner_conf)
{
struct videobuf_dvb_frontend *fe0;
/* Get the first frontend */
fe0 = videobuf_dvb_get_frontend(&dev->frontends, 1);
fe0->dvb.frontend = dvb_attach(tda10046_attach, cdec_conf, &dev->i2c_adap);
if (fe0->dvb.frontend) {
if (cdec_conf->i2c_gate)
fe0->dvb.frontend->ops.i2c_gate_ctrl = tda8290_i2c_gate_ctrl;
if (dvb_attach(tda827x_attach, fe0->dvb.frontend,
cdec_conf->tuner_address,
&dev->i2c_adap, tuner_conf))
return 0;
wprintk("no tda827x tuner found at addr: %02x\n",
cdec_conf->tuner_address);
}
return -EINVAL;
}
/* ------------------------------------------------------------------ */
static struct tda827x_config tda827x_cfg_0 = {
.init = philips_tda827x_tuner_init,
.sleep = philips_tda827x_tuner_sleep,
.config = 0,
.switch_addr = 0
};
static struct tda827x_config tda827x_cfg_1 = {
.init = philips_tda827x_tuner_init,
.sleep = philips_tda827x_tuner_sleep,
.config = 1,
.switch_addr = 0x4b
};
static struct tda827x_config tda827x_cfg_2 = {
.init = philips_tda827x_tuner_init,
.sleep = philips_tda827x_tuner_sleep,
.config = 2,
.switch_addr = 0x4b
};
static struct tda827x_config tda827x_cfg_2_sw42 = {
.init = philips_tda827x_tuner_init,
.sleep = philips_tda827x_tuner_sleep,
.config = 2,
.switch_addr = 0x42
};
/* ------------------------------------------------------------------ */
static struct tda1004x_config tda827x_lifeview_config = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP11_I,
.if_freq = TDA10046_FREQ_045,
.tuner_address = 0x60,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config philips_tiger_config = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP11_I,
.if_freq = TDA10046_FREQ_045,
.i2c_gate = 0x4b,
.tuner_address = 0x61,
.antenna_switch= 1,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config cinergy_ht_config = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP01_I,
.if_freq = TDA10046_FREQ_045,
.i2c_gate = 0x4b,
.tuner_address = 0x61,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config cinergy_ht_pci_config = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP01_I,
.if_freq = TDA10046_FREQ_045,
.i2c_gate = 0x4b,
.tuner_address = 0x60,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config philips_tiger_s_config = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP01_I,
.if_freq = TDA10046_FREQ_045,
.i2c_gate = 0x4b,
.tuner_address = 0x61,
.antenna_switch= 1,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config pinnacle_pctv_310i_config = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP11_I,
.if_freq = TDA10046_FREQ_045,
.i2c_gate = 0x4b,
.tuner_address = 0x61,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config hauppauge_hvr_1110_config = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP11_I,
.if_freq = TDA10046_FREQ_045,
.i2c_gate = 0x4b,
.tuner_address = 0x61,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config asus_p7131_dual_config = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP11_I,
.if_freq = TDA10046_FREQ_045,
.i2c_gate = 0x4b,
.tuner_address = 0x61,
.antenna_switch= 2,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config lifeview_trio_config = {
.demod_address = 0x09,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP00_I,
.if_freq = TDA10046_FREQ_045,
.tuner_address = 0x60,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config tevion_dvbt220rf_config = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP11_I,
.if_freq = TDA10046_FREQ_045,
.tuner_address = 0x60,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config md8800_dvbt_config = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP01_I,
.if_freq = TDA10046_FREQ_045,
.i2c_gate = 0x4b,
.tuner_address = 0x60,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config asus_p7131_4871_config = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP01_I,
.if_freq = TDA10046_FREQ_045,
.i2c_gate = 0x4b,
.tuner_address = 0x61,
.antenna_switch= 2,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config asus_p7131_hybrid_lna_config = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP11_I,
.if_freq = TDA10046_FREQ_045,
.i2c_gate = 0x4b,
.tuner_address = 0x61,
.antenna_switch= 2,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config kworld_dvb_t_210_config = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP11_I,
.if_freq = TDA10046_FREQ_045,
.i2c_gate = 0x4b,
.tuner_address = 0x61,
.antenna_switch= 1,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config avermedia_super_007_config = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP01_I,
.if_freq = TDA10046_FREQ_045,
.i2c_gate = 0x4b,
.tuner_address = 0x60,
.antenna_switch= 1,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config twinhan_dtv_dvb_3056_config = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP01_I,
.if_freq = TDA10046_FREQ_045,
.i2c_gate = 0x42,
.tuner_address = 0x61,
.antenna_switch = 1,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config asus_tiger_3in1_config = {
.demod_address = 0x0b,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP11_I,
.if_freq = TDA10046_FREQ_045,
.i2c_gate = 0x4b,
.tuner_address = 0x61,
.antenna_switch = 1,
.request_firmware = philips_tda1004x_request_firmware
};
/* ------------------------------------------------------------------
* special case: this card uses saa713x GPIO22 for the mode switch
*/
static int ads_duo_tuner_init(struct dvb_frontend *fe)
{
struct saa7134_dev *dev = fe->dvb->priv;
philips_tda827x_tuner_init(fe);
/* route TDA8275a AGC input to the channel decoder */
saa7134_set_gpio(dev, 22, 1);
return 0;
}
static int ads_duo_tuner_sleep(struct dvb_frontend *fe)
{
struct saa7134_dev *dev = fe->dvb->priv;
/* route TDA8275a AGC input to the analog IF chip*/
saa7134_set_gpio(dev, 22, 0);
philips_tda827x_tuner_sleep(fe);
return 0;
}
static struct tda827x_config ads_duo_cfg = {
.init = ads_duo_tuner_init,
.sleep = ads_duo_tuner_sleep,
.config = 0
};
static struct tda1004x_config ads_tech_duo_config = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP00_I,
.if_freq = TDA10046_FREQ_045,
.tuner_address = 0x61,
.request_firmware = philips_tda1004x_request_firmware
};
static struct zl10353_config behold_h6_config = {
.demod_address = 0x1e>>1,
.no_tuner = 1,
.parallel_ts = 1,
.disable_i2c_gate_ctrl = 1,
};
static struct xc5000_config behold_x7_tunerconfig = {
.i2c_address = 0xc2>>1,
.if_khz = 4560,
.radio_input = XC5000_RADIO_FM1,
};
static struct zl10353_config behold_x7_config = {
.demod_address = 0x1e>>1,
.if2 = 45600,
.no_tuner = 1,
.parallel_ts = 1,
.disable_i2c_gate_ctrl = 1,
};
/* ==================================================================
* tda10086 based DVB-S cards, helper functions
*/
static struct tda10086_config flydvbs = {
.demod_address = 0x0e,
.invert = 0,
.diseqc_tone = 0,
.xtal_freq = TDA10086_XTAL_16M,
};
static struct tda10086_config sd1878_4m = {
.demod_address = 0x0e,
.invert = 0,
.diseqc_tone = 0,
.xtal_freq = TDA10086_XTAL_4M,
};
/* ------------------------------------------------------------------
* special case: lnb supply is connected to the gated i2c
*/
static int md8800_set_voltage(struct dvb_frontend *fe, fe_sec_voltage_t voltage)
{
int res = -EIO;
struct saa7134_dev *dev = fe->dvb->priv;
if (fe->ops.i2c_gate_ctrl) {
fe->ops.i2c_gate_ctrl(fe, 1);
if (dev->original_set_voltage)
res = dev->original_set_voltage(fe, voltage);
fe->ops.i2c_gate_ctrl(fe, 0);
}
return res;
};
static int md8800_set_high_voltage(struct dvb_frontend *fe, long arg)
{
int res = -EIO;
struct saa7134_dev *dev = fe->dvb->priv;
if (fe->ops.i2c_gate_ctrl) {
fe->ops.i2c_gate_ctrl(fe, 1);
if (dev->original_set_high_voltage)
res = dev->original_set_high_voltage(fe, arg);
fe->ops.i2c_gate_ctrl(fe, 0);
}
return res;
};
static int md8800_set_voltage2(struct dvb_frontend *fe, fe_sec_voltage_t voltage)
{
struct saa7134_dev *dev = fe->dvb->priv;
u8 wbuf[2] = { 0x1f, 00 };
u8 rbuf;
struct i2c_msg msg[] = { { .addr = 0x08, .flags = 0, .buf = wbuf, .len = 1 },
{ .addr = 0x08, .flags = I2C_M_RD, .buf = &rbuf, .len = 1 } };
if (i2c_transfer(&dev->i2c_adap, msg, 2) != 2)
return -EIO;
/* NOTE: this assumes that gpo1 is used, it might be bit 5 (gpo2) */
if (voltage == SEC_VOLTAGE_18)
wbuf[1] = rbuf | 0x10;
else
wbuf[1] = rbuf & 0xef;
msg[0].len = 2;
i2c_transfer(&dev->i2c_adap, msg, 1);
return 0;
}
static int md8800_set_high_voltage2(struct dvb_frontend *fe, long arg)
{
struct saa7134_dev *dev = fe->dvb->priv;
wprintk("%s: sorry can't set high LNB supply voltage from here\n", __func__);
return -EIO;
}
/* ==================================================================
* nxt200x based ATSC cards, helper functions
*/
static struct nxt200x_config avertvhda180 = {
.demod_address = 0x0a,
};
static struct nxt200x_config kworldatsc110 = {
.demod_address = 0x0a,
};
/* ------------------------------------------------------------------ */
static struct mt312_config avertv_a700_mt312 = {
.demod_address = 0x0e,
.voltage_inverted = 1,
};
static struct zl10036_config avertv_a700_tuner = {
.tuner_address = 0x60,
};
static struct mt312_config zl10313_compro_s350_config = {
.demod_address = 0x0e,
};
static struct lgdt3305_config hcw_lgdt3305_config = {
.i2c_addr = 0x0e,
.mpeg_mode = LGDT3305_MPEG_SERIAL,
.tpclk_edge = LGDT3305_TPCLK_RISING_EDGE,
.tpvalid_polarity = LGDT3305_TP_VALID_HIGH,
.deny_i2c_rptr = 1,
.spectral_inversion = 1,
.qam_if_khz = 4000,
.vsb_if_khz = 3250,
};
static struct tda10048_config hcw_tda10048_config = {
.demod_address = 0x10 >> 1,
.output_mode = TDA10048_SERIAL_OUTPUT,
.fwbulkwritelen = TDA10048_BULKWRITE_200,
.inversion = TDA10048_INVERSION_ON,
.dtv6_if_freq_khz = TDA10048_IF_3300,
.dtv7_if_freq_khz = TDA10048_IF_3500,
.dtv8_if_freq_khz = TDA10048_IF_4000,
.clk_freq_khz = TDA10048_CLK_16000,
.disable_gate_access = 1,
};
static struct tda18271_std_map hauppauge_tda18271_std_map = {
.atsc_6 = { .if_freq = 3250, .agc_mode = 3, .std = 4,
.if_lvl = 1, .rfagc_top = 0x58, },
.qam_6 = { .if_freq = 4000, .agc_mode = 3, .std = 5,
.if_lvl = 1, .rfagc_top = 0x58, },
};
static struct tda18271_config hcw_tda18271_config = {
.std_map = &hauppauge_tda18271_std_map,
.gate = TDA18271_GATE_ANALOG,
.config = 3,
.output_opt = TDA18271_OUTPUT_LT_OFF,
};
static struct tda829x_config tda829x_no_probe = {
.probe_tuner = TDA829X_DONT_PROBE,
};
static struct tda10048_config zolid_tda10048_config = {
.demod_address = 0x10 >> 1,
.output_mode = TDA10048_PARALLEL_OUTPUT,
.fwbulkwritelen = TDA10048_BULKWRITE_200,
.inversion = TDA10048_INVERSION_ON,
.dtv6_if_freq_khz = TDA10048_IF_3300,
.dtv7_if_freq_khz = TDA10048_IF_3500,
.dtv8_if_freq_khz = TDA10048_IF_4000,
.clk_freq_khz = TDA10048_CLK_16000,
.disable_gate_access = 1,
};
static struct tda18271_config zolid_tda18271_config = {
.gate = TDA18271_GATE_ANALOG,
};
static struct tda10048_config dtv1000s_tda10048_config = {
.demod_address = 0x10 >> 1,
.output_mode = TDA10048_PARALLEL_OUTPUT,
.fwbulkwritelen = TDA10048_BULKWRITE_200,
.inversion = TDA10048_INVERSION_ON,
.dtv6_if_freq_khz = TDA10048_IF_3300,
.dtv7_if_freq_khz = TDA10048_IF_3800,
.dtv8_if_freq_khz = TDA10048_IF_4300,
.clk_freq_khz = TDA10048_CLK_16000,
.disable_gate_access = 1,
};
static struct tda18271_std_map dtv1000s_tda18271_std_map = {
.dvbt_6 = { .if_freq = 3300, .agc_mode = 3, .std = 4,
.if_lvl = 1, .rfagc_top = 0x37, },
.dvbt_7 = { .if_freq = 3800, .agc_mode = 3, .std = 5,
.if_lvl = 1, .rfagc_top = 0x37, },
.dvbt_8 = { .if_freq = 4300, .agc_mode = 3, .std = 6,
.if_lvl = 1, .rfagc_top = 0x37, },
};
static struct tda18271_config dtv1000s_tda18271_config = {
.std_map = &dtv1000s_tda18271_std_map,
.gate = TDA18271_GATE_ANALOG,
};
static struct lgs8gxx_config prohdtv_pro2_lgs8g75_config = {
.prod = LGS8GXX_PROD_LGS8G75,
.demod_address = 0x1d,
.serial_ts = 0,
.ts_clk_pol = 1,
.ts_clk_gated = 0,
.if_clk_freq = 30400, /* 30.4 MHz */
.if_freq = 4000, /* 4.00 MHz */
.if_neg_center = 0,
.ext_adc = 0,
.adc_signed = 1,
.adc_vpp = 3, /* 2.0 Vpp */
.if_neg_edge = 1,
};
static struct tda18271_config prohdtv_pro2_tda18271_config = {
.gate = TDA18271_GATE_ANALOG,
.output_opt = TDA18271_OUTPUT_LT_OFF,
};
/* ==================================================================
* Core code
*/
static int dvb_init(struct saa7134_dev *dev)
{
int ret;
int attach_xc3028 = 0;
struct videobuf_dvb_frontend *fe0;
/* FIXME: add support for multi-frontend */
mutex_init(&dev->frontends.lock);
INIT_LIST_HEAD(&dev->frontends.felist);
printk(KERN_INFO "%s() allocating 1 frontend\n", __func__);
fe0 = videobuf_dvb_alloc_frontend(&dev->frontends, 1);
if (!fe0) {
printk(KERN_ERR "%s() failed to alloc\n", __func__);
return -ENOMEM;
}
/* init struct videobuf_dvb */
dev->ts.nr_bufs = 32;
dev->ts.nr_packets = 32*4;
fe0->dvb.name = dev->name;
videobuf_queue_sg_init(&fe0->dvb.dvbq, &saa7134_ts_qops,
&dev->pci->dev, &dev->slock,
V4L2_BUF_TYPE_VIDEO_CAPTURE,
V4L2_FIELD_ALTERNATE,
sizeof(struct saa7134_buf),
dev, NULL);
switch (dev->board) {
case SAA7134_BOARD_PINNACLE_300I_DVBT_PAL:
dprintk("pinnacle 300i dvb setup\n");
fe0->dvb.frontend = dvb_attach(mt352_attach, &pinnacle_300i,
&dev->i2c_adap);
if (fe0->dvb.frontend) {
fe0->dvb.frontend->ops.tuner_ops.set_params = mt352_pinnacle_tuner_set_params;
}
break;
case SAA7134_BOARD_AVERMEDIA_777:
case SAA7134_BOARD_AVERMEDIA_A16AR:
dprintk("avertv 777 dvb setup\n");
fe0->dvb.frontend = dvb_attach(mt352_attach, &avermedia_777,
&dev->i2c_adap);
if (fe0->dvb.frontend) {
dvb_attach(simple_tuner_attach, fe0->dvb.frontend,
&dev->i2c_adap, 0x61,
TUNER_PHILIPS_TD1316);
}
break;
case SAA7134_BOARD_AVERMEDIA_A16D:
dprintk("AverMedia A16D dvb setup\n");
fe0->dvb.frontend = dvb_attach(mt352_attach,
&avermedia_xc3028_mt352_dev,
&dev->i2c_adap);
attach_xc3028 = 1;
break;
case SAA7134_BOARD_MD7134:
fe0->dvb.frontend = dvb_attach(tda10046_attach,
&medion_cardbus,
&dev->i2c_adap);
if (fe0->dvb.frontend) {
dvb_attach(simple_tuner_attach, fe0->dvb.frontend,
&dev->i2c_adap, medion_cardbus.tuner_address,
TUNER_PHILIPS_FMD1216ME_MK3);
}
break;
case SAA7134_BOARD_PHILIPS_TOUGH:
fe0->dvb.frontend = dvb_attach(tda10046_attach,
&philips_tu1216_60_config,
&dev->i2c_adap);
if (fe0->dvb.frontend) {
fe0->dvb.frontend->ops.tuner_ops.init = philips_tu1216_init;
fe0->dvb.frontend->ops.tuner_ops.set_params = philips_tda6651_pll_set;
}
break;
case SAA7134_BOARD_FLYDVBTDUO:
case SAA7134_BOARD_FLYDVBT_DUO_CARDBUS:
if (configure_tda827x_fe(dev, &tda827x_lifeview_config,
&tda827x_cfg_0) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_PHILIPS_EUROPA:
case SAA7134_BOARD_VIDEOMATE_DVBT_300:
case SAA7134_BOARD_ASUS_EUROPA_HYBRID:
fe0->dvb.frontend = dvb_attach(tda10046_attach,
&philips_europa_config,
&dev->i2c_adap);
if (fe0->dvb.frontend) {
dev->original_demod_sleep = fe0->dvb.frontend->ops.sleep;
fe0->dvb.frontend->ops.sleep = philips_europa_demod_sleep;
fe0->dvb.frontend->ops.tuner_ops.init = philips_europa_tuner_init;
fe0->dvb.frontend->ops.tuner_ops.sleep = philips_europa_tuner_sleep;
fe0->dvb.frontend->ops.tuner_ops.set_params = philips_td1316_tuner_set_params;
}
break;
case SAA7134_BOARD_TECHNOTREND_BUDGET_T3000:
fe0->dvb.frontend = dvb_attach(tda10046_attach,
&technotrend_budget_t3000_config,
&dev->i2c_adap);
if (fe0->dvb.frontend) {
dev->original_demod_sleep = fe0->dvb.frontend->ops.sleep;
fe0->dvb.frontend->ops.sleep = philips_europa_demod_sleep;
fe0->dvb.frontend->ops.tuner_ops.init = philips_europa_tuner_init;
fe0->dvb.frontend->ops.tuner_ops.sleep = philips_europa_tuner_sleep;
fe0->dvb.frontend->ops.tuner_ops.set_params = philips_td1316_tuner_set_params;
}
break;
case SAA7134_BOARD_VIDEOMATE_DVBT_200:
fe0->dvb.frontend = dvb_attach(tda10046_attach,
&philips_tu1216_61_config,
&dev->i2c_adap);
if (fe0->dvb.frontend) {
fe0->dvb.frontend->ops.tuner_ops.init = philips_tu1216_init;
fe0->dvb.frontend->ops.tuner_ops.set_params = philips_tda6651_pll_set;
}
break;
case SAA7134_BOARD_KWORLD_DVBT_210:
if (configure_tda827x_fe(dev, &kworld_dvb_t_210_config,
&tda827x_cfg_2) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_HAUPPAUGE_HVR1120:
fe0->dvb.frontend = dvb_attach(tda10048_attach,
&hcw_tda10048_config,
&dev->i2c_adap);
if (fe0->dvb.frontend != NULL) {
dvb_attach(tda829x_attach, fe0->dvb.frontend,
&dev->i2c_adap, 0x4b,
&tda829x_no_probe);
dvb_attach(tda18271_attach, fe0->dvb.frontend,
0x60, &dev->i2c_adap,
&hcw_tda18271_config);
}
break;
case SAA7134_BOARD_PHILIPS_TIGER:
if (configure_tda827x_fe(dev, &philips_tiger_config,
&tda827x_cfg_0) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_PINNACLE_PCTV_310i:
if (configure_tda827x_fe(dev, &pinnacle_pctv_310i_config,
&tda827x_cfg_1) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_HAUPPAUGE_HVR1110:
if (configure_tda827x_fe(dev, &hauppauge_hvr_1110_config,
&tda827x_cfg_1) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_HAUPPAUGE_HVR1150:
fe0->dvb.frontend = dvb_attach(lgdt3305_attach,
&hcw_lgdt3305_config,
&dev->i2c_adap);
if (fe0->dvb.frontend) {
dvb_attach(tda829x_attach, fe0->dvb.frontend,
&dev->i2c_adap, 0x4b,
&tda829x_no_probe);
dvb_attach(tda18271_attach, fe0->dvb.frontend,
0x60, &dev->i2c_adap,
&hcw_tda18271_config);
}
break;
case SAA7134_BOARD_ASUSTeK_P7131_DUAL:
if (configure_tda827x_fe(dev, &asus_p7131_dual_config,
&tda827x_cfg_0) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_FLYDVBT_LR301:
if (configure_tda827x_fe(dev, &tda827x_lifeview_config,
&tda827x_cfg_0) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_FLYDVB_TRIO:
if (!use_frontend) { /* terrestrial */
if (configure_tda827x_fe(dev, &lifeview_trio_config,
&tda827x_cfg_0) < 0)
goto dettach_frontend;
} else { /* satellite */
fe0->dvb.frontend = dvb_attach(tda10086_attach, &flydvbs, &dev->i2c_adap);
if (fe0->dvb.frontend) {
if (dvb_attach(tda826x_attach, fe0->dvb.frontend, 0x63,
&dev->i2c_adap, 0) == NULL) {
wprintk("%s: Lifeview Trio, No tda826x found!\n", __func__);
goto dettach_frontend;
}
if (dvb_attach(isl6421_attach, fe0->dvb.frontend, &dev->i2c_adap,
0x08, 0, 0) == NULL) {
wprintk("%s: Lifeview Trio, No ISL6421 found!\n", __func__);
goto dettach_frontend;
}
}
}
break;
case SAA7134_BOARD_ADS_DUO_CARDBUS_PTV331:
case SAA7134_BOARD_FLYDVBT_HYBRID_CARDBUS:
fe0->dvb.frontend = dvb_attach(tda10046_attach,
&ads_tech_duo_config,
&dev->i2c_adap);
if (fe0->dvb.frontend) {
if (dvb_attach(tda827x_attach,fe0->dvb.frontend,
ads_tech_duo_config.tuner_address, &dev->i2c_adap,
&ads_duo_cfg) == NULL) {
wprintk("no tda827x tuner found at addr: %02x\n",
ads_tech_duo_config.tuner_address);
goto dettach_frontend;
}
} else
wprintk("failed to attach tda10046\n");
break;
case SAA7134_BOARD_TEVION_DVBT_220RF:
if (configure_tda827x_fe(dev, &tevion_dvbt220rf_config,
&tda827x_cfg_0) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_MEDION_MD8800_QUADRO:
if (!use_frontend) { /* terrestrial */
if (configure_tda827x_fe(dev, &md8800_dvbt_config,
&tda827x_cfg_0) < 0)
goto dettach_frontend;
} else { /* satellite */
fe0->dvb.frontend = dvb_attach(tda10086_attach,
&flydvbs, &dev->i2c_adap);
if (fe0->dvb.frontend) {
struct dvb_frontend *fe = fe0->dvb.frontend;
u8 dev_id = dev->eedata[2];
u8 data = 0xc4;
struct i2c_msg msg = {.addr = 0x08, .flags = 0, .len = 1};
if (dvb_attach(tda826x_attach, fe0->dvb.frontend,
0x60, &dev->i2c_adap, 0) == NULL) {
wprintk("%s: Medion Quadro, no tda826x "
"found !\n", __func__);
goto dettach_frontend;
}
if (dev_id != 0x08) {
/* we need to open the i2c gate (we know it exists) */
fe->ops.i2c_gate_ctrl(fe, 1);
if (dvb_attach(isl6405_attach, fe,
&dev->i2c_adap, 0x08, 0, 0) == NULL) {
wprintk("%s: Medion Quadro, no ISL6405 "
"found !\n", __func__);
goto dettach_frontend;
}
if (dev_id == 0x07) {
/* fire up the 2nd section of the LNB supply since
we can't do this from the other section */
msg.buf = &data;
i2c_transfer(&dev->i2c_adap, &msg, 1);
}
fe->ops.i2c_gate_ctrl(fe, 0);
dev->original_set_voltage = fe->ops.set_voltage;
fe->ops.set_voltage = md8800_set_voltage;
dev->original_set_high_voltage = fe->ops.enable_high_lnb_voltage;
fe->ops.enable_high_lnb_voltage = md8800_set_high_voltage;
} else {
fe->ops.set_voltage = md8800_set_voltage2;
fe->ops.enable_high_lnb_voltage = md8800_set_high_voltage2;
}
}
}
break;
case SAA7134_BOARD_AVERMEDIA_AVERTVHD_A180:
fe0->dvb.frontend = dvb_attach(nxt200x_attach, &avertvhda180,
&dev->i2c_adap);
if (fe0->dvb.frontend)
dvb_attach(dvb_pll_attach, fe0->dvb.frontend, 0x61,
NULL, DVB_PLL_TDHU2);
break;
case SAA7134_BOARD_ADS_INSTANT_HDTV_PCI:
case SAA7134_BOARD_KWORLD_ATSC110:
fe0->dvb.frontend = dvb_attach(nxt200x_attach, &kworldatsc110,
&dev->i2c_adap);
if (fe0->dvb.frontend)
dvb_attach(simple_tuner_attach, fe0->dvb.frontend,
&dev->i2c_adap, 0x61,
TUNER_PHILIPS_TUV1236D);
break;
case SAA7134_BOARD_FLYDVBS_LR300:
fe0->dvb.frontend = dvb_attach(tda10086_attach, &flydvbs,
&dev->i2c_adap);
if (fe0->dvb.frontend) {
if (dvb_attach(tda826x_attach, fe0->dvb.frontend, 0x60,
&dev->i2c_adap, 0) == NULL) {
wprintk("%s: No tda826x found!\n", __func__);
goto dettach_frontend;
}
if (dvb_attach(isl6421_attach, fe0->dvb.frontend,
&dev->i2c_adap, 0x08, 0, 0) == NULL) {
wprintk("%s: No ISL6421 found!\n", __func__);
goto dettach_frontend;
}
}
break;
case SAA7134_BOARD_ASUS_EUROPA2_HYBRID:
fe0->dvb.frontend = dvb_attach(tda10046_attach,
&medion_cardbus,
&dev->i2c_adap);
if (fe0->dvb.frontend) {
dev->original_demod_sleep = fe0->dvb.frontend->ops.sleep;
fe0->dvb.frontend->ops.sleep = philips_europa_demod_sleep;
dvb_attach(simple_tuner_attach, fe0->dvb.frontend,
&dev->i2c_adap, medion_cardbus.tuner_address,
TUNER_PHILIPS_FMD1216ME_MK3);
}
break;
case SAA7134_BOARD_VIDEOMATE_DVBT_200A:
fe0->dvb.frontend = dvb_attach(tda10046_attach,
&philips_europa_config,
&dev->i2c_adap);
if (fe0->dvb.frontend) {
fe0->dvb.frontend->ops.tuner_ops.init = philips_td1316_tuner_init;
fe0->dvb.frontend->ops.tuner_ops.set_params = philips_td1316_tuner_set_params;
}
break;
case SAA7134_BOARD_CINERGY_HT_PCMCIA:
if (configure_tda827x_fe(dev, &cinergy_ht_config,
&tda827x_cfg_0) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_CINERGY_HT_PCI:
if (configure_tda827x_fe(dev, &cinergy_ht_pci_config,
&tda827x_cfg_0) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_PHILIPS_TIGER_S:
if (configure_tda827x_fe(dev, &philips_tiger_s_config,
&tda827x_cfg_2) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_ASUS_P7131_4871:
if (configure_tda827x_fe(dev, &asus_p7131_4871_config,
&tda827x_cfg_2) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_ASUSTeK_P7131_HYBRID_LNA:
if (configure_tda827x_fe(dev, &asus_p7131_hybrid_lna_config,
&tda827x_cfg_2) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_AVERMEDIA_SUPER_007:
if (configure_tda827x_fe(dev, &avermedia_super_007_config,
&tda827x_cfg_0) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_TWINHAN_DTV_DVB_3056:
if (configure_tda827x_fe(dev, &twinhan_dtv_dvb_3056_config,
&tda827x_cfg_2_sw42) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_PHILIPS_SNAKE:
fe0->dvb.frontend = dvb_attach(tda10086_attach, &flydvbs,
&dev->i2c_adap);
if (fe0->dvb.frontend) {
if (dvb_attach(tda826x_attach, fe0->dvb.frontend, 0x60,
&dev->i2c_adap, 0) == NULL) {
wprintk("%s: No tda826x found!\n", __func__);
goto dettach_frontend;
}
if (dvb_attach(lnbp21_attach, fe0->dvb.frontend,
&dev->i2c_adap, 0, 0) == NULL) {
wprintk("%s: No lnbp21 found!\n", __func__);
goto dettach_frontend;
}
}
break;
case SAA7134_BOARD_CREATIX_CTX953:
if (configure_tda827x_fe(dev, &md8800_dvbt_config,
&tda827x_cfg_0) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_MSI_TVANYWHERE_AD11:
if (configure_tda827x_fe(dev, &philips_tiger_s_config,
&tda827x_cfg_2) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_AVERMEDIA_CARDBUS_506:
dprintk("AverMedia E506R dvb setup\n");
saa7134_set_gpio(dev, 25, 0);
msleep(10);
saa7134_set_gpio(dev, 25, 1);
fe0->dvb.frontend = dvb_attach(mt352_attach,
&avermedia_xc3028_mt352_dev,
&dev->i2c_adap);
attach_xc3028 = 1;
break;
case SAA7134_BOARD_MD7134_BRIDGE_2:
fe0->dvb.frontend = dvb_attach(tda10086_attach,
&sd1878_4m, &dev->i2c_adap);
if (fe0->dvb.frontend) {
struct dvb_frontend *fe;
if (dvb_attach(dvb_pll_attach, fe0->dvb.frontend, 0x60,
&dev->i2c_adap, DVB_PLL_PHILIPS_SD1878_TDA8261) == NULL) {
wprintk("%s: MD7134 DVB-S, no SD1878 "
"found !\n", __func__);
goto dettach_frontend;
}
/* we need to open the i2c gate (we know it exists) */
fe = fe0->dvb.frontend;
fe->ops.i2c_gate_ctrl(fe, 1);
if (dvb_attach(isl6405_attach, fe,
&dev->i2c_adap, 0x08, 0, 0) == NULL) {
wprintk("%s: MD7134 DVB-S, no ISL6405 "
"found !\n", __func__);
goto dettach_frontend;
}
fe->ops.i2c_gate_ctrl(fe, 0);
dev->original_set_voltage = fe->ops.set_voltage;
fe->ops.set_voltage = md8800_set_voltage;
dev->original_set_high_voltage = fe->ops.enable_high_lnb_voltage;
fe->ops.enable_high_lnb_voltage = md8800_set_high_voltage;
}
break;
case SAA7134_BOARD_AVERMEDIA_M103:
saa7134_set_gpio(dev, 25, 0);
msleep(10);
saa7134_set_gpio(dev, 25, 1);
fe0->dvb.frontend = dvb_attach(mt352_attach,
&avermedia_xc3028_mt352_dev,
&dev->i2c_adap);
attach_xc3028 = 1;
break;
case SAA7134_BOARD_ASUSTeK_TIGER_3IN1:
if (!use_frontend) { /* terrestrial */
if (configure_tda827x_fe(dev, &asus_tiger_3in1_config,
&tda827x_cfg_2) < 0)
goto dettach_frontend;
} else { /* satellite */
fe0->dvb.frontend = dvb_attach(tda10086_attach,
&flydvbs, &dev->i2c_adap);
if (fe0->dvb.frontend) {
if (dvb_attach(tda826x_attach,
fe0->dvb.frontend, 0x60,
&dev->i2c_adap, 0) == NULL) {
wprintk("%s: Asus Tiger 3in1, no "
"tda826x found!\n", __func__);
goto dettach_frontend;
}
if (dvb_attach(lnbp21_attach, fe0->dvb.frontend,
&dev->i2c_adap, 0, 0) == NULL) {
wprintk("%s: Asus Tiger 3in1, no lnbp21"
" found!\n", __func__);
goto dettach_frontend;
}
}
}
break;
case SAA7134_BOARD_ASUSTeK_TIGER:
if (configure_tda827x_fe(dev, &philips_tiger_config,
&tda827x_cfg_0) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_BEHOLD_H6:
fe0->dvb.frontend = dvb_attach(zl10353_attach,
&behold_h6_config,
&dev->i2c_adap);
if (fe0->dvb.frontend) {
dvb_attach(simple_tuner_attach, fe0->dvb.frontend,
&dev->i2c_adap, 0x61,
TUNER_PHILIPS_FMD1216MEX_MK3);
}
break;
case SAA7134_BOARD_BEHOLD_X7:
fe0->dvb.frontend = dvb_attach(zl10353_attach,
&behold_x7_config,
&dev->i2c_adap);
if (fe0->dvb.frontend) {
dvb_attach(xc5000_attach, fe0->dvb.frontend,
&dev->i2c_adap, &behold_x7_tunerconfig);
}
break;
case SAA7134_BOARD_BEHOLD_H7:
fe0->dvb.frontend = dvb_attach(zl10353_attach,
&behold_x7_config,
&dev->i2c_adap);
if (fe0->dvb.frontend) {
dvb_attach(xc5000_attach, fe0->dvb.frontend,
&dev->i2c_adap, &behold_x7_tunerconfig);
}
break;
case SAA7134_BOARD_AVERMEDIA_A700_PRO:
case SAA7134_BOARD_AVERMEDIA_A700_HYBRID:
/* Zarlink ZL10313 */
fe0->dvb.frontend = dvb_attach(mt312_attach,
&avertv_a700_mt312, &dev->i2c_adap);
if (fe0->dvb.frontend) {
if (dvb_attach(zl10036_attach, fe0->dvb.frontend,
&avertv_a700_tuner, &dev->i2c_adap) == NULL) {
wprintk("%s: No zl10036 found!\n",
__func__);
}
}
break;
case SAA7134_BOARD_VIDEOMATE_S350:
fe0->dvb.frontend = dvb_attach(mt312_attach,
&zl10313_compro_s350_config, &dev->i2c_adap);
if (fe0->dvb.frontend)
if (dvb_attach(zl10039_attach, fe0->dvb.frontend,
0x60, &dev->i2c_adap) == NULL)
wprintk("%s: No zl10039 found!\n",
__func__);
break;
case SAA7134_BOARD_ZOLID_HYBRID_PCI:
fe0->dvb.frontend = dvb_attach(tda10048_attach,
&zolid_tda10048_config,
&dev->i2c_adap);
if (fe0->dvb.frontend != NULL) {
dvb_attach(tda829x_attach, fe0->dvb.frontend,
&dev->i2c_adap, 0x4b,
&tda829x_no_probe);
dvb_attach(tda18271_attach, fe0->dvb.frontend,
0x60, &dev->i2c_adap,
&zolid_tda18271_config);
}
break;
case SAA7134_BOARD_LEADTEK_WINFAST_DTV1000S:
fe0->dvb.frontend = dvb_attach(tda10048_attach,
&dtv1000s_tda10048_config,
&dev->i2c_adap);
if (fe0->dvb.frontend != NULL) {
dvb_attach(tda829x_attach, fe0->dvb.frontend,
&dev->i2c_adap, 0x4b,
&tda829x_no_probe);
dvb_attach(tda18271_attach, fe0->dvb.frontend,
0x60, &dev->i2c_adap,
&dtv1000s_tda18271_config);
}
break;
case SAA7134_BOARD_KWORLD_PCI_SBTVD_FULLSEG:
/* Switch to digital mode */
saa7134_tuner_callback(dev, 0,
TDA18271_CALLBACK_CMD_AGC_ENABLE, 1);
fe0->dvb.frontend = dvb_attach(mb86a20s_attach,
&kworld_mb86a20s_config,
&dev->i2c_adap);
if (fe0->dvb.frontend != NULL) {
dvb_attach(tda829x_attach, fe0->dvb.frontend,
&dev->i2c_adap, 0x4b,
&tda829x_no_probe);
dvb_attach(tda18271_attach, fe0->dvb.frontend,
0x60, &dev->i2c_adap,
&kworld_tda18271_config);
fe0->dvb.frontend->ops.i2c_gate_ctrl = kworld_sbtvd_gate_ctrl;
}
/* mb86a20s need to use the I2C gateway */
break;
case SAA7134_BOARD_MAGICPRO_PROHDTV_PRO2:
fe0->dvb.frontend = dvb_attach(lgs8gxx_attach,
&prohdtv_pro2_lgs8g75_config,
&dev->i2c_adap);
if (fe0->dvb.frontend != NULL) {
dvb_attach(tda829x_attach, fe0->dvb.frontend,
&dev->i2c_adap, 0x4b,
&tda829x_no_probe);
dvb_attach(tda18271_attach, fe0->dvb.frontend,
0x60, &dev->i2c_adap,
&prohdtv_pro2_tda18271_config);
}
break;
default:
wprintk("Huh? unknown DVB card?\n");
break;
}
if (attach_xc3028) {
struct dvb_frontend *fe;
struct xc2028_config cfg = {
.i2c_adap = &dev->i2c_adap,
.i2c_addr = 0x61,
};
if (!fe0->dvb.frontend)
goto dettach_frontend;
fe = dvb_attach(xc2028_attach, fe0->dvb.frontend, &cfg);
if (!fe) {
printk(KERN_ERR "%s/2: xc3028 attach failed\n",
dev->name);
goto dettach_frontend;
}
}
if (NULL == fe0->dvb.frontend) {
printk(KERN_ERR "%s/dvb: frontend initialization failed\n", dev->name);
goto dettach_frontend;
}
/* define general-purpose callback pointer */
fe0->dvb.frontend->callback = saa7134_tuner_callback;
/* register everything else */
ret = videobuf_dvb_register_bus(&dev->frontends, THIS_MODULE, dev,
&dev->pci->dev, adapter_nr, 0, NULL);
/* this sequence is necessary to make the tda1004x load its firmware
* and to enter analog mode of hybrid boards
*/
if (!ret) {
if (fe0->dvb.frontend->ops.init)
fe0->dvb.frontend->ops.init(fe0->dvb.frontend);
if (fe0->dvb.frontend->ops.sleep)
fe0->dvb.frontend->ops.sleep(fe0->dvb.frontend);
if (fe0->dvb.frontend->ops.tuner_ops.sleep)
fe0->dvb.frontend->ops.tuner_ops.sleep(fe0->dvb.frontend);
}
return ret;
dettach_frontend:
videobuf_dvb_dealloc_frontends(&dev->frontends);
return -EINVAL;
}
static int dvb_fini(struct saa7134_dev *dev)
{
struct videobuf_dvb_frontend *fe0;
/* Get the first frontend */
fe0 = videobuf_dvb_get_frontend(&dev->frontends, 1);
if (!fe0)
return -EINVAL;
/* FIXME: I suspect that this code is bogus, since the entry for
Pinnacle 300I DVB-T PAL already defines the proper init to allow
the detection of mt2032 (TDA9887_PORT2_INACTIVE)
*/
if (dev->board == SAA7134_BOARD_PINNACLE_300I_DVBT_PAL) {
struct v4l2_priv_tun_config tda9887_cfg;
static int on = TDA9887_PRESENT | TDA9887_PORT2_INACTIVE;
tda9887_cfg.tuner = TUNER_TDA9887;
tda9887_cfg.priv = &on;
/* otherwise we don't detect the tuner on next insmod */
saa_call_all(dev, tuner, s_config, &tda9887_cfg);
} else if (dev->board == SAA7134_BOARD_MEDION_MD8800_QUADRO) {
if ((dev->eedata[2] == 0x07) && use_frontend) {
/* turn off the 2nd lnb supply */
u8 data = 0x80;
struct i2c_msg msg = {.addr = 0x08, .buf = &data, .flags = 0, .len = 1};
struct dvb_frontend *fe;
fe = fe0->dvb.frontend;
if (fe->ops.i2c_gate_ctrl) {
fe->ops.i2c_gate_ctrl(fe, 1);
i2c_transfer(&dev->i2c_adap, &msg, 1);
fe->ops.i2c_gate_ctrl(fe, 0);
}
}
}
videobuf_dvb_unregister_bus(&dev->frontends);
return 0;
}
static struct saa7134_mpeg_ops dvb_ops = {
.type = SAA7134_MPEG_DVB,
.init = dvb_init,
.fini = dvb_fini,
};
static int __init dvb_register(void)
{
return saa7134_ts_register(&dvb_ops);
}
static void __exit dvb_unregister(void)
{
saa7134_ts_unregister(&dvb_ops);
}
module_init(dvb_register);
module_exit(dvb_unregister);
/* ------------------------------------------------------------------ */
/*
* Local variables:
* c-basic-offset: 8
* End:
*/
| gpl-2.0 |
andi34/kernel_samsung_espresso | drivers/media/video/saa7134/saa7134-dvb.c | 2385 | 54094 | /*
*
* (c) 2004 Gerd Knorr <kraxel@bytesex.org> [SuSE Labs]
*
* Extended 3 / 2005 by Hartmut Hackmann to support various
* cards with the tda10046 DVB-T channel decoder
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/init.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/kthread.h>
#include <linux/suspend.h>
#include "saa7134-reg.h"
#include "saa7134.h"
#include <media/v4l2-common.h>
#include "dvb-pll.h"
#include <dvb_frontend.h>
#include "mt352.h"
#include "mt352_priv.h" /* FIXME */
#include "tda1004x.h"
#include "nxt200x.h"
#include "tuner-xc2028.h"
#include "xc5000.h"
#include "tda10086.h"
#include "tda826x.h"
#include "tda827x.h"
#include "isl6421.h"
#include "isl6405.h"
#include "lnbp21.h"
#include "tuner-simple.h"
#include "tda10048.h"
#include "tda18271.h"
#include "lgdt3305.h"
#include "tda8290.h"
#include "mb86a20s.h"
#include "lgs8gxx.h"
#include "zl10353.h"
#include "zl10036.h"
#include "zl10039.h"
#include "mt312.h"
MODULE_AUTHOR("Gerd Knorr <kraxel@bytesex.org> [SuSE Labs]");
MODULE_LICENSE("GPL");
static unsigned int antenna_pwr;
module_param(antenna_pwr, int, 0444);
MODULE_PARM_DESC(antenna_pwr,"enable antenna power (Pinnacle 300i)");
static int use_frontend;
module_param(use_frontend, int, 0644);
MODULE_PARM_DESC(use_frontend,"for cards with multiple frontends (0: terrestrial, 1: satellite)");
static int debug;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "Turn on/off module debugging (default:off).");
DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr);
#define dprintk(fmt, arg...) do { if (debug) \
printk(KERN_DEBUG "%s/dvb: " fmt, dev->name , ## arg); } while(0)
/* Print a warning */
#define wprintk(fmt, arg...) \
printk(KERN_WARNING "%s/dvb: " fmt, dev->name, ## arg)
/* ------------------------------------------------------------------
* mt352 based DVB-T cards
*/
static int pinnacle_antenna_pwr(struct saa7134_dev *dev, int on)
{
u32 ok;
if (!on) {
saa_setl(SAA7134_GPIO_GPMODE0 >> 2, (1 << 26));
saa_clearl(SAA7134_GPIO_GPSTATUS0 >> 2, (1 << 26));
return 0;
}
saa_setl(SAA7134_GPIO_GPMODE0 >> 2, (1 << 26));
saa_setl(SAA7134_GPIO_GPSTATUS0 >> 2, (1 << 26));
udelay(10);
saa_setl(SAA7134_GPIO_GPMODE0 >> 2, (1 << 28));
saa_clearl(SAA7134_GPIO_GPSTATUS0 >> 2, (1 << 28));
udelay(10);
saa_setl(SAA7134_GPIO_GPSTATUS0 >> 2, (1 << 28));
udelay(10);
ok = saa_readl(SAA7134_GPIO_GPSTATUS0) & (1 << 27);
dprintk("%s %s\n", __func__, ok ? "on" : "off");
if (!ok)
saa_clearl(SAA7134_GPIO_GPSTATUS0 >> 2, (1 << 26));
return ok;
}
static int mt352_pinnacle_init(struct dvb_frontend* fe)
{
static u8 clock_config [] = { CLOCK_CTL, 0x3d, 0x28 };
static u8 reset [] = { RESET, 0x80 };
static u8 adc_ctl_1_cfg [] = { ADC_CTL_1, 0x40 };
static u8 agc_cfg [] = { AGC_TARGET, 0x28, 0xa0 };
static u8 capt_range_cfg[] = { CAPT_RANGE, 0x31 };
static u8 fsm_ctl_cfg[] = { 0x7b, 0x04 };
static u8 gpp_ctl_cfg [] = { GPP_CTL, 0x0f };
static u8 scan_ctl_cfg [] = { SCAN_CTL, 0x0d };
static u8 irq_cfg [] = { INTERRUPT_EN_0, 0x00, 0x00, 0x00, 0x00 };
struct saa7134_dev *dev= fe->dvb->priv;
dprintk("%s called\n", __func__);
mt352_write(fe, clock_config, sizeof(clock_config));
udelay(200);
mt352_write(fe, reset, sizeof(reset));
mt352_write(fe, adc_ctl_1_cfg, sizeof(adc_ctl_1_cfg));
mt352_write(fe, agc_cfg, sizeof(agc_cfg));
mt352_write(fe, capt_range_cfg, sizeof(capt_range_cfg));
mt352_write(fe, gpp_ctl_cfg, sizeof(gpp_ctl_cfg));
mt352_write(fe, fsm_ctl_cfg, sizeof(fsm_ctl_cfg));
mt352_write(fe, scan_ctl_cfg, sizeof(scan_ctl_cfg));
mt352_write(fe, irq_cfg, sizeof(irq_cfg));
return 0;
}
static int mt352_aver777_init(struct dvb_frontend* fe)
{
static u8 clock_config [] = { CLOCK_CTL, 0x38, 0x2d };
static u8 reset [] = { RESET, 0x80 };
static u8 adc_ctl_1_cfg [] = { ADC_CTL_1, 0x40 };
static u8 agc_cfg [] = { AGC_TARGET, 0x28, 0xa0 };
static u8 capt_range_cfg[] = { CAPT_RANGE, 0x33 };
mt352_write(fe, clock_config, sizeof(clock_config));
udelay(200);
mt352_write(fe, reset, sizeof(reset));
mt352_write(fe, adc_ctl_1_cfg, sizeof(adc_ctl_1_cfg));
mt352_write(fe, agc_cfg, sizeof(agc_cfg));
mt352_write(fe, capt_range_cfg, sizeof(capt_range_cfg));
return 0;
}
static int mt352_avermedia_xc3028_init(struct dvb_frontend *fe)
{
static u8 clock_config [] = { CLOCK_CTL, 0x38, 0x2d };
static u8 reset [] = { RESET, 0x80 };
static u8 adc_ctl_1_cfg [] = { ADC_CTL_1, 0x40 };
static u8 agc_cfg [] = { AGC_TARGET, 0xe };
static u8 capt_range_cfg[] = { CAPT_RANGE, 0x33 };
mt352_write(fe, clock_config, sizeof(clock_config));
udelay(200);
mt352_write(fe, reset, sizeof(reset));
mt352_write(fe, adc_ctl_1_cfg, sizeof(adc_ctl_1_cfg));
mt352_write(fe, agc_cfg, sizeof(agc_cfg));
mt352_write(fe, capt_range_cfg, sizeof(capt_range_cfg));
return 0;
}
static int mt352_pinnacle_tuner_set_params(struct dvb_frontend* fe,
struct dvb_frontend_parameters* params)
{
u8 off[] = { 0x00, 0xf1};
u8 on[] = { 0x00, 0x71};
struct i2c_msg msg = {.addr=0x43, .flags=0, .buf=off, .len = sizeof(off)};
struct saa7134_dev *dev = fe->dvb->priv;
struct v4l2_frequency f;
/* set frequency (mt2050) */
f.tuner = 0;
f.type = V4L2_TUNER_DIGITAL_TV;
f.frequency = params->frequency / 1000 * 16 / 1000;
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 1);
i2c_transfer(&dev->i2c_adap, &msg, 1);
saa_call_all(dev, tuner, s_frequency, &f);
msg.buf = on;
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 1);
i2c_transfer(&dev->i2c_adap, &msg, 1);
pinnacle_antenna_pwr(dev, antenna_pwr);
/* mt352 setup */
return mt352_pinnacle_init(fe);
}
static struct mt352_config pinnacle_300i = {
.demod_address = 0x3c >> 1,
.adc_clock = 20333,
.if2 = 36150,
.no_tuner = 1,
.demod_init = mt352_pinnacle_init,
};
static struct mt352_config avermedia_777 = {
.demod_address = 0xf,
.demod_init = mt352_aver777_init,
};
static struct mt352_config avermedia_xc3028_mt352_dev = {
.demod_address = (0x1e >> 1),
.no_tuner = 1,
.demod_init = mt352_avermedia_xc3028_init,
};
static struct tda18271_std_map mb86a20s_tda18271_std_map = {
.dvbt_6 = { .if_freq = 3300, .agc_mode = 3, .std = 4,
.if_lvl = 7, .rfagc_top = 0x37, },
};
static struct tda18271_config kworld_tda18271_config = {
.std_map = &mb86a20s_tda18271_std_map,
.gate = TDA18271_GATE_DIGITAL,
.config = 3, /* Use tuner callback for AGC */
};
static const struct mb86a20s_config kworld_mb86a20s_config = {
.demod_address = 0x10,
};
static int kworld_sbtvd_gate_ctrl(struct dvb_frontend* fe, int enable)
{
struct saa7134_dev *dev = fe->dvb->priv;
unsigned char initmsg[] = {0x45, 0x97};
unsigned char msg_enable[] = {0x45, 0xc1};
unsigned char msg_disable[] = {0x45, 0x81};
struct i2c_msg msg = {.addr = 0x4b, .flags = 0, .buf = initmsg, .len = 2};
if (i2c_transfer(&dev->i2c_adap, &msg, 1) != 1) {
wprintk("could not access the I2C gate\n");
return -EIO;
}
if (enable)
msg.buf = msg_enable;
else
msg.buf = msg_disable;
if (i2c_transfer(&dev->i2c_adap, &msg, 1) != 1) {
wprintk("could not access the I2C gate\n");
return -EIO;
}
msleep(20);
return 0;
}
/* ==================================================================
* tda1004x based DVB-T cards, helper functions
*/
static int philips_tda1004x_request_firmware(struct dvb_frontend *fe,
const struct firmware **fw, char *name)
{
struct saa7134_dev *dev = fe->dvb->priv;
return request_firmware(fw, name, &dev->pci->dev);
}
/* ------------------------------------------------------------------
* these tuners are tu1216, td1316(a)
*/
static int philips_tda6651_pll_set(struct dvb_frontend *fe, struct dvb_frontend_parameters *params)
{
struct saa7134_dev *dev = fe->dvb->priv;
struct tda1004x_state *state = fe->demodulator_priv;
u8 addr = state->config->tuner_address;
u8 tuner_buf[4];
struct i2c_msg tuner_msg = {.addr = addr,.flags = 0,.buf = tuner_buf,.len =
sizeof(tuner_buf) };
int tuner_frequency = 0;
u8 band, cp, filter;
/* determine charge pump */
tuner_frequency = params->frequency + 36166000;
if (tuner_frequency < 87000000)
return -EINVAL;
else if (tuner_frequency < 130000000)
cp = 3;
else if (tuner_frequency < 160000000)
cp = 5;
else if (tuner_frequency < 200000000)
cp = 6;
else if (tuner_frequency < 290000000)
cp = 3;
else if (tuner_frequency < 420000000)
cp = 5;
else if (tuner_frequency < 480000000)
cp = 6;
else if (tuner_frequency < 620000000)
cp = 3;
else if (tuner_frequency < 830000000)
cp = 5;
else if (tuner_frequency < 895000000)
cp = 7;
else
return -EINVAL;
/* determine band */
if (params->frequency < 49000000)
return -EINVAL;
else if (params->frequency < 161000000)
band = 1;
else if (params->frequency < 444000000)
band = 2;
else if (params->frequency < 861000000)
band = 4;
else
return -EINVAL;
/* setup PLL filter */
switch (params->u.ofdm.bandwidth) {
case BANDWIDTH_6_MHZ:
filter = 0;
break;
case BANDWIDTH_7_MHZ:
filter = 0;
break;
case BANDWIDTH_8_MHZ:
filter = 1;
break;
default:
return -EINVAL;
}
/* calculate divisor
* ((36166000+((1000000/6)/2)) + Finput)/(1000000/6)
*/
tuner_frequency = (((params->frequency / 1000) * 6) + 217496) / 1000;
/* setup tuner buffer */
tuner_buf[0] = (tuner_frequency >> 8) & 0x7f;
tuner_buf[1] = tuner_frequency & 0xff;
tuner_buf[2] = 0xca;
tuner_buf[3] = (cp << 5) | (filter << 3) | band;
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 1);
if (i2c_transfer(&dev->i2c_adap, &tuner_msg, 1) != 1) {
wprintk("could not write to tuner at addr: 0x%02x\n",
addr << 1);
return -EIO;
}
msleep(1);
return 0;
}
static int philips_tu1216_init(struct dvb_frontend *fe)
{
struct saa7134_dev *dev = fe->dvb->priv;
struct tda1004x_state *state = fe->demodulator_priv;
u8 addr = state->config->tuner_address;
static u8 tu1216_init[] = { 0x0b, 0xf5, 0x85, 0xab };
struct i2c_msg tuner_msg = {.addr = addr,.flags = 0,.buf = tu1216_init,.len = sizeof(tu1216_init) };
/* setup PLL configuration */
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 1);
if (i2c_transfer(&dev->i2c_adap, &tuner_msg, 1) != 1)
return -EIO;
msleep(1);
return 0;
}
/* ------------------------------------------------------------------ */
static struct tda1004x_config philips_tu1216_60_config = {
.demod_address = 0x8,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_4M,
.agc_config = TDA10046_AGC_DEFAULT,
.if_freq = TDA10046_FREQ_3617,
.tuner_address = 0x60,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config philips_tu1216_61_config = {
.demod_address = 0x8,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_4M,
.agc_config = TDA10046_AGC_DEFAULT,
.if_freq = TDA10046_FREQ_3617,
.tuner_address = 0x61,
.request_firmware = philips_tda1004x_request_firmware
};
/* ------------------------------------------------------------------ */
static int philips_td1316_tuner_init(struct dvb_frontend *fe)
{
struct saa7134_dev *dev = fe->dvb->priv;
struct tda1004x_state *state = fe->demodulator_priv;
u8 addr = state->config->tuner_address;
static u8 msg[] = { 0x0b, 0xf5, 0x86, 0xab };
struct i2c_msg init_msg = {.addr = addr,.flags = 0,.buf = msg,.len = sizeof(msg) };
/* setup PLL configuration */
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 1);
if (i2c_transfer(&dev->i2c_adap, &init_msg, 1) != 1)
return -EIO;
return 0;
}
static int philips_td1316_tuner_set_params(struct dvb_frontend *fe, struct dvb_frontend_parameters *params)
{
return philips_tda6651_pll_set(fe, params);
}
static int philips_td1316_tuner_sleep(struct dvb_frontend *fe)
{
struct saa7134_dev *dev = fe->dvb->priv;
struct tda1004x_state *state = fe->demodulator_priv;
u8 addr = state->config->tuner_address;
static u8 msg[] = { 0x0b, 0xdc, 0x86, 0xa4 };
struct i2c_msg analog_msg = {.addr = addr,.flags = 0,.buf = msg,.len = sizeof(msg) };
/* switch the tuner to analog mode */
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 1);
if (i2c_transfer(&dev->i2c_adap, &analog_msg, 1) != 1)
return -EIO;
return 0;
}
/* ------------------------------------------------------------------ */
static int philips_europa_tuner_init(struct dvb_frontend *fe)
{
struct saa7134_dev *dev = fe->dvb->priv;
static u8 msg[] = { 0x00, 0x40};
struct i2c_msg init_msg = {.addr = 0x43,.flags = 0,.buf = msg,.len = sizeof(msg) };
if (philips_td1316_tuner_init(fe))
return -EIO;
msleep(1);
if (i2c_transfer(&dev->i2c_adap, &init_msg, 1) != 1)
return -EIO;
return 0;
}
static int philips_europa_tuner_sleep(struct dvb_frontend *fe)
{
struct saa7134_dev *dev = fe->dvb->priv;
static u8 msg[] = { 0x00, 0x14 };
struct i2c_msg analog_msg = {.addr = 0x43,.flags = 0,.buf = msg,.len = sizeof(msg) };
if (philips_td1316_tuner_sleep(fe))
return -EIO;
/* switch the board to analog mode */
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 1);
i2c_transfer(&dev->i2c_adap, &analog_msg, 1);
return 0;
}
static int philips_europa_demod_sleep(struct dvb_frontend *fe)
{
struct saa7134_dev *dev = fe->dvb->priv;
if (dev->original_demod_sleep)
dev->original_demod_sleep(fe);
fe->ops.i2c_gate_ctrl(fe, 1);
return 0;
}
static struct tda1004x_config philips_europa_config = {
.demod_address = 0x8,
.invert = 0,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_4M,
.agc_config = TDA10046_AGC_IFO_AUTO_POS,
.if_freq = TDA10046_FREQ_052,
.tuner_address = 0x61,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config medion_cardbus = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_IFO_AUTO_NEG,
.if_freq = TDA10046_FREQ_3613,
.tuner_address = 0x61,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config technotrend_budget_t3000_config = {
.demod_address = 0x8,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_4M,
.agc_config = TDA10046_AGC_DEFAULT,
.if_freq = TDA10046_FREQ_3617,
.tuner_address = 0x63,
.request_firmware = philips_tda1004x_request_firmware
};
/* ------------------------------------------------------------------
* tda 1004x based cards with philips silicon tuner
*/
static int tda8290_i2c_gate_ctrl( struct dvb_frontend* fe, int enable)
{
struct tda1004x_state *state = fe->demodulator_priv;
u8 addr = state->config->i2c_gate;
static u8 tda8290_close[] = { 0x21, 0xc0};
static u8 tda8290_open[] = { 0x21, 0x80};
struct i2c_msg tda8290_msg = {.addr = addr,.flags = 0, .len = 2};
if (enable) {
tda8290_msg.buf = tda8290_close;
} else {
tda8290_msg.buf = tda8290_open;
}
if (i2c_transfer(state->i2c, &tda8290_msg, 1) != 1) {
struct saa7134_dev *dev = fe->dvb->priv;
wprintk("could not access tda8290 I2C gate\n");
return -EIO;
}
msleep(20);
return 0;
}
static int philips_tda827x_tuner_init(struct dvb_frontend *fe)
{
struct saa7134_dev *dev = fe->dvb->priv;
struct tda1004x_state *state = fe->demodulator_priv;
switch (state->config->antenna_switch) {
case 0: break;
case 1: dprintk("setting GPIO21 to 0 (TV antenna?)\n");
saa7134_set_gpio(dev, 21, 0);
break;
case 2: dprintk("setting GPIO21 to 1 (Radio antenna?)\n");
saa7134_set_gpio(dev, 21, 1);
break;
}
return 0;
}
static int philips_tda827x_tuner_sleep(struct dvb_frontend *fe)
{
struct saa7134_dev *dev = fe->dvb->priv;
struct tda1004x_state *state = fe->demodulator_priv;
switch (state->config->antenna_switch) {
case 0: break;
case 1: dprintk("setting GPIO21 to 1 (Radio antenna?)\n");
saa7134_set_gpio(dev, 21, 1);
break;
case 2: dprintk("setting GPIO21 to 0 (TV antenna?)\n");
saa7134_set_gpio(dev, 21, 0);
break;
}
return 0;
}
static int configure_tda827x_fe(struct saa7134_dev *dev,
struct tda1004x_config *cdec_conf,
struct tda827x_config *tuner_conf)
{
struct videobuf_dvb_frontend *fe0;
/* Get the first frontend */
fe0 = videobuf_dvb_get_frontend(&dev->frontends, 1);
fe0->dvb.frontend = dvb_attach(tda10046_attach, cdec_conf, &dev->i2c_adap);
if (fe0->dvb.frontend) {
if (cdec_conf->i2c_gate)
fe0->dvb.frontend->ops.i2c_gate_ctrl = tda8290_i2c_gate_ctrl;
if (dvb_attach(tda827x_attach, fe0->dvb.frontend,
cdec_conf->tuner_address,
&dev->i2c_adap, tuner_conf))
return 0;
wprintk("no tda827x tuner found at addr: %02x\n",
cdec_conf->tuner_address);
}
return -EINVAL;
}
/* ------------------------------------------------------------------ */
static struct tda827x_config tda827x_cfg_0 = {
.init = philips_tda827x_tuner_init,
.sleep = philips_tda827x_tuner_sleep,
.config = 0,
.switch_addr = 0
};
static struct tda827x_config tda827x_cfg_1 = {
.init = philips_tda827x_tuner_init,
.sleep = philips_tda827x_tuner_sleep,
.config = 1,
.switch_addr = 0x4b
};
static struct tda827x_config tda827x_cfg_2 = {
.init = philips_tda827x_tuner_init,
.sleep = philips_tda827x_tuner_sleep,
.config = 2,
.switch_addr = 0x4b
};
static struct tda827x_config tda827x_cfg_2_sw42 = {
.init = philips_tda827x_tuner_init,
.sleep = philips_tda827x_tuner_sleep,
.config = 2,
.switch_addr = 0x42
};
/* ------------------------------------------------------------------ */
static struct tda1004x_config tda827x_lifeview_config = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP11_I,
.if_freq = TDA10046_FREQ_045,
.tuner_address = 0x60,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config philips_tiger_config = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP11_I,
.if_freq = TDA10046_FREQ_045,
.i2c_gate = 0x4b,
.tuner_address = 0x61,
.antenna_switch= 1,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config cinergy_ht_config = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP01_I,
.if_freq = TDA10046_FREQ_045,
.i2c_gate = 0x4b,
.tuner_address = 0x61,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config cinergy_ht_pci_config = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP01_I,
.if_freq = TDA10046_FREQ_045,
.i2c_gate = 0x4b,
.tuner_address = 0x60,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config philips_tiger_s_config = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP01_I,
.if_freq = TDA10046_FREQ_045,
.i2c_gate = 0x4b,
.tuner_address = 0x61,
.antenna_switch= 1,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config pinnacle_pctv_310i_config = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP11_I,
.if_freq = TDA10046_FREQ_045,
.i2c_gate = 0x4b,
.tuner_address = 0x61,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config hauppauge_hvr_1110_config = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP11_I,
.if_freq = TDA10046_FREQ_045,
.i2c_gate = 0x4b,
.tuner_address = 0x61,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config asus_p7131_dual_config = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP11_I,
.if_freq = TDA10046_FREQ_045,
.i2c_gate = 0x4b,
.tuner_address = 0x61,
.antenna_switch= 2,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config lifeview_trio_config = {
.demod_address = 0x09,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP00_I,
.if_freq = TDA10046_FREQ_045,
.tuner_address = 0x60,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config tevion_dvbt220rf_config = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP11_I,
.if_freq = TDA10046_FREQ_045,
.tuner_address = 0x60,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config md8800_dvbt_config = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP01_I,
.if_freq = TDA10046_FREQ_045,
.i2c_gate = 0x4b,
.tuner_address = 0x60,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config asus_p7131_4871_config = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP01_I,
.if_freq = TDA10046_FREQ_045,
.i2c_gate = 0x4b,
.tuner_address = 0x61,
.antenna_switch= 2,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config asus_p7131_hybrid_lna_config = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP11_I,
.if_freq = TDA10046_FREQ_045,
.i2c_gate = 0x4b,
.tuner_address = 0x61,
.antenna_switch= 2,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config kworld_dvb_t_210_config = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP11_I,
.if_freq = TDA10046_FREQ_045,
.i2c_gate = 0x4b,
.tuner_address = 0x61,
.antenna_switch= 1,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config avermedia_super_007_config = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP01_I,
.if_freq = TDA10046_FREQ_045,
.i2c_gate = 0x4b,
.tuner_address = 0x60,
.antenna_switch= 1,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config twinhan_dtv_dvb_3056_config = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP01_I,
.if_freq = TDA10046_FREQ_045,
.i2c_gate = 0x42,
.tuner_address = 0x61,
.antenna_switch = 1,
.request_firmware = philips_tda1004x_request_firmware
};
static struct tda1004x_config asus_tiger_3in1_config = {
.demod_address = 0x0b,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP11_I,
.if_freq = TDA10046_FREQ_045,
.i2c_gate = 0x4b,
.tuner_address = 0x61,
.antenna_switch = 1,
.request_firmware = philips_tda1004x_request_firmware
};
/* ------------------------------------------------------------------
* special case: this card uses saa713x GPIO22 for the mode switch
*/
static int ads_duo_tuner_init(struct dvb_frontend *fe)
{
struct saa7134_dev *dev = fe->dvb->priv;
philips_tda827x_tuner_init(fe);
/* route TDA8275a AGC input to the channel decoder */
saa7134_set_gpio(dev, 22, 1);
return 0;
}
static int ads_duo_tuner_sleep(struct dvb_frontend *fe)
{
struct saa7134_dev *dev = fe->dvb->priv;
/* route TDA8275a AGC input to the analog IF chip*/
saa7134_set_gpio(dev, 22, 0);
philips_tda827x_tuner_sleep(fe);
return 0;
}
static struct tda827x_config ads_duo_cfg = {
.init = ads_duo_tuner_init,
.sleep = ads_duo_tuner_sleep,
.config = 0
};
static struct tda1004x_config ads_tech_duo_config = {
.demod_address = 0x08,
.invert = 1,
.invert_oclk = 0,
.xtal_freq = TDA10046_XTAL_16M,
.agc_config = TDA10046_AGC_TDA827X,
.gpio_config = TDA10046_GP00_I,
.if_freq = TDA10046_FREQ_045,
.tuner_address = 0x61,
.request_firmware = philips_tda1004x_request_firmware
};
static struct zl10353_config behold_h6_config = {
.demod_address = 0x1e>>1,
.no_tuner = 1,
.parallel_ts = 1,
.disable_i2c_gate_ctrl = 1,
};
static struct xc5000_config behold_x7_tunerconfig = {
.i2c_address = 0xc2>>1,
.if_khz = 4560,
.radio_input = XC5000_RADIO_FM1,
};
static struct zl10353_config behold_x7_config = {
.demod_address = 0x1e>>1,
.if2 = 45600,
.no_tuner = 1,
.parallel_ts = 1,
.disable_i2c_gate_ctrl = 1,
};
/* ==================================================================
* tda10086 based DVB-S cards, helper functions
*/
static struct tda10086_config flydvbs = {
.demod_address = 0x0e,
.invert = 0,
.diseqc_tone = 0,
.xtal_freq = TDA10086_XTAL_16M,
};
static struct tda10086_config sd1878_4m = {
.demod_address = 0x0e,
.invert = 0,
.diseqc_tone = 0,
.xtal_freq = TDA10086_XTAL_4M,
};
/* ------------------------------------------------------------------
* special case: lnb supply is connected to the gated i2c
*/
static int md8800_set_voltage(struct dvb_frontend *fe, fe_sec_voltage_t voltage)
{
int res = -EIO;
struct saa7134_dev *dev = fe->dvb->priv;
if (fe->ops.i2c_gate_ctrl) {
fe->ops.i2c_gate_ctrl(fe, 1);
if (dev->original_set_voltage)
res = dev->original_set_voltage(fe, voltage);
fe->ops.i2c_gate_ctrl(fe, 0);
}
return res;
};
static int md8800_set_high_voltage(struct dvb_frontend *fe, long arg)
{
int res = -EIO;
struct saa7134_dev *dev = fe->dvb->priv;
if (fe->ops.i2c_gate_ctrl) {
fe->ops.i2c_gate_ctrl(fe, 1);
if (dev->original_set_high_voltage)
res = dev->original_set_high_voltage(fe, arg);
fe->ops.i2c_gate_ctrl(fe, 0);
}
return res;
};
static int md8800_set_voltage2(struct dvb_frontend *fe, fe_sec_voltage_t voltage)
{
struct saa7134_dev *dev = fe->dvb->priv;
u8 wbuf[2] = { 0x1f, 00 };
u8 rbuf;
struct i2c_msg msg[] = { { .addr = 0x08, .flags = 0, .buf = wbuf, .len = 1 },
{ .addr = 0x08, .flags = I2C_M_RD, .buf = &rbuf, .len = 1 } };
if (i2c_transfer(&dev->i2c_adap, msg, 2) != 2)
return -EIO;
/* NOTE: this assumes that gpo1 is used, it might be bit 5 (gpo2) */
if (voltage == SEC_VOLTAGE_18)
wbuf[1] = rbuf | 0x10;
else
wbuf[1] = rbuf & 0xef;
msg[0].len = 2;
i2c_transfer(&dev->i2c_adap, msg, 1);
return 0;
}
static int md8800_set_high_voltage2(struct dvb_frontend *fe, long arg)
{
struct saa7134_dev *dev = fe->dvb->priv;
wprintk("%s: sorry can't set high LNB supply voltage from here\n", __func__);
return -EIO;
}
/* ==================================================================
* nxt200x based ATSC cards, helper functions
*/
static struct nxt200x_config avertvhda180 = {
.demod_address = 0x0a,
};
static struct nxt200x_config kworldatsc110 = {
.demod_address = 0x0a,
};
/* ------------------------------------------------------------------ */
static struct mt312_config avertv_a700_mt312 = {
.demod_address = 0x0e,
.voltage_inverted = 1,
};
static struct zl10036_config avertv_a700_tuner = {
.tuner_address = 0x60,
};
static struct mt312_config zl10313_compro_s350_config = {
.demod_address = 0x0e,
};
static struct lgdt3305_config hcw_lgdt3305_config = {
.i2c_addr = 0x0e,
.mpeg_mode = LGDT3305_MPEG_SERIAL,
.tpclk_edge = LGDT3305_TPCLK_RISING_EDGE,
.tpvalid_polarity = LGDT3305_TP_VALID_HIGH,
.deny_i2c_rptr = 1,
.spectral_inversion = 1,
.qam_if_khz = 4000,
.vsb_if_khz = 3250,
};
static struct tda10048_config hcw_tda10048_config = {
.demod_address = 0x10 >> 1,
.output_mode = TDA10048_SERIAL_OUTPUT,
.fwbulkwritelen = TDA10048_BULKWRITE_200,
.inversion = TDA10048_INVERSION_ON,
.dtv6_if_freq_khz = TDA10048_IF_3300,
.dtv7_if_freq_khz = TDA10048_IF_3500,
.dtv8_if_freq_khz = TDA10048_IF_4000,
.clk_freq_khz = TDA10048_CLK_16000,
.disable_gate_access = 1,
};
static struct tda18271_std_map hauppauge_tda18271_std_map = {
.atsc_6 = { .if_freq = 3250, .agc_mode = 3, .std = 4,
.if_lvl = 1, .rfagc_top = 0x58, },
.qam_6 = { .if_freq = 4000, .agc_mode = 3, .std = 5,
.if_lvl = 1, .rfagc_top = 0x58, },
};
static struct tda18271_config hcw_tda18271_config = {
.std_map = &hauppauge_tda18271_std_map,
.gate = TDA18271_GATE_ANALOG,
.config = 3,
.output_opt = TDA18271_OUTPUT_LT_OFF,
};
static struct tda829x_config tda829x_no_probe = {
.probe_tuner = TDA829X_DONT_PROBE,
};
static struct tda10048_config zolid_tda10048_config = {
.demod_address = 0x10 >> 1,
.output_mode = TDA10048_PARALLEL_OUTPUT,
.fwbulkwritelen = TDA10048_BULKWRITE_200,
.inversion = TDA10048_INVERSION_ON,
.dtv6_if_freq_khz = TDA10048_IF_3300,
.dtv7_if_freq_khz = TDA10048_IF_3500,
.dtv8_if_freq_khz = TDA10048_IF_4000,
.clk_freq_khz = TDA10048_CLK_16000,
.disable_gate_access = 1,
};
static struct tda18271_config zolid_tda18271_config = {
.gate = TDA18271_GATE_ANALOG,
};
static struct tda10048_config dtv1000s_tda10048_config = {
.demod_address = 0x10 >> 1,
.output_mode = TDA10048_PARALLEL_OUTPUT,
.fwbulkwritelen = TDA10048_BULKWRITE_200,
.inversion = TDA10048_INVERSION_ON,
.dtv6_if_freq_khz = TDA10048_IF_3300,
.dtv7_if_freq_khz = TDA10048_IF_3800,
.dtv8_if_freq_khz = TDA10048_IF_4300,
.clk_freq_khz = TDA10048_CLK_16000,
.disable_gate_access = 1,
};
static struct tda18271_std_map dtv1000s_tda18271_std_map = {
.dvbt_6 = { .if_freq = 3300, .agc_mode = 3, .std = 4,
.if_lvl = 1, .rfagc_top = 0x37, },
.dvbt_7 = { .if_freq = 3800, .agc_mode = 3, .std = 5,
.if_lvl = 1, .rfagc_top = 0x37, },
.dvbt_8 = { .if_freq = 4300, .agc_mode = 3, .std = 6,
.if_lvl = 1, .rfagc_top = 0x37, },
};
static struct tda18271_config dtv1000s_tda18271_config = {
.std_map = &dtv1000s_tda18271_std_map,
.gate = TDA18271_GATE_ANALOG,
};
static struct lgs8gxx_config prohdtv_pro2_lgs8g75_config = {
.prod = LGS8GXX_PROD_LGS8G75,
.demod_address = 0x1d,
.serial_ts = 0,
.ts_clk_pol = 1,
.ts_clk_gated = 0,
.if_clk_freq = 30400, /* 30.4 MHz */
.if_freq = 4000, /* 4.00 MHz */
.if_neg_center = 0,
.ext_adc = 0,
.adc_signed = 1,
.adc_vpp = 3, /* 2.0 Vpp */
.if_neg_edge = 1,
};
static struct tda18271_config prohdtv_pro2_tda18271_config = {
.gate = TDA18271_GATE_ANALOG,
.output_opt = TDA18271_OUTPUT_LT_OFF,
};
/* ==================================================================
* Core code
*/
static int dvb_init(struct saa7134_dev *dev)
{
int ret;
int attach_xc3028 = 0;
struct videobuf_dvb_frontend *fe0;
/* FIXME: add support for multi-frontend */
mutex_init(&dev->frontends.lock);
INIT_LIST_HEAD(&dev->frontends.felist);
printk(KERN_INFO "%s() allocating 1 frontend\n", __func__);
fe0 = videobuf_dvb_alloc_frontend(&dev->frontends, 1);
if (!fe0) {
printk(KERN_ERR "%s() failed to alloc\n", __func__);
return -ENOMEM;
}
/* init struct videobuf_dvb */
dev->ts.nr_bufs = 32;
dev->ts.nr_packets = 32*4;
fe0->dvb.name = dev->name;
videobuf_queue_sg_init(&fe0->dvb.dvbq, &saa7134_ts_qops,
&dev->pci->dev, &dev->slock,
V4L2_BUF_TYPE_VIDEO_CAPTURE,
V4L2_FIELD_ALTERNATE,
sizeof(struct saa7134_buf),
dev, NULL);
switch (dev->board) {
case SAA7134_BOARD_PINNACLE_300I_DVBT_PAL:
dprintk("pinnacle 300i dvb setup\n");
fe0->dvb.frontend = dvb_attach(mt352_attach, &pinnacle_300i,
&dev->i2c_adap);
if (fe0->dvb.frontend) {
fe0->dvb.frontend->ops.tuner_ops.set_params = mt352_pinnacle_tuner_set_params;
}
break;
case SAA7134_BOARD_AVERMEDIA_777:
case SAA7134_BOARD_AVERMEDIA_A16AR:
dprintk("avertv 777 dvb setup\n");
fe0->dvb.frontend = dvb_attach(mt352_attach, &avermedia_777,
&dev->i2c_adap);
if (fe0->dvb.frontend) {
dvb_attach(simple_tuner_attach, fe0->dvb.frontend,
&dev->i2c_adap, 0x61,
TUNER_PHILIPS_TD1316);
}
break;
case SAA7134_BOARD_AVERMEDIA_A16D:
dprintk("AverMedia A16D dvb setup\n");
fe0->dvb.frontend = dvb_attach(mt352_attach,
&avermedia_xc3028_mt352_dev,
&dev->i2c_adap);
attach_xc3028 = 1;
break;
case SAA7134_BOARD_MD7134:
fe0->dvb.frontend = dvb_attach(tda10046_attach,
&medion_cardbus,
&dev->i2c_adap);
if (fe0->dvb.frontend) {
dvb_attach(simple_tuner_attach, fe0->dvb.frontend,
&dev->i2c_adap, medion_cardbus.tuner_address,
TUNER_PHILIPS_FMD1216ME_MK3);
}
break;
case SAA7134_BOARD_PHILIPS_TOUGH:
fe0->dvb.frontend = dvb_attach(tda10046_attach,
&philips_tu1216_60_config,
&dev->i2c_adap);
if (fe0->dvb.frontend) {
fe0->dvb.frontend->ops.tuner_ops.init = philips_tu1216_init;
fe0->dvb.frontend->ops.tuner_ops.set_params = philips_tda6651_pll_set;
}
break;
case SAA7134_BOARD_FLYDVBTDUO:
case SAA7134_BOARD_FLYDVBT_DUO_CARDBUS:
if (configure_tda827x_fe(dev, &tda827x_lifeview_config,
&tda827x_cfg_0) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_PHILIPS_EUROPA:
case SAA7134_BOARD_VIDEOMATE_DVBT_300:
case SAA7134_BOARD_ASUS_EUROPA_HYBRID:
fe0->dvb.frontend = dvb_attach(tda10046_attach,
&philips_europa_config,
&dev->i2c_adap);
if (fe0->dvb.frontend) {
dev->original_demod_sleep = fe0->dvb.frontend->ops.sleep;
fe0->dvb.frontend->ops.sleep = philips_europa_demod_sleep;
fe0->dvb.frontend->ops.tuner_ops.init = philips_europa_tuner_init;
fe0->dvb.frontend->ops.tuner_ops.sleep = philips_europa_tuner_sleep;
fe0->dvb.frontend->ops.tuner_ops.set_params = philips_td1316_tuner_set_params;
}
break;
case SAA7134_BOARD_TECHNOTREND_BUDGET_T3000:
fe0->dvb.frontend = dvb_attach(tda10046_attach,
&technotrend_budget_t3000_config,
&dev->i2c_adap);
if (fe0->dvb.frontend) {
dev->original_demod_sleep = fe0->dvb.frontend->ops.sleep;
fe0->dvb.frontend->ops.sleep = philips_europa_demod_sleep;
fe0->dvb.frontend->ops.tuner_ops.init = philips_europa_tuner_init;
fe0->dvb.frontend->ops.tuner_ops.sleep = philips_europa_tuner_sleep;
fe0->dvb.frontend->ops.tuner_ops.set_params = philips_td1316_tuner_set_params;
}
break;
case SAA7134_BOARD_VIDEOMATE_DVBT_200:
fe0->dvb.frontend = dvb_attach(tda10046_attach,
&philips_tu1216_61_config,
&dev->i2c_adap);
if (fe0->dvb.frontend) {
fe0->dvb.frontend->ops.tuner_ops.init = philips_tu1216_init;
fe0->dvb.frontend->ops.tuner_ops.set_params = philips_tda6651_pll_set;
}
break;
case SAA7134_BOARD_KWORLD_DVBT_210:
if (configure_tda827x_fe(dev, &kworld_dvb_t_210_config,
&tda827x_cfg_2) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_HAUPPAUGE_HVR1120:
fe0->dvb.frontend = dvb_attach(tda10048_attach,
&hcw_tda10048_config,
&dev->i2c_adap);
if (fe0->dvb.frontend != NULL) {
dvb_attach(tda829x_attach, fe0->dvb.frontend,
&dev->i2c_adap, 0x4b,
&tda829x_no_probe);
dvb_attach(tda18271_attach, fe0->dvb.frontend,
0x60, &dev->i2c_adap,
&hcw_tda18271_config);
}
break;
case SAA7134_BOARD_PHILIPS_TIGER:
if (configure_tda827x_fe(dev, &philips_tiger_config,
&tda827x_cfg_0) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_PINNACLE_PCTV_310i:
if (configure_tda827x_fe(dev, &pinnacle_pctv_310i_config,
&tda827x_cfg_1) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_HAUPPAUGE_HVR1110:
if (configure_tda827x_fe(dev, &hauppauge_hvr_1110_config,
&tda827x_cfg_1) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_HAUPPAUGE_HVR1150:
fe0->dvb.frontend = dvb_attach(lgdt3305_attach,
&hcw_lgdt3305_config,
&dev->i2c_adap);
if (fe0->dvb.frontend) {
dvb_attach(tda829x_attach, fe0->dvb.frontend,
&dev->i2c_adap, 0x4b,
&tda829x_no_probe);
dvb_attach(tda18271_attach, fe0->dvb.frontend,
0x60, &dev->i2c_adap,
&hcw_tda18271_config);
}
break;
case SAA7134_BOARD_ASUSTeK_P7131_DUAL:
if (configure_tda827x_fe(dev, &asus_p7131_dual_config,
&tda827x_cfg_0) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_FLYDVBT_LR301:
if (configure_tda827x_fe(dev, &tda827x_lifeview_config,
&tda827x_cfg_0) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_FLYDVB_TRIO:
if (!use_frontend) { /* terrestrial */
if (configure_tda827x_fe(dev, &lifeview_trio_config,
&tda827x_cfg_0) < 0)
goto dettach_frontend;
} else { /* satellite */
fe0->dvb.frontend = dvb_attach(tda10086_attach, &flydvbs, &dev->i2c_adap);
if (fe0->dvb.frontend) {
if (dvb_attach(tda826x_attach, fe0->dvb.frontend, 0x63,
&dev->i2c_adap, 0) == NULL) {
wprintk("%s: Lifeview Trio, No tda826x found!\n", __func__);
goto dettach_frontend;
}
if (dvb_attach(isl6421_attach, fe0->dvb.frontend, &dev->i2c_adap,
0x08, 0, 0) == NULL) {
wprintk("%s: Lifeview Trio, No ISL6421 found!\n", __func__);
goto dettach_frontend;
}
}
}
break;
case SAA7134_BOARD_ADS_DUO_CARDBUS_PTV331:
case SAA7134_BOARD_FLYDVBT_HYBRID_CARDBUS:
fe0->dvb.frontend = dvb_attach(tda10046_attach,
&ads_tech_duo_config,
&dev->i2c_adap);
if (fe0->dvb.frontend) {
if (dvb_attach(tda827x_attach,fe0->dvb.frontend,
ads_tech_duo_config.tuner_address, &dev->i2c_adap,
&ads_duo_cfg) == NULL) {
wprintk("no tda827x tuner found at addr: %02x\n",
ads_tech_duo_config.tuner_address);
goto dettach_frontend;
}
} else
wprintk("failed to attach tda10046\n");
break;
case SAA7134_BOARD_TEVION_DVBT_220RF:
if (configure_tda827x_fe(dev, &tevion_dvbt220rf_config,
&tda827x_cfg_0) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_MEDION_MD8800_QUADRO:
if (!use_frontend) { /* terrestrial */
if (configure_tda827x_fe(dev, &md8800_dvbt_config,
&tda827x_cfg_0) < 0)
goto dettach_frontend;
} else { /* satellite */
fe0->dvb.frontend = dvb_attach(tda10086_attach,
&flydvbs, &dev->i2c_adap);
if (fe0->dvb.frontend) {
struct dvb_frontend *fe = fe0->dvb.frontend;
u8 dev_id = dev->eedata[2];
u8 data = 0xc4;
struct i2c_msg msg = {.addr = 0x08, .flags = 0, .len = 1};
if (dvb_attach(tda826x_attach, fe0->dvb.frontend,
0x60, &dev->i2c_adap, 0) == NULL) {
wprintk("%s: Medion Quadro, no tda826x "
"found !\n", __func__);
goto dettach_frontend;
}
if (dev_id != 0x08) {
/* we need to open the i2c gate (we know it exists) */
fe->ops.i2c_gate_ctrl(fe, 1);
if (dvb_attach(isl6405_attach, fe,
&dev->i2c_adap, 0x08, 0, 0) == NULL) {
wprintk("%s: Medion Quadro, no ISL6405 "
"found !\n", __func__);
goto dettach_frontend;
}
if (dev_id == 0x07) {
/* fire up the 2nd section of the LNB supply since
we can't do this from the other section */
msg.buf = &data;
i2c_transfer(&dev->i2c_adap, &msg, 1);
}
fe->ops.i2c_gate_ctrl(fe, 0);
dev->original_set_voltage = fe->ops.set_voltage;
fe->ops.set_voltage = md8800_set_voltage;
dev->original_set_high_voltage = fe->ops.enable_high_lnb_voltage;
fe->ops.enable_high_lnb_voltage = md8800_set_high_voltage;
} else {
fe->ops.set_voltage = md8800_set_voltage2;
fe->ops.enable_high_lnb_voltage = md8800_set_high_voltage2;
}
}
}
break;
case SAA7134_BOARD_AVERMEDIA_AVERTVHD_A180:
fe0->dvb.frontend = dvb_attach(nxt200x_attach, &avertvhda180,
&dev->i2c_adap);
if (fe0->dvb.frontend)
dvb_attach(dvb_pll_attach, fe0->dvb.frontend, 0x61,
NULL, DVB_PLL_TDHU2);
break;
case SAA7134_BOARD_ADS_INSTANT_HDTV_PCI:
case SAA7134_BOARD_KWORLD_ATSC110:
fe0->dvb.frontend = dvb_attach(nxt200x_attach, &kworldatsc110,
&dev->i2c_adap);
if (fe0->dvb.frontend)
dvb_attach(simple_tuner_attach, fe0->dvb.frontend,
&dev->i2c_adap, 0x61,
TUNER_PHILIPS_TUV1236D);
break;
case SAA7134_BOARD_FLYDVBS_LR300:
fe0->dvb.frontend = dvb_attach(tda10086_attach, &flydvbs,
&dev->i2c_adap);
if (fe0->dvb.frontend) {
if (dvb_attach(tda826x_attach, fe0->dvb.frontend, 0x60,
&dev->i2c_adap, 0) == NULL) {
wprintk("%s: No tda826x found!\n", __func__);
goto dettach_frontend;
}
if (dvb_attach(isl6421_attach, fe0->dvb.frontend,
&dev->i2c_adap, 0x08, 0, 0) == NULL) {
wprintk("%s: No ISL6421 found!\n", __func__);
goto dettach_frontend;
}
}
break;
case SAA7134_BOARD_ASUS_EUROPA2_HYBRID:
fe0->dvb.frontend = dvb_attach(tda10046_attach,
&medion_cardbus,
&dev->i2c_adap);
if (fe0->dvb.frontend) {
dev->original_demod_sleep = fe0->dvb.frontend->ops.sleep;
fe0->dvb.frontend->ops.sleep = philips_europa_demod_sleep;
dvb_attach(simple_tuner_attach, fe0->dvb.frontend,
&dev->i2c_adap, medion_cardbus.tuner_address,
TUNER_PHILIPS_FMD1216ME_MK3);
}
break;
case SAA7134_BOARD_VIDEOMATE_DVBT_200A:
fe0->dvb.frontend = dvb_attach(tda10046_attach,
&philips_europa_config,
&dev->i2c_adap);
if (fe0->dvb.frontend) {
fe0->dvb.frontend->ops.tuner_ops.init = philips_td1316_tuner_init;
fe0->dvb.frontend->ops.tuner_ops.set_params = philips_td1316_tuner_set_params;
}
break;
case SAA7134_BOARD_CINERGY_HT_PCMCIA:
if (configure_tda827x_fe(dev, &cinergy_ht_config,
&tda827x_cfg_0) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_CINERGY_HT_PCI:
if (configure_tda827x_fe(dev, &cinergy_ht_pci_config,
&tda827x_cfg_0) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_PHILIPS_TIGER_S:
if (configure_tda827x_fe(dev, &philips_tiger_s_config,
&tda827x_cfg_2) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_ASUS_P7131_4871:
if (configure_tda827x_fe(dev, &asus_p7131_4871_config,
&tda827x_cfg_2) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_ASUSTeK_P7131_HYBRID_LNA:
if (configure_tda827x_fe(dev, &asus_p7131_hybrid_lna_config,
&tda827x_cfg_2) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_AVERMEDIA_SUPER_007:
if (configure_tda827x_fe(dev, &avermedia_super_007_config,
&tda827x_cfg_0) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_TWINHAN_DTV_DVB_3056:
if (configure_tda827x_fe(dev, &twinhan_dtv_dvb_3056_config,
&tda827x_cfg_2_sw42) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_PHILIPS_SNAKE:
fe0->dvb.frontend = dvb_attach(tda10086_attach, &flydvbs,
&dev->i2c_adap);
if (fe0->dvb.frontend) {
if (dvb_attach(tda826x_attach, fe0->dvb.frontend, 0x60,
&dev->i2c_adap, 0) == NULL) {
wprintk("%s: No tda826x found!\n", __func__);
goto dettach_frontend;
}
if (dvb_attach(lnbp21_attach, fe0->dvb.frontend,
&dev->i2c_adap, 0, 0) == NULL) {
wprintk("%s: No lnbp21 found!\n", __func__);
goto dettach_frontend;
}
}
break;
case SAA7134_BOARD_CREATIX_CTX953:
if (configure_tda827x_fe(dev, &md8800_dvbt_config,
&tda827x_cfg_0) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_MSI_TVANYWHERE_AD11:
if (configure_tda827x_fe(dev, &philips_tiger_s_config,
&tda827x_cfg_2) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_AVERMEDIA_CARDBUS_506:
dprintk("AverMedia E506R dvb setup\n");
saa7134_set_gpio(dev, 25, 0);
msleep(10);
saa7134_set_gpio(dev, 25, 1);
fe0->dvb.frontend = dvb_attach(mt352_attach,
&avermedia_xc3028_mt352_dev,
&dev->i2c_adap);
attach_xc3028 = 1;
break;
case SAA7134_BOARD_MD7134_BRIDGE_2:
fe0->dvb.frontend = dvb_attach(tda10086_attach,
&sd1878_4m, &dev->i2c_adap);
if (fe0->dvb.frontend) {
struct dvb_frontend *fe;
if (dvb_attach(dvb_pll_attach, fe0->dvb.frontend, 0x60,
&dev->i2c_adap, DVB_PLL_PHILIPS_SD1878_TDA8261) == NULL) {
wprintk("%s: MD7134 DVB-S, no SD1878 "
"found !\n", __func__);
goto dettach_frontend;
}
/* we need to open the i2c gate (we know it exists) */
fe = fe0->dvb.frontend;
fe->ops.i2c_gate_ctrl(fe, 1);
if (dvb_attach(isl6405_attach, fe,
&dev->i2c_adap, 0x08, 0, 0) == NULL) {
wprintk("%s: MD7134 DVB-S, no ISL6405 "
"found !\n", __func__);
goto dettach_frontend;
}
fe->ops.i2c_gate_ctrl(fe, 0);
dev->original_set_voltage = fe->ops.set_voltage;
fe->ops.set_voltage = md8800_set_voltage;
dev->original_set_high_voltage = fe->ops.enable_high_lnb_voltage;
fe->ops.enable_high_lnb_voltage = md8800_set_high_voltage;
}
break;
case SAA7134_BOARD_AVERMEDIA_M103:
saa7134_set_gpio(dev, 25, 0);
msleep(10);
saa7134_set_gpio(dev, 25, 1);
fe0->dvb.frontend = dvb_attach(mt352_attach,
&avermedia_xc3028_mt352_dev,
&dev->i2c_adap);
attach_xc3028 = 1;
break;
case SAA7134_BOARD_ASUSTeK_TIGER_3IN1:
if (!use_frontend) { /* terrestrial */
if (configure_tda827x_fe(dev, &asus_tiger_3in1_config,
&tda827x_cfg_2) < 0)
goto dettach_frontend;
} else { /* satellite */
fe0->dvb.frontend = dvb_attach(tda10086_attach,
&flydvbs, &dev->i2c_adap);
if (fe0->dvb.frontend) {
if (dvb_attach(tda826x_attach,
fe0->dvb.frontend, 0x60,
&dev->i2c_adap, 0) == NULL) {
wprintk("%s: Asus Tiger 3in1, no "
"tda826x found!\n", __func__);
goto dettach_frontend;
}
if (dvb_attach(lnbp21_attach, fe0->dvb.frontend,
&dev->i2c_adap, 0, 0) == NULL) {
wprintk("%s: Asus Tiger 3in1, no lnbp21"
" found!\n", __func__);
goto dettach_frontend;
}
}
}
break;
case SAA7134_BOARD_ASUSTeK_TIGER:
if (configure_tda827x_fe(dev, &philips_tiger_config,
&tda827x_cfg_0) < 0)
goto dettach_frontend;
break;
case SAA7134_BOARD_BEHOLD_H6:
fe0->dvb.frontend = dvb_attach(zl10353_attach,
&behold_h6_config,
&dev->i2c_adap);
if (fe0->dvb.frontend) {
dvb_attach(simple_tuner_attach, fe0->dvb.frontend,
&dev->i2c_adap, 0x61,
TUNER_PHILIPS_FMD1216MEX_MK3);
}
break;
case SAA7134_BOARD_BEHOLD_X7:
fe0->dvb.frontend = dvb_attach(zl10353_attach,
&behold_x7_config,
&dev->i2c_adap);
if (fe0->dvb.frontend) {
dvb_attach(xc5000_attach, fe0->dvb.frontend,
&dev->i2c_adap, &behold_x7_tunerconfig);
}
break;
case SAA7134_BOARD_BEHOLD_H7:
fe0->dvb.frontend = dvb_attach(zl10353_attach,
&behold_x7_config,
&dev->i2c_adap);
if (fe0->dvb.frontend) {
dvb_attach(xc5000_attach, fe0->dvb.frontend,
&dev->i2c_adap, &behold_x7_tunerconfig);
}
break;
case SAA7134_BOARD_AVERMEDIA_A700_PRO:
case SAA7134_BOARD_AVERMEDIA_A700_HYBRID:
/* Zarlink ZL10313 */
fe0->dvb.frontend = dvb_attach(mt312_attach,
&avertv_a700_mt312, &dev->i2c_adap);
if (fe0->dvb.frontend) {
if (dvb_attach(zl10036_attach, fe0->dvb.frontend,
&avertv_a700_tuner, &dev->i2c_adap) == NULL) {
wprintk("%s: No zl10036 found!\n",
__func__);
}
}
break;
case SAA7134_BOARD_VIDEOMATE_S350:
fe0->dvb.frontend = dvb_attach(mt312_attach,
&zl10313_compro_s350_config, &dev->i2c_adap);
if (fe0->dvb.frontend)
if (dvb_attach(zl10039_attach, fe0->dvb.frontend,
0x60, &dev->i2c_adap) == NULL)
wprintk("%s: No zl10039 found!\n",
__func__);
break;
case SAA7134_BOARD_ZOLID_HYBRID_PCI:
fe0->dvb.frontend = dvb_attach(tda10048_attach,
&zolid_tda10048_config,
&dev->i2c_adap);
if (fe0->dvb.frontend != NULL) {
dvb_attach(tda829x_attach, fe0->dvb.frontend,
&dev->i2c_adap, 0x4b,
&tda829x_no_probe);
dvb_attach(tda18271_attach, fe0->dvb.frontend,
0x60, &dev->i2c_adap,
&zolid_tda18271_config);
}
break;
case SAA7134_BOARD_LEADTEK_WINFAST_DTV1000S:
fe0->dvb.frontend = dvb_attach(tda10048_attach,
&dtv1000s_tda10048_config,
&dev->i2c_adap);
if (fe0->dvb.frontend != NULL) {
dvb_attach(tda829x_attach, fe0->dvb.frontend,
&dev->i2c_adap, 0x4b,
&tda829x_no_probe);
dvb_attach(tda18271_attach, fe0->dvb.frontend,
0x60, &dev->i2c_adap,
&dtv1000s_tda18271_config);
}
break;
case SAA7134_BOARD_KWORLD_PCI_SBTVD_FULLSEG:
/* Switch to digital mode */
saa7134_tuner_callback(dev, 0,
TDA18271_CALLBACK_CMD_AGC_ENABLE, 1);
fe0->dvb.frontend = dvb_attach(mb86a20s_attach,
&kworld_mb86a20s_config,
&dev->i2c_adap);
if (fe0->dvb.frontend != NULL) {
dvb_attach(tda829x_attach, fe0->dvb.frontend,
&dev->i2c_adap, 0x4b,
&tda829x_no_probe);
dvb_attach(tda18271_attach, fe0->dvb.frontend,
0x60, &dev->i2c_adap,
&kworld_tda18271_config);
fe0->dvb.frontend->ops.i2c_gate_ctrl = kworld_sbtvd_gate_ctrl;
}
/* mb86a20s need to use the I2C gateway */
break;
case SAA7134_BOARD_MAGICPRO_PROHDTV_PRO2:
fe0->dvb.frontend = dvb_attach(lgs8gxx_attach,
&prohdtv_pro2_lgs8g75_config,
&dev->i2c_adap);
if (fe0->dvb.frontend != NULL) {
dvb_attach(tda829x_attach, fe0->dvb.frontend,
&dev->i2c_adap, 0x4b,
&tda829x_no_probe);
dvb_attach(tda18271_attach, fe0->dvb.frontend,
0x60, &dev->i2c_adap,
&prohdtv_pro2_tda18271_config);
}
break;
default:
wprintk("Huh? unknown DVB card?\n");
break;
}
if (attach_xc3028) {
struct dvb_frontend *fe;
struct xc2028_config cfg = {
.i2c_adap = &dev->i2c_adap,
.i2c_addr = 0x61,
};
if (!fe0->dvb.frontend)
goto dettach_frontend;
fe = dvb_attach(xc2028_attach, fe0->dvb.frontend, &cfg);
if (!fe) {
printk(KERN_ERR "%s/2: xc3028 attach failed\n",
dev->name);
goto dettach_frontend;
}
}
if (NULL == fe0->dvb.frontend) {
printk(KERN_ERR "%s/dvb: frontend initialization failed\n", dev->name);
goto dettach_frontend;
}
/* define general-purpose callback pointer */
fe0->dvb.frontend->callback = saa7134_tuner_callback;
/* register everything else */
ret = videobuf_dvb_register_bus(&dev->frontends, THIS_MODULE, dev,
&dev->pci->dev, adapter_nr, 0, NULL);
/* this sequence is necessary to make the tda1004x load its firmware
* and to enter analog mode of hybrid boards
*/
if (!ret) {
if (fe0->dvb.frontend->ops.init)
fe0->dvb.frontend->ops.init(fe0->dvb.frontend);
if (fe0->dvb.frontend->ops.sleep)
fe0->dvb.frontend->ops.sleep(fe0->dvb.frontend);
if (fe0->dvb.frontend->ops.tuner_ops.sleep)
fe0->dvb.frontend->ops.tuner_ops.sleep(fe0->dvb.frontend);
}
return ret;
dettach_frontend:
videobuf_dvb_dealloc_frontends(&dev->frontends);
return -EINVAL;
}
static int dvb_fini(struct saa7134_dev *dev)
{
struct videobuf_dvb_frontend *fe0;
/* Get the first frontend */
fe0 = videobuf_dvb_get_frontend(&dev->frontends, 1);
if (!fe0)
return -EINVAL;
/* FIXME: I suspect that this code is bogus, since the entry for
Pinnacle 300I DVB-T PAL already defines the proper init to allow
the detection of mt2032 (TDA9887_PORT2_INACTIVE)
*/
if (dev->board == SAA7134_BOARD_PINNACLE_300I_DVBT_PAL) {
struct v4l2_priv_tun_config tda9887_cfg;
static int on = TDA9887_PRESENT | TDA9887_PORT2_INACTIVE;
tda9887_cfg.tuner = TUNER_TDA9887;
tda9887_cfg.priv = &on;
/* otherwise we don't detect the tuner on next insmod */
saa_call_all(dev, tuner, s_config, &tda9887_cfg);
} else if (dev->board == SAA7134_BOARD_MEDION_MD8800_QUADRO) {
if ((dev->eedata[2] == 0x07) && use_frontend) {
/* turn off the 2nd lnb supply */
u8 data = 0x80;
struct i2c_msg msg = {.addr = 0x08, .buf = &data, .flags = 0, .len = 1};
struct dvb_frontend *fe;
fe = fe0->dvb.frontend;
if (fe->ops.i2c_gate_ctrl) {
fe->ops.i2c_gate_ctrl(fe, 1);
i2c_transfer(&dev->i2c_adap, &msg, 1);
fe->ops.i2c_gate_ctrl(fe, 0);
}
}
}
videobuf_dvb_unregister_bus(&dev->frontends);
return 0;
}
static struct saa7134_mpeg_ops dvb_ops = {
.type = SAA7134_MPEG_DVB,
.init = dvb_init,
.fini = dvb_fini,
};
static int __init dvb_register(void)
{
return saa7134_ts_register(&dvb_ops);
}
static void __exit dvb_unregister(void)
{
saa7134_ts_unregister(&dvb_ops);
}
module_init(dvb_register);
module_exit(dvb_unregister);
/* ------------------------------------------------------------------ */
/*
* Local variables:
* c-basic-offset: 8
* End:
*/
| gpl-2.0 |
FrozenCow/FIRE-ICE | drivers/media/platform/omap3isp/isphist.c | 2641 | 14777 | /*
* isphist.c
*
* TI OMAP3 ISP - Histogram module
*
* Copyright (C) 2010 Nokia Corporation
* Copyright (C) 2009 Texas Instruments, Inc.
*
* Contacts: David Cohen <dacohen@gmail.com>
* Laurent Pinchart <laurent.pinchart@ideasonboard.com>
* Sakari Ailus <sakari.ailus@iki.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <linux/device.h>
#include "isp.h"
#include "ispreg.h"
#include "isphist.h"
#define OMAP24XX_DMA_NO_DEVICE 0
#define HIST_CONFIG_DMA 1
#define HIST_USING_DMA(hist) ((hist)->dma_ch >= 0)
/*
* hist_reset_mem - clear Histogram memory before start stats engine.
*/
static void hist_reset_mem(struct ispstat *hist)
{
struct isp_device *isp = hist->isp;
struct omap3isp_hist_config *conf = hist->priv;
unsigned int i;
isp_reg_writel(isp, 0, OMAP3_ISP_IOMEM_HIST, ISPHIST_ADDR);
/*
* By setting it, the histogram internal buffer is being cleared at the
* same time it's being read. This bit must be cleared afterwards.
*/
isp_reg_set(isp, OMAP3_ISP_IOMEM_HIST, ISPHIST_CNT, ISPHIST_CNT_CLEAR);
/*
* We'll clear 4 words at each iteration for optimization. It avoids
* 3/4 of the jumps. We also know HIST_MEM_SIZE is divisible by 4.
*/
for (i = OMAP3ISP_HIST_MEM_SIZE / 4; i > 0; i--) {
isp_reg_readl(isp, OMAP3_ISP_IOMEM_HIST, ISPHIST_DATA);
isp_reg_readl(isp, OMAP3_ISP_IOMEM_HIST, ISPHIST_DATA);
isp_reg_readl(isp, OMAP3_ISP_IOMEM_HIST, ISPHIST_DATA);
isp_reg_readl(isp, OMAP3_ISP_IOMEM_HIST, ISPHIST_DATA);
}
isp_reg_clr(isp, OMAP3_ISP_IOMEM_HIST, ISPHIST_CNT, ISPHIST_CNT_CLEAR);
hist->wait_acc_frames = conf->num_acc_frames;
}
static void hist_dma_config(struct ispstat *hist)
{
struct isp_device *isp = hist->isp;
hist->dma_config.data_type = OMAP_DMA_DATA_TYPE_S32;
hist->dma_config.sync_mode = OMAP_DMA_SYNC_ELEMENT;
hist->dma_config.frame_count = 1;
hist->dma_config.src_amode = OMAP_DMA_AMODE_CONSTANT;
hist->dma_config.src_start = isp->mmio_base_phys[OMAP3_ISP_IOMEM_HIST]
+ ISPHIST_DATA;
hist->dma_config.dst_amode = OMAP_DMA_AMODE_POST_INC;
hist->dma_config.src_or_dst_synch = OMAP_DMA_SRC_SYNC;
}
/*
* hist_setup_regs - Helper function to update Histogram registers.
*/
static void hist_setup_regs(struct ispstat *hist, void *priv)
{
struct isp_device *isp = hist->isp;
struct omap3isp_hist_config *conf = priv;
int c;
u32 cnt;
u32 wb_gain;
u32 reg_hor[OMAP3ISP_HIST_MAX_REGIONS];
u32 reg_ver[OMAP3ISP_HIST_MAX_REGIONS];
if (!hist->update || hist->state == ISPSTAT_DISABLED ||
hist->state == ISPSTAT_DISABLING)
return;
cnt = conf->cfa << ISPHIST_CNT_CFA_SHIFT;
wb_gain = conf->wg[0] << ISPHIST_WB_GAIN_WG00_SHIFT;
wb_gain |= conf->wg[1] << ISPHIST_WB_GAIN_WG01_SHIFT;
wb_gain |= conf->wg[2] << ISPHIST_WB_GAIN_WG02_SHIFT;
if (conf->cfa == OMAP3ISP_HIST_CFA_BAYER)
wb_gain |= conf->wg[3] << ISPHIST_WB_GAIN_WG03_SHIFT;
/* Regions size and position */
for (c = 0; c < OMAP3ISP_HIST_MAX_REGIONS; c++) {
if (c < conf->num_regions) {
reg_hor[c] = (conf->region[c].h_start <<
ISPHIST_REG_START_SHIFT)
| (conf->region[c].h_end <<
ISPHIST_REG_END_SHIFT);
reg_ver[c] = (conf->region[c].v_start <<
ISPHIST_REG_START_SHIFT)
| (conf->region[c].v_end <<
ISPHIST_REG_END_SHIFT);
} else {
reg_hor[c] = 0;
reg_ver[c] = 0;
}
}
cnt |= conf->hist_bins << ISPHIST_CNT_BINS_SHIFT;
switch (conf->hist_bins) {
case OMAP3ISP_HIST_BINS_256:
cnt |= (ISPHIST_IN_BIT_WIDTH_CCDC - 8) <<
ISPHIST_CNT_SHIFT_SHIFT;
break;
case OMAP3ISP_HIST_BINS_128:
cnt |= (ISPHIST_IN_BIT_WIDTH_CCDC - 7) <<
ISPHIST_CNT_SHIFT_SHIFT;
break;
case OMAP3ISP_HIST_BINS_64:
cnt |= (ISPHIST_IN_BIT_WIDTH_CCDC - 6) <<
ISPHIST_CNT_SHIFT_SHIFT;
break;
default: /* OMAP3ISP_HIST_BINS_32 */
cnt |= (ISPHIST_IN_BIT_WIDTH_CCDC - 5) <<
ISPHIST_CNT_SHIFT_SHIFT;
break;
}
hist_reset_mem(hist);
isp_reg_writel(isp, cnt, OMAP3_ISP_IOMEM_HIST, ISPHIST_CNT);
isp_reg_writel(isp, wb_gain, OMAP3_ISP_IOMEM_HIST, ISPHIST_WB_GAIN);
isp_reg_writel(isp, reg_hor[0], OMAP3_ISP_IOMEM_HIST, ISPHIST_R0_HORZ);
isp_reg_writel(isp, reg_ver[0], OMAP3_ISP_IOMEM_HIST, ISPHIST_R0_VERT);
isp_reg_writel(isp, reg_hor[1], OMAP3_ISP_IOMEM_HIST, ISPHIST_R1_HORZ);
isp_reg_writel(isp, reg_ver[1], OMAP3_ISP_IOMEM_HIST, ISPHIST_R1_VERT);
isp_reg_writel(isp, reg_hor[2], OMAP3_ISP_IOMEM_HIST, ISPHIST_R2_HORZ);
isp_reg_writel(isp, reg_ver[2], OMAP3_ISP_IOMEM_HIST, ISPHIST_R2_VERT);
isp_reg_writel(isp, reg_hor[3], OMAP3_ISP_IOMEM_HIST, ISPHIST_R3_HORZ);
isp_reg_writel(isp, reg_ver[3], OMAP3_ISP_IOMEM_HIST, ISPHIST_R3_VERT);
hist->update = 0;
hist->config_counter += hist->inc_config;
hist->inc_config = 0;
hist->buf_size = conf->buf_size;
}
static void hist_enable(struct ispstat *hist, int enable)
{
if (enable) {
isp_reg_set(hist->isp, OMAP3_ISP_IOMEM_HIST, ISPHIST_PCR,
ISPHIST_PCR_ENABLE);
omap3isp_subclk_enable(hist->isp, OMAP3_ISP_SUBCLK_HIST);
} else {
isp_reg_clr(hist->isp, OMAP3_ISP_IOMEM_HIST, ISPHIST_PCR,
ISPHIST_PCR_ENABLE);
omap3isp_subclk_disable(hist->isp, OMAP3_ISP_SUBCLK_HIST);
}
}
static int hist_busy(struct ispstat *hist)
{
return isp_reg_readl(hist->isp, OMAP3_ISP_IOMEM_HIST, ISPHIST_PCR)
& ISPHIST_PCR_BUSY;
}
static void hist_dma_cb(int lch, u16 ch_status, void *data)
{
struct ispstat *hist = data;
if (ch_status & ~OMAP_DMA_BLOCK_IRQ) {
dev_dbg(hist->isp->dev, "hist: DMA error. status = 0x%04x\n",
ch_status);
omap_stop_dma(lch);
hist_reset_mem(hist);
atomic_set(&hist->buf_err, 1);
}
isp_reg_clr(hist->isp, OMAP3_ISP_IOMEM_HIST, ISPHIST_CNT,
ISPHIST_CNT_CLEAR);
omap3isp_stat_dma_isr(hist);
if (hist->state != ISPSTAT_DISABLED)
omap3isp_hist_dma_done(hist->isp);
}
static int hist_buf_dma(struct ispstat *hist)
{
dma_addr_t dma_addr = hist->active_buf->dma_addr;
if (unlikely(!dma_addr)) {
dev_dbg(hist->isp->dev, "hist: invalid DMA buffer address\n");
hist_reset_mem(hist);
return STAT_NO_BUF;
}
isp_reg_writel(hist->isp, 0, OMAP3_ISP_IOMEM_HIST, ISPHIST_ADDR);
isp_reg_set(hist->isp, OMAP3_ISP_IOMEM_HIST, ISPHIST_CNT,
ISPHIST_CNT_CLEAR);
omap3isp_flush(hist->isp);
hist->dma_config.dst_start = dma_addr;
hist->dma_config.elem_count = hist->buf_size / sizeof(u32);
omap_set_dma_params(hist->dma_ch, &hist->dma_config);
omap_start_dma(hist->dma_ch);
return STAT_BUF_WAITING_DMA;
}
static int hist_buf_pio(struct ispstat *hist)
{
struct isp_device *isp = hist->isp;
u32 *buf = hist->active_buf->virt_addr;
unsigned int i;
if (!buf) {
dev_dbg(isp->dev, "hist: invalid PIO buffer address\n");
hist_reset_mem(hist);
return STAT_NO_BUF;
}
isp_reg_writel(isp, 0, OMAP3_ISP_IOMEM_HIST, ISPHIST_ADDR);
/*
* By setting it, the histogram internal buffer is being cleared at the
* same time it's being read. This bit must be cleared just after all
* data is acquired.
*/
isp_reg_set(isp, OMAP3_ISP_IOMEM_HIST, ISPHIST_CNT, ISPHIST_CNT_CLEAR);
/*
* We'll read 4 times a 4-bytes-word at each iteration for
* optimization. It avoids 3/4 of the jumps. We also know buf_size is
* divisible by 16.
*/
for (i = hist->buf_size / 16; i > 0; i--) {
*buf++ = isp_reg_readl(isp, OMAP3_ISP_IOMEM_HIST, ISPHIST_DATA);
*buf++ = isp_reg_readl(isp, OMAP3_ISP_IOMEM_HIST, ISPHIST_DATA);
*buf++ = isp_reg_readl(isp, OMAP3_ISP_IOMEM_HIST, ISPHIST_DATA);
*buf++ = isp_reg_readl(isp, OMAP3_ISP_IOMEM_HIST, ISPHIST_DATA);
}
isp_reg_clr(hist->isp, OMAP3_ISP_IOMEM_HIST, ISPHIST_CNT,
ISPHIST_CNT_CLEAR);
return STAT_BUF_DONE;
}
/*
* hist_buf_process - Callback from ISP driver for HIST interrupt.
*/
static int hist_buf_process(struct ispstat *hist)
{
struct omap3isp_hist_config *user_cfg = hist->priv;
int ret;
if (atomic_read(&hist->buf_err) || hist->state != ISPSTAT_ENABLED) {
hist_reset_mem(hist);
return STAT_NO_BUF;
}
if (--(hist->wait_acc_frames))
return STAT_NO_BUF;
if (HIST_USING_DMA(hist))
ret = hist_buf_dma(hist);
else
ret = hist_buf_pio(hist);
hist->wait_acc_frames = user_cfg->num_acc_frames;
return ret;
}
static u32 hist_get_buf_size(struct omap3isp_hist_config *conf)
{
return OMAP3ISP_HIST_MEM_SIZE_BINS(conf->hist_bins) * conf->num_regions;
}
/*
* hist_validate_params - Helper function to check user given params.
* @user_cfg: Pointer to user configuration structure.
*
* Returns 0 on success configuration.
*/
static int hist_validate_params(struct ispstat *hist, void *new_conf)
{
struct omap3isp_hist_config *user_cfg = new_conf;
int c;
u32 buf_size;
if (user_cfg->cfa > OMAP3ISP_HIST_CFA_FOVEONX3)
return -EINVAL;
/* Regions size and position */
if ((user_cfg->num_regions < OMAP3ISP_HIST_MIN_REGIONS) ||
(user_cfg->num_regions > OMAP3ISP_HIST_MAX_REGIONS))
return -EINVAL;
/* Regions */
for (c = 0; c < user_cfg->num_regions; c++) {
if (user_cfg->region[c].h_start & ~ISPHIST_REG_START_END_MASK)
return -EINVAL;
if (user_cfg->region[c].h_end & ~ISPHIST_REG_START_END_MASK)
return -EINVAL;
if (user_cfg->region[c].v_start & ~ISPHIST_REG_START_END_MASK)
return -EINVAL;
if (user_cfg->region[c].v_end & ~ISPHIST_REG_START_END_MASK)
return -EINVAL;
if (user_cfg->region[c].h_start > user_cfg->region[c].h_end)
return -EINVAL;
if (user_cfg->region[c].v_start > user_cfg->region[c].v_end)
return -EINVAL;
}
switch (user_cfg->num_regions) {
case 1:
if (user_cfg->hist_bins > OMAP3ISP_HIST_BINS_256)
return -EINVAL;
break;
case 2:
if (user_cfg->hist_bins > OMAP3ISP_HIST_BINS_128)
return -EINVAL;
break;
default: /* 3 or 4 */
if (user_cfg->hist_bins > OMAP3ISP_HIST_BINS_64)
return -EINVAL;
break;
}
buf_size = hist_get_buf_size(user_cfg);
if (buf_size > user_cfg->buf_size)
/* User's buf_size request wasn't enoght */
user_cfg->buf_size = buf_size;
else if (user_cfg->buf_size > OMAP3ISP_HIST_MAX_BUF_SIZE)
user_cfg->buf_size = OMAP3ISP_HIST_MAX_BUF_SIZE;
return 0;
}
static int hist_comp_params(struct ispstat *hist,
struct omap3isp_hist_config *user_cfg)
{
struct omap3isp_hist_config *cur_cfg = hist->priv;
int c;
if (cur_cfg->cfa != user_cfg->cfa)
return 1;
if (cur_cfg->num_acc_frames != user_cfg->num_acc_frames)
return 1;
if (cur_cfg->hist_bins != user_cfg->hist_bins)
return 1;
for (c = 0; c < OMAP3ISP_HIST_MAX_WG; c++) {
if (c == 3 && user_cfg->cfa == OMAP3ISP_HIST_CFA_FOVEONX3)
break;
else if (cur_cfg->wg[c] != user_cfg->wg[c])
return 1;
}
if (cur_cfg->num_regions != user_cfg->num_regions)
return 1;
/* Regions */
for (c = 0; c < user_cfg->num_regions; c++) {
if (cur_cfg->region[c].h_start != user_cfg->region[c].h_start)
return 1;
if (cur_cfg->region[c].h_end != user_cfg->region[c].h_end)
return 1;
if (cur_cfg->region[c].v_start != user_cfg->region[c].v_start)
return 1;
if (cur_cfg->region[c].v_end != user_cfg->region[c].v_end)
return 1;
}
return 0;
}
/*
* hist_update_params - Helper function to check and store user given params.
* @new_conf: Pointer to user configuration structure.
*/
static void hist_set_params(struct ispstat *hist, void *new_conf)
{
struct omap3isp_hist_config *user_cfg = new_conf;
struct omap3isp_hist_config *cur_cfg = hist->priv;
if (!hist->configured || hist_comp_params(hist, user_cfg)) {
memcpy(cur_cfg, user_cfg, sizeof(*user_cfg));
if (user_cfg->num_acc_frames == 0)
user_cfg->num_acc_frames = 1;
hist->inc_config++;
hist->update = 1;
/*
* User might be asked for a bigger buffer than necessary for
* this configuration. In order to return the right amount of
* data during buffer request, let's calculate the size here
* instead of stick with user_cfg->buf_size.
*/
cur_cfg->buf_size = hist_get_buf_size(cur_cfg);
}
}
static long hist_ioctl(struct v4l2_subdev *sd, unsigned int cmd, void *arg)
{
struct ispstat *stat = v4l2_get_subdevdata(sd);
switch (cmd) {
case VIDIOC_OMAP3ISP_HIST_CFG:
return omap3isp_stat_config(stat, arg);
case VIDIOC_OMAP3ISP_STAT_REQ:
return omap3isp_stat_request_statistics(stat, arg);
case VIDIOC_OMAP3ISP_STAT_EN: {
int *en = arg;
return omap3isp_stat_enable(stat, !!*en);
}
}
return -ENOIOCTLCMD;
}
static const struct ispstat_ops hist_ops = {
.validate_params = hist_validate_params,
.set_params = hist_set_params,
.setup_regs = hist_setup_regs,
.enable = hist_enable,
.busy = hist_busy,
.buf_process = hist_buf_process,
};
static const struct v4l2_subdev_core_ops hist_subdev_core_ops = {
.ioctl = hist_ioctl,
.subscribe_event = omap3isp_stat_subscribe_event,
.unsubscribe_event = omap3isp_stat_unsubscribe_event,
};
static const struct v4l2_subdev_video_ops hist_subdev_video_ops = {
.s_stream = omap3isp_stat_s_stream,
};
static const struct v4l2_subdev_ops hist_subdev_ops = {
.core = &hist_subdev_core_ops,
.video = &hist_subdev_video_ops,
};
/*
* omap3isp_hist_init - Module Initialization.
*/
int omap3isp_hist_init(struct isp_device *isp)
{
struct ispstat *hist = &isp->isp_hist;
struct omap3isp_hist_config *hist_cfg;
int ret = -1;
hist_cfg = devm_kzalloc(isp->dev, sizeof(*hist_cfg), GFP_KERNEL);
if (hist_cfg == NULL)
return -ENOMEM;
hist->isp = isp;
if (HIST_CONFIG_DMA)
ret = omap_request_dma(OMAP24XX_DMA_NO_DEVICE, "DMA_ISP_HIST",
hist_dma_cb, hist, &hist->dma_ch);
if (ret) {
if (HIST_CONFIG_DMA)
dev_warn(isp->dev, "hist: DMA request channel failed. "
"Using PIO only.\n");
hist->dma_ch = -1;
} else {
dev_dbg(isp->dev, "hist: DMA channel = %d\n", hist->dma_ch);
hist_dma_config(hist);
omap_enable_dma_irq(hist->dma_ch, OMAP_DMA_BLOCK_IRQ);
}
hist->ops = &hist_ops;
hist->priv = hist_cfg;
hist->event_type = V4L2_EVENT_OMAP3ISP_HIST;
ret = omap3isp_stat_init(hist, "histogram", &hist_subdev_ops);
if (ret) {
if (HIST_USING_DMA(hist))
omap_free_dma(hist->dma_ch);
}
return ret;
}
/*
* omap3isp_hist_cleanup - Module cleanup.
*/
void omap3isp_hist_cleanup(struct isp_device *isp)
{
if (HIST_USING_DMA(&isp->isp_hist))
omap_free_dma(isp->isp_hist.dma_ch);
omap3isp_stat_cleanup(&isp->isp_hist);
}
| gpl-2.0 |
Mark092/android_kernel_samsung_common | drivers/input/serio/sa1111ps2.c | 3665 | 7864 | /*
* linux/drivers/input/serio/sa1111ps2.c
*
* Copyright (C) 2002 Russell King
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/input.h>
#include <linux/serio.h>
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <asm/io.h>
#include <asm/system.h>
#include <asm/hardware/sa1111.h>
struct ps2if {
struct serio *io;
struct sa1111_dev *dev;
void __iomem *base;
unsigned int open;
spinlock_t lock;
unsigned int head;
unsigned int tail;
unsigned char buf[4];
};
/*
* Read all bytes waiting in the PS2 port. There should be
* at the most one, but we loop for safety. If there was a
* framing error, we have to manually clear the status.
*/
static irqreturn_t ps2_rxint(int irq, void *dev_id)
{
struct ps2if *ps2if = dev_id;
unsigned int scancode, flag, status;
status = sa1111_readl(ps2if->base + SA1111_PS2STAT);
while (status & PS2STAT_RXF) {
if (status & PS2STAT_STP)
sa1111_writel(PS2STAT_STP, ps2if->base + SA1111_PS2STAT);
flag = (status & PS2STAT_STP ? SERIO_FRAME : 0) |
(status & PS2STAT_RXP ? 0 : SERIO_PARITY);
scancode = sa1111_readl(ps2if->base + SA1111_PS2DATA) & 0xff;
if (hweight8(scancode) & 1)
flag ^= SERIO_PARITY;
serio_interrupt(ps2if->io, scancode, flag);
status = sa1111_readl(ps2if->base + SA1111_PS2STAT);
}
return IRQ_HANDLED;
}
/*
* Completion of ps2 write
*/
static irqreturn_t ps2_txint(int irq, void *dev_id)
{
struct ps2if *ps2if = dev_id;
unsigned int status;
spin_lock(&ps2if->lock);
status = sa1111_readl(ps2if->base + SA1111_PS2STAT);
if (ps2if->head == ps2if->tail) {
disable_irq_nosync(irq);
/* done */
} else if (status & PS2STAT_TXE) {
sa1111_writel(ps2if->buf[ps2if->tail], ps2if->base + SA1111_PS2DATA);
ps2if->tail = (ps2if->tail + 1) & (sizeof(ps2if->buf) - 1);
}
spin_unlock(&ps2if->lock);
return IRQ_HANDLED;
}
/*
* Write a byte to the PS2 port. We have to wait for the
* port to indicate that the transmitter is empty.
*/
static int ps2_write(struct serio *io, unsigned char val)
{
struct ps2if *ps2if = io->port_data;
unsigned long flags;
unsigned int head;
spin_lock_irqsave(&ps2if->lock, flags);
/*
* If the TX register is empty, we can go straight out.
*/
if (sa1111_readl(ps2if->base + SA1111_PS2STAT) & PS2STAT_TXE) {
sa1111_writel(val, ps2if->base + SA1111_PS2DATA);
} else {
if (ps2if->head == ps2if->tail)
enable_irq(ps2if->dev->irq[1]);
head = (ps2if->head + 1) & (sizeof(ps2if->buf) - 1);
if (head != ps2if->tail) {
ps2if->buf[ps2if->head] = val;
ps2if->head = head;
}
}
spin_unlock_irqrestore(&ps2if->lock, flags);
return 0;
}
static int ps2_open(struct serio *io)
{
struct ps2if *ps2if = io->port_data;
int ret;
sa1111_enable_device(ps2if->dev);
ret = request_irq(ps2if->dev->irq[0], ps2_rxint, 0,
SA1111_DRIVER_NAME(ps2if->dev), ps2if);
if (ret) {
printk(KERN_ERR "sa1111ps2: could not allocate IRQ%d: %d\n",
ps2if->dev->irq[0], ret);
return ret;
}
ret = request_irq(ps2if->dev->irq[1], ps2_txint, 0,
SA1111_DRIVER_NAME(ps2if->dev), ps2if);
if (ret) {
printk(KERN_ERR "sa1111ps2: could not allocate IRQ%d: %d\n",
ps2if->dev->irq[1], ret);
free_irq(ps2if->dev->irq[0], ps2if);
return ret;
}
ps2if->open = 1;
enable_irq_wake(ps2if->dev->irq[0]);
sa1111_writel(PS2CR_ENA, ps2if->base + SA1111_PS2CR);
return 0;
}
static void ps2_close(struct serio *io)
{
struct ps2if *ps2if = io->port_data;
sa1111_writel(0, ps2if->base + SA1111_PS2CR);
disable_irq_wake(ps2if->dev->irq[0]);
ps2if->open = 0;
free_irq(ps2if->dev->irq[1], ps2if);
free_irq(ps2if->dev->irq[0], ps2if);
sa1111_disable_device(ps2if->dev);
}
/*
* Clear the input buffer.
*/
static void __devinit ps2_clear_input(struct ps2if *ps2if)
{
int maxread = 100;
while (maxread--) {
if ((sa1111_readl(ps2if->base + SA1111_PS2DATA) & 0xff) == 0xff)
break;
}
}
static unsigned int __devinit ps2_test_one(struct ps2if *ps2if,
unsigned int mask)
{
unsigned int val;
sa1111_writel(PS2CR_ENA | mask, ps2if->base + SA1111_PS2CR);
udelay(2);
val = sa1111_readl(ps2if->base + SA1111_PS2STAT);
return val & (PS2STAT_KBC | PS2STAT_KBD);
}
/*
* Test the keyboard interface. We basically check to make sure that
* we can drive each line to the keyboard independently of each other.
*/
static int __devinit ps2_test(struct ps2if *ps2if)
{
unsigned int stat;
int ret = 0;
stat = ps2_test_one(ps2if, PS2CR_FKC);
if (stat != PS2STAT_KBD) {
printk("PS/2 interface test failed[1]: %02x\n", stat);
ret = -ENODEV;
}
stat = ps2_test_one(ps2if, 0);
if (stat != (PS2STAT_KBC | PS2STAT_KBD)) {
printk("PS/2 interface test failed[2]: %02x\n", stat);
ret = -ENODEV;
}
stat = ps2_test_one(ps2if, PS2CR_FKD);
if (stat != PS2STAT_KBC) {
printk("PS/2 interface test failed[3]: %02x\n", stat);
ret = -ENODEV;
}
sa1111_writel(0, ps2if->base + SA1111_PS2CR);
return ret;
}
/*
* Add one device to this driver.
*/
static int __devinit ps2_probe(struct sa1111_dev *dev)
{
struct ps2if *ps2if;
struct serio *serio;
int ret;
ps2if = kzalloc(sizeof(struct ps2if), GFP_KERNEL);
serio = kzalloc(sizeof(struct serio), GFP_KERNEL);
if (!ps2if || !serio) {
ret = -ENOMEM;
goto free;
}
serio->id.type = SERIO_8042;
serio->write = ps2_write;
serio->open = ps2_open;
serio->close = ps2_close;
strlcpy(serio->name, dev_name(&dev->dev), sizeof(serio->name));
strlcpy(serio->phys, dev_name(&dev->dev), sizeof(serio->phys));
serio->port_data = ps2if;
serio->dev.parent = &dev->dev;
ps2if->io = serio;
ps2if->dev = dev;
sa1111_set_drvdata(dev, ps2if);
spin_lock_init(&ps2if->lock);
/*
* Request the physical region for this PS2 port.
*/
if (!request_mem_region(dev->res.start,
dev->res.end - dev->res.start + 1,
SA1111_DRIVER_NAME(dev))) {
ret = -EBUSY;
goto free;
}
/*
* Our parent device has already mapped the region.
*/
ps2if->base = dev->mapbase;
sa1111_enable_device(ps2if->dev);
/* Incoming clock is 8MHz */
sa1111_writel(0, ps2if->base + SA1111_PS2CLKDIV);
sa1111_writel(127, ps2if->base + SA1111_PS2PRECNT);
/*
* Flush any pending input.
*/
ps2_clear_input(ps2if);
/*
* Test the keyboard interface.
*/
ret = ps2_test(ps2if);
if (ret)
goto out;
/*
* Flush any pending input.
*/
ps2_clear_input(ps2if);
sa1111_disable_device(ps2if->dev);
serio_register_port(ps2if->io);
return 0;
out:
sa1111_disable_device(ps2if->dev);
release_mem_region(dev->res.start,
dev->res.end - dev->res.start + 1);
free:
sa1111_set_drvdata(dev, NULL);
kfree(ps2if);
kfree(serio);
return ret;
}
/*
* Remove one device from this driver.
*/
static int __devexit ps2_remove(struct sa1111_dev *dev)
{
struct ps2if *ps2if = sa1111_get_drvdata(dev);
serio_unregister_port(ps2if->io);
release_mem_region(dev->res.start,
dev->res.end - dev->res.start + 1);
sa1111_set_drvdata(dev, NULL);
kfree(ps2if);
return 0;
}
/*
* Our device driver structure
*/
static struct sa1111_driver ps2_driver = {
.drv = {
.name = "sa1111-ps2",
},
.devid = SA1111_DEVID_PS2,
.probe = ps2_probe,
.remove = __devexit_p(ps2_remove),
};
static int __init ps2_init(void)
{
return sa1111_driver_register(&ps2_driver);
}
static void __exit ps2_exit(void)
{
sa1111_driver_unregister(&ps2_driver);
}
module_init(ps2_init);
module_exit(ps2_exit);
MODULE_AUTHOR("Russell King <rmk@arm.linux.org.uk>");
MODULE_DESCRIPTION("SA1111 PS2 controller driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
DHOMD/amlogic_kernel_playground | arch/m68k/kernel/module.c | 3921 | 3852 | /*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive
* for more details.
*/
#include <linux/moduleloader.h>
#include <linux/elf.h>
#include <linux/vmalloc.h>
#include <linux/fs.h>
#include <linux/string.h>
#include <linux/kernel.h>
#if 0
#define DEBUGP printk
#else
#define DEBUGP(fmt...)
#endif
#ifdef CONFIG_MODULES
void *module_alloc(unsigned long size)
{
if (size == 0)
return NULL;
return vmalloc(size);
}
/* Free memory returned from module_alloc */
void module_free(struct module *mod, void *module_region)
{
vfree(module_region);
}
/* We don't need anything special. */
int module_frob_arch_sections(Elf_Ehdr *hdr,
Elf_Shdr *sechdrs,
char *secstrings,
struct module *mod)
{
return 0;
}
int apply_relocate(Elf32_Shdr *sechdrs,
const char *strtab,
unsigned int symindex,
unsigned int relsec,
struct module *me)
{
unsigned int i;
Elf32_Rel *rel = (void *)sechdrs[relsec].sh_addr;
Elf32_Sym *sym;
uint32_t *location;
DEBUGP("Applying relocate section %u to %u\n", relsec,
sechdrs[relsec].sh_info);
for (i = 0; i < sechdrs[relsec].sh_size / sizeof(*rel); i++) {
/* This is where to make the change */
location = (void *)sechdrs[sechdrs[relsec].sh_info].sh_addr
+ rel[i].r_offset;
/* This is the symbol it is referring to. Note that all
undefined symbols have been resolved. */
sym = (Elf32_Sym *)sechdrs[symindex].sh_addr
+ ELF32_R_SYM(rel[i].r_info);
switch (ELF32_R_TYPE(rel[i].r_info)) {
case R_68K_32:
/* We add the value into the location given */
*location += sym->st_value;
break;
case R_68K_PC32:
/* Add the value, subtract its postition */
*location += sym->st_value - (uint32_t)location;
break;
default:
printk(KERN_ERR "module %s: Unknown relocation: %u\n",
me->name, ELF32_R_TYPE(rel[i].r_info));
return -ENOEXEC;
}
}
return 0;
}
int apply_relocate_add(Elf32_Shdr *sechdrs,
const char *strtab,
unsigned int symindex,
unsigned int relsec,
struct module *me)
{
unsigned int i;
Elf32_Rela *rel = (void *)sechdrs[relsec].sh_addr;
Elf32_Sym *sym;
uint32_t *location;
DEBUGP("Applying relocate_add section %u to %u\n", relsec,
sechdrs[relsec].sh_info);
for (i = 0; i < sechdrs[relsec].sh_size / sizeof(*rel); i++) {
/* This is where to make the change */
location = (void *)sechdrs[sechdrs[relsec].sh_info].sh_addr
+ rel[i].r_offset;
/* This is the symbol it is referring to. Note that all
undefined symbols have been resolved. */
sym = (Elf32_Sym *)sechdrs[symindex].sh_addr
+ ELF32_R_SYM(rel[i].r_info);
switch (ELF32_R_TYPE(rel[i].r_info)) {
case R_68K_32:
/* We add the value into the location given */
*location = rel[i].r_addend + sym->st_value;
break;
case R_68K_PC32:
/* Add the value, subtract its postition */
*location = rel[i].r_addend + sym->st_value - (uint32_t)location;
break;
default:
printk(KERN_ERR "module %s: Unknown relocation: %u\n",
me->name, ELF32_R_TYPE(rel[i].r_info));
return -ENOEXEC;
}
}
return 0;
}
int module_finalize(const Elf_Ehdr *hdr,
const Elf_Shdr *sechdrs,
struct module *mod)
{
module_fixup(mod, mod->arch.fixup_start, mod->arch.fixup_end);
return 0;
}
void module_arch_cleanup(struct module *mod)
{
}
#endif /* CONFIG_MODULES */
void module_fixup(struct module *mod, struct m68k_fixup_info *start,
struct m68k_fixup_info *end)
{
struct m68k_fixup_info *fixup;
for (fixup = start; fixup < end; fixup++) {
switch (fixup->type) {
case m68k_fixup_memoffset:
*(u32 *)fixup->addr = m68k_memoffset;
break;
case m68k_fixup_vnode_shift:
*(u16 *)fixup->addr += m68k_virt_to_node_shift;
break;
}
}
}
| gpl-2.0 |
SMAICP/kernel_amazon_otter-common | arch/powerpc/platforms/chrp/pci.c | 3921 | 10679 | /*
* CHRP pci routines.
*/
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/delay.h>
#include <linux/string.h>
#include <linux/init.h>
#include <asm/io.h>
#include <asm/pgtable.h>
#include <asm/irq.h>
#include <asm/hydra.h>
#include <asm/prom.h>
#include <asm/machdep.h>
#include <asm/sections.h>
#include <asm/pci-bridge.h>
#include <asm/grackle.h>
#include <asm/rtas.h>
#include "chrp.h"
#include "gg2.h"
/* LongTrail */
void __iomem *gg2_pci_config_base;
/*
* The VLSI Golden Gate II has only 512K of PCI configuration space, so we
* limit the bus number to 3 bits
*/
int gg2_read_config(struct pci_bus *bus, unsigned int devfn, int off,
int len, u32 *val)
{
volatile void __iomem *cfg_data;
struct pci_controller *hose = pci_bus_to_host(bus);
if (bus->number > 7)
return PCIBIOS_DEVICE_NOT_FOUND;
/*
* Note: the caller has already checked that off is
* suitably aligned and that len is 1, 2 or 4.
*/
cfg_data = hose->cfg_data + ((bus->number<<16) | (devfn<<8) | off);
switch (len) {
case 1:
*val = in_8(cfg_data);
break;
case 2:
*val = in_le16(cfg_data);
break;
default:
*val = in_le32(cfg_data);
break;
}
return PCIBIOS_SUCCESSFUL;
}
int gg2_write_config(struct pci_bus *bus, unsigned int devfn, int off,
int len, u32 val)
{
volatile void __iomem *cfg_data;
struct pci_controller *hose = pci_bus_to_host(bus);
if (bus->number > 7)
return PCIBIOS_DEVICE_NOT_FOUND;
/*
* Note: the caller has already checked that off is
* suitably aligned and that len is 1, 2 or 4.
*/
cfg_data = hose->cfg_data + ((bus->number<<16) | (devfn<<8) | off);
switch (len) {
case 1:
out_8(cfg_data, val);
break;
case 2:
out_le16(cfg_data, val);
break;
default:
out_le32(cfg_data, val);
break;
}
return PCIBIOS_SUCCESSFUL;
}
static struct pci_ops gg2_pci_ops =
{
.read = gg2_read_config,
.write = gg2_write_config,
};
/*
* Access functions for PCI config space using RTAS calls.
*/
int rtas_read_config(struct pci_bus *bus, unsigned int devfn, int offset,
int len, u32 *val)
{
struct pci_controller *hose = pci_bus_to_host(bus);
unsigned long addr = (offset & 0xff) | ((devfn & 0xff) << 8)
| (((bus->number - hose->first_busno) & 0xff) << 16)
| (hose->global_number << 24);
int ret = -1;
int rval;
rval = rtas_call(rtas_token("read-pci-config"), 2, 2, &ret, addr, len);
*val = ret;
return rval? PCIBIOS_DEVICE_NOT_FOUND: PCIBIOS_SUCCESSFUL;
}
int rtas_write_config(struct pci_bus *bus, unsigned int devfn, int offset,
int len, u32 val)
{
struct pci_controller *hose = pci_bus_to_host(bus);
unsigned long addr = (offset & 0xff) | ((devfn & 0xff) << 8)
| (((bus->number - hose->first_busno) & 0xff) << 16)
| (hose->global_number << 24);
int rval;
rval = rtas_call(rtas_token("write-pci-config"), 3, 1, NULL,
addr, len, val);
return rval? PCIBIOS_DEVICE_NOT_FOUND: PCIBIOS_SUCCESSFUL;
}
static struct pci_ops rtas_pci_ops =
{
.read = rtas_read_config,
.write = rtas_write_config,
};
volatile struct Hydra __iomem *Hydra = NULL;
int __init
hydra_init(void)
{
struct device_node *np;
struct resource r;
np = of_find_node_by_name(NULL, "mac-io");
if (np == NULL || of_address_to_resource(np, 0, &r)) {
of_node_put(np);
return 0;
}
of_node_put(np);
Hydra = ioremap(r.start, r.end-r.start);
printk("Hydra Mac I/O at %llx\n", (unsigned long long)r.start);
printk("Hydra Feature_Control was %x",
in_le32(&Hydra->Feature_Control));
out_le32(&Hydra->Feature_Control, (HYDRA_FC_SCC_CELL_EN |
HYDRA_FC_SCSI_CELL_EN |
HYDRA_FC_SCCA_ENABLE |
HYDRA_FC_SCCB_ENABLE |
HYDRA_FC_ARB_BYPASS |
HYDRA_FC_MPIC_ENABLE |
HYDRA_FC_SLOW_SCC_PCLK |
HYDRA_FC_MPIC_IS_MASTER));
printk(", now %x\n", in_le32(&Hydra->Feature_Control));
return 1;
}
#define PRG_CL_RESET_VALID 0x00010000
static void __init
setup_python(struct pci_controller *hose, struct device_node *dev)
{
u32 __iomem *reg;
u32 val;
struct resource r;
if (of_address_to_resource(dev, 0, &r)) {
printk(KERN_ERR "No address for Python PCI controller\n");
return;
}
/* Clear the magic go-slow bit */
reg = ioremap(r.start + 0xf6000, 0x40);
BUG_ON(!reg);
val = in_be32(®[12]);
if (val & PRG_CL_RESET_VALID) {
out_be32(®[12], val & ~PRG_CL_RESET_VALID);
in_be32(®[12]);
}
iounmap(reg);
setup_indirect_pci(hose, r.start + 0xf8000, r.start + 0xf8010, 0);
}
/* Marvell Discovery II based Pegasos 2 */
static void __init setup_peg2(struct pci_controller *hose, struct device_node *dev)
{
struct device_node *root = of_find_node_by_path("/");
struct device_node *rtas;
rtas = of_find_node_by_name (root, "rtas");
if (rtas) {
hose->ops = &rtas_pci_ops;
of_node_put(rtas);
} else {
printk ("RTAS supporting Pegasos OF not found, please upgrade"
" your firmware\n");
}
ppc_pci_add_flags(PPC_PCI_REASSIGN_ALL_BUS);
/* keep the reference to the root node */
}
void __init
chrp_find_bridges(void)
{
struct device_node *dev;
const int *bus_range;
int len, index = -1;
struct pci_controller *hose;
const unsigned int *dma;
const char *model, *machine;
int is_longtrail = 0, is_mot = 0, is_pegasos = 0;
struct device_node *root = of_find_node_by_path("/");
struct resource r;
/*
* The PCI host bridge nodes on some machines don't have
* properties to adequately identify them, so we have to
* look at what sort of machine this is as well.
*/
machine = of_get_property(root, "model", NULL);
if (machine != NULL) {
is_longtrail = strncmp(machine, "IBM,LongTrail", 13) == 0;
is_mot = strncmp(machine, "MOT", 3) == 0;
if (strncmp(machine, "Pegasos2", 8) == 0)
is_pegasos = 2;
else if (strncmp(machine, "Pegasos", 7) == 0)
is_pegasos = 1;
}
for (dev = root->child; dev != NULL; dev = dev->sibling) {
if (dev->type == NULL || strcmp(dev->type, "pci") != 0)
continue;
++index;
/* The GG2 bridge on the LongTrail doesn't have an address */
if (of_address_to_resource(dev, 0, &r) && !is_longtrail) {
printk(KERN_WARNING "Can't use %s: no address\n",
dev->full_name);
continue;
}
bus_range = of_get_property(dev, "bus-range", &len);
if (bus_range == NULL || len < 2 * sizeof(int)) {
printk(KERN_WARNING "Can't get bus-range for %s\n",
dev->full_name);
continue;
}
if (bus_range[1] == bus_range[0])
printk(KERN_INFO "PCI bus %d", bus_range[0]);
else
printk(KERN_INFO "PCI buses %d..%d",
bus_range[0], bus_range[1]);
printk(" controlled by %s", dev->full_name);
if (!is_longtrail)
printk(" at %llx", (unsigned long long)r.start);
printk("\n");
hose = pcibios_alloc_controller(dev);
if (!hose) {
printk("Can't allocate PCI controller structure for %s\n",
dev->full_name);
continue;
}
hose->first_busno = hose->self_busno = bus_range[0];
hose->last_busno = bus_range[1];
model = of_get_property(dev, "model", NULL);
if (model == NULL)
model = "<none>";
if (strncmp(model, "IBM, Python", 11) == 0) {
setup_python(hose, dev);
} else if (is_mot
|| strncmp(model, "Motorola, Grackle", 17) == 0) {
setup_grackle(hose);
} else if (is_longtrail) {
void __iomem *p = ioremap(GG2_PCI_CONFIG_BASE, 0x80000);
hose->ops = &gg2_pci_ops;
hose->cfg_data = p;
gg2_pci_config_base = p;
} else if (is_pegasos == 1) {
setup_indirect_pci(hose, 0xfec00cf8, 0xfee00cfc, 0);
} else if (is_pegasos == 2) {
setup_peg2(hose, dev);
} else if (!strncmp(model, "IBM,CPC710", 10)) {
setup_indirect_pci(hose,
r.start + 0x000f8000,
r.start + 0x000f8010,
0);
if (index == 0) {
dma = of_get_property(dev, "system-dma-base",
&len);
if (dma && len >= sizeof(*dma)) {
dma = (unsigned int *)
(((unsigned long)dma) +
len - sizeof(*dma));
pci_dram_offset = *dma;
}
}
} else {
printk("No methods for %s (model %s), using RTAS\n",
dev->full_name, model);
hose->ops = &rtas_pci_ops;
}
pci_process_bridge_OF_ranges(hose, dev, index == 0);
/* check the first bridge for a property that we can
use to set pci_dram_offset */
dma = of_get_property(dev, "ibm,dma-ranges", &len);
if (index == 0 && dma != NULL && len >= 6 * sizeof(*dma)) {
pci_dram_offset = dma[2] - dma[3];
printk("pci_dram_offset = %lx\n", pci_dram_offset);
}
}
of_node_put(root);
}
/* SL82C105 IDE Control/Status Register */
#define SL82C105_IDECSR 0x40
/* Fixup for Winbond ATA quirk, required for briq mostly because the
* 8259 is configured for level sensitive IRQ 14 and so wants the
* ATA controller to be set to fully native mode or bad things
* will happen.
*/
static void __devinit chrp_pci_fixup_winbond_ata(struct pci_dev *sl82c105)
{
u8 progif;
/* If non-briq machines need that fixup too, please speak up */
if (!machine_is(chrp) || _chrp_type != _CHRP_briq)
return;
if ((sl82c105->class & 5) != 5) {
printk("W83C553: Switching SL82C105 IDE to PCI native mode\n");
/* Enable SL82C105 PCI native IDE mode */
pci_read_config_byte(sl82c105, PCI_CLASS_PROG, &progif);
pci_write_config_byte(sl82c105, PCI_CLASS_PROG, progif | 0x05);
sl82c105->class |= 0x05;
/* Disable SL82C105 second port */
pci_write_config_word(sl82c105, SL82C105_IDECSR, 0x0003);
/* Clear IO BARs, they will be reassigned */
pci_write_config_dword(sl82c105, PCI_BASE_ADDRESS_0, 0);
pci_write_config_dword(sl82c105, PCI_BASE_ADDRESS_1, 0);
pci_write_config_dword(sl82c105, PCI_BASE_ADDRESS_2, 0);
pci_write_config_dword(sl82c105, PCI_BASE_ADDRESS_3, 0);
}
}
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_WINBOND, PCI_DEVICE_ID_WINBOND_82C105,
chrp_pci_fixup_winbond_ata);
/* Pegasos2 firmware version 20040810 configures the built-in IDE controller
* in legacy mode, but sets the PCI registers to PCI native mode.
* The chip can only operate in legacy mode, so force the PCI class into legacy
* mode as well. The same fixup must be done to the class-code property in
* the IDE node /pci@80000000/ide@C,1
*/
static void chrp_pci_fixup_vt8231_ata(struct pci_dev *viaide)
{
u8 progif;
struct pci_dev *viaisa;
if (!machine_is(chrp) || _chrp_type != _CHRP_Pegasos)
return;
if (viaide->irq != 14)
return;
viaisa = pci_get_device(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8231, NULL);
if (!viaisa)
return;
dev_info(&viaide->dev, "Fixing VIA IDE, force legacy mode on\n");
pci_read_config_byte(viaide, PCI_CLASS_PROG, &progif);
pci_write_config_byte(viaide, PCI_CLASS_PROG, progif & ~0x5);
viaide->class &= ~0x5;
pci_dev_put(viaisa);
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C586_1, chrp_pci_fixup_vt8231_ata);
| gpl-2.0 |
davidel/linux | drivers/hid/hid-samsung.c | 4177 | 6095 | /*
* HID driver for some samsung "special" devices
*
* Copyright (c) 1999 Andreas Gal
* Copyright (c) 2000-2005 Vojtech Pavlik <vojtech@suse.cz>
* Copyright (c) 2005 Michael Haboustak <mike-@cinci.rr.com> for Concept2, Inc
* Copyright (c) 2006-2007 Jiri Kosina
* Copyright (c) 2008 Jiri Slaby
* Copyright (c) 2010 Don Prince <dhprince.devel@yahoo.co.uk>
*
*
* This driver supports several HID devices:
*
* [0419:0001] Samsung IrDA remote controller (reports as Cypress USB Mouse).
* various hid report fixups for different variants.
*
* [0419:0600] Creative Desktop Wireless 6000 keyboard/mouse combo
* several key mappings used from the consumer usage page
* deviate from the USB HUT 1.12 standard.
*
*/
/*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*/
#include <linux/device.h>
#include <linux/usb.h>
#include <linux/hid.h>
#include <linux/module.h>
#include "hid-ids.h"
/*
* There are several variants for 0419:0001:
*
* 1. 184 byte report descriptor
* Vendor specific report #4 has a size of 48 bit,
* and therefore is not accepted when inspecting the descriptors.
* As a workaround we reinterpret the report as:
* Variable type, count 6, size 8 bit, log. maximum 255
* The burden to reconstruct the data is moved into user space.
*
* 2. 203 byte report descriptor
* Report #4 has an array field with logical range 0..18 instead of 1..15.
*
* 3. 135 byte report descriptor
* Report #4 has an array field with logical range 0..17 instead of 1..14.
*
* 4. 171 byte report descriptor
* Report #3 has an array field with logical range 0..1 instead of 1..3.
*/
static inline void samsung_irda_dev_trace(struct hid_device *hdev,
unsigned int rsize)
{
hid_info(hdev, "fixing up Samsung IrDA %d byte report descriptor\n",
rsize);
}
static __u8 *samsung_irda_report_fixup(struct hid_device *hdev, __u8 *rdesc,
unsigned int *rsize)
{
if (*rsize == 184 && rdesc[175] == 0x25 && rdesc[176] == 0x40 &&
rdesc[177] == 0x75 && rdesc[178] == 0x30 &&
rdesc[179] == 0x95 && rdesc[180] == 0x01 &&
rdesc[182] == 0x40) {
samsung_irda_dev_trace(hdev, 184);
rdesc[176] = 0xff;
rdesc[178] = 0x08;
rdesc[180] = 0x06;
rdesc[182] = 0x42;
} else
if (*rsize == 203 && rdesc[192] == 0x15 && rdesc[193] == 0x0 &&
rdesc[194] == 0x25 && rdesc[195] == 0x12) {
samsung_irda_dev_trace(hdev, 203);
rdesc[193] = 0x1;
rdesc[195] = 0xf;
} else
if (*rsize == 135 && rdesc[124] == 0x15 && rdesc[125] == 0x0 &&
rdesc[126] == 0x25 && rdesc[127] == 0x11) {
samsung_irda_dev_trace(hdev, 135);
rdesc[125] = 0x1;
rdesc[127] = 0xe;
} else
if (*rsize == 171 && rdesc[160] == 0x15 && rdesc[161] == 0x0 &&
rdesc[162] == 0x25 && rdesc[163] == 0x01) {
samsung_irda_dev_trace(hdev, 171);
rdesc[161] = 0x1;
rdesc[163] = 0x3;
}
return rdesc;
}
#define samsung_kbd_mouse_map_key_clear(c) \
hid_map_usage_clear(hi, usage, bit, max, EV_KEY, (c))
static int samsung_kbd_mouse_input_mapping(struct hid_device *hdev,
struct hid_input *hi, struct hid_field *field, struct hid_usage *usage,
unsigned long **bit, int *max)
{
struct usb_interface *intf = to_usb_interface(hdev->dev.parent);
unsigned short ifnum = intf->cur_altsetting->desc.bInterfaceNumber;
if (1 != ifnum || HID_UP_CONSUMER != (usage->hid & HID_USAGE_PAGE))
return 0;
dbg_hid("samsung wireless keyboard/mouse input mapping event [0x%x]\n",
usage->hid & HID_USAGE);
switch (usage->hid & HID_USAGE) {
/* report 2 */
case 0x183: samsung_kbd_mouse_map_key_clear(KEY_MEDIA); break;
case 0x195: samsung_kbd_mouse_map_key_clear(KEY_EMAIL); break;
case 0x196: samsung_kbd_mouse_map_key_clear(KEY_CALC); break;
case 0x197: samsung_kbd_mouse_map_key_clear(KEY_COMPUTER); break;
case 0x22b: samsung_kbd_mouse_map_key_clear(KEY_SEARCH); break;
case 0x22c: samsung_kbd_mouse_map_key_clear(KEY_WWW); break;
case 0x22d: samsung_kbd_mouse_map_key_clear(KEY_BACK); break;
case 0x22e: samsung_kbd_mouse_map_key_clear(KEY_FORWARD); break;
case 0x22f: samsung_kbd_mouse_map_key_clear(KEY_FAVORITES); break;
case 0x230: samsung_kbd_mouse_map_key_clear(KEY_REFRESH); break;
case 0x231: samsung_kbd_mouse_map_key_clear(KEY_STOP); break;
default:
return 0;
}
return 1;
}
static __u8 *samsung_report_fixup(struct hid_device *hdev, __u8 *rdesc,
unsigned int *rsize)
{
if (USB_DEVICE_ID_SAMSUNG_IR_REMOTE == hdev->product)
rdesc = samsung_irda_report_fixup(hdev, rdesc, rsize);
return rdesc;
}
static int samsung_input_mapping(struct hid_device *hdev, struct hid_input *hi,
struct hid_field *field, struct hid_usage *usage,
unsigned long **bit, int *max)
{
int ret = 0;
if (USB_DEVICE_ID_SAMSUNG_WIRELESS_KBD_MOUSE == hdev->product)
ret = samsung_kbd_mouse_input_mapping(hdev,
hi, field, usage, bit, max);
return ret;
}
static int samsung_probe(struct hid_device *hdev,
const struct hid_device_id *id)
{
int ret;
unsigned int cmask = HID_CONNECT_DEFAULT;
ret = hid_parse(hdev);
if (ret) {
hid_err(hdev, "parse failed\n");
goto err_free;
}
if (USB_DEVICE_ID_SAMSUNG_IR_REMOTE == hdev->product) {
if (hdev->rsize == 184) {
/* disable hidinput, force hiddev */
cmask = (cmask & ~HID_CONNECT_HIDINPUT) |
HID_CONNECT_HIDDEV_FORCE;
}
}
ret = hid_hw_start(hdev, cmask);
if (ret) {
hid_err(hdev, "hw start failed\n");
goto err_free;
}
return 0;
err_free:
return ret;
}
static const struct hid_device_id samsung_devices[] = {
{ HID_USB_DEVICE(USB_VENDOR_ID_SAMSUNG, USB_DEVICE_ID_SAMSUNG_IR_REMOTE) },
{ HID_USB_DEVICE(USB_VENDOR_ID_SAMSUNG, USB_DEVICE_ID_SAMSUNG_WIRELESS_KBD_MOUSE) },
{ }
};
MODULE_DEVICE_TABLE(hid, samsung_devices);
static struct hid_driver samsung_driver = {
.name = "samsung",
.id_table = samsung_devices,
.report_fixup = samsung_report_fixup,
.input_mapping = samsung_input_mapping,
.probe = samsung_probe,
};
module_hid_driver(samsung_driver);
MODULE_LICENSE("GPL");
| gpl-2.0 |
yuanguo8/nubiaz5s_kernel | arch/powerpc/sysdev/fsl_lbc.c | 4689 | 9842 | /*
* Freescale LBC and UPM routines.
*
* Copyright © 2007-2008 MontaVista Software, Inc.
* Copyright © 2010 Freescale Semiconductor
*
* Author: Anton Vorontsov <avorontsov@ru.mvista.com>
* Author: Jack Lan <Jack.Lan@freescale.com>
* Author: Roy Zang <tie-fei.zang@freescale.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <linux/init.h>
#include <linux/export.h>
#include <linux/kernel.h>
#include <linux/compiler.h>
#include <linux/spinlock.h>
#include <linux/types.h>
#include <linux/io.h>
#include <linux/of.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/platform_device.h>
#include <linux/interrupt.h>
#include <linux/mod_devicetable.h>
#include <asm/prom.h>
#include <asm/fsl_lbc.h>
static spinlock_t fsl_lbc_lock = __SPIN_LOCK_UNLOCKED(fsl_lbc_lock);
struct fsl_lbc_ctrl *fsl_lbc_ctrl_dev;
EXPORT_SYMBOL(fsl_lbc_ctrl_dev);
/**
* fsl_lbc_addr - convert the base address
* @addr_base: base address of the memory bank
*
* This function converts a base address of lbc into the right format for the
* BR register. If the SOC has eLBC then it returns 32bit physical address
* else it convers a 34bit local bus physical address to correct format of
* 32bit address for BR register (Example: MPC8641).
*/
u32 fsl_lbc_addr(phys_addr_t addr_base)
{
struct device_node *np = fsl_lbc_ctrl_dev->dev->of_node;
u32 addr = addr_base & 0xffff8000;
if (of_device_is_compatible(np, "fsl,elbc"))
return addr;
return addr | ((addr_base & 0x300000000ull) >> 19);
}
EXPORT_SYMBOL(fsl_lbc_addr);
/**
* fsl_lbc_find - find Localbus bank
* @addr_base: base address of the memory bank
*
* This function walks LBC banks comparing "Base address" field of the BR
* registers with the supplied addr_base argument. When bases match this
* function returns bank number (starting with 0), otherwise it returns
* appropriate errno value.
*/
int fsl_lbc_find(phys_addr_t addr_base)
{
int i;
struct fsl_lbc_regs __iomem *lbc;
if (!fsl_lbc_ctrl_dev || !fsl_lbc_ctrl_dev->regs)
return -ENODEV;
lbc = fsl_lbc_ctrl_dev->regs;
for (i = 0; i < ARRAY_SIZE(lbc->bank); i++) {
__be32 br = in_be32(&lbc->bank[i].br);
__be32 or = in_be32(&lbc->bank[i].or);
if (br & BR_V && (br & or & BR_BA) == fsl_lbc_addr(addr_base))
return i;
}
return -ENOENT;
}
EXPORT_SYMBOL(fsl_lbc_find);
/**
* fsl_upm_find - find pre-programmed UPM via base address
* @addr_base: base address of the memory bank controlled by the UPM
* @upm: pointer to the allocated fsl_upm structure
*
* This function fills fsl_upm structure so you can use it with the rest of
* UPM API. On success this function returns 0, otherwise it returns
* appropriate errno value.
*/
int fsl_upm_find(phys_addr_t addr_base, struct fsl_upm *upm)
{
int bank;
__be32 br;
struct fsl_lbc_regs __iomem *lbc;
bank = fsl_lbc_find(addr_base);
if (bank < 0)
return bank;
if (!fsl_lbc_ctrl_dev || !fsl_lbc_ctrl_dev->regs)
return -ENODEV;
lbc = fsl_lbc_ctrl_dev->regs;
br = in_be32(&lbc->bank[bank].br);
switch (br & BR_MSEL) {
case BR_MS_UPMA:
upm->mxmr = &lbc->mamr;
break;
case BR_MS_UPMB:
upm->mxmr = &lbc->mbmr;
break;
case BR_MS_UPMC:
upm->mxmr = &lbc->mcmr;
break;
default:
return -EINVAL;
}
switch (br & BR_PS) {
case BR_PS_8:
upm->width = 8;
break;
case BR_PS_16:
upm->width = 16;
break;
case BR_PS_32:
upm->width = 32;
break;
default:
return -EINVAL;
}
return 0;
}
EXPORT_SYMBOL(fsl_upm_find);
/**
* fsl_upm_run_pattern - actually run an UPM pattern
* @upm: pointer to the fsl_upm structure obtained via fsl_upm_find
* @io_base: remapped pointer to where memory access should happen
* @mar: MAR register content during pattern execution
*
* This function triggers dummy write to the memory specified by the io_base,
* thus UPM pattern actually executed. Note that mar usage depends on the
* pre-programmed AMX bits in the UPM RAM.
*/
int fsl_upm_run_pattern(struct fsl_upm *upm, void __iomem *io_base, u32 mar)
{
int ret = 0;
unsigned long flags;
if (!fsl_lbc_ctrl_dev || !fsl_lbc_ctrl_dev->regs)
return -ENODEV;
spin_lock_irqsave(&fsl_lbc_lock, flags);
out_be32(&fsl_lbc_ctrl_dev->regs->mar, mar);
switch (upm->width) {
case 8:
out_8(io_base, 0x0);
break;
case 16:
out_be16(io_base, 0x0);
break;
case 32:
out_be32(io_base, 0x0);
break;
default:
ret = -EINVAL;
break;
}
spin_unlock_irqrestore(&fsl_lbc_lock, flags);
return ret;
}
EXPORT_SYMBOL(fsl_upm_run_pattern);
static int __devinit fsl_lbc_ctrl_init(struct fsl_lbc_ctrl *ctrl,
struct device_node *node)
{
struct fsl_lbc_regs __iomem *lbc = ctrl->regs;
/* clear event registers */
setbits32(&lbc->ltesr, LTESR_CLEAR);
out_be32(&lbc->lteatr, 0);
out_be32(&lbc->ltear, 0);
out_be32(&lbc->lteccr, LTECCR_CLEAR);
out_be32(&lbc->ltedr, LTEDR_ENABLE);
/* Set the monitor timeout value to the maximum for erratum A001 */
if (of_device_is_compatible(node, "fsl,elbc"))
clrsetbits_be32(&lbc->lbcr, LBCR_BMT, LBCR_BMTPS);
return 0;
}
/*
* NOTE: This interrupt is used to report localbus events of various kinds,
* such as transaction errors on the chipselects.
*/
static irqreturn_t fsl_lbc_ctrl_irq(int irqno, void *data)
{
struct fsl_lbc_ctrl *ctrl = data;
struct fsl_lbc_regs __iomem *lbc = ctrl->regs;
u32 status;
status = in_be32(&lbc->ltesr);
if (!status)
return IRQ_NONE;
out_be32(&lbc->ltesr, LTESR_CLEAR);
out_be32(&lbc->lteatr, 0);
out_be32(&lbc->ltear, 0);
ctrl->irq_status = status;
if (status & LTESR_BM)
dev_err(ctrl->dev, "Local bus monitor time-out: "
"LTESR 0x%08X\n", status);
if (status & LTESR_WP)
dev_err(ctrl->dev, "Write protect error: "
"LTESR 0x%08X\n", status);
if (status & LTESR_ATMW)
dev_err(ctrl->dev, "Atomic write error: "
"LTESR 0x%08X\n", status);
if (status & LTESR_ATMR)
dev_err(ctrl->dev, "Atomic read error: "
"LTESR 0x%08X\n", status);
if (status & LTESR_CS)
dev_err(ctrl->dev, "Chip select error: "
"LTESR 0x%08X\n", status);
if (status & LTESR_UPM)
;
if (status & LTESR_FCT) {
dev_err(ctrl->dev, "FCM command time-out: "
"LTESR 0x%08X\n", status);
smp_wmb();
wake_up(&ctrl->irq_wait);
}
if (status & LTESR_PAR) {
dev_err(ctrl->dev, "Parity or Uncorrectable ECC error: "
"LTESR 0x%08X\n", status);
smp_wmb();
wake_up(&ctrl->irq_wait);
}
if (status & LTESR_CC) {
smp_wmb();
wake_up(&ctrl->irq_wait);
}
if (status & ~LTESR_MASK)
dev_err(ctrl->dev, "Unknown error: "
"LTESR 0x%08X\n", status);
return IRQ_HANDLED;
}
/*
* fsl_lbc_ctrl_probe
*
* called by device layer when it finds a device matching
* one our driver can handled. This code allocates all of
* the resources needed for the controller only. The
* resources for the NAND banks themselves are allocated
* in the chip probe function.
*/
static int __devinit fsl_lbc_ctrl_probe(struct platform_device *dev)
{
int ret;
if (!dev->dev.of_node) {
dev_err(&dev->dev, "Device OF-Node is NULL");
return -EFAULT;
}
fsl_lbc_ctrl_dev = kzalloc(sizeof(*fsl_lbc_ctrl_dev), GFP_KERNEL);
if (!fsl_lbc_ctrl_dev)
return -ENOMEM;
dev_set_drvdata(&dev->dev, fsl_lbc_ctrl_dev);
spin_lock_init(&fsl_lbc_ctrl_dev->lock);
init_waitqueue_head(&fsl_lbc_ctrl_dev->irq_wait);
fsl_lbc_ctrl_dev->regs = of_iomap(dev->dev.of_node, 0);
if (!fsl_lbc_ctrl_dev->regs) {
dev_err(&dev->dev, "failed to get memory region\n");
ret = -ENODEV;
goto err;
}
fsl_lbc_ctrl_dev->irq = irq_of_parse_and_map(dev->dev.of_node, 0);
if (fsl_lbc_ctrl_dev->irq == NO_IRQ) {
dev_err(&dev->dev, "failed to get irq resource\n");
ret = -ENODEV;
goto err;
}
fsl_lbc_ctrl_dev->dev = &dev->dev;
ret = fsl_lbc_ctrl_init(fsl_lbc_ctrl_dev, dev->dev.of_node);
if (ret < 0)
goto err;
ret = request_irq(fsl_lbc_ctrl_dev->irq, fsl_lbc_ctrl_irq, 0,
"fsl-lbc", fsl_lbc_ctrl_dev);
if (ret != 0) {
dev_err(&dev->dev, "failed to install irq (%d)\n",
fsl_lbc_ctrl_dev->irq);
ret = fsl_lbc_ctrl_dev->irq;
goto err;
}
/* Enable interrupts for any detected events */
out_be32(&fsl_lbc_ctrl_dev->regs->lteir, LTEIR_ENABLE);
return 0;
err:
iounmap(fsl_lbc_ctrl_dev->regs);
kfree(fsl_lbc_ctrl_dev);
fsl_lbc_ctrl_dev = NULL;
return ret;
}
#ifdef CONFIG_SUSPEND
/* save lbc registers */
static int fsl_lbc_suspend(struct platform_device *pdev, pm_message_t state)
{
struct fsl_lbc_ctrl *ctrl = dev_get_drvdata(&pdev->dev);
struct fsl_lbc_regs __iomem *lbc = ctrl->regs;
ctrl->saved_regs = kmalloc(sizeof(struct fsl_lbc_regs), GFP_KERNEL);
if (!ctrl->saved_regs)
return -ENOMEM;
_memcpy_fromio(ctrl->saved_regs, lbc, sizeof(struct fsl_lbc_regs));
return 0;
}
/* restore lbc registers */
static int fsl_lbc_resume(struct platform_device *pdev)
{
struct fsl_lbc_ctrl *ctrl = dev_get_drvdata(&pdev->dev);
struct fsl_lbc_regs __iomem *lbc = ctrl->regs;
if (ctrl->saved_regs) {
_memcpy_toio(lbc, ctrl->saved_regs,
sizeof(struct fsl_lbc_regs));
kfree(ctrl->saved_regs);
ctrl->saved_regs = NULL;
}
return 0;
}
#endif /* CONFIG_SUSPEND */
static const struct of_device_id fsl_lbc_match[] = {
{ .compatible = "fsl,elbc", },
{ .compatible = "fsl,pq3-localbus", },
{ .compatible = "fsl,pq2-localbus", },
{ .compatible = "fsl,pq2pro-localbus", },
{},
};
static struct platform_driver fsl_lbc_ctrl_driver = {
.driver = {
.name = "fsl-lbc",
.of_match_table = fsl_lbc_match,
},
.probe = fsl_lbc_ctrl_probe,
#ifdef CONFIG_SUSPEND
.suspend = fsl_lbc_suspend,
.resume = fsl_lbc_resume,
#endif
};
static int __init fsl_lbc_init(void)
{
return platform_driver_register(&fsl_lbc_ctrl_driver);
}
module_init(fsl_lbc_init);
| gpl-2.0 |
Jackeagle/android_kernel_htc_dlxub1 | drivers/gpu/drm/nouveau/nouveau_dma.c | 4945 | 7763 | /*
* Copyright (C) 2007 Ben Skeggs.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include "drmP.h"
#include "drm.h"
#include "nouveau_drv.h"
#include "nouveau_dma.h"
#include "nouveau_ramht.h"
void
nouveau_dma_init(struct nouveau_channel *chan)
{
struct drm_nouveau_private *dev_priv = chan->dev->dev_private;
struct nouveau_bo *pushbuf = chan->pushbuf_bo;
if (dev_priv->card_type >= NV_50) {
const int ib_size = pushbuf->bo.mem.size / 2;
chan->dma.ib_base = (pushbuf->bo.mem.size - ib_size) >> 2;
chan->dma.ib_max = (ib_size / 8) - 1;
chan->dma.ib_put = 0;
chan->dma.ib_free = chan->dma.ib_max - chan->dma.ib_put;
chan->dma.max = (pushbuf->bo.mem.size - ib_size) >> 2;
} else {
chan->dma.max = (pushbuf->bo.mem.size >> 2) - 2;
}
chan->dma.put = 0;
chan->dma.cur = chan->dma.put;
chan->dma.free = chan->dma.max - chan->dma.cur;
}
void
OUT_RINGp(struct nouveau_channel *chan, const void *data, unsigned nr_dwords)
{
bool is_iomem;
u32 *mem = ttm_kmap_obj_virtual(&chan->pushbuf_bo->kmap, &is_iomem);
mem = &mem[chan->dma.cur];
if (is_iomem)
memcpy_toio((void __force __iomem *)mem, data, nr_dwords * 4);
else
memcpy(mem, data, nr_dwords * 4);
chan->dma.cur += nr_dwords;
}
/* Fetch and adjust GPU GET pointer
*
* Returns:
* value >= 0, the adjusted GET pointer
* -EINVAL if GET pointer currently outside main push buffer
* -EBUSY if timeout exceeded
*/
static inline int
READ_GET(struct nouveau_channel *chan, uint64_t *prev_get, int *timeout)
{
uint64_t val;
val = nvchan_rd32(chan, chan->user_get);
if (chan->user_get_hi)
val |= (uint64_t)nvchan_rd32(chan, chan->user_get_hi) << 32;
/* reset counter as long as GET is still advancing, this is
* to avoid misdetecting a GPU lockup if the GPU happens to
* just be processing an operation that takes a long time
*/
if (val != *prev_get) {
*prev_get = val;
*timeout = 0;
}
if ((++*timeout & 0xff) == 0) {
DRM_UDELAY(1);
if (*timeout > 100000)
return -EBUSY;
}
if (val < chan->pushbuf_base ||
val > chan->pushbuf_base + (chan->dma.max << 2))
return -EINVAL;
return (val - chan->pushbuf_base) >> 2;
}
void
nv50_dma_push(struct nouveau_channel *chan, struct nouveau_bo *bo,
int delta, int length)
{
struct nouveau_bo *pb = chan->pushbuf_bo;
struct nouveau_vma *vma;
int ip = (chan->dma.ib_put * 2) + chan->dma.ib_base;
u64 offset;
vma = nouveau_bo_vma_find(bo, chan->vm);
BUG_ON(!vma);
offset = vma->offset + delta;
BUG_ON(chan->dma.ib_free < 1);
nouveau_bo_wr32(pb, ip++, lower_32_bits(offset));
nouveau_bo_wr32(pb, ip++, upper_32_bits(offset) | length << 8);
chan->dma.ib_put = (chan->dma.ib_put + 1) & chan->dma.ib_max;
DRM_MEMORYBARRIER();
/* Flush writes. */
nouveau_bo_rd32(pb, 0);
nvchan_wr32(chan, 0x8c, chan->dma.ib_put);
chan->dma.ib_free--;
}
static int
nv50_dma_push_wait(struct nouveau_channel *chan, int count)
{
uint32_t cnt = 0, prev_get = 0;
while (chan->dma.ib_free < count) {
uint32_t get = nvchan_rd32(chan, 0x88);
if (get != prev_get) {
prev_get = get;
cnt = 0;
}
if ((++cnt & 0xff) == 0) {
DRM_UDELAY(1);
if (cnt > 100000)
return -EBUSY;
}
chan->dma.ib_free = get - chan->dma.ib_put;
if (chan->dma.ib_free <= 0)
chan->dma.ib_free += chan->dma.ib_max;
}
return 0;
}
static int
nv50_dma_wait(struct nouveau_channel *chan, int slots, int count)
{
uint64_t prev_get = 0;
int ret, cnt = 0;
ret = nv50_dma_push_wait(chan, slots + 1);
if (unlikely(ret))
return ret;
while (chan->dma.free < count) {
int get = READ_GET(chan, &prev_get, &cnt);
if (unlikely(get < 0)) {
if (get == -EINVAL)
continue;
return get;
}
if (get <= chan->dma.cur) {
chan->dma.free = chan->dma.max - chan->dma.cur;
if (chan->dma.free >= count)
break;
FIRE_RING(chan);
do {
get = READ_GET(chan, &prev_get, &cnt);
if (unlikely(get < 0)) {
if (get == -EINVAL)
continue;
return get;
}
} while (get == 0);
chan->dma.cur = 0;
chan->dma.put = 0;
}
chan->dma.free = get - chan->dma.cur - 1;
}
return 0;
}
int
nouveau_dma_wait(struct nouveau_channel *chan, int slots, int size)
{
uint64_t prev_get = 0;
int cnt = 0, get;
if (chan->dma.ib_max)
return nv50_dma_wait(chan, slots, size);
while (chan->dma.free < size) {
get = READ_GET(chan, &prev_get, &cnt);
if (unlikely(get == -EBUSY))
return -EBUSY;
/* loop until we have a usable GET pointer. the value
* we read from the GPU may be outside the main ring if
* PFIFO is processing a buffer called from the main ring,
* discard these values until something sensible is seen.
*
* the other case we discard GET is while the GPU is fetching
* from the SKIPS area, so the code below doesn't have to deal
* with some fun corner cases.
*/
if (unlikely(get == -EINVAL) || get < NOUVEAU_DMA_SKIPS)
continue;
if (get <= chan->dma.cur) {
/* engine is fetching behind us, or is completely
* idle (GET == PUT) so we have free space up until
* the end of the push buffer
*
* we can only hit that path once per call due to
* looping back to the beginning of the push buffer,
* we'll hit the fetching-ahead-of-us path from that
* point on.
*
* the *one* exception to that rule is if we read
* GET==PUT, in which case the below conditional will
* always succeed and break us out of the wait loop.
*/
chan->dma.free = chan->dma.max - chan->dma.cur;
if (chan->dma.free >= size)
break;
/* not enough space left at the end of the push buffer,
* instruct the GPU to jump back to the start right
* after processing the currently pending commands.
*/
OUT_RING(chan, chan->pushbuf_base | 0x20000000);
/* wait for GET to depart from the skips area.
* prevents writing GET==PUT and causing a race
* condition that causes us to think the GPU is
* idle when it's not.
*/
do {
get = READ_GET(chan, &prev_get, &cnt);
if (unlikely(get == -EBUSY))
return -EBUSY;
if (unlikely(get == -EINVAL))
continue;
} while (get <= NOUVEAU_DMA_SKIPS);
WRITE_PUT(NOUVEAU_DMA_SKIPS);
/* we're now submitting commands at the start of
* the push buffer.
*/
chan->dma.cur =
chan->dma.put = NOUVEAU_DMA_SKIPS;
}
/* engine fetching ahead of us, we have space up until the
* current GET pointer. the "- 1" is to ensure there's
* space left to emit a jump back to the beginning of the
* push buffer if we require it. we can never get GET == PUT
* here, so this is safe.
*/
chan->dma.free = get - chan->dma.cur - 1;
}
return 0;
}
| gpl-2.0 |
vivilyu/android_kernel_huawei_c8813 | net/caif/cfmuxl.c | 5201 | 6463 | /*
* Copyright (C) ST-Ericsson AB 2010
* Author: Sjur Brendeland/sjur.brandeland@stericsson.com
* License terms: GNU General Public License (GPL) version 2
*/
#define pr_fmt(fmt) KBUILD_MODNAME ":%s(): " fmt, __func__
#include <linux/stddef.h>
#include <linux/spinlock.h>
#include <linux/slab.h>
#include <linux/rculist.h>
#include <net/caif/cfpkt.h>
#include <net/caif/cfmuxl.h>
#include <net/caif/cfsrvl.h>
#include <net/caif/cffrml.h>
#define container_obj(layr) container_of(layr, struct cfmuxl, layer)
#define CAIF_CTRL_CHANNEL 0
#define UP_CACHE_SIZE 8
#define DN_CACHE_SIZE 8
struct cfmuxl {
struct cflayer layer;
struct list_head srvl_list;
struct list_head frml_list;
struct cflayer *up_cache[UP_CACHE_SIZE];
struct cflayer *dn_cache[DN_CACHE_SIZE];
/*
* Set when inserting or removing downwards layers.
*/
spinlock_t transmit_lock;
/*
* Set when inserting or removing upwards layers.
*/
spinlock_t receive_lock;
};
static int cfmuxl_receive(struct cflayer *layr, struct cfpkt *pkt);
static int cfmuxl_transmit(struct cflayer *layr, struct cfpkt *pkt);
static void cfmuxl_ctrlcmd(struct cflayer *layr, enum caif_ctrlcmd ctrl,
int phyid);
static struct cflayer *get_up(struct cfmuxl *muxl, u16 id);
struct cflayer *cfmuxl_create(void)
{
struct cfmuxl *this = kmalloc(sizeof(struct cfmuxl), GFP_ATOMIC);
if (!this)
return NULL;
memset(this, 0, sizeof(*this));
this->layer.receive = cfmuxl_receive;
this->layer.transmit = cfmuxl_transmit;
this->layer.ctrlcmd = cfmuxl_ctrlcmd;
INIT_LIST_HEAD(&this->srvl_list);
INIT_LIST_HEAD(&this->frml_list);
spin_lock_init(&this->transmit_lock);
spin_lock_init(&this->receive_lock);
snprintf(this->layer.name, CAIF_LAYER_NAME_SZ, "mux");
return &this->layer;
}
int cfmuxl_set_dnlayer(struct cflayer *layr, struct cflayer *dn, u8 phyid)
{
struct cfmuxl *muxl = (struct cfmuxl *) layr;
spin_lock_bh(&muxl->transmit_lock);
list_add_rcu(&dn->node, &muxl->frml_list);
spin_unlock_bh(&muxl->transmit_lock);
return 0;
}
static struct cflayer *get_from_id(struct list_head *list, u16 id)
{
struct cflayer *lyr;
list_for_each_entry_rcu(lyr, list, node) {
if (lyr->id == id)
return lyr;
}
return NULL;
}
int cfmuxl_set_uplayer(struct cflayer *layr, struct cflayer *up, u8 linkid)
{
struct cfmuxl *muxl = container_obj(layr);
struct cflayer *old;
spin_lock_bh(&muxl->receive_lock);
/* Two entries with same id is wrong, so remove old layer from mux */
old = get_from_id(&muxl->srvl_list, linkid);
if (old != NULL)
list_del_rcu(&old->node);
list_add_rcu(&up->node, &muxl->srvl_list);
spin_unlock_bh(&muxl->receive_lock);
return 0;
}
struct cflayer *cfmuxl_remove_dnlayer(struct cflayer *layr, u8 phyid)
{
struct cfmuxl *muxl = container_obj(layr);
struct cflayer *dn;
int idx = phyid % DN_CACHE_SIZE;
spin_lock_bh(&muxl->transmit_lock);
RCU_INIT_POINTER(muxl->dn_cache[idx], NULL);
dn = get_from_id(&muxl->frml_list, phyid);
if (dn == NULL)
goto out;
list_del_rcu(&dn->node);
caif_assert(dn != NULL);
out:
spin_unlock_bh(&muxl->transmit_lock);
return dn;
}
static struct cflayer *get_up(struct cfmuxl *muxl, u16 id)
{
struct cflayer *up;
int idx = id % UP_CACHE_SIZE;
up = rcu_dereference(muxl->up_cache[idx]);
if (up == NULL || up->id != id) {
spin_lock_bh(&muxl->receive_lock);
up = get_from_id(&muxl->srvl_list, id);
rcu_assign_pointer(muxl->up_cache[idx], up);
spin_unlock_bh(&muxl->receive_lock);
}
return up;
}
static struct cflayer *get_dn(struct cfmuxl *muxl, struct dev_info *dev_info)
{
struct cflayer *dn;
int idx = dev_info->id % DN_CACHE_SIZE;
dn = rcu_dereference(muxl->dn_cache[idx]);
if (dn == NULL || dn->id != dev_info->id) {
spin_lock_bh(&muxl->transmit_lock);
dn = get_from_id(&muxl->frml_list, dev_info->id);
rcu_assign_pointer(muxl->dn_cache[idx], dn);
spin_unlock_bh(&muxl->transmit_lock);
}
return dn;
}
struct cflayer *cfmuxl_remove_uplayer(struct cflayer *layr, u8 id)
{
struct cflayer *up;
struct cfmuxl *muxl = container_obj(layr);
int idx = id % UP_CACHE_SIZE;
if (id == 0) {
pr_warn("Trying to remove control layer\n");
return NULL;
}
spin_lock_bh(&muxl->receive_lock);
up = get_from_id(&muxl->srvl_list, id);
if (up == NULL)
goto out;
RCU_INIT_POINTER(muxl->up_cache[idx], NULL);
list_del_rcu(&up->node);
out:
spin_unlock_bh(&muxl->receive_lock);
return up;
}
static int cfmuxl_receive(struct cflayer *layr, struct cfpkt *pkt)
{
int ret;
struct cfmuxl *muxl = container_obj(layr);
u8 id;
struct cflayer *up;
if (cfpkt_extr_head(pkt, &id, 1) < 0) {
pr_err("erroneous Caif Packet\n");
cfpkt_destroy(pkt);
return -EPROTO;
}
rcu_read_lock();
up = get_up(muxl, id);
if (up == NULL) {
pr_debug("Received data on unknown link ID = %d (0x%x)"
" up == NULL", id, id);
cfpkt_destroy(pkt);
/*
* Don't return ERROR, since modem misbehaves and sends out
* flow on before linksetup response.
*/
rcu_read_unlock();
return /* CFGLU_EPROT; */ 0;
}
/* We can't hold rcu_lock during receive, so take a ref count instead */
cfsrvl_get(up);
rcu_read_unlock();
ret = up->receive(up, pkt);
cfsrvl_put(up);
return ret;
}
static int cfmuxl_transmit(struct cflayer *layr, struct cfpkt *pkt)
{
struct cfmuxl *muxl = container_obj(layr);
int err;
u8 linkid;
struct cflayer *dn;
struct caif_payload_info *info = cfpkt_info(pkt);
BUG_ON(!info);
rcu_read_lock();
dn = get_dn(muxl, info->dev_info);
if (dn == NULL) {
pr_debug("Send data on unknown phy ID = %d (0x%x)\n",
info->dev_info->id, info->dev_info->id);
rcu_read_unlock();
cfpkt_destroy(pkt);
return -ENOTCONN;
}
info->hdr_len += 1;
linkid = info->channel_id;
cfpkt_add_head(pkt, &linkid, 1);
/* We can't hold rcu_lock during receive, so take a ref count instead */
cffrml_hold(dn);
rcu_read_unlock();
err = dn->transmit(dn, pkt);
cffrml_put(dn);
return err;
}
static void cfmuxl_ctrlcmd(struct cflayer *layr, enum caif_ctrlcmd ctrl,
int phyid)
{
struct cfmuxl *muxl = container_obj(layr);
struct cflayer *layer;
rcu_read_lock();
list_for_each_entry_rcu(layer, &muxl->srvl_list, node) {
if (cfsrvl_phyid_match(layer, phyid) && layer->ctrlcmd) {
if ((ctrl == _CAIF_CTRLCMD_PHYIF_DOWN_IND ||
ctrl == CAIF_CTRLCMD_REMOTE_SHUTDOWN_IND) &&
layer->id != 0)
cfmuxl_remove_uplayer(layr, layer->id);
/* NOTE: ctrlcmd is not allowed to block */
layer->ctrlcmd(layer, ctrl, phyid);
}
}
rcu_read_unlock();
}
| gpl-2.0 |
franciscofranco/flounder | arch/parisc/kernel/time.c | 8273 | 7667 | /*
* linux/arch/parisc/kernel/time.c
*
* Copyright (C) 1991, 1992, 1995 Linus Torvalds
* Modifications for ARM (C) 1994, 1995, 1996,1997 Russell King
* Copyright (C) 1999 SuSE GmbH, (Philipp Rumpf, prumpf@tux.org)
*
* 1994-07-02 Alan Modra
* fixed set_rtc_mmss, fixed time.year for >= 2000, new mktime
* 1998-12-20 Updated NTP code according to technical memorandum Jan '96
* "A Kernel Model for Precision Timekeeping" by Dave Mills
*/
#include <linux/errno.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/param.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/time.h>
#include <linux/init.h>
#include <linux/smp.h>
#include <linux/profile.h>
#include <linux/clocksource.h>
#include <linux/platform_device.h>
#include <linux/ftrace.h>
#include <asm/uaccess.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/page.h>
#include <asm/param.h>
#include <asm/pdc.h>
#include <asm/led.h>
#include <linux/timex.h>
static unsigned long clocktick __read_mostly; /* timer cycles per tick */
/*
* We keep time on PA-RISC Linux by using the Interval Timer which is
* a pair of registers; one is read-only and one is write-only; both
* accessed through CR16. The read-only register is 32 or 64 bits wide,
* and increments by 1 every CPU clock tick. The architecture only
* guarantees us a rate between 0.5 and 2, but all implementations use a
* rate of 1. The write-only register is 32-bits wide. When the lowest
* 32 bits of the read-only register compare equal to the write-only
* register, it raises a maskable external interrupt. Each processor has
* an Interval Timer of its own and they are not synchronised.
*
* We want to generate an interrupt every 1/HZ seconds. So we program
* CR16 to interrupt every @clocktick cycles. The it_value in cpu_data
* is programmed with the intended time of the next tick. We can be
* held off for an arbitrarily long period of time by interrupts being
* disabled, so we may miss one or more ticks.
*/
irqreturn_t __irq_entry timer_interrupt(int irq, void *dev_id)
{
unsigned long now, now2;
unsigned long next_tick;
unsigned long cycles_elapsed, ticks_elapsed = 1;
unsigned long cycles_remainder;
unsigned int cpu = smp_processor_id();
struct cpuinfo_parisc *cpuinfo = &per_cpu(cpu_data, cpu);
/* gcc can optimize for "read-only" case with a local clocktick */
unsigned long cpt = clocktick;
profile_tick(CPU_PROFILING);
/* Initialize next_tick to the expected tick time. */
next_tick = cpuinfo->it_value;
/* Get current cycle counter (Control Register 16). */
now = mfctl(16);
cycles_elapsed = now - next_tick;
if ((cycles_elapsed >> 6) < cpt) {
/* use "cheap" math (add/subtract) instead
* of the more expensive div/mul method
*/
cycles_remainder = cycles_elapsed;
while (cycles_remainder > cpt) {
cycles_remainder -= cpt;
ticks_elapsed++;
}
} else {
/* TODO: Reduce this to one fdiv op */
cycles_remainder = cycles_elapsed % cpt;
ticks_elapsed += cycles_elapsed / cpt;
}
/* convert from "division remainder" to "remainder of clock tick" */
cycles_remainder = cpt - cycles_remainder;
/* Determine when (in CR16 cycles) next IT interrupt will fire.
* We want IT to fire modulo clocktick even if we miss/skip some.
* But those interrupts don't in fact get delivered that regularly.
*/
next_tick = now + cycles_remainder;
cpuinfo->it_value = next_tick;
/* Program the IT when to deliver the next interrupt.
* Only bottom 32-bits of next_tick are writable in CR16!
*/
mtctl(next_tick, 16);
/* Skip one clocktick on purpose if we missed next_tick.
* The new CR16 must be "later" than current CR16 otherwise
* itimer would not fire until CR16 wrapped - e.g 4 seconds
* later on a 1Ghz processor. We'll account for the missed
* tick on the next timer interrupt.
*
* "next_tick - now" will always give the difference regardless
* if one or the other wrapped. If "now" is "bigger" we'll end up
* with a very large unsigned number.
*/
now2 = mfctl(16);
if (next_tick - now2 > cpt)
mtctl(next_tick+cpt, 16);
#if 1
/*
* GGG: DEBUG code for how many cycles programming CR16 used.
*/
if (unlikely(now2 - now > 0x3000)) /* 12K cycles */
printk (KERN_CRIT "timer_interrupt(CPU %d): SLOW! 0x%lx cycles!"
" cyc %lX rem %lX "
" next/now %lX/%lX\n",
cpu, now2 - now, cycles_elapsed, cycles_remainder,
next_tick, now );
#endif
/* Can we differentiate between "early CR16" (aka Scenario 1) and
* "long delay" (aka Scenario 3)? I don't think so.
*
* Timer_interrupt will be delivered at least a few hundred cycles
* after the IT fires. But it's arbitrary how much time passes
* before we call it "late". I've picked one second.
*
* It's important NO printk's are between reading CR16 and
* setting up the next value. May introduce huge variance.
*/
if (unlikely(ticks_elapsed > HZ)) {
/* Scenario 3: very long delay? bad in any case */
printk (KERN_CRIT "timer_interrupt(CPU %d): delayed!"
" cycles %lX rem %lX "
" next/now %lX/%lX\n",
cpu,
cycles_elapsed, cycles_remainder,
next_tick, now );
}
/* Done mucking with unreliable delivery of interrupts.
* Go do system house keeping.
*/
if (!--cpuinfo->prof_counter) {
cpuinfo->prof_counter = cpuinfo->prof_multiplier;
update_process_times(user_mode(get_irq_regs()));
}
if (cpu == 0)
xtime_update(ticks_elapsed);
return IRQ_HANDLED;
}
unsigned long profile_pc(struct pt_regs *regs)
{
unsigned long pc = instruction_pointer(regs);
if (regs->gr[0] & PSW_N)
pc -= 4;
#ifdef CONFIG_SMP
if (in_lock_functions(pc))
pc = regs->gr[2];
#endif
return pc;
}
EXPORT_SYMBOL(profile_pc);
/* clock source code */
static cycle_t read_cr16(struct clocksource *cs)
{
return get_cycles();
}
static struct clocksource clocksource_cr16 = {
.name = "cr16",
.rating = 300,
.read = read_cr16,
.mask = CLOCKSOURCE_MASK(BITS_PER_LONG),
.flags = CLOCK_SOURCE_IS_CONTINUOUS,
};
#ifdef CONFIG_SMP
int update_cr16_clocksource(void)
{
/* since the cr16 cycle counters are not synchronized across CPUs,
we'll check if we should switch to a safe clocksource: */
if (clocksource_cr16.rating != 0 && num_online_cpus() > 1) {
clocksource_change_rating(&clocksource_cr16, 0);
return 1;
}
return 0;
}
#else
int update_cr16_clocksource(void)
{
return 0; /* no change */
}
#endif /*CONFIG_SMP*/
void __init start_cpu_itimer(void)
{
unsigned int cpu = smp_processor_id();
unsigned long next_tick = mfctl(16) + clocktick;
mtctl(next_tick, 16); /* kick off Interval Timer (CR16) */
per_cpu(cpu_data, cpu).it_value = next_tick;
}
static struct platform_device rtc_generic_dev = {
.name = "rtc-generic",
.id = -1,
};
static int __init rtc_init(void)
{
if (platform_device_register(&rtc_generic_dev) < 0)
printk(KERN_ERR "unable to register rtc device...\n");
/* not necessarily an error */
return 0;
}
module_init(rtc_init);
void read_persistent_clock(struct timespec *ts)
{
static struct pdc_tod tod_data;
if (pdc_tod_read(&tod_data) == 0) {
ts->tv_sec = tod_data.tod_sec;
ts->tv_nsec = tod_data.tod_usec * 1000;
} else {
printk(KERN_ERR "Error reading tod clock\n");
ts->tv_sec = 0;
ts->tv_nsec = 0;
}
}
void __init time_init(void)
{
unsigned long current_cr16_khz;
clocktick = (100 * PAGE0->mem_10msec) / HZ;
start_cpu_itimer(); /* get CPU 0 started */
/* register at clocksource framework */
current_cr16_khz = PAGE0->mem_10msec/10; /* kHz */
clocksource_register_khz(&clocksource_cr16, current_cr16_khz);
}
| gpl-2.0 |
MassStash/htc_jewel_kernel_sense | drivers/gpu/stub/poulsbo.c | 8529 | 1374 | /*
* Intel Poulsbo Stub driver
*
* Copyright (C) 2010 Novell <jlee@novell.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
*/
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/acpi.h>
#include <acpi/video.h>
#define DRIVER_NAME "poulsbo"
enum {
CHIP_PSB_8108 = 0,
CHIP_PSB_8109 = 1,
};
static DEFINE_PCI_DEVICE_TABLE(pciidlist) = {
{0x8086, 0x8108, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_PSB_8108}, \
{0x8086, 0x8109, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_PSB_8109}, \
{0, 0, 0}
};
static int poulsbo_probe(struct pci_dev *pdev, const struct pci_device_id *id)
{
return acpi_video_register();
}
static void poulsbo_remove(struct pci_dev *pdev)
{
acpi_video_unregister();
}
static struct pci_driver poulsbo_driver = {
.name = DRIVER_NAME,
.id_table = pciidlist,
.probe = poulsbo_probe,
.remove = poulsbo_remove,
};
static int __init poulsbo_init(void)
{
return pci_register_driver(&poulsbo_driver);
}
static void __exit poulsbo_exit(void)
{
pci_unregister_driver(&poulsbo_driver);
}
module_init(poulsbo_init);
module_exit(poulsbo_exit);
MODULE_AUTHOR("Lee, Chun-Yi <jlee@novell.com>");
MODULE_DESCRIPTION("Poulsbo Stub Driver");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, pciidlist);
| gpl-2.0 |
sos22/nc1.5 | arch/arm/mach-vt8500/bv07.c | 82 | 2254 | /*
* arch/arm/mach-vt8500/bv07.c
*
* Copyright (C) 2010 Alexey Charkov <alchark@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/io.h>
#include <linux/pm.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <mach/restart.h>
#include "devices.h"
static void __iomem *pmc_hiber;
static struct platform_device *devices[] __initdata = {
&vt8500_device_uart0,
&vt8500_device_lcdc,
&vt8500_device_ehci,
&vt8500_device_ge_rops,
&vt8500_device_pwm,
&vt8500_device_pwmbl,
&vt8500_device_rtc,
};
static void vt8500_power_off(void)
{
local_irq_disable();
writew(5, pmc_hiber);
asm("mcr%? p15, 0, %0, c7, c0, 4" : : "r" (0));
}
void __init bv07_init(void)
{
#ifdef CONFIG_FB_VT8500
void __iomem *gpio_mux_reg = ioremap(wmt_gpio_base + 0x200, 4);
if (gpio_mux_reg) {
writel(readl(gpio_mux_reg) | 1, gpio_mux_reg);
iounmap(gpio_mux_reg);
} else {
printk(KERN_ERR "Could not remap the GPIO mux register, display may not work properly!\n");
}
#endif
pmc_hiber = ioremap(wmt_pmc_base + 0x12, 2);
if (pmc_hiber)
pm_power_off = &vt8500_power_off;
else
printk(KERN_ERR "PMC Hibernation register could not be remapped, not enabling power off!\n");
wmt_setup_restart();
vt8500_set_resources();
platform_add_devices(devices, ARRAY_SIZE(devices));
vt8500_gpio_init();
}
MACHINE_START(BV07, "Benign BV07 Mini Netbook")
.atag_offset = 0x100,
.restart = wmt_restart,
.reserve = vt8500_reserve_mem,
.map_io = vt8500_map_io,
.init_irq = vt8500_init_irq,
.timer = &vt8500_timer,
.init_machine = bv07_init,
MACHINE_END
| gpl-2.0 |
muryliang/linux | kernel/events/ring_buffer.c | 82 | 18165 | /*
* Performance events ring-buffer code:
*
* Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
* Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar
* Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
* Copyright © 2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
*
* For licensing details see kernel-base/COPYING
*/
#include <linux/perf_event.h>
#include <linux/vmalloc.h>
#include <linux/slab.h>
#include <linux/circ_buf.h>
#include <linux/poll.h>
#include "internal.h"
static void perf_output_wakeup(struct perf_output_handle *handle)
{
atomic_set(&handle->rb->poll, POLLIN);
handle->event->pending_wakeup = 1;
irq_work_queue(&handle->event->pending);
}
/*
* We need to ensure a later event_id doesn't publish a head when a former
* event isn't done writing. However since we need to deal with NMIs we
* cannot fully serialize things.
*
* We only publish the head (and generate a wakeup) when the outer-most
* event completes.
*/
static void perf_output_get_handle(struct perf_output_handle *handle)
{
struct ring_buffer *rb = handle->rb;
preempt_disable();
local_inc(&rb->nest);
handle->wakeup = local_read(&rb->wakeup);
}
static void perf_output_put_handle(struct perf_output_handle *handle)
{
struct ring_buffer *rb = handle->rb;
unsigned long head;
again:
head = local_read(&rb->head);
/*
* IRQ/NMI can happen here, which means we can miss a head update.
*/
if (!local_dec_and_test(&rb->nest))
goto out;
/*
* Since the mmap() consumer (userspace) can run on a different CPU:
*
* kernel user
*
* if (LOAD ->data_tail) { LOAD ->data_head
* (A) smp_rmb() (C)
* STORE $data LOAD $data
* smp_wmb() (B) smp_mb() (D)
* STORE ->data_head STORE ->data_tail
* }
*
* Where A pairs with D, and B pairs with C.
*
* In our case (A) is a control dependency that separates the load of
* the ->data_tail and the stores of $data. In case ->data_tail
* indicates there is no room in the buffer to store $data we do not.
*
* D needs to be a full barrier since it separates the data READ
* from the tail WRITE.
*
* For B a WMB is sufficient since it separates two WRITEs, and for C
* an RMB is sufficient since it separates two READs.
*
* See perf_output_begin().
*/
smp_wmb(); /* B, matches C */
rb->user_page->data_head = head;
/*
* Now check if we missed an update -- rely on previous implied
* compiler barriers to force a re-read.
*/
if (unlikely(head != local_read(&rb->head))) {
local_inc(&rb->nest);
goto again;
}
if (handle->wakeup != local_read(&rb->wakeup))
perf_output_wakeup(handle);
out:
preempt_enable();
}
int perf_output_begin(struct perf_output_handle *handle,
struct perf_event *event, unsigned int size)
{
struct ring_buffer *rb;
unsigned long tail, offset, head;
int have_lost, page_shift;
struct {
struct perf_event_header header;
u64 id;
u64 lost;
} lost_event;
rcu_read_lock();
/*
* For inherited events we send all the output towards the parent.
*/
if (event->parent)
event = event->parent;
rb = rcu_dereference(event->rb);
if (unlikely(!rb))
goto out;
if (unlikely(!rb->nr_pages))
goto out;
handle->rb = rb;
handle->event = event;
have_lost = local_read(&rb->lost);
if (unlikely(have_lost)) {
size += sizeof(lost_event);
if (event->attr.sample_id_all)
size += event->id_header_size;
}
perf_output_get_handle(handle);
do {
tail = READ_ONCE_CTRL(rb->user_page->data_tail);
offset = head = local_read(&rb->head);
if (!rb->overwrite &&
unlikely(CIRC_SPACE(head, tail, perf_data_size(rb)) < size))
goto fail;
/*
* The above forms a control dependency barrier separating the
* @tail load above from the data stores below. Since the @tail
* load is required to compute the branch to fail below.
*
* A, matches D; the full memory barrier userspace SHOULD issue
* after reading the data and before storing the new tail
* position.
*
* See perf_output_put_handle().
*/
head += size;
} while (local_cmpxchg(&rb->head, offset, head) != offset);
/*
* We rely on the implied barrier() by local_cmpxchg() to ensure
* none of the data stores below can be lifted up by the compiler.
*/
if (unlikely(head - local_read(&rb->wakeup) > rb->watermark))
local_add(rb->watermark, &rb->wakeup);
page_shift = PAGE_SHIFT + page_order(rb);
handle->page = (offset >> page_shift) & (rb->nr_pages - 1);
offset &= (1UL << page_shift) - 1;
handle->addr = rb->data_pages[handle->page] + offset;
handle->size = (1UL << page_shift) - offset;
if (unlikely(have_lost)) {
struct perf_sample_data sample_data;
lost_event.header.size = sizeof(lost_event);
lost_event.header.type = PERF_RECORD_LOST;
lost_event.header.misc = 0;
lost_event.id = event->id;
lost_event.lost = local_xchg(&rb->lost, 0);
perf_event_header__init_id(&lost_event.header,
&sample_data, event);
perf_output_put(handle, lost_event);
perf_event__output_id_sample(event, handle, &sample_data);
}
return 0;
fail:
local_inc(&rb->lost);
perf_output_put_handle(handle);
out:
rcu_read_unlock();
return -ENOSPC;
}
unsigned int perf_output_copy(struct perf_output_handle *handle,
const void *buf, unsigned int len)
{
return __output_copy(handle, buf, len);
}
unsigned int perf_output_skip(struct perf_output_handle *handle,
unsigned int len)
{
return __output_skip(handle, NULL, len);
}
void perf_output_end(struct perf_output_handle *handle)
{
perf_output_put_handle(handle);
rcu_read_unlock();
}
static void rb_irq_work(struct irq_work *work);
static void
ring_buffer_init(struct ring_buffer *rb, long watermark, int flags)
{
long max_size = perf_data_size(rb);
if (watermark)
rb->watermark = min(max_size, watermark);
if (!rb->watermark)
rb->watermark = max_size / 2;
if (flags & RING_BUFFER_WRITABLE)
rb->overwrite = 0;
else
rb->overwrite = 1;
atomic_set(&rb->refcount, 1);
INIT_LIST_HEAD(&rb->event_list);
spin_lock_init(&rb->event_lock);
init_irq_work(&rb->irq_work, rb_irq_work);
}
static void ring_buffer_put_async(struct ring_buffer *rb)
{
if (!atomic_dec_and_test(&rb->refcount))
return;
rb->rcu_head.next = (void *)rb;
irq_work_queue(&rb->irq_work);
}
/*
* This is called before hardware starts writing to the AUX area to
* obtain an output handle and make sure there's room in the buffer.
* When the capture completes, call perf_aux_output_end() to commit
* the recorded data to the buffer.
*
* The ordering is similar to that of perf_output_{begin,end}, with
* the exception of (B), which should be taken care of by the pmu
* driver, since ordering rules will differ depending on hardware.
*/
void *perf_aux_output_begin(struct perf_output_handle *handle,
struct perf_event *event)
{
struct perf_event *output_event = event;
unsigned long aux_head, aux_tail;
struct ring_buffer *rb;
if (output_event->parent)
output_event = output_event->parent;
/*
* Since this will typically be open across pmu::add/pmu::del, we
* grab ring_buffer's refcount instead of holding rcu read lock
* to make sure it doesn't disappear under us.
*/
rb = ring_buffer_get(output_event);
if (!rb)
return NULL;
if (!rb_has_aux(rb) || !atomic_inc_not_zero(&rb->aux_refcount))
goto err;
/*
* Nesting is not supported for AUX area, make sure nested
* writers are caught early
*/
if (WARN_ON_ONCE(local_xchg(&rb->aux_nest, 1)))
goto err_put;
aux_head = local_read(&rb->aux_head);
handle->rb = rb;
handle->event = event;
handle->head = aux_head;
handle->size = 0;
/*
* In overwrite mode, AUX data stores do not depend on aux_tail,
* therefore (A) control dependency barrier does not exist. The
* (B) <-> (C) ordering is still observed by the pmu driver.
*/
if (!rb->aux_overwrite) {
aux_tail = ACCESS_ONCE(rb->user_page->aux_tail);
handle->wakeup = local_read(&rb->aux_wakeup) + rb->aux_watermark;
if (aux_head - aux_tail < perf_aux_size(rb))
handle->size = CIRC_SPACE(aux_head, aux_tail, perf_aux_size(rb));
/*
* handle->size computation depends on aux_tail load; this forms a
* control dependency barrier separating aux_tail load from aux data
* store that will be enabled on successful return
*/
if (!handle->size) { /* A, matches D */
event->pending_disable = 1;
perf_output_wakeup(handle);
local_set(&rb->aux_nest, 0);
goto err_put;
}
}
return handle->rb->aux_priv;
err_put:
rb_free_aux(rb);
err:
ring_buffer_put_async(rb);
handle->event = NULL;
return NULL;
}
/*
* Commit the data written by hardware into the ring buffer by adjusting
* aux_head and posting a PERF_RECORD_AUX into the perf buffer. It is the
* pmu driver's responsibility to observe ordering rules of the hardware,
* so that all the data is externally visible before this is called.
*/
void perf_aux_output_end(struct perf_output_handle *handle, unsigned long size,
bool truncated)
{
struct ring_buffer *rb = handle->rb;
unsigned long aux_head;
u64 flags = 0;
if (truncated)
flags |= PERF_AUX_FLAG_TRUNCATED;
/* in overwrite mode, driver provides aux_head via handle */
if (rb->aux_overwrite) {
flags |= PERF_AUX_FLAG_OVERWRITE;
aux_head = handle->head;
local_set(&rb->aux_head, aux_head);
} else {
aux_head = local_read(&rb->aux_head);
local_add(size, &rb->aux_head);
}
if (size || flags) {
/*
* Only send RECORD_AUX if we have something useful to communicate
*/
perf_event_aux_event(handle->event, aux_head, size, flags);
}
aux_head = rb->user_page->aux_head = local_read(&rb->aux_head);
if (aux_head - local_read(&rb->aux_wakeup) >= rb->aux_watermark) {
perf_output_wakeup(handle);
local_add(rb->aux_watermark, &rb->aux_wakeup);
}
handle->event = NULL;
local_set(&rb->aux_nest, 0);
rb_free_aux(rb);
ring_buffer_put_async(rb);
}
/*
* Skip over a given number of bytes in the AUX buffer, due to, for example,
* hardware's alignment constraints.
*/
int perf_aux_output_skip(struct perf_output_handle *handle, unsigned long size)
{
struct ring_buffer *rb = handle->rb;
unsigned long aux_head;
if (size > handle->size)
return -ENOSPC;
local_add(size, &rb->aux_head);
aux_head = rb->user_page->aux_head = local_read(&rb->aux_head);
if (aux_head - local_read(&rb->aux_wakeup) >= rb->aux_watermark) {
perf_output_wakeup(handle);
local_add(rb->aux_watermark, &rb->aux_wakeup);
handle->wakeup = local_read(&rb->aux_wakeup) +
rb->aux_watermark;
}
handle->head = aux_head;
handle->size -= size;
return 0;
}
void *perf_get_aux(struct perf_output_handle *handle)
{
/* this is only valid between perf_aux_output_begin and *_end */
if (!handle->event)
return NULL;
return handle->rb->aux_priv;
}
#define PERF_AUX_GFP (GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_NORETRY)
static struct page *rb_alloc_aux_page(int node, int order)
{
struct page *page;
if (order > MAX_ORDER)
order = MAX_ORDER;
do {
page = alloc_pages_node(node, PERF_AUX_GFP, order);
} while (!page && order--);
if (page && order) {
/*
* Communicate the allocation size to the driver
*/
split_page(page, order);
SetPagePrivate(page);
set_page_private(page, order);
}
return page;
}
static void rb_free_aux_page(struct ring_buffer *rb, int idx)
{
struct page *page = virt_to_page(rb->aux_pages[idx]);
ClearPagePrivate(page);
page->mapping = NULL;
__free_page(page);
}
int rb_alloc_aux(struct ring_buffer *rb, struct perf_event *event,
pgoff_t pgoff, int nr_pages, long watermark, int flags)
{
bool overwrite = !(flags & RING_BUFFER_WRITABLE);
int node = (event->cpu == -1) ? -1 : cpu_to_node(event->cpu);
int ret = -ENOMEM, max_order = 0;
if (!has_aux(event))
return -ENOTSUPP;
if (event->pmu->capabilities & PERF_PMU_CAP_AUX_NO_SG) {
/*
* We need to start with the max_order that fits in nr_pages,
* not the other way around, hence ilog2() and not get_order.
*/
max_order = ilog2(nr_pages);
/*
* PMU requests more than one contiguous chunks of memory
* for SW double buffering
*/
if ((event->pmu->capabilities & PERF_PMU_CAP_AUX_SW_DOUBLEBUF) &&
!overwrite) {
if (!max_order)
return -EINVAL;
max_order--;
}
}
rb->aux_pages = kzalloc_node(nr_pages * sizeof(void *), GFP_KERNEL, node);
if (!rb->aux_pages)
return -ENOMEM;
rb->free_aux = event->pmu->free_aux;
for (rb->aux_nr_pages = 0; rb->aux_nr_pages < nr_pages;) {
struct page *page;
int last, order;
order = min(max_order, ilog2(nr_pages - rb->aux_nr_pages));
page = rb_alloc_aux_page(node, order);
if (!page)
goto out;
for (last = rb->aux_nr_pages + (1 << page_private(page));
last > rb->aux_nr_pages; rb->aux_nr_pages++)
rb->aux_pages[rb->aux_nr_pages] = page_address(page++);
}
/*
* In overwrite mode, PMUs that don't support SG may not handle more
* than one contiguous allocation, since they rely on PMI to do double
* buffering. In this case, the entire buffer has to be one contiguous
* chunk.
*/
if ((event->pmu->capabilities & PERF_PMU_CAP_AUX_NO_SG) &&
overwrite) {
struct page *page = virt_to_page(rb->aux_pages[0]);
if (page_private(page) != max_order)
goto out;
}
rb->aux_priv = event->pmu->setup_aux(event->cpu, rb->aux_pages, nr_pages,
overwrite);
if (!rb->aux_priv)
goto out;
ret = 0;
/*
* aux_pages (and pmu driver's private data, aux_priv) will be
* referenced in both producer's and consumer's contexts, thus
* we keep a refcount here to make sure either of the two can
* reference them safely.
*/
atomic_set(&rb->aux_refcount, 1);
rb->aux_overwrite = overwrite;
rb->aux_watermark = watermark;
if (!rb->aux_watermark && !rb->aux_overwrite)
rb->aux_watermark = nr_pages << (PAGE_SHIFT - 1);
out:
if (!ret)
rb->aux_pgoff = pgoff;
else
rb_free_aux(rb);
return ret;
}
static void __rb_free_aux(struct ring_buffer *rb)
{
int pg;
if (rb->aux_priv) {
rb->free_aux(rb->aux_priv);
rb->free_aux = NULL;
rb->aux_priv = NULL;
}
for (pg = 0; pg < rb->aux_nr_pages; pg++)
rb_free_aux_page(rb, pg);
kfree(rb->aux_pages);
rb->aux_nr_pages = 0;
}
void rb_free_aux(struct ring_buffer *rb)
{
if (atomic_dec_and_test(&rb->aux_refcount))
irq_work_queue(&rb->irq_work);
}
static void rb_irq_work(struct irq_work *work)
{
struct ring_buffer *rb = container_of(work, struct ring_buffer, irq_work);
if (!atomic_read(&rb->aux_refcount))
__rb_free_aux(rb);
if (rb->rcu_head.next == (void *)rb)
call_rcu(&rb->rcu_head, rb_free_rcu);
}
#ifndef CONFIG_PERF_USE_VMALLOC
/*
* Back perf_mmap() with regular GFP_KERNEL-0 pages.
*/
static struct page *
__perf_mmap_to_page(struct ring_buffer *rb, unsigned long pgoff)
{
if (pgoff > rb->nr_pages)
return NULL;
if (pgoff == 0)
return virt_to_page(rb->user_page);
return virt_to_page(rb->data_pages[pgoff - 1]);
}
static void *perf_mmap_alloc_page(int cpu)
{
struct page *page;
int node;
node = (cpu == -1) ? cpu : cpu_to_node(cpu);
page = alloc_pages_node(node, GFP_KERNEL | __GFP_ZERO, 0);
if (!page)
return NULL;
return page_address(page);
}
struct ring_buffer *rb_alloc(int nr_pages, long watermark, int cpu, int flags)
{
struct ring_buffer *rb;
unsigned long size;
int i;
size = sizeof(struct ring_buffer);
size += nr_pages * sizeof(void *);
rb = kzalloc(size, GFP_KERNEL);
if (!rb)
goto fail;
rb->user_page = perf_mmap_alloc_page(cpu);
if (!rb->user_page)
goto fail_user_page;
for (i = 0; i < nr_pages; i++) {
rb->data_pages[i] = perf_mmap_alloc_page(cpu);
if (!rb->data_pages[i])
goto fail_data_pages;
}
rb->nr_pages = nr_pages;
ring_buffer_init(rb, watermark, flags);
return rb;
fail_data_pages:
for (i--; i >= 0; i--)
free_page((unsigned long)rb->data_pages[i]);
free_page((unsigned long)rb->user_page);
fail_user_page:
kfree(rb);
fail:
return NULL;
}
static void perf_mmap_free_page(unsigned long addr)
{
struct page *page = virt_to_page((void *)addr);
page->mapping = NULL;
__free_page(page);
}
void rb_free(struct ring_buffer *rb)
{
int i;
perf_mmap_free_page((unsigned long)rb->user_page);
for (i = 0; i < rb->nr_pages; i++)
perf_mmap_free_page((unsigned long)rb->data_pages[i]);
kfree(rb);
}
#else
static int data_page_nr(struct ring_buffer *rb)
{
return rb->nr_pages << page_order(rb);
}
static struct page *
__perf_mmap_to_page(struct ring_buffer *rb, unsigned long pgoff)
{
/* The '>' counts in the user page. */
if (pgoff > data_page_nr(rb))
return NULL;
return vmalloc_to_page((void *)rb->user_page + pgoff * PAGE_SIZE);
}
static void perf_mmap_unmark_page(void *addr)
{
struct page *page = vmalloc_to_page(addr);
page->mapping = NULL;
}
static void rb_free_work(struct work_struct *work)
{
struct ring_buffer *rb;
void *base;
int i, nr;
rb = container_of(work, struct ring_buffer, work);
nr = data_page_nr(rb);
base = rb->user_page;
/* The '<=' counts in the user page. */
for (i = 0; i <= nr; i++)
perf_mmap_unmark_page(base + (i * PAGE_SIZE));
vfree(base);
kfree(rb);
}
void rb_free(struct ring_buffer *rb)
{
schedule_work(&rb->work);
}
struct ring_buffer *rb_alloc(int nr_pages, long watermark, int cpu, int flags)
{
struct ring_buffer *rb;
unsigned long size;
void *all_buf;
size = sizeof(struct ring_buffer);
size += sizeof(void *);
rb = kzalloc(size, GFP_KERNEL);
if (!rb)
goto fail;
INIT_WORK(&rb->work, rb_free_work);
all_buf = vmalloc_user((nr_pages + 1) * PAGE_SIZE);
if (!all_buf)
goto fail_all_buf;
rb->user_page = all_buf;
rb->data_pages[0] = all_buf + PAGE_SIZE;
rb->page_order = ilog2(nr_pages);
rb->nr_pages = !!nr_pages;
ring_buffer_init(rb, watermark, flags);
return rb;
fail_all_buf:
kfree(rb);
fail:
return NULL;
}
#endif
struct page *
perf_mmap_to_page(struct ring_buffer *rb, unsigned long pgoff)
{
if (rb->aux_nr_pages) {
/* above AUX space */
if (pgoff > rb->aux_pgoff + rb->aux_nr_pages)
return NULL;
/* AUX space */
if (pgoff >= rb->aux_pgoff)
return virt_to_page(rb->aux_pages[pgoff - rb->aux_pgoff]);
}
return __perf_mmap_to_page(rb, pgoff);
}
| gpl-2.0 |
ryangribble/xbmc | xbmc/filesystem/MusicDatabaseDirectory/DirectoryNodeGrouped.cpp | 82 | 1793 | /*
* Copyright (C) 2005-2013 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "DirectoryNodeGrouped.h"
#include "music/MusicDatabase.h"
using namespace XFILE::MUSICDATABASEDIRECTORY;
CDirectoryNodeGrouped::CDirectoryNodeGrouped(NODE_TYPE type, const std::string& strName, CDirectoryNode* pParent)
: CDirectoryNode(type, strName, pParent)
{ }
NODE_TYPE CDirectoryNodeGrouped::GetChildType() const
{
if (GetType() == NODE_TYPE_YEAR)
return NODE_TYPE_YEAR_ALBUM;
return NODE_TYPE_ARTIST;
}
std::string CDirectoryNodeGrouped::GetLocalizedName() const
{
CMusicDatabase db;
if (db.Open())
return db.GetItemById(GetContentType(), GetID());
return "";
}
bool CDirectoryNodeGrouped::GetContent(CFileItemList& items) const
{
CMusicDatabase musicdatabase;
if (!musicdatabase.Open())
return false;
return musicdatabase.GetItems(BuildPath(), GetContentType(), items);
}
std::string CDirectoryNodeGrouped::GetContentType() const
{
switch (GetType())
{
case NODE_TYPE_GENRE:
return "genres";
case NODE_TYPE_YEAR:
return "years";
default:
break;
}
return "";
}
| gpl-2.0 |
waleedq/samsung-kernel-latona | drivers/usb/gadget/multi.c | 82 | 8662 | /*
* multi.c -- Multifunction Composite driver
*
* Copyright (C) 2008 David Brownell
* Copyright (C) 2008 Nokia Corporation
* Copyright (C) 2009 Samsung Electronics
* Author: Michal Nazarewicz (m.nazarewicz@samsung.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/kernel.h>
#include <linux/utsname.h>
#include <linux/module.h>
#if defined USB_ETH_RNDIS
# undef USB_ETH_RNDIS
#endif
#ifdef CONFIG_USB_G_MULTI_RNDIS
# define USB_ETH_RNDIS y
#endif
#define DRIVER_DESC "Multifunction Composite Gadget"
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_AUTHOR("Michal Nazarewicz");
MODULE_LICENSE("GPL");
/***************************** All the files... *****************************/
/*
* kbuild is not very cooperative with respect to linking separately
* compiled library objects into one module. So for now we won't use
* separate compilation ... ensuring init/exit sections work to shrink
* the runtime footprint, and giving us at least some parts of what
* a "gcc --combine ... part1.c part2.c part3.c ... " build would.
*/
#include "composite.c"
#include "usbstring.c"
#include "config.c"
#include "epautoconf.c"
#include "f_mass_storage.c"
#include "u_serial.c"
#include "f_acm.c"
#include "f_ecm.c"
#include "f_subset.c"
#ifdef USB_ETH_RNDIS
# include "f_rndis.c"
# include "rndis.c"
#endif
#include "u_ether.c"
/***************************** Device Descriptor ****************************/
#define MULTI_VENDOR_NUM 0x0525 /* XXX NetChip */
#define MULTI_PRODUCT_NUM 0xa4ab /* XXX */
enum {
__MULTI_NO_CONFIG,
#ifdef CONFIG_USB_G_MULTI_RNDIS
MULTI_RNDIS_CONFIG_NUM,
#endif
#ifdef CONFIG_USB_G_MULTI_CDC
MULTI_CDC_CONFIG_NUM,
#endif
};
static struct usb_device_descriptor device_desc = {
.bLength = sizeof device_desc,
.bDescriptorType = USB_DT_DEVICE,
.bcdUSB = cpu_to_le16(0x0200),
.bDeviceClass = USB_CLASS_MISC /* 0xEF */,
.bDeviceSubClass = 2,
.bDeviceProtocol = 1,
/* Vendor and product id can be overridden by module parameters. */
.idVendor = cpu_to_le16(MULTI_VENDOR_NUM),
.idProduct = cpu_to_le16(MULTI_PRODUCT_NUM),
};
static const struct usb_descriptor_header *otg_desc[] = {
(struct usb_descriptor_header *) &(struct usb_otg_descriptor){
.bLength = sizeof(struct usb_otg_descriptor),
.bDescriptorType = USB_DT_OTG,
/*
* REVISIT SRP-only hardware is possible, although
* it would not be called "OTG" ...
*/
.bmAttributes = USB_OTG_SRP | USB_OTG_HNP,
},
NULL,
};
enum {
MULTI_STRING_MANUFACTURER_IDX,
MULTI_STRING_PRODUCT_IDX,
#ifdef CONFIG_USB_G_MULTI_RNDIS
MULTI_STRING_RNDIS_CONFIG_IDX,
#endif
#ifdef CONFIG_USB_G_MULTI_CDC
MULTI_STRING_CDC_CONFIG_IDX,
#endif
};
static char manufacturer[50];
static struct usb_string strings_dev[] = {
[MULTI_STRING_MANUFACTURER_IDX].s = manufacturer,
[MULTI_STRING_PRODUCT_IDX].s = DRIVER_DESC,
#ifdef CONFIG_USB_G_MULTI_RNDIS
[MULTI_STRING_RNDIS_CONFIG_IDX].s = "Multifunction with RNDIS",
#endif
#ifdef CONFIG_USB_G_MULTI_CDC
[MULTI_STRING_CDC_CONFIG_IDX].s = "Multifunction with CDC ECM",
#endif
{ } /* end of list */
};
static struct usb_gadget_strings *dev_strings[] = {
&(struct usb_gadget_strings){
.language = 0x0409, /* en-us */
.strings = strings_dev,
},
NULL,
};
/****************************** Configurations ******************************/
static struct fsg_module_parameters fsg_mod_data = { .stall = 1 };
FSG_MODULE_PARAMETERS(/* no prefix */, fsg_mod_data);
static struct fsg_common fsg_common;
static u8 hostaddr[ETH_ALEN];
/********** RNDIS **********/
#ifdef USB_ETH_RNDIS
static __ref int rndis_do_config(struct usb_configuration *c)
{
int ret;
if (gadget_is_otg(c->cdev->gadget)) {
c->descriptors = otg_desc;
c->bmAttributes |= USB_CONFIG_ATT_WAKEUP;
}
ret = rndis_bind_config(c, hostaddr);
if (ret < 0)
return ret;
ret = acm_bind_config(c, 0);
if (ret < 0)
return ret;
ret = fsg_bind_config(c->cdev, c, &fsg_common);
if (ret < 0)
return ret;
return 0;
}
static int rndis_config_register(struct usb_composite_dev *cdev)
{
static struct usb_configuration config = {
.bind = rndis_do_config,
.bConfigurationValue = MULTI_RNDIS_CONFIG_NUM,
.bmAttributes = USB_CONFIG_ATT_SELFPOWER,
};
config.label = strings_dev[MULTI_STRING_RNDIS_CONFIG_IDX].s;
config.iConfiguration = strings_dev[MULTI_STRING_RNDIS_CONFIG_IDX].id;
return usb_add_config(cdev, &config);
}
#else
static int rndis_config_register(struct usb_composite_dev *cdev)
{
return 0;
}
#endif
/********** CDC ECM **********/
#ifdef CONFIG_USB_G_MULTI_CDC
static __ref int cdc_do_config(struct usb_configuration *c)
{
int ret;
if (gadget_is_otg(c->cdev->gadget)) {
c->descriptors = otg_desc;
c->bmAttributes |= USB_CONFIG_ATT_WAKEUP;
}
ret = ecm_bind_config(c, hostaddr);
if (ret < 0)
return ret;
ret = acm_bind_config(c, 0);
if (ret < 0)
return ret;
ret = fsg_bind_config(c->cdev, c, &fsg_common);
if (ret < 0)
return ret;
return 0;
}
static int cdc_config_register(struct usb_composite_dev *cdev)
{
static struct usb_configuration config = {
.bind = cdc_do_config,
.bConfigurationValue = MULTI_CDC_CONFIG_NUM,
.bmAttributes = USB_CONFIG_ATT_SELFPOWER,
};
config.label = strings_dev[MULTI_STRING_CDC_CONFIG_IDX].s;
config.iConfiguration = strings_dev[MULTI_STRING_CDC_CONFIG_IDX].id;
return usb_add_config(cdev, &config);
}
#else
static int cdc_config_register(struct usb_composite_dev *cdev)
{
return 0;
}
#endif
/****************************** Gadget Bind ******************************/
static int __ref multi_bind(struct usb_composite_dev *cdev)
{
struct usb_gadget *gadget = cdev->gadget;
int status, gcnum;
if (!can_support_ecm(cdev->gadget)) {
dev_err(&gadget->dev, "controller '%s' not usable\n",
gadget->name);
return -EINVAL;
}
/* set up network link layer */
status = gether_setup(cdev->gadget, hostaddr);
if (status < 0)
return status;
/* set up serial link layer */
status = gserial_setup(cdev->gadget, 1);
if (status < 0)
goto fail0;
/* set up mass storage function */
{
void *retp;
retp = fsg_common_from_params(&fsg_common, cdev, &fsg_mod_data);
if (IS_ERR(retp)) {
status = PTR_ERR(retp);
goto fail1;
}
}
/* set bcdDevice */
gcnum = usb_gadget_controller_number(gadget);
if (gcnum >= 0) {
device_desc.bcdDevice = cpu_to_le16(0x0300 | gcnum);
} else {
WARNING(cdev, "controller '%s' not recognized\n", gadget->name);
device_desc.bcdDevice = cpu_to_le16(0x0300 | 0x0099);
}
/* allocate string descriptor numbers */
snprintf(manufacturer, sizeof manufacturer, "%s %s with %s",
init_utsname()->sysname, init_utsname()->release,
gadget->name);
status = usb_string_ids_tab(cdev, strings_dev);
if (unlikely(status < 0))
goto fail2;
device_desc.iManufacturer =
strings_dev[MULTI_STRING_MANUFACTURER_IDX].id;
device_desc.iProduct =
strings_dev[MULTI_STRING_PRODUCT_IDX].id;
/* register configurations */
status = rndis_config_register(cdev);
if (unlikely(status < 0))
goto fail2;
status = cdc_config_register(cdev);
if (unlikely(status < 0))
goto fail2;
/* we're done */
dev_info(&gadget->dev, DRIVER_DESC "\n");
fsg_common_put(&fsg_common);
return 0;
/* error recovery */
fail2:
fsg_common_put(&fsg_common);
fail1:
gserial_cleanup();
fail0:
gether_cleanup();
return status;
}
static int __exit multi_unbind(struct usb_composite_dev *cdev)
{
gserial_cleanup();
gether_cleanup();
return 0;
}
/****************************** Some noise ******************************/
static struct usb_composite_driver multi_driver = {
.name = "g_multi",
.dev = &device_desc,
.strings = dev_strings,
.bind = multi_bind,
.unbind = __exit_p(multi_unbind),
};
static int __init multi_init(void)
{
return usb_composite_register(&multi_driver);
}
module_init(multi_init);
static void __exit multi_exit(void)
{
usb_composite_unregister(&multi_driver);
}
module_exit(multi_exit);
| gpl-2.0 |
TeamSXL/htc-cm-kernel-doubleshot-34_old | drivers/mmc/host/sdhci.c | 338 | 81828 | /*
* linux/drivers/mmc/host/sdhci.c - Secure Digital Host Controller Interface driver
*
* Copyright (C) 2005-2008 Pierre Ossman, All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Thanks to the following companies for their support:
*
* - JMicron (hardware and technical support)
*/
#include <linux/delay.h>
#include <linux/highmem.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/dma-mapping.h>
#include <linux/slab.h>
#include <linux/scatterlist.h>
#include <linux/regulator/consumer.h>
#include <linux/pm_runtime.h>
#include <linux/leds.h>
#include <linux/mmc/mmc.h>
#include <linux/mmc/host.h>
#include <linux/mmc/card.h>
#include "sdhci.h"
#define DRIVER_NAME "sdhci"
#define DBG(f, x...) \
pr_debug(DRIVER_NAME " [%s()]: " f, __func__,## x)
#if defined(CONFIG_LEDS_CLASS) || (defined(CONFIG_LEDS_CLASS_MODULE) && \
defined(CONFIG_MMC_SDHCI_MODULE))
#define SDHCI_USE_LEDS_CLASS
#endif
#define MAX_TUNING_LOOP 40
static unsigned int debug_quirks = 0;
static unsigned int debug_quirks2;
static void sdhci_finish_data(struct sdhci_host *);
static void sdhci_send_command(struct sdhci_host *, struct mmc_command *);
static void sdhci_finish_command(struct sdhci_host *);
static int sdhci_execute_tuning(struct mmc_host *mmc, u32 opcode);
static void sdhci_tuning_timer(unsigned long data);
#ifdef CONFIG_PM_RUNTIME
static int sdhci_runtime_pm_get(struct sdhci_host *host);
static int sdhci_runtime_pm_put(struct sdhci_host *host);
#else
static inline int sdhci_runtime_pm_get(struct sdhci_host *host)
{
return 0;
}
static inline int sdhci_runtime_pm_put(struct sdhci_host *host)
{
return 0;
}
#endif
static void sdhci_dumpregs(struct sdhci_host *host)
{
pr_debug(DRIVER_NAME ": =========== REGISTER DUMP (%s)===========\n",
mmc_hostname(host->mmc));
pr_debug(DRIVER_NAME ": Sys addr: 0x%08x | Version: 0x%08x\n",
sdhci_readl(host, SDHCI_DMA_ADDRESS),
sdhci_readw(host, SDHCI_HOST_VERSION));
pr_debug(DRIVER_NAME ": Blk size: 0x%08x | Blk cnt: 0x%08x\n",
sdhci_readw(host, SDHCI_BLOCK_SIZE),
sdhci_readw(host, SDHCI_BLOCK_COUNT));
pr_debug(DRIVER_NAME ": Argument: 0x%08x | Trn mode: 0x%08x\n",
sdhci_readl(host, SDHCI_ARGUMENT),
sdhci_readw(host, SDHCI_TRANSFER_MODE));
pr_debug(DRIVER_NAME ": Present: 0x%08x | Host ctl: 0x%08x\n",
sdhci_readl(host, SDHCI_PRESENT_STATE),
sdhci_readb(host, SDHCI_HOST_CONTROL));
pr_debug(DRIVER_NAME ": Power: 0x%08x | Blk gap: 0x%08x\n",
sdhci_readb(host, SDHCI_POWER_CONTROL),
sdhci_readb(host, SDHCI_BLOCK_GAP_CONTROL));
pr_debug(DRIVER_NAME ": Wake-up: 0x%08x | Clock: 0x%08x\n",
sdhci_readb(host, SDHCI_WAKE_UP_CONTROL),
sdhci_readw(host, SDHCI_CLOCK_CONTROL));
pr_debug(DRIVER_NAME ": Timeout: 0x%08x | Int stat: 0x%08x\n",
sdhci_readb(host, SDHCI_TIMEOUT_CONTROL),
sdhci_readl(host, SDHCI_INT_STATUS));
pr_debug(DRIVER_NAME ": Int enab: 0x%08x | Sig enab: 0x%08x\n",
sdhci_readl(host, SDHCI_INT_ENABLE),
sdhci_readl(host, SDHCI_SIGNAL_ENABLE));
pr_debug(DRIVER_NAME ": AC12 err: 0x%08x | Slot int: 0x%08x\n",
sdhci_readw(host, SDHCI_ACMD12_ERR),
sdhci_readw(host, SDHCI_SLOT_INT_STATUS));
pr_debug(DRIVER_NAME ": Caps: 0x%08x | Caps_1: 0x%08x\n",
sdhci_readl(host, SDHCI_CAPABILITIES),
sdhci_readl(host, SDHCI_CAPABILITIES_1));
pr_debug(DRIVER_NAME ": Cmd: 0x%08x | Max curr: 0x%08x\n",
sdhci_readw(host, SDHCI_COMMAND),
sdhci_readl(host, SDHCI_MAX_CURRENT));
pr_debug(DRIVER_NAME ": Host ctl2: 0x%08x\n",
sdhci_readw(host, SDHCI_HOST_CONTROL2));
if (host->flags & SDHCI_USE_ADMA)
pr_debug(DRIVER_NAME ": ADMA Err: 0x%08x | ADMA Ptr: 0x%08x\n",
readl(host->ioaddr + SDHCI_ADMA_ERROR),
readl(host->ioaddr + SDHCI_ADMA_ADDRESS));
pr_debug(DRIVER_NAME ": ===========================================\n");
}
/*****************************************************************************\
* *
* Low level functions *
* *
\*****************************************************************************/
static void sdhci_clear_set_irqs(struct sdhci_host *host, u32 clear, u32 set)
{
u32 ier;
ier = sdhci_readl(host, SDHCI_INT_ENABLE);
ier &= ~clear;
ier |= set;
sdhci_writel(host, ier, SDHCI_INT_ENABLE);
sdhci_writel(host, ier, SDHCI_SIGNAL_ENABLE);
}
static void sdhci_unmask_irqs(struct sdhci_host *host, u32 irqs)
{
sdhci_clear_set_irqs(host, 0, irqs);
}
static void sdhci_mask_irqs(struct sdhci_host *host, u32 irqs)
{
sdhci_clear_set_irqs(host, irqs, 0);
}
static void sdhci_set_card_detection(struct sdhci_host *host, bool enable)
{
u32 present, irqs;
if ((host->quirks & SDHCI_QUIRK_BROKEN_CARD_DETECTION) ||
(host->mmc->caps & MMC_CAP_NONREMOVABLE))
return;
present = sdhci_readl(host, SDHCI_PRESENT_STATE) &
SDHCI_CARD_PRESENT;
irqs = present ? SDHCI_INT_CARD_REMOVE : SDHCI_INT_CARD_INSERT;
if (enable)
sdhci_unmask_irqs(host, irqs);
else
sdhci_mask_irqs(host, irqs);
}
static void sdhci_enable_card_detection(struct sdhci_host *host)
{
sdhci_set_card_detection(host, true);
}
static void sdhci_disable_card_detection(struct sdhci_host *host)
{
sdhci_set_card_detection(host, false);
}
static void sdhci_reset(struct sdhci_host *host, u8 mask)
{
unsigned long timeout;
u32 uninitialized_var(ier);
if (host->quirks & SDHCI_QUIRK_NO_CARD_NO_RESET) {
if (!(sdhci_readl(host, SDHCI_PRESENT_STATE) &
SDHCI_CARD_PRESENT))
return;
}
if (host->quirks & SDHCI_QUIRK_RESTORE_IRQS_AFTER_RESET)
ier = sdhci_readl(host, SDHCI_INT_ENABLE);
if (host->ops->platform_reset_enter)
host->ops->platform_reset_enter(host, mask);
sdhci_writeb(host, mask, SDHCI_SOFTWARE_RESET);
if (mask & SDHCI_RESET_ALL)
host->clock = 0;
/* Wait max 100 ms */
timeout = 100;
/* hw clears the bit when it's done */
while (sdhci_readb(host, SDHCI_SOFTWARE_RESET) & mask) {
if (timeout == 0) {
pr_err("%s: Reset 0x%x never completed.\n",
mmc_hostname(host->mmc), (int)mask);
sdhci_dumpregs(host);
return;
}
timeout--;
mdelay(1);
}
if (host->ops->platform_reset_exit)
host->ops->platform_reset_exit(host, mask);
if (host->quirks & SDHCI_QUIRK_RESTORE_IRQS_AFTER_RESET)
sdhci_clear_set_irqs(host, SDHCI_INT_ALL_MASK, ier);
if (host->flags & (SDHCI_USE_SDMA | SDHCI_USE_ADMA)) {
if ((host->ops->enable_dma) && (mask & SDHCI_RESET_ALL))
host->ops->enable_dma(host);
}
}
static void sdhci_set_ios(struct mmc_host *mmc, struct mmc_ios *ios);
static void sdhci_init(struct sdhci_host *host, int soft)
{
if (soft)
sdhci_reset(host, SDHCI_RESET_CMD|SDHCI_RESET_DATA);
else
sdhci_reset(host, SDHCI_RESET_ALL);
sdhci_clear_set_irqs(host, SDHCI_INT_ALL_MASK,
SDHCI_INT_BUS_POWER | SDHCI_INT_DATA_END_BIT |
SDHCI_INT_DATA_CRC | SDHCI_INT_DATA_TIMEOUT | SDHCI_INT_INDEX |
SDHCI_INT_END_BIT | SDHCI_INT_CRC | SDHCI_INT_TIMEOUT |
SDHCI_INT_DATA_END | SDHCI_INT_RESPONSE);
if (soft) {
/* force clock reconfiguration */
host->clock = 0;
sdhci_set_ios(host->mmc, &host->mmc->ios);
}
}
static void sdhci_reinit(struct sdhci_host *host)
{
sdhci_init(host, 0);
sdhci_enable_card_detection(host);
}
static void sdhci_activate_led(struct sdhci_host *host)
{
u8 ctrl;
ctrl = sdhci_readb(host, SDHCI_HOST_CONTROL);
ctrl |= SDHCI_CTRL_LED;
sdhci_writeb(host, ctrl, SDHCI_HOST_CONTROL);
}
static void sdhci_deactivate_led(struct sdhci_host *host)
{
u8 ctrl;
ctrl = sdhci_readb(host, SDHCI_HOST_CONTROL);
ctrl &= ~SDHCI_CTRL_LED;
sdhci_writeb(host, ctrl, SDHCI_HOST_CONTROL);
}
#ifdef SDHCI_USE_LEDS_CLASS
static void sdhci_led_control(struct led_classdev *led,
enum led_brightness brightness)
{
struct sdhci_host *host = container_of(led, struct sdhci_host, led);
unsigned long flags;
spin_lock_irqsave(&host->lock, flags);
if (host->runtime_suspended)
goto out;
if (brightness == LED_OFF)
sdhci_deactivate_led(host);
else
sdhci_activate_led(host);
out:
spin_unlock_irqrestore(&host->lock, flags);
}
#endif
/*****************************************************************************\
* *
* Core functions *
* *
\*****************************************************************************/
static void sdhci_read_block_pio(struct sdhci_host *host)
{
unsigned long flags;
size_t blksize, len, chunk;
u32 uninitialized_var(scratch);
u8 *buf;
DBG("PIO reading\n");
blksize = host->data->blksz;
chunk = 0;
local_irq_save(flags);
while (blksize) {
if (!sg_miter_next(&host->sg_miter))
BUG();
len = min(host->sg_miter.length, blksize);
blksize -= len;
host->sg_miter.consumed = len;
buf = host->sg_miter.addr;
while (len) {
if (chunk == 0) {
scratch = sdhci_readl(host, SDHCI_BUFFER);
chunk = 4;
}
*buf = scratch & 0xFF;
buf++;
scratch >>= 8;
chunk--;
len--;
}
}
sg_miter_stop(&host->sg_miter);
local_irq_restore(flags);
}
static void sdhci_write_block_pio(struct sdhci_host *host)
{
unsigned long flags;
size_t blksize, len, chunk;
u32 scratch;
u8 *buf;
DBG("PIO writing\n");
blksize = host->data->blksz;
chunk = 0;
scratch = 0;
local_irq_save(flags);
while (blksize) {
if (!sg_miter_next(&host->sg_miter))
BUG();
len = min(host->sg_miter.length, blksize);
blksize -= len;
host->sg_miter.consumed = len;
buf = host->sg_miter.addr;
while (len) {
scratch |= (u32)*buf << (chunk * 8);
buf++;
chunk++;
len--;
if ((chunk == 4) || ((len == 0) && (blksize == 0))) {
sdhci_writel(host, scratch, SDHCI_BUFFER);
chunk = 0;
scratch = 0;
}
}
}
sg_miter_stop(&host->sg_miter);
local_irq_restore(flags);
}
static void sdhci_transfer_pio(struct sdhci_host *host)
{
u32 mask;
BUG_ON(!host->data);
if (host->blocks == 0)
return;
if (host->data->flags & MMC_DATA_READ)
mask = SDHCI_DATA_AVAILABLE;
else
mask = SDHCI_SPACE_AVAILABLE;
/*
* Some controllers (JMicron JMB38x) mess up the buffer bits
* for transfers < 4 bytes. As long as it is just one block,
* we can ignore the bits.
*/
if ((host->quirks & SDHCI_QUIRK_BROKEN_SMALL_PIO) &&
(host->data->blocks == 1))
mask = ~0;
while (sdhci_readl(host, SDHCI_PRESENT_STATE) & mask) {
if (host->quirks & SDHCI_QUIRK_PIO_NEEDS_DELAY)
udelay(100);
if (host->data->flags & MMC_DATA_READ)
sdhci_read_block_pio(host);
else
sdhci_write_block_pio(host);
host->blocks--;
if (host->blocks == 0)
break;
}
DBG("PIO transfer complete.\n");
}
static char *sdhci_kmap_atomic(struct scatterlist *sg, unsigned long *flags)
{
local_irq_save(*flags);
return kmap_atomic(sg_page(sg)) + sg->offset;
}
static void sdhci_kunmap_atomic(void *buffer, unsigned long *flags)
{
kunmap_atomic(buffer);
local_irq_restore(*flags);
}
static void sdhci_set_adma_desc(u8 *desc, u32 addr, int len, unsigned cmd)
{
__le32 *dataddr = (__le32 __force *)(desc + 4);
__le16 *cmdlen = (__le16 __force *)desc;
/* SDHCI specification says ADMA descriptors should be 4 byte
* aligned, so using 16 or 32bit operations should be safe. */
cmdlen[0] = cpu_to_le16(cmd);
cmdlen[1] = cpu_to_le16(len);
dataddr[0] = cpu_to_le32(addr);
}
static int sdhci_adma_table_pre(struct sdhci_host *host,
struct mmc_data *data)
{
int direction;
u8 *desc;
u8 *align;
dma_addr_t addr;
dma_addr_t align_addr;
int len, offset;
struct scatterlist *sg;
int i;
char *buffer;
unsigned long flags;
/*
* The spec does not specify endianness of descriptor table.
* We currently guess that it is LE.
*/
if (data->flags & MMC_DATA_READ)
direction = DMA_FROM_DEVICE;
else
direction = DMA_TO_DEVICE;
/*
* The ADMA descriptor table is mapped further down as we
* need to fill it with data first.
*/
host->align_addr = dma_map_single(mmc_dev(host->mmc),
host->align_buffer, 128 * 4, direction);
if (dma_mapping_error(mmc_dev(host->mmc), host->align_addr))
goto fail;
BUG_ON(host->align_addr & 0x3);
host->sg_count = dma_map_sg(mmc_dev(host->mmc),
data->sg, data->sg_len, direction);
if (host->sg_count == 0)
goto unmap_align;
desc = host->adma_desc;
align = host->align_buffer;
align_addr = host->align_addr;
for_each_sg(data->sg, sg, host->sg_count, i) {
addr = sg_dma_address(sg);
len = sg_dma_len(sg);
/*
* The SDHCI specification states that ADMA
* addresses must be 32-bit aligned. If they
* aren't, then we use a bounce buffer for
* the (up to three) bytes that screw up the
* alignment.
*/
offset = (4 - (addr & 0x3)) & 0x3;
if (offset) {
if (data->flags & MMC_DATA_WRITE) {
buffer = sdhci_kmap_atomic(sg, &flags);
WARN_ON(((long)buffer & PAGE_MASK) > (PAGE_SIZE - 3));
memcpy(align, buffer, offset);
sdhci_kunmap_atomic(buffer, &flags);
}
/* tran, valid */
sdhci_set_adma_desc(desc, align_addr, offset, 0x21);
BUG_ON(offset > 65536);
align += 4;
align_addr += 4;
desc += 8;
addr += offset;
len -= offset;
}
BUG_ON(len > 65536);
/* tran, valid */
sdhci_set_adma_desc(desc, addr, len, 0x21);
desc += 8;
/*
* If this triggers then we have a calculation bug
* somewhere. :/
*/
WARN_ON((desc - host->adma_desc) > (128 * 2 + 1) * 4);
}
if (host->quirks & SDHCI_QUIRK_NO_ENDATTR_IN_NOPDESC) {
/*
* Mark the last descriptor as the terminating descriptor
*/
if (desc != host->adma_desc) {
desc -= 8;
desc[0] |= 0x2; /* end */
}
} else {
/*
* Add a terminating entry.
*/
/* nop, end, valid */
sdhci_set_adma_desc(desc, 0, 0, 0x3);
}
/*
* Resync align buffer as we might have changed it.
*/
if (data->flags & MMC_DATA_WRITE) {
dma_sync_single_for_device(mmc_dev(host->mmc),
host->align_addr, 128 * 4, direction);
}
host->adma_addr = dma_map_single(mmc_dev(host->mmc),
host->adma_desc, (128 * 2 + 1) * 4, DMA_TO_DEVICE);
if (dma_mapping_error(mmc_dev(host->mmc), host->adma_addr))
goto unmap_entries;
BUG_ON(host->adma_addr & 0x3);
return 0;
unmap_entries:
dma_unmap_sg(mmc_dev(host->mmc), data->sg,
data->sg_len, direction);
unmap_align:
dma_unmap_single(mmc_dev(host->mmc), host->align_addr,
128 * 4, direction);
fail:
return -EINVAL;
}
static void sdhci_adma_table_post(struct sdhci_host *host,
struct mmc_data *data)
{
int direction;
struct scatterlist *sg;
int i, size;
u8 *align;
char *buffer;
unsigned long flags;
if (data->flags & MMC_DATA_READ)
direction = DMA_FROM_DEVICE;
else
direction = DMA_TO_DEVICE;
dma_unmap_single(mmc_dev(host->mmc), host->adma_addr,
(128 * 2 + 1) * 4, DMA_TO_DEVICE);
dma_unmap_single(mmc_dev(host->mmc), host->align_addr,
128 * 4, direction);
if (data->flags & MMC_DATA_READ) {
dma_sync_sg_for_cpu(mmc_dev(host->mmc), data->sg,
data->sg_len, direction);
align = host->align_buffer;
for_each_sg(data->sg, sg, host->sg_count, i) {
if (sg_dma_address(sg) & 0x3) {
size = 4 - (sg_dma_address(sg) & 0x3);
buffer = sdhci_kmap_atomic(sg, &flags);
WARN_ON(((long)buffer & PAGE_MASK) > (PAGE_SIZE - 3));
memcpy(buffer, align, size);
sdhci_kunmap_atomic(buffer, &flags);
align += 4;
}
}
}
dma_unmap_sg(mmc_dev(host->mmc), data->sg,
data->sg_len, direction);
}
static u8 sdhci_calc_timeout(struct sdhci_host *host, struct mmc_command *cmd)
{
u8 count;
struct mmc_data *data = cmd->data;
unsigned target_timeout, current_timeout;
/*
* If the host controller provides us with an incorrect timeout
* value, just skip the check and use 0xE. The hardware may take
* longer to time out, but that's much better than having a too-short
* timeout value.
*/
if (host->quirks & SDHCI_QUIRK_BROKEN_TIMEOUT_VAL)
return 0xE;
/* Unspecified timeout, assume max */
if (!data && !cmd->cmd_timeout_ms)
return 0xE;
/* timeout in us */
if (!data)
target_timeout = cmd->cmd_timeout_ms * 1000;
else {
target_timeout = data->timeout_ns / 1000;
if (host->clock)
target_timeout += data->timeout_clks / host->clock;
}
/*
* Figure out needed cycles.
* We do this in steps in order to fit inside a 32 bit int.
* The first step is the minimum timeout, which will have a
* minimum resolution of 6 bits:
* (1) 2^13*1000 > 2^22,
* (2) host->timeout_clk < 2^16
* =>
* (1) / (2) > 2^6
*/
count = 0;
current_timeout = (1 << 13) * 1000 / host->timeout_clk;
while (current_timeout < target_timeout) {
count++;
current_timeout <<= 1;
if (count >= 0xF)
break;
}
if (count >= 0xF) {
pr_warning("%s: Too large timeout requested for CMD%d!\n",
mmc_hostname(host->mmc), cmd->opcode);
count = 0xE;
}
return count;
}
static void sdhci_set_transfer_irqs(struct sdhci_host *host)
{
u32 pio_irqs = SDHCI_INT_DATA_AVAIL | SDHCI_INT_SPACE_AVAIL;
u32 dma_irqs = SDHCI_INT_DMA_END | SDHCI_INT_ADMA_ERROR;
if (host->flags & SDHCI_REQ_USE_DMA)
sdhci_clear_set_irqs(host, pio_irqs, dma_irqs);
else
sdhci_clear_set_irqs(host, dma_irqs, pio_irqs);
}
static void sdhci_prepare_data(struct sdhci_host *host, struct mmc_command *cmd)
{
u8 count;
u8 ctrl;
struct mmc_data *data = cmd->data;
int ret;
WARN_ON(host->data);
if (data || (cmd->flags & MMC_RSP_BUSY)) {
count = sdhci_calc_timeout(host, cmd);
sdhci_writeb(host, count, SDHCI_TIMEOUT_CONTROL);
}
if (!data)
return;
/* Sanity checks */
BUG_ON(data->blksz * data->blocks > 524288);
BUG_ON(data->blksz > host->mmc->max_blk_size);
BUG_ON(data->blocks > 65535);
host->data = data;
host->data_early = 0;
host->data->bytes_xfered = 0;
if (host->flags & (SDHCI_USE_SDMA | SDHCI_USE_ADMA))
host->flags |= SDHCI_REQ_USE_DMA;
/*
* FIXME: This doesn't account for merging when mapping the
* scatterlist.
*/
if (host->flags & SDHCI_REQ_USE_DMA) {
int broken, i;
struct scatterlist *sg;
broken = 0;
if (host->flags & SDHCI_USE_ADMA) {
if (host->quirks & SDHCI_QUIRK_32BIT_ADMA_SIZE)
broken = 1;
} else {
if (host->quirks & SDHCI_QUIRK_32BIT_DMA_SIZE)
broken = 1;
}
if (unlikely(broken)) {
for_each_sg(data->sg, sg, data->sg_len, i) {
if (sg->length & 0x3) {
DBG("Reverting to PIO because of "
"transfer size (%d)\n",
sg->length);
host->flags &= ~SDHCI_REQ_USE_DMA;
break;
}
}
}
}
/*
* The assumption here being that alignment is the same after
* translation to device address space.
*/
if (host->flags & SDHCI_REQ_USE_DMA) {
int broken, i;
struct scatterlist *sg;
broken = 0;
if (host->flags & SDHCI_USE_ADMA) {
/*
* As we use 3 byte chunks to work around
* alignment problems, we need to check this
* quirk.
*/
if (host->quirks & SDHCI_QUIRK_32BIT_ADMA_SIZE)
broken = 1;
} else {
if (host->quirks & SDHCI_QUIRK_32BIT_DMA_ADDR)
broken = 1;
}
if (unlikely(broken)) {
for_each_sg(data->sg, sg, data->sg_len, i) {
if (sg->offset & 0x3) {
DBG("Reverting to PIO because of "
"bad alignment\n");
host->flags &= ~SDHCI_REQ_USE_DMA;
break;
}
}
}
}
if (host->flags & SDHCI_REQ_USE_DMA) {
if (host->flags & SDHCI_USE_ADMA) {
ret = sdhci_adma_table_pre(host, data);
if (ret) {
/*
* This only happens when someone fed
* us an invalid request.
*/
WARN_ON(1);
host->flags &= ~SDHCI_REQ_USE_DMA;
} else {
sdhci_writel(host, host->adma_addr,
SDHCI_ADMA_ADDRESS);
}
} else {
int sg_cnt;
sg_cnt = dma_map_sg(mmc_dev(host->mmc),
data->sg, data->sg_len,
(data->flags & MMC_DATA_READ) ?
DMA_FROM_DEVICE :
DMA_TO_DEVICE);
if (sg_cnt == 0) {
/*
* This only happens when someone fed
* us an invalid request.
*/
WARN_ON(1);
host->flags &= ~SDHCI_REQ_USE_DMA;
} else {
WARN_ON(sg_cnt != 1);
sdhci_writel(host, sg_dma_address(data->sg),
SDHCI_DMA_ADDRESS);
}
}
}
/*
* Always adjust the DMA selection as some controllers
* (e.g. JMicron) can't do PIO properly when the selection
* is ADMA.
*/
if (host->version >= SDHCI_SPEC_200) {
ctrl = sdhci_readb(host, SDHCI_HOST_CONTROL);
ctrl &= ~SDHCI_CTRL_DMA_MASK;
if ((host->flags & SDHCI_REQ_USE_DMA) &&
(host->flags & SDHCI_USE_ADMA))
ctrl |= SDHCI_CTRL_ADMA32;
else
ctrl |= SDHCI_CTRL_SDMA;
sdhci_writeb(host, ctrl, SDHCI_HOST_CONTROL);
}
if (!(host->flags & SDHCI_REQ_USE_DMA)) {
int flags;
flags = SG_MITER_ATOMIC;
if (host->data->flags & MMC_DATA_READ)
flags |= SG_MITER_TO_SG;
else
flags |= SG_MITER_FROM_SG;
sg_miter_start(&host->sg_miter, data->sg, data->sg_len, flags);
host->blocks = data->blocks;
}
sdhci_set_transfer_irqs(host);
/* Set the DMA boundary value and block size */
sdhci_writew(host, SDHCI_MAKE_BLKSZ(SDHCI_DEFAULT_BOUNDARY_ARG,
data->blksz), SDHCI_BLOCK_SIZE);
sdhci_writew(host, data->blocks, SDHCI_BLOCK_COUNT);
}
static void sdhci_set_transfer_mode(struct sdhci_host *host,
struct mmc_command *cmd)
{
u16 mode;
struct mmc_data *data = cmd->data;
if (data == NULL)
return;
WARN_ON(!host->data);
mode = SDHCI_TRNS_BLK_CNT_EN;
if (mmc_op_multi(cmd->opcode) || data->blocks > 1) {
mode |= SDHCI_TRNS_MULTI;
/*
* If we are sending CMD23, CMD12 never gets sent
* on successful completion (so no Auto-CMD12).
*/
if (!host->mrq->sbc && (host->flags & SDHCI_AUTO_CMD12))
mode |= SDHCI_TRNS_AUTO_CMD12;
else if (host->mrq->sbc && (host->flags & SDHCI_AUTO_CMD23)) {
mode |= SDHCI_TRNS_AUTO_CMD23;
sdhci_writel(host, host->mrq->sbc->arg, SDHCI_ARGUMENT2);
}
}
if (data->flags & MMC_DATA_READ)
mode |= SDHCI_TRNS_READ;
if (host->flags & SDHCI_REQ_USE_DMA)
mode |= SDHCI_TRNS_DMA;
sdhci_writew(host, mode, SDHCI_TRANSFER_MODE);
}
static void sdhci_finish_data(struct sdhci_host *host)
{
struct mmc_data *data;
BUG_ON(!host->data);
data = host->data;
host->data = NULL;
if (host->flags & SDHCI_REQ_USE_DMA) {
if (host->flags & SDHCI_USE_ADMA)
sdhci_adma_table_post(host, data);
else {
dma_unmap_sg(mmc_dev(host->mmc), data->sg,
data->sg_len, (data->flags & MMC_DATA_READ) ?
DMA_FROM_DEVICE : DMA_TO_DEVICE);
}
}
/*
* The specification states that the block count register must
* be updated, but it does not specify at what point in the
* data flow. That makes the register entirely useless to read
* back so we have to assume that nothing made it to the card
* in the event of an error.
*/
if (data->error)
data->bytes_xfered = 0;
else
data->bytes_xfered = data->blksz * data->blocks;
/*
* Need to send CMD12 if -
* a) open-ended multiblock transfer (no CMD23)
* b) error in multiblock transfer
*/
if (data->stop &&
(data->error ||
!host->mrq->sbc)) {
/*
* The controller needs a reset of internal state machines
* upon error conditions.
*/
if (data->error) {
sdhci_reset(host, SDHCI_RESET_CMD);
sdhci_reset(host, SDHCI_RESET_DATA);
}
sdhci_send_command(host, data->stop);
} else
tasklet_schedule(&host->finish_tasklet);
}
static void sdhci_send_command(struct sdhci_host *host, struct mmc_command *cmd)
{
int flags;
u32 mask;
unsigned long timeout;
WARN_ON(host->cmd);
/* Wait max 10 ms */
timeout = 10;
mask = SDHCI_CMD_INHIBIT;
if ((cmd->data != NULL) || (cmd->flags & MMC_RSP_BUSY))
mask |= SDHCI_DATA_INHIBIT;
/* We shouldn't wait for data inihibit for stop commands, even
though they might use busy signaling */
if (host->mrq->data && (cmd == host->mrq->data->stop))
mask &= ~SDHCI_DATA_INHIBIT;
while (sdhci_readl(host, SDHCI_PRESENT_STATE) & mask) {
if (timeout == 0) {
pr_err("%s: Controller never released "
"inhibit bit(s).\n", mmc_hostname(host->mmc));
sdhci_dumpregs(host);
cmd->error = -EIO;
tasklet_schedule(&host->finish_tasklet);
return;
}
timeout--;
mdelay(1);
}
mod_timer(&host->timer, jiffies + 10 * HZ);
host->cmd = cmd;
sdhci_prepare_data(host, cmd);
sdhci_writel(host, cmd->arg, SDHCI_ARGUMENT);
sdhci_set_transfer_mode(host, cmd);
if ((cmd->flags & MMC_RSP_136) && (cmd->flags & MMC_RSP_BUSY)) {
pr_err("%s: Unsupported response type!\n",
mmc_hostname(host->mmc));
cmd->error = -EINVAL;
tasklet_schedule(&host->finish_tasklet);
return;
}
if (!(cmd->flags & MMC_RSP_PRESENT))
flags = SDHCI_CMD_RESP_NONE;
else if (cmd->flags & MMC_RSP_136)
flags = SDHCI_CMD_RESP_LONG;
else if (cmd->flags & MMC_RSP_BUSY)
flags = SDHCI_CMD_RESP_SHORT_BUSY;
else
flags = SDHCI_CMD_RESP_SHORT;
if (cmd->flags & MMC_RSP_CRC)
flags |= SDHCI_CMD_CRC;
if (cmd->flags & MMC_RSP_OPCODE)
flags |= SDHCI_CMD_INDEX;
/* CMD19 is special in that the Data Present Select should be set */
if (cmd->data || cmd->opcode == MMC_SEND_TUNING_BLOCK ||
cmd->opcode == MMC_SEND_TUNING_BLOCK_HS200)
flags |= SDHCI_CMD_DATA;
sdhci_writew(host, SDHCI_MAKE_CMD(cmd->opcode, flags), SDHCI_COMMAND);
}
static void sdhci_finish_command(struct sdhci_host *host)
{
int i;
BUG_ON(host->cmd == NULL);
if (host->cmd->flags & MMC_RSP_PRESENT) {
if (host->cmd->flags & MMC_RSP_136) {
/* CRC is stripped so we need to do some shifting. */
for (i = 0;i < 4;i++) {
host->cmd->resp[i] = sdhci_readl(host,
SDHCI_RESPONSE + (3-i)*4) << 8;
if (i != 3)
host->cmd->resp[i] |=
sdhci_readb(host,
SDHCI_RESPONSE + (3-i)*4-1);
}
} else {
host->cmd->resp[0] = sdhci_readl(host, SDHCI_RESPONSE);
}
}
host->cmd->error = 0;
/* Finished CMD23, now send actual command. */
if (host->cmd == host->mrq->sbc) {
host->cmd = NULL;
sdhci_send_command(host, host->mrq->cmd);
} else {
/* Processed actual command. */
if (host->data && host->data_early)
sdhci_finish_data(host);
if (!host->cmd->data)
tasklet_schedule(&host->finish_tasklet);
host->cmd = NULL;
}
}
static void sdhci_set_clock(struct sdhci_host *host, unsigned int clock)
{
int div = 0; /* Initialized for compiler warning */
int real_div = div, clk_mul = 1;
u16 clk = 0;
unsigned long timeout;
if (clock && clock == host->clock)
return;
host->mmc->actual_clock = 0;
if (host->ops->set_clock) {
host->ops->set_clock(host, clock);
if (host->quirks & SDHCI_QUIRK_NONSTANDARD_CLOCK)
return;
}
sdhci_writew(host, 0, SDHCI_CLOCK_CONTROL);
if (clock == 0)
goto out;
if (host->version >= SDHCI_SPEC_300) {
/*
* Check if the Host Controller supports Programmable Clock
* Mode.
*/
if (host->clk_mul) {
u16 ctrl;
/*
* We need to figure out whether the Host Driver needs
* to select Programmable Clock Mode, or the value can
* be set automatically by the Host Controller based on
* the Preset Value registers.
*/
ctrl = sdhci_readw(host, SDHCI_HOST_CONTROL2);
if (!(ctrl & SDHCI_CTRL_PRESET_VAL_ENABLE)) {
for (div = 1; div <= 1024; div++) {
if (((host->max_clk * host->clk_mul) /
div) <= clock)
break;
}
/*
* Set Programmable Clock Mode in the Clock
* Control register.
*/
clk = SDHCI_PROG_CLOCK_MODE;
real_div = div;
clk_mul = host->clk_mul;
div--;
}
} else {
/* Version 3.00 divisors must be a multiple of 2. */
if (host->max_clk <= clock)
div = 1;
else {
for (div = 2; div < SDHCI_MAX_DIV_SPEC_300;
div += 2) {
if ((host->max_clk / div) <= clock)
break;
}
}
real_div = div;
div >>= 1;
}
} else {
/* Version 2.00 divisors must be a power of 2. */
for (div = 1; div < SDHCI_MAX_DIV_SPEC_200; div *= 2) {
if ((host->max_clk / div) <= clock)
break;
}
real_div = div;
div >>= 1;
}
if (real_div)
host->mmc->actual_clock = (host->max_clk * clk_mul) / real_div;
clk |= (div & SDHCI_DIV_MASK) << SDHCI_DIVIDER_SHIFT;
clk |= ((div & SDHCI_DIV_HI_MASK) >> SDHCI_DIV_MASK_LEN)
<< SDHCI_DIVIDER_HI_SHIFT;
clk |= SDHCI_CLOCK_INT_EN;
sdhci_writew(host, clk, SDHCI_CLOCK_CONTROL);
/* Wait max 20 ms */
timeout = 20;
while (!((clk = sdhci_readw(host, SDHCI_CLOCK_CONTROL))
& SDHCI_CLOCK_INT_STABLE)) {
if (timeout == 0) {
pr_err("%s: Internal clock never "
"stabilised.\n", mmc_hostname(host->mmc));
sdhci_dumpregs(host);
return;
}
timeout--;
mdelay(1);
}
clk |= SDHCI_CLOCK_CARD_EN;
sdhci_writew(host, clk, SDHCI_CLOCK_CONTROL);
out:
host->clock = clock;
}
static int sdhci_set_power(struct sdhci_host *host, unsigned short power)
{
u8 pwr = 0;
if (power != (unsigned short)-1) {
switch (1 << power) {
case MMC_VDD_165_195:
pwr = SDHCI_POWER_180;
break;
case MMC_VDD_29_30:
case MMC_VDD_30_31:
pwr = SDHCI_POWER_300;
break;
case MMC_VDD_32_33:
case MMC_VDD_33_34:
pwr = SDHCI_POWER_330;
break;
default:
BUG();
}
}
if (host->pwr == pwr)
return -1;
host->pwr = pwr;
if (pwr == 0) {
sdhci_writeb(host, 0, SDHCI_POWER_CONTROL);
return 0;
}
/*
* Spec says that we should clear the power reg before setting
* a new value. Some controllers don't seem to like this though.
*/
if (!(host->quirks & SDHCI_QUIRK_SINGLE_POWER_WRITE))
sdhci_writeb(host, 0, SDHCI_POWER_CONTROL);
/*
* At least the Marvell CaFe chip gets confused if we set the voltage
* and set turn on power at the same time, so set the voltage first.
*/
if (host->quirks & SDHCI_QUIRK_NO_SIMULT_VDD_AND_POWER)
sdhci_writeb(host, pwr, SDHCI_POWER_CONTROL);
pwr |= SDHCI_POWER_ON;
sdhci_writeb(host, pwr, SDHCI_POWER_CONTROL);
/*
* Some controllers need an extra 10ms delay of 10ms before they
* can apply clock after applying power
*/
if (host->quirks & SDHCI_QUIRK_DELAY_AFTER_POWER)
mdelay(10);
return power;
}
/*****************************************************************************\
* *
* MMC callbacks *
* *
\*****************************************************************************/
static void sdhci_request(struct mmc_host *mmc, struct mmc_request *mrq)
{
struct sdhci_host *host;
bool present;
unsigned long flags;
u32 tuning_opcode;
host = mmc_priv(mmc);
sdhci_runtime_pm_get(host);
spin_lock_irqsave(&host->lock, flags);
WARN_ON(host->mrq != NULL);
#ifndef SDHCI_USE_LEDS_CLASS
sdhci_activate_led(host);
#endif
/*
* Ensure we don't send the STOP for non-SET_BLOCK_COUNTED
* requests if Auto-CMD12 is enabled.
*/
if (!mrq->sbc && (host->flags & SDHCI_AUTO_CMD12)) {
if (mrq->stop) {
mrq->data->stop = NULL;
mrq->stop = NULL;
}
}
host->mrq = mrq;
/* If polling, assume that the card is always present. */
if (host->quirks & SDHCI_QUIRK_BROKEN_CARD_DETECTION)
present = true;
else
present = sdhci_readl(host, SDHCI_PRESENT_STATE) &
SDHCI_CARD_PRESENT;
if (!present || host->flags & SDHCI_DEVICE_DEAD) {
host->mrq->cmd->error = -ENOMEDIUM;
tasklet_schedule(&host->finish_tasklet);
} else {
u32 present_state;
present_state = sdhci_readl(host, SDHCI_PRESENT_STATE);
/*
* Check if the re-tuning timer has already expired and there
* is no on-going data transfer. If so, we need to execute
* tuning procedure before sending command.
*/
if ((host->flags & SDHCI_NEEDS_RETUNING) &&
!(present_state & (SDHCI_DOING_WRITE | SDHCI_DOING_READ))) {
/* eMMC uses cmd21 while sd and sdio use cmd19 */
tuning_opcode = mmc->card->type == MMC_TYPE_MMC ?
MMC_SEND_TUNING_BLOCK_HS200 :
MMC_SEND_TUNING_BLOCK;
spin_unlock_irqrestore(&host->lock, flags);
sdhci_execute_tuning(mmc, tuning_opcode);
spin_lock_irqsave(&host->lock, flags);
/* Restore original mmc_request structure */
host->mrq = mrq;
}
if (mrq->sbc && !(host->flags & SDHCI_AUTO_CMD23))
sdhci_send_command(host, mrq->sbc);
else
sdhci_send_command(host, mrq->cmd);
}
mmiowb();
spin_unlock_irqrestore(&host->lock, flags);
}
static void sdhci_do_set_ios(struct sdhci_host *host, struct mmc_ios *ios)
{
unsigned long flags;
int vdd_bit = -1;
u8 ctrl;
spin_lock_irqsave(&host->lock, flags);
if (host->flags & SDHCI_DEVICE_DEAD) {
spin_unlock_irqrestore(&host->lock, flags);
if (host->vmmc && ios->power_mode == MMC_POWER_OFF)
mmc_regulator_set_ocr(host->mmc, host->vmmc, 0);
return;
}
/*
* Reset the chip on each power off.
* Should clear out any weird states.
*/
if (ios->power_mode == MMC_POWER_OFF) {
sdhci_writel(host, 0, SDHCI_SIGNAL_ENABLE);
sdhci_reinit(host);
}
sdhci_set_clock(host, ios->clock);
if (ios->power_mode == MMC_POWER_OFF)
vdd_bit = sdhci_set_power(host, -1);
else
vdd_bit = sdhci_set_power(host, ios->vdd);
if (host->vmmc && vdd_bit != -1) {
spin_unlock_irqrestore(&host->lock, flags);
mmc_regulator_set_ocr(host->mmc, host->vmmc, vdd_bit);
spin_lock_irqsave(&host->lock, flags);
}
if (host->ops->platform_send_init_74_clocks)
host->ops->platform_send_init_74_clocks(host, ios->power_mode);
/*
* If your platform has 8-bit width support but is not a v3 controller,
* or if it requires special setup code, you should implement that in
* platform_8bit_width().
*/
if (host->ops->platform_8bit_width)
host->ops->platform_8bit_width(host, ios->bus_width);
else {
ctrl = sdhci_readb(host, SDHCI_HOST_CONTROL);
if (ios->bus_width == MMC_BUS_WIDTH_8) {
ctrl &= ~SDHCI_CTRL_4BITBUS;
if (host->version >= SDHCI_SPEC_300)
ctrl |= SDHCI_CTRL_8BITBUS;
} else {
if (host->version >= SDHCI_SPEC_300)
ctrl &= ~SDHCI_CTRL_8BITBUS;
if (ios->bus_width == MMC_BUS_WIDTH_4)
ctrl |= SDHCI_CTRL_4BITBUS;
else
ctrl &= ~SDHCI_CTRL_4BITBUS;
}
sdhci_writeb(host, ctrl, SDHCI_HOST_CONTROL);
}
ctrl = sdhci_readb(host, SDHCI_HOST_CONTROL);
if ((ios->timing == MMC_TIMING_SD_HS ||
ios->timing == MMC_TIMING_MMC_HS)
&& !(host->quirks & SDHCI_QUIRK_NO_HISPD_BIT))
ctrl |= SDHCI_CTRL_HISPD;
else
ctrl &= ~SDHCI_CTRL_HISPD;
if (host->version >= SDHCI_SPEC_300) {
u16 clk, ctrl_2;
unsigned int clock;
/* In case of UHS-I modes, set High Speed Enable */
if ((ios->timing == MMC_TIMING_MMC_HS200) ||
(ios->timing == MMC_TIMING_UHS_SDR50) ||
(ios->timing == MMC_TIMING_UHS_SDR104) ||
(ios->timing == MMC_TIMING_UHS_DDR50) ||
(ios->timing == MMC_TIMING_UHS_SDR25))
ctrl |= SDHCI_CTRL_HISPD;
ctrl_2 = sdhci_readw(host, SDHCI_HOST_CONTROL2);
if (!(ctrl_2 & SDHCI_CTRL_PRESET_VAL_ENABLE)) {
sdhci_writeb(host, ctrl, SDHCI_HOST_CONTROL);
/*
* We only need to set Driver Strength if the
* preset value enable is not set.
*/
ctrl_2 &= ~SDHCI_CTRL_DRV_TYPE_MASK;
if (ios->drv_type == MMC_SET_DRIVER_TYPE_A)
ctrl_2 |= SDHCI_CTRL_DRV_TYPE_A;
else if (ios->drv_type == MMC_SET_DRIVER_TYPE_C)
ctrl_2 |= SDHCI_CTRL_DRV_TYPE_C;
sdhci_writew(host, ctrl_2, SDHCI_HOST_CONTROL2);
} else {
/*
* According to SDHC Spec v3.00, if the Preset Value
* Enable in the Host Control 2 register is set, we
* need to reset SD Clock Enable before changing High
* Speed Enable to avoid generating clock gliches.
*/
/* Reset SD Clock Enable */
clk = sdhci_readw(host, SDHCI_CLOCK_CONTROL);
clk &= ~SDHCI_CLOCK_CARD_EN;
sdhci_writew(host, clk, SDHCI_CLOCK_CONTROL);
sdhci_writeb(host, ctrl, SDHCI_HOST_CONTROL);
/* Re-enable SD Clock */
clock = host->clock;
host->clock = 0;
sdhci_set_clock(host, clock);
}
/* Reset SD Clock Enable */
clk = sdhci_readw(host, SDHCI_CLOCK_CONTROL);
clk &= ~SDHCI_CLOCK_CARD_EN;
sdhci_writew(host, clk, SDHCI_CLOCK_CONTROL);
if (host->ops->set_uhs_signaling)
host->ops->set_uhs_signaling(host, ios->timing);
else {
ctrl_2 = sdhci_readw(host, SDHCI_HOST_CONTROL2);
/* Select Bus Speed Mode for host */
ctrl_2 &= ~SDHCI_CTRL_UHS_MASK;
if (ios->timing == MMC_TIMING_MMC_HS200)
ctrl_2 |= SDHCI_CTRL_HS_SDR200;
else if (ios->timing == MMC_TIMING_UHS_SDR12)
ctrl_2 |= SDHCI_CTRL_UHS_SDR12;
else if (ios->timing == MMC_TIMING_UHS_SDR25)
ctrl_2 |= SDHCI_CTRL_UHS_SDR25;
else if (ios->timing == MMC_TIMING_UHS_SDR50)
ctrl_2 |= SDHCI_CTRL_UHS_SDR50;
else if (ios->timing == MMC_TIMING_UHS_SDR104)
ctrl_2 |= SDHCI_CTRL_UHS_SDR104;
else if (ios->timing == MMC_TIMING_UHS_DDR50)
ctrl_2 |= SDHCI_CTRL_UHS_DDR50;
sdhci_writew(host, ctrl_2, SDHCI_HOST_CONTROL2);
}
/* Re-enable SD Clock */
clock = host->clock;
host->clock = 0;
sdhci_set_clock(host, clock);
} else
sdhci_writeb(host, ctrl, SDHCI_HOST_CONTROL);
/*
* Some (ENE) controllers go apeshit on some ios operation,
* signalling timeout and CRC errors even on CMD0. Resetting
* it on each ios seems to solve the problem.
*/
if(host->quirks & SDHCI_QUIRK_RESET_CMD_DATA_ON_IOS)
sdhci_reset(host, SDHCI_RESET_CMD | SDHCI_RESET_DATA);
mmiowb();
spin_unlock_irqrestore(&host->lock, flags);
}
static void sdhci_set_ios(struct mmc_host *mmc, struct mmc_ios *ios)
{
struct sdhci_host *host = mmc_priv(mmc);
sdhci_runtime_pm_get(host);
sdhci_do_set_ios(host, ios);
sdhci_runtime_pm_put(host);
}
static int sdhci_check_ro(struct sdhci_host *host)
{
unsigned long flags;
int is_readonly;
spin_lock_irqsave(&host->lock, flags);
if (host->flags & SDHCI_DEVICE_DEAD)
is_readonly = 0;
else if (host->ops->get_ro)
is_readonly = host->ops->get_ro(host);
else
is_readonly = !(sdhci_readl(host, SDHCI_PRESENT_STATE)
& SDHCI_WRITE_PROTECT);
spin_unlock_irqrestore(&host->lock, flags);
/* This quirk needs to be replaced by a callback-function later */
return host->quirks & SDHCI_QUIRK_INVERTED_WRITE_PROTECT ?
!is_readonly : is_readonly;
}
#define SAMPLE_COUNT 5
static int sdhci_do_get_ro(struct sdhci_host *host)
{
int i, ro_count;
if (!(host->quirks & SDHCI_QUIRK_UNSTABLE_RO_DETECT))
return sdhci_check_ro(host);
ro_count = 0;
for (i = 0; i < SAMPLE_COUNT; i++) {
if (sdhci_check_ro(host)) {
if (++ro_count > SAMPLE_COUNT / 2)
return 1;
}
msleep(30);
}
return 0;
}
static void sdhci_hw_reset(struct mmc_host *mmc)
{
struct sdhci_host *host = mmc_priv(mmc);
if (host->ops && host->ops->hw_reset)
host->ops->hw_reset(host);
}
static int sdhci_get_ro(struct mmc_host *mmc)
{
struct sdhci_host *host = mmc_priv(mmc);
int ret;
sdhci_runtime_pm_get(host);
ret = sdhci_do_get_ro(host);
sdhci_runtime_pm_put(host);
return ret;
}
static void sdhci_enable_sdio_irq_nolock(struct sdhci_host *host, int enable)
{
if (host->flags & SDHCI_DEVICE_DEAD)
goto out;
if (enable)
host->flags |= SDHCI_SDIO_IRQ_ENABLED;
else
host->flags &= ~SDHCI_SDIO_IRQ_ENABLED;
/* SDIO IRQ will be enabled as appropriate in runtime resume */
if (host->runtime_suspended)
goto out;
if (enable)
sdhci_unmask_irqs(host, SDHCI_INT_CARD_INT);
else
sdhci_mask_irqs(host, SDHCI_INT_CARD_INT);
out:
mmiowb();
}
static void sdhci_enable_sdio_irq(struct mmc_host *mmc, int enable)
{
struct sdhci_host *host = mmc_priv(mmc);
unsigned long flags;
spin_lock_irqsave(&host->lock, flags);
sdhci_enable_sdio_irq_nolock(host, enable);
spin_unlock_irqrestore(&host->lock, flags);
}
static int sdhci_do_start_signal_voltage_switch(struct sdhci_host *host,
struct mmc_ios *ios)
{
u8 pwr;
u16 clk, ctrl;
u32 present_state;
/*
* Signal Voltage Switching is only applicable for Host Controllers
* v3.00 and above.
*/
if (host->version < SDHCI_SPEC_300)
return 0;
/*
* We first check whether the request is to set signalling voltage
* to 3.3V. If so, we change the voltage to 3.3V and return quickly.
*/
ctrl = sdhci_readw(host, SDHCI_HOST_CONTROL2);
if (ios->signal_voltage == MMC_SIGNAL_VOLTAGE_330) {
/* Set 1.8V Signal Enable in the Host Control2 register to 0 */
ctrl &= ~SDHCI_CTRL_VDD_180;
sdhci_writew(host, ctrl, SDHCI_HOST_CONTROL2);
/* Wait for 5ms */
usleep_range(5000, 5500);
/* 3.3V regulator output should be stable within 5 ms */
ctrl = sdhci_readw(host, SDHCI_HOST_CONTROL2);
if (!(ctrl & SDHCI_CTRL_VDD_180))
return 0;
else {
pr_info(DRIVER_NAME ": Switching to 3.3V "
"signalling voltage failed\n");
return -EIO;
}
} else if (!(ctrl & SDHCI_CTRL_VDD_180) &&
(ios->signal_voltage == MMC_SIGNAL_VOLTAGE_180)) {
/* Stop SDCLK */
clk = sdhci_readw(host, SDHCI_CLOCK_CONTROL);
clk &= ~SDHCI_CLOCK_CARD_EN;
sdhci_writew(host, clk, SDHCI_CLOCK_CONTROL);
/* Check whether DAT[3:0] is 0000 */
present_state = sdhci_readl(host, SDHCI_PRESENT_STATE);
if (!((present_state & SDHCI_DATA_LVL_MASK) >>
SDHCI_DATA_LVL_SHIFT)) {
/*
* Enable 1.8V Signal Enable in the Host Control2
* register
*/
ctrl |= SDHCI_CTRL_VDD_180;
sdhci_writew(host, ctrl, SDHCI_HOST_CONTROL2);
/* Wait for 5ms */
usleep_range(5000, 5500);
ctrl = sdhci_readw(host, SDHCI_HOST_CONTROL2);
if (ctrl & SDHCI_CTRL_VDD_180) {
/* Provide SDCLK again and wait for 1ms*/
clk = sdhci_readw(host, SDHCI_CLOCK_CONTROL);
clk |= SDHCI_CLOCK_CARD_EN;
sdhci_writew(host, clk, SDHCI_CLOCK_CONTROL);
usleep_range(1000, 1500);
/*
* If DAT[3:0] level is 1111b, then the card
* was successfully switched to 1.8V signaling.
*/
present_state = sdhci_readl(host,
SDHCI_PRESENT_STATE);
if ((present_state & SDHCI_DATA_LVL_MASK) ==
SDHCI_DATA_LVL_MASK)
return 0;
}
}
/*
* If we are here, that means the switch to 1.8V signaling
* failed. We power cycle the card, and retry initialization
* sequence by setting S18R to 0.
*/
pwr = sdhci_readb(host, SDHCI_POWER_CONTROL);
pwr &= ~SDHCI_POWER_ON;
sdhci_writeb(host, pwr, SDHCI_POWER_CONTROL);
/* Wait for 1ms as per the spec */
usleep_range(1000, 1500);
pwr |= SDHCI_POWER_ON;
sdhci_writeb(host, pwr, SDHCI_POWER_CONTROL);
pr_info(DRIVER_NAME ": Switching to 1.8V signalling "
"voltage failed, retrying with S18R set to 0\n");
return -EAGAIN;
} else
/* No signal voltage switch required */
return 0;
}
static int sdhci_start_signal_voltage_switch(struct mmc_host *mmc,
struct mmc_ios *ios)
{
struct sdhci_host *host = mmc_priv(mmc);
int err;
if (host->version < SDHCI_SPEC_300)
return 0;
sdhci_runtime_pm_get(host);
err = sdhci_do_start_signal_voltage_switch(host, ios);
sdhci_runtime_pm_put(host);
return err;
}
static int sdhci_execute_tuning(struct mmc_host *mmc, u32 opcode)
{
struct sdhci_host *host;
u16 ctrl;
u32 ier;
int tuning_loop_counter = MAX_TUNING_LOOP;
unsigned long timeout;
int err = 0;
bool requires_tuning_nonuhs = false;
host = mmc_priv(mmc);
sdhci_runtime_pm_get(host);
disable_irq(host->irq);
spin_lock(&host->lock);
ctrl = sdhci_readw(host, SDHCI_HOST_CONTROL2);
/*
* The Host Controller needs tuning only in case of SDR104 mode
* and for SDR50 mode when Use Tuning for SDR50 is set in the
* Capabilities register.
* If the Host Controller supports the HS200 mode then the
* tuning function has to be executed.
*/
if (((ctrl & SDHCI_CTRL_UHS_MASK) == SDHCI_CTRL_UHS_SDR50) &&
(host->flags & SDHCI_SDR50_NEEDS_TUNING ||
host->flags & SDHCI_HS200_NEEDS_TUNING))
requires_tuning_nonuhs = true;
if (((ctrl & SDHCI_CTRL_UHS_MASK) == SDHCI_CTRL_UHS_SDR104) ||
requires_tuning_nonuhs)
ctrl |= SDHCI_CTRL_EXEC_TUNING;
else {
spin_unlock(&host->lock);
enable_irq(host->irq);
sdhci_runtime_pm_put(host);
return 0;
}
sdhci_writew(host, ctrl, SDHCI_HOST_CONTROL2);
/*
* As per the Host Controller spec v3.00, tuning command
* generates Buffer Read Ready interrupt, so enable that.
*
* Note: The spec clearly says that when tuning sequence
* is being performed, the controller does not generate
* interrupts other than Buffer Read Ready interrupt. But
* to make sure we don't hit a controller bug, we _only_
* enable Buffer Read Ready interrupt here.
*/
ier = sdhci_readl(host, SDHCI_INT_ENABLE);
sdhci_clear_set_irqs(host, ier, SDHCI_INT_DATA_AVAIL);
/*
* Issue CMD19 repeatedly till Execute Tuning is set to 0 or the number
* of loops reaches 40 times or a timeout of 150ms occurs.
*/
timeout = 150;
do {
struct mmc_command cmd = {0};
struct mmc_request mrq = {NULL};
if (!tuning_loop_counter && !timeout)
break;
cmd.opcode = opcode;
cmd.arg = 0;
cmd.flags = MMC_RSP_R1 | MMC_CMD_ADTC;
cmd.retries = 0;
cmd.data = NULL;
cmd.error = 0;
mrq.cmd = &cmd;
host->mrq = &mrq;
/*
* In response to CMD19, the card sends 64 bytes of tuning
* block to the Host Controller. So we set the block size
* to 64 here.
*/
if (cmd.opcode == MMC_SEND_TUNING_BLOCK_HS200) {
if (mmc->ios.bus_width == MMC_BUS_WIDTH_8)
sdhci_writew(host, SDHCI_MAKE_BLKSZ(7, 128),
SDHCI_BLOCK_SIZE);
else if (mmc->ios.bus_width == MMC_BUS_WIDTH_4)
sdhci_writew(host, SDHCI_MAKE_BLKSZ(7, 64),
SDHCI_BLOCK_SIZE);
} else {
sdhci_writew(host, SDHCI_MAKE_BLKSZ(7, 64),
SDHCI_BLOCK_SIZE);
}
/*
* The tuning block is sent by the card to the host controller.
* So we set the TRNS_READ bit in the Transfer Mode register.
* This also takes care of setting DMA Enable and Multi Block
* Select in the same register to 0.
*/
sdhci_writew(host, SDHCI_TRNS_READ, SDHCI_TRANSFER_MODE);
sdhci_send_command(host, &cmd);
host->cmd = NULL;
host->mrq = NULL;
spin_unlock(&host->lock);
enable_irq(host->irq);
/* Wait for Buffer Read Ready interrupt */
wait_event_interruptible_timeout(host->buf_ready_int,
(host->tuning_done == 1),
msecs_to_jiffies(50));
disable_irq(host->irq);
spin_lock(&host->lock);
if (!host->tuning_done) {
pr_info(DRIVER_NAME ": Timeout waiting for "
"Buffer Read Ready interrupt during tuning "
"procedure, falling back to fixed sampling "
"clock\n");
ctrl = sdhci_readw(host, SDHCI_HOST_CONTROL2);
ctrl &= ~SDHCI_CTRL_TUNED_CLK;
ctrl &= ~SDHCI_CTRL_EXEC_TUNING;
sdhci_writew(host, ctrl, SDHCI_HOST_CONTROL2);
err = -EIO;
goto out;
}
host->tuning_done = 0;
ctrl = sdhci_readw(host, SDHCI_HOST_CONTROL2);
tuning_loop_counter--;
timeout--;
mdelay(1);
} while (ctrl & SDHCI_CTRL_EXEC_TUNING);
/*
* The Host Driver has exhausted the maximum number of loops allowed,
* so use fixed sampling frequency.
*/
if (!tuning_loop_counter || !timeout) {
ctrl &= ~SDHCI_CTRL_TUNED_CLK;
sdhci_writew(host, ctrl, SDHCI_HOST_CONTROL2);
} else {
if (!(ctrl & SDHCI_CTRL_TUNED_CLK)) {
pr_info(DRIVER_NAME ": Tuning procedure"
" failed, falling back to fixed sampling"
" clock\n");
err = -EIO;
}
}
out:
/*
* If this is the very first time we are here, we start the retuning
* timer. Since only during the first time, SDHCI_NEEDS_RETUNING
* flag won't be set, we check this condition before actually starting
* the timer.
*/
if (!(host->flags & SDHCI_NEEDS_RETUNING) && host->tuning_count &&
(host->tuning_mode == SDHCI_TUNING_MODE_1)) {
mod_timer(&host->tuning_timer, jiffies +
host->tuning_count * HZ);
/* Tuning mode 1 limits the maximum data length to 4MB */
mmc->max_blk_count = (4 * 1024 * 1024) / mmc->max_blk_size;
} else {
host->flags &= ~SDHCI_NEEDS_RETUNING;
/* Reload the new initial value for timer */
if (host->tuning_mode == SDHCI_TUNING_MODE_1)
mod_timer(&host->tuning_timer, jiffies +
host->tuning_count * HZ);
}
/*
* In case tuning fails, host controllers which support re-tuning can
* try tuning again at a later time, when the re-tuning timer expires.
* So for these controllers, we return 0. Since there might be other
* controllers who do not have this capability, we return error for
* them.
*/
if (err && host->tuning_count &&
host->tuning_mode == SDHCI_TUNING_MODE_1)
err = 0;
sdhci_clear_set_irqs(host, SDHCI_INT_DATA_AVAIL, ier);
spin_unlock(&host->lock);
enable_irq(host->irq);
sdhci_runtime_pm_put(host);
return err;
}
static void sdhci_do_enable_preset_value(struct sdhci_host *host, bool enable)
{
u16 ctrl;
unsigned long flags;
/* Host Controller v3.00 defines preset value registers */
if (host->version < SDHCI_SPEC_300)
return;
spin_lock_irqsave(&host->lock, flags);
ctrl = sdhci_readw(host, SDHCI_HOST_CONTROL2);
/*
* We only enable or disable Preset Value if they are not already
* enabled or disabled respectively. Otherwise, we bail out.
*/
if (enable && !(ctrl & SDHCI_CTRL_PRESET_VAL_ENABLE)) {
ctrl |= SDHCI_CTRL_PRESET_VAL_ENABLE;
sdhci_writew(host, ctrl, SDHCI_HOST_CONTROL2);
host->flags |= SDHCI_PV_ENABLED;
} else if (!enable && (ctrl & SDHCI_CTRL_PRESET_VAL_ENABLE)) {
ctrl &= ~SDHCI_CTRL_PRESET_VAL_ENABLE;
sdhci_writew(host, ctrl, SDHCI_HOST_CONTROL2);
host->flags &= ~SDHCI_PV_ENABLED;
}
spin_unlock_irqrestore(&host->lock, flags);
}
static void sdhci_enable_preset_value(struct mmc_host *mmc, bool enable)
{
struct sdhci_host *host = mmc_priv(mmc);
sdhci_runtime_pm_get(host);
sdhci_do_enable_preset_value(host, enable);
sdhci_runtime_pm_put(host);
}
static const struct mmc_host_ops sdhci_ops = {
.request = sdhci_request,
.set_ios = sdhci_set_ios,
.get_ro = sdhci_get_ro,
.hw_reset = sdhci_hw_reset,
.enable_sdio_irq = sdhci_enable_sdio_irq,
.start_signal_voltage_switch = sdhci_start_signal_voltage_switch,
.execute_tuning = sdhci_execute_tuning,
.enable_preset_value = sdhci_enable_preset_value,
};
/*****************************************************************************\
* *
* Tasklets *
* *
\*****************************************************************************/
static void sdhci_tasklet_card(unsigned long param)
{
struct sdhci_host *host;
unsigned long flags;
host = (struct sdhci_host*)param;
spin_lock_irqsave(&host->lock, flags);
/* Check host->mrq first in case we are runtime suspended */
if (host->mrq &&
!(sdhci_readl(host, SDHCI_PRESENT_STATE) & SDHCI_CARD_PRESENT)) {
pr_err("%s: Card removed during transfer!\n",
mmc_hostname(host->mmc));
pr_err("%s: Resetting controller.\n",
mmc_hostname(host->mmc));
sdhci_reset(host, SDHCI_RESET_CMD);
sdhci_reset(host, SDHCI_RESET_DATA);
host->mrq->cmd->error = -ENOMEDIUM;
tasklet_schedule(&host->finish_tasklet);
}
spin_unlock_irqrestore(&host->lock, flags);
mmc_detect_change(host->mmc, msecs_to_jiffies(200));
}
static void sdhci_tasklet_finish(unsigned long param)
{
struct sdhci_host *host;
unsigned long flags;
struct mmc_request *mrq;
host = (struct sdhci_host*)param;
spin_lock_irqsave(&host->lock, flags);
/*
* If this tasklet gets rescheduled while running, it will
* be run again afterwards but without any active request.
*/
if (!host->mrq) {
spin_unlock_irqrestore(&host->lock, flags);
return;
}
del_timer(&host->timer);
mrq = host->mrq;
/*
* The controller needs a reset of internal state machines
* upon error conditions.
*/
if (!(host->flags & SDHCI_DEVICE_DEAD) &&
((mrq->cmd && mrq->cmd->error) ||
(mrq->data && (mrq->data->error ||
(mrq->data->stop && mrq->data->stop->error))) ||
(host->quirks & SDHCI_QUIRK_RESET_AFTER_REQUEST))) {
/* Some controllers need this kick or reset won't work here */
if (host->quirks & SDHCI_QUIRK_CLOCK_BEFORE_RESET) {
unsigned int clock;
/* This is to force an update */
clock = host->clock;
host->clock = 0;
sdhci_set_clock(host, clock);
}
/* Spec says we should do both at the same time, but Ricoh
controllers do not like that. */
sdhci_reset(host, SDHCI_RESET_CMD);
sdhci_reset(host, SDHCI_RESET_DATA);
}
host->mrq = NULL;
host->cmd = NULL;
host->data = NULL;
#ifndef SDHCI_USE_LEDS_CLASS
sdhci_deactivate_led(host);
#endif
mmiowb();
spin_unlock_irqrestore(&host->lock, flags);
mmc_request_done(host->mmc, mrq);
sdhci_runtime_pm_put(host);
}
static void sdhci_timeout_timer(unsigned long data)
{
struct sdhci_host *host;
unsigned long flags;
host = (struct sdhci_host*)data;
spin_lock_irqsave(&host->lock, flags);
if (host->mrq) {
pr_err("%s: Timeout waiting for hardware "
"interrupt.\n", mmc_hostname(host->mmc));
sdhci_dumpregs(host);
if (host->data) {
host->data->error = -ETIMEDOUT;
sdhci_finish_data(host);
} else {
if (host->cmd)
host->cmd->error = -ETIMEDOUT;
else
host->mrq->cmd->error = -ETIMEDOUT;
tasklet_schedule(&host->finish_tasklet);
}
}
mmiowb();
spin_unlock_irqrestore(&host->lock, flags);
}
static void sdhci_tuning_timer(unsigned long data)
{
struct sdhci_host *host;
unsigned long flags;
host = (struct sdhci_host *)data;
spin_lock_irqsave(&host->lock, flags);
host->flags |= SDHCI_NEEDS_RETUNING;
spin_unlock_irqrestore(&host->lock, flags);
}
/*****************************************************************************\
* *
* Interrupt handling *
* *
\*****************************************************************************/
static void sdhci_cmd_irq(struct sdhci_host *host, u32 intmask)
{
BUG_ON(intmask == 0);
if (!host->cmd) {
pr_err("%s: Got command interrupt 0x%08x even "
"though no command operation was in progress.\n",
mmc_hostname(host->mmc), (unsigned)intmask);
sdhci_dumpregs(host);
return;
}
if (intmask & SDHCI_INT_TIMEOUT)
host->cmd->error = -ETIMEDOUT;
else if (intmask & (SDHCI_INT_CRC | SDHCI_INT_END_BIT |
SDHCI_INT_INDEX))
host->cmd->error = -EILSEQ;
if (host->cmd->error) {
tasklet_schedule(&host->finish_tasklet);
return;
}
/*
* The host can send and interrupt when the busy state has
* ended, allowing us to wait without wasting CPU cycles.
* Unfortunately this is overloaded on the "data complete"
* interrupt, so we need to take some care when handling
* it.
*
* Note: The 1.0 specification is a bit ambiguous about this
* feature so there might be some problems with older
* controllers.
*/
if (host->cmd->flags & MMC_RSP_BUSY) {
if (host->cmd->data)
DBG("Cannot wait for busy signal when also "
"doing a data transfer");
else if (!(host->quirks & SDHCI_QUIRK_NO_BUSY_IRQ))
return;
/* The controller does not support the end-of-busy IRQ,
* fall through and take the SDHCI_INT_RESPONSE */
}
if (intmask & SDHCI_INT_RESPONSE)
sdhci_finish_command(host);
}
#ifdef CONFIG_MMC_DEBUG
static void sdhci_show_adma_error(struct sdhci_host *host)
{
const char *name = mmc_hostname(host->mmc);
u8 *desc = host->adma_desc;
__le32 *dma;
__le16 *len;
u8 attr;
sdhci_dumpregs(host);
while (true) {
dma = (__le32 *)(desc + 4);
len = (__le16 *)(desc + 2);
attr = *desc;
DBG("%s: %p: DMA 0x%08x, LEN 0x%04x, Attr=0x%02x\n",
name, desc, le32_to_cpu(*dma), le16_to_cpu(*len), attr);
desc += 8;
if (attr & 2)
break;
}
}
#else
static void sdhci_show_adma_error(struct sdhci_host *host) { }
#endif
static void sdhci_data_irq(struct sdhci_host *host, u32 intmask)
{
u32 command;
BUG_ON(intmask == 0);
/* CMD19 generates _only_ Buffer Read Ready interrupt */
if (intmask & SDHCI_INT_DATA_AVAIL) {
command = SDHCI_GET_CMD(sdhci_readw(host, SDHCI_COMMAND));
if (command == MMC_SEND_TUNING_BLOCK ||
command == MMC_SEND_TUNING_BLOCK_HS200) {
host->tuning_done = 1;
wake_up(&host->buf_ready_int);
return;
}
}
if (!host->data) {
/*
* The "data complete" interrupt is also used to
* indicate that a busy state has ended. See comment
* above in sdhci_cmd_irq().
*/
if (host->cmd && (host->cmd->flags & MMC_RSP_BUSY)) {
if (intmask & SDHCI_INT_DATA_END) {
sdhci_finish_command(host);
return;
}
}
pr_err("%s: Got data interrupt 0x%08x even "
"though no data operation was in progress.\n",
mmc_hostname(host->mmc), (unsigned)intmask);
sdhci_dumpregs(host);
return;
}
if (intmask & SDHCI_INT_DATA_TIMEOUT)
host->data->error = -ETIMEDOUT;
else if (intmask & SDHCI_INT_DATA_END_BIT)
host->data->error = -EILSEQ;
else if ((intmask & SDHCI_INT_DATA_CRC) &&
SDHCI_GET_CMD(sdhci_readw(host, SDHCI_COMMAND))
!= MMC_BUS_TEST_R)
host->data->error = -EILSEQ;
else if (intmask & SDHCI_INT_ADMA_ERROR) {
pr_err("%s: ADMA error\n", mmc_hostname(host->mmc));
sdhci_show_adma_error(host);
host->data->error = -EIO;
}
if (host->data->error)
sdhci_finish_data(host);
else {
if (intmask & (SDHCI_INT_DATA_AVAIL | SDHCI_INT_SPACE_AVAIL))
sdhci_transfer_pio(host);
/*
* We currently don't do anything fancy with DMA
* boundaries, but as we can't disable the feature
* we need to at least restart the transfer.
*
* According to the spec sdhci_readl(host, SDHCI_DMA_ADDRESS)
* should return a valid address to continue from, but as
* some controllers are faulty, don't trust them.
*/
if (intmask & SDHCI_INT_DMA_END) {
u32 dmastart, dmanow;
dmastart = sg_dma_address(host->data->sg);
dmanow = dmastart + host->data->bytes_xfered;
/*
* Force update to the next DMA block boundary.
*/
dmanow = (dmanow &
~(SDHCI_DEFAULT_BOUNDARY_SIZE - 1)) +
SDHCI_DEFAULT_BOUNDARY_SIZE;
host->data->bytes_xfered = dmanow - dmastart;
DBG("%s: DMA base 0x%08x, transferred 0x%06x bytes,"
" next 0x%08x\n",
mmc_hostname(host->mmc), dmastart,
host->data->bytes_xfered, dmanow);
sdhci_writel(host, dmanow, SDHCI_DMA_ADDRESS);
}
if (intmask & SDHCI_INT_DATA_END) {
if (host->cmd) {
/*
* Data managed to finish before the
* command completed. Make sure we do
* things in the proper order.
*/
host->data_early = 1;
} else {
sdhci_finish_data(host);
}
}
}
}
static irqreturn_t sdhci_irq(int irq, void *dev_id)
{
irqreturn_t result;
struct sdhci_host *host = dev_id;
u32 intmask, unexpected = 0;
int cardint = 0, max_loops = 16;
spin_lock(&host->lock);
if (host->runtime_suspended) {
spin_unlock(&host->lock);
pr_warning("%s: got irq while runtime suspended\n",
mmc_hostname(host->mmc));
return IRQ_HANDLED;
}
intmask = sdhci_readl(host, SDHCI_INT_STATUS);
if (!intmask || intmask == 0xffffffff) {
result = IRQ_NONE;
goto out;
}
again:
DBG("*** %s got interrupt: 0x%08x\n",
mmc_hostname(host->mmc), intmask);
if (intmask & (SDHCI_INT_CARD_INSERT | SDHCI_INT_CARD_REMOVE)) {
u32 present = sdhci_readl(host, SDHCI_PRESENT_STATE) &
SDHCI_CARD_PRESENT;
/*
* There is a observation on i.mx esdhc. INSERT bit will be
* immediately set again when it gets cleared, if a card is
* inserted. We have to mask the irq to prevent interrupt
* storm which will freeze the system. And the REMOVE gets
* the same situation.
*
* More testing are needed here to ensure it works for other
* platforms though.
*/
sdhci_mask_irqs(host, present ? SDHCI_INT_CARD_INSERT :
SDHCI_INT_CARD_REMOVE);
sdhci_unmask_irqs(host, present ? SDHCI_INT_CARD_REMOVE :
SDHCI_INT_CARD_INSERT);
sdhci_writel(host, intmask & (SDHCI_INT_CARD_INSERT |
SDHCI_INT_CARD_REMOVE), SDHCI_INT_STATUS);
intmask &= ~(SDHCI_INT_CARD_INSERT | SDHCI_INT_CARD_REMOVE);
tasklet_schedule(&host->card_tasklet);
}
if (intmask & SDHCI_INT_CMD_MASK) {
sdhci_writel(host, intmask & SDHCI_INT_CMD_MASK,
SDHCI_INT_STATUS);
sdhci_cmd_irq(host, intmask & SDHCI_INT_CMD_MASK);
}
if (intmask & SDHCI_INT_DATA_MASK) {
sdhci_writel(host, intmask & SDHCI_INT_DATA_MASK,
SDHCI_INT_STATUS);
sdhci_data_irq(host, intmask & SDHCI_INT_DATA_MASK);
}
intmask &= ~(SDHCI_INT_CMD_MASK | SDHCI_INT_DATA_MASK);
intmask &= ~SDHCI_INT_ERROR;
if (intmask & SDHCI_INT_BUS_POWER) {
pr_err("%s: Card is consuming too much power!\n",
mmc_hostname(host->mmc));
sdhci_writel(host, SDHCI_INT_BUS_POWER, SDHCI_INT_STATUS);
}
intmask &= ~SDHCI_INT_BUS_POWER;
if (intmask & SDHCI_INT_CARD_INT)
cardint = 1;
intmask &= ~SDHCI_INT_CARD_INT;
if (intmask) {
unexpected |= intmask;
sdhci_writel(host, intmask, SDHCI_INT_STATUS);
}
result = IRQ_HANDLED;
intmask = sdhci_readl(host, SDHCI_INT_STATUS);
if (intmask && --max_loops)
goto again;
out:
spin_unlock(&host->lock);
if (unexpected) {
pr_err("%s: Unexpected interrupt 0x%08x.\n",
mmc_hostname(host->mmc), unexpected);
sdhci_dumpregs(host);
}
/*
* We have to delay this as it calls back into the driver.
*/
if (cardint)
mmc_signal_sdio_irq(host->mmc);
return result;
}
/*****************************************************************************\
* *
* Suspend/resume *
* *
\*****************************************************************************/
#ifdef CONFIG_PM
int sdhci_suspend_host(struct sdhci_host *host)
{
int ret;
bool has_tuning_timer;
if (host->ops->platform_suspend)
host->ops->platform_suspend(host);
sdhci_disable_card_detection(host);
/* Disable tuning since we are suspending */
has_tuning_timer = host->version >= SDHCI_SPEC_300 &&
host->tuning_count && host->tuning_mode == SDHCI_TUNING_MODE_1;
if (has_tuning_timer) {
del_timer_sync(&host->tuning_timer);
host->flags &= ~SDHCI_NEEDS_RETUNING;
}
ret = mmc_suspend_host(host->mmc);
if (ret) {
if (has_tuning_timer) {
host->flags |= SDHCI_NEEDS_RETUNING;
mod_timer(&host->tuning_timer, jiffies +
host->tuning_count * HZ);
}
sdhci_enable_card_detection(host);
return ret;
}
free_irq(host->irq, host);
return ret;
}
EXPORT_SYMBOL_GPL(sdhci_suspend_host);
int sdhci_resume_host(struct sdhci_host *host)
{
int ret;
if (host->flags & (SDHCI_USE_SDMA | SDHCI_USE_ADMA)) {
if (host->ops->enable_dma)
host->ops->enable_dma(host);
}
ret = request_irq(host->irq, sdhci_irq, IRQF_SHARED,
mmc_hostname(host->mmc), host);
if (ret)
return ret;
if ((host->mmc->pm_flags & MMC_PM_KEEP_POWER) &&
(host->quirks2 & SDHCI_QUIRK2_HOST_OFF_CARD_ON)) {
/* Card keeps power but host controller does not */
sdhci_init(host, 0);
host->pwr = 0;
host->clock = 0;
sdhci_do_set_ios(host, &host->mmc->ios);
} else {
sdhci_init(host, (host->mmc->pm_flags & MMC_PM_KEEP_POWER));
mmiowb();
}
ret = mmc_resume_host(host->mmc);
sdhci_enable_card_detection(host);
if (host->ops->platform_resume)
host->ops->platform_resume(host);
/* Set the re-tuning expiration flag */
if ((host->version >= SDHCI_SPEC_300) && host->tuning_count &&
(host->tuning_mode == SDHCI_TUNING_MODE_1))
host->flags |= SDHCI_NEEDS_RETUNING;
return ret;
}
EXPORT_SYMBOL_GPL(sdhci_resume_host);
void sdhci_enable_irq_wakeups(struct sdhci_host *host)
{
u8 val;
val = sdhci_readb(host, SDHCI_WAKE_UP_CONTROL);
val |= SDHCI_WAKE_ON_INT;
sdhci_writeb(host, val, SDHCI_WAKE_UP_CONTROL);
}
EXPORT_SYMBOL_GPL(sdhci_enable_irq_wakeups);
#endif /* CONFIG_PM */
#ifdef CONFIG_PM_RUNTIME
static int sdhci_runtime_pm_get(struct sdhci_host *host)
{
return pm_runtime_get_sync(host->mmc->parent);
}
static int sdhci_runtime_pm_put(struct sdhci_host *host)
{
pm_runtime_mark_last_busy(host->mmc->parent);
return pm_runtime_put_autosuspend(host->mmc->parent);
}
int sdhci_runtime_suspend_host(struct sdhci_host *host)
{
unsigned long flags;
int ret = 0;
/* Disable tuning since we are suspending */
if (host->version >= SDHCI_SPEC_300 &&
host->tuning_mode == SDHCI_TUNING_MODE_1) {
del_timer_sync(&host->tuning_timer);
host->flags &= ~SDHCI_NEEDS_RETUNING;
}
spin_lock_irqsave(&host->lock, flags);
sdhci_mask_irqs(host, SDHCI_INT_ALL_MASK);
spin_unlock_irqrestore(&host->lock, flags);
synchronize_irq(host->irq);
spin_lock_irqsave(&host->lock, flags);
host->runtime_suspended = true;
spin_unlock_irqrestore(&host->lock, flags);
return ret;
}
EXPORT_SYMBOL_GPL(sdhci_runtime_suspend_host);
int sdhci_runtime_resume_host(struct sdhci_host *host)
{
unsigned long flags;
int ret = 0, host_flags = host->flags;
if (host_flags & (SDHCI_USE_SDMA | SDHCI_USE_ADMA)) {
if (host->ops->enable_dma)
host->ops->enable_dma(host);
}
sdhci_init(host, 0);
/* Force clock and power re-program */
host->pwr = 0;
host->clock = 0;
sdhci_do_set_ios(host, &host->mmc->ios);
sdhci_do_start_signal_voltage_switch(host, &host->mmc->ios);
if (host_flags & SDHCI_PV_ENABLED)
sdhci_do_enable_preset_value(host, true);
/* Set the re-tuning expiration flag */
if ((host->version >= SDHCI_SPEC_300) && host->tuning_count &&
(host->tuning_mode == SDHCI_TUNING_MODE_1))
host->flags |= SDHCI_NEEDS_RETUNING;
spin_lock_irqsave(&host->lock, flags);
host->runtime_suspended = false;
/* Enable SDIO IRQ */
if ((host->flags & SDHCI_SDIO_IRQ_ENABLED))
sdhci_enable_sdio_irq_nolock(host, true);
/* Enable Card Detection */
sdhci_enable_card_detection(host);
spin_unlock_irqrestore(&host->lock, flags);
return ret;
}
EXPORT_SYMBOL_GPL(sdhci_runtime_resume_host);
#endif
/*****************************************************************************\
* *
* Device allocation/registration *
* *
\*****************************************************************************/
struct sdhci_host *sdhci_alloc_host(struct device *dev,
size_t priv_size)
{
struct mmc_host *mmc;
struct sdhci_host *host;
WARN_ON(dev == NULL);
mmc = mmc_alloc_host(sizeof(struct sdhci_host) + priv_size, dev);
if (!mmc)
return ERR_PTR(-ENOMEM);
host = mmc_priv(mmc);
host->mmc = mmc;
return host;
}
EXPORT_SYMBOL_GPL(sdhci_alloc_host);
int sdhci_add_host(struct sdhci_host *host)
{
struct mmc_host *mmc;
u32 caps[2];
u32 max_current_caps;
unsigned int ocr_avail;
int ret;
WARN_ON(host == NULL);
if (host == NULL)
return -EINVAL;
mmc = host->mmc;
if (debug_quirks)
host->quirks = debug_quirks;
if (debug_quirks2)
host->quirks2 = debug_quirks2;
sdhci_reset(host, SDHCI_RESET_ALL);
host->version = sdhci_readw(host, SDHCI_HOST_VERSION);
host->version = (host->version & SDHCI_SPEC_VER_MASK)
>> SDHCI_SPEC_VER_SHIFT;
if (host->version > SDHCI_SPEC_300) {
pr_err("%s: Unknown controller version (%d). "
"You may experience problems.\n", mmc_hostname(mmc),
host->version);
}
caps[0] = (host->quirks & SDHCI_QUIRK_MISSING_CAPS) ? host->caps :
sdhci_readl(host, SDHCI_CAPABILITIES);
caps[1] = (host->version >= SDHCI_SPEC_300) ?
sdhci_readl(host, SDHCI_CAPABILITIES_1) : 0;
if (host->quirks & SDHCI_QUIRK_FORCE_DMA)
host->flags |= SDHCI_USE_SDMA;
else if (!(caps[0] & SDHCI_CAN_DO_SDMA))
DBG("Controller doesn't have SDMA capability\n");
else
host->flags |= SDHCI_USE_SDMA;
if ((host->quirks & SDHCI_QUIRK_BROKEN_DMA) &&
(host->flags & SDHCI_USE_SDMA)) {
DBG("Disabling DMA as it is marked broken\n");
host->flags &= ~SDHCI_USE_SDMA;
}
if ((host->version >= SDHCI_SPEC_200) &&
(caps[0] & SDHCI_CAN_DO_ADMA2))
host->flags |= SDHCI_USE_ADMA;
if ((host->quirks & SDHCI_QUIRK_BROKEN_ADMA) &&
(host->flags & SDHCI_USE_ADMA)) {
DBG("Disabling ADMA as it is marked broken\n");
host->flags &= ~SDHCI_USE_ADMA;
}
if (host->flags & (SDHCI_USE_SDMA | SDHCI_USE_ADMA)) {
if (host->ops->enable_dma) {
if (host->ops->enable_dma(host)) {
pr_warning("%s: No suitable DMA "
"available. Falling back to PIO.\n",
mmc_hostname(mmc));
host->flags &=
~(SDHCI_USE_SDMA | SDHCI_USE_ADMA);
}
}
}
if (host->flags & SDHCI_USE_ADMA) {
/*
* We need to allocate descriptors for all sg entries
* (128) and potentially one alignment transfer for
* each of those entries.
*/
host->adma_desc = kmalloc((128 * 2 + 1) * 4, GFP_KERNEL);
host->align_buffer = kmalloc(128 * 4, GFP_KERNEL);
if (!host->adma_desc || !host->align_buffer) {
kfree(host->adma_desc);
kfree(host->align_buffer);
pr_warning("%s: Unable to allocate ADMA "
"buffers. Falling back to standard DMA.\n",
mmc_hostname(mmc));
host->flags &= ~SDHCI_USE_ADMA;
}
}
/*
* If we use DMA, then it's up to the caller to set the DMA
* mask, but PIO does not need the hw shim so we set a new
* mask here in that case.
*/
if (!(host->flags & (SDHCI_USE_SDMA | SDHCI_USE_ADMA))) {
host->dma_mask = DMA_BIT_MASK(64);
mmc_dev(host->mmc)->dma_mask = &host->dma_mask;
}
if (host->version >= SDHCI_SPEC_300)
host->max_clk = (caps[0] & SDHCI_CLOCK_V3_BASE_MASK)
>> SDHCI_CLOCK_BASE_SHIFT;
else
host->max_clk = (caps[0] & SDHCI_CLOCK_BASE_MASK)
>> SDHCI_CLOCK_BASE_SHIFT;
host->max_clk *= 1000000;
if (host->max_clk == 0 || host->quirks &
SDHCI_QUIRK_CAP_CLOCK_BASE_BROKEN) {
if (!host->ops->get_max_clock) {
pr_err("%s: Hardware doesn't specify base clock "
"frequency.\n", mmc_hostname(mmc));
return -ENODEV;
}
host->max_clk = host->ops->get_max_clock(host);
}
/*
* In case of Host Controller v3.00, find out whether clock
* multiplier is supported.
*/
host->clk_mul = (caps[1] & SDHCI_CLOCK_MUL_MASK) >>
SDHCI_CLOCK_MUL_SHIFT;
/*
* In case the value in Clock Multiplier is 0, then programmable
* clock mode is not supported, otherwise the actual clock
* multiplier is one more than the value of Clock Multiplier
* in the Capabilities Register.
*/
if (host->clk_mul)
host->clk_mul += 1;
/*
* Set host parameters.
*/
mmc->ops = &sdhci_ops;
mmc->f_max = host->max_clk;
if (host->ops->get_min_clock)
mmc->f_min = host->ops->get_min_clock(host);
else if (host->version >= SDHCI_SPEC_300) {
if (host->clk_mul) {
mmc->f_min = (host->max_clk * host->clk_mul) / 1024;
mmc->f_max = host->max_clk * host->clk_mul;
} else
mmc->f_min = host->max_clk / SDHCI_MAX_DIV_SPEC_300;
} else
mmc->f_min = host->max_clk / SDHCI_MAX_DIV_SPEC_200;
host->timeout_clk =
(caps[0] & SDHCI_TIMEOUT_CLK_MASK) >> SDHCI_TIMEOUT_CLK_SHIFT;
if (host->timeout_clk == 0) {
if (host->ops->get_timeout_clock) {
host->timeout_clk = host->ops->get_timeout_clock(host);
} else if (!(host->quirks &
SDHCI_QUIRK_DATA_TIMEOUT_USES_SDCLK)) {
pr_err("%s: Hardware doesn't specify timeout clock "
"frequency.\n", mmc_hostname(mmc));
return -ENODEV;
}
}
if (caps[0] & SDHCI_TIMEOUT_CLK_UNIT)
host->timeout_clk *= 1000;
if (host->quirks & SDHCI_QUIRK_DATA_TIMEOUT_USES_SDCLK)
host->timeout_clk = mmc->f_max / 1000;
mmc->max_discard_to = (1 << 27) / host->timeout_clk;
mmc->caps |= MMC_CAP_SDIO_IRQ | MMC_CAP_ERASE | MMC_CAP_CMD23;
if (host->quirks & SDHCI_QUIRK_MULTIBLOCK_READ_ACMD12)
host->flags |= SDHCI_AUTO_CMD12;
/* Auto-CMD23 stuff only works in ADMA or PIO. */
if ((host->version >= SDHCI_SPEC_300) &&
((host->flags & SDHCI_USE_ADMA) ||
!(host->flags & SDHCI_USE_SDMA))) {
host->flags |= SDHCI_AUTO_CMD23;
DBG("%s: Auto-CMD23 available\n", mmc_hostname(mmc));
} else {
DBG("%s: Auto-CMD23 unavailable\n", mmc_hostname(mmc));
}
/*
* A controller may support 8-bit width, but the board itself
* might not have the pins brought out. Boards that support
* 8-bit width must set "mmc->caps |= MMC_CAP_8_BIT_DATA;" in
* their platform code before calling sdhci_add_host(), and we
* won't assume 8-bit width for hosts without that CAP.
*/
if (!(host->quirks & SDHCI_QUIRK_FORCE_1_BIT_DATA))
mmc->caps |= MMC_CAP_4_BIT_DATA;
if (caps[0] & SDHCI_CAN_DO_HISPD)
mmc->caps |= MMC_CAP_SD_HIGHSPEED | MMC_CAP_MMC_HIGHSPEED;
if ((host->quirks & SDHCI_QUIRK_BROKEN_CARD_DETECTION) &&
mmc_card_is_removable(mmc))
mmc->caps |= MMC_CAP_NEEDS_POLL;
/* Any UHS-I mode in caps implies SDR12 and SDR25 support. */
if (caps[1] & (SDHCI_SUPPORT_SDR104 | SDHCI_SUPPORT_SDR50 |
SDHCI_SUPPORT_DDR50))
mmc->caps |= MMC_CAP_UHS_SDR12 | MMC_CAP_UHS_SDR25;
/* SDR104 supports also implies SDR50 support */
if (caps[1] & SDHCI_SUPPORT_SDR104)
mmc->caps |= MMC_CAP_UHS_SDR104 | MMC_CAP_UHS_SDR50;
else if (caps[1] & SDHCI_SUPPORT_SDR50)
mmc->caps |= MMC_CAP_UHS_SDR50;
if (caps[1] & SDHCI_SUPPORT_DDR50)
mmc->caps |= MMC_CAP_UHS_DDR50;
/* Does the host need tuning for SDR50? */
if (caps[1] & SDHCI_USE_SDR50_TUNING)
host->flags |= SDHCI_SDR50_NEEDS_TUNING;
/* Does the host need tuning for HS200? */
if (mmc->caps2 & MMC_CAP2_HS200)
host->flags |= SDHCI_HS200_NEEDS_TUNING;
/* Driver Type(s) (A, C, D) supported by the host */
if (caps[1] & SDHCI_DRIVER_TYPE_A)
mmc->caps |= MMC_CAP_DRIVER_TYPE_A;
if (caps[1] & SDHCI_DRIVER_TYPE_C)
mmc->caps |= MMC_CAP_DRIVER_TYPE_C;
if (caps[1] & SDHCI_DRIVER_TYPE_D)
mmc->caps |= MMC_CAP_DRIVER_TYPE_D;
/*
* If Power Off Notify capability is enabled by the host,
* set notify to short power off notify timeout value.
*/
if (mmc->caps2 & MMC_CAP2_POWEROFF_NOTIFY)
mmc->power_notify_type = MMC_HOST_PW_NOTIFY_SHORT;
else
mmc->power_notify_type = MMC_HOST_PW_NOTIFY_NONE;
/* Initial value for re-tuning timer count */
host->tuning_count = (caps[1] & SDHCI_RETUNING_TIMER_COUNT_MASK) >>
SDHCI_RETUNING_TIMER_COUNT_SHIFT;
/*
* In case Re-tuning Timer is not disabled, the actual value of
* re-tuning timer will be 2 ^ (n - 1).
*/
if (host->tuning_count)
host->tuning_count = 1 << (host->tuning_count - 1);
/* Re-tuning mode supported by the Host Controller */
host->tuning_mode = (caps[1] & SDHCI_RETUNING_MODE_MASK) >>
SDHCI_RETUNING_MODE_SHIFT;
ocr_avail = 0;
/*
* According to SD Host Controller spec v3.00, if the Host System
* can afford more than 150mA, Host Driver should set XPC to 1. Also
* the value is meaningful only if Voltage Support in the Capabilities
* register is set. The actual current value is 4 times the register
* value.
*/
max_current_caps = sdhci_readl(host, SDHCI_MAX_CURRENT);
if (caps[0] & SDHCI_CAN_VDD_330) {
int max_current_330;
ocr_avail |= MMC_VDD_32_33 | MMC_VDD_33_34;
max_current_330 = ((max_current_caps &
SDHCI_MAX_CURRENT_330_MASK) >>
SDHCI_MAX_CURRENT_330_SHIFT) *
SDHCI_MAX_CURRENT_MULTIPLIER;
if (max_current_330 > 150)
mmc->caps |= MMC_CAP_SET_XPC_330;
}
if (caps[0] & SDHCI_CAN_VDD_300) {
int max_current_300;
ocr_avail |= MMC_VDD_29_30 | MMC_VDD_30_31;
max_current_300 = ((max_current_caps &
SDHCI_MAX_CURRENT_300_MASK) >>
SDHCI_MAX_CURRENT_300_SHIFT) *
SDHCI_MAX_CURRENT_MULTIPLIER;
if (max_current_300 > 150)
mmc->caps |= MMC_CAP_SET_XPC_300;
}
if (caps[0] & SDHCI_CAN_VDD_180) {
int max_current_180;
ocr_avail |= MMC_VDD_165_195;
max_current_180 = ((max_current_caps &
SDHCI_MAX_CURRENT_180_MASK) >>
SDHCI_MAX_CURRENT_180_SHIFT) *
SDHCI_MAX_CURRENT_MULTIPLIER;
if (max_current_180 > 150)
mmc->caps |= MMC_CAP_SET_XPC_180;
/* Maximum current capabilities of the host at 1.8V */
if (max_current_180 >= 800)
mmc->caps |= MMC_CAP_MAX_CURRENT_800;
else if (max_current_180 >= 600)
mmc->caps |= MMC_CAP_MAX_CURRENT_600;
else if (max_current_180 >= 400)
mmc->caps |= MMC_CAP_MAX_CURRENT_400;
else
mmc->caps |= MMC_CAP_MAX_CURRENT_200;
}
mmc->ocr_avail = ocr_avail;
mmc->ocr_avail_sdio = ocr_avail;
if (host->ocr_avail_sdio)
mmc->ocr_avail_sdio &= host->ocr_avail_sdio;
mmc->ocr_avail_sd = ocr_avail;
if (host->ocr_avail_sd)
mmc->ocr_avail_sd &= host->ocr_avail_sd;
else /* normal SD controllers don't support 1.8V */
mmc->ocr_avail_sd &= ~MMC_VDD_165_195;
mmc->ocr_avail_mmc = ocr_avail;
if (host->ocr_avail_mmc)
mmc->ocr_avail_mmc &= host->ocr_avail_mmc;
if (mmc->ocr_avail == 0) {
pr_err("%s: Hardware doesn't report any "
"support voltages.\n", mmc_hostname(mmc));
return -ENODEV;
}
spin_lock_init(&host->lock);
/*
* Maximum number of segments. Depends on if the hardware
* can do scatter/gather or not.
*/
if (host->flags & SDHCI_USE_ADMA)
mmc->max_segs = 128;
else if (host->flags & SDHCI_USE_SDMA)
mmc->max_segs = 1;
else /* PIO */
mmc->max_segs = 128;
/*
* Maximum number of sectors in one transfer. Limited by DMA boundary
* size (512KiB).
*/
mmc->max_req_size = 524288;
/*
* Maximum segment size. Could be one segment with the maximum number
* of bytes. When doing hardware scatter/gather, each entry cannot
* be larger than 64 KiB though.
*/
if (host->flags & SDHCI_USE_ADMA) {
if (host->quirks & SDHCI_QUIRK_BROKEN_ADMA_ZEROLEN_DESC)
mmc->max_seg_size = 65535;
else
mmc->max_seg_size = 65536;
} else {
mmc->max_seg_size = mmc->max_req_size;
}
/*
* Maximum block size. This varies from controller to controller and
* is specified in the capabilities register.
*/
if (host->quirks & SDHCI_QUIRK_FORCE_BLK_SZ_2048) {
mmc->max_blk_size = 2;
} else {
mmc->max_blk_size = (caps[0] & SDHCI_MAX_BLOCK_MASK) >>
SDHCI_MAX_BLOCK_SHIFT;
if (mmc->max_blk_size >= 3) {
pr_warning("%s: Invalid maximum block size, "
"assuming 512 bytes\n", mmc_hostname(mmc));
mmc->max_blk_size = 0;
}
}
mmc->max_blk_size = 512 << mmc->max_blk_size;
/*
* Maximum block count.
*/
mmc->max_blk_count = (host->quirks & SDHCI_QUIRK_NO_MULTIBLOCK) ? 1 : 65535;
/*
* Init tasklets.
*/
tasklet_init(&host->card_tasklet,
sdhci_tasklet_card, (unsigned long)host);
tasklet_init(&host->finish_tasklet,
sdhci_tasklet_finish, (unsigned long)host);
setup_timer(&host->timer, sdhci_timeout_timer, (unsigned long)host);
if (host->version >= SDHCI_SPEC_300) {
init_waitqueue_head(&host->buf_ready_int);
/* Initialize re-tuning timer */
init_timer(&host->tuning_timer);
host->tuning_timer.data = (unsigned long)host;
host->tuning_timer.function = sdhci_tuning_timer;
}
ret = request_irq(host->irq, sdhci_irq, IRQF_SHARED,
mmc_hostname(mmc), host);
if (ret)
goto untasklet;
host->vmmc = regulator_get(mmc_dev(mmc), "vmmc");
if (IS_ERR(host->vmmc)) {
pr_info("%s: no vmmc regulator found\n", mmc_hostname(mmc));
host->vmmc = NULL;
}
sdhci_init(host, 0);
#ifdef CONFIG_MMC_DEBUG
sdhci_dumpregs(host);
#endif
#ifdef SDHCI_USE_LEDS_CLASS
snprintf(host->led_name, sizeof(host->led_name),
"%s::", mmc_hostname(mmc));
host->led.name = host->led_name;
host->led.brightness = LED_OFF;
host->led.default_trigger = mmc_hostname(mmc);
host->led.brightness_set = sdhci_led_control;
ret = led_classdev_register(mmc_dev(mmc), &host->led);
if (ret)
goto reset;
#endif
mmiowb();
mmc_add_host(mmc);
pr_info("%s: SDHCI controller on %s [%s] using %s\n",
mmc_hostname(mmc), host->hw_name, dev_name(mmc_dev(mmc)),
(host->flags & SDHCI_USE_ADMA) ? "ADMA" :
(host->flags & SDHCI_USE_SDMA) ? "DMA" : "PIO");
sdhci_enable_card_detection(host);
return 0;
#ifdef SDHCI_USE_LEDS_CLASS
reset:
sdhci_reset(host, SDHCI_RESET_ALL);
free_irq(host->irq, host);
#endif
untasklet:
tasklet_kill(&host->card_tasklet);
tasklet_kill(&host->finish_tasklet);
return ret;
}
EXPORT_SYMBOL_GPL(sdhci_add_host);
void sdhci_remove_host(struct sdhci_host *host, int dead)
{
unsigned long flags;
if (dead) {
spin_lock_irqsave(&host->lock, flags);
host->flags |= SDHCI_DEVICE_DEAD;
if (host->mrq) {
pr_err("%s: Controller removed during "
" transfer!\n", mmc_hostname(host->mmc));
host->mrq->cmd->error = -ENOMEDIUM;
tasklet_schedule(&host->finish_tasklet);
}
spin_unlock_irqrestore(&host->lock, flags);
}
sdhci_disable_card_detection(host);
mmc_remove_host(host->mmc);
#ifdef SDHCI_USE_LEDS_CLASS
led_classdev_unregister(&host->led);
#endif
if (!dead)
sdhci_reset(host, SDHCI_RESET_ALL);
free_irq(host->irq, host);
del_timer_sync(&host->timer);
if (host->version >= SDHCI_SPEC_300)
del_timer_sync(&host->tuning_timer);
tasklet_kill(&host->card_tasklet);
tasklet_kill(&host->finish_tasklet);
if (host->vmmc)
regulator_put(host->vmmc);
kfree(host->adma_desc);
kfree(host->align_buffer);
host->adma_desc = NULL;
host->align_buffer = NULL;
}
EXPORT_SYMBOL_GPL(sdhci_remove_host);
void sdhci_free_host(struct sdhci_host *host)
{
mmc_free_host(host->mmc);
}
EXPORT_SYMBOL_GPL(sdhci_free_host);
/*****************************************************************************\
* *
* Driver init/exit *
* *
\*****************************************************************************/
static int __init sdhci_drv_init(void)
{
pr_info(DRIVER_NAME
": Secure Digital Host Controller Interface driver\n");
pr_info(DRIVER_NAME ": Copyright(c) Pierre Ossman\n");
return 0;
}
static void __exit sdhci_drv_exit(void)
{
}
module_init(sdhci_drv_init);
module_exit(sdhci_drv_exit);
module_param(debug_quirks, uint, 0444);
module_param(debug_quirks2, uint, 0444);
MODULE_AUTHOR("Pierre Ossman <pierre@ossman.eu>");
MODULE_DESCRIPTION("Secure Digital Host Controller Interface core driver");
MODULE_LICENSE("GPL");
MODULE_PARM_DESC(debug_quirks, "Force certain quirks.");
MODULE_PARM_DESC(debug_quirks2, "Force certain other quirks.");
| gpl-2.0 |
dastuam/linux37-beaglebone | drivers/net/ppp/ppp_async.c | 338 | 24227 | /*
* PPP async serial channel driver for Linux.
*
* Copyright 1999 Paul Mackerras.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* This driver provides the encapsulation and framing for sending
* and receiving PPP frames over async serial lines. It relies on
* the generic PPP layer to give it frames to send and to process
* received frames. It implements the PPP line discipline.
*
* Part of the code in this driver was inspired by the old async-only
* PPP driver, written by Michael Callahan and Al Longyear, and
* subsequently hacked by Paul Mackerras.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/skbuff.h>
#include <linux/tty.h>
#include <linux/netdevice.h>
#include <linux/poll.h>
#include <linux/crc-ccitt.h>
#include <linux/ppp_defs.h>
#include <linux/ppp-ioctl.h>
#include <linux/ppp_channel.h>
#include <linux/spinlock.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/jiffies.h>
#include <linux/slab.h>
#include <asm/unaligned.h>
#include <asm/uaccess.h>
#include <asm/string.h>
#define PPP_VERSION "2.4.2"
#define OBUFSIZE 4096
/* Structure for storing local state. */
struct asyncppp {
struct tty_struct *tty;
unsigned int flags;
unsigned int state;
unsigned int rbits;
int mru;
spinlock_t xmit_lock;
spinlock_t recv_lock;
unsigned long xmit_flags;
u32 xaccm[8];
u32 raccm;
unsigned int bytes_sent;
unsigned int bytes_rcvd;
struct sk_buff *tpkt;
int tpkt_pos;
u16 tfcs;
unsigned char *optr;
unsigned char *olim;
unsigned long last_xmit;
struct sk_buff *rpkt;
int lcp_fcs;
struct sk_buff_head rqueue;
struct tasklet_struct tsk;
atomic_t refcnt;
struct semaphore dead_sem;
struct ppp_channel chan; /* interface to generic ppp layer */
unsigned char obuf[OBUFSIZE];
};
/* Bit numbers in xmit_flags */
#define XMIT_WAKEUP 0
#define XMIT_FULL 1
#define XMIT_BUSY 2
/* State bits */
#define SC_TOSS 1
#define SC_ESCAPE 2
#define SC_PREV_ERROR 4
/* Bits in rbits */
#define SC_RCV_BITS (SC_RCV_B7_1|SC_RCV_B7_0|SC_RCV_ODDP|SC_RCV_EVNP)
static int flag_time = HZ;
module_param(flag_time, int, 0);
MODULE_PARM_DESC(flag_time, "ppp_async: interval between flagged packets (in clock ticks)");
MODULE_LICENSE("GPL");
MODULE_ALIAS_LDISC(N_PPP);
/*
* Prototypes.
*/
static int ppp_async_encode(struct asyncppp *ap);
static int ppp_async_send(struct ppp_channel *chan, struct sk_buff *skb);
static int ppp_async_push(struct asyncppp *ap);
static void ppp_async_flush_output(struct asyncppp *ap);
static void ppp_async_input(struct asyncppp *ap, const unsigned char *buf,
char *flags, int count);
static int ppp_async_ioctl(struct ppp_channel *chan, unsigned int cmd,
unsigned long arg);
static void ppp_async_process(unsigned long arg);
static void async_lcp_peek(struct asyncppp *ap, unsigned char *data,
int len, int inbound);
static const struct ppp_channel_ops async_ops = {
.start_xmit = ppp_async_send,
.ioctl = ppp_async_ioctl,
};
/*
* Routines implementing the PPP line discipline.
*/
/*
* We have a potential race on dereferencing tty->disc_data,
* because the tty layer provides no locking at all - thus one
* cpu could be running ppp_asynctty_receive while another
* calls ppp_asynctty_close, which zeroes tty->disc_data and
* frees the memory that ppp_asynctty_receive is using. The best
* way to fix this is to use a rwlock in the tty struct, but for now
* we use a single global rwlock for all ttys in ppp line discipline.
*
* FIXME: this is no longer true. The _close path for the ldisc is
* now guaranteed to be sane.
*/
static DEFINE_RWLOCK(disc_data_lock);
static struct asyncppp *ap_get(struct tty_struct *tty)
{
struct asyncppp *ap;
read_lock(&disc_data_lock);
ap = tty->disc_data;
if (ap != NULL)
atomic_inc(&ap->refcnt);
read_unlock(&disc_data_lock);
return ap;
}
static void ap_put(struct asyncppp *ap)
{
if (atomic_dec_and_test(&ap->refcnt))
up(&ap->dead_sem);
}
/*
* Called when a tty is put into PPP line discipline. Called in process
* context.
*/
static int
ppp_asynctty_open(struct tty_struct *tty)
{
struct asyncppp *ap;
int err;
int speed;
if (tty->ops->write == NULL)
return -EOPNOTSUPP;
err = -ENOMEM;
ap = kzalloc(sizeof(*ap), GFP_KERNEL);
if (!ap)
goto out;
/* initialize the asyncppp structure */
ap->tty = tty;
ap->mru = PPP_MRU;
spin_lock_init(&ap->xmit_lock);
spin_lock_init(&ap->recv_lock);
ap->xaccm[0] = ~0U;
ap->xaccm[3] = 0x60000000U;
ap->raccm = ~0U;
ap->optr = ap->obuf;
ap->olim = ap->obuf;
ap->lcp_fcs = -1;
skb_queue_head_init(&ap->rqueue);
tasklet_init(&ap->tsk, ppp_async_process, (unsigned long) ap);
atomic_set(&ap->refcnt, 1);
sema_init(&ap->dead_sem, 0);
ap->chan.private = ap;
ap->chan.ops = &async_ops;
ap->chan.mtu = PPP_MRU;
speed = tty_get_baud_rate(tty);
ap->chan.speed = speed;
err = ppp_register_channel(&ap->chan);
if (err)
goto out_free;
tty->disc_data = ap;
tty->receive_room = 65536;
return 0;
out_free:
kfree(ap);
out:
return err;
}
/*
* Called when the tty is put into another line discipline
* or it hangs up. We have to wait for any cpu currently
* executing in any of the other ppp_asynctty_* routines to
* finish before we can call ppp_unregister_channel and free
* the asyncppp struct. This routine must be called from
* process context, not interrupt or softirq context.
*/
static void
ppp_asynctty_close(struct tty_struct *tty)
{
struct asyncppp *ap;
write_lock_irq(&disc_data_lock);
ap = tty->disc_data;
tty->disc_data = NULL;
write_unlock_irq(&disc_data_lock);
if (!ap)
return;
/*
* We have now ensured that nobody can start using ap from now
* on, but we have to wait for all existing users to finish.
* Note that ppp_unregister_channel ensures that no calls to
* our channel ops (i.e. ppp_async_send/ioctl) are in progress
* by the time it returns.
*/
if (!atomic_dec_and_test(&ap->refcnt))
down(&ap->dead_sem);
tasklet_kill(&ap->tsk);
ppp_unregister_channel(&ap->chan);
kfree_skb(ap->rpkt);
skb_queue_purge(&ap->rqueue);
kfree_skb(ap->tpkt);
kfree(ap);
}
/*
* Called on tty hangup in process context.
*
* Wait for I/O to driver to complete and unregister PPP channel.
* This is already done by the close routine, so just call that.
*/
static int ppp_asynctty_hangup(struct tty_struct *tty)
{
ppp_asynctty_close(tty);
return 0;
}
/*
* Read does nothing - no data is ever available this way.
* Pppd reads and writes packets via /dev/ppp instead.
*/
static ssize_t
ppp_asynctty_read(struct tty_struct *tty, struct file *file,
unsigned char __user *buf, size_t count)
{
return -EAGAIN;
}
/*
* Write on the tty does nothing, the packets all come in
* from the ppp generic stuff.
*/
static ssize_t
ppp_asynctty_write(struct tty_struct *tty, struct file *file,
const unsigned char *buf, size_t count)
{
return -EAGAIN;
}
/*
* Called in process context only. May be re-entered by multiple
* ioctl calling threads.
*/
static int
ppp_asynctty_ioctl(struct tty_struct *tty, struct file *file,
unsigned int cmd, unsigned long arg)
{
struct asyncppp *ap = ap_get(tty);
int err, val;
int __user *p = (int __user *)arg;
if (!ap)
return -ENXIO;
err = -EFAULT;
switch (cmd) {
case PPPIOCGCHAN:
err = -EFAULT;
if (put_user(ppp_channel_index(&ap->chan), p))
break;
err = 0;
break;
case PPPIOCGUNIT:
err = -EFAULT;
if (put_user(ppp_unit_number(&ap->chan), p))
break;
err = 0;
break;
case TCFLSH:
/* flush our buffers and the serial port's buffer */
if (arg == TCIOFLUSH || arg == TCOFLUSH)
ppp_async_flush_output(ap);
err = tty_perform_flush(tty, arg);
break;
case FIONREAD:
val = 0;
if (put_user(val, p))
break;
err = 0;
break;
default:
/* Try the various mode ioctls */
err = tty_mode_ioctl(tty, file, cmd, arg);
}
ap_put(ap);
return err;
}
/* No kernel lock - fine */
static unsigned int
ppp_asynctty_poll(struct tty_struct *tty, struct file *file, poll_table *wait)
{
return 0;
}
/* May sleep, don't call from interrupt level or with interrupts disabled */
static void
ppp_asynctty_receive(struct tty_struct *tty, const unsigned char *buf,
char *cflags, int count)
{
struct asyncppp *ap = ap_get(tty);
unsigned long flags;
if (!ap)
return;
spin_lock_irqsave(&ap->recv_lock, flags);
ppp_async_input(ap, buf, cflags, count);
spin_unlock_irqrestore(&ap->recv_lock, flags);
if (!skb_queue_empty(&ap->rqueue))
tasklet_schedule(&ap->tsk);
ap_put(ap);
tty_unthrottle(tty);
}
static void
ppp_asynctty_wakeup(struct tty_struct *tty)
{
struct asyncppp *ap = ap_get(tty);
clear_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
if (!ap)
return;
set_bit(XMIT_WAKEUP, &ap->xmit_flags);
tasklet_schedule(&ap->tsk);
ap_put(ap);
}
static struct tty_ldisc_ops ppp_ldisc = {
.owner = THIS_MODULE,
.magic = TTY_LDISC_MAGIC,
.name = "ppp",
.open = ppp_asynctty_open,
.close = ppp_asynctty_close,
.hangup = ppp_asynctty_hangup,
.read = ppp_asynctty_read,
.write = ppp_asynctty_write,
.ioctl = ppp_asynctty_ioctl,
.poll = ppp_asynctty_poll,
.receive_buf = ppp_asynctty_receive,
.write_wakeup = ppp_asynctty_wakeup,
};
static int __init
ppp_async_init(void)
{
int err;
err = tty_register_ldisc(N_PPP, &ppp_ldisc);
if (err != 0)
printk(KERN_ERR "PPP_async: error %d registering line disc.\n",
err);
return err;
}
/*
* The following routines provide the PPP channel interface.
*/
static int
ppp_async_ioctl(struct ppp_channel *chan, unsigned int cmd, unsigned long arg)
{
struct asyncppp *ap = chan->private;
void __user *argp = (void __user *)arg;
int __user *p = argp;
int err, val;
u32 accm[8];
err = -EFAULT;
switch (cmd) {
case PPPIOCGFLAGS:
val = ap->flags | ap->rbits;
if (put_user(val, p))
break;
err = 0;
break;
case PPPIOCSFLAGS:
if (get_user(val, p))
break;
ap->flags = val & ~SC_RCV_BITS;
spin_lock_irq(&ap->recv_lock);
ap->rbits = val & SC_RCV_BITS;
spin_unlock_irq(&ap->recv_lock);
err = 0;
break;
case PPPIOCGASYNCMAP:
if (put_user(ap->xaccm[0], (u32 __user *)argp))
break;
err = 0;
break;
case PPPIOCSASYNCMAP:
if (get_user(ap->xaccm[0], (u32 __user *)argp))
break;
err = 0;
break;
case PPPIOCGRASYNCMAP:
if (put_user(ap->raccm, (u32 __user *)argp))
break;
err = 0;
break;
case PPPIOCSRASYNCMAP:
if (get_user(ap->raccm, (u32 __user *)argp))
break;
err = 0;
break;
case PPPIOCGXASYNCMAP:
if (copy_to_user(argp, ap->xaccm, sizeof(ap->xaccm)))
break;
err = 0;
break;
case PPPIOCSXASYNCMAP:
if (copy_from_user(accm, argp, sizeof(accm)))
break;
accm[2] &= ~0x40000000U; /* can't escape 0x5e */
accm[3] |= 0x60000000U; /* must escape 0x7d, 0x7e */
memcpy(ap->xaccm, accm, sizeof(ap->xaccm));
err = 0;
break;
case PPPIOCGMRU:
if (put_user(ap->mru, p))
break;
err = 0;
break;
case PPPIOCSMRU:
if (get_user(val, p))
break;
if (val < PPP_MRU)
val = PPP_MRU;
ap->mru = val;
err = 0;
break;
default:
err = -ENOTTY;
}
return err;
}
/*
* This is called at softirq level to deliver received packets
* to the ppp_generic code, and to tell the ppp_generic code
* if we can accept more output now.
*/
static void ppp_async_process(unsigned long arg)
{
struct asyncppp *ap = (struct asyncppp *) arg;
struct sk_buff *skb;
/* process received packets */
while ((skb = skb_dequeue(&ap->rqueue)) != NULL) {
if (skb->cb[0])
ppp_input_error(&ap->chan, 0);
ppp_input(&ap->chan, skb);
}
/* try to push more stuff out */
if (test_bit(XMIT_WAKEUP, &ap->xmit_flags) && ppp_async_push(ap))
ppp_output_wakeup(&ap->chan);
}
/*
* Procedures for encapsulation and framing.
*/
/*
* Procedure to encode the data for async serial transmission.
* Does octet stuffing (escaping), puts the address/control bytes
* on if A/C compression is disabled, and does protocol compression.
* Assumes ap->tpkt != 0 on entry.
* Returns 1 if we finished the current frame, 0 otherwise.
*/
#define PUT_BYTE(ap, buf, c, islcp) do { \
if ((islcp && c < 0x20) || (ap->xaccm[c >> 5] & (1 << (c & 0x1f)))) {\
*buf++ = PPP_ESCAPE; \
*buf++ = c ^ PPP_TRANS; \
} else \
*buf++ = c; \
} while (0)
static int
ppp_async_encode(struct asyncppp *ap)
{
int fcs, i, count, c, proto;
unsigned char *buf, *buflim;
unsigned char *data;
int islcp;
buf = ap->obuf;
ap->olim = buf;
ap->optr = buf;
i = ap->tpkt_pos;
data = ap->tpkt->data;
count = ap->tpkt->len;
fcs = ap->tfcs;
proto = get_unaligned_be16(data);
/*
* LCP packets with code values between 1 (configure-reqest)
* and 7 (code-reject) must be sent as though no options
* had been negotiated.
*/
islcp = proto == PPP_LCP && 1 <= data[2] && data[2] <= 7;
if (i == 0) {
if (islcp)
async_lcp_peek(ap, data, count, 0);
/*
* Start of a new packet - insert the leading FLAG
* character if necessary.
*/
if (islcp || flag_time == 0 ||
time_after_eq(jiffies, ap->last_xmit + flag_time))
*buf++ = PPP_FLAG;
ap->last_xmit = jiffies;
fcs = PPP_INITFCS;
/*
* Put in the address/control bytes if necessary
*/
if ((ap->flags & SC_COMP_AC) == 0 || islcp) {
PUT_BYTE(ap, buf, 0xff, islcp);
fcs = PPP_FCS(fcs, 0xff);
PUT_BYTE(ap, buf, 0x03, islcp);
fcs = PPP_FCS(fcs, 0x03);
}
}
/*
* Once we put in the last byte, we need to put in the FCS
* and closing flag, so make sure there is at least 7 bytes
* of free space in the output buffer.
*/
buflim = ap->obuf + OBUFSIZE - 6;
while (i < count && buf < buflim) {
c = data[i++];
if (i == 1 && c == 0 && (ap->flags & SC_COMP_PROT))
continue; /* compress protocol field */
fcs = PPP_FCS(fcs, c);
PUT_BYTE(ap, buf, c, islcp);
}
if (i < count) {
/*
* Remember where we are up to in this packet.
*/
ap->olim = buf;
ap->tpkt_pos = i;
ap->tfcs = fcs;
return 0;
}
/*
* We have finished the packet. Add the FCS and flag.
*/
fcs = ~fcs;
c = fcs & 0xff;
PUT_BYTE(ap, buf, c, islcp);
c = (fcs >> 8) & 0xff;
PUT_BYTE(ap, buf, c, islcp);
*buf++ = PPP_FLAG;
ap->olim = buf;
consume_skb(ap->tpkt);
ap->tpkt = NULL;
return 1;
}
/*
* Transmit-side routines.
*/
/*
* Send a packet to the peer over an async tty line.
* Returns 1 iff the packet was accepted.
* If the packet was not accepted, we will call ppp_output_wakeup
* at some later time.
*/
static int
ppp_async_send(struct ppp_channel *chan, struct sk_buff *skb)
{
struct asyncppp *ap = chan->private;
ppp_async_push(ap);
if (test_and_set_bit(XMIT_FULL, &ap->xmit_flags))
return 0; /* already full */
ap->tpkt = skb;
ap->tpkt_pos = 0;
ppp_async_push(ap);
return 1;
}
/*
* Push as much data as possible out to the tty.
*/
static int
ppp_async_push(struct asyncppp *ap)
{
int avail, sent, done = 0;
struct tty_struct *tty = ap->tty;
int tty_stuffed = 0;
/*
* We can get called recursively here if the tty write
* function calls our wakeup function. This can happen
* for example on a pty with both the master and slave
* set to PPP line discipline.
* We use the XMIT_BUSY bit to detect this and get out,
* leaving the XMIT_WAKEUP bit set to tell the other
* instance that it may now be able to write more now.
*/
if (test_and_set_bit(XMIT_BUSY, &ap->xmit_flags))
return 0;
spin_lock_bh(&ap->xmit_lock);
for (;;) {
if (test_and_clear_bit(XMIT_WAKEUP, &ap->xmit_flags))
tty_stuffed = 0;
if (!tty_stuffed && ap->optr < ap->olim) {
avail = ap->olim - ap->optr;
set_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
sent = tty->ops->write(tty, ap->optr, avail);
if (sent < 0)
goto flush; /* error, e.g. loss of CD */
ap->optr += sent;
if (sent < avail)
tty_stuffed = 1;
continue;
}
if (ap->optr >= ap->olim && ap->tpkt) {
if (ppp_async_encode(ap)) {
/* finished processing ap->tpkt */
clear_bit(XMIT_FULL, &ap->xmit_flags);
done = 1;
}
continue;
}
/*
* We haven't made any progress this time around.
* Clear XMIT_BUSY to let other callers in, but
* after doing so we have to check if anyone set
* XMIT_WAKEUP since we last checked it. If they
* did, we should try again to set XMIT_BUSY and go
* around again in case XMIT_BUSY was still set when
* the other caller tried.
*/
clear_bit(XMIT_BUSY, &ap->xmit_flags);
/* any more work to do? if not, exit the loop */
if (!(test_bit(XMIT_WAKEUP, &ap->xmit_flags) ||
(!tty_stuffed && ap->tpkt)))
break;
/* more work to do, see if we can do it now */
if (test_and_set_bit(XMIT_BUSY, &ap->xmit_flags))
break;
}
spin_unlock_bh(&ap->xmit_lock);
return done;
flush:
clear_bit(XMIT_BUSY, &ap->xmit_flags);
if (ap->tpkt) {
kfree_skb(ap->tpkt);
ap->tpkt = NULL;
clear_bit(XMIT_FULL, &ap->xmit_flags);
done = 1;
}
ap->optr = ap->olim;
spin_unlock_bh(&ap->xmit_lock);
return done;
}
/*
* Flush output from our internal buffers.
* Called for the TCFLSH ioctl. Can be entered in parallel
* but this is covered by the xmit_lock.
*/
static void
ppp_async_flush_output(struct asyncppp *ap)
{
int done = 0;
spin_lock_bh(&ap->xmit_lock);
ap->optr = ap->olim;
if (ap->tpkt != NULL) {
kfree_skb(ap->tpkt);
ap->tpkt = NULL;
clear_bit(XMIT_FULL, &ap->xmit_flags);
done = 1;
}
spin_unlock_bh(&ap->xmit_lock);
if (done)
ppp_output_wakeup(&ap->chan);
}
/*
* Receive-side routines.
*/
/* see how many ordinary chars there are at the start of buf */
static inline int
scan_ordinary(struct asyncppp *ap, const unsigned char *buf, int count)
{
int i, c;
for (i = 0; i < count; ++i) {
c = buf[i];
if (c == PPP_ESCAPE || c == PPP_FLAG ||
(c < 0x20 && (ap->raccm & (1 << c)) != 0))
break;
}
return i;
}
/* called when a flag is seen - do end-of-packet processing */
static void
process_input_packet(struct asyncppp *ap)
{
struct sk_buff *skb;
unsigned char *p;
unsigned int len, fcs, proto;
skb = ap->rpkt;
if (ap->state & (SC_TOSS | SC_ESCAPE))
goto err;
if (skb == NULL)
return; /* 0-length packet */
/* check the FCS */
p = skb->data;
len = skb->len;
if (len < 3)
goto err; /* too short */
fcs = PPP_INITFCS;
for (; len > 0; --len)
fcs = PPP_FCS(fcs, *p++);
if (fcs != PPP_GOODFCS)
goto err; /* bad FCS */
skb_trim(skb, skb->len - 2);
/* check for address/control and protocol compression */
p = skb->data;
if (p[0] == PPP_ALLSTATIONS) {
/* chop off address/control */
if (p[1] != PPP_UI || skb->len < 3)
goto err;
p = skb_pull(skb, 2);
}
proto = p[0];
if (proto & 1) {
/* protocol is compressed */
skb_push(skb, 1)[0] = 0;
} else {
if (skb->len < 2)
goto err;
proto = (proto << 8) + p[1];
if (proto == PPP_LCP)
async_lcp_peek(ap, p, skb->len, 1);
}
/* queue the frame to be processed */
skb->cb[0] = ap->state;
skb_queue_tail(&ap->rqueue, skb);
ap->rpkt = NULL;
ap->state = 0;
return;
err:
/* frame had an error, remember that, reset SC_TOSS & SC_ESCAPE */
ap->state = SC_PREV_ERROR;
if (skb) {
/* make skb appear as freshly allocated */
skb_trim(skb, 0);
skb_reserve(skb, - skb_headroom(skb));
}
}
/* Called when the tty driver has data for us. Runs parallel with the
other ldisc functions but will not be re-entered */
static void
ppp_async_input(struct asyncppp *ap, const unsigned char *buf,
char *flags, int count)
{
struct sk_buff *skb;
int c, i, j, n, s, f;
unsigned char *sp;
/* update bits used for 8-bit cleanness detection */
if (~ap->rbits & SC_RCV_BITS) {
s = 0;
for (i = 0; i < count; ++i) {
c = buf[i];
if (flags && flags[i] != 0)
continue;
s |= (c & 0x80)? SC_RCV_B7_1: SC_RCV_B7_0;
c = ((c >> 4) ^ c) & 0xf;
s |= (0x6996 & (1 << c))? SC_RCV_ODDP: SC_RCV_EVNP;
}
ap->rbits |= s;
}
while (count > 0) {
/* scan through and see how many chars we can do in bulk */
if ((ap->state & SC_ESCAPE) && buf[0] == PPP_ESCAPE)
n = 1;
else
n = scan_ordinary(ap, buf, count);
f = 0;
if (flags && (ap->state & SC_TOSS) == 0) {
/* check the flags to see if any char had an error */
for (j = 0; j < n; ++j)
if ((f = flags[j]) != 0)
break;
}
if (f != 0) {
/* start tossing */
ap->state |= SC_TOSS;
} else if (n > 0 && (ap->state & SC_TOSS) == 0) {
/* stuff the chars in the skb */
skb = ap->rpkt;
if (!skb) {
skb = dev_alloc_skb(ap->mru + PPP_HDRLEN + 2);
if (!skb)
goto nomem;
ap->rpkt = skb;
}
if (skb->len == 0) {
/* Try to get the payload 4-byte aligned.
* This should match the
* PPP_ALLSTATIONS/PPP_UI/compressed tests in
* process_input_packet, but we do not have
* enough chars here to test buf[1] and buf[2].
*/
if (buf[0] != PPP_ALLSTATIONS)
skb_reserve(skb, 2 + (buf[0] & 1));
}
if (n > skb_tailroom(skb)) {
/* packet overflowed MRU */
ap->state |= SC_TOSS;
} else {
sp = skb_put(skb, n);
memcpy(sp, buf, n);
if (ap->state & SC_ESCAPE) {
sp[0] ^= PPP_TRANS;
ap->state &= ~SC_ESCAPE;
}
}
}
if (n >= count)
break;
c = buf[n];
if (flags != NULL && flags[n] != 0) {
ap->state |= SC_TOSS;
} else if (c == PPP_FLAG) {
process_input_packet(ap);
} else if (c == PPP_ESCAPE) {
ap->state |= SC_ESCAPE;
} else if (I_IXON(ap->tty)) {
if (c == START_CHAR(ap->tty))
start_tty(ap->tty);
else if (c == STOP_CHAR(ap->tty))
stop_tty(ap->tty);
}
/* otherwise it's a char in the recv ACCM */
++n;
buf += n;
if (flags)
flags += n;
count -= n;
}
return;
nomem:
printk(KERN_ERR "PPPasync: no memory (input pkt)\n");
ap->state |= SC_TOSS;
}
/*
* We look at LCP frames going past so that we can notice
* and react to the LCP configure-ack from the peer.
* In the situation where the peer has been sent a configure-ack
* already, LCP is up once it has sent its configure-ack
* so the immediately following packet can be sent with the
* configured LCP options. This allows us to process the following
* packet correctly without pppd needing to respond quickly.
*
* We only respond to the received configure-ack if we have just
* sent a configure-request, and the configure-ack contains the
* same data (this is checked using a 16-bit crc of the data).
*/
#define CONFREQ 1 /* LCP code field values */
#define CONFACK 2
#define LCP_MRU 1 /* LCP option numbers */
#define LCP_ASYNCMAP 2
static void async_lcp_peek(struct asyncppp *ap, unsigned char *data,
int len, int inbound)
{
int dlen, fcs, i, code;
u32 val;
data += 2; /* skip protocol bytes */
len -= 2;
if (len < 4) /* 4 = code, ID, length */
return;
code = data[0];
if (code != CONFACK && code != CONFREQ)
return;
dlen = get_unaligned_be16(data + 2);
if (len < dlen)
return; /* packet got truncated or length is bogus */
if (code == (inbound? CONFACK: CONFREQ)) {
/*
* sent confreq or received confack:
* calculate the crc of the data from the ID field on.
*/
fcs = PPP_INITFCS;
for (i = 1; i < dlen; ++i)
fcs = PPP_FCS(fcs, data[i]);
if (!inbound) {
/* outbound confreq - remember the crc for later */
ap->lcp_fcs = fcs;
return;
}
/* received confack, check the crc */
fcs ^= ap->lcp_fcs;
ap->lcp_fcs = -1;
if (fcs != 0)
return;
} else if (inbound)
return; /* not interested in received confreq */
/* process the options in the confack */
data += 4;
dlen -= 4;
/* data[0] is code, data[1] is length */
while (dlen >= 2 && dlen >= data[1] && data[1] >= 2) {
switch (data[0]) {
case LCP_MRU:
val = get_unaligned_be16(data + 2);
if (inbound)
ap->mru = val;
else
ap->chan.mtu = val;
break;
case LCP_ASYNCMAP:
val = get_unaligned_be32(data + 2);
if (inbound)
ap->raccm = val;
else
ap->xaccm[0] = val;
break;
}
dlen -= data[1];
data += data[1];
}
}
static void __exit ppp_async_cleanup(void)
{
if (tty_unregister_ldisc(N_PPP) != 0)
printk(KERN_ERR "failed to unregister PPP line discipline\n");
}
module_init(ppp_async_init);
module_exit(ppp_async_cleanup);
| gpl-2.0 |
nagataka/linux-2.6.32.65 | arch/arm/mach-ep93xx/adssphere.c | 594 | 1666 | /*
* arch/arm/mach-ep93xx/adssphere.c
* ADS Sphere support.
*
* Copyright (C) 2006 Lennert Buytenhek <buytenh@wantstofly.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/mtd/physmap.h>
#include <mach/hardware.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
static struct physmap_flash_data adssphere_flash_data = {
.width = 4,
};
static struct resource adssphere_flash_resource = {
.start = EP93XX_CS6_PHYS_BASE,
.end = EP93XX_CS6_PHYS_BASE + SZ_32M - 1,
.flags = IORESOURCE_MEM,
};
static struct platform_device adssphere_flash = {
.name = "physmap-flash",
.id = 0,
.dev = {
.platform_data = &adssphere_flash_data,
},
.num_resources = 1,
.resource = &adssphere_flash_resource,
};
static struct ep93xx_eth_data adssphere_eth_data = {
.phy_id = 1,
};
static void __init adssphere_init_machine(void)
{
ep93xx_init_devices();
platform_device_register(&adssphere_flash);
ep93xx_register_eth(&adssphere_eth_data, 1);
}
MACHINE_START(ADSSPHERE, "ADS Sphere board")
/* Maintainer: Lennert Buytenhek <buytenh@wantstofly.org> */
.phys_io = EP93XX_APB_PHYS_BASE,
.io_pg_offst = ((EP93XX_APB_VIRT_BASE) >> 18) & 0xfffc,
.boot_params = EP93XX_SDCE3_PHYS_BASE_SYNC + 0x100,
.map_io = ep93xx_map_io,
.init_irq = ep93xx_init_irq,
.timer = &ep93xx_timer,
.init_machine = adssphere_init_machine,
MACHINE_END
| gpl-2.0 |
gauravdatir/linux | arch/mips/sgi-ip27/ip27-irq.c | 850 | 5637 | /*
* ip27-irq.c: Highlevel interrupt handling for IP27 architecture.
*
* Copyright (C) 1999, 2000 Ralf Baechle (ralf@gnu.org)
* Copyright (C) 1999, 2000 Silicon Graphics, Inc.
* Copyright (C) 1999 - 2001 Kanoj Sarcar
*/
#undef DEBUG
#include <linux/init.h>
#include <linux/irq.h>
#include <linux/errno.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/types.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/timex.h>
#include <linux/smp.h>
#include <linux/random.h>
#include <linux/kernel.h>
#include <linux/kernel_stat.h>
#include <linux/delay.h>
#include <linux/bitops.h>
#include <asm/bootinfo.h>
#include <asm/io.h>
#include <asm/mipsregs.h>
#include <asm/processor.h>
#include <asm/sn/addrs.h>
#include <asm/sn/agent.h>
#include <asm/sn/arch.h>
#include <asm/sn/hub.h>
#include <asm/sn/intr.h>
/*
* Linux has a controller-independent x86 interrupt architecture.
* every controller has a 'controller-template', that is used
* by the main code to do the right thing. Each driver-visible
* interrupt source is transparently wired to the appropriate
* controller. Thus drivers need not be aware of the
* interrupt-controller.
*
* Various interrupt controllers we handle: 8259 PIC, SMP IO-APIC,
* PIIX4's internal 8259 PIC and SGI's Visual Workstation Cobalt (IO-)APIC.
* (IO-APICs assumed to be messaging to Pentium local-APICs)
*
* the code is designed to be easily extended with new/different
* interrupt controllers, without having to do assembly magic.
*/
extern asmlinkage void ip27_irq(void);
/*
* Find first bit set
*/
static int ms1bit(unsigned long x)
{
int b = 0, s;
s = 16; if (x >> 16 == 0) s = 0; b += s; x >>= s;
s = 8; if (x >> 8 == 0) s = 0; b += s; x >>= s;
s = 4; if (x >> 4 == 0) s = 0; b += s; x >>= s;
s = 2; if (x >> 2 == 0) s = 0; b += s; x >>= s;
s = 1; if (x >> 1 == 0) s = 0; b += s;
return b;
}
/*
* This code is unnecessarily complex, because we do
* intr enabling. Basically, once we grab the set of intrs we need
* to service, we must mask _all_ these interrupts; firstly, to make
* sure the same intr does not intr again, causing recursion that
* can lead to stack overflow. Secondly, we can not just mask the
* one intr we are do_IRQing, because the non-masked intrs in the
* first set might intr again, causing multiple servicings of the
* same intr. This effect is mostly seen for intercpu intrs.
* Kanoj 05.13.00
*/
static void ip27_do_irq_mask0(void)
{
int irq, swlevel;
hubreg_t pend0, mask0;
cpuid_t cpu = smp_processor_id();
int pi_int_mask0 =
(cputoslice(cpu) == 0) ? PI_INT_MASK0_A : PI_INT_MASK0_B;
/* copied from Irix intpend0() */
pend0 = LOCAL_HUB_L(PI_INT_PEND0);
mask0 = LOCAL_HUB_L(pi_int_mask0);
pend0 &= mask0; /* Pick intrs we should look at */
if (!pend0)
return;
swlevel = ms1bit(pend0);
#ifdef CONFIG_SMP
if (pend0 & (1UL << CPU_RESCHED_A_IRQ)) {
LOCAL_HUB_CLR_INTR(CPU_RESCHED_A_IRQ);
scheduler_ipi();
} else if (pend0 & (1UL << CPU_RESCHED_B_IRQ)) {
LOCAL_HUB_CLR_INTR(CPU_RESCHED_B_IRQ);
scheduler_ipi();
} else if (pend0 & (1UL << CPU_CALL_A_IRQ)) {
LOCAL_HUB_CLR_INTR(CPU_CALL_A_IRQ);
irq_enter();
generic_smp_call_function_interrupt();
irq_exit();
} else if (pend0 & (1UL << CPU_CALL_B_IRQ)) {
LOCAL_HUB_CLR_INTR(CPU_CALL_B_IRQ);
irq_enter();
generic_smp_call_function_interrupt();
irq_exit();
} else
#endif
{
/* "map" swlevel to irq */
struct slice_data *si = cpu_data[cpu].data;
irq = si->level_to_irq[swlevel];
do_IRQ(irq);
}
LOCAL_HUB_L(PI_INT_PEND0);
}
static void ip27_do_irq_mask1(void)
{
int irq, swlevel;
hubreg_t pend1, mask1;
cpuid_t cpu = smp_processor_id();
int pi_int_mask1 = (cputoslice(cpu) == 0) ? PI_INT_MASK1_A : PI_INT_MASK1_B;
struct slice_data *si = cpu_data[cpu].data;
/* copied from Irix intpend0() */
pend1 = LOCAL_HUB_L(PI_INT_PEND1);
mask1 = LOCAL_HUB_L(pi_int_mask1);
pend1 &= mask1; /* Pick intrs we should look at */
if (!pend1)
return;
swlevel = ms1bit(pend1);
/* "map" swlevel to irq */
irq = si->level_to_irq[swlevel];
LOCAL_HUB_CLR_INTR(swlevel);
do_IRQ(irq);
LOCAL_HUB_L(PI_INT_PEND1);
}
static void ip27_prof_timer(void)
{
panic("CPU %d got a profiling interrupt", smp_processor_id());
}
static void ip27_hub_error(void)
{
panic("CPU %d got a hub error interrupt", smp_processor_id());
}
asmlinkage void plat_irq_dispatch(void)
{
unsigned long pending = read_c0_cause() & read_c0_status();
extern unsigned int rt_timer_irq;
if (pending & CAUSEF_IP4)
do_IRQ(rt_timer_irq);
else if (pending & CAUSEF_IP2) /* PI_INT_PEND_0 or CC_PEND_{A|B} */
ip27_do_irq_mask0();
else if (pending & CAUSEF_IP3) /* PI_INT_PEND_1 */
ip27_do_irq_mask1();
else if (pending & CAUSEF_IP5)
ip27_prof_timer();
else if (pending & CAUSEF_IP6)
ip27_hub_error();
}
void __init arch_init_irq(void)
{
}
void install_ipi(void)
{
int slice = LOCAL_HUB_L(PI_CPU_NUM);
int cpu = smp_processor_id();
struct slice_data *si = cpu_data[cpu].data;
struct hub_data *hub = hub_data(cpu_to_node(cpu));
int resched, call;
resched = CPU_RESCHED_A_IRQ + slice;
__set_bit(resched, hub->irq_alloc_mask);
__set_bit(resched, si->irq_enable_mask);
LOCAL_HUB_CLR_INTR(resched);
call = CPU_CALL_A_IRQ + slice;
__set_bit(call, hub->irq_alloc_mask);
__set_bit(call, si->irq_enable_mask);
LOCAL_HUB_CLR_INTR(call);
if (slice == 0) {
LOCAL_HUB_S(PI_INT_MASK0_A, si->irq_enable_mask[0]);
LOCAL_HUB_S(PI_INT_MASK1_A, si->irq_enable_mask[1]);
} else {
LOCAL_HUB_S(PI_INT_MASK0_B, si->irq_enable_mask[0]);
LOCAL_HUB_S(PI_INT_MASK1_B, si->irq_enable_mask[1]);
}
}
| gpl-2.0 |
Quarx2k/msm8260_kernel_fly_iq285 | drivers/net/ixgbevf/vf.c | 850 | 11525 | /*******************************************************************************
Intel 82599 Virtual Function driver
Copyright(c) 1999 - 2009 Intel Corporation.
This program is free software; you can redistribute it and/or modify it
under the terms and conditions of the GNU General Public License,
version 2, as published by the Free Software Foundation.
This program is distributed in the hope it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
Contact Information:
e1000-devel Mailing List <e1000-devel@lists.sourceforge.net>
Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*******************************************************************************/
#include "vf.h"
/**
* ixgbevf_start_hw_vf - Prepare hardware for Tx/Rx
* @hw: pointer to hardware structure
*
* Starts the hardware by filling the bus info structure and media type, clears
* all on chip counters, initializes receive address registers, multicast
* table, VLAN filter table, calls routine to set up link and flow control
* settings, and leaves transmit and receive units disabled and uninitialized
**/
static s32 ixgbevf_start_hw_vf(struct ixgbe_hw *hw)
{
/* Clear adapter stopped flag */
hw->adapter_stopped = false;
return 0;
}
/**
* ixgbevf_init_hw_vf - virtual function hardware initialization
* @hw: pointer to hardware structure
*
* Initialize the hardware by resetting the hardware and then starting
* the hardware
**/
static s32 ixgbevf_init_hw_vf(struct ixgbe_hw *hw)
{
s32 status = hw->mac.ops.start_hw(hw);
hw->mac.ops.get_mac_addr(hw, hw->mac.addr);
return status;
}
/**
* ixgbevf_reset_hw_vf - Performs hardware reset
* @hw: pointer to hardware structure
*
* Resets the hardware by reseting the transmit and receive units, masks and
* clears all interrupts.
**/
static s32 ixgbevf_reset_hw_vf(struct ixgbe_hw *hw)
{
struct ixgbe_mbx_info *mbx = &hw->mbx;
u32 timeout = IXGBE_VF_INIT_TIMEOUT;
s32 ret_val = IXGBE_ERR_INVALID_MAC_ADDR;
u32 msgbuf[IXGBE_VF_PERMADDR_MSG_LEN];
u8 *addr = (u8 *)(&msgbuf[1]);
/* Call adapter stop to disable tx/rx and clear interrupts */
hw->mac.ops.stop_adapter(hw);
IXGBE_WRITE_REG(hw, IXGBE_VFCTRL, IXGBE_CTRL_RST);
IXGBE_WRITE_FLUSH(hw);
/* we cannot reset while the RSTI / RSTD bits are asserted */
while (!mbx->ops.check_for_rst(hw) && timeout) {
timeout--;
udelay(5);
}
if (!timeout)
return IXGBE_ERR_RESET_FAILED;
/* mailbox timeout can now become active */
mbx->timeout = IXGBE_VF_MBX_INIT_TIMEOUT;
msgbuf[0] = IXGBE_VF_RESET;
mbx->ops.write_posted(hw, msgbuf, 1);
msleep(10);
/* set our "perm_addr" based on info provided by PF */
/* also set up the mc_filter_type which is piggy backed
* on the mac address in word 3 */
ret_val = mbx->ops.read_posted(hw, msgbuf, IXGBE_VF_PERMADDR_MSG_LEN);
if (ret_val)
return ret_val;
if (msgbuf[0] != (IXGBE_VF_RESET | IXGBE_VT_MSGTYPE_ACK))
return IXGBE_ERR_INVALID_MAC_ADDR;
memcpy(hw->mac.perm_addr, addr, IXGBE_ETH_LENGTH_OF_ADDRESS);
hw->mac.mc_filter_type = msgbuf[IXGBE_VF_MC_TYPE_WORD];
return 0;
}
/**
* ixgbevf_stop_hw_vf - Generic stop Tx/Rx units
* @hw: pointer to hardware structure
*
* Sets the adapter_stopped flag within ixgbe_hw struct. Clears interrupts,
* disables transmit and receive units. The adapter_stopped flag is used by
* the shared code and drivers to determine if the adapter is in a stopped
* state and should not touch the hardware.
**/
static s32 ixgbevf_stop_hw_vf(struct ixgbe_hw *hw)
{
u32 number_of_queues;
u32 reg_val;
u16 i;
/*
* Set the adapter_stopped flag so other driver functions stop touching
* the hardware
*/
hw->adapter_stopped = true;
/* Disable the receive unit by stopped each queue */
number_of_queues = hw->mac.max_rx_queues;
for (i = 0; i < number_of_queues; i++) {
reg_val = IXGBE_READ_REG(hw, IXGBE_VFRXDCTL(i));
if (reg_val & IXGBE_RXDCTL_ENABLE) {
reg_val &= ~IXGBE_RXDCTL_ENABLE;
IXGBE_WRITE_REG(hw, IXGBE_VFRXDCTL(i), reg_val);
}
}
IXGBE_WRITE_FLUSH(hw);
/* Clear interrupt mask to stop from interrupts being generated */
IXGBE_WRITE_REG(hw, IXGBE_VTEIMC, IXGBE_VF_IRQ_CLEAR_MASK);
/* Clear any pending interrupts */
IXGBE_READ_REG(hw, IXGBE_VTEICR);
/* Disable the transmit unit. Each queue must be disabled. */
number_of_queues = hw->mac.max_tx_queues;
for (i = 0; i < number_of_queues; i++) {
reg_val = IXGBE_READ_REG(hw, IXGBE_VFTXDCTL(i));
if (reg_val & IXGBE_TXDCTL_ENABLE) {
reg_val &= ~IXGBE_TXDCTL_ENABLE;
IXGBE_WRITE_REG(hw, IXGBE_VFTXDCTL(i), reg_val);
}
}
return 0;
}
/**
* ixgbevf_mta_vector - Determines bit-vector in multicast table to set
* @hw: pointer to hardware structure
* @mc_addr: the multicast address
*
* Extracts the 12 bits, from a multicast address, to determine which
* bit-vector to set in the multicast table. The hardware uses 12 bits, from
* incoming rx multicast addresses, to determine the bit-vector to check in
* the MTA. Which of the 4 combination, of 12-bits, the hardware uses is set
* by the MO field of the MCSTCTRL. The MO field is set during initialization
* to mc_filter_type.
**/
static s32 ixgbevf_mta_vector(struct ixgbe_hw *hw, u8 *mc_addr)
{
u32 vector = 0;
switch (hw->mac.mc_filter_type) {
case 0: /* use bits [47:36] of the address */
vector = ((mc_addr[4] >> 4) | (((u16)mc_addr[5]) << 4));
break;
case 1: /* use bits [46:35] of the address */
vector = ((mc_addr[4] >> 3) | (((u16)mc_addr[5]) << 5));
break;
case 2: /* use bits [45:34] of the address */
vector = ((mc_addr[4] >> 2) | (((u16)mc_addr[5]) << 6));
break;
case 3: /* use bits [43:32] of the address */
vector = ((mc_addr[4]) | (((u16)mc_addr[5]) << 8));
break;
default: /* Invalid mc_filter_type */
break;
}
/* vector can only be 12-bits or boundary will be exceeded */
vector &= 0xFFF;
return vector;
}
/**
* ixgbevf_get_mac_addr_vf - Read device MAC address
* @hw: pointer to the HW structure
* @mac_addr: pointer to storage for retrieved MAC address
**/
static s32 ixgbevf_get_mac_addr_vf(struct ixgbe_hw *hw, u8 *mac_addr)
{
memcpy(mac_addr, hw->mac.perm_addr, IXGBE_ETH_LENGTH_OF_ADDRESS);
return 0;
}
/**
* ixgbevf_set_rar_vf - set device MAC address
* @hw: pointer to hardware structure
* @index: Receive address register to write
* @addr: Address to put into receive address register
* @vmdq: Unused in this implementation
**/
static s32 ixgbevf_set_rar_vf(struct ixgbe_hw *hw, u32 index, u8 *addr,
u32 vmdq)
{
struct ixgbe_mbx_info *mbx = &hw->mbx;
u32 msgbuf[3];
u8 *msg_addr = (u8 *)(&msgbuf[1]);
s32 ret_val;
memset(msgbuf, 0, sizeof(msgbuf));
msgbuf[0] = IXGBE_VF_SET_MAC_ADDR;
memcpy(msg_addr, addr, 6);
ret_val = mbx->ops.write_posted(hw, msgbuf, 3);
if (!ret_val)
ret_val = mbx->ops.read_posted(hw, msgbuf, 3);
msgbuf[0] &= ~IXGBE_VT_MSGTYPE_CTS;
/* if nacked the address was rejected, use "perm_addr" */
if (!ret_val &&
(msgbuf[0] == (IXGBE_VF_SET_MAC_ADDR | IXGBE_VT_MSGTYPE_NACK)))
ixgbevf_get_mac_addr_vf(hw, hw->mac.addr);
return ret_val;
}
/**
* ixgbevf_update_mc_addr_list_vf - Update Multicast addresses
* @hw: pointer to the HW structure
* @netdev: pointer to net device structure
*
* Updates the Multicast Table Array.
**/
static s32 ixgbevf_update_mc_addr_list_vf(struct ixgbe_hw *hw,
struct net_device *netdev)
{
struct netdev_hw_addr *ha;
struct ixgbe_mbx_info *mbx = &hw->mbx;
u32 msgbuf[IXGBE_VFMAILBOX_SIZE];
u16 *vector_list = (u16 *)&msgbuf[1];
u32 cnt, i;
/* Each entry in the list uses 1 16 bit word. We have 30
* 16 bit words available in our HW msg buffer (minus 1 for the
* msg type). That's 30 hash values if we pack 'em right. If
* there are more than 30 MC addresses to add then punt the
* extras for now and then add code to handle more than 30 later.
* It would be unusual for a server to request that many multi-cast
* addresses except for in large enterprise network environments.
*/
cnt = netdev_mc_count(netdev);
if (cnt > 30)
cnt = 30;
msgbuf[0] = IXGBE_VF_SET_MULTICAST;
msgbuf[0] |= cnt << IXGBE_VT_MSGINFO_SHIFT;
i = 0;
netdev_for_each_mc_addr(ha, netdev) {
if (i == cnt)
break;
vector_list[i++] = ixgbevf_mta_vector(hw, ha->addr);
}
mbx->ops.write_posted(hw, msgbuf, IXGBE_VFMAILBOX_SIZE);
return 0;
}
/**
* ixgbevf_set_vfta_vf - Set/Unset vlan filter table address
* @hw: pointer to the HW structure
* @vlan: 12 bit VLAN ID
* @vind: unused by VF drivers
* @vlan_on: if true then set bit, else clear bit
**/
static s32 ixgbevf_set_vfta_vf(struct ixgbe_hw *hw, u32 vlan, u32 vind,
bool vlan_on)
{
struct ixgbe_mbx_info *mbx = &hw->mbx;
u32 msgbuf[2];
msgbuf[0] = IXGBE_VF_SET_VLAN;
msgbuf[1] = vlan;
/* Setting the 8 bit field MSG INFO to TRUE indicates "add" */
msgbuf[0] |= vlan_on << IXGBE_VT_MSGINFO_SHIFT;
return mbx->ops.write_posted(hw, msgbuf, 2);
}
/**
* ixgbevf_setup_mac_link_vf - Setup MAC link settings
* @hw: pointer to hardware structure
* @speed: Unused in this implementation
* @autoneg: Unused in this implementation
* @autoneg_wait_to_complete: Unused in this implementation
*
* Do nothing and return success. VF drivers are not allowed to change
* global settings. Maintained for driver compatibility.
**/
static s32 ixgbevf_setup_mac_link_vf(struct ixgbe_hw *hw,
ixgbe_link_speed speed, bool autoneg,
bool autoneg_wait_to_complete)
{
return 0;
}
/**
* ixgbevf_check_mac_link_vf - Get link/speed status
* @hw: pointer to hardware structure
* @speed: pointer to link speed
* @link_up: true is link is up, false otherwise
* @autoneg_wait_to_complete: true when waiting for completion is needed
*
* Reads the links register to determine if link is up and the current speed
**/
static s32 ixgbevf_check_mac_link_vf(struct ixgbe_hw *hw,
ixgbe_link_speed *speed,
bool *link_up,
bool autoneg_wait_to_complete)
{
u32 links_reg;
if (!(hw->mbx.ops.check_for_rst(hw))) {
*link_up = false;
*speed = 0;
return -1;
}
links_reg = IXGBE_READ_REG(hw, IXGBE_VFLINKS);
if (links_reg & IXGBE_LINKS_UP)
*link_up = true;
else
*link_up = false;
if ((links_reg & IXGBE_LINKS_SPEED_82599) ==
IXGBE_LINKS_SPEED_10G_82599)
*speed = IXGBE_LINK_SPEED_10GB_FULL;
else
*speed = IXGBE_LINK_SPEED_1GB_FULL;
return 0;
}
struct ixgbe_mac_operations ixgbevf_mac_ops = {
.init_hw = ixgbevf_init_hw_vf,
.reset_hw = ixgbevf_reset_hw_vf,
.start_hw = ixgbevf_start_hw_vf,
.get_mac_addr = ixgbevf_get_mac_addr_vf,
.stop_adapter = ixgbevf_stop_hw_vf,
.setup_link = ixgbevf_setup_mac_link_vf,
.check_link = ixgbevf_check_mac_link_vf,
.set_rar = ixgbevf_set_rar_vf,
.update_mc_addr_list = ixgbevf_update_mc_addr_list_vf,
.set_vfta = ixgbevf_set_vfta_vf,
};
struct ixgbevf_info ixgbevf_vf_info = {
.mac = ixgbe_mac_82599_vf,
.mac_ops = &ixgbevf_mac_ops,
};
| gpl-2.0 |
TeamWin/PoonSense-2.3.3 | drivers/staging/go7007/wis-sony-tuner.c | 850 | 18600 | /*
* Copyright (C) 2005-2006 Micronas USA Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License (Version 2) as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, USA.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/i2c.h>
#include <linux/videodev2.h>
#include <linux/slab.h>
#include <media/tuner.h>
#include <media/v4l2-common.h>
#include <media/v4l2-ioctl.h>
#include "wis-i2c.h"
/* #define MPX_DEBUG */
/* AS(IF/MPX) pin: LOW HIGH/OPEN
* IF/MPX address: 0x42/0x40 0x43/0x44
*/
#define IF_I2C_ADDR 0x43
#define MPX_I2C_ADDR 0x44
static v4l2_std_id force_band;
static char force_band_str[] = "-";
module_param_string(force_band, force_band_str, sizeof(force_band_str), 0644);
static int force_mpx_mode = -1;
module_param(force_mpx_mode, int, 0644);
/* Store tuner info in the same format as tuner.c, so maybe we can put the
* Sony tuner support in there. */
struct sony_tunertype {
char *name;
unsigned char Vendor; /* unused here */
unsigned char Type; /* unused here */
unsigned short thresh1; /* band switch VHF_LO <=> VHF_HI */
unsigned short thresh2; /* band switch VHF_HI <=> UHF */
unsigned char VHF_L;
unsigned char VHF_H;
unsigned char UHF;
unsigned char config;
unsigned short IFPCoff;
};
/* This array is indexed by (tuner_type - 200) */
static struct sony_tunertype sony_tuners[] = {
{ "Sony PAL+SECAM (BTF-PG472Z)", 0, 0,
16*144.25, 16*427.25, 0x01, 0x02, 0x04, 0xc6, 623},
{ "Sony NTSC_JP (BTF-PK467Z)", 0, 0,
16*220.25, 16*467.25, 0x01, 0x02, 0x04, 0xc6, 940},
{ "Sony NTSC (BTF-PB463Z)", 0, 0,
16*130.25, 16*364.25, 0x01, 0x02, 0x04, 0xc6, 732},
};
struct wis_sony_tuner {
int type;
v4l2_std_id std;
unsigned int freq;
int mpxmode;
u32 audmode;
};
/* Basically the same as default_set_tv_freq() in tuner.c */
static int set_freq(struct i2c_client *client, int freq)
{
struct wis_sony_tuner *t = i2c_get_clientdata(client);
char *band_name;
int n;
int band_select;
struct sony_tunertype *tun;
u8 buffer[4];
tun = &sony_tuners[t->type - 200];
if (freq < tun->thresh1) {
band_name = "VHF_L";
band_select = tun->VHF_L;
} else if (freq < tun->thresh2) {
band_name = "VHF_H";
band_select = tun->VHF_H;
} else {
band_name = "UHF";
band_select = tun->UHF;
}
printk(KERN_DEBUG "wis-sony-tuner: tuning to frequency %d.%04d (%s)\n",
freq / 16, (freq % 16) * 625, band_name);
n = freq + tun->IFPCoff;
buffer[0] = n >> 8;
buffer[1] = n & 0xff;
buffer[2] = tun->config;
buffer[3] = band_select;
i2c_master_send(client, buffer, 4);
return 0;
}
static int mpx_write(struct i2c_client *client, int dev, int addr, int val)
{
u8 buffer[5];
struct i2c_msg msg;
buffer[0] = dev;
buffer[1] = addr >> 8;
buffer[2] = addr & 0xff;
buffer[3] = val >> 8;
buffer[4] = val & 0xff;
msg.addr = MPX_I2C_ADDR;
msg.flags = 0;
msg.len = 5;
msg.buf = buffer;
i2c_transfer(client->adapter, &msg, 1);
return 0;
}
/*
* MPX register values for the BTF-PG472Z:
*
* FM_ NICAM_ SCART_
* MODUS SOURCE ACB PRESCAL PRESCAL PRESCAL SYSTEM VOLUME
* 10/0030 12/0008 12/0013 12/000E 12/0010 12/0000 10/0020 12/0000
* ---------------------------------------------------------------
* Auto 1003 0020 0100 2603 5000 XXXX 0001 7500
*
* B/G
* Mono 1003 0020 0100 2603 5000 XXXX 0003 7500
* A2 1003 0020 0100 2601 5000 XXXX 0003 7500
* NICAM 1003 0120 0100 2603 5000 XXXX 0008 7500
*
* I
* Mono 1003 0020 0100 2603 7900 XXXX 000A 7500
* NICAM 1003 0120 0100 2603 7900 XXXX 000A 7500
*
* D/K
* Mono 1003 0020 0100 2603 5000 XXXX 0004 7500
* A2-1 1003 0020 0100 2601 5000 XXXX 0004 7500
* A2-2 1003 0020 0100 2601 5000 XXXX 0005 7500
* A2-3 1003 0020 0100 2601 5000 XXXX 0007 7500
* NICAM 1003 0120 0100 2603 5000 XXXX 000B 7500
*
* L/L'
* Mono 0003 0200 0100 7C03 5000 2200 0009 7500
* NICAM 0003 0120 0100 7C03 5000 XXXX 0009 7500
*
* M
* Mono 1003 0200 0100 2B03 5000 2B00 0002 7500
*
* For Asia, replace the 0x26XX in FM_PRESCALE with 0x14XX.
*
* Bilingual selection in A2/NICAM:
*
* High byte of SOURCE Left chan Right chan
* 0x01 MAIN SUB
* 0x03 MAIN MAIN
* 0x04 SUB SUB
*
* Force mono in NICAM by setting the high byte of SOURCE to 0x02 (L/L') or
* 0x00 (all other bands). Force mono in A2 with FMONO_A2:
*
* FMONO_A2
* 10/0022
* --------
* Forced mono ON 07F0
* Forced mono OFF 0190
*/
static struct {
enum { AUD_MONO, AUD_A2, AUD_NICAM, AUD_NICAM_L } audio_mode;
u16 modus;
u16 source;
u16 acb;
u16 fm_prescale;
u16 nicam_prescale;
u16 scart_prescale;
u16 system;
u16 volume;
} mpx_audio_modes[] = {
/* Auto */ { AUD_MONO, 0x1003, 0x0020, 0x0100, 0x2603,
0x5000, 0x0000, 0x0001, 0x7500 },
/* B/G Mono */ { AUD_MONO, 0x1003, 0x0020, 0x0100, 0x2603,
0x5000, 0x0000, 0x0003, 0x7500 },
/* B/G A2 */ { AUD_A2, 0x1003, 0x0020, 0x0100, 0x2601,
0x5000, 0x0000, 0x0003, 0x7500 },
/* B/G NICAM */ { AUD_NICAM, 0x1003, 0x0120, 0x0100, 0x2603,
0x5000, 0x0000, 0x0008, 0x7500 },
/* I Mono */ { AUD_MONO, 0x1003, 0x0020, 0x0100, 0x2603,
0x7900, 0x0000, 0x000A, 0x7500 },
/* I NICAM */ { AUD_NICAM, 0x1003, 0x0120, 0x0100, 0x2603,
0x7900, 0x0000, 0x000A, 0x7500 },
/* D/K Mono */ { AUD_MONO, 0x1003, 0x0020, 0x0100, 0x2603,
0x5000, 0x0000, 0x0004, 0x7500 },
/* D/K A2-1 */ { AUD_A2, 0x1003, 0x0020, 0x0100, 0x2601,
0x5000, 0x0000, 0x0004, 0x7500 },
/* D/K A2-2 */ { AUD_A2, 0x1003, 0x0020, 0x0100, 0x2601,
0x5000, 0x0000, 0x0005, 0x7500 },
/* D/K A2-3 */ { AUD_A2, 0x1003, 0x0020, 0x0100, 0x2601,
0x5000, 0x0000, 0x0007, 0x7500 },
/* D/K NICAM */ { AUD_NICAM, 0x1003, 0x0120, 0x0100, 0x2603,
0x5000, 0x0000, 0x000B, 0x7500 },
/* L/L' Mono */ { AUD_MONO, 0x0003, 0x0200, 0x0100, 0x7C03,
0x5000, 0x2200, 0x0009, 0x7500 },
/* L/L' NICAM */{ AUD_NICAM_L, 0x0003, 0x0120, 0x0100, 0x7C03,
0x5000, 0x0000, 0x0009, 0x7500 },
};
#define MPX_NUM_MODES ARRAY_SIZE(mpx_audio_modes)
static int mpx_setup(struct i2c_client *client)
{
struct wis_sony_tuner *t = i2c_get_clientdata(client);
u16 source = 0;
u8 buffer[3];
struct i2c_msg msg;
/* reset MPX */
buffer[0] = 0x00;
buffer[1] = 0x80;
buffer[2] = 0x00;
msg.addr = MPX_I2C_ADDR;
msg.flags = 0;
msg.len = 3;
msg.buf = buffer;
i2c_transfer(client->adapter, &msg, 1);
buffer[1] = 0x00;
i2c_transfer(client->adapter, &msg, 1);
if (mpx_audio_modes[t->mpxmode].audio_mode != AUD_MONO) {
switch (t->audmode) {
case V4L2_TUNER_MODE_MONO:
switch (mpx_audio_modes[t->mpxmode].audio_mode) {
case AUD_A2:
source = mpx_audio_modes[t->mpxmode].source;
break;
case AUD_NICAM:
source = 0x0000;
break;
case AUD_NICAM_L:
source = 0x0200;
break;
default:
break;
}
break;
case V4L2_TUNER_MODE_STEREO:
source = mpx_audio_modes[t->mpxmode].source;
break;
case V4L2_TUNER_MODE_LANG1:
source = 0x0300;
break;
case V4L2_TUNER_MODE_LANG2:
source = 0x0400;
break;
}
source |= mpx_audio_modes[t->mpxmode].source & 0x00ff;
} else
source = mpx_audio_modes[t->mpxmode].source;
mpx_write(client, 0x10, 0x0030, mpx_audio_modes[t->mpxmode].modus);
mpx_write(client, 0x12, 0x0008, source);
mpx_write(client, 0x12, 0x0013, mpx_audio_modes[t->mpxmode].acb);
mpx_write(client, 0x12, 0x000e,
mpx_audio_modes[t->mpxmode].fm_prescale);
mpx_write(client, 0x12, 0x0010,
mpx_audio_modes[t->mpxmode].nicam_prescale);
mpx_write(client, 0x12, 0x000d,
mpx_audio_modes[t->mpxmode].scart_prescale);
mpx_write(client, 0x10, 0x0020, mpx_audio_modes[t->mpxmode].system);
mpx_write(client, 0x12, 0x0000, mpx_audio_modes[t->mpxmode].volume);
if (mpx_audio_modes[t->mpxmode].audio_mode == AUD_A2)
mpx_write(client, 0x10, 0x0022,
t->audmode == V4L2_TUNER_MODE_MONO ? 0x07f0 : 0x0190);
#ifdef MPX_DEBUG
{
u8 buf1[3], buf2[2];
struct i2c_msg msgs[2];
printk(KERN_DEBUG "wis-sony-tuner: MPX registers: %04x %04x "
"%04x %04x %04x %04x %04x %04x\n",
mpx_audio_modes[t->mpxmode].modus,
source,
mpx_audio_modes[t->mpxmode].acb,
mpx_audio_modes[t->mpxmode].fm_prescale,
mpx_audio_modes[t->mpxmode].nicam_prescale,
mpx_audio_modes[t->mpxmode].scart_prescale,
mpx_audio_modes[t->mpxmode].system,
mpx_audio_modes[t->mpxmode].volume);
buf1[0] = 0x11;
buf1[1] = 0x00;
buf1[2] = 0x7e;
msgs[0].addr = MPX_I2C_ADDR;
msgs[0].flags = 0;
msgs[0].len = 3;
msgs[0].buf = buf1;
msgs[1].addr = MPX_I2C_ADDR;
msgs[1].flags = I2C_M_RD;
msgs[1].len = 2;
msgs[1].buf = buf2;
i2c_transfer(client->adapter, msgs, 2);
printk(KERN_DEBUG "wis-sony-tuner: MPX system: %02x%02x\n",
buf2[0], buf2[1]);
buf1[0] = 0x11;
buf1[1] = 0x02;
buf1[2] = 0x00;
i2c_transfer(client->adapter, msgs, 2);
printk(KERN_DEBUG "wis-sony-tuner: MPX status: %02x%02x\n",
buf2[0], buf2[1]);
}
#endif
return 0;
}
/*
* IF configuration values for the BTF-PG472Z:
*
* B/G: 0x94 0x70 0x49
* I: 0x14 0x70 0x4a
* D/K: 0x14 0x70 0x4b
* L: 0x04 0x70 0x4b
* L': 0x44 0x70 0x53
* M: 0x50 0x30 0x4c
*/
static int set_if(struct i2c_client *client)
{
struct wis_sony_tuner *t = i2c_get_clientdata(client);
u8 buffer[4];
struct i2c_msg msg;
int default_mpx_mode = 0;
/* configure IF */
buffer[0] = 0;
if (t->std & V4L2_STD_PAL_BG) {
buffer[1] = 0x94;
buffer[2] = 0x70;
buffer[3] = 0x49;
default_mpx_mode = 1;
} else if (t->std & V4L2_STD_PAL_I) {
buffer[1] = 0x14;
buffer[2] = 0x70;
buffer[3] = 0x4a;
default_mpx_mode = 4;
} else if (t->std & V4L2_STD_PAL_DK) {
buffer[1] = 0x14;
buffer[2] = 0x70;
buffer[3] = 0x4b;
default_mpx_mode = 6;
} else if (t->std & V4L2_STD_SECAM_L) {
buffer[1] = 0x04;
buffer[2] = 0x70;
buffer[3] = 0x4b;
default_mpx_mode = 11;
}
msg.addr = IF_I2C_ADDR;
msg.flags = 0;
msg.len = 4;
msg.buf = buffer;
i2c_transfer(client->adapter, &msg, 1);
/* Select MPX mode if not forced by the user */
if (force_mpx_mode >= 0 && force_mpx_mode < MPX_NUM_MODES)
t->mpxmode = force_mpx_mode;
else
t->mpxmode = default_mpx_mode;
printk(KERN_DEBUG "wis-sony-tuner: setting MPX to mode %d\n",
t->mpxmode);
mpx_setup(client);
return 0;
}
static int tuner_command(struct i2c_client *client, unsigned int cmd, void *arg)
{
struct wis_sony_tuner *t = i2c_get_clientdata(client);
switch (cmd) {
#if 0
#ifdef TUNER_SET_TYPE_ADDR
case TUNER_SET_TYPE_ADDR:
{
struct tuner_setup *tun_setup = arg;
int *type = &tun_setup->type;
#else
case TUNER_SET_TYPE:
{
int *type = arg;
#endif
if (t->type >= 0) {
if (t->type != *type)
printk(KERN_ERR "wis-sony-tuner: type already "
"set to %d, ignoring request for %d\n",
t->type, *type);
break;
}
t->type = *type;
switch (t->type) {
case TUNER_SONY_BTF_PG472Z:
switch (force_band_str[0]) {
case 'b':
case 'B':
case 'g':
case 'G':
printk(KERN_INFO "wis-sony-tuner: forcing "
"tuner to PAL-B/G bands\n");
force_band = V4L2_STD_PAL_BG;
break;
case 'i':
case 'I':
printk(KERN_INFO "wis-sony-tuner: forcing "
"tuner to PAL-I band\n");
force_band = V4L2_STD_PAL_I;
break;
case 'd':
case 'D':
case 'k':
case 'K':
printk(KERN_INFO "wis-sony-tuner: forcing "
"tuner to PAL-D/K bands\n");
force_band = V4L2_STD_PAL_I;
break;
case 'l':
case 'L':
printk(KERN_INFO "wis-sony-tuner: forcing "
"tuner to SECAM-L band\n");
force_band = V4L2_STD_SECAM_L;
break;
default:
force_band = 0;
break;
}
if (force_band)
t->std = force_band;
else
t->std = V4L2_STD_PAL_BG;
set_if(client);
break;
case TUNER_SONY_BTF_PK467Z:
t->std = V4L2_STD_NTSC_M_JP;
break;
case TUNER_SONY_BTF_PB463Z:
t->std = V4L2_STD_NTSC_M;
break;
default:
printk(KERN_ERR "wis-sony-tuner: tuner type %d is not "
"supported by this module\n", *type);
break;
}
if (type >= 0)
printk(KERN_INFO
"wis-sony-tuner: type set to %d (%s)\n",
t->type, sony_tuners[t->type - 200].name);
break;
}
#endif
case VIDIOC_G_FREQUENCY:
{
struct v4l2_frequency *f = arg;
f->frequency = t->freq;
break;
}
case VIDIOC_S_FREQUENCY:
{
struct v4l2_frequency *f = arg;
t->freq = f->frequency;
set_freq(client, t->freq);
break;
}
case VIDIOC_ENUMSTD:
{
struct v4l2_standard *std = arg;
switch (t->type) {
case TUNER_SONY_BTF_PG472Z:
switch (std->index) {
case 0:
v4l2_video_std_construct(std,
V4L2_STD_PAL_BG, "PAL-B/G");
break;
case 1:
v4l2_video_std_construct(std,
V4L2_STD_PAL_I, "PAL-I");
break;
case 2:
v4l2_video_std_construct(std,
V4L2_STD_PAL_DK, "PAL-D/K");
break;
case 3:
v4l2_video_std_construct(std,
V4L2_STD_SECAM_L, "SECAM-L");
break;
default:
std->id = 0; /* hack to indicate EINVAL */
break;
}
break;
case TUNER_SONY_BTF_PK467Z:
if (std->index != 0) {
std->id = 0; /* hack to indicate EINVAL */
break;
}
v4l2_video_std_construct(std,
V4L2_STD_NTSC_M_JP, "NTSC-J");
break;
case TUNER_SONY_BTF_PB463Z:
if (std->index != 0) {
std->id = 0; /* hack to indicate EINVAL */
break;
}
v4l2_video_std_construct(std, V4L2_STD_NTSC_M, "NTSC");
break;
}
break;
}
case VIDIOC_G_STD:
{
v4l2_std_id *std = arg;
*std = t->std;
break;
}
case VIDIOC_S_STD:
{
v4l2_std_id *std = arg;
v4l2_std_id old = t->std;
switch (t->type) {
case TUNER_SONY_BTF_PG472Z:
if (force_band && (*std & force_band) != *std &&
*std != V4L2_STD_PAL &&
*std != V4L2_STD_SECAM) {
printk(KERN_DEBUG "wis-sony-tuner: ignoring "
"requested TV standard in "
"favor of force_band value\n");
t->std = force_band;
} else if (*std & V4L2_STD_PAL_BG) { /* default */
t->std = V4L2_STD_PAL_BG;
} else if (*std & V4L2_STD_PAL_I) {
t->std = V4L2_STD_PAL_I;
} else if (*std & V4L2_STD_PAL_DK) {
t->std = V4L2_STD_PAL_DK;
} else if (*std & V4L2_STD_SECAM_L) {
t->std = V4L2_STD_SECAM_L;
} else {
printk(KERN_ERR "wis-sony-tuner: TV standard "
"not supported\n");
*std = 0; /* hack to indicate EINVAL */
break;
}
if (old != t->std)
set_if(client);
break;
case TUNER_SONY_BTF_PK467Z:
if (!(*std & V4L2_STD_NTSC_M_JP)) {
printk(KERN_ERR "wis-sony-tuner: TV standard "
"not supported\n");
*std = 0; /* hack to indicate EINVAL */
}
break;
case TUNER_SONY_BTF_PB463Z:
if (!(*std & V4L2_STD_NTSC_M)) {
printk(KERN_ERR "wis-sony-tuner: TV standard "
"not supported\n");
*std = 0; /* hack to indicate EINVAL */
}
break;
}
break;
}
case VIDIOC_QUERYSTD:
{
v4l2_std_id *std = arg;
switch (t->type) {
case TUNER_SONY_BTF_PG472Z:
if (force_band)
*std = force_band;
else
*std = V4L2_STD_PAL_BG | V4L2_STD_PAL_I |
V4L2_STD_PAL_DK | V4L2_STD_SECAM_L;
break;
case TUNER_SONY_BTF_PK467Z:
*std = V4L2_STD_NTSC_M_JP;
break;
case TUNER_SONY_BTF_PB463Z:
*std = V4L2_STD_NTSC_M;
break;
}
break;
}
case VIDIOC_G_TUNER:
{
struct v4l2_tuner *tun = arg;
memset(tun, 0, sizeof(*tun));
strcpy(tun->name, "Television");
tun->type = V4L2_TUNER_ANALOG_TV;
tun->rangelow = 0UL; /* does anything use these? */
tun->rangehigh = 0xffffffffUL;
switch (t->type) {
case TUNER_SONY_BTF_PG472Z:
tun->capability = V4L2_TUNER_CAP_NORM |
V4L2_TUNER_CAP_STEREO | V4L2_TUNER_CAP_LANG1 |
V4L2_TUNER_CAP_LANG2;
tun->rxsubchans = V4L2_TUNER_SUB_MONO |
V4L2_TUNER_SUB_STEREO | V4L2_TUNER_SUB_LANG1 |
V4L2_TUNER_SUB_LANG2;
break;
case TUNER_SONY_BTF_PK467Z:
case TUNER_SONY_BTF_PB463Z:
tun->capability = V4L2_TUNER_CAP_STEREO;
tun->rxsubchans = V4L2_TUNER_SUB_MONO |
V4L2_TUNER_SUB_STEREO;
break;
}
tun->audmode = t->audmode;
return 0;
}
case VIDIOC_S_TUNER:
{
struct v4l2_tuner *tun = arg;
switch (t->type) {
case TUNER_SONY_BTF_PG472Z:
if (tun->audmode != t->audmode) {
t->audmode = tun->audmode;
mpx_setup(client);
}
break;
case TUNER_SONY_BTF_PK467Z:
case TUNER_SONY_BTF_PB463Z:
break;
}
return 0;
}
default:
break;
}
return 0;
}
static int wis_sony_tuner_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct i2c_adapter *adapter = client->adapter;
struct wis_sony_tuner *t;
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_I2C_BLOCK))
return -ENODEV;
t = kmalloc(sizeof(struct wis_sony_tuner), GFP_KERNEL);
if (t == NULL)
return -ENOMEM;
t->type = -1;
t->freq = 0;
t->mpxmode = 0;
t->audmode = V4L2_TUNER_MODE_STEREO;
i2c_set_clientdata(client, t);
printk(KERN_DEBUG
"wis-sony-tuner: initializing tuner at address %d on %s\n",
client->addr, adapter->name);
return 0;
}
static int wis_sony_tuner_remove(struct i2c_client *client)
{
struct wis_sony_tuner *t = i2c_get_clientdata(client);
kfree(t);
return 0;
}
static const struct i2c_device_id wis_sony_tuner_id[] = {
{ "wis_sony_tuner", 0 },
{ }
};
static struct i2c_driver wis_sony_tuner_driver = {
.driver = {
.name = "WIS Sony TV Tuner I2C driver",
},
.probe = wis_sony_tuner_probe,
.remove = wis_sony_tuner_remove,
.command = tuner_command,
.id_table = wis_sony_tuner_id,
};
static int __init wis_sony_tuner_init(void)
{
return i2c_add_driver(&wis_sony_tuner_driver);
}
static void __exit wis_sony_tuner_cleanup(void)
{
i2c_del_driver(&wis_sony_tuner_driver);
}
module_init(wis_sony_tuner_init);
module_exit(wis_sony_tuner_cleanup);
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
mpconsulting/rtt-kernel | arch/alpha/boot/main.c | 1106 | 4321 | /*
* arch/alpha/boot/main.c
*
* Copyright (C) 1994, 1995 Linus Torvalds
*
* This file is the bootloader for the Linux/AXP kernel
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <generated/utsrelease.h>
#include <linux/mm.h>
#include <asm/console.h>
#include <asm/hwrpb.h>
#include <asm/pgtable.h>
#include <stdarg.h>
#include "ksize.h"
extern unsigned long switch_to_osf_pal(unsigned long nr,
struct pcb_struct * pcb_va, struct pcb_struct * pcb_pa,
unsigned long *vptb);
struct hwrpb_struct *hwrpb = INIT_HWRPB;
static struct pcb_struct pcb_va[1];
/*
* Find a physical address of a virtual object..
*
* This is easy using the virtual page table address.
*/
static inline void *
find_pa(unsigned long *vptb, void *ptr)
{
unsigned long address = (unsigned long) ptr;
unsigned long result;
result = vptb[address >> 13];
result >>= 32;
result <<= 13;
result |= address & 0x1fff;
return (void *) result;
}
/*
* This function moves into OSF/1 pal-code, and has a temporary
* PCB for that. The kernel proper should replace this PCB with
* the real one as soon as possible.
*
* The page table muckery in here depends on the fact that the boot
* code has the L1 page table identity-map itself in the second PTE
* in the L1 page table. Thus the L1-page is virtually addressable
* itself (through three levels) at virtual address 0x200802000.
*/
#define VPTB ((unsigned long *) 0x200000000)
#define L1 ((unsigned long *) 0x200802000)
void
pal_init(void)
{
unsigned long i, rev;
struct percpu_struct * percpu;
struct pcb_struct * pcb_pa;
/* Create the dummy PCB. */
pcb_va->ksp = 0;
pcb_va->usp = 0;
pcb_va->ptbr = L1[1] >> 32;
pcb_va->asn = 0;
pcb_va->pcc = 0;
pcb_va->unique = 0;
pcb_va->flags = 1;
pcb_va->res1 = 0;
pcb_va->res2 = 0;
pcb_pa = find_pa(VPTB, pcb_va);
/*
* a0 = 2 (OSF)
* a1 = return address, but we give the asm the vaddr of the PCB
* a2 = physical addr of PCB
* a3 = new virtual page table pointer
* a4 = KSP (but the asm sets it)
*/
srm_printk("Switching to OSF PAL-code .. ");
i = switch_to_osf_pal(2, pcb_va, pcb_pa, VPTB);
if (i) {
srm_printk("failed, code %ld\n", i);
__halt();
}
percpu = (struct percpu_struct *)
(INIT_HWRPB->processor_offset + (unsigned long) INIT_HWRPB);
rev = percpu->pal_revision = percpu->palcode_avail[2];
srm_printk("Ok (rev %lx)\n", rev);
tbia(); /* do it directly in case we are SMP */
}
static inline long openboot(void)
{
char bootdev[256];
long result;
result = callback_getenv(ENV_BOOTED_DEV, bootdev, 255);
if (result < 0)
return result;
return callback_open(bootdev, result & 255);
}
static inline long close(long dev)
{
return callback_close(dev);
}
static inline long load(long dev, unsigned long addr, unsigned long count)
{
char bootfile[256];
extern char _end;
long result, boot_size = &_end - (char *) BOOT_ADDR;
result = callback_getenv(ENV_BOOTED_FILE, bootfile, 255);
if (result < 0)
return result;
result &= 255;
bootfile[result] = '\0';
if (result)
srm_printk("Boot file specification (%s) not implemented\n",
bootfile);
return callback_read(dev, count, (void *)addr, boot_size/512 + 1);
}
/*
* Start the kernel.
*/
static void runkernel(void)
{
__asm__ __volatile__(
"bis %1,%1,$30\n\t"
"bis %0,%0,$26\n\t"
"ret ($26)"
: /* no outputs: it doesn't even return */
: "r" (START_ADDR),
"r" (PAGE_SIZE + INIT_STACK));
}
void start_kernel(void)
{
long i;
long dev;
int nbytes;
char envval[256];
srm_printk("Linux/AXP bootloader for Linux " UTS_RELEASE "\n");
if (INIT_HWRPB->pagesize != 8192) {
srm_printk("Expected 8kB pages, got %ldkB\n", INIT_HWRPB->pagesize >> 10);
return;
}
pal_init();
dev = openboot();
if (dev < 0) {
srm_printk("Unable to open boot device: %016lx\n", dev);
return;
}
dev &= 0xffffffff;
srm_printk("Loading vmlinux ...");
i = load(dev, START_ADDR, KERNEL_SIZE);
close(dev);
if (i != KERNEL_SIZE) {
srm_printk("Failed (%lx)\n", i);
return;
}
nbytes = callback_getenv(ENV_BOOTED_OSFLAGS, envval, sizeof(envval));
if (nbytes < 0) {
nbytes = 0;
}
envval[nbytes] = '\0';
strcpy((char*)ZERO_PGE, envval);
srm_printk(" Ok\nNow booting the kernel\n");
runkernel();
for (i = 0 ; i < 0x100000000 ; i++)
/* nothing */;
__halt();
}
| gpl-2.0 |
EPDCenter/android_kernel_woxter_nimbus_98q | drivers/net/enic/enic_res.c | 2386 | 9135 | /*
* Copyright 2008-2010 Cisco Systems, Inc. All rights reserved.
* Copyright 2007 Nuova Systems, Inc. All rights reserved.
*
* This program is free software; you may redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/netdevice.h>
#include "wq_enet_desc.h"
#include "rq_enet_desc.h"
#include "cq_enet_desc.h"
#include "vnic_resource.h"
#include "vnic_enet.h"
#include "vnic_dev.h"
#include "vnic_wq.h"
#include "vnic_rq.h"
#include "vnic_cq.h"
#include "vnic_intr.h"
#include "vnic_stats.h"
#include "vnic_nic.h"
#include "vnic_rss.h"
#include "enic_res.h"
#include "enic.h"
int enic_get_vnic_config(struct enic *enic)
{
struct vnic_enet_config *c = &enic->config;
int err;
err = vnic_dev_mac_addr(enic->vdev, enic->mac_addr);
if (err) {
dev_err(enic_get_dev(enic),
"Error getting MAC addr, %d\n", err);
return err;
}
#define GET_CONFIG(m) \
do { \
err = vnic_dev_spec(enic->vdev, \
offsetof(struct vnic_enet_config, m), \
sizeof(c->m), &c->m); \
if (err) { \
dev_err(enic_get_dev(enic), \
"Error getting %s, %d\n", #m, err); \
return err; \
} \
} while (0)
GET_CONFIG(flags);
GET_CONFIG(wq_desc_count);
GET_CONFIG(rq_desc_count);
GET_CONFIG(mtu);
GET_CONFIG(intr_timer_type);
GET_CONFIG(intr_mode);
GET_CONFIG(intr_timer_usec);
GET_CONFIG(loop_tag);
c->wq_desc_count =
min_t(u32, ENIC_MAX_WQ_DESCS,
max_t(u32, ENIC_MIN_WQ_DESCS,
c->wq_desc_count));
c->wq_desc_count &= 0xffffffe0; /* must be aligned to groups of 32 */
c->rq_desc_count =
min_t(u32, ENIC_MAX_RQ_DESCS,
max_t(u32, ENIC_MIN_RQ_DESCS,
c->rq_desc_count));
c->rq_desc_count &= 0xffffffe0; /* must be aligned to groups of 32 */
if (c->mtu == 0)
c->mtu = 1500;
c->mtu = min_t(u16, ENIC_MAX_MTU,
max_t(u16, ENIC_MIN_MTU,
c->mtu));
c->intr_timer_usec = min_t(u32,
INTR_COALESCE_HW_TO_USEC(VNIC_INTR_TIMER_MAX),
c->intr_timer_usec);
dev_info(enic_get_dev(enic),
"vNIC MAC addr %pM wq/rq %d/%d mtu %d\n",
enic->mac_addr, c->wq_desc_count, c->rq_desc_count, c->mtu);
dev_info(enic_get_dev(enic), "vNIC csum tx/rx %d/%d "
"tso %d intr timer %d usec rss %d\n",
ENIC_SETTING(enic, TXCSUM), ENIC_SETTING(enic, RXCSUM),
ENIC_SETTING(enic, TSO),
c->intr_timer_usec, ENIC_SETTING(enic, RSS));
return 0;
}
int enic_add_vlan(struct enic *enic, u16 vlanid)
{
u64 a0 = vlanid, a1 = 0;
int wait = 1000;
int err;
err = vnic_dev_cmd(enic->vdev, CMD_VLAN_ADD, &a0, &a1, wait);
if (err)
dev_err(enic_get_dev(enic), "Can't add vlan id, %d\n", err);
return err;
}
int enic_del_vlan(struct enic *enic, u16 vlanid)
{
u64 a0 = vlanid, a1 = 0;
int wait = 1000;
int err;
err = vnic_dev_cmd(enic->vdev, CMD_VLAN_DEL, &a0, &a1, wait);
if (err)
dev_err(enic_get_dev(enic), "Can't delete vlan id, %d\n", err);
return err;
}
int enic_set_nic_cfg(struct enic *enic, u8 rss_default_cpu, u8 rss_hash_type,
u8 rss_hash_bits, u8 rss_base_cpu, u8 rss_enable, u8 tso_ipid_split_en,
u8 ig_vlan_strip_en)
{
u64 a0, a1;
u32 nic_cfg;
int wait = 1000;
vnic_set_nic_cfg(&nic_cfg, rss_default_cpu,
rss_hash_type, rss_hash_bits, rss_base_cpu,
rss_enable, tso_ipid_split_en, ig_vlan_strip_en);
a0 = nic_cfg;
a1 = 0;
return vnic_dev_cmd(enic->vdev, CMD_NIC_CFG, &a0, &a1, wait);
}
int enic_set_rss_key(struct enic *enic, dma_addr_t key_pa, u64 len)
{
u64 a0 = (u64)key_pa, a1 = len;
int wait = 1000;
return vnic_dev_cmd(enic->vdev, CMD_RSS_KEY, &a0, &a1, wait);
}
int enic_set_rss_cpu(struct enic *enic, dma_addr_t cpu_pa, u64 len)
{
u64 a0 = (u64)cpu_pa, a1 = len;
int wait = 1000;
return vnic_dev_cmd(enic->vdev, CMD_RSS_CPU, &a0, &a1, wait);
}
void enic_free_vnic_resources(struct enic *enic)
{
unsigned int i;
for (i = 0; i < enic->wq_count; i++)
vnic_wq_free(&enic->wq[i]);
for (i = 0; i < enic->rq_count; i++)
vnic_rq_free(&enic->rq[i]);
for (i = 0; i < enic->cq_count; i++)
vnic_cq_free(&enic->cq[i]);
for (i = 0; i < enic->intr_count; i++)
vnic_intr_free(&enic->intr[i]);
}
void enic_get_res_counts(struct enic *enic)
{
enic->wq_count = vnic_dev_get_res_count(enic->vdev, RES_TYPE_WQ);
enic->rq_count = vnic_dev_get_res_count(enic->vdev, RES_TYPE_RQ);
enic->cq_count = vnic_dev_get_res_count(enic->vdev, RES_TYPE_CQ);
enic->intr_count = vnic_dev_get_res_count(enic->vdev,
RES_TYPE_INTR_CTRL);
dev_info(enic_get_dev(enic),
"vNIC resources avail: wq %d rq %d cq %d intr %d\n",
enic->wq_count, enic->rq_count,
enic->cq_count, enic->intr_count);
}
void enic_init_vnic_resources(struct enic *enic)
{
enum vnic_dev_intr_mode intr_mode;
unsigned int mask_on_assertion;
unsigned int interrupt_offset;
unsigned int error_interrupt_enable;
unsigned int error_interrupt_offset;
unsigned int cq_index;
unsigned int i;
intr_mode = vnic_dev_get_intr_mode(enic->vdev);
/* Init RQ/WQ resources.
*
* RQ[0 - n-1] point to CQ[0 - n-1]
* WQ[0 - m-1] point to CQ[n - n+m-1]
*
* Error interrupt is not enabled for MSI.
*/
switch (intr_mode) {
case VNIC_DEV_INTR_MODE_INTX:
case VNIC_DEV_INTR_MODE_MSIX:
error_interrupt_enable = 1;
error_interrupt_offset = enic->intr_count - 2;
break;
default:
error_interrupt_enable = 0;
error_interrupt_offset = 0;
break;
}
for (i = 0; i < enic->rq_count; i++) {
cq_index = i;
vnic_rq_init(&enic->rq[i],
cq_index,
error_interrupt_enable,
error_interrupt_offset);
}
for (i = 0; i < enic->wq_count; i++) {
cq_index = enic->rq_count + i;
vnic_wq_init(&enic->wq[i],
cq_index,
error_interrupt_enable,
error_interrupt_offset);
}
/* Init CQ resources
*
* CQ[0 - n+m-1] point to INTR[0] for INTx, MSI
* CQ[0 - n+m-1] point to INTR[0 - n+m-1] for MSI-X
*/
for (i = 0; i < enic->cq_count; i++) {
switch (intr_mode) {
case VNIC_DEV_INTR_MODE_MSIX:
interrupt_offset = i;
break;
default:
interrupt_offset = 0;
break;
}
vnic_cq_init(&enic->cq[i],
0 /* flow_control_enable */,
1 /* color_enable */,
0 /* cq_head */,
0 /* cq_tail */,
1 /* cq_tail_color */,
1 /* interrupt_enable */,
1 /* cq_entry_enable */,
0 /* cq_message_enable */,
interrupt_offset,
0 /* cq_message_addr */);
}
/* Init INTR resources
*
* mask_on_assertion is not used for INTx due to the level-
* triggered nature of INTx
*/
switch (intr_mode) {
case VNIC_DEV_INTR_MODE_MSI:
case VNIC_DEV_INTR_MODE_MSIX:
mask_on_assertion = 1;
break;
default:
mask_on_assertion = 0;
break;
}
for (i = 0; i < enic->intr_count; i++) {
vnic_intr_init(&enic->intr[i],
INTR_COALESCE_USEC_TO_HW(enic->config.intr_timer_usec),
enic->config.intr_timer_type,
mask_on_assertion);
}
}
int enic_alloc_vnic_resources(struct enic *enic)
{
enum vnic_dev_intr_mode intr_mode;
unsigned int i;
int err;
intr_mode = vnic_dev_get_intr_mode(enic->vdev);
dev_info(enic_get_dev(enic), "vNIC resources used: "
"wq %d rq %d cq %d intr %d intr mode %s\n",
enic->wq_count, enic->rq_count,
enic->cq_count, enic->intr_count,
intr_mode == VNIC_DEV_INTR_MODE_INTX ? "legacy PCI INTx" :
intr_mode == VNIC_DEV_INTR_MODE_MSI ? "MSI" :
intr_mode == VNIC_DEV_INTR_MODE_MSIX ? "MSI-X" :
"unknown");
/* Allocate queue resources
*/
for (i = 0; i < enic->wq_count; i++) {
err = vnic_wq_alloc(enic->vdev, &enic->wq[i], i,
enic->config.wq_desc_count,
sizeof(struct wq_enet_desc));
if (err)
goto err_out_cleanup;
}
for (i = 0; i < enic->rq_count; i++) {
err = vnic_rq_alloc(enic->vdev, &enic->rq[i], i,
enic->config.rq_desc_count,
sizeof(struct rq_enet_desc));
if (err)
goto err_out_cleanup;
}
for (i = 0; i < enic->cq_count; i++) {
if (i < enic->rq_count)
err = vnic_cq_alloc(enic->vdev, &enic->cq[i], i,
enic->config.rq_desc_count,
sizeof(struct cq_enet_rq_desc));
else
err = vnic_cq_alloc(enic->vdev, &enic->cq[i], i,
enic->config.wq_desc_count,
sizeof(struct cq_enet_wq_desc));
if (err)
goto err_out_cleanup;
}
for (i = 0; i < enic->intr_count; i++) {
err = vnic_intr_alloc(enic->vdev, &enic->intr[i], i);
if (err)
goto err_out_cleanup;
}
/* Hook remaining resource
*/
enic->legacy_pba = vnic_dev_get_res(enic->vdev,
RES_TYPE_INTR_PBA_LEGACY, 0);
if (!enic->legacy_pba && intr_mode == VNIC_DEV_INTR_MODE_INTX) {
dev_err(enic_get_dev(enic),
"Failed to hook legacy pba resource\n");
err = -ENODEV;
goto err_out_cleanup;
}
return 0;
err_out_cleanup:
enic_free_vnic_resources(enic);
return err;
}
| gpl-2.0 |
blackwing182/htc-kernel-msm7x30-3.0 | drivers/staging/altera-stapl/altera.c | 2386 | 57360 | /*
* altera.c
*
* altera FPGA driver
*
* Copyright (C) Altera Corporation 1998-2001
* Copyright (C) 2010,2011 NetUP Inc.
* Copyright (C) 2010,2011 Igor M. Liplianin <liplianin@netup.ru>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <asm/unaligned.h>
#include <linux/ctype.h>
#include <linux/string.h>
#include <linux/firmware.h>
#include <linux/slab.h>
#include "altera.h"
#include "altera-exprt.h"
#include "altera-jtag.h"
static int debug = 1;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "enable debugging information");
MODULE_DESCRIPTION("altera FPGA kernel module");
MODULE_AUTHOR("Igor M. Liplianin <liplianin@netup.ru>");
MODULE_LICENSE("GPL");
#define dprintk(args...) \
if (debug) { \
printk(KERN_DEBUG args); \
}
enum altera_fpga_opcode {
OP_NOP = 0,
OP_DUP,
OP_SWP,
OP_ADD,
OP_SUB,
OP_MULT,
OP_DIV,
OP_MOD,
OP_SHL,
OP_SHR,
OP_NOT,
OP_AND,
OP_OR,
OP_XOR,
OP_INV,
OP_GT,
OP_LT,
OP_RET,
OP_CMPS,
OP_PINT,
OP_PRNT,
OP_DSS,
OP_DSSC,
OP_ISS,
OP_ISSC,
OP_DPR = 0x1c,
OP_DPRL,
OP_DPO,
OP_DPOL,
OP_IPR,
OP_IPRL,
OP_IPO,
OP_IPOL,
OP_PCHR,
OP_EXIT,
OP_EQU,
OP_POPT,
OP_ABS = 0x2c,
OP_BCH0,
OP_PSH0 = 0x2f,
OP_PSHL = 0x40,
OP_PSHV,
OP_JMP,
OP_CALL,
OP_NEXT,
OP_PSTR,
OP_SINT = 0x47,
OP_ST,
OP_ISTP,
OP_DSTP,
OP_SWPN,
OP_DUPN,
OP_POPV,
OP_POPE,
OP_POPA,
OP_JMPZ,
OP_DS,
OP_IS,
OP_DPRA,
OP_DPOA,
OP_IPRA,
OP_IPOA,
OP_EXPT,
OP_PSHE,
OP_PSHA,
OP_DYNA,
OP_EXPV = 0x5c,
OP_COPY = 0x80,
OP_REVA,
OP_DSC,
OP_ISC,
OP_WAIT,
OP_VS,
OP_CMPA = 0xc0,
OP_VSC,
};
struct altera_procinfo {
char *name;
u8 attrs;
struct altera_procinfo *next;
};
/* This function checks if enough parameters are available on the stack. */
static int altera_check_stack(int stack_ptr, int count, int *status)
{
if (stack_ptr < count) {
*status = -EOVERFLOW;
return 0;
}
return 1;
}
static void altera_export_int(char *key, s32 value)
{
dprintk("Export: key = \"%s\", value = %d\n", key, value);
}
#define HEX_LINE_CHARS 72
#define HEX_LINE_BITS (HEX_LINE_CHARS * 4)
static void altera_export_bool_array(char *key, u8 *data, s32 count)
{
char string[HEX_LINE_CHARS + 1];
s32 i, offset;
u32 size, line, lines, linebits, value, j, k;
if (count > HEX_LINE_BITS) {
dprintk("Export: key = \"%s\", %d bits, value = HEX\n",
key, count);
lines = (count + (HEX_LINE_BITS - 1)) / HEX_LINE_BITS;
for (line = 0; line < lines; ++line) {
if (line < (lines - 1)) {
linebits = HEX_LINE_BITS;
size = HEX_LINE_CHARS;
offset = count - ((line + 1) * HEX_LINE_BITS);
} else {
linebits =
count - ((lines - 1) * HEX_LINE_BITS);
size = (linebits + 3) / 4;
offset = 0L;
}
string[size] = '\0';
j = size - 1;
value = 0;
for (k = 0; k < linebits; ++k) {
i = k + offset;
if (data[i >> 3] & (1 << (i & 7)))
value |= (1 << (i & 3));
if ((i & 3) == 3) {
sprintf(&string[j], "%1x", value);
value = 0;
--j;
}
}
if ((k & 3) > 0)
sprintf(&string[j], "%1x", value);
dprintk("%s\n", string);
}
} else {
size = (count + 3) / 4;
string[size] = '\0';
j = size - 1;
value = 0;
for (i = 0; i < count; ++i) {
if (data[i >> 3] & (1 << (i & 7)))
value |= (1 << (i & 3));
if ((i & 3) == 3) {
sprintf(&string[j], "%1x", value);
value = 0;
--j;
}
}
if ((i & 3) > 0)
sprintf(&string[j], "%1x", value);
dprintk("Export: key = \"%s\", %d bits, value = HEX %s\n",
key, count, string);
}
}
static int altera_execute(struct altera_state *astate,
u8 *p,
s32 program_size,
s32 *error_address,
int *exit_code,
int *format_version)
{
struct altera_config *aconf = astate->config;
char *msg_buff = astate->msg_buff;
long *stack = astate->stack;
int status = 0;
u32 first_word = 0L;
u32 action_table = 0L;
u32 proc_table = 0L;
u32 str_table = 0L;
u32 sym_table = 0L;
u32 data_sect = 0L;
u32 code_sect = 0L;
u32 debug_sect = 0L;
u32 action_count = 0L;
u32 proc_count = 0L;
u32 sym_count = 0L;
long *vars = NULL;
s32 *var_size = NULL;
char *attrs = NULL;
u8 *proc_attributes = NULL;
u32 pc;
u32 opcode_address;
u32 args[3];
u32 opcode;
u32 name_id;
u8 charbuf[4];
long long_tmp;
u32 variable_id;
u8 *charptr_tmp;
u8 *charptr_tmp2;
long *longptr_tmp;
int version = 0;
int delta = 0;
int stack_ptr = 0;
u32 arg_count;
int done = 0;
int bad_opcode = 0;
u32 count;
u32 index;
u32 index2;
s32 long_count;
s32 long_idx;
s32 long_idx2;
u32 i;
u32 j;
u32 uncomp_size;
u32 offset;
u32 value;
int current_proc = 0;
int reverse;
char *name;
dprintk("%s\n", __func__);
/* Read header information */
if (program_size > 52L) {
first_word = get_unaligned_be32(&p[0]);
version = (first_word & 1L);
*format_version = version + 1;
delta = version * 8;
action_table = get_unaligned_be32(&p[4]);
proc_table = get_unaligned_be32(&p[8]);
str_table = get_unaligned_be32(&p[4 + delta]);
sym_table = get_unaligned_be32(&p[16 + delta]);
data_sect = get_unaligned_be32(&p[20 + delta]);
code_sect = get_unaligned_be32(&p[24 + delta]);
debug_sect = get_unaligned_be32(&p[28 + delta]);
action_count = get_unaligned_be32(&p[40 + delta]);
proc_count = get_unaligned_be32(&p[44 + delta]);
sym_count = get_unaligned_be32(&p[48 + (2 * delta)]);
}
if ((first_word != 0x4A414D00L) && (first_word != 0x4A414D01L)) {
done = 1;
status = -EIO;
goto exit_done;
}
if (sym_count <= 0)
goto exit_done;
vars = kzalloc(sym_count * sizeof(long), GFP_KERNEL);
if (vars == NULL)
status = -ENOMEM;
if (status == 0) {
var_size = kzalloc(sym_count * sizeof(s32), GFP_KERNEL);
if (var_size == NULL)
status = -ENOMEM;
}
if (status == 0) {
attrs = kzalloc(sym_count, GFP_KERNEL);
if (attrs == NULL)
status = -ENOMEM;
}
if ((status == 0) && (version > 0)) {
proc_attributes = kzalloc(proc_count, GFP_KERNEL);
if (proc_attributes == NULL)
status = -ENOMEM;
}
if (status != 0)
goto exit_done;
delta = version * 2;
for (i = 0; i < sym_count; ++i) {
offset = (sym_table + ((11 + delta) * i));
value = get_unaligned_be32(&p[offset + 3 + delta]);
attrs[i] = p[offset];
/*
* use bit 7 of attribute byte to indicate that
* this buffer was dynamically allocated
* and should be freed later
*/
attrs[i] &= 0x7f;
var_size[i] = get_unaligned_be32(&p[offset + 7 + delta]);
/*
* Attribute bits:
* bit 0: 0 = read-only, 1 = read-write
* bit 1: 0 = not compressed, 1 = compressed
* bit 2: 0 = not initialized, 1 = initialized
* bit 3: 0 = scalar, 1 = array
* bit 4: 0 = Boolean, 1 = integer
* bit 5: 0 = declared variable,
* 1 = compiler created temporary variable
*/
if ((attrs[i] & 0x0c) == 0x04)
/* initialized scalar variable */
vars[i] = value;
else if ((attrs[i] & 0x1e) == 0x0e) {
/* initialized compressed Boolean array */
uncomp_size = get_unaligned_le32(&p[data_sect + value]);
/* allocate a buffer for the uncompressed data */
vars[i] = (long)kzalloc(uncomp_size, GFP_KERNEL);
if (vars[i] == 0L)
status = -ENOMEM;
else {
/* set flag so buffer will be freed later */
attrs[i] |= 0x80;
/* uncompress the data */
if (altera_shrink(&p[data_sect + value],
var_size[i],
(u8 *)vars[i],
uncomp_size,
version) != uncomp_size)
/* decompression failed */
status = -EIO;
else
var_size[i] = uncomp_size * 8L;
}
} else if ((attrs[i] & 0x1e) == 0x0c) {
/* initialized Boolean array */
vars[i] = value + data_sect + (long)p;
} else if ((attrs[i] & 0x1c) == 0x1c) {
/* initialized integer array */
vars[i] = value + data_sect;
} else if ((attrs[i] & 0x0c) == 0x08) {
/* uninitialized array */
/* flag attrs so that memory is freed */
attrs[i] |= 0x80;
if (var_size[i] > 0) {
u32 size;
if (attrs[i] & 0x10)
/* integer array */
size = (var_size[i] * sizeof(s32));
else
/* Boolean array */
size = ((var_size[i] + 7L) / 8L);
vars[i] = (long)kzalloc(size, GFP_KERNEL);
if (vars[i] == 0) {
status = -ENOMEM;
} else {
/* zero out memory */
for (j = 0; j < size; ++j)
((u8 *)(vars[i]))[j] = 0;
}
} else
vars[i] = 0;
} else
vars[i] = 0;
}
exit_done:
if (status != 0)
done = 1;
altera_jinit(astate);
pc = code_sect;
msg_buff[0] = '\0';
/*
* For JBC version 2, we will execute the procedures corresponding to
* the selected ACTION
*/
if (version > 0) {
if (aconf->action == NULL) {
status = -EINVAL;
done = 1;
} else {
int action_found = 0;
for (i = 0; (i < action_count) && !action_found; ++i) {
name_id = get_unaligned_be32(&p[action_table +
(12 * i)]);
name = &p[str_table + name_id];
if (strnicmp(aconf->action, name, strlen(name)) == 0) {
action_found = 1;
current_proc =
get_unaligned_be32(&p[action_table +
(12 * i) + 8]);
}
}
if (!action_found) {
status = -EINVAL;
done = 1;
}
}
if (status == 0) {
int first_time = 1;
i = current_proc;
while ((i != 0) || first_time) {
first_time = 0;
/* check procedure attribute byte */
proc_attributes[i] =
(p[proc_table +
(13 * i) + 8] &
0x03);
/*
* BIT0 - OPTIONAL
* BIT1 - RECOMMENDED
* BIT6 - FORCED OFF
* BIT7 - FORCED ON
*/
i = get_unaligned_be32(&p[proc_table +
(13 * i) + 4]);
}
/*
* Set current_proc to the first procedure
* to be executed
*/
i = current_proc;
while ((i != 0) &&
((proc_attributes[i] == 1) ||
((proc_attributes[i] & 0xc0) == 0x40))) {
i = get_unaligned_be32(&p[proc_table +
(13 * i) + 4]);
}
if ((i != 0) || ((i == 0) && (current_proc == 0) &&
((proc_attributes[0] != 1) &&
((proc_attributes[0] & 0xc0) != 0x40)))) {
current_proc = i;
pc = code_sect +
get_unaligned_be32(&p[proc_table +
(13 * i) + 9]);
if ((pc < code_sect) || (pc >= debug_sect))
status = -ERANGE;
} else
/* there are no procedures to execute! */
done = 1;
}
}
msg_buff[0] = '\0';
while (!done) {
opcode = (p[pc] & 0xff);
opcode_address = pc;
++pc;
if (debug > 1)
printk("opcode: %02x\n", opcode);
arg_count = (opcode >> 6) & 3;
for (i = 0; i < arg_count; ++i) {
args[i] = get_unaligned_be32(&p[pc]);
pc += 4;
}
switch (opcode) {
case OP_NOP:
break;
case OP_DUP:
if (altera_check_stack(stack_ptr, 1, &status)) {
stack[stack_ptr] = stack[stack_ptr - 1];
++stack_ptr;
}
break;
case OP_SWP:
if (altera_check_stack(stack_ptr, 2, &status)) {
long_tmp = stack[stack_ptr - 2];
stack[stack_ptr - 2] = stack[stack_ptr - 1];
stack[stack_ptr - 1] = long_tmp;
}
break;
case OP_ADD:
if (altera_check_stack(stack_ptr, 2, &status)) {
--stack_ptr;
stack[stack_ptr - 1] += stack[stack_ptr];
}
break;
case OP_SUB:
if (altera_check_stack(stack_ptr, 2, &status)) {
--stack_ptr;
stack[stack_ptr - 1] -= stack[stack_ptr];
}
break;
case OP_MULT:
if (altera_check_stack(stack_ptr, 2, &status)) {
--stack_ptr;
stack[stack_ptr - 1] *= stack[stack_ptr];
}
break;
case OP_DIV:
if (altera_check_stack(stack_ptr, 2, &status)) {
--stack_ptr;
stack[stack_ptr - 1] /= stack[stack_ptr];
}
break;
case OP_MOD:
if (altera_check_stack(stack_ptr, 2, &status)) {
--stack_ptr;
stack[stack_ptr - 1] %= stack[stack_ptr];
}
break;
case OP_SHL:
if (altera_check_stack(stack_ptr, 2, &status)) {
--stack_ptr;
stack[stack_ptr - 1] <<= stack[stack_ptr];
}
break;
case OP_SHR:
if (altera_check_stack(stack_ptr, 2, &status)) {
--stack_ptr;
stack[stack_ptr - 1] >>= stack[stack_ptr];
}
break;
case OP_NOT:
if (altera_check_stack(stack_ptr, 1, &status))
stack[stack_ptr - 1] ^= (-1L);
break;
case OP_AND:
if (altera_check_stack(stack_ptr, 2, &status)) {
--stack_ptr;
stack[stack_ptr - 1] &= stack[stack_ptr];
}
break;
case OP_OR:
if (altera_check_stack(stack_ptr, 2, &status)) {
--stack_ptr;
stack[stack_ptr - 1] |= stack[stack_ptr];
}
break;
case OP_XOR:
if (altera_check_stack(stack_ptr, 2, &status)) {
--stack_ptr;
stack[stack_ptr - 1] ^= stack[stack_ptr];
}
break;
case OP_INV:
if (!altera_check_stack(stack_ptr, 1, &status))
break;
stack[stack_ptr - 1] = stack[stack_ptr - 1] ? 0L : 1L;
break;
case OP_GT:
if (!altera_check_stack(stack_ptr, 2, &status))
break;
--stack_ptr;
stack[stack_ptr - 1] =
(stack[stack_ptr - 1] > stack[stack_ptr]) ?
1L : 0L;
break;
case OP_LT:
if (!altera_check_stack(stack_ptr, 2, &status))
break;
--stack_ptr;
stack[stack_ptr - 1] =
(stack[stack_ptr - 1] < stack[stack_ptr]) ?
1L : 0L;
break;
case OP_RET:
if ((version > 0) && (stack_ptr == 0)) {
/*
* We completed one of the main procedures
* of an ACTION.
* Find the next procedure
* to be executed and jump to it.
* If there are no more procedures, then EXIT.
*/
i = get_unaligned_be32(&p[proc_table +
(13 * current_proc) + 4]);
while ((i != 0) &&
((proc_attributes[i] == 1) ||
((proc_attributes[i] & 0xc0) == 0x40)))
i = get_unaligned_be32(&p[proc_table +
(13 * i) + 4]);
if (i == 0) {
/* no procedures to execute! */
done = 1;
*exit_code = 0; /* success */
} else {
current_proc = i;
pc = code_sect + get_unaligned_be32(
&p[proc_table +
(13 * i) + 9]);
if ((pc < code_sect) ||
(pc >= debug_sect))
status = -ERANGE;
}
} else
if (altera_check_stack(stack_ptr, 1, &status)) {
pc = stack[--stack_ptr] + code_sect;
if ((pc <= code_sect) ||
(pc >= debug_sect))
status = -ERANGE;
}
break;
case OP_CMPS:
/*
* Array short compare
* ...stack 0 is source 1 value
* ...stack 1 is source 2 value
* ...stack 2 is mask value
* ...stack 3 is count
*/
if (altera_check_stack(stack_ptr, 4, &status)) {
s32 a = stack[--stack_ptr];
s32 b = stack[--stack_ptr];
long_tmp = stack[--stack_ptr];
count = stack[stack_ptr - 1];
if ((count < 1) || (count > 32))
status = -ERANGE;
else {
long_tmp &= ((-1L) >> (32 - count));
stack[stack_ptr - 1] =
((a & long_tmp) == (b & long_tmp))
? 1L : 0L;
}
}
break;
case OP_PINT:
/*
* PRINT add integer
* ...stack 0 is integer value
*/
if (!altera_check_stack(stack_ptr, 1, &status))
break;
sprintf(&msg_buff[strlen(msg_buff)],
"%ld", stack[--stack_ptr]);
break;
case OP_PRNT:
/* PRINT finish */
if (debug)
printk(msg_buff, "\n");
msg_buff[0] = '\0';
break;
case OP_DSS:
/*
* DRSCAN short
* ...stack 0 is scan data
* ...stack 1 is count
*/
if (!altera_check_stack(stack_ptr, 2, &status))
break;
long_tmp = stack[--stack_ptr];
count = stack[--stack_ptr];
put_unaligned_le32(long_tmp, &charbuf[0]);
status = altera_drscan(astate, count, charbuf, 0);
break;
case OP_DSSC:
/*
* DRSCAN short with capture
* ...stack 0 is scan data
* ...stack 1 is count
*/
if (!altera_check_stack(stack_ptr, 2, &status))
break;
long_tmp = stack[--stack_ptr];
count = stack[stack_ptr - 1];
put_unaligned_le32(long_tmp, &charbuf[0]);
status = altera_swap_dr(astate, count, charbuf,
0, charbuf, 0);
stack[stack_ptr - 1] = get_unaligned_le32(&charbuf[0]);
break;
case OP_ISS:
/*
* IRSCAN short
* ...stack 0 is scan data
* ...stack 1 is count
*/
if (!altera_check_stack(stack_ptr, 2, &status))
break;
long_tmp = stack[--stack_ptr];
count = stack[--stack_ptr];
put_unaligned_le32(long_tmp, &charbuf[0]);
status = altera_irscan(astate, count, charbuf, 0);
break;
case OP_ISSC:
/*
* IRSCAN short with capture
* ...stack 0 is scan data
* ...stack 1 is count
*/
if (!altera_check_stack(stack_ptr, 2, &status))
break;
long_tmp = stack[--stack_ptr];
count = stack[stack_ptr - 1];
put_unaligned_le32(long_tmp, &charbuf[0]);
status = altera_swap_ir(astate, count, charbuf,
0, charbuf, 0);
stack[stack_ptr - 1] = get_unaligned_le32(&charbuf[0]);
break;
case OP_DPR:
if (!altera_check_stack(stack_ptr, 1, &status))
break;
count = stack[--stack_ptr];
status = altera_set_dr_pre(&astate->js, count, 0, NULL);
break;
case OP_DPRL:
/*
* DRPRE with literal data
* ...stack 0 is count
* ...stack 1 is literal data
*/
if (!altera_check_stack(stack_ptr, 2, &status))
break;
count = stack[--stack_ptr];
long_tmp = stack[--stack_ptr];
put_unaligned_le32(long_tmp, &charbuf[0]);
status = altera_set_dr_pre(&astate->js, count, 0,
charbuf);
break;
case OP_DPO:
/*
* DRPOST
* ...stack 0 is count
*/
if (altera_check_stack(stack_ptr, 1, &status)) {
count = stack[--stack_ptr];
status = altera_set_dr_post(&astate->js, count,
0, NULL);
}
break;
case OP_DPOL:
/*
* DRPOST with literal data
* ...stack 0 is count
* ...stack 1 is literal data
*/
if (!altera_check_stack(stack_ptr, 2, &status))
break;
count = stack[--stack_ptr];
long_tmp = stack[--stack_ptr];
put_unaligned_le32(long_tmp, &charbuf[0]);
status = altera_set_dr_post(&astate->js, count, 0,
charbuf);
break;
case OP_IPR:
if (altera_check_stack(stack_ptr, 1, &status)) {
count = stack[--stack_ptr];
status = altera_set_ir_pre(&astate->js, count,
0, NULL);
}
break;
case OP_IPRL:
/*
* IRPRE with literal data
* ...stack 0 is count
* ...stack 1 is literal data
*/
if (altera_check_stack(stack_ptr, 2, &status)) {
count = stack[--stack_ptr];
long_tmp = stack[--stack_ptr];
put_unaligned_le32(long_tmp, &charbuf[0]);
status = altera_set_ir_pre(&astate->js, count,
0, charbuf);
}
break;
case OP_IPO:
/*
* IRPOST
* ...stack 0 is count
*/
if (altera_check_stack(stack_ptr, 1, &status)) {
count = stack[--stack_ptr];
status = altera_set_ir_post(&astate->js, count,
0, NULL);
}
break;
case OP_IPOL:
/*
* IRPOST with literal data
* ...stack 0 is count
* ...stack 1 is literal data
*/
if (!altera_check_stack(stack_ptr, 2, &status))
break;
count = stack[--stack_ptr];
long_tmp = stack[--stack_ptr];
put_unaligned_le32(long_tmp, &charbuf[0]);
status = altera_set_ir_post(&astate->js, count, 0,
charbuf);
break;
case OP_PCHR:
if (altera_check_stack(stack_ptr, 1, &status)) {
u8 ch;
count = strlen(msg_buff);
ch = (char) stack[--stack_ptr];
if ((ch < 1) || (ch > 127)) {
/*
* character code out of range
* instead of flagging an error,
* force the value to 127
*/
ch = 127;
}
msg_buff[count] = ch;
msg_buff[count + 1] = '\0';
}
break;
case OP_EXIT:
if (altera_check_stack(stack_ptr, 1, &status))
*exit_code = stack[--stack_ptr];
done = 1;
break;
case OP_EQU:
if (!altera_check_stack(stack_ptr, 2, &status))
break;
--stack_ptr;
stack[stack_ptr - 1] =
(stack[stack_ptr - 1] == stack[stack_ptr]) ?
1L : 0L;
break;
case OP_POPT:
if (altera_check_stack(stack_ptr, 1, &status))
--stack_ptr;
break;
case OP_ABS:
if (!altera_check_stack(stack_ptr, 1, &status))
break;
if (stack[stack_ptr - 1] < 0)
stack[stack_ptr - 1] = 0 - stack[stack_ptr - 1];
break;
case OP_BCH0:
/*
* Batch operation 0
* SWP
* SWPN 7
* SWP
* SWPN 6
* DUPN 8
* SWPN 2
* SWP
* DUPN 6
* DUPN 6
*/
/* SWP */
if (altera_check_stack(stack_ptr, 2, &status)) {
long_tmp = stack[stack_ptr - 2];
stack[stack_ptr - 2] = stack[stack_ptr - 1];
stack[stack_ptr - 1] = long_tmp;
}
/* SWPN 7 */
index = 7 + 1;
if (altera_check_stack(stack_ptr, index, &status)) {
long_tmp = stack[stack_ptr - index];
stack[stack_ptr - index] = stack[stack_ptr - 1];
stack[stack_ptr - 1] = long_tmp;
}
/* SWP */
if (altera_check_stack(stack_ptr, 2, &status)) {
long_tmp = stack[stack_ptr - 2];
stack[stack_ptr - 2] = stack[stack_ptr - 1];
stack[stack_ptr - 1] = long_tmp;
}
/* SWPN 6 */
index = 6 + 1;
if (altera_check_stack(stack_ptr, index, &status)) {
long_tmp = stack[stack_ptr - index];
stack[stack_ptr - index] = stack[stack_ptr - 1];
stack[stack_ptr - 1] = long_tmp;
}
/* DUPN 8 */
index = 8 + 1;
if (altera_check_stack(stack_ptr, index, &status)) {
stack[stack_ptr] = stack[stack_ptr - index];
++stack_ptr;
}
/* SWPN 2 */
index = 2 + 1;
if (altera_check_stack(stack_ptr, index, &status)) {
long_tmp = stack[stack_ptr - index];
stack[stack_ptr - index] = stack[stack_ptr - 1];
stack[stack_ptr - 1] = long_tmp;
}
/* SWP */
if (altera_check_stack(stack_ptr, 2, &status)) {
long_tmp = stack[stack_ptr - 2];
stack[stack_ptr - 2] = stack[stack_ptr - 1];
stack[stack_ptr - 1] = long_tmp;
}
/* DUPN 6 */
index = 6 + 1;
if (altera_check_stack(stack_ptr, index, &status)) {
stack[stack_ptr] = stack[stack_ptr - index];
++stack_ptr;
}
/* DUPN 6 */
index = 6 + 1;
if (altera_check_stack(stack_ptr, index, &status)) {
stack[stack_ptr] = stack[stack_ptr - index];
++stack_ptr;
}
break;
case OP_PSH0:
stack[stack_ptr++] = 0;
break;
case OP_PSHL:
stack[stack_ptr++] = (s32) args[0];
break;
case OP_PSHV:
stack[stack_ptr++] = vars[args[0]];
break;
case OP_JMP:
pc = args[0] + code_sect;
if ((pc < code_sect) || (pc >= debug_sect))
status = -ERANGE;
break;
case OP_CALL:
stack[stack_ptr++] = pc;
pc = args[0] + code_sect;
if ((pc < code_sect) || (pc >= debug_sect))
status = -ERANGE;
break;
case OP_NEXT:
/*
* Process FOR / NEXT loop
* ...argument 0 is variable ID
* ...stack 0 is step value
* ...stack 1 is end value
* ...stack 2 is top address
*/
if (altera_check_stack(stack_ptr, 3, &status)) {
s32 step = stack[stack_ptr - 1];
s32 end = stack[stack_ptr - 2];
s32 top = stack[stack_ptr - 3];
s32 iterator = vars[args[0]];
int break_out = 0;
if (step < 0) {
if (iterator <= end)
break_out = 1;
} else if (iterator >= end)
break_out = 1;
if (break_out) {
stack_ptr -= 3;
} else {
vars[args[0]] = iterator + step;
pc = top + code_sect;
if ((pc < code_sect) ||
(pc >= debug_sect))
status = -ERANGE;
}
}
break;
case OP_PSTR:
/*
* PRINT add string
* ...argument 0 is string ID
*/
count = strlen(msg_buff);
strlcpy(&msg_buff[count],
&p[str_table + args[0]],
ALTERA_MESSAGE_LENGTH - count);
break;
case OP_SINT:
/*
* STATE intermediate state
* ...argument 0 is state code
*/
status = altera_goto_jstate(astate, args[0]);
break;
case OP_ST:
/*
* STATE final state
* ...argument 0 is state code
*/
status = altera_goto_jstate(astate, args[0]);
break;
case OP_ISTP:
/*
* IRSTOP state
* ...argument 0 is state code
*/
status = altera_set_irstop(&astate->js, args[0]);
break;
case OP_DSTP:
/*
* DRSTOP state
* ...argument 0 is state code
*/
status = altera_set_drstop(&astate->js, args[0]);
break;
case OP_SWPN:
/*
* Exchange top with Nth stack value
* ...argument 0 is 0-based stack entry
* to swap with top element
*/
index = (args[0]) + 1;
if (altera_check_stack(stack_ptr, index, &status)) {
long_tmp = stack[stack_ptr - index];
stack[stack_ptr - index] = stack[stack_ptr - 1];
stack[stack_ptr - 1] = long_tmp;
}
break;
case OP_DUPN:
/*
* Duplicate Nth stack value
* ...argument 0 is 0-based stack entry to duplicate
*/
index = (args[0]) + 1;
if (altera_check_stack(stack_ptr, index, &status)) {
stack[stack_ptr] = stack[stack_ptr - index];
++stack_ptr;
}
break;
case OP_POPV:
/*
* Pop stack into scalar variable
* ...argument 0 is variable ID
* ...stack 0 is value
*/
if (altera_check_stack(stack_ptr, 1, &status))
vars[args[0]] = stack[--stack_ptr];
break;
case OP_POPE:
/*
* Pop stack into integer array element
* ...argument 0 is variable ID
* ...stack 0 is array index
* ...stack 1 is value
*/
if (!altera_check_stack(stack_ptr, 2, &status))
break;
variable_id = args[0];
/*
* If variable is read-only,
* convert to writable array
*/
if ((version > 0) &&
((attrs[variable_id] & 0x9c) == 0x1c)) {
/* Allocate a writable buffer for this array */
count = var_size[variable_id];
long_tmp = vars[variable_id];
longptr_tmp = kzalloc(count * sizeof(long),
GFP_KERNEL);
vars[variable_id] = (long)longptr_tmp;
if (vars[variable_id] == 0) {
status = -ENOMEM;
break;
}
/* copy previous contents into buffer */
for (i = 0; i < count; ++i) {
longptr_tmp[i] =
get_unaligned_be32(&p[long_tmp]);
long_tmp += sizeof(long);
}
/*
* set bit 7 - buffer was
* dynamically allocated
*/
attrs[variable_id] |= 0x80;
/* clear bit 2 - variable is writable */
attrs[variable_id] &= ~0x04;
attrs[variable_id] |= 0x01;
}
/* check that variable is a writable integer array */
if ((attrs[variable_id] & 0x1c) != 0x18)
status = -ERANGE;
else {
longptr_tmp = (long *)vars[variable_id];
/* pop the array index */
index = stack[--stack_ptr];
/* pop the value and store it into the array */
longptr_tmp[index] = stack[--stack_ptr];
}
break;
case OP_POPA:
/*
* Pop stack into Boolean array
* ...argument 0 is variable ID
* ...stack 0 is count
* ...stack 1 is array index
* ...stack 2 is value
*/
if (!altera_check_stack(stack_ptr, 3, &status))
break;
variable_id = args[0];
/*
* If variable is read-only,
* convert to writable array
*/
if ((version > 0) &&
((attrs[variable_id] & 0x9c) == 0x0c)) {
/* Allocate a writable buffer for this array */
long_tmp =
(var_size[variable_id] + 7L) >> 3L;
charptr_tmp2 = (u8 *)vars[variable_id];
charptr_tmp =
kzalloc(long_tmp, GFP_KERNEL);
vars[variable_id] = (long)charptr_tmp;
if (vars[variable_id] == 0) {
status = -ENOMEM;
break;
}
/* zero the buffer */
for (long_idx = 0L;
long_idx < long_tmp;
++long_idx) {
charptr_tmp[long_idx] = 0;
}
/* copy previous contents into buffer */
for (long_idx = 0L;
long_idx < var_size[variable_id];
++long_idx) {
long_idx2 = long_idx;
if (charptr_tmp2[long_idx2 >> 3] &
(1 << (long_idx2 & 7))) {
charptr_tmp[long_idx >> 3] |=
(1 << (long_idx & 7));
}
}
/*
* set bit 7 - buffer was
* dynamically allocated
*/
attrs[variable_id] |= 0x80;
/* clear bit 2 - variable is writable */
attrs[variable_id] &= ~0x04;
attrs[variable_id] |= 0x01;
}
/*
* check that variable is
* a writable Boolean array
*/
if ((attrs[variable_id] & 0x1c) != 0x08) {
status = -ERANGE;
break;
}
charptr_tmp = (u8 *)vars[variable_id];
/* pop the count (number of bits to copy) */
long_count = stack[--stack_ptr];
/* pop the array index */
long_idx = stack[--stack_ptr];
reverse = 0;
if (version > 0) {
/*
* stack 0 = array right index
* stack 1 = array left index
*/
if (long_idx > long_count) {
reverse = 1;
long_tmp = long_count;
long_count = 1 + long_idx -
long_count;
long_idx = long_tmp;
/* reverse POPA is not supported */
status = -ERANGE;
break;
} else
long_count = 1 + long_count -
long_idx;
}
/* pop the data */
long_tmp = stack[--stack_ptr];
if (long_count < 1) {
status = -ERANGE;
break;
}
for (i = 0; i < long_count; ++i) {
if (long_tmp & (1L << (s32) i))
charptr_tmp[long_idx >> 3L] |=
(1L << (long_idx & 7L));
else
charptr_tmp[long_idx >> 3L] &=
~(1L << (long_idx & 7L));
++long_idx;
}
break;
case OP_JMPZ:
/*
* Pop stack and branch if zero
* ...argument 0 is address
* ...stack 0 is condition value
*/
if (altera_check_stack(stack_ptr, 1, &status)) {
if (stack[--stack_ptr] == 0) {
pc = args[0] + code_sect;
if ((pc < code_sect) ||
(pc >= debug_sect))
status = -ERANGE;
}
}
break;
case OP_DS:
case OP_IS:
/*
* DRSCAN
* IRSCAN
* ...argument 0 is scan data variable ID
* ...stack 0 is array index
* ...stack 1 is count
*/
if (!altera_check_stack(stack_ptr, 2, &status))
break;
long_idx = stack[--stack_ptr];
long_count = stack[--stack_ptr];
reverse = 0;
if (version > 0) {
/*
* stack 0 = array right index
* stack 1 = array left index
* stack 2 = count
*/
long_tmp = long_count;
long_count = stack[--stack_ptr];
if (long_idx > long_tmp) {
reverse = 1;
long_idx = long_tmp;
}
}
charptr_tmp = (u8 *)vars[args[0]];
if (reverse) {
/*
* allocate a buffer
* and reverse the data order
*/
charptr_tmp2 = charptr_tmp;
charptr_tmp = kzalloc((long_count >> 3) + 1,
GFP_KERNEL);
if (charptr_tmp == NULL) {
status = -ENOMEM;
break;
}
long_tmp = long_idx + long_count - 1;
long_idx2 = 0;
while (long_idx2 < long_count) {
if (charptr_tmp2[long_tmp >> 3] &
(1 << (long_tmp & 7)))
charptr_tmp[long_idx2 >> 3] |=
(1 << (long_idx2 & 7));
else
charptr_tmp[long_idx2 >> 3] &=
~(1 << (long_idx2 & 7));
--long_tmp;
++long_idx2;
}
}
if (opcode == 0x51) /* DS */
status = altera_drscan(astate, long_count,
charptr_tmp, long_idx);
else /* IS */
status = altera_irscan(astate, long_count,
charptr_tmp, long_idx);
if (reverse)
kfree(charptr_tmp);
break;
case OP_DPRA:
/*
* DRPRE with array data
* ...argument 0 is variable ID
* ...stack 0 is array index
* ...stack 1 is count
*/
if (!altera_check_stack(stack_ptr, 2, &status))
break;
index = stack[--stack_ptr];
count = stack[--stack_ptr];
if (version > 0)
/*
* stack 0 = array right index
* stack 1 = array left index
*/
count = 1 + count - index;
charptr_tmp = (u8 *)vars[args[0]];
status = altera_set_dr_pre(&astate->js, count, index,
charptr_tmp);
break;
case OP_DPOA:
/*
* DRPOST with array data
* ...argument 0 is variable ID
* ...stack 0 is array index
* ...stack 1 is count
*/
if (!altera_check_stack(stack_ptr, 2, &status))
break;
index = stack[--stack_ptr];
count = stack[--stack_ptr];
if (version > 0)
/*
* stack 0 = array right index
* stack 1 = array left index
*/
count = 1 + count - index;
charptr_tmp = (u8 *)vars[args[0]];
status = altera_set_dr_post(&astate->js, count, index,
charptr_tmp);
break;
case OP_IPRA:
/*
* IRPRE with array data
* ...argument 0 is variable ID
* ...stack 0 is array index
* ...stack 1 is count
*/
if (!altera_check_stack(stack_ptr, 2, &status))
break;
index = stack[--stack_ptr];
count = stack[--stack_ptr];
if (version > 0)
/*
* stack 0 = array right index
* stack 1 = array left index
*/
count = 1 + count - index;
charptr_tmp = (u8 *)vars[args[0]];
status = altera_set_ir_pre(&astate->js, count, index,
charptr_tmp);
break;
case OP_IPOA:
/*
* IRPOST with array data
* ...argument 0 is variable ID
* ...stack 0 is array index
* ...stack 1 is count
*/
if (!altera_check_stack(stack_ptr, 2, &status))
break;
index = stack[--stack_ptr];
count = stack[--stack_ptr];
if (version > 0)
/*
* stack 0 = array right index
* stack 1 = array left index
*/
count = 1 + count - index;
charptr_tmp = (u8 *)vars[args[0]];
status = altera_set_ir_post(&astate->js, count, index,
charptr_tmp);
break;
case OP_EXPT:
/*
* EXPORT
* ...argument 0 is string ID
* ...stack 0 is integer expression
*/
if (altera_check_stack(stack_ptr, 1, &status)) {
name = &p[str_table + args[0]];
long_tmp = stack[--stack_ptr];
altera_export_int(name, long_tmp);
}
break;
case OP_PSHE:
/*
* Push integer array element
* ...argument 0 is variable ID
* ...stack 0 is array index
*/
if (!altera_check_stack(stack_ptr, 1, &status))
break;
variable_id = args[0];
index = stack[stack_ptr - 1];
/* check variable type */
if ((attrs[variable_id] & 0x1f) == 0x19) {
/* writable integer array */
longptr_tmp = (long *)vars[variable_id];
stack[stack_ptr - 1] = longptr_tmp[index];
} else if ((attrs[variable_id] & 0x1f) == 0x1c) {
/* read-only integer array */
long_tmp = vars[variable_id] +
(index * sizeof(long));
stack[stack_ptr - 1] =
get_unaligned_be32(&p[long_tmp]);
} else
status = -ERANGE;
break;
case OP_PSHA:
/*
* Push Boolean array
* ...argument 0 is variable ID
* ...stack 0 is count
* ...stack 1 is array index
*/
if (!altera_check_stack(stack_ptr, 2, &status))
break;
variable_id = args[0];
/* check that variable is a Boolean array */
if ((attrs[variable_id] & 0x18) != 0x08) {
status = -ERANGE;
break;
}
charptr_tmp = (u8 *)vars[variable_id];
/* pop the count (number of bits to copy) */
count = stack[--stack_ptr];
/* pop the array index */
index = stack[stack_ptr - 1];
if (version > 0)
/*
* stack 0 = array right index
* stack 1 = array left index
*/
count = 1 + count - index;
if ((count < 1) || (count > 32)) {
status = -ERANGE;
break;
}
long_tmp = 0L;
for (i = 0; i < count; ++i)
if (charptr_tmp[(i + index) >> 3] &
(1 << ((i + index) & 7)))
long_tmp |= (1L << i);
stack[stack_ptr - 1] = long_tmp;
break;
case OP_DYNA:
/*
* Dynamically change size of array
* ...argument 0 is variable ID
* ...stack 0 is new size
*/
if (!altera_check_stack(stack_ptr, 1, &status))
break;
variable_id = args[0];
long_tmp = stack[--stack_ptr];
if (long_tmp > var_size[variable_id]) {
var_size[variable_id] = long_tmp;
if (attrs[variable_id] & 0x10)
/* allocate integer array */
long_tmp *= sizeof(long);
else
/* allocate Boolean array */
long_tmp = (long_tmp + 7) >> 3;
/*
* If the buffer was previously allocated,
* free it
*/
if (attrs[variable_id] & 0x80) {
kfree((void *)vars[variable_id]);
vars[variable_id] = 0;
}
/*
* Allocate a new buffer
* of the requested size
*/
vars[variable_id] = (long)
kzalloc(long_tmp, GFP_KERNEL);
if (vars[variable_id] == 0) {
status = -ENOMEM;
break;
}
/*
* Set the attribute bit to indicate that
* this buffer was dynamically allocated and
* should be freed later
*/
attrs[variable_id] |= 0x80;
/* zero out memory */
count = ((var_size[variable_id] + 7L) /
8L);
charptr_tmp = (u8 *)(vars[variable_id]);
for (index = 0; index < count; ++index)
charptr_tmp[index] = 0;
}
break;
case OP_EXPV:
/*
* Export Boolean array
* ...argument 0 is string ID
* ...stack 0 is variable ID
* ...stack 1 is array right index
* ...stack 2 is array left index
*/
if (!altera_check_stack(stack_ptr, 3, &status))
break;
if (version == 0) {
/* EXPV is not supported in JBC 1.0 */
bad_opcode = 1;
break;
}
name = &p[str_table + args[0]];
variable_id = stack[--stack_ptr];
long_idx = stack[--stack_ptr];/* right indx */
long_idx2 = stack[--stack_ptr];/* left indx */
if (long_idx > long_idx2) {
/* reverse indices not supported */
status = -ERANGE;
break;
}
long_count = 1 + long_idx2 - long_idx;
charptr_tmp = (u8 *)vars[variable_id];
charptr_tmp2 = NULL;
if ((long_idx & 7L) != 0) {
s32 k = long_idx;
charptr_tmp2 =
kzalloc(((long_count + 7L) / 8L),
GFP_KERNEL);
if (charptr_tmp2 == NULL) {
status = -ENOMEM;
break;
}
for (i = 0; i < long_count; ++i) {
if (charptr_tmp[k >> 3] &
(1 << (k & 7)))
charptr_tmp2[i >> 3] |=
(1 << (i & 7));
else
charptr_tmp2[i >> 3] &=
~(1 << (i & 7));
++k;
}
charptr_tmp = charptr_tmp2;
} else if (long_idx != 0)
charptr_tmp = &charptr_tmp[long_idx >> 3];
altera_export_bool_array(name, charptr_tmp,
long_count);
/* free allocated buffer */
if ((long_idx & 7L) != 0)
kfree(charptr_tmp2);
break;
case OP_COPY: {
/*
* Array copy
* ...argument 0 is dest ID
* ...argument 1 is source ID
* ...stack 0 is count
* ...stack 1 is dest index
* ...stack 2 is source index
*/
s32 copy_count;
s32 copy_index;
s32 copy_index2;
s32 destleft;
s32 src_count;
s32 dest_count;
int src_reverse = 0;
int dest_reverse = 0;
if (!altera_check_stack(stack_ptr, 3, &status))
break;
copy_count = stack[--stack_ptr];
copy_index = stack[--stack_ptr];
copy_index2 = stack[--stack_ptr];
reverse = 0;
if (version > 0) {
/*
* stack 0 = source right index
* stack 1 = source left index
* stack 2 = destination right index
* stack 3 = destination left index
*/
destleft = stack[--stack_ptr];
if (copy_count > copy_index) {
src_reverse = 1;
reverse = 1;
src_count = 1 + copy_count - copy_index;
/* copy_index = source start index */
} else {
src_count = 1 + copy_index - copy_count;
/* source start index */
copy_index = copy_count;
}
if (copy_index2 > destleft) {
dest_reverse = 1;
reverse = !reverse;
dest_count = 1 + copy_index2 - destleft;
/* destination start index */
copy_index2 = destleft;
} else
dest_count = 1 + destleft - copy_index2;
copy_count = (src_count < dest_count) ?
src_count : dest_count;
if ((src_reverse || dest_reverse) &&
(src_count != dest_count))
/*
* If either the source or destination
* is reversed, we can't tolerate
* a length mismatch, because we
* "left justify" arrays when copying.
* This won't work correctly
* with reversed arrays.
*/
status = -ERANGE;
}
count = copy_count;
index = copy_index;
index2 = copy_index2;
/*
* If destination is a read-only array,
* allocate a buffer and convert it to a writable array
*/
variable_id = args[1];
if ((version > 0) &&
((attrs[variable_id] & 0x9c) == 0x0c)) {
/* Allocate a writable buffer for this array */
long_tmp =
(var_size[variable_id] + 7L) >> 3L;
charptr_tmp2 = (u8 *)vars[variable_id];
charptr_tmp =
kzalloc(long_tmp, GFP_KERNEL);
vars[variable_id] = (long)charptr_tmp;
if (vars[variable_id] == 0) {
status = -ENOMEM;
break;
}
/* zero the buffer */
for (long_idx = 0L; long_idx < long_tmp;
++long_idx)
charptr_tmp[long_idx] = 0;
/* copy previous contents into buffer */
for (long_idx = 0L;
long_idx < var_size[variable_id];
++long_idx) {
long_idx2 = long_idx;
if (charptr_tmp2[long_idx2 >> 3] &
(1 << (long_idx2 & 7)))
charptr_tmp[long_idx >> 3] |=
(1 << (long_idx & 7));
}
/*
set bit 7 - buffer was dynamically allocated */
attrs[variable_id] |= 0x80;
/* clear bit 2 - variable is writable */
attrs[variable_id] &= ~0x04;
attrs[variable_id] |= 0x01;
}
charptr_tmp = (u8 *)vars[args[1]];
charptr_tmp2 = (u8 *)vars[args[0]];
/* check if destination is a writable Boolean array */
if ((attrs[args[1]] & 0x1c) != 0x08) {
status = -ERANGE;
break;
}
if (count < 1) {
status = -ERANGE;
break;
}
if (reverse)
index2 += (count - 1);
for (i = 0; i < count; ++i) {
if (charptr_tmp2[index >> 3] &
(1 << (index & 7)))
charptr_tmp[index2 >> 3] |=
(1 << (index2 & 7));
else
charptr_tmp[index2 >> 3] &=
~(1 << (index2 & 7));
++index;
if (reverse)
--index2;
else
++index2;
}
break;
}
case OP_DSC:
case OP_ISC: {
/*
* DRSCAN with capture
* IRSCAN with capture
* ...argument 0 is scan data variable ID
* ...argument 1 is capture variable ID
* ...stack 0 is capture index
* ...stack 1 is scan data index
* ...stack 2 is count
*/
s32 scan_right, scan_left;
s32 capture_count = 0;
s32 scan_count = 0;
s32 capture_index;
s32 scan_index;
if (!altera_check_stack(stack_ptr, 3, &status))
break;
capture_index = stack[--stack_ptr];
scan_index = stack[--stack_ptr];
if (version > 0) {
/*
* stack 0 = capture right index
* stack 1 = capture left index
* stack 2 = scan right index
* stack 3 = scan left index
* stack 4 = count
*/
scan_right = stack[--stack_ptr];
scan_left = stack[--stack_ptr];
capture_count = 1 + scan_index - capture_index;
scan_count = 1 + scan_left - scan_right;
scan_index = scan_right;
}
long_count = stack[--stack_ptr];
/*
* If capture array is read-only, allocate a buffer
* and convert it to a writable array
*/
variable_id = args[1];
if ((version > 0) &&
((attrs[variable_id] & 0x9c) == 0x0c)) {
/* Allocate a writable buffer for this array */
long_tmp =
(var_size[variable_id] + 7L) >> 3L;
charptr_tmp2 = (u8 *)vars[variable_id];
charptr_tmp =
kzalloc(long_tmp, GFP_KERNEL);
vars[variable_id] = (long)charptr_tmp;
if (vars[variable_id] == 0) {
status = -ENOMEM;
break;
}
/* zero the buffer */
for (long_idx = 0L; long_idx < long_tmp;
++long_idx)
charptr_tmp[long_idx] = 0;
/* copy previous contents into buffer */
for (long_idx = 0L;
long_idx < var_size[variable_id];
++long_idx) {
long_idx2 = long_idx;
if (charptr_tmp2[long_idx2 >> 3] &
(1 << (long_idx2 & 7)))
charptr_tmp[long_idx >> 3] |=
(1 << (long_idx & 7));
}
/*
* set bit 7 - buffer was
* dynamically allocated
*/
attrs[variable_id] |= 0x80;
/* clear bit 2 - variable is writable */
attrs[variable_id] &= ~0x04;
attrs[variable_id] |= 0x01;
}
charptr_tmp = (u8 *)vars[args[0]];
charptr_tmp2 = (u8 *)vars[args[1]];
if ((version > 0) &&
((long_count > capture_count) ||
(long_count > scan_count))) {
status = -ERANGE;
break;
}
/*
* check that capture array
* is a writable Boolean array
*/
if ((attrs[args[1]] & 0x1c) != 0x08) {
status = -ERANGE;
break;
}
if (status == 0) {
if (opcode == 0x82) /* DSC */
status = altera_swap_dr(astate,
long_count,
charptr_tmp,
scan_index,
charptr_tmp2,
capture_index);
else /* ISC */
status = altera_swap_ir(astate,
long_count,
charptr_tmp,
scan_index,
charptr_tmp2,
capture_index);
}
break;
}
case OP_WAIT:
/*
* WAIT
* ...argument 0 is wait state
* ...argument 1 is end state
* ...stack 0 is cycles
* ...stack 1 is microseconds
*/
if (!altera_check_stack(stack_ptr, 2, &status))
break;
long_tmp = stack[--stack_ptr];
if (long_tmp != 0L)
status = altera_wait_cycles(astate, long_tmp,
args[0]);
long_tmp = stack[--stack_ptr];
if ((status == 0) && (long_tmp != 0L))
status = altera_wait_msecs(astate,
long_tmp,
args[0]);
if ((status == 0) && (args[1] != args[0]))
status = altera_goto_jstate(astate,
args[1]);
if (version > 0) {
--stack_ptr; /* throw away MAX cycles */
--stack_ptr; /* throw away MAX microseconds */
}
break;
case OP_CMPA: {
/*
* Array compare
* ...argument 0 is source 1 ID
* ...argument 1 is source 2 ID
* ...argument 2 is mask ID
* ...stack 0 is source 1 index
* ...stack 1 is source 2 index
* ...stack 2 is mask index
* ...stack 3 is count
*/
s32 a, b;
u8 *source1 = (u8 *)vars[args[0]];
u8 *source2 = (u8 *)vars[args[1]];
u8 *mask = (u8 *)vars[args[2]];
u32 index1;
u32 index2;
u32 mask_index;
if (!altera_check_stack(stack_ptr, 4, &status))
break;
index1 = stack[--stack_ptr];
index2 = stack[--stack_ptr];
mask_index = stack[--stack_ptr];
long_count = stack[--stack_ptr];
if (version > 0) {
/*
* stack 0 = source 1 right index
* stack 1 = source 1 left index
* stack 2 = source 2 right index
* stack 3 = source 2 left index
* stack 4 = mask right index
* stack 5 = mask left index
*/
s32 mask_right = stack[--stack_ptr];
s32 mask_left = stack[--stack_ptr];
/* source 1 count */
a = 1 + index2 - index1;
/* source 2 count */
b = 1 + long_count - mask_index;
a = (a < b) ? a : b;
/* mask count */
b = 1 + mask_left - mask_right;
a = (a < b) ? a : b;
/* source 2 start index */
index2 = mask_index;
/* mask start index */
mask_index = mask_right;
long_count = a;
}
long_tmp = 1L;
if (long_count < 1)
status = -ERANGE;
else {
count = long_count;
for (i = 0; i < count; ++i) {
if (mask[mask_index >> 3] &
(1 << (mask_index & 7))) {
a = source1[index1 >> 3] &
(1 << (index1 & 7))
? 1 : 0;
b = source2[index2 >> 3] &
(1 << (index2 & 7))
? 1 : 0;
if (a != b) /* failure */
long_tmp = 0L;
}
++index1;
++index2;
++mask_index;
}
}
stack[stack_ptr++] = long_tmp;
break;
}
default:
/* Unrecognized opcode -- ERROR! */
bad_opcode = 1;
break;
}
if (bad_opcode)
status = -ENOSYS;
if ((stack_ptr < 0) || (stack_ptr >= ALTERA_STACK_SIZE))
status = -EOVERFLOW;
if (status != 0) {
done = 1;
*error_address = (s32)(opcode_address - code_sect);
}
}
altera_free_buffers(astate);
/* Free all dynamically allocated arrays */
if ((attrs != NULL) && (vars != NULL))
for (i = 0; i < sym_count; ++i)
if (attrs[i] & 0x80)
kfree((void *)vars[i]);
kfree(vars);
kfree(var_size);
kfree(attrs);
kfree(proc_attributes);
return status;
}
static int altera_get_note(u8 *p, s32 program_size,
s32 *offset, char *key, char *value, int length)
/*
* Gets key and value of NOTE fields in the JBC file.
* Can be called in two modes: if offset pointer is NULL,
* then the function searches for note fields which match
* the key string provided. If offset is not NULL, then
* the function finds the next note field of any key,
* starting at the offset specified by the offset pointer.
* Returns 0 for success, else appropriate error code
*/
{
int status = -ENODATA;
u32 note_strings = 0L;
u32 note_table = 0L;
u32 note_count = 0L;
u32 first_word = 0L;
int version = 0;
int delta = 0;
char *key_ptr;
char *value_ptr;
int i;
/* Read header information */
if (program_size > 52L) {
first_word = get_unaligned_be32(&p[0]);
version = (first_word & 1L);
delta = version * 8;
note_strings = get_unaligned_be32(&p[8 + delta]);
note_table = get_unaligned_be32(&p[12 + delta]);
note_count = get_unaligned_be32(&p[44 + (2 * delta)]);
}
if ((first_word != 0x4A414D00L) && (first_word != 0x4A414D01L))
return -EIO;
if (note_count <= 0L)
return status;
if (offset == NULL) {
/*
* We will search for the first note with a specific key,
* and return only the value
*/
for (i = 0; (i < note_count) &&
(status != 0); ++i) {
key_ptr = &p[note_strings +
get_unaligned_be32(
&p[note_table + (8 * i)])];
if ((strnicmp(key, key_ptr, strlen(key_ptr)) == 0) &&
(key != NULL)) {
status = 0;
value_ptr = &p[note_strings +
get_unaligned_be32(
&p[note_table + (8 * i) + 4])];
if (value != NULL)
strlcpy(value, value_ptr, length);
}
}
} else {
/*
* We will search for the next note, regardless of the key,
* and return both the value and the key
*/
i = *offset;
if ((i >= 0) && (i < note_count)) {
status = 0;
if (key != NULL)
strlcpy(key, &p[note_strings +
get_unaligned_be32(
&p[note_table + (8 * i)])],
length);
if (value != NULL)
strlcpy(value, &p[note_strings +
get_unaligned_be32(
&p[note_table + (8 * i) + 4])],
length);
*offset = i + 1;
}
}
return status;
}
static int altera_check_crc(u8 *p, s32 program_size)
{
int status = 0;
u16 local_expected = 0,
local_actual = 0,
shift_reg = 0xffff;
int bit, feedback;
u8 databyte;
u32 i;
u32 crc_section = 0L;
u32 first_word = 0L;
int version = 0;
int delta = 0;
if (program_size > 52L) {
first_word = get_unaligned_be32(&p[0]);
version = (first_word & 1L);
delta = version * 8;
crc_section = get_unaligned_be32(&p[32 + delta]);
}
if ((first_word != 0x4A414D00L) && (first_word != 0x4A414D01L))
status = -EIO;
if (crc_section >= program_size)
status = -EIO;
if (status == 0) {
local_expected = (u16)get_unaligned_be16(&p[crc_section]);
for (i = 0; i < crc_section; ++i) {
databyte = p[i];
for (bit = 0; bit < 8; bit++) {
feedback = (databyte ^ shift_reg) & 0x01;
shift_reg >>= 1;
if (feedback)
shift_reg ^= 0x8408;
databyte >>= 1;
}
}
local_actual = (u16)~shift_reg;
if (local_expected != local_actual)
status = -EILSEQ;
}
if (debug || status) {
switch (status) {
case 0:
printk(KERN_INFO "%s: CRC matched: %04x\n", __func__,
local_actual);
break;
case -EILSEQ:
printk(KERN_ERR "%s: CRC mismatch: expected %04x, "
"actual %04x\n", __func__, local_expected,
local_actual);
break;
case -ENODATA:
printk(KERN_ERR "%s: expected CRC not found, "
"actual CRC = %04x\n", __func__,
local_actual);
break;
case -EIO:
printk(KERN_ERR "%s: error: format isn't "
"recognized.\n", __func__);
break;
default:
printk(KERN_ERR "%s: CRC function returned error "
"code %d\n", __func__, status);
break;
}
}
return status;
}
static int altera_get_file_info(u8 *p,
s32 program_size,
int *format_version,
int *action_count,
int *procedure_count)
{
int status = -EIO;
u32 first_word = 0;
int version = 0;
if (program_size <= 52L)
return status;
first_word = get_unaligned_be32(&p[0]);
if ((first_word == 0x4A414D00L) || (first_word == 0x4A414D01L)) {
status = 0;
version = (first_word & 1L);
*format_version = version + 1;
if (version > 0) {
*action_count = get_unaligned_be32(&p[48]);
*procedure_count = get_unaligned_be32(&p[52]);
}
}
return status;
}
static int altera_get_act_info(u8 *p,
s32 program_size,
int index,
char **name,
char **description,
struct altera_procinfo **proc_list)
{
int status = -EIO;
struct altera_procinfo *procptr = NULL;
struct altera_procinfo *tmpptr = NULL;
u32 first_word = 0L;
u32 action_table = 0L;
u32 proc_table = 0L;
u32 str_table = 0L;
u32 note_strings = 0L;
u32 action_count = 0L;
u32 proc_count = 0L;
u32 act_name_id = 0L;
u32 act_desc_id = 0L;
u32 act_proc_id = 0L;
u32 act_proc_name = 0L;
u8 act_proc_attribute = 0;
if (program_size <= 52L)
return status;
/* Read header information */
first_word = get_unaligned_be32(&p[0]);
if (first_word != 0x4A414D01L)
return status;
action_table = get_unaligned_be32(&p[4]);
proc_table = get_unaligned_be32(&p[8]);
str_table = get_unaligned_be32(&p[12]);
note_strings = get_unaligned_be32(&p[16]);
action_count = get_unaligned_be32(&p[48]);
proc_count = get_unaligned_be32(&p[52]);
if (index >= action_count)
return status;
act_name_id = get_unaligned_be32(&p[action_table + (12 * index)]);
act_desc_id = get_unaligned_be32(&p[action_table + (12 * index) + 4]);
act_proc_id = get_unaligned_be32(&p[action_table + (12 * index) + 8]);
*name = &p[str_table + act_name_id];
if (act_desc_id < (note_strings - str_table))
*description = &p[str_table + act_desc_id];
do {
act_proc_name = get_unaligned_be32(
&p[proc_table + (13 * act_proc_id)]);
act_proc_attribute =
(p[proc_table + (13 * act_proc_id) + 8] & 0x03);
procptr = (struct altera_procinfo *)
kzalloc(sizeof(struct altera_procinfo),
GFP_KERNEL);
if (procptr == NULL)
status = -ENOMEM;
else {
procptr->name = &p[str_table + act_proc_name];
procptr->attrs = act_proc_attribute;
procptr->next = NULL;
/* add record to end of linked list */
if (*proc_list == NULL)
*proc_list = procptr;
else {
tmpptr = *proc_list;
while (tmpptr->next != NULL)
tmpptr = tmpptr->next;
tmpptr->next = procptr;
}
}
act_proc_id = get_unaligned_be32(
&p[proc_table + (13 * act_proc_id) + 4]);
} while ((act_proc_id != 0) && (act_proc_id < proc_count));
return status;
}
int altera_init(struct altera_config *config, const struct firmware *fw)
{
struct altera_state *astate = NULL;
struct altera_procinfo *proc_list = NULL;
struct altera_procinfo *procptr = NULL;
char *key = NULL;
char *value = NULL;
char *action_name = NULL;
char *description = NULL;
int exec_result = 0;
int exit_code = 0;
int format_version = 0;
int action_count = 0;
int procedure_count = 0;
int index = 0;
s32 offset = 0L;
s32 error_address = 0L;
key = kzalloc(33 * sizeof(char), GFP_KERNEL);
if (!key)
return -ENOMEM;
value = kzalloc(257 * sizeof(char), GFP_KERNEL);
if (!value)
return -ENOMEM;
astate = kzalloc(sizeof(struct altera_state), GFP_KERNEL);
if (!astate)
return -ENOMEM;
astate->config = config;
if (!astate->config->jtag_io) {
dprintk(KERN_INFO "%s: using byteblaster!\n", __func__);
astate->config->jtag_io = netup_jtag_io_lpt;
}
altera_check_crc((u8 *)fw->data, fw->size);
if (debug) {
altera_get_file_info((u8 *)fw->data, fw->size, &format_version,
&action_count, &procedure_count);
printk(KERN_INFO "%s: File format is %s ByteCode format\n",
__func__, (format_version == 2) ? "Jam STAPL" :
"pre-standardized Jam 1.1");
while (altera_get_note((u8 *)fw->data, fw->size,
&offset, key, value, 256) == 0)
printk(KERN_INFO "%s: NOTE \"%s\" = \"%s\"\n",
__func__, key, value);
}
if (debug && (format_version == 2) && (action_count > 0)) {
printk(KERN_INFO "%s: Actions available:\n", __func__);
for (index = 0; index < action_count; ++index) {
altera_get_act_info((u8 *)fw->data, fw->size,
index, &action_name,
&description,
&proc_list);
if (description == NULL)
printk(KERN_INFO "%s: %s\n",
__func__,
action_name);
else
printk(KERN_INFO "%s: %s \"%s\"\n",
__func__,
action_name,
description);
procptr = proc_list;
while (procptr != NULL) {
if (procptr->attrs != 0)
printk(KERN_INFO "%s: %s (%s)\n",
__func__,
procptr->name,
(procptr->attrs == 1) ?
"optional" : "recommended");
proc_list = procptr->next;
kfree(procptr);
procptr = proc_list;
}
}
printk(KERN_INFO "\n");
}
exec_result = altera_execute(astate, (u8 *)fw->data, fw->size,
&error_address, &exit_code, &format_version);
if (exit_code)
exec_result = -EREMOTEIO;
if ((format_version == 2) && (exec_result == -EINVAL)) {
if (astate->config->action == NULL)
printk(KERN_ERR "%s: error: no action specified for "
"Jam STAPL file.\nprogram terminated.\n",
__func__);
else
printk(KERN_ERR "%s: error: action \"%s\""
" is not supported "
"for this Jam STAPL file.\n"
"Program terminated.\n", __func__,
astate->config->action);
} else if (exec_result)
printk(KERN_ERR "%s: error %d\n", __func__, exec_result);
kfree(key);
kfree(value);
kfree(astate);
return 0;
}
EXPORT_SYMBOL(altera_init);
| gpl-2.0 |
markcn/kernel_huawei_c8812 | drivers/staging/gma500/psb_2d.c | 2386 | 10443 | /**************************************************************************
* Copyright (c) 2007, Intel Corporation.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
* Intel funded Tungsten Graphics (http://www.tungstengraphics.com) to
* develop this driver.
*
**************************************************************************/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/tty.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/fb.h>
#include <linux/init.h>
#include <linux/console.h>
#include <drm/drmP.h>
#include <drm/drm.h>
#include <drm/drm_crtc.h>
#include "psb_drv.h"
#include "psb_reg.h"
#include "psb_drv.h"
#include "psb_fb.h"
void psb_spank(struct drm_psb_private *dev_priv)
{
PSB_WSGX32(_PSB_CS_RESET_BIF_RESET | _PSB_CS_RESET_DPM_RESET |
_PSB_CS_RESET_TA_RESET | _PSB_CS_RESET_USE_RESET |
_PSB_CS_RESET_ISP_RESET | _PSB_CS_RESET_TSP_RESET |
_PSB_CS_RESET_TWOD_RESET, PSB_CR_SOFT_RESET);
(void) PSB_RSGX32(PSB_CR_SOFT_RESET);
msleep(1);
PSB_WSGX32(0, PSB_CR_SOFT_RESET);
wmb();
PSB_WSGX32(PSB_RSGX32(PSB_CR_BIF_CTRL) | _PSB_CB_CTRL_CLEAR_FAULT,
PSB_CR_BIF_CTRL);
wmb();
(void) PSB_RSGX32(PSB_CR_BIF_CTRL);
msleep(1);
PSB_WSGX32(PSB_RSGX32(PSB_CR_BIF_CTRL) & ~_PSB_CB_CTRL_CLEAR_FAULT,
PSB_CR_BIF_CTRL);
(void) PSB_RSGX32(PSB_CR_BIF_CTRL);
PSB_WSGX32(dev_priv->pg->gatt_start, PSB_CR_BIF_TWOD_REQ_BASE);
}
static int psb_2d_wait_available(struct drm_psb_private *dev_priv,
unsigned size)
{
uint32_t avail = PSB_RSGX32(PSB_CR_2D_SOCIF);
unsigned long t = jiffies + HZ;
while(avail < size) {
avail = PSB_RSGX32(PSB_CR_2D_SOCIF);
if (time_after(jiffies, t)) {
psb_spank(dev_priv);
return -EIO;
}
}
return 0;
}
/* FIXME: Remember if we expose the 2D engine to the DRM we need to serialize
it with console use */
int psbfb_2d_submit(struct drm_psb_private *dev_priv, uint32_t *cmdbuf,
unsigned size)
{
int ret = 0;
int i;
unsigned submit_size;
while (size > 0) {
submit_size = (size < 0x60) ? size : 0x60;
size -= submit_size;
ret = psb_2d_wait_available(dev_priv, submit_size);
if (ret)
return ret;
submit_size <<= 2;
for (i = 0; i < submit_size; i += 4) {
PSB_WSGX32(*cmdbuf++, PSB_SGX_2D_SLAVE_PORT + i);
}
(void)PSB_RSGX32(PSB_SGX_2D_SLAVE_PORT + i - 4);
}
return 0;
}
static int psb_accel_2d_fillrect(struct drm_psb_private *dev_priv,
uint32_t dst_offset, uint32_t dst_stride,
uint32_t dst_format, uint16_t dst_x,
uint16_t dst_y, uint16_t size_x,
uint16_t size_y, uint32_t fill)
{
uint32_t buffer[10];
uint32_t *buf;
buf = buffer;
*buf++ = PSB_2D_FENCE_BH;
*buf++ =
PSB_2D_DST_SURF_BH | dst_format | (dst_stride <<
PSB_2D_DST_STRIDE_SHIFT);
*buf++ = dst_offset;
*buf++ =
PSB_2D_BLIT_BH |
PSB_2D_ROT_NONE |
PSB_2D_COPYORDER_TL2BR |
PSB_2D_DSTCK_DISABLE |
PSB_2D_SRCCK_DISABLE | PSB_2D_USE_FILL | PSB_2D_ROP3_PATCOPY;
*buf++ = fill << PSB_2D_FILLCOLOUR_SHIFT;
*buf++ =
(dst_x << PSB_2D_DST_XSTART_SHIFT) | (dst_y <<
PSB_2D_DST_YSTART_SHIFT);
*buf++ =
(size_x << PSB_2D_DST_XSIZE_SHIFT) | (size_y <<
PSB_2D_DST_YSIZE_SHIFT);
*buf++ = PSB_2D_FLUSH_BH;
return psbfb_2d_submit(dev_priv, buffer, buf - buffer);
}
static void psbfb_fillrect_accel(struct fb_info *info,
const struct fb_fillrect *r)
{
struct psb_fbdev *fbdev = info->par;
struct psb_framebuffer *psbfb = fbdev->pfb;
struct drm_device *dev = psbfb->base.dev;
struct drm_framebuffer *fb = fbdev->psb_fb_helper.fb;
struct drm_psb_private *dev_priv = dev->dev_private;
uint32_t offset;
uint32_t stride;
uint32_t format;
if (!fb)
return;
offset = psbfb->gtt->offset;
stride = fb->pitch;
switch (fb->depth) {
case 8:
format = PSB_2D_DST_332RGB;
break;
case 15:
format = PSB_2D_DST_555RGB;
break;
case 16:
format = PSB_2D_DST_565RGB;
break;
case 24:
case 32:
/* this is wrong but since we don't do blending its okay */
format = PSB_2D_DST_8888ARGB;
break;
default:
/* software fallback */
cfb_fillrect(info, r);
return;
}
psb_accel_2d_fillrect(dev_priv,
offset, stride, format,
r->dx, r->dy, r->width, r->height, r->color);
}
void psbfb_fillrect(struct fb_info *info,
const struct fb_fillrect *rect)
{
if (unlikely(info->state != FBINFO_STATE_RUNNING))
return;
if (1 || (info->flags & FBINFO_HWACCEL_DISABLED))
return cfb_fillrect(info, rect);
/*psb_check_power_state(dev, PSB_DEVICE_SGX); */
psbfb_fillrect_accel(info, rect);
/* Drop power again here on MRST FIXMEAC */
}
static u32 psb_accel_2d_copy_direction(int xdir, int ydir)
{
if (xdir < 0)
return (ydir < 0) ? PSB_2D_COPYORDER_BR2TL :
PSB_2D_COPYORDER_TR2BL;
else
return (ydir < 0) ? PSB_2D_COPYORDER_BL2TR :
PSB_2D_COPYORDER_TL2BR;
}
/*
* @src_offset in bytes
* @src_stride in bytes
* @src_format psb 2D format defines
* @dst_offset in bytes
* @dst_stride in bytes
* @dst_format psb 2D format defines
* @src_x offset in pixels
* @src_y offset in pixels
* @dst_x offset in pixels
* @dst_y offset in pixels
* @size_x of the copied area
* @size_y of the copied area
*/
static int psb_accel_2d_copy(struct drm_psb_private *dev_priv,
uint32_t src_offset, uint32_t src_stride,
uint32_t src_format, uint32_t dst_offset,
uint32_t dst_stride, uint32_t dst_format,
uint16_t src_x, uint16_t src_y,
uint16_t dst_x, uint16_t dst_y,
uint16_t size_x, uint16_t size_y)
{
uint32_t blit_cmd;
uint32_t buffer[10];
uint32_t *buf;
uint32_t direction;
buf = buffer;
direction =
psb_accel_2d_copy_direction(src_x - dst_x, src_y - dst_y);
if (direction == PSB_2D_COPYORDER_BR2TL ||
direction == PSB_2D_COPYORDER_TR2BL) {
src_x += size_x - 1;
dst_x += size_x - 1;
}
if (direction == PSB_2D_COPYORDER_BR2TL ||
direction == PSB_2D_COPYORDER_BL2TR) {
src_y += size_y - 1;
dst_y += size_y - 1;
}
blit_cmd =
PSB_2D_BLIT_BH |
PSB_2D_ROT_NONE |
PSB_2D_DSTCK_DISABLE |
PSB_2D_SRCCK_DISABLE |
PSB_2D_USE_PAT | PSB_2D_ROP3_SRCCOPY | direction;
*buf++ = PSB_2D_FENCE_BH;
*buf++ =
PSB_2D_DST_SURF_BH | dst_format | (dst_stride <<
PSB_2D_DST_STRIDE_SHIFT);
*buf++ = dst_offset;
*buf++ =
PSB_2D_SRC_SURF_BH | src_format | (src_stride <<
PSB_2D_SRC_STRIDE_SHIFT);
*buf++ = src_offset;
*buf++ =
PSB_2D_SRC_OFF_BH | (src_x << PSB_2D_SRCOFF_XSTART_SHIFT) |
(src_y << PSB_2D_SRCOFF_YSTART_SHIFT);
*buf++ = blit_cmd;
*buf++ =
(dst_x << PSB_2D_DST_XSTART_SHIFT) | (dst_y <<
PSB_2D_DST_YSTART_SHIFT);
*buf++ =
(size_x << PSB_2D_DST_XSIZE_SHIFT) | (size_y <<
PSB_2D_DST_YSIZE_SHIFT);
*buf++ = PSB_2D_FLUSH_BH;
return psbfb_2d_submit(dev_priv, buffer, buf - buffer);
}
static void psbfb_copyarea_accel(struct fb_info *info,
const struct fb_copyarea *a)
{
struct psb_fbdev *fbdev = info->par;
struct psb_framebuffer *psbfb = fbdev->pfb;
struct drm_device *dev = psbfb->base.dev;
struct drm_framebuffer *fb = fbdev->psb_fb_helper.fb;
struct drm_psb_private *dev_priv = dev->dev_private;
uint32_t offset;
uint32_t stride;
uint32_t src_format;
uint32_t dst_format;
if (!fb)
return;
offset = psbfb->gtt->offset;
stride = fb->pitch;
switch (fb->depth) {
case 8:
src_format = PSB_2D_SRC_332RGB;
dst_format = PSB_2D_DST_332RGB;
break;
case 15:
src_format = PSB_2D_SRC_555RGB;
dst_format = PSB_2D_DST_555RGB;
break;
case 16:
src_format = PSB_2D_SRC_565RGB;
dst_format = PSB_2D_DST_565RGB;
break;
case 24:
case 32:
/* this is wrong but since we don't do blending its okay */
src_format = PSB_2D_SRC_8888ARGB;
dst_format = PSB_2D_DST_8888ARGB;
break;
default:
/* software fallback */
cfb_copyarea(info, a);
return;
}
psb_accel_2d_copy(dev_priv,
offset, stride, src_format,
offset, stride, dst_format,
a->sx, a->sy, a->dx, a->dy, a->width, a->height);
}
void psbfb_copyarea(struct fb_info *info,
const struct fb_copyarea *region)
{
if (unlikely(info->state != FBINFO_STATE_RUNNING))
return;
if (info->flags & FBINFO_HWACCEL_DISABLED)
return cfb_copyarea(info, region);
/* psb_check_power_state(dev, PSB_DEVICE_SGX); */
psbfb_copyarea_accel(info, region);
/* Need to power back off here for MRST FIXMEAC */
}
void psbfb_imageblit(struct fb_info *info, const struct fb_image *image)
{
/* For now */
cfb_imageblit(info, image);
}
int psbfb_sync(struct fb_info *info)
{
struct psb_fbdev *fbdev = info->par;
struct psb_framebuffer *psbfb = fbdev->pfb;
struct drm_device *dev = psbfb->base.dev;
struct drm_psb_private *dev_priv = dev->dev_private;
unsigned long _end = jiffies + DRM_HZ;
int busy = 0;
#if 0
/* Just a way to quickly test if cmd issue explodes */
u32 test[2] = {
PSB_2D_FENCE_BH,
};
psbfb_2d_submit(dev_priv, test, 1);
#endif
/*
* First idle the 2D engine.
*/
if ((PSB_RSGX32(PSB_CR_2D_SOCIF) == _PSB_C2_SOCIF_EMPTY) &&
((PSB_RSGX32(PSB_CR_2D_BLIT_STATUS) & _PSB_C2B_STATUS_BUSY) == 0))
goto out;
do {
busy = (PSB_RSGX32(PSB_CR_2D_SOCIF) != _PSB_C2_SOCIF_EMPTY);
cpu_relax();
} while (busy && !time_after_eq(jiffies, _end));
if (busy)
busy = (PSB_RSGX32(PSB_CR_2D_SOCIF) != _PSB_C2_SOCIF_EMPTY);
if (busy)
goto out;
do {
busy = ((PSB_RSGX32(PSB_CR_2D_BLIT_STATUS) &
_PSB_C2B_STATUS_BUSY) != 0);
cpu_relax();
} while (busy && !time_after_eq(jiffies, _end));
if (busy)
busy = ((PSB_RSGX32(PSB_CR_2D_BLIT_STATUS) &
_PSB_C2B_STATUS_BUSY) != 0);
out:
return (busy) ? -EBUSY : 0;
}
/*
info->fix.accel = FB_ACCEL_I830;
info->flags = FBINFO_DEFAULT;
*/
| gpl-2.0 |
airk000/kernel_pantech_msm8660 | drivers/net/irda/sh_irda.c | 2642 | 19641 | /*
* SuperH IrDA Driver
*
* Copyright (C) 2010 Renesas Solutions Corp.
* Kuninori Morimoto <morimoto.kuninori@renesas.com>
*
* Based on sh_sir.c
* Copyright (C) 2009 Renesas Solutions Corp.
* Copyright 2006-2009 Analog Devices Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/*
* CAUTION
*
* This driver is very simple.
* So, it doesn't have below support now
* - MIR/FIR support
* - DMA transfer support
* - FIFO mode support
*/
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/clk.h>
#include <net/irda/wrapper.h>
#include <net/irda/irda_device.h>
#define DRIVER_NAME "sh_irda"
#if defined(CONFIG_ARCH_SH7367) || defined(CONFIG_ARCH_SH7377)
#define __IRDARAM_LEN 0x13FF
#else
#define __IRDARAM_LEN 0x1039
#endif
#define IRTMR 0x1F00 /* Transfer mode */
#define IRCFR 0x1F02 /* Configuration */
#define IRCTR 0x1F04 /* IR control */
#define IRTFLR 0x1F20 /* Transmit frame length */
#define IRTCTR 0x1F22 /* Transmit control */
#define IRRFLR 0x1F40 /* Receive frame length */
#define IRRCTR 0x1F42 /* Receive control */
#define SIRISR 0x1F60 /* SIR-UART mode interrupt source */
#define SIRIMR 0x1F62 /* SIR-UART mode interrupt mask */
#define SIRICR 0x1F64 /* SIR-UART mode interrupt clear */
#define SIRBCR 0x1F68 /* SIR-UART mode baud rate count */
#define MFIRISR 0x1F70 /* MIR/FIR mode interrupt source */
#define MFIRIMR 0x1F72 /* MIR/FIR mode interrupt mask */
#define MFIRICR 0x1F74 /* MIR/FIR mode interrupt clear */
#define CRCCTR 0x1F80 /* CRC engine control */
#define CRCIR 0x1F86 /* CRC engine input data */
#define CRCCR 0x1F8A /* CRC engine calculation */
#define CRCOR 0x1F8E /* CRC engine output data */
#define FIFOCP 0x1FC0 /* FIFO current pointer */
#define FIFOFP 0x1FC2 /* FIFO follow pointer */
#define FIFORSMSK 0x1FC4 /* FIFO receive status mask */
#define FIFORSOR 0x1FC6 /* FIFO receive status OR */
#define FIFOSEL 0x1FC8 /* FIFO select */
#define FIFORS 0x1FCA /* FIFO receive status */
#define FIFORFL 0x1FCC /* FIFO receive frame length */
#define FIFORAMCP 0x1FCE /* FIFO RAM current pointer */
#define FIFORAMFP 0x1FD0 /* FIFO RAM follow pointer */
#define BIFCTL 0x1FD2 /* BUS interface control */
#define IRDARAM 0x0000 /* IrDA buffer RAM */
#define IRDARAM_LEN __IRDARAM_LEN /* - 8/16/32 (read-only for 32) */
/* IRTMR */
#define TMD_MASK (0x3 << 14) /* Transfer Mode */
#define TMD_SIR (0x0 << 14)
#define TMD_MIR (0x3 << 14)
#define TMD_FIR (0x2 << 14)
#define FIFORIM (1 << 8) /* FIFO receive interrupt mask */
#define MIM (1 << 4) /* MIR/FIR Interrupt Mask */
#define SIM (1 << 0) /* SIR Interrupt Mask */
#define xIM_MASK (FIFORIM | MIM | SIM)
/* IRCFR */
#define RTO_SHIFT 8 /* shift for Receive Timeout */
#define RTO (0x3 << RTO_SHIFT)
/* IRTCTR */
#define ARMOD (1 << 15) /* Auto-Receive Mode */
#define TE (1 << 0) /* Transmit Enable */
/* IRRFLR */
#define RFL_MASK (0x1FFF) /* mask for Receive Frame Length */
/* IRRCTR */
#define RE (1 << 0) /* Receive Enable */
/*
* SIRISR, SIRIMR, SIRICR,
* MFIRISR, MFIRIMR, MFIRICR
*/
#define FRE (1 << 15) /* Frame Receive End */
#define TROV (1 << 11) /* Transfer Area Overflow */
#define xIR_9 (1 << 9)
#define TOT xIR_9 /* for SIR Timeout */
#define ABTD xIR_9 /* for MIR/FIR Abort Detection */
#define xIR_8 (1 << 8)
#define FER xIR_8 /* for SIR Framing Error */
#define CRCER xIR_8 /* for MIR/FIR CRC error */
#define FTE (1 << 7) /* Frame Transmit End */
#define xIR_MASK (FRE | TROV | xIR_9 | xIR_8 | FTE)
/* SIRBCR */
#define BRC_MASK (0x3F) /* mask for Baud Rate Count */
/* CRCCTR */
#define CRC_RST (1 << 15) /* CRC Engine Reset */
#define CRC_CT_MASK 0x0FFF /* mask for CRC Engine Input Data Count */
/* CRCIR */
#define CRC_IN_MASK 0x0FFF /* mask for CRC Engine Input Data */
/************************************************************************
enum / structure
************************************************************************/
enum sh_irda_mode {
SH_IRDA_NONE = 0,
SH_IRDA_SIR,
SH_IRDA_MIR,
SH_IRDA_FIR,
};
struct sh_irda_self;
struct sh_irda_xir_func {
int (*xir_fre) (struct sh_irda_self *self);
int (*xir_trov) (struct sh_irda_self *self);
int (*xir_9) (struct sh_irda_self *self);
int (*xir_8) (struct sh_irda_self *self);
int (*xir_fte) (struct sh_irda_self *self);
};
struct sh_irda_self {
void __iomem *membase;
unsigned int irq;
struct clk *clk;
struct net_device *ndev;
struct irlap_cb *irlap;
struct qos_info qos;
iobuff_t tx_buff;
iobuff_t rx_buff;
enum sh_irda_mode mode;
spinlock_t lock;
struct sh_irda_xir_func *xir_func;
};
/************************************************************************
common function
************************************************************************/
static void sh_irda_write(struct sh_irda_self *self, u32 offset, u16 data)
{
unsigned long flags;
spin_lock_irqsave(&self->lock, flags);
iowrite16(data, self->membase + offset);
spin_unlock_irqrestore(&self->lock, flags);
}
static u16 sh_irda_read(struct sh_irda_self *self, u32 offset)
{
unsigned long flags;
u16 ret;
spin_lock_irqsave(&self->lock, flags);
ret = ioread16(self->membase + offset);
spin_unlock_irqrestore(&self->lock, flags);
return ret;
}
static void sh_irda_update_bits(struct sh_irda_self *self, u32 offset,
u16 mask, u16 data)
{
unsigned long flags;
u16 old, new;
spin_lock_irqsave(&self->lock, flags);
old = ioread16(self->membase + offset);
new = (old & ~mask) | data;
if (old != new)
iowrite16(data, self->membase + offset);
spin_unlock_irqrestore(&self->lock, flags);
}
/************************************************************************
mode function
************************************************************************/
/*=====================================
*
* common
*
*=====================================*/
static void sh_irda_rcv_ctrl(struct sh_irda_self *self, int enable)
{
struct device *dev = &self->ndev->dev;
sh_irda_update_bits(self, IRRCTR, RE, enable ? RE : 0);
dev_dbg(dev, "recv %s\n", enable ? "enable" : "disable");
}
static int sh_irda_set_timeout(struct sh_irda_self *self, int interval)
{
struct device *dev = &self->ndev->dev;
if (SH_IRDA_SIR != self->mode)
interval = 0;
if (interval < 0 || interval > 2) {
dev_err(dev, "unsupported timeout interval\n");
return -EINVAL;
}
sh_irda_update_bits(self, IRCFR, RTO, interval << RTO_SHIFT);
return 0;
}
static int sh_irda_set_baudrate(struct sh_irda_self *self, int baudrate)
{
struct device *dev = &self->ndev->dev;
u16 val;
if (baudrate < 0)
return 0;
if (SH_IRDA_SIR != self->mode) {
dev_err(dev, "it is not SIR mode\n");
return -EINVAL;
}
/*
* Baud rate (bits/s) =
* (48 MHz / 26) / (baud rate counter value + 1) x 16
*/
val = (48000000 / 26 / 16 / baudrate) - 1;
dev_dbg(dev, "baudrate = %d, val = 0x%02x\n", baudrate, val);
sh_irda_update_bits(self, SIRBCR, BRC_MASK, val);
return 0;
}
static int xir_get_rcv_length(struct sh_irda_self *self)
{
return RFL_MASK & sh_irda_read(self, IRRFLR);
}
/*=====================================
*
* NONE MODE
*
*=====================================*/
static int xir_fre(struct sh_irda_self *self)
{
struct device *dev = &self->ndev->dev;
dev_err(dev, "none mode: frame recv\n");
return 0;
}
static int xir_trov(struct sh_irda_self *self)
{
struct device *dev = &self->ndev->dev;
dev_err(dev, "none mode: buffer ram over\n");
return 0;
}
static int xir_9(struct sh_irda_self *self)
{
struct device *dev = &self->ndev->dev;
dev_err(dev, "none mode: time over\n");
return 0;
}
static int xir_8(struct sh_irda_self *self)
{
struct device *dev = &self->ndev->dev;
dev_err(dev, "none mode: framing error\n");
return 0;
}
static int xir_fte(struct sh_irda_self *self)
{
struct device *dev = &self->ndev->dev;
dev_err(dev, "none mode: frame transmit end\n");
return 0;
}
static struct sh_irda_xir_func xir_func = {
.xir_fre = xir_fre,
.xir_trov = xir_trov,
.xir_9 = xir_9,
.xir_8 = xir_8,
.xir_fte = xir_fte,
};
/*=====================================
*
* MIR/FIR MODE
*
* MIR/FIR are not supported now
*=====================================*/
static struct sh_irda_xir_func mfir_func = {
.xir_fre = xir_fre,
.xir_trov = xir_trov,
.xir_9 = xir_9,
.xir_8 = xir_8,
.xir_fte = xir_fte,
};
/*=====================================
*
* SIR MODE
*
*=====================================*/
static int sir_fre(struct sh_irda_self *self)
{
struct device *dev = &self->ndev->dev;
u16 data16;
u8 *data = (u8 *)&data16;
int len = xir_get_rcv_length(self);
int i, j;
if (len > IRDARAM_LEN)
len = IRDARAM_LEN;
dev_dbg(dev, "frame recv length = %d\n", len);
for (i = 0; i < len; i++) {
j = i % 2;
if (!j)
data16 = sh_irda_read(self, IRDARAM + i);
async_unwrap_char(self->ndev, &self->ndev->stats,
&self->rx_buff, data[j]);
}
self->ndev->last_rx = jiffies;
sh_irda_rcv_ctrl(self, 1);
return 0;
}
static int sir_trov(struct sh_irda_self *self)
{
struct device *dev = &self->ndev->dev;
dev_err(dev, "buffer ram over\n");
sh_irda_rcv_ctrl(self, 1);
return 0;
}
static int sir_tot(struct sh_irda_self *self)
{
struct device *dev = &self->ndev->dev;
dev_err(dev, "time over\n");
sh_irda_set_baudrate(self, 9600);
sh_irda_rcv_ctrl(self, 1);
return 0;
}
static int sir_fer(struct sh_irda_self *self)
{
struct device *dev = &self->ndev->dev;
dev_err(dev, "framing error\n");
sh_irda_rcv_ctrl(self, 1);
return 0;
}
static int sir_fte(struct sh_irda_self *self)
{
struct device *dev = &self->ndev->dev;
dev_dbg(dev, "frame transmit end\n");
netif_wake_queue(self->ndev);
return 0;
}
static struct sh_irda_xir_func sir_func = {
.xir_fre = sir_fre,
.xir_trov = sir_trov,
.xir_9 = sir_tot,
.xir_8 = sir_fer,
.xir_fte = sir_fte,
};
static void sh_irda_set_mode(struct sh_irda_self *self, enum sh_irda_mode mode)
{
struct device *dev = &self->ndev->dev;
struct sh_irda_xir_func *func;
const char *name;
u16 data;
switch (mode) {
case SH_IRDA_SIR:
name = "SIR";
data = TMD_SIR;
func = &sir_func;
break;
case SH_IRDA_MIR:
name = "MIR";
data = TMD_MIR;
func = &mfir_func;
break;
case SH_IRDA_FIR:
name = "FIR";
data = TMD_FIR;
func = &mfir_func;
break;
default:
name = "NONE";
data = 0;
func = &xir_func;
break;
}
self->mode = mode;
self->xir_func = func;
sh_irda_update_bits(self, IRTMR, TMD_MASK, data);
dev_dbg(dev, "switch to %s mode", name);
}
/************************************************************************
irq function
************************************************************************/
static void sh_irda_set_irq_mask(struct sh_irda_self *self)
{
u16 tmr_hole;
u16 xir_reg;
/* set all mask */
sh_irda_update_bits(self, IRTMR, xIM_MASK, xIM_MASK);
sh_irda_update_bits(self, SIRIMR, xIR_MASK, xIR_MASK);
sh_irda_update_bits(self, MFIRIMR, xIR_MASK, xIR_MASK);
/* clear irq */
sh_irda_update_bits(self, SIRICR, xIR_MASK, xIR_MASK);
sh_irda_update_bits(self, MFIRICR, xIR_MASK, xIR_MASK);
switch (self->mode) {
case SH_IRDA_SIR:
tmr_hole = SIM;
xir_reg = SIRIMR;
break;
case SH_IRDA_MIR:
case SH_IRDA_FIR:
tmr_hole = MIM;
xir_reg = MFIRIMR;
break;
default:
tmr_hole = 0;
xir_reg = 0;
break;
}
/* open mask */
if (xir_reg) {
sh_irda_update_bits(self, IRTMR, tmr_hole, 0);
sh_irda_update_bits(self, xir_reg, xIR_MASK, 0);
}
}
static irqreturn_t sh_irda_irq(int irq, void *dev_id)
{
struct sh_irda_self *self = dev_id;
struct sh_irda_xir_func *func = self->xir_func;
u16 isr = sh_irda_read(self, SIRISR);
/* clear irq */
sh_irda_write(self, SIRICR, isr);
if (isr & FRE)
func->xir_fre(self);
if (isr & TROV)
func->xir_trov(self);
if (isr & xIR_9)
func->xir_9(self);
if (isr & xIR_8)
func->xir_8(self);
if (isr & FTE)
func->xir_fte(self);
return IRQ_HANDLED;
}
/************************************************************************
CRC function
************************************************************************/
static void sh_irda_crc_reset(struct sh_irda_self *self)
{
sh_irda_write(self, CRCCTR, CRC_RST);
}
static void sh_irda_crc_add(struct sh_irda_self *self, u16 data)
{
sh_irda_write(self, CRCIR, data & CRC_IN_MASK);
}
static u16 sh_irda_crc_cnt(struct sh_irda_self *self)
{
return CRC_CT_MASK & sh_irda_read(self, CRCCTR);
}
static u16 sh_irda_crc_out(struct sh_irda_self *self)
{
return sh_irda_read(self, CRCOR);
}
static int sh_irda_crc_init(struct sh_irda_self *self)
{
struct device *dev = &self->ndev->dev;
int ret = -EIO;
u16 val;
sh_irda_crc_reset(self);
sh_irda_crc_add(self, 0xCC);
sh_irda_crc_add(self, 0xF5);
sh_irda_crc_add(self, 0xF1);
sh_irda_crc_add(self, 0xA7);
val = sh_irda_crc_cnt(self);
if (4 != val) {
dev_err(dev, "CRC count error %x\n", val);
goto crc_init_out;
}
val = sh_irda_crc_out(self);
if (0x51DF != val) {
dev_err(dev, "CRC result error%x\n", val);
goto crc_init_out;
}
ret = 0;
crc_init_out:
sh_irda_crc_reset(self);
return ret;
}
/************************************************************************
iobuf function
************************************************************************/
static void sh_irda_remove_iobuf(struct sh_irda_self *self)
{
kfree(self->rx_buff.head);
self->tx_buff.head = NULL;
self->tx_buff.data = NULL;
self->rx_buff.head = NULL;
self->rx_buff.data = NULL;
}
static int sh_irda_init_iobuf(struct sh_irda_self *self, int rxsize, int txsize)
{
if (self->rx_buff.head ||
self->tx_buff.head) {
dev_err(&self->ndev->dev, "iobuff has already existed.");
return -EINVAL;
}
/* rx_buff */
self->rx_buff.head = kmalloc(rxsize, GFP_KERNEL);
if (!self->rx_buff.head)
return -ENOMEM;
self->rx_buff.truesize = rxsize;
self->rx_buff.in_frame = FALSE;
self->rx_buff.state = OUTSIDE_FRAME;
self->rx_buff.data = self->rx_buff.head;
/* tx_buff */
self->tx_buff.head = self->membase + IRDARAM;
self->tx_buff.truesize = IRDARAM_LEN;
return 0;
}
/************************************************************************
net_device_ops function
************************************************************************/
static int sh_irda_hard_xmit(struct sk_buff *skb, struct net_device *ndev)
{
struct sh_irda_self *self = netdev_priv(ndev);
struct device *dev = &self->ndev->dev;
int speed = irda_get_next_speed(skb);
int ret;
dev_dbg(dev, "hard xmit\n");
netif_stop_queue(ndev);
sh_irda_rcv_ctrl(self, 0);
ret = sh_irda_set_baudrate(self, speed);
if (ret < 0)
goto sh_irda_hard_xmit_end;
self->tx_buff.len = 0;
if (skb->len) {
unsigned long flags;
spin_lock_irqsave(&self->lock, flags);
self->tx_buff.len = async_wrap_skb(skb,
self->tx_buff.head,
self->tx_buff.truesize);
spin_unlock_irqrestore(&self->lock, flags);
if (self->tx_buff.len > self->tx_buff.truesize)
self->tx_buff.len = self->tx_buff.truesize;
sh_irda_write(self, IRTFLR, self->tx_buff.len);
sh_irda_write(self, IRTCTR, ARMOD | TE);
} else
goto sh_irda_hard_xmit_end;
dev_kfree_skb(skb);
return 0;
sh_irda_hard_xmit_end:
sh_irda_set_baudrate(self, 9600);
netif_wake_queue(self->ndev);
sh_irda_rcv_ctrl(self, 1);
dev_kfree_skb(skb);
return ret;
}
static int sh_irda_ioctl(struct net_device *ndev, struct ifreq *ifreq, int cmd)
{
/*
* FIXME
*
* This function is needed for irda framework.
* But nothing to do now
*/
return 0;
}
static struct net_device_stats *sh_irda_stats(struct net_device *ndev)
{
struct sh_irda_self *self = netdev_priv(ndev);
return &self->ndev->stats;
}
static int sh_irda_open(struct net_device *ndev)
{
struct sh_irda_self *self = netdev_priv(ndev);
int err;
clk_enable(self->clk);
err = sh_irda_crc_init(self);
if (err)
goto open_err;
sh_irda_set_mode(self, SH_IRDA_SIR);
sh_irda_set_timeout(self, 2);
sh_irda_set_baudrate(self, 9600);
self->irlap = irlap_open(ndev, &self->qos, DRIVER_NAME);
if (!self->irlap) {
err = -ENODEV;
goto open_err;
}
netif_start_queue(ndev);
sh_irda_rcv_ctrl(self, 1);
sh_irda_set_irq_mask(self);
dev_info(&ndev->dev, "opened\n");
return 0;
open_err:
clk_disable(self->clk);
return err;
}
static int sh_irda_stop(struct net_device *ndev)
{
struct sh_irda_self *self = netdev_priv(ndev);
/* Stop IrLAP */
if (self->irlap) {
irlap_close(self->irlap);
self->irlap = NULL;
}
netif_stop_queue(ndev);
dev_info(&ndev->dev, "stoped\n");
return 0;
}
static const struct net_device_ops sh_irda_ndo = {
.ndo_open = sh_irda_open,
.ndo_stop = sh_irda_stop,
.ndo_start_xmit = sh_irda_hard_xmit,
.ndo_do_ioctl = sh_irda_ioctl,
.ndo_get_stats = sh_irda_stats,
};
/************************************************************************
platform_driver function
************************************************************************/
static int __devinit sh_irda_probe(struct platform_device *pdev)
{
struct net_device *ndev;
struct sh_irda_self *self;
struct resource *res;
int irq;
int err = -ENOMEM;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
irq = platform_get_irq(pdev, 0);
if (!res || irq < 0) {
dev_err(&pdev->dev, "Not enough platform resources.\n");
goto exit;
}
ndev = alloc_irdadev(sizeof(*self));
if (!ndev)
goto exit;
self = netdev_priv(ndev);
self->membase = ioremap_nocache(res->start, resource_size(res));
if (!self->membase) {
err = -ENXIO;
dev_err(&pdev->dev, "Unable to ioremap.\n");
goto err_mem_1;
}
err = sh_irda_init_iobuf(self, IRDA_SKB_MAX_MTU, IRDA_SIR_MAX_FRAME);
if (err)
goto err_mem_2;
self->clk = clk_get(&pdev->dev, NULL);
if (IS_ERR(self->clk)) {
dev_err(&pdev->dev, "cannot get irda clock\n");
goto err_mem_3;
}
irda_init_max_qos_capabilies(&self->qos);
ndev->netdev_ops = &sh_irda_ndo;
ndev->irq = irq;
self->ndev = ndev;
self->qos.baud_rate.bits &= IR_9600; /* FIXME */
self->qos.min_turn_time.bits = 1; /* 10 ms or more */
spin_lock_init(&self->lock);
irda_qos_bits_to_value(&self->qos);
err = register_netdev(ndev);
if (err)
goto err_mem_4;
platform_set_drvdata(pdev, ndev);
if (request_irq(irq, sh_irda_irq, IRQF_DISABLED, "sh_irda", self)) {
dev_warn(&pdev->dev, "Unable to attach sh_irda interrupt\n");
goto err_mem_4;
}
dev_info(&pdev->dev, "SuperH IrDA probed\n");
goto exit;
err_mem_4:
clk_put(self->clk);
err_mem_3:
sh_irda_remove_iobuf(self);
err_mem_2:
iounmap(self->membase);
err_mem_1:
free_netdev(ndev);
exit:
return err;
}
static int __devexit sh_irda_remove(struct platform_device *pdev)
{
struct net_device *ndev = platform_get_drvdata(pdev);
struct sh_irda_self *self = netdev_priv(ndev);
if (!self)
return 0;
unregister_netdev(ndev);
clk_put(self->clk);
sh_irda_remove_iobuf(self);
iounmap(self->membase);
free_netdev(ndev);
platform_set_drvdata(pdev, NULL);
return 0;
}
static struct platform_driver sh_irda_driver = {
.probe = sh_irda_probe,
.remove = __devexit_p(sh_irda_remove),
.driver = {
.name = DRIVER_NAME,
},
};
static int __init sh_irda_init(void)
{
return platform_driver_register(&sh_irda_driver);
}
static void __exit sh_irda_exit(void)
{
platform_driver_unregister(&sh_irda_driver);
}
module_init(sh_irda_init);
module_exit(sh_irda_exit);
MODULE_AUTHOR("Kuninori Morimoto <morimoto.kuninori@renesas.com>");
MODULE_DESCRIPTION("SuperH IrDA driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
stelios97/sony-kernel-msm7x27a | drivers/of/of_net.c | 2642 | 1732 | /*
* OF helpers for network devices.
*
* This file is released under the GPLv2
*
* Initially copied out of arch/powerpc/kernel/prom_parse.c
*/
#include <linux/etherdevice.h>
#include <linux/kernel.h>
#include <linux/of_net.h>
/**
* Search the device tree for the best MAC address to use. 'mac-address' is
* checked first, because that is supposed to contain to "most recent" MAC
* address. If that isn't set, then 'local-mac-address' is checked next,
* because that is the default address. If that isn't set, then the obsolete
* 'address' is checked, just in case we're using an old device tree.
*
* Note that the 'address' property is supposed to contain a virtual address of
* the register set, but some DTS files have redefined that property to be the
* MAC address.
*
* All-zero MAC addresses are rejected, because those could be properties that
* exist in the device tree, but were not set by U-Boot. For example, the
* DTS could define 'mac-address' and 'local-mac-address', with zero MAC
* addresses. Some older U-Boots only initialized 'local-mac-address'. In
* this case, the real MAC is in 'local-mac-address', and 'mac-address' exists
* but is all zeros.
*/
const void *of_get_mac_address(struct device_node *np)
{
struct property *pp;
pp = of_find_property(np, "mac-address", NULL);
if (pp && (pp->length == 6) && is_valid_ether_addr(pp->value))
return pp->value;
pp = of_find_property(np, "local-mac-address", NULL);
if (pp && (pp->length == 6) && is_valid_ether_addr(pp->value))
return pp->value;
pp = of_find_property(np, "address", NULL);
if (pp && (pp->length == 6) && is_valid_ether_addr(pp->value))
return pp->value;
return NULL;
}
EXPORT_SYMBOL(of_get_mac_address);
| gpl-2.0 |
SSLab-NTHU/linux-host-armvisor | arch/arm/mach-s5pc100/cpu.c | 3154 | 3752 | /* linux/arch/arm/mach-s5pc100/cpu.c
*
* Copyright (c) 2010 Samsung Electronics Co., Ltd.
* http://www.samsung.com
*
* Copyright 2009 Samsung Electronics Co.
* Byungho Min <bhmin@samsung.com>
*
* Based on mach-s3c6410/cpu.c
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/interrupt.h>
#include <linux/list.h>
#include <linux/timer.h>
#include <linux/init.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/sysdev.h>
#include <linux/serial_core.h>
#include <linux/platform_device.h>
#include <linux/sched.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <asm/proc-fns.h>
#include <mach/hardware.h>
#include <mach/map.h>
#include <asm/irq.h>
#include <plat/regs-serial.h>
#include <mach/regs-clock.h>
#include <plat/cpu.h>
#include <plat/devs.h>
#include <plat/clock.h>
#include <plat/ata-core.h>
#include <plat/iic-core.h>
#include <plat/sdhci.h>
#include <plat/adc-core.h>
#include <plat/onenand-core.h>
#include <plat/fb-core.h>
#include <plat/s5pc100.h>
/* Initial IO mappings */
static struct map_desc s5pc100_iodesc[] __initdata = {
{
.virtual = (unsigned long)S5P_VA_SYSTIMER,
.pfn = __phys_to_pfn(S5PC100_PA_SYSTIMER),
.length = SZ_16K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S5P_VA_GPIO,
.pfn = __phys_to_pfn(S5PC100_PA_GPIO),
.length = SZ_4K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)VA_VIC0,
.pfn = __phys_to_pfn(S5PC100_PA_VIC0),
.length = SZ_16K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)VA_VIC1,
.pfn = __phys_to_pfn(S5PC100_PA_VIC1),
.length = SZ_16K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)VA_VIC2,
.pfn = __phys_to_pfn(S5PC100_PA_VIC2),
.length = SZ_16K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S3C_VA_UART,
.pfn = __phys_to_pfn(S3C_PA_UART),
.length = SZ_512K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S5PC100_VA_OTHERS,
.pfn = __phys_to_pfn(S5PC100_PA_OTHERS),
.length = SZ_4K,
.type = MT_DEVICE,
}
};
static void s5pc100_idle(void)
{
if (!need_resched())
cpu_do_idle();
local_irq_enable();
}
/* s5pc100_map_io
*
* register the standard cpu IO areas
*/
void __init s5pc100_map_io(void)
{
iotable_init(s5pc100_iodesc, ARRAY_SIZE(s5pc100_iodesc));
/* initialise device information early */
s5pc100_default_sdhci0();
s5pc100_default_sdhci1();
s5pc100_default_sdhci2();
s3c_adc_setname("s3c64xx-adc");
/* the i2c devices are directly compatible with s3c2440 */
s3c_i2c0_setname("s3c2440-i2c");
s3c_i2c1_setname("s3c2440-i2c");
s3c_onenand_setname("s5pc100-onenand");
s3c_fb_setname("s5pc100-fb");
s3c_cfcon_setname("s5pc100-pata");
}
void __init s5pc100_init_clocks(int xtal)
{
printk(KERN_DEBUG "%s: initializing clocks\n", __func__);
s3c24xx_register_baseclocks(xtal);
s5p_register_clocks(xtal);
s5pc100_register_clocks();
s5pc100_setup_clocks();
}
void __init s5pc100_init_irq(void)
{
u32 vic[] = {~0, ~0, ~0};
/* VIC0, VIC1, and VIC2 are fully populated. */
s5p_init_irq(vic, ARRAY_SIZE(vic));
}
static struct sysdev_class s5pc100_sysclass = {
.name = "s5pc100-core",
};
static struct sys_device s5pc100_sysdev = {
.cls = &s5pc100_sysclass,
};
static int __init s5pc100_core_init(void)
{
return sysdev_class_register(&s5pc100_sysclass);
}
core_initcall(s5pc100_core_init);
int __init s5pc100_init(void)
{
printk(KERN_INFO "S5PC100: Initializing architecture\n");
/* set idle function */
pm_idle = s5pc100_idle;
return sysdev_register(&s5pc100_sysdev);
}
| gpl-2.0 |
Pure4Team/desire820 | net/ax25/ax25_ds_timer.c | 4178 | 5904 | /*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Copyright (C) Jonathan Naylor G4KLX (g4klx@g4klx.demon.co.uk)
* Copyright (C) Joerg Reuter DL1BKE (jreuter@yaina.de)
*/
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/spinlock.h>
#include <linux/in.h>
#include <linux/kernel.h>
#include <linux/jiffies.h>
#include <linux/timer.h>
#include <linux/string.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <net/tcp_states.h>
#include <net/ax25.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <net/sock.h>
#include <asm/uaccess.h>
#include <linux/fcntl.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
static void ax25_ds_timeout(unsigned long);
/*
* Add DAMA slave timeout timer to timer list.
* Unlike the connection based timers the timeout function gets
* triggered every second. Please note that NET_AX25_DAMA_SLAVE_TIMEOUT
* (aka /proc/sys/net/ax25/{dev}/dama_slave_timeout) is still in
* 1/10th of a second.
*/
void ax25_ds_setup_timer(ax25_dev *ax25_dev)
{
setup_timer(&ax25_dev->dama.slave_timer, ax25_ds_timeout,
(unsigned long)ax25_dev);
}
void ax25_ds_del_timer(ax25_dev *ax25_dev)
{
if (ax25_dev)
del_timer(&ax25_dev->dama.slave_timer);
}
void ax25_ds_set_timer(ax25_dev *ax25_dev)
{
if (ax25_dev == NULL) /* paranoia */
return;
ax25_dev->dama.slave_timeout =
msecs_to_jiffies(ax25_dev->values[AX25_VALUES_DS_TIMEOUT]) / 10;
mod_timer(&ax25_dev->dama.slave_timer, jiffies + HZ);
}
/*
* DAMA Slave Timeout
* Silently discard all (slave) connections in case our master forgot us...
*/
static void ax25_ds_timeout(unsigned long arg)
{
ax25_dev *ax25_dev = (struct ax25_dev *) arg;
ax25_cb *ax25;
if (ax25_dev == NULL || !ax25_dev->dama.slave)
return; /* Yikes! */
if (!ax25_dev->dama.slave_timeout || --ax25_dev->dama.slave_timeout) {
ax25_ds_set_timer(ax25_dev);
return;
}
spin_lock(&ax25_list_lock);
ax25_for_each(ax25, &ax25_list) {
if (ax25->ax25_dev != ax25_dev || !(ax25->condition & AX25_COND_DAMA_MODE))
continue;
ax25_send_control(ax25, AX25_DISC, AX25_POLLON, AX25_COMMAND);
ax25_disconnect(ax25, ETIMEDOUT);
}
spin_unlock(&ax25_list_lock);
ax25_dev_dama_off(ax25_dev);
}
void ax25_ds_heartbeat_expiry(ax25_cb *ax25)
{
struct sock *sk=ax25->sk;
if (sk)
bh_lock_sock(sk);
switch (ax25->state) {
case AX25_STATE_0:
/* Magic here: If we listen() and a new link dies before it
is accepted() it isn't 'dead' so doesn't get removed. */
if (!sk || sock_flag(sk, SOCK_DESTROY) ||
(sk->sk_state == TCP_LISTEN &&
sock_flag(sk, SOCK_DEAD))) {
if (sk) {
sock_hold(sk);
ax25_destroy_socket(ax25);
bh_unlock_sock(sk);
sock_put(sk);
} else
ax25_destroy_socket(ax25);
return;
}
break;
case AX25_STATE_3:
/*
* Check the state of the receive buffer.
*/
if (sk != NULL) {
if (atomic_read(&sk->sk_rmem_alloc) <
(sk->sk_rcvbuf >> 1) &&
(ax25->condition & AX25_COND_OWN_RX_BUSY)) {
ax25->condition &= ~AX25_COND_OWN_RX_BUSY;
ax25->condition &= ~AX25_COND_ACK_PENDING;
break;
}
}
break;
}
if (sk)
bh_unlock_sock(sk);
ax25_start_heartbeat(ax25);
}
/* dl1bke 960114: T3 works much like the IDLE timeout, but
* gets reloaded with every frame for this
* connection.
*/
void ax25_ds_t3timer_expiry(ax25_cb *ax25)
{
ax25_send_control(ax25, AX25_DISC, AX25_POLLON, AX25_COMMAND);
ax25_dama_off(ax25);
ax25_disconnect(ax25, ETIMEDOUT);
}
/* dl1bke 960228: close the connection when IDLE expires.
* unlike T3 this timer gets reloaded only on
* I frames.
*/
void ax25_ds_idletimer_expiry(ax25_cb *ax25)
{
ax25_clear_queues(ax25);
ax25->n2count = 0;
ax25->state = AX25_STATE_2;
ax25_calculate_t1(ax25);
ax25_start_t1timer(ax25);
ax25_stop_t3timer(ax25);
if (ax25->sk != NULL) {
bh_lock_sock(ax25->sk);
ax25->sk->sk_state = TCP_CLOSE;
ax25->sk->sk_err = 0;
ax25->sk->sk_shutdown |= SEND_SHUTDOWN;
if (!sock_flag(ax25->sk, SOCK_DEAD)) {
ax25->sk->sk_state_change(ax25->sk);
sock_set_flag(ax25->sk, SOCK_DEAD);
}
bh_unlock_sock(ax25->sk);
}
}
/* dl1bke 960114: The DAMA protocol requires to send data and SABM/DISC
* within the poll of any connected channel. Remember
* that we are not allowed to send anything unless we
* get polled by the Master.
*
* Thus we'll have to do parts of our T1 handling in
* ax25_enquiry_response().
*/
void ax25_ds_t1_timeout(ax25_cb *ax25)
{
switch (ax25->state) {
case AX25_STATE_1:
if (ax25->n2count == ax25->n2) {
if (ax25->modulus == AX25_MODULUS) {
ax25_disconnect(ax25, ETIMEDOUT);
return;
} else {
ax25->modulus = AX25_MODULUS;
ax25->window = ax25->ax25_dev->values[AX25_VALUES_WINDOW];
ax25->n2count = 0;
ax25_send_control(ax25, AX25_SABM, AX25_POLLOFF, AX25_COMMAND);
}
} else {
ax25->n2count++;
if (ax25->modulus == AX25_MODULUS)
ax25_send_control(ax25, AX25_SABM, AX25_POLLOFF, AX25_COMMAND);
else
ax25_send_control(ax25, AX25_SABME, AX25_POLLOFF, AX25_COMMAND);
}
break;
case AX25_STATE_2:
if (ax25->n2count == ax25->n2) {
ax25_send_control(ax25, AX25_DISC, AX25_POLLON, AX25_COMMAND);
ax25_disconnect(ax25, ETIMEDOUT);
return;
} else {
ax25->n2count++;
}
break;
case AX25_STATE_3:
if (ax25->n2count == ax25->n2) {
ax25_send_control(ax25, AX25_DM, AX25_POLLON, AX25_RESPONSE);
ax25_disconnect(ax25, ETIMEDOUT);
return;
} else {
ax25->n2count++;
}
break;
}
ax25_calculate_t1(ax25);
ax25_start_t1timer(ax25);
}
| gpl-2.0 |
lawnn/android_kernel_samsung_d2dcm | arch/m68k/emu/nfeth.c | 4690 | 6405 | /*
* atari_nfeth.c - ARAnyM ethernet card driver for GNU/Linux
*
* Copyright (c) 2005 Milan Jurik, Petr Stehlik of ARAnyM dev team
*
* Based on ARAnyM driver for FreeMiNT written by Standa Opichal
*
* This software may be used and distributed according to the terms of
* the GNU General Public License (GPL), incorporated herein by reference.
*/
#define DRV_VERSION "0.3"
#define DRV_RELDATE "10/12/2005"
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <asm/natfeat.h>
#include <asm/virtconvert.h>
enum {
GET_VERSION = 0,/* no parameters, return NFAPI_VERSION in d0 */
XIF_INTLEVEL, /* no parameters, return Interrupt Level in d0 */
XIF_IRQ, /* acknowledge interrupt from host */
XIF_START, /* (ethX), called on 'ifup', start receiver thread */
XIF_STOP, /* (ethX), called on 'ifdown', stop the thread */
XIF_READLENGTH, /* (ethX), return size of network data block to read */
XIF_READBLOCK, /* (ethX, buffer, size), read block of network data */
XIF_WRITEBLOCK, /* (ethX, buffer, size), write block of network data */
XIF_GET_MAC, /* (ethX, buffer, size), return MAC HW addr in buffer */
XIF_GET_IPHOST, /* (ethX, buffer, size), return IP address of host */
XIF_GET_IPATARI,/* (ethX, buffer, size), return IP address of atari */
XIF_GET_NETMASK /* (ethX, buffer, size), return IP netmask */
};
#define MAX_UNIT 8
/* These identify the driver base version and may not be removed. */
static const char version[] __devinitconst =
KERN_INFO KBUILD_MODNAME ".c:v" DRV_VERSION " " DRV_RELDATE
" S.Opichal, M.Jurik, P.Stehlik\n"
KERN_INFO " http://aranym.org/\n";
MODULE_AUTHOR("Milan Jurik");
MODULE_DESCRIPTION("Atari NFeth driver");
MODULE_LICENSE("GPL");
/*
MODULE_PARM(nfeth_debug, "i");
MODULE_PARM_DESC(nfeth_debug, "nfeth_debug level (1-2)");
*/
static long nfEtherID;
static int nfEtherIRQ;
struct nfeth_private {
int ethX;
};
static struct net_device *nfeth_dev[MAX_UNIT];
static int nfeth_open(struct net_device *dev)
{
struct nfeth_private *priv = netdev_priv(dev);
int res;
res = nf_call(nfEtherID + XIF_START, priv->ethX);
netdev_dbg(dev, "%s: %d\n", __func__, res);
/* Ready for data */
netif_start_queue(dev);
return 0;
}
static int nfeth_stop(struct net_device *dev)
{
struct nfeth_private *priv = netdev_priv(dev);
/* No more data */
netif_stop_queue(dev);
nf_call(nfEtherID + XIF_STOP, priv->ethX);
return 0;
}
/*
* Read a packet out of the adapter and pass it to the upper layers
*/
static inline void recv_packet(struct net_device *dev)
{
struct nfeth_private *priv = netdev_priv(dev);
unsigned short pktlen;
struct sk_buff *skb;
/* read packet length (excluding 32 bit crc) */
pktlen = nf_call(nfEtherID + XIF_READLENGTH, priv->ethX);
netdev_dbg(dev, "%s: %u\n", __func__, pktlen);
if (!pktlen) {
netdev_dbg(dev, "%s: pktlen == 0\n", __func__);
dev->stats.rx_errors++;
return;
}
skb = dev_alloc_skb(pktlen + 2);
if (!skb) {
netdev_dbg(dev, "%s: out of mem (buf_alloc failed)\n",
__func__);
dev->stats.rx_dropped++;
return;
}
skb->dev = dev;
skb_reserve(skb, 2); /* 16 Byte align */
skb_put(skb, pktlen); /* make room */
nf_call(nfEtherID + XIF_READBLOCK, priv->ethX, virt_to_phys(skb->data),
pktlen);
skb->protocol = eth_type_trans(skb, dev);
netif_rx(skb);
dev->last_rx = jiffies;
dev->stats.rx_packets++;
dev->stats.rx_bytes += pktlen;
/* and enqueue packet */
return;
}
static irqreturn_t nfeth_interrupt(int irq, void *dev_id)
{
int i, m, mask;
mask = nf_call(nfEtherID + XIF_IRQ, 0);
for (i = 0, m = 1; i < MAX_UNIT; m <<= 1, i++) {
if (mask & m && nfeth_dev[i]) {
recv_packet(nfeth_dev[i]);
nf_call(nfEtherID + XIF_IRQ, m);
}
}
return IRQ_HANDLED;
}
static int nfeth_xmit(struct sk_buff *skb, struct net_device *dev)
{
unsigned int len;
char *data, shortpkt[ETH_ZLEN];
struct nfeth_private *priv = netdev_priv(dev);
data = skb->data;
len = skb->len;
if (len < ETH_ZLEN) {
memset(shortpkt, 0, ETH_ZLEN);
memcpy(shortpkt, data, len);
data = shortpkt;
len = ETH_ZLEN;
}
netdev_dbg(dev, "%s: send %u bytes\n", __func__, len);
nf_call(nfEtherID + XIF_WRITEBLOCK, priv->ethX, virt_to_phys(data),
len);
dev->stats.tx_packets++;
dev->stats.tx_bytes += len;
dev_kfree_skb(skb);
return 0;
}
static void nfeth_tx_timeout(struct net_device *dev)
{
dev->stats.tx_errors++;
netif_wake_queue(dev);
}
static const struct net_device_ops nfeth_netdev_ops = {
.ndo_open = nfeth_open,
.ndo_stop = nfeth_stop,
.ndo_start_xmit = nfeth_xmit,
.ndo_tx_timeout = nfeth_tx_timeout,
.ndo_validate_addr = eth_validate_addr,
.ndo_change_mtu = eth_change_mtu,
.ndo_set_mac_address = eth_mac_addr,
};
static struct net_device * __init nfeth_probe(int unit)
{
struct net_device *dev;
struct nfeth_private *priv;
char mac[ETH_ALEN], host_ip[32], local_ip[32];
int err;
if (!nf_call(nfEtherID + XIF_GET_MAC, unit, mac, ETH_ALEN))
return NULL;
dev = alloc_etherdev(sizeof(struct nfeth_private));
if (!dev)
return NULL;
dev->irq = nfEtherIRQ;
dev->netdev_ops = &nfeth_netdev_ops;
memcpy(dev->dev_addr, mac, ETH_ALEN);
priv = netdev_priv(dev);
priv->ethX = unit;
err = register_netdev(dev);
if (err) {
free_netdev(dev);
return NULL;
}
nf_call(nfEtherID + XIF_GET_IPHOST, unit,
host_ip, sizeof(host_ip));
nf_call(nfEtherID + XIF_GET_IPATARI, unit,
local_ip, sizeof(local_ip));
netdev_info(dev, KBUILD_MODNAME " addr:%s (%s) HWaddr:%pM\n", host_ip,
local_ip, mac);
return dev;
}
static int __init nfeth_init(void)
{
long ver;
int error, i;
nfEtherID = nf_get_id("ETHERNET");
if (!nfEtherID)
return -ENODEV;
ver = nf_call(nfEtherID + GET_VERSION);
pr_info("API %lu\n", ver);
nfEtherIRQ = nf_call(nfEtherID + XIF_INTLEVEL);
error = request_irq(nfEtherIRQ, nfeth_interrupt, IRQF_SHARED,
"eth emu", nfeth_interrupt);
if (error) {
pr_err("request for irq %d failed %d", nfEtherIRQ, error);
return error;
}
for (i = 0; i < MAX_UNIT; i++)
nfeth_dev[i] = nfeth_probe(i);
return 0;
}
static void __exit nfeth_cleanup(void)
{
int i;
for (i = 0; i < MAX_UNIT; i++) {
if (nfeth_dev[i]) {
unregister_netdev(nfeth_dev[0]);
free_netdev(nfeth_dev[0]);
}
}
free_irq(nfEtherIRQ, nfeth_interrupt);
}
module_init(nfeth_init);
module_exit(nfeth_cleanup);
| gpl-2.0 |
46890580/whitetiger-linux-kernel | drivers/hid/hid-primax.c | 4690 | 2239 | /*
* HID driver for primax and similar keyboards with in-band modifiers
*
* Copyright 2011 Google Inc. All Rights Reserved
*
* Author:
* Terry Lambert <tlambert@google.com>
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/device.h>
#include <linux/hid.h>
#include <linux/module.h>
#include "hid-ids.h"
static int px_raw_event(struct hid_device *hid, struct hid_report *report,
u8 *data, int size)
{
int idx = size;
switch (report->id) {
case 0: /* keyboard input */
/*
* Convert in-band modifier key values into out of band
* modifier bits and pull the key strokes from the report.
* Thus a report data set which looked like:
*
* [00][00][E0][30][00][00][00][00]
* (no modifier bits + "Left Shift" key + "1" key)
*
* Would be converted to:
*
* [01][00][00][30][00][00][00][00]
* (Left Shift modifier bit + "1" key)
*
* As long as it's in the size range, the upper level
* drivers don't particularly care if there are in-band
* 0-valued keys, so they don't stop parsing.
*/
while (--idx > 1) {
if (data[idx] < 0xE0 || data[idx] > 0xE7)
continue;
data[0] |= (1 << (data[idx] - 0xE0));
data[idx] = 0;
}
hid_report_raw_event(hid, HID_INPUT_REPORT, data, size, 0);
return 1;
default: /* unknown report */
/* Unknown report type; pass upstream */
hid_info(hid, "unknown report type %d\n", report->id);
break;
}
return 0;
}
static const struct hid_device_id px_devices[] = {
{ HID_USB_DEVICE(USB_VENDOR_ID_PRIMAX, USB_DEVICE_ID_PRIMAX_KEYBOARD) },
{ }
};
MODULE_DEVICE_TABLE(hid, px_devices);
static struct hid_driver px_driver = {
.name = "primax",
.id_table = px_devices,
.raw_event = px_raw_event,
};
module_hid_driver(px_driver);
MODULE_AUTHOR("Terry Lambert <tlambert@google.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
squake/first | sound/soc/fsl/fsl_dma.c | 4946 | 32057 | /*
* Freescale DMA ALSA SoC PCM driver
*
* Author: Timur Tabi <timur@freescale.com>
*
* Copyright 2007-2010 Freescale Semiconductor, Inc.
*
* This file is licensed under the terms of the GNU General Public License
* version 2. This program is licensed "as is" without any warranty of any
* kind, whether express or implied.
*
* This driver implements ASoC support for the Elo DMA controller, which is
* the DMA controller on Freescale 83xx, 85xx, and 86xx SOCs. In ALSA terms,
* the PCM driver is what handles the DMA buffer.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/gfp.h>
#include <linux/of_platform.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <asm/io.h>
#include "fsl_dma.h"
#include "fsl_ssi.h" /* For the offset of stx0 and srx0 */
/*
* The formats that the DMA controller supports, which is anything
* that is 8, 16, or 32 bits.
*/
#define FSLDMA_PCM_FORMATS (SNDRV_PCM_FMTBIT_S8 | \
SNDRV_PCM_FMTBIT_U8 | \
SNDRV_PCM_FMTBIT_S16_LE | \
SNDRV_PCM_FMTBIT_S16_BE | \
SNDRV_PCM_FMTBIT_U16_LE | \
SNDRV_PCM_FMTBIT_U16_BE | \
SNDRV_PCM_FMTBIT_S24_LE | \
SNDRV_PCM_FMTBIT_S24_BE | \
SNDRV_PCM_FMTBIT_U24_LE | \
SNDRV_PCM_FMTBIT_U24_BE | \
SNDRV_PCM_FMTBIT_S32_LE | \
SNDRV_PCM_FMTBIT_S32_BE | \
SNDRV_PCM_FMTBIT_U32_LE | \
SNDRV_PCM_FMTBIT_U32_BE)
#define FSLDMA_PCM_RATES (SNDRV_PCM_RATE_5512 | SNDRV_PCM_RATE_8000_192000 | \
SNDRV_PCM_RATE_CONTINUOUS)
struct dma_object {
struct snd_soc_platform_driver dai;
dma_addr_t ssi_stx_phys;
dma_addr_t ssi_srx_phys;
unsigned int ssi_fifo_depth;
struct ccsr_dma_channel __iomem *channel;
unsigned int irq;
bool assigned;
char path[1];
};
/*
* The number of DMA links to use. Two is the bare minimum, but if you
* have really small links you might need more.
*/
#define NUM_DMA_LINKS 2
/** fsl_dma_private: p-substream DMA data
*
* Each substream has a 1-to-1 association with a DMA channel.
*
* The link[] array is first because it needs to be aligned on a 32-byte
* boundary, so putting it first will ensure alignment without padding the
* structure.
*
* @link[]: array of link descriptors
* @dma_channel: pointer to the DMA channel's registers
* @irq: IRQ for this DMA channel
* @substream: pointer to the substream object, needed by the ISR
* @ssi_sxx_phys: bus address of the STX or SRX register to use
* @ld_buf_phys: physical address of the LD buffer
* @current_link: index into link[] of the link currently being processed
* @dma_buf_phys: physical address of the DMA buffer
* @dma_buf_next: physical address of the next period to process
* @dma_buf_end: physical address of the byte after the end of the DMA
* @buffer period_size: the size of a single period
* @num_periods: the number of periods in the DMA buffer
*/
struct fsl_dma_private {
struct fsl_dma_link_descriptor link[NUM_DMA_LINKS];
struct ccsr_dma_channel __iomem *dma_channel;
unsigned int irq;
struct snd_pcm_substream *substream;
dma_addr_t ssi_sxx_phys;
unsigned int ssi_fifo_depth;
dma_addr_t ld_buf_phys;
unsigned int current_link;
dma_addr_t dma_buf_phys;
dma_addr_t dma_buf_next;
dma_addr_t dma_buf_end;
size_t period_size;
unsigned int num_periods;
};
/**
* fsl_dma_hardare: define characteristics of the PCM hardware.
*
* The PCM hardware is the Freescale DMA controller. This structure defines
* the capabilities of that hardware.
*
* Since the sampling rate and data format are not controlled by the DMA
* controller, we specify no limits for those values. The only exception is
* period_bytes_min, which is set to a reasonably low value to prevent the
* DMA controller from generating too many interrupts per second.
*
* Since each link descriptor has a 32-bit byte count field, we set
* period_bytes_max to the largest 32-bit number. We also have no maximum
* number of periods.
*
* Note that we specify SNDRV_PCM_INFO_JOINT_DUPLEX here, but only because a
* limitation in the SSI driver requires the sample rates for playback and
* capture to be the same.
*/
static const struct snd_pcm_hardware fsl_dma_hardware = {
.info = SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_JOINT_DUPLEX |
SNDRV_PCM_INFO_PAUSE,
.formats = FSLDMA_PCM_FORMATS,
.rates = FSLDMA_PCM_RATES,
.rate_min = 5512,
.rate_max = 192000,
.period_bytes_min = 512, /* A reasonable limit */
.period_bytes_max = (u32) -1,
.periods_min = NUM_DMA_LINKS,
.periods_max = (unsigned int) -1,
.buffer_bytes_max = 128 * 1024, /* A reasonable limit */
};
/**
* fsl_dma_abort_stream: tell ALSA that the DMA transfer has aborted
*
* This function should be called by the ISR whenever the DMA controller
* halts data transfer.
*/
static void fsl_dma_abort_stream(struct snd_pcm_substream *substream)
{
unsigned long flags;
snd_pcm_stream_lock_irqsave(substream, flags);
if (snd_pcm_running(substream))
snd_pcm_stop(substream, SNDRV_PCM_STATE_XRUN);
snd_pcm_stream_unlock_irqrestore(substream, flags);
}
/**
* fsl_dma_update_pointers - update LD pointers to point to the next period
*
* As each period is completed, this function changes the the link
* descriptor pointers for that period to point to the next period.
*/
static void fsl_dma_update_pointers(struct fsl_dma_private *dma_private)
{
struct fsl_dma_link_descriptor *link =
&dma_private->link[dma_private->current_link];
/* Update our link descriptors to point to the next period. On a 36-bit
* system, we also need to update the ESAD bits. We also set (keep) the
* snoop bits. See the comments in fsl_dma_hw_params() about snooping.
*/
if (dma_private->substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
link->source_addr = cpu_to_be32(dma_private->dma_buf_next);
#ifdef CONFIG_PHYS_64BIT
link->source_attr = cpu_to_be32(CCSR_DMA_ATR_SNOOP |
upper_32_bits(dma_private->dma_buf_next));
#endif
} else {
link->dest_addr = cpu_to_be32(dma_private->dma_buf_next);
#ifdef CONFIG_PHYS_64BIT
link->dest_attr = cpu_to_be32(CCSR_DMA_ATR_SNOOP |
upper_32_bits(dma_private->dma_buf_next));
#endif
}
/* Update our variables for next time */
dma_private->dma_buf_next += dma_private->period_size;
if (dma_private->dma_buf_next >= dma_private->dma_buf_end)
dma_private->dma_buf_next = dma_private->dma_buf_phys;
if (++dma_private->current_link >= NUM_DMA_LINKS)
dma_private->current_link = 0;
}
/**
* fsl_dma_isr: interrupt handler for the DMA controller
*
* @irq: IRQ of the DMA channel
* @dev_id: pointer to the dma_private structure for this DMA channel
*/
static irqreturn_t fsl_dma_isr(int irq, void *dev_id)
{
struct fsl_dma_private *dma_private = dev_id;
struct snd_pcm_substream *substream = dma_private->substream;
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct device *dev = rtd->platform->dev;
struct ccsr_dma_channel __iomem *dma_channel = dma_private->dma_channel;
irqreturn_t ret = IRQ_NONE;
u32 sr, sr2 = 0;
/* We got an interrupt, so read the status register to see what we
were interrupted for.
*/
sr = in_be32(&dma_channel->sr);
if (sr & CCSR_DMA_SR_TE) {
dev_err(dev, "dma transmit error\n");
fsl_dma_abort_stream(substream);
sr2 |= CCSR_DMA_SR_TE;
ret = IRQ_HANDLED;
}
if (sr & CCSR_DMA_SR_CH)
ret = IRQ_HANDLED;
if (sr & CCSR_DMA_SR_PE) {
dev_err(dev, "dma programming error\n");
fsl_dma_abort_stream(substream);
sr2 |= CCSR_DMA_SR_PE;
ret = IRQ_HANDLED;
}
if (sr & CCSR_DMA_SR_EOLNI) {
sr2 |= CCSR_DMA_SR_EOLNI;
ret = IRQ_HANDLED;
}
if (sr & CCSR_DMA_SR_CB)
ret = IRQ_HANDLED;
if (sr & CCSR_DMA_SR_EOSI) {
/* Tell ALSA we completed a period. */
snd_pcm_period_elapsed(substream);
/*
* Update our link descriptors to point to the next period. We
* only need to do this if the number of periods is not equal to
* the number of links.
*/
if (dma_private->num_periods != NUM_DMA_LINKS)
fsl_dma_update_pointers(dma_private);
sr2 |= CCSR_DMA_SR_EOSI;
ret = IRQ_HANDLED;
}
if (sr & CCSR_DMA_SR_EOLSI) {
sr2 |= CCSR_DMA_SR_EOLSI;
ret = IRQ_HANDLED;
}
/* Clear the bits that we set */
if (sr2)
out_be32(&dma_channel->sr, sr2);
return ret;
}
/**
* fsl_dma_new: initialize this PCM driver.
*
* This function is called when the codec driver calls snd_soc_new_pcms(),
* once for each .dai_link in the machine driver's snd_soc_card
* structure.
*
* snd_dma_alloc_pages() is just a front-end to dma_alloc_coherent(), which
* (currently) always allocates the DMA buffer in lowmem, even if GFP_HIGHMEM
* is specified. Therefore, any DMA buffers we allocate will always be in low
* memory, but we support for 36-bit physical addresses anyway.
*
* Regardless of where the memory is actually allocated, since the device can
* technically DMA to any 36-bit address, we do need to set the DMA mask to 36.
*/
static int fsl_dma_new(struct snd_soc_pcm_runtime *rtd)
{
struct snd_card *card = rtd->card->snd_card;
struct snd_pcm *pcm = rtd->pcm;
static u64 fsl_dma_dmamask = DMA_BIT_MASK(36);
int ret;
if (!card->dev->dma_mask)
card->dev->dma_mask = &fsl_dma_dmamask;
if (!card->dev->coherent_dma_mask)
card->dev->coherent_dma_mask = fsl_dma_dmamask;
/* Some codecs have separate DAIs for playback and capture, so we
* should allocate a DMA buffer only for the streams that are valid.
*/
if (pcm->streams[SNDRV_PCM_STREAM_PLAYBACK].substream) {
ret = snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV, card->dev,
fsl_dma_hardware.buffer_bytes_max,
&pcm->streams[SNDRV_PCM_STREAM_PLAYBACK].substream->dma_buffer);
if (ret) {
dev_err(card->dev, "can't alloc playback dma buffer\n");
return ret;
}
}
if (pcm->streams[SNDRV_PCM_STREAM_CAPTURE].substream) {
ret = snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV, card->dev,
fsl_dma_hardware.buffer_bytes_max,
&pcm->streams[SNDRV_PCM_STREAM_CAPTURE].substream->dma_buffer);
if (ret) {
dev_err(card->dev, "can't alloc capture dma buffer\n");
snd_dma_free_pages(&pcm->streams[SNDRV_PCM_STREAM_PLAYBACK].substream->dma_buffer);
return ret;
}
}
return 0;
}
/**
* fsl_dma_open: open a new substream.
*
* Each substream has its own DMA buffer.
*
* ALSA divides the DMA buffer into N periods. We create NUM_DMA_LINKS link
* descriptors that ping-pong from one period to the next. For example, if
* there are six periods and two link descriptors, this is how they look
* before playback starts:
*
* The last link descriptor
* ____________ points back to the first
* | |
* V |
* ___ ___ |
* | |->| |->|
* |___| |___|
* | |
* | |
* V V
* _________________________________________
* | | | | | | | The DMA buffer is
* | | | | | | | divided into 6 parts
* |______|______|______|______|______|______|
*
* and here's how they look after the first period is finished playing:
*
* ____________
* | |
* V |
* ___ ___ |
* | |->| |->|
* |___| |___|
* | |
* |______________
* | |
* V V
* _________________________________________
* | | | | | | |
* | | | | | | |
* |______|______|______|______|______|______|
*
* The first link descriptor now points to the third period. The DMA
* controller is currently playing the second period. When it finishes, it
* will jump back to the first descriptor and play the third period.
*
* There are four reasons we do this:
*
* 1. The only way to get the DMA controller to automatically restart the
* transfer when it gets to the end of the buffer is to use chaining
* mode. Basic direct mode doesn't offer that feature.
* 2. We need to receive an interrupt at the end of every period. The DMA
* controller can generate an interrupt at the end of every link transfer
* (aka segment). Making each period into a DMA segment will give us the
* interrupts we need.
* 3. By creating only two link descriptors, regardless of the number of
* periods, we do not need to reallocate the link descriptors if the
* number of periods changes.
* 4. All of the audio data is still stored in a single, contiguous DMA
* buffer, which is what ALSA expects. We're just dividing it into
* contiguous parts, and creating a link descriptor for each one.
*/
static int fsl_dma_open(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct device *dev = rtd->platform->dev;
struct dma_object *dma =
container_of(rtd->platform->driver, struct dma_object, dai);
struct fsl_dma_private *dma_private;
struct ccsr_dma_channel __iomem *dma_channel;
dma_addr_t ld_buf_phys;
u64 temp_link; /* Pointer to next link descriptor */
u32 mr;
unsigned int channel;
int ret = 0;
unsigned int i;
/*
* Reject any DMA buffer whose size is not a multiple of the period
* size. We need to make sure that the DMA buffer can be evenly divided
* into periods.
*/
ret = snd_pcm_hw_constraint_integer(runtime,
SNDRV_PCM_HW_PARAM_PERIODS);
if (ret < 0) {
dev_err(dev, "invalid buffer size\n");
return ret;
}
channel = substream->stream == SNDRV_PCM_STREAM_PLAYBACK ? 0 : 1;
if (dma->assigned) {
dev_err(dev, "dma channel already assigned\n");
return -EBUSY;
}
dma_private = dma_alloc_coherent(dev, sizeof(struct fsl_dma_private),
&ld_buf_phys, GFP_KERNEL);
if (!dma_private) {
dev_err(dev, "can't allocate dma private data\n");
return -ENOMEM;
}
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
dma_private->ssi_sxx_phys = dma->ssi_stx_phys;
else
dma_private->ssi_sxx_phys = dma->ssi_srx_phys;
dma_private->ssi_fifo_depth = dma->ssi_fifo_depth;
dma_private->dma_channel = dma->channel;
dma_private->irq = dma->irq;
dma_private->substream = substream;
dma_private->ld_buf_phys = ld_buf_phys;
dma_private->dma_buf_phys = substream->dma_buffer.addr;
ret = request_irq(dma_private->irq, fsl_dma_isr, 0, "fsldma-audio",
dma_private);
if (ret) {
dev_err(dev, "can't register ISR for IRQ %u (ret=%i)\n",
dma_private->irq, ret);
dma_free_coherent(dev, sizeof(struct fsl_dma_private),
dma_private, dma_private->ld_buf_phys);
return ret;
}
dma->assigned = 1;
snd_pcm_set_runtime_buffer(substream, &substream->dma_buffer);
snd_soc_set_runtime_hwparams(substream, &fsl_dma_hardware);
runtime->private_data = dma_private;
/* Program the fixed DMA controller parameters */
dma_channel = dma_private->dma_channel;
temp_link = dma_private->ld_buf_phys +
sizeof(struct fsl_dma_link_descriptor);
for (i = 0; i < NUM_DMA_LINKS; i++) {
dma_private->link[i].next = cpu_to_be64(temp_link);
temp_link += sizeof(struct fsl_dma_link_descriptor);
}
/* The last link descriptor points to the first */
dma_private->link[i - 1].next = cpu_to_be64(dma_private->ld_buf_phys);
/* Tell the DMA controller where the first link descriptor is */
out_be32(&dma_channel->clndar,
CCSR_DMA_CLNDAR_ADDR(dma_private->ld_buf_phys));
out_be32(&dma_channel->eclndar,
CCSR_DMA_ECLNDAR_ADDR(dma_private->ld_buf_phys));
/* The manual says the BCR must be clear before enabling EMP */
out_be32(&dma_channel->bcr, 0);
/*
* Program the mode register for interrupts, external master control,
* and source/destination hold. Also clear the Channel Abort bit.
*/
mr = in_be32(&dma_channel->mr) &
~(CCSR_DMA_MR_CA | CCSR_DMA_MR_DAHE | CCSR_DMA_MR_SAHE);
/*
* We want External Master Start and External Master Pause enabled,
* because the SSI is controlling the DMA controller. We want the DMA
* controller to be set up in advance, and then we signal only the SSI
* to start transferring.
*
* We want End-Of-Segment Interrupts enabled, because this will generate
* an interrupt at the end of each segment (each link descriptor
* represents one segment). Each DMA segment is the same thing as an
* ALSA period, so this is how we get an interrupt at the end of every
* period.
*
* We want Error Interrupt enabled, so that we can get an error if
* the DMA controller is mis-programmed somehow.
*/
mr |= CCSR_DMA_MR_EOSIE | CCSR_DMA_MR_EIE | CCSR_DMA_MR_EMP_EN |
CCSR_DMA_MR_EMS_EN;
/* For playback, we want the destination address to be held. For
capture, set the source address to be held. */
mr |= (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) ?
CCSR_DMA_MR_DAHE : CCSR_DMA_MR_SAHE;
out_be32(&dma_channel->mr, mr);
return 0;
}
/**
* fsl_dma_hw_params: continue initializing the DMA links
*
* This function obtains hardware parameters about the opened stream and
* programs the DMA controller accordingly.
*
* One drawback of big-endian is that when copying integers of different
* sizes to a fixed-sized register, the address to which the integer must be
* copied is dependent on the size of the integer.
*
* For example, if P is the address of a 32-bit register, and X is a 32-bit
* integer, then X should be copied to address P. However, if X is a 16-bit
* integer, then it should be copied to P+2. If X is an 8-bit register,
* then it should be copied to P+3.
*
* So for playback of 8-bit samples, the DMA controller must transfer single
* bytes from the DMA buffer to the last byte of the STX0 register, i.e.
* offset by 3 bytes. For 16-bit samples, the offset is two bytes.
*
* For 24-bit samples, the offset is 1 byte. However, the DMA controller
* does not support 3-byte copies (the DAHTS register supports only 1, 2, 4,
* and 8 bytes at a time). So we do not support packed 24-bit samples.
* 24-bit data must be padded to 32 bits.
*/
static int fsl_dma_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct fsl_dma_private *dma_private = runtime->private_data;
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct device *dev = rtd->platform->dev;
/* Number of bits per sample */
unsigned int sample_bits =
snd_pcm_format_physical_width(params_format(hw_params));
/* Number of bytes per frame */
unsigned int sample_bytes = sample_bits / 8;
/* Bus address of SSI STX register */
dma_addr_t ssi_sxx_phys = dma_private->ssi_sxx_phys;
/* Size of the DMA buffer, in bytes */
size_t buffer_size = params_buffer_bytes(hw_params);
/* Number of bytes per period */
size_t period_size = params_period_bytes(hw_params);
/* Pointer to next period */
dma_addr_t temp_addr = substream->dma_buffer.addr;
/* Pointer to DMA controller */
struct ccsr_dma_channel __iomem *dma_channel = dma_private->dma_channel;
u32 mr; /* DMA Mode Register */
unsigned int i;
/* Initialize our DMA tracking variables */
dma_private->period_size = period_size;
dma_private->num_periods = params_periods(hw_params);
dma_private->dma_buf_end = dma_private->dma_buf_phys + buffer_size;
dma_private->dma_buf_next = dma_private->dma_buf_phys +
(NUM_DMA_LINKS * period_size);
if (dma_private->dma_buf_next >= dma_private->dma_buf_end)
/* This happens if the number of periods == NUM_DMA_LINKS */
dma_private->dma_buf_next = dma_private->dma_buf_phys;
mr = in_be32(&dma_channel->mr) & ~(CCSR_DMA_MR_BWC_MASK |
CCSR_DMA_MR_SAHTS_MASK | CCSR_DMA_MR_DAHTS_MASK);
/* Due to a quirk of the SSI's STX register, the target address
* for the DMA operations depends on the sample size. So we calculate
* that offset here. While we're at it, also tell the DMA controller
* how much data to transfer per sample.
*/
switch (sample_bits) {
case 8:
mr |= CCSR_DMA_MR_DAHTS_1 | CCSR_DMA_MR_SAHTS_1;
ssi_sxx_phys += 3;
break;
case 16:
mr |= CCSR_DMA_MR_DAHTS_2 | CCSR_DMA_MR_SAHTS_2;
ssi_sxx_phys += 2;
break;
case 32:
mr |= CCSR_DMA_MR_DAHTS_4 | CCSR_DMA_MR_SAHTS_4;
break;
default:
/* We should never get here */
dev_err(dev, "unsupported sample size %u\n", sample_bits);
return -EINVAL;
}
/*
* BWC determines how many bytes are sent/received before the DMA
* controller checks the SSI to see if it needs to stop. BWC should
* always be a multiple of the frame size, so that we always transmit
* whole frames. Each frame occupies two slots in the FIFO. The
* parameter for CCSR_DMA_MR_BWC() is rounded down the next power of two
* (MR[BWC] can only represent even powers of two).
*
* To simplify the process, we set BWC to the largest value that is
* less than or equal to the FIFO watermark. For playback, this ensures
* that we transfer the maximum amount without overrunning the FIFO.
* For capture, this ensures that we transfer the maximum amount without
* underrunning the FIFO.
*
* f = SSI FIFO depth
* w = SSI watermark value (which equals f - 2)
* b = DMA bandwidth count (in bytes)
* s = sample size (in bytes, which equals frame_size * 2)
*
* For playback, we never transmit more than the transmit FIFO
* watermark, otherwise we might write more data than the FIFO can hold.
* The watermark is equal to the FIFO depth minus two.
*
* For capture, two equations must hold:
* w > f - (b / s)
* w >= b / s
*
* So, b > 2 * s, but b must also be <= s * w. To simplify, we set
* b = s * w, which is equal to
* (dma_private->ssi_fifo_depth - 2) * sample_bytes.
*/
mr |= CCSR_DMA_MR_BWC((dma_private->ssi_fifo_depth - 2) * sample_bytes);
out_be32(&dma_channel->mr, mr);
for (i = 0; i < NUM_DMA_LINKS; i++) {
struct fsl_dma_link_descriptor *link = &dma_private->link[i];
link->count = cpu_to_be32(period_size);
/* The snoop bit tells the DMA controller whether it should tell
* the ECM to snoop during a read or write to an address. For
* audio, we use DMA to transfer data between memory and an I/O
* device (the SSI's STX0 or SRX0 register). Snooping is only
* needed if there is a cache, so we need to snoop memory
* addresses only. For playback, that means we snoop the source
* but not the destination. For capture, we snoop the
* destination but not the source.
*
* Note that failing to snoop properly is unlikely to cause
* cache incoherency if the period size is larger than the
* size of L1 cache. This is because filling in one period will
* flush out the data for the previous period. So if you
* increased period_bytes_min to a large enough size, you might
* get more performance by not snooping, and you'll still be
* okay. You'll need to update fsl_dma_update_pointers() also.
*/
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
link->source_addr = cpu_to_be32(temp_addr);
link->source_attr = cpu_to_be32(CCSR_DMA_ATR_SNOOP |
upper_32_bits(temp_addr));
link->dest_addr = cpu_to_be32(ssi_sxx_phys);
link->dest_attr = cpu_to_be32(CCSR_DMA_ATR_NOSNOOP |
upper_32_bits(ssi_sxx_phys));
} else {
link->source_addr = cpu_to_be32(ssi_sxx_phys);
link->source_attr = cpu_to_be32(CCSR_DMA_ATR_NOSNOOP |
upper_32_bits(ssi_sxx_phys));
link->dest_addr = cpu_to_be32(temp_addr);
link->dest_attr = cpu_to_be32(CCSR_DMA_ATR_SNOOP |
upper_32_bits(temp_addr));
}
temp_addr += period_size;
}
return 0;
}
/**
* fsl_dma_pointer: determine the current position of the DMA transfer
*
* This function is called by ALSA when ALSA wants to know where in the
* stream buffer the hardware currently is.
*
* For playback, the SAR register contains the physical address of the most
* recent DMA transfer. For capture, the value is in the DAR register.
*
* The base address of the buffer is stored in the source_addr field of the
* first link descriptor.
*/
static snd_pcm_uframes_t fsl_dma_pointer(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct fsl_dma_private *dma_private = runtime->private_data;
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct device *dev = rtd->platform->dev;
struct ccsr_dma_channel __iomem *dma_channel = dma_private->dma_channel;
dma_addr_t position;
snd_pcm_uframes_t frames;
/* Obtain the current DMA pointer, but don't read the ESAD bits if we
* only have 32-bit DMA addresses. This function is typically called
* in interrupt context, so we need to optimize it.
*/
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
position = in_be32(&dma_channel->sar);
#ifdef CONFIG_PHYS_64BIT
position |= (u64)(in_be32(&dma_channel->satr) &
CCSR_DMA_ATR_ESAD_MASK) << 32;
#endif
} else {
position = in_be32(&dma_channel->dar);
#ifdef CONFIG_PHYS_64BIT
position |= (u64)(in_be32(&dma_channel->datr) &
CCSR_DMA_ATR_ESAD_MASK) << 32;
#endif
}
/*
* When capture is started, the SSI immediately starts to fill its FIFO.
* This means that the DMA controller is not started until the FIFO is
* full. However, ALSA calls this function before that happens, when
* MR.DAR is still zero. In this case, just return zero to indicate
* that nothing has been received yet.
*/
if (!position)
return 0;
if ((position < dma_private->dma_buf_phys) ||
(position > dma_private->dma_buf_end)) {
dev_err(dev, "dma pointer is out of range, halting stream\n");
return SNDRV_PCM_POS_XRUN;
}
frames = bytes_to_frames(runtime, position - dma_private->dma_buf_phys);
/*
* If the current address is just past the end of the buffer, wrap it
* around.
*/
if (frames == runtime->buffer_size)
frames = 0;
return frames;
}
/**
* fsl_dma_hw_free: release resources allocated in fsl_dma_hw_params()
*
* Release the resources allocated in fsl_dma_hw_params() and de-program the
* registers.
*
* This function can be called multiple times.
*/
static int fsl_dma_hw_free(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct fsl_dma_private *dma_private = runtime->private_data;
if (dma_private) {
struct ccsr_dma_channel __iomem *dma_channel;
dma_channel = dma_private->dma_channel;
/* Stop the DMA */
out_be32(&dma_channel->mr, CCSR_DMA_MR_CA);
out_be32(&dma_channel->mr, 0);
/* Reset all the other registers */
out_be32(&dma_channel->sr, -1);
out_be32(&dma_channel->clndar, 0);
out_be32(&dma_channel->eclndar, 0);
out_be32(&dma_channel->satr, 0);
out_be32(&dma_channel->sar, 0);
out_be32(&dma_channel->datr, 0);
out_be32(&dma_channel->dar, 0);
out_be32(&dma_channel->bcr, 0);
out_be32(&dma_channel->nlndar, 0);
out_be32(&dma_channel->enlndar, 0);
}
return 0;
}
/**
* fsl_dma_close: close the stream.
*/
static int fsl_dma_close(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct fsl_dma_private *dma_private = runtime->private_data;
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct device *dev = rtd->platform->dev;
struct dma_object *dma =
container_of(rtd->platform->driver, struct dma_object, dai);
if (dma_private) {
if (dma_private->irq)
free_irq(dma_private->irq, dma_private);
if (dma_private->ld_buf_phys) {
dma_unmap_single(dev, dma_private->ld_buf_phys,
sizeof(dma_private->link),
DMA_TO_DEVICE);
}
/* Deallocate the fsl_dma_private structure */
dma_free_coherent(dev, sizeof(struct fsl_dma_private),
dma_private, dma_private->ld_buf_phys);
substream->runtime->private_data = NULL;
}
dma->assigned = 0;
return 0;
}
/*
* Remove this PCM driver.
*/
static void fsl_dma_free_dma_buffers(struct snd_pcm *pcm)
{
struct snd_pcm_substream *substream;
unsigned int i;
for (i = 0; i < ARRAY_SIZE(pcm->streams); i++) {
substream = pcm->streams[i].substream;
if (substream) {
snd_dma_free_pages(&substream->dma_buffer);
substream->dma_buffer.area = NULL;
substream->dma_buffer.addr = 0;
}
}
}
/**
* find_ssi_node -- returns the SSI node that points to his DMA channel node
*
* Although this DMA driver attempts to operate independently of the other
* devices, it still needs to determine some information about the SSI device
* that it's working with. Unfortunately, the device tree does not contain
* a pointer from the DMA channel node to the SSI node -- the pointer goes the
* other way. So we need to scan the device tree for SSI nodes until we find
* the one that points to the given DMA channel node. It's ugly, but at least
* it's contained in this one function.
*/
static struct device_node *find_ssi_node(struct device_node *dma_channel_np)
{
struct device_node *ssi_np, *np;
for_each_compatible_node(ssi_np, NULL, "fsl,mpc8610-ssi") {
/* Check each DMA phandle to see if it points to us. We
* assume that device_node pointers are a valid comparison.
*/
np = of_parse_phandle(ssi_np, "fsl,playback-dma", 0);
of_node_put(np);
if (np == dma_channel_np)
return ssi_np;
np = of_parse_phandle(ssi_np, "fsl,capture-dma", 0);
of_node_put(np);
if (np == dma_channel_np)
return ssi_np;
}
return NULL;
}
static struct snd_pcm_ops fsl_dma_ops = {
.open = fsl_dma_open,
.close = fsl_dma_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = fsl_dma_hw_params,
.hw_free = fsl_dma_hw_free,
.pointer = fsl_dma_pointer,
};
static int __devinit fsl_soc_dma_probe(struct platform_device *pdev)
{
struct dma_object *dma;
struct device_node *np = pdev->dev.of_node;
struct device_node *ssi_np;
struct resource res;
const uint32_t *iprop;
int ret;
/* Find the SSI node that points to us. */
ssi_np = find_ssi_node(np);
if (!ssi_np) {
dev_err(&pdev->dev, "cannot find parent SSI node\n");
return -ENODEV;
}
ret = of_address_to_resource(ssi_np, 0, &res);
if (ret) {
dev_err(&pdev->dev, "could not determine resources for %s\n",
ssi_np->full_name);
of_node_put(ssi_np);
return ret;
}
dma = kzalloc(sizeof(*dma) + strlen(np->full_name), GFP_KERNEL);
if (!dma) {
dev_err(&pdev->dev, "could not allocate dma object\n");
of_node_put(ssi_np);
return -ENOMEM;
}
strcpy(dma->path, np->full_name);
dma->dai.ops = &fsl_dma_ops;
dma->dai.pcm_new = fsl_dma_new;
dma->dai.pcm_free = fsl_dma_free_dma_buffers;
/* Store the SSI-specific information that we need */
dma->ssi_stx_phys = res.start + offsetof(struct ccsr_ssi, stx0);
dma->ssi_srx_phys = res.start + offsetof(struct ccsr_ssi, srx0);
iprop = of_get_property(ssi_np, "fsl,fifo-depth", NULL);
if (iprop)
dma->ssi_fifo_depth = be32_to_cpup(iprop);
else
/* Older 8610 DTs didn't have the fifo-depth property */
dma->ssi_fifo_depth = 8;
of_node_put(ssi_np);
ret = snd_soc_register_platform(&pdev->dev, &dma->dai);
if (ret) {
dev_err(&pdev->dev, "could not register platform\n");
kfree(dma);
return ret;
}
dma->channel = of_iomap(np, 0);
dma->irq = irq_of_parse_and_map(np, 0);
dev_set_drvdata(&pdev->dev, dma);
return 0;
}
static int __devexit fsl_soc_dma_remove(struct platform_device *pdev)
{
struct dma_object *dma = dev_get_drvdata(&pdev->dev);
snd_soc_unregister_platform(&pdev->dev);
iounmap(dma->channel);
irq_dispose_mapping(dma->irq);
kfree(dma);
return 0;
}
static const struct of_device_id fsl_soc_dma_ids[] = {
{ .compatible = "fsl,ssi-dma-channel", },
{}
};
MODULE_DEVICE_TABLE(of, fsl_soc_dma_ids);
static struct platform_driver fsl_soc_dma_driver = {
.driver = {
.name = "fsl-pcm-audio",
.owner = THIS_MODULE,
.of_match_table = fsl_soc_dma_ids,
},
.probe = fsl_soc_dma_probe,
.remove = __devexit_p(fsl_soc_dma_remove),
};
module_platform_driver(fsl_soc_dma_driver);
MODULE_AUTHOR("Timur Tabi <timur@freescale.com>");
MODULE_DESCRIPTION("Freescale Elo DMA ASoC PCM Driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
ruslan250283/alcatel_6036 | drivers/power/olpc_battery.c | 4946 | 15711 | /*
* Battery driver for One Laptop Per Child board.
*
* Copyright © 2006-2010 David Woodhouse <dwmw2@infradead.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/err.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/power_supply.h>
#include <linux/jiffies.h>
#include <linux/sched.h>
#include <asm/olpc.h>
#define EC_BAT_VOLTAGE 0x10 /* uint16_t, *9.76/32, mV */
#define EC_BAT_CURRENT 0x11 /* int16_t, *15.625/120, mA */
#define EC_BAT_ACR 0x12 /* int16_t, *6250/15, µAh */
#define EC_BAT_TEMP 0x13 /* uint16_t, *100/256, °C */
#define EC_AMB_TEMP 0x14 /* uint16_t, *100/256, °C */
#define EC_BAT_STATUS 0x15 /* uint8_t, bitmask */
#define EC_BAT_SOC 0x16 /* uint8_t, percentage */
#define EC_BAT_SERIAL 0x17 /* uint8_t[6] */
#define EC_BAT_EEPROM 0x18 /* uint8_t adr as input, uint8_t output */
#define EC_BAT_ERRCODE 0x1f /* uint8_t, bitmask */
#define BAT_STAT_PRESENT 0x01
#define BAT_STAT_FULL 0x02
#define BAT_STAT_LOW 0x04
#define BAT_STAT_DESTROY 0x08
#define BAT_STAT_AC 0x10
#define BAT_STAT_CHARGING 0x20
#define BAT_STAT_DISCHARGING 0x40
#define BAT_STAT_TRICKLE 0x80
#define BAT_ERR_INFOFAIL 0x02
#define BAT_ERR_OVERVOLTAGE 0x04
#define BAT_ERR_OVERTEMP 0x05
#define BAT_ERR_GAUGESTOP 0x06
#define BAT_ERR_OUT_OF_CONTROL 0x07
#define BAT_ERR_ID_FAIL 0x09
#define BAT_ERR_ACR_FAIL 0x10
#define BAT_ADDR_MFR_TYPE 0x5F
/*********************************************************************
* Power
*********************************************************************/
static int olpc_ac_get_prop(struct power_supply *psy,
enum power_supply_property psp,
union power_supply_propval *val)
{
int ret = 0;
uint8_t status;
switch (psp) {
case POWER_SUPPLY_PROP_ONLINE:
ret = olpc_ec_cmd(EC_BAT_STATUS, NULL, 0, &status, 1);
if (ret)
return ret;
val->intval = !!(status & BAT_STAT_AC);
break;
default:
ret = -EINVAL;
break;
}
return ret;
}
static enum power_supply_property olpc_ac_props[] = {
POWER_SUPPLY_PROP_ONLINE,
};
static struct power_supply olpc_ac = {
.name = "olpc-ac",
.type = POWER_SUPPLY_TYPE_MAINS,
.properties = olpc_ac_props,
.num_properties = ARRAY_SIZE(olpc_ac_props),
.get_property = olpc_ac_get_prop,
};
static char bat_serial[17]; /* Ick */
static int olpc_bat_get_status(union power_supply_propval *val, uint8_t ec_byte)
{
if (olpc_platform_info.ecver > 0x44) {
if (ec_byte & (BAT_STAT_CHARGING | BAT_STAT_TRICKLE))
val->intval = POWER_SUPPLY_STATUS_CHARGING;
else if (ec_byte & BAT_STAT_DISCHARGING)
val->intval = POWER_SUPPLY_STATUS_DISCHARGING;
else if (ec_byte & BAT_STAT_FULL)
val->intval = POWER_SUPPLY_STATUS_FULL;
else /* er,... */
val->intval = POWER_SUPPLY_STATUS_NOT_CHARGING;
} else {
/* Older EC didn't report charge/discharge bits */
if (!(ec_byte & BAT_STAT_AC)) /* No AC means discharging */
val->intval = POWER_SUPPLY_STATUS_DISCHARGING;
else if (ec_byte & BAT_STAT_FULL)
val->intval = POWER_SUPPLY_STATUS_FULL;
else /* Not _necessarily_ true but EC doesn't tell all yet */
val->intval = POWER_SUPPLY_STATUS_CHARGING;
}
return 0;
}
static int olpc_bat_get_health(union power_supply_propval *val)
{
uint8_t ec_byte;
int ret;
ret = olpc_ec_cmd(EC_BAT_ERRCODE, NULL, 0, &ec_byte, 1);
if (ret)
return ret;
switch (ec_byte) {
case 0:
val->intval = POWER_SUPPLY_HEALTH_GOOD;
break;
case BAT_ERR_OVERTEMP:
val->intval = POWER_SUPPLY_HEALTH_OVERHEAT;
break;
case BAT_ERR_OVERVOLTAGE:
val->intval = POWER_SUPPLY_HEALTH_OVERVOLTAGE;
break;
case BAT_ERR_INFOFAIL:
case BAT_ERR_OUT_OF_CONTROL:
case BAT_ERR_ID_FAIL:
case BAT_ERR_ACR_FAIL:
val->intval = POWER_SUPPLY_HEALTH_UNSPEC_FAILURE;
break;
default:
/* Eep. We don't know this failure code */
ret = -EIO;
}
return ret;
}
static int olpc_bat_get_mfr(union power_supply_propval *val)
{
uint8_t ec_byte;
int ret;
ec_byte = BAT_ADDR_MFR_TYPE;
ret = olpc_ec_cmd(EC_BAT_EEPROM, &ec_byte, 1, &ec_byte, 1);
if (ret)
return ret;
switch (ec_byte >> 4) {
case 1:
val->strval = "Gold Peak";
break;
case 2:
val->strval = "BYD";
break;
default:
val->strval = "Unknown";
break;
}
return ret;
}
static int olpc_bat_get_tech(union power_supply_propval *val)
{
uint8_t ec_byte;
int ret;
ec_byte = BAT_ADDR_MFR_TYPE;
ret = olpc_ec_cmd(EC_BAT_EEPROM, &ec_byte, 1, &ec_byte, 1);
if (ret)
return ret;
switch (ec_byte & 0xf) {
case 1:
val->intval = POWER_SUPPLY_TECHNOLOGY_NiMH;
break;
case 2:
val->intval = POWER_SUPPLY_TECHNOLOGY_LiFe;
break;
default:
val->intval = POWER_SUPPLY_TECHNOLOGY_UNKNOWN;
break;
}
return ret;
}
static int olpc_bat_get_charge_full_design(union power_supply_propval *val)
{
uint8_t ec_byte;
union power_supply_propval tech;
int ret, mfr;
ret = olpc_bat_get_tech(&tech);
if (ret)
return ret;
ec_byte = BAT_ADDR_MFR_TYPE;
ret = olpc_ec_cmd(EC_BAT_EEPROM, &ec_byte, 1, &ec_byte, 1);
if (ret)
return ret;
mfr = ec_byte >> 4;
switch (tech.intval) {
case POWER_SUPPLY_TECHNOLOGY_NiMH:
switch (mfr) {
case 1: /* Gold Peak */
val->intval = 3000000*.8;
break;
default:
return -EIO;
}
break;
case POWER_SUPPLY_TECHNOLOGY_LiFe:
switch (mfr) {
case 1: /* Gold Peak */
val->intval = 2800000;
break;
case 2: /* BYD */
val->intval = 3100000;
break;
default:
return -EIO;
}
break;
default:
return -EIO;
}
return ret;
}
static int olpc_bat_get_charge_now(union power_supply_propval *val)
{
uint8_t soc;
union power_supply_propval full;
int ret;
ret = olpc_ec_cmd(EC_BAT_SOC, NULL, 0, &soc, 1);
if (ret)
return ret;
ret = olpc_bat_get_charge_full_design(&full);
if (ret)
return ret;
val->intval = soc * (full.intval / 100);
return 0;
}
/*********************************************************************
* Battery properties
*********************************************************************/
static int olpc_bat_get_property(struct power_supply *psy,
enum power_supply_property psp,
union power_supply_propval *val)
{
int ret = 0;
__be16 ec_word;
uint8_t ec_byte;
__be64 ser_buf;
ret = olpc_ec_cmd(EC_BAT_STATUS, NULL, 0, &ec_byte, 1);
if (ret)
return ret;
/* Theoretically there's a race here -- the battery could be
removed immediately after we check whether it's present, and
then we query for some other property of the now-absent battery.
It doesn't matter though -- the EC will return the last-known
information, and it's as if we just ran that _little_ bit faster
and managed to read it out before the battery went away. */
if (!(ec_byte & (BAT_STAT_PRESENT | BAT_STAT_TRICKLE)) &&
psp != POWER_SUPPLY_PROP_PRESENT)
return -ENODEV;
switch (psp) {
case POWER_SUPPLY_PROP_STATUS:
ret = olpc_bat_get_status(val, ec_byte);
if (ret)
return ret;
break;
case POWER_SUPPLY_PROP_CHARGE_TYPE:
if (ec_byte & BAT_STAT_TRICKLE)
val->intval = POWER_SUPPLY_CHARGE_TYPE_TRICKLE;
else if (ec_byte & BAT_STAT_CHARGING)
val->intval = POWER_SUPPLY_CHARGE_TYPE_FAST;
else
val->intval = POWER_SUPPLY_CHARGE_TYPE_NONE;
break;
case POWER_SUPPLY_PROP_PRESENT:
val->intval = !!(ec_byte & (BAT_STAT_PRESENT |
BAT_STAT_TRICKLE));
break;
case POWER_SUPPLY_PROP_HEALTH:
if (ec_byte & BAT_STAT_DESTROY)
val->intval = POWER_SUPPLY_HEALTH_DEAD;
else {
ret = olpc_bat_get_health(val);
if (ret)
return ret;
}
break;
case POWER_SUPPLY_PROP_MANUFACTURER:
ret = olpc_bat_get_mfr(val);
if (ret)
return ret;
break;
case POWER_SUPPLY_PROP_TECHNOLOGY:
ret = olpc_bat_get_tech(val);
if (ret)
return ret;
break;
case POWER_SUPPLY_PROP_VOLTAGE_AVG:
case POWER_SUPPLY_PROP_VOLTAGE_NOW:
ret = olpc_ec_cmd(EC_BAT_VOLTAGE, NULL, 0, (void *)&ec_word, 2);
if (ret)
return ret;
val->intval = (s16)be16_to_cpu(ec_word) * 9760L / 32;
break;
case POWER_SUPPLY_PROP_CURRENT_AVG:
case POWER_SUPPLY_PROP_CURRENT_NOW:
ret = olpc_ec_cmd(EC_BAT_CURRENT, NULL, 0, (void *)&ec_word, 2);
if (ret)
return ret;
val->intval = (s16)be16_to_cpu(ec_word) * 15625L / 120;
break;
case POWER_SUPPLY_PROP_CAPACITY:
ret = olpc_ec_cmd(EC_BAT_SOC, NULL, 0, &ec_byte, 1);
if (ret)
return ret;
val->intval = ec_byte;
break;
case POWER_SUPPLY_PROP_CAPACITY_LEVEL:
if (ec_byte & BAT_STAT_FULL)
val->intval = POWER_SUPPLY_CAPACITY_LEVEL_FULL;
else if (ec_byte & BAT_STAT_LOW)
val->intval = POWER_SUPPLY_CAPACITY_LEVEL_LOW;
else
val->intval = POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
break;
case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN:
ret = olpc_bat_get_charge_full_design(val);
if (ret)
return ret;
break;
case POWER_SUPPLY_PROP_CHARGE_NOW:
ret = olpc_bat_get_charge_now(val);
if (ret)
return ret;
break;
case POWER_SUPPLY_PROP_TEMP:
ret = olpc_ec_cmd(EC_BAT_TEMP, NULL, 0, (void *)&ec_word, 2);
if (ret)
return ret;
val->intval = (s16)be16_to_cpu(ec_word) * 100 / 256;
break;
case POWER_SUPPLY_PROP_TEMP_AMBIENT:
ret = olpc_ec_cmd(EC_AMB_TEMP, NULL, 0, (void *)&ec_word, 2);
if (ret)
return ret;
val->intval = (int)be16_to_cpu(ec_word) * 100 / 256;
break;
case POWER_SUPPLY_PROP_CHARGE_COUNTER:
ret = olpc_ec_cmd(EC_BAT_ACR, NULL, 0, (void *)&ec_word, 2);
if (ret)
return ret;
val->intval = (s16)be16_to_cpu(ec_word) * 6250 / 15;
break;
case POWER_SUPPLY_PROP_SERIAL_NUMBER:
ret = olpc_ec_cmd(EC_BAT_SERIAL, NULL, 0, (void *)&ser_buf, 8);
if (ret)
return ret;
sprintf(bat_serial, "%016llx", (long long)be64_to_cpu(ser_buf));
val->strval = bat_serial;
break;
default:
ret = -EINVAL;
break;
}
return ret;
}
static enum power_supply_property olpc_xo1_bat_props[] = {
POWER_SUPPLY_PROP_STATUS,
POWER_SUPPLY_PROP_CHARGE_TYPE,
POWER_SUPPLY_PROP_PRESENT,
POWER_SUPPLY_PROP_HEALTH,
POWER_SUPPLY_PROP_TECHNOLOGY,
POWER_SUPPLY_PROP_VOLTAGE_AVG,
POWER_SUPPLY_PROP_VOLTAGE_NOW,
POWER_SUPPLY_PROP_CURRENT_AVG,
POWER_SUPPLY_PROP_CURRENT_NOW,
POWER_SUPPLY_PROP_CAPACITY,
POWER_SUPPLY_PROP_CAPACITY_LEVEL,
POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN,
POWER_SUPPLY_PROP_CHARGE_NOW,
POWER_SUPPLY_PROP_TEMP,
POWER_SUPPLY_PROP_TEMP_AMBIENT,
POWER_SUPPLY_PROP_MANUFACTURER,
POWER_SUPPLY_PROP_SERIAL_NUMBER,
POWER_SUPPLY_PROP_CHARGE_COUNTER,
};
/* XO-1.5 does not have ambient temperature property */
static enum power_supply_property olpc_xo15_bat_props[] = {
POWER_SUPPLY_PROP_STATUS,
POWER_SUPPLY_PROP_CHARGE_TYPE,
POWER_SUPPLY_PROP_PRESENT,
POWER_SUPPLY_PROP_HEALTH,
POWER_SUPPLY_PROP_TECHNOLOGY,
POWER_SUPPLY_PROP_VOLTAGE_AVG,
POWER_SUPPLY_PROP_VOLTAGE_NOW,
POWER_SUPPLY_PROP_CURRENT_AVG,
POWER_SUPPLY_PROP_CURRENT_NOW,
POWER_SUPPLY_PROP_CAPACITY,
POWER_SUPPLY_PROP_CAPACITY_LEVEL,
POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN,
POWER_SUPPLY_PROP_CHARGE_NOW,
POWER_SUPPLY_PROP_TEMP,
POWER_SUPPLY_PROP_MANUFACTURER,
POWER_SUPPLY_PROP_SERIAL_NUMBER,
POWER_SUPPLY_PROP_CHARGE_COUNTER,
};
/* EEPROM reading goes completely around the power_supply API, sadly */
#define EEPROM_START 0x20
#define EEPROM_END 0x80
#define EEPROM_SIZE (EEPROM_END - EEPROM_START)
static ssize_t olpc_bat_eeprom_read(struct file *filp, struct kobject *kobj,
struct bin_attribute *attr, char *buf, loff_t off, size_t count)
{
uint8_t ec_byte;
int ret;
int i;
if (off >= EEPROM_SIZE)
return 0;
if (off + count > EEPROM_SIZE)
count = EEPROM_SIZE - off;
for (i = 0; i < count; i++) {
ec_byte = EEPROM_START + off + i;
ret = olpc_ec_cmd(EC_BAT_EEPROM, &ec_byte, 1, &buf[i], 1);
if (ret) {
pr_err("olpc-battery: "
"EC_BAT_EEPROM cmd @ 0x%x failed - %d!\n",
ec_byte, ret);
return -EIO;
}
}
return count;
}
static struct bin_attribute olpc_bat_eeprom = {
.attr = {
.name = "eeprom",
.mode = S_IRUGO,
},
.size = 0,
.read = olpc_bat_eeprom_read,
};
/* Allow userspace to see the specific error value pulled from the EC */
static ssize_t olpc_bat_error_read(struct device *dev,
struct device_attribute *attr, char *buf)
{
uint8_t ec_byte;
ssize_t ret;
ret = olpc_ec_cmd(EC_BAT_ERRCODE, NULL, 0, &ec_byte, 1);
if (ret < 0)
return ret;
return sprintf(buf, "%d\n", ec_byte);
}
static struct device_attribute olpc_bat_error = {
.attr = {
.name = "error",
.mode = S_IRUGO,
},
.show = olpc_bat_error_read,
};
/*********************************************************************
* Initialisation
*********************************************************************/
static struct power_supply olpc_bat = {
.name = "olpc-battery",
.get_property = olpc_bat_get_property,
.use_for_apm = 1,
};
static int olpc_battery_suspend(struct platform_device *pdev,
pm_message_t state)
{
if (device_may_wakeup(olpc_ac.dev))
olpc_ec_wakeup_set(EC_SCI_SRC_ACPWR);
else
olpc_ec_wakeup_clear(EC_SCI_SRC_ACPWR);
if (device_may_wakeup(olpc_bat.dev))
olpc_ec_wakeup_set(EC_SCI_SRC_BATTERY | EC_SCI_SRC_BATSOC
| EC_SCI_SRC_BATERR);
else
olpc_ec_wakeup_clear(EC_SCI_SRC_BATTERY | EC_SCI_SRC_BATSOC
| EC_SCI_SRC_BATERR);
return 0;
}
static int __devinit olpc_battery_probe(struct platform_device *pdev)
{
int ret;
uint8_t status;
/*
* We've seen a number of EC protocol changes; this driver requires
* the latest EC protocol, supported by 0x44 and above.
*/
if (olpc_platform_info.ecver < 0x44) {
printk(KERN_NOTICE "OLPC EC version 0x%02x too old for "
"battery driver.\n", olpc_platform_info.ecver);
return -ENXIO;
}
ret = olpc_ec_cmd(EC_BAT_STATUS, NULL, 0, &status, 1);
if (ret)
return ret;
/* Ignore the status. It doesn't actually matter */
ret = power_supply_register(&pdev->dev, &olpc_ac);
if (ret)
return ret;
if (olpc_board_at_least(olpc_board_pre(0xd0))) { /* XO-1.5 */
olpc_bat.properties = olpc_xo15_bat_props;
olpc_bat.num_properties = ARRAY_SIZE(olpc_xo15_bat_props);
} else { /* XO-1 */
olpc_bat.properties = olpc_xo1_bat_props;
olpc_bat.num_properties = ARRAY_SIZE(olpc_xo1_bat_props);
}
ret = power_supply_register(&pdev->dev, &olpc_bat);
if (ret)
goto battery_failed;
ret = device_create_bin_file(olpc_bat.dev, &olpc_bat_eeprom);
if (ret)
goto eeprom_failed;
ret = device_create_file(olpc_bat.dev, &olpc_bat_error);
if (ret)
goto error_failed;
if (olpc_ec_wakeup_available()) {
device_set_wakeup_capable(olpc_ac.dev, true);
device_set_wakeup_capable(olpc_bat.dev, true);
}
return 0;
error_failed:
device_remove_bin_file(olpc_bat.dev, &olpc_bat_eeprom);
eeprom_failed:
power_supply_unregister(&olpc_bat);
battery_failed:
power_supply_unregister(&olpc_ac);
return ret;
}
static int __devexit olpc_battery_remove(struct platform_device *pdev)
{
device_remove_file(olpc_bat.dev, &olpc_bat_error);
device_remove_bin_file(olpc_bat.dev, &olpc_bat_eeprom);
power_supply_unregister(&olpc_bat);
power_supply_unregister(&olpc_ac);
return 0;
}
static const struct of_device_id olpc_battery_ids[] __devinitconst = {
{ .compatible = "olpc,xo1-battery" },
{}
};
MODULE_DEVICE_TABLE(of, olpc_battery_ids);
static struct platform_driver olpc_battery_driver = {
.driver = {
.name = "olpc-battery",
.owner = THIS_MODULE,
.of_match_table = olpc_battery_ids,
},
.probe = olpc_battery_probe,
.remove = __devexit_p(olpc_battery_remove),
.suspend = olpc_battery_suspend,
};
module_platform_driver(olpc_battery_driver);
MODULE_AUTHOR("David Woodhouse <dwmw2@infradead.org>");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Battery driver for One Laptop Per Child 'XO' machine");
| gpl-2.0 |
cphelps76/kernel_google_msm | sound/soc/fsl/mpc5200_dma.c | 4946 | 14971 | /*
* Freescale MPC5200 PSC DMA
* ALSA SoC Platform driver
*
* Copyright (C) 2008 Secret Lab Technologies Ltd.
* Copyright (C) 2009 Jon Smirl, Digispeaker
*/
#include <linux/module.h>
#include <linux/of_device.h>
#include <linux/dma-mapping.h>
#include <linux/slab.h>
#include <linux/of_platform.h>
#include <sound/soc.h>
#include <sysdev/bestcomm/bestcomm.h>
#include <sysdev/bestcomm/gen_bd.h>
#include <asm/mpc52xx_psc.h>
#include "mpc5200_dma.h"
/*
* Interrupt handlers
*/
static irqreturn_t psc_dma_status_irq(int irq, void *_psc_dma)
{
struct psc_dma *psc_dma = _psc_dma;
struct mpc52xx_psc __iomem *regs = psc_dma->psc_regs;
u16 isr;
isr = in_be16(®s->mpc52xx_psc_isr);
/* Playback underrun error */
if (psc_dma->playback.active && (isr & MPC52xx_PSC_IMR_TXEMP))
psc_dma->stats.underrun_count++;
/* Capture overrun error */
if (psc_dma->capture.active && (isr & MPC52xx_PSC_IMR_ORERR))
psc_dma->stats.overrun_count++;
out_8(®s->command, MPC52xx_PSC_RST_ERR_STAT);
return IRQ_HANDLED;
}
/**
* psc_dma_bcom_enqueue_next_buffer - Enqueue another audio buffer
* @s: pointer to stream private data structure
*
* Enqueues another audio period buffer into the bestcomm queue.
*
* Note: The routine must only be called when there is space available in
* the queue. Otherwise the enqueue will fail and the audio ring buffer
* will get out of sync
*/
static void psc_dma_bcom_enqueue_next_buffer(struct psc_dma_stream *s)
{
struct bcom_bd *bd;
/* Prepare and enqueue the next buffer descriptor */
bd = bcom_prepare_next_buffer(s->bcom_task);
bd->status = s->period_bytes;
bd->data[0] = s->runtime->dma_addr + (s->period_next * s->period_bytes);
bcom_submit_next_buffer(s->bcom_task, NULL);
/* Update for next period */
s->period_next = (s->period_next + 1) % s->runtime->periods;
}
/* Bestcomm DMA irq handler */
static irqreturn_t psc_dma_bcom_irq(int irq, void *_psc_dma_stream)
{
struct psc_dma_stream *s = _psc_dma_stream;
spin_lock(&s->psc_dma->lock);
/* For each finished period, dequeue the completed period buffer
* and enqueue a new one in it's place. */
while (bcom_buffer_done(s->bcom_task)) {
bcom_retrieve_buffer(s->bcom_task, NULL, NULL);
s->period_current = (s->period_current+1) % s->runtime->periods;
s->period_count++;
psc_dma_bcom_enqueue_next_buffer(s);
}
spin_unlock(&s->psc_dma->lock);
/* If the stream is active, then also inform the PCM middle layer
* of the period finished event. */
if (s->active)
snd_pcm_period_elapsed(s->stream);
return IRQ_HANDLED;
}
static int psc_dma_hw_free(struct snd_pcm_substream *substream)
{
snd_pcm_set_runtime_buffer(substream, NULL);
return 0;
}
/**
* psc_dma_trigger: start and stop the DMA transfer.
*
* This function is called by ALSA to start, stop, pause, and resume the DMA
* transfer of data.
*/
static int psc_dma_trigger(struct snd_pcm_substream *substream, int cmd)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct psc_dma *psc_dma = snd_soc_dai_get_drvdata(rtd->cpu_dai);
struct snd_pcm_runtime *runtime = substream->runtime;
struct psc_dma_stream *s = to_psc_dma_stream(substream, psc_dma);
struct mpc52xx_psc __iomem *regs = psc_dma->psc_regs;
u16 imr;
unsigned long flags;
int i;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
dev_dbg(psc_dma->dev, "START: stream=%i fbits=%u ps=%u #p=%u\n",
substream->pstr->stream, runtime->frame_bits,
(int)runtime->period_size, runtime->periods);
s->period_bytes = frames_to_bytes(runtime,
runtime->period_size);
s->period_next = 0;
s->period_current = 0;
s->active = 1;
s->period_count = 0;
s->runtime = runtime;
/* Fill up the bestcomm bd queue and enable DMA.
* This will begin filling the PSC's fifo.
*/
spin_lock_irqsave(&psc_dma->lock, flags);
if (substream->pstr->stream == SNDRV_PCM_STREAM_CAPTURE)
bcom_gen_bd_rx_reset(s->bcom_task);
else
bcom_gen_bd_tx_reset(s->bcom_task);
for (i = 0; i < runtime->periods; i++)
if (!bcom_queue_full(s->bcom_task))
psc_dma_bcom_enqueue_next_buffer(s);
bcom_enable(s->bcom_task);
spin_unlock_irqrestore(&psc_dma->lock, flags);
out_8(®s->command, MPC52xx_PSC_RST_ERR_STAT);
break;
case SNDRV_PCM_TRIGGER_STOP:
dev_dbg(psc_dma->dev, "STOP: stream=%i periods_count=%i\n",
substream->pstr->stream, s->period_count);
s->active = 0;
spin_lock_irqsave(&psc_dma->lock, flags);
bcom_disable(s->bcom_task);
if (substream->pstr->stream == SNDRV_PCM_STREAM_CAPTURE)
bcom_gen_bd_rx_reset(s->bcom_task);
else
bcom_gen_bd_tx_reset(s->bcom_task);
spin_unlock_irqrestore(&psc_dma->lock, flags);
break;
default:
dev_dbg(psc_dma->dev, "unhandled trigger: stream=%i cmd=%i\n",
substream->pstr->stream, cmd);
return -EINVAL;
}
/* Update interrupt enable settings */
imr = 0;
if (psc_dma->playback.active)
imr |= MPC52xx_PSC_IMR_TXEMP;
if (psc_dma->capture.active)
imr |= MPC52xx_PSC_IMR_ORERR;
out_be16(®s->isr_imr.imr, psc_dma->imr | imr);
return 0;
}
/* ---------------------------------------------------------------------
* The PSC DMA 'ASoC platform' driver
*
* Can be referenced by an 'ASoC machine' driver
* This driver only deals with the audio bus; it doesn't have any
* interaction with the attached codec
*/
static const struct snd_pcm_hardware psc_dma_hardware = {
.info = SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_BATCH,
.formats = SNDRV_PCM_FMTBIT_S8 | SNDRV_PCM_FMTBIT_S16_BE |
SNDRV_PCM_FMTBIT_S24_BE | SNDRV_PCM_FMTBIT_S32_BE,
.rate_min = 8000,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
.period_bytes_max = 1024 * 1024,
.period_bytes_min = 32,
.periods_min = 2,
.periods_max = 256,
.buffer_bytes_max = 2 * 1024 * 1024,
.fifo_size = 512,
};
static int psc_dma_open(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct psc_dma *psc_dma = snd_soc_dai_get_drvdata(rtd->cpu_dai);
struct psc_dma_stream *s;
int rc;
dev_dbg(psc_dma->dev, "psc_dma_open(substream=%p)\n", substream);
if (substream->pstr->stream == SNDRV_PCM_STREAM_CAPTURE)
s = &psc_dma->capture;
else
s = &psc_dma->playback;
snd_soc_set_runtime_hwparams(substream, &psc_dma_hardware);
rc = snd_pcm_hw_constraint_integer(runtime,
SNDRV_PCM_HW_PARAM_PERIODS);
if (rc < 0) {
dev_err(substream->pcm->card->dev, "invalid buffer size\n");
return rc;
}
s->stream = substream;
return 0;
}
static int psc_dma_close(struct snd_pcm_substream *substream)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct psc_dma *psc_dma = snd_soc_dai_get_drvdata(rtd->cpu_dai);
struct psc_dma_stream *s;
dev_dbg(psc_dma->dev, "psc_dma_close(substream=%p)\n", substream);
if (substream->pstr->stream == SNDRV_PCM_STREAM_CAPTURE)
s = &psc_dma->capture;
else
s = &psc_dma->playback;
if (!psc_dma->playback.active &&
!psc_dma->capture.active) {
/* Disable all interrupts and reset the PSC */
out_be16(&psc_dma->psc_regs->isr_imr.imr, psc_dma->imr);
out_8(&psc_dma->psc_regs->command, 4 << 4); /* reset error */
}
s->stream = NULL;
return 0;
}
static snd_pcm_uframes_t
psc_dma_pointer(struct snd_pcm_substream *substream)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct psc_dma *psc_dma = snd_soc_dai_get_drvdata(rtd->cpu_dai);
struct psc_dma_stream *s;
dma_addr_t count;
if (substream->pstr->stream == SNDRV_PCM_STREAM_CAPTURE)
s = &psc_dma->capture;
else
s = &psc_dma->playback;
count = s->period_current * s->period_bytes;
return bytes_to_frames(substream->runtime, count);
}
static int
psc_dma_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
snd_pcm_set_runtime_buffer(substream, &substream->dma_buffer);
return 0;
}
static struct snd_pcm_ops psc_dma_ops = {
.open = psc_dma_open,
.close = psc_dma_close,
.hw_free = psc_dma_hw_free,
.ioctl = snd_pcm_lib_ioctl,
.pointer = psc_dma_pointer,
.trigger = psc_dma_trigger,
.hw_params = psc_dma_hw_params,
};
static u64 psc_dma_dmamask = DMA_BIT_MASK(32);
static int psc_dma_new(struct snd_soc_pcm_runtime *rtd)
{
struct snd_card *card = rtd->card->snd_card;
struct snd_soc_dai *dai = rtd->cpu_dai;
struct snd_pcm *pcm = rtd->pcm;
struct psc_dma *psc_dma = snd_soc_dai_get_drvdata(rtd->cpu_dai);
size_t size = psc_dma_hardware.buffer_bytes_max;
int rc = 0;
dev_dbg(rtd->platform->dev, "psc_dma_new(card=%p, dai=%p, pcm=%p)\n",
card, dai, pcm);
if (!card->dev->dma_mask)
card->dev->dma_mask = &psc_dma_dmamask;
if (!card->dev->coherent_dma_mask)
card->dev->coherent_dma_mask = DMA_BIT_MASK(32);
if (pcm->streams[SNDRV_PCM_STREAM_PLAYBACK].substream) {
rc = snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV, pcm->card->dev,
size, &pcm->streams[SNDRV_PCM_STREAM_PLAYBACK].substream->dma_buffer);
if (rc)
goto playback_alloc_err;
}
if (pcm->streams[SNDRV_PCM_STREAM_CAPTURE].substream) {
rc = snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV, pcm->card->dev,
size, &pcm->streams[SNDRV_PCM_STREAM_CAPTURE].substream->dma_buffer);
if (rc)
goto capture_alloc_err;
}
if (rtd->codec->ac97)
rtd->codec->ac97->private_data = psc_dma;
return 0;
capture_alloc_err:
if (pcm->streams[SNDRV_PCM_STREAM_PLAYBACK].substream)
snd_dma_free_pages(&pcm->streams[SNDRV_PCM_STREAM_PLAYBACK].substream->dma_buffer);
playback_alloc_err:
dev_err(card->dev, "Cannot allocate buffer(s)\n");
return -ENOMEM;
}
static void psc_dma_free(struct snd_pcm *pcm)
{
struct snd_soc_pcm_runtime *rtd = pcm->private_data;
struct snd_pcm_substream *substream;
int stream;
dev_dbg(rtd->platform->dev, "psc_dma_free(pcm=%p)\n", pcm);
for (stream = 0; stream < 2; stream++) {
substream = pcm->streams[stream].substream;
if (substream) {
snd_dma_free_pages(&substream->dma_buffer);
substream->dma_buffer.area = NULL;
substream->dma_buffer.addr = 0;
}
}
}
static struct snd_soc_platform_driver mpc5200_audio_dma_platform = {
.ops = &psc_dma_ops,
.pcm_new = &psc_dma_new,
.pcm_free = &psc_dma_free,
};
static int mpc5200_hpcd_probe(struct platform_device *op)
{
phys_addr_t fifo;
struct psc_dma *psc_dma;
struct resource res;
int size, irq, rc;
const __be32 *prop;
void __iomem *regs;
int ret;
/* Fetch the registers and IRQ of the PSC */
irq = irq_of_parse_and_map(op->dev.of_node, 0);
if (of_address_to_resource(op->dev.of_node, 0, &res)) {
dev_err(&op->dev, "Missing reg property\n");
return -ENODEV;
}
regs = ioremap(res.start, resource_size(&res));
if (!regs) {
dev_err(&op->dev, "Could not map registers\n");
return -ENODEV;
}
/* Allocate and initialize the driver private data */
psc_dma = kzalloc(sizeof *psc_dma, GFP_KERNEL);
if (!psc_dma) {
ret = -ENOMEM;
goto out_unmap;
}
/* Get the PSC ID */
prop = of_get_property(op->dev.of_node, "cell-index", &size);
if (!prop || size < sizeof *prop) {
ret = -ENODEV;
goto out_free;
}
spin_lock_init(&psc_dma->lock);
mutex_init(&psc_dma->mutex);
psc_dma->id = be32_to_cpu(*prop);
psc_dma->irq = irq;
psc_dma->psc_regs = regs;
psc_dma->fifo_regs = regs + sizeof *psc_dma->psc_regs;
psc_dma->dev = &op->dev;
psc_dma->playback.psc_dma = psc_dma;
psc_dma->capture.psc_dma = psc_dma;
snprintf(psc_dma->name, sizeof psc_dma->name, "PSC%u", psc_dma->id);
/* Find the address of the fifo data registers and setup the
* DMA tasks */
fifo = res.start + offsetof(struct mpc52xx_psc, buffer.buffer_32);
psc_dma->capture.bcom_task =
bcom_psc_gen_bd_rx_init(psc_dma->id, 10, fifo, 512);
psc_dma->playback.bcom_task =
bcom_psc_gen_bd_tx_init(psc_dma->id, 10, fifo);
if (!psc_dma->capture.bcom_task ||
!psc_dma->playback.bcom_task) {
dev_err(&op->dev, "Could not allocate bestcomm tasks\n");
ret = -ENODEV;
goto out_free;
}
/* Disable all interrupts and reset the PSC */
out_be16(&psc_dma->psc_regs->isr_imr.imr, psc_dma->imr);
/* reset receiver */
out_8(&psc_dma->psc_regs->command, MPC52xx_PSC_RST_RX);
/* reset transmitter */
out_8(&psc_dma->psc_regs->command, MPC52xx_PSC_RST_TX);
/* reset error */
out_8(&psc_dma->psc_regs->command, MPC52xx_PSC_RST_ERR_STAT);
/* reset mode */
out_8(&psc_dma->psc_regs->command, MPC52xx_PSC_SEL_MODE_REG_1);
/* Set up mode register;
* First write: RxRdy (FIFO Alarm) generates rx FIFO irq
* Second write: register Normal mode for non loopback
*/
out_8(&psc_dma->psc_regs->mode, 0);
out_8(&psc_dma->psc_regs->mode, 0);
/* Set the TX and RX fifo alarm thresholds */
out_be16(&psc_dma->fifo_regs->rfalarm, 0x100);
out_8(&psc_dma->fifo_regs->rfcntl, 0x4);
out_be16(&psc_dma->fifo_regs->tfalarm, 0x100);
out_8(&psc_dma->fifo_regs->tfcntl, 0x7);
/* Lookup the IRQ numbers */
psc_dma->playback.irq =
bcom_get_task_irq(psc_dma->playback.bcom_task);
psc_dma->capture.irq =
bcom_get_task_irq(psc_dma->capture.bcom_task);
rc = request_irq(psc_dma->irq, &psc_dma_status_irq, IRQF_SHARED,
"psc-dma-status", psc_dma);
rc |= request_irq(psc_dma->capture.irq, &psc_dma_bcom_irq, IRQF_SHARED,
"psc-dma-capture", &psc_dma->capture);
rc |= request_irq(psc_dma->playback.irq, &psc_dma_bcom_irq, IRQF_SHARED,
"psc-dma-playback", &psc_dma->playback);
if (rc) {
ret = -ENODEV;
goto out_irq;
}
/* Save what we've done so it can be found again later */
dev_set_drvdata(&op->dev, psc_dma);
/* Tell the ASoC OF helpers about it */
return snd_soc_register_platform(&op->dev, &mpc5200_audio_dma_platform);
out_irq:
free_irq(psc_dma->irq, psc_dma);
free_irq(psc_dma->capture.irq, &psc_dma->capture);
free_irq(psc_dma->playback.irq, &psc_dma->playback);
out_free:
kfree(psc_dma);
out_unmap:
iounmap(regs);
return ret;
}
static int mpc5200_hpcd_remove(struct platform_device *op)
{
struct psc_dma *psc_dma = dev_get_drvdata(&op->dev);
dev_dbg(&op->dev, "mpc5200_audio_dma_destroy()\n");
snd_soc_unregister_platform(&op->dev);
bcom_gen_bd_rx_release(psc_dma->capture.bcom_task);
bcom_gen_bd_tx_release(psc_dma->playback.bcom_task);
/* Release irqs */
free_irq(psc_dma->irq, psc_dma);
free_irq(psc_dma->capture.irq, &psc_dma->capture);
free_irq(psc_dma->playback.irq, &psc_dma->playback);
iounmap(psc_dma->psc_regs);
kfree(psc_dma);
dev_set_drvdata(&op->dev, NULL);
return 0;
}
static struct of_device_id mpc5200_hpcd_match[] = {
{ .compatible = "fsl,mpc5200-pcm", },
{}
};
MODULE_DEVICE_TABLE(of, mpc5200_hpcd_match);
static struct platform_driver mpc5200_hpcd_of_driver = {
.probe = mpc5200_hpcd_probe,
.remove = mpc5200_hpcd_remove,
.driver = {
.owner = THIS_MODULE,
.name = "mpc5200-pcm-audio",
.of_match_table = mpc5200_hpcd_match,
}
};
module_platform_driver(mpc5200_hpcd_of_driver);
MODULE_AUTHOR("Grant Likely <grant.likely@secretlab.ca>");
MODULE_DESCRIPTION("Freescale MPC5200 PSC in DMA mode ASoC Driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
lollipop-og/F93_LGE975_KK_Kernel | fs/btrfs/zlib.c | 4946 | 10583 | /*
* Copyright (C) 2008 Oracle. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License v2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 021110-1307, USA.
*
* Based on jffs2 zlib code:
* Copyright © 2001-2007 Red Hat, Inc.
* Created by David Woodhouse <dwmw2@infradead.org>
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/zlib.h>
#include <linux/zutil.h>
#include <linux/vmalloc.h>
#include <linux/init.h>
#include <linux/err.h>
#include <linux/sched.h>
#include <linux/pagemap.h>
#include <linux/bio.h>
#include "compression.h"
struct workspace {
z_stream inf_strm;
z_stream def_strm;
char *buf;
struct list_head list;
};
static void zlib_free_workspace(struct list_head *ws)
{
struct workspace *workspace = list_entry(ws, struct workspace, list);
vfree(workspace->def_strm.workspace);
vfree(workspace->inf_strm.workspace);
kfree(workspace->buf);
kfree(workspace);
}
static struct list_head *zlib_alloc_workspace(void)
{
struct workspace *workspace;
workspace = kzalloc(sizeof(*workspace), GFP_NOFS);
if (!workspace)
return ERR_PTR(-ENOMEM);
workspace->def_strm.workspace = vmalloc(zlib_deflate_workspacesize(
MAX_WBITS, MAX_MEM_LEVEL));
workspace->inf_strm.workspace = vmalloc(zlib_inflate_workspacesize());
workspace->buf = kmalloc(PAGE_CACHE_SIZE, GFP_NOFS);
if (!workspace->def_strm.workspace ||
!workspace->inf_strm.workspace || !workspace->buf)
goto fail;
INIT_LIST_HEAD(&workspace->list);
return &workspace->list;
fail:
zlib_free_workspace(&workspace->list);
return ERR_PTR(-ENOMEM);
}
static int zlib_compress_pages(struct list_head *ws,
struct address_space *mapping,
u64 start, unsigned long len,
struct page **pages,
unsigned long nr_dest_pages,
unsigned long *out_pages,
unsigned long *total_in,
unsigned long *total_out,
unsigned long max_out)
{
struct workspace *workspace = list_entry(ws, struct workspace, list);
int ret;
char *data_in;
char *cpage_out;
int nr_pages = 0;
struct page *in_page = NULL;
struct page *out_page = NULL;
unsigned long bytes_left;
*out_pages = 0;
*total_out = 0;
*total_in = 0;
if (Z_OK != zlib_deflateInit(&workspace->def_strm, 3)) {
printk(KERN_WARNING "deflateInit failed\n");
ret = -1;
goto out;
}
workspace->def_strm.total_in = 0;
workspace->def_strm.total_out = 0;
in_page = find_get_page(mapping, start >> PAGE_CACHE_SHIFT);
data_in = kmap(in_page);
out_page = alloc_page(GFP_NOFS | __GFP_HIGHMEM);
if (out_page == NULL) {
ret = -1;
goto out;
}
cpage_out = kmap(out_page);
pages[0] = out_page;
nr_pages = 1;
workspace->def_strm.next_in = data_in;
workspace->def_strm.next_out = cpage_out;
workspace->def_strm.avail_out = PAGE_CACHE_SIZE;
workspace->def_strm.avail_in = min(len, PAGE_CACHE_SIZE);
while (workspace->def_strm.total_in < len) {
ret = zlib_deflate(&workspace->def_strm, Z_SYNC_FLUSH);
if (ret != Z_OK) {
printk(KERN_DEBUG "btrfs deflate in loop returned %d\n",
ret);
zlib_deflateEnd(&workspace->def_strm);
ret = -1;
goto out;
}
/* we're making it bigger, give up */
if (workspace->def_strm.total_in > 8192 &&
workspace->def_strm.total_in <
workspace->def_strm.total_out) {
ret = -1;
goto out;
}
/* we need another page for writing out. Test this
* before the total_in so we will pull in a new page for
* the stream end if required
*/
if (workspace->def_strm.avail_out == 0) {
kunmap(out_page);
if (nr_pages == nr_dest_pages) {
out_page = NULL;
ret = -1;
goto out;
}
out_page = alloc_page(GFP_NOFS | __GFP_HIGHMEM);
if (out_page == NULL) {
ret = -1;
goto out;
}
cpage_out = kmap(out_page);
pages[nr_pages] = out_page;
nr_pages++;
workspace->def_strm.avail_out = PAGE_CACHE_SIZE;
workspace->def_strm.next_out = cpage_out;
}
/* we're all done */
if (workspace->def_strm.total_in >= len)
break;
/* we've read in a full page, get a new one */
if (workspace->def_strm.avail_in == 0) {
if (workspace->def_strm.total_out > max_out)
break;
bytes_left = len - workspace->def_strm.total_in;
kunmap(in_page);
page_cache_release(in_page);
start += PAGE_CACHE_SIZE;
in_page = find_get_page(mapping,
start >> PAGE_CACHE_SHIFT);
data_in = kmap(in_page);
workspace->def_strm.avail_in = min(bytes_left,
PAGE_CACHE_SIZE);
workspace->def_strm.next_in = data_in;
}
}
workspace->def_strm.avail_in = 0;
ret = zlib_deflate(&workspace->def_strm, Z_FINISH);
zlib_deflateEnd(&workspace->def_strm);
if (ret != Z_STREAM_END) {
ret = -1;
goto out;
}
if (workspace->def_strm.total_out >= workspace->def_strm.total_in) {
ret = -1;
goto out;
}
ret = 0;
*total_out = workspace->def_strm.total_out;
*total_in = workspace->def_strm.total_in;
out:
*out_pages = nr_pages;
if (out_page)
kunmap(out_page);
if (in_page) {
kunmap(in_page);
page_cache_release(in_page);
}
return ret;
}
static int zlib_decompress_biovec(struct list_head *ws, struct page **pages_in,
u64 disk_start,
struct bio_vec *bvec,
int vcnt,
size_t srclen)
{
struct workspace *workspace = list_entry(ws, struct workspace, list);
int ret = 0, ret2;
int wbits = MAX_WBITS;
char *data_in;
size_t total_out = 0;
unsigned long page_in_index = 0;
unsigned long page_out_index = 0;
unsigned long total_pages_in = (srclen + PAGE_CACHE_SIZE - 1) /
PAGE_CACHE_SIZE;
unsigned long buf_start;
unsigned long pg_offset;
data_in = kmap(pages_in[page_in_index]);
workspace->inf_strm.next_in = data_in;
workspace->inf_strm.avail_in = min_t(size_t, srclen, PAGE_CACHE_SIZE);
workspace->inf_strm.total_in = 0;
workspace->inf_strm.total_out = 0;
workspace->inf_strm.next_out = workspace->buf;
workspace->inf_strm.avail_out = PAGE_CACHE_SIZE;
pg_offset = 0;
/* If it's deflate, and it's got no preset dictionary, then
we can tell zlib to skip the adler32 check. */
if (srclen > 2 && !(data_in[1] & PRESET_DICT) &&
((data_in[0] & 0x0f) == Z_DEFLATED) &&
!(((data_in[0]<<8) + data_in[1]) % 31)) {
wbits = -((data_in[0] >> 4) + 8);
workspace->inf_strm.next_in += 2;
workspace->inf_strm.avail_in -= 2;
}
if (Z_OK != zlib_inflateInit2(&workspace->inf_strm, wbits)) {
printk(KERN_WARNING "inflateInit failed\n");
return -1;
}
while (workspace->inf_strm.total_in < srclen) {
ret = zlib_inflate(&workspace->inf_strm, Z_NO_FLUSH);
if (ret != Z_OK && ret != Z_STREAM_END)
break;
buf_start = total_out;
total_out = workspace->inf_strm.total_out;
/* we didn't make progress in this inflate call, we're done */
if (buf_start == total_out)
break;
ret2 = btrfs_decompress_buf2page(workspace->buf, buf_start,
total_out, disk_start,
bvec, vcnt,
&page_out_index, &pg_offset);
if (ret2 == 0) {
ret = 0;
goto done;
}
workspace->inf_strm.next_out = workspace->buf;
workspace->inf_strm.avail_out = PAGE_CACHE_SIZE;
if (workspace->inf_strm.avail_in == 0) {
unsigned long tmp;
kunmap(pages_in[page_in_index]);
page_in_index++;
if (page_in_index >= total_pages_in) {
data_in = NULL;
break;
}
data_in = kmap(pages_in[page_in_index]);
workspace->inf_strm.next_in = data_in;
tmp = srclen - workspace->inf_strm.total_in;
workspace->inf_strm.avail_in = min(tmp,
PAGE_CACHE_SIZE);
}
}
if (ret != Z_STREAM_END)
ret = -1;
else
ret = 0;
done:
zlib_inflateEnd(&workspace->inf_strm);
if (data_in)
kunmap(pages_in[page_in_index]);
return ret;
}
static int zlib_decompress(struct list_head *ws, unsigned char *data_in,
struct page *dest_page,
unsigned long start_byte,
size_t srclen, size_t destlen)
{
struct workspace *workspace = list_entry(ws, struct workspace, list);
int ret = 0;
int wbits = MAX_WBITS;
unsigned long bytes_left = destlen;
unsigned long total_out = 0;
char *kaddr;
workspace->inf_strm.next_in = data_in;
workspace->inf_strm.avail_in = srclen;
workspace->inf_strm.total_in = 0;
workspace->inf_strm.next_out = workspace->buf;
workspace->inf_strm.avail_out = PAGE_CACHE_SIZE;
workspace->inf_strm.total_out = 0;
/* If it's deflate, and it's got no preset dictionary, then
we can tell zlib to skip the adler32 check. */
if (srclen > 2 && !(data_in[1] & PRESET_DICT) &&
((data_in[0] & 0x0f) == Z_DEFLATED) &&
!(((data_in[0]<<8) + data_in[1]) % 31)) {
wbits = -((data_in[0] >> 4) + 8);
workspace->inf_strm.next_in += 2;
workspace->inf_strm.avail_in -= 2;
}
if (Z_OK != zlib_inflateInit2(&workspace->inf_strm, wbits)) {
printk(KERN_WARNING "inflateInit failed\n");
return -1;
}
while (bytes_left > 0) {
unsigned long buf_start;
unsigned long buf_offset;
unsigned long bytes;
unsigned long pg_offset = 0;
ret = zlib_inflate(&workspace->inf_strm, Z_NO_FLUSH);
if (ret != Z_OK && ret != Z_STREAM_END)
break;
buf_start = total_out;
total_out = workspace->inf_strm.total_out;
if (total_out == buf_start) {
ret = -1;
break;
}
if (total_out <= start_byte)
goto next;
if (total_out > start_byte && buf_start < start_byte)
buf_offset = start_byte - buf_start;
else
buf_offset = 0;
bytes = min(PAGE_CACHE_SIZE - pg_offset,
PAGE_CACHE_SIZE - buf_offset);
bytes = min(bytes, bytes_left);
kaddr = kmap_atomic(dest_page);
memcpy(kaddr + pg_offset, workspace->buf + buf_offset, bytes);
kunmap_atomic(kaddr);
pg_offset += bytes;
bytes_left -= bytes;
next:
workspace->inf_strm.next_out = workspace->buf;
workspace->inf_strm.avail_out = PAGE_CACHE_SIZE;
}
if (ret != Z_STREAM_END && bytes_left != 0)
ret = -1;
else
ret = 0;
zlib_inflateEnd(&workspace->inf_strm);
return ret;
}
struct btrfs_compress_op btrfs_zlib_compress = {
.alloc_workspace = zlib_alloc_workspace,
.free_workspace = zlib_free_workspace,
.compress_pages = zlib_compress_pages,
.decompress_biovec = zlib_decompress_biovec,
.decompress = zlib_decompress,
};
| gpl-2.0 |
jiangchao87/m8uhl | net/sched/act_simple.c | 5458 | 5268 | /*
* net/sched/simp.c Simple example of an action
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Authors: Jamal Hadi Salim (2005-8)
*
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/skbuff.h>
#include <linux/rtnetlink.h>
#include <net/netlink.h>
#include <net/pkt_sched.h>
#define TCA_ACT_SIMP 22
#include <linux/tc_act/tc_defact.h>
#include <net/tc_act/tc_defact.h>
#define SIMP_TAB_MASK 7
static struct tcf_common *tcf_simp_ht[SIMP_TAB_MASK + 1];
static u32 simp_idx_gen;
static DEFINE_RWLOCK(simp_lock);
static struct tcf_hashinfo simp_hash_info = {
.htab = tcf_simp_ht,
.hmask = SIMP_TAB_MASK,
.lock = &simp_lock,
};
#define SIMP_MAX_DATA 32
static int tcf_simp(struct sk_buff *skb, const struct tc_action *a,
struct tcf_result *res)
{
struct tcf_defact *d = a->priv;
spin_lock(&d->tcf_lock);
d->tcf_tm.lastuse = jiffies;
bstats_update(&d->tcf_bstats, skb);
/* print policy string followed by _ then packet count
* Example if this was the 3rd packet and the string was "hello"
* then it would look like "hello_3" (without quotes)
*/
pr_info("simple: %s_%d\n",
(char *)d->tcfd_defdata, d->tcf_bstats.packets);
spin_unlock(&d->tcf_lock);
return d->tcf_action;
}
static int tcf_simp_release(struct tcf_defact *d, int bind)
{
int ret = 0;
if (d) {
if (bind)
d->tcf_bindcnt--;
d->tcf_refcnt--;
if (d->tcf_bindcnt <= 0 && d->tcf_refcnt <= 0) {
kfree(d->tcfd_defdata);
tcf_hash_destroy(&d->common, &simp_hash_info);
ret = 1;
}
}
return ret;
}
static int alloc_defdata(struct tcf_defact *d, char *defdata)
{
d->tcfd_defdata = kzalloc(SIMP_MAX_DATA, GFP_KERNEL);
if (unlikely(!d->tcfd_defdata))
return -ENOMEM;
strlcpy(d->tcfd_defdata, defdata, SIMP_MAX_DATA);
return 0;
}
static void reset_policy(struct tcf_defact *d, char *defdata,
struct tc_defact *p)
{
spin_lock_bh(&d->tcf_lock);
d->tcf_action = p->action;
memset(d->tcfd_defdata, 0, SIMP_MAX_DATA);
strlcpy(d->tcfd_defdata, defdata, SIMP_MAX_DATA);
spin_unlock_bh(&d->tcf_lock);
}
static const struct nla_policy simple_policy[TCA_DEF_MAX + 1] = {
[TCA_DEF_PARMS] = { .len = sizeof(struct tc_defact) },
[TCA_DEF_DATA] = { .type = NLA_STRING, .len = SIMP_MAX_DATA },
};
static int tcf_simp_init(struct nlattr *nla, struct nlattr *est,
struct tc_action *a, int ovr, int bind)
{
struct nlattr *tb[TCA_DEF_MAX + 1];
struct tc_defact *parm;
struct tcf_defact *d;
struct tcf_common *pc;
char *defdata;
int ret = 0, err;
if (nla == NULL)
return -EINVAL;
err = nla_parse_nested(tb, TCA_DEF_MAX, nla, simple_policy);
if (err < 0)
return err;
if (tb[TCA_DEF_PARMS] == NULL)
return -EINVAL;
if (tb[TCA_DEF_DATA] == NULL)
return -EINVAL;
parm = nla_data(tb[TCA_DEF_PARMS]);
defdata = nla_data(tb[TCA_DEF_DATA]);
pc = tcf_hash_check(parm->index, a, bind, &simp_hash_info);
if (!pc) {
pc = tcf_hash_create(parm->index, est, a, sizeof(*d), bind,
&simp_idx_gen, &simp_hash_info);
if (IS_ERR(pc))
return PTR_ERR(pc);
d = to_defact(pc);
ret = alloc_defdata(d, defdata);
if (ret < 0) {
kfree(pc);
return ret;
}
d->tcf_action = parm->action;
ret = ACT_P_CREATED;
} else {
d = to_defact(pc);
if (!ovr) {
tcf_simp_release(d, bind);
return -EEXIST;
}
reset_policy(d, defdata, parm);
}
if (ret == ACT_P_CREATED)
tcf_hash_insert(pc, &simp_hash_info);
return ret;
}
static int tcf_simp_cleanup(struct tc_action *a, int bind)
{
struct tcf_defact *d = a->priv;
if (d)
return tcf_simp_release(d, bind);
return 0;
}
static int tcf_simp_dump(struct sk_buff *skb, struct tc_action *a,
int bind, int ref)
{
unsigned char *b = skb_tail_pointer(skb);
struct tcf_defact *d = a->priv;
struct tc_defact opt = {
.index = d->tcf_index,
.refcnt = d->tcf_refcnt - ref,
.bindcnt = d->tcf_bindcnt - bind,
.action = d->tcf_action,
};
struct tcf_t t;
NLA_PUT(skb, TCA_DEF_PARMS, sizeof(opt), &opt);
NLA_PUT_STRING(skb, TCA_DEF_DATA, d->tcfd_defdata);
t.install = jiffies_to_clock_t(jiffies - d->tcf_tm.install);
t.lastuse = jiffies_to_clock_t(jiffies - d->tcf_tm.lastuse);
t.expires = jiffies_to_clock_t(d->tcf_tm.expires);
NLA_PUT(skb, TCA_DEF_TM, sizeof(t), &t);
return skb->len;
nla_put_failure:
nlmsg_trim(skb, b);
return -1;
}
static struct tc_action_ops act_simp_ops = {
.kind = "simple",
.hinfo = &simp_hash_info,
.type = TCA_ACT_SIMP,
.capab = TCA_CAP_NONE,
.owner = THIS_MODULE,
.act = tcf_simp,
.dump = tcf_simp_dump,
.cleanup = tcf_simp_cleanup,
.init = tcf_simp_init,
.walk = tcf_generic_walker,
};
MODULE_AUTHOR("Jamal Hadi Salim(2005)");
MODULE_DESCRIPTION("Simple example action");
MODULE_LICENSE("GPL");
static int __init simp_init_module(void)
{
int ret = tcf_register_action(&act_simp_ops);
if (!ret)
pr_info("Simple TC action Loaded\n");
return ret;
}
static void __exit simp_cleanup_module(void)
{
tcf_unregister_action(&act_simp_ops);
}
module_init(simp_init_module);
module_exit(simp_cleanup_module);
| gpl-2.0 |
wujichang/linux | arch/powerpc/oprofile/cell/vma_map.c | 13138 | 8040 | /*
* Cell Broadband Engine OProfile Support
*
* (C) Copyright IBM Corporation 2006
*
* Author: Maynard Johnson <maynardj@us.ibm.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
/* The code in this source file is responsible for generating
* vma-to-fileOffset maps for both overlay and non-overlay SPU
* applications.
*/
#include <linux/mm.h>
#include <linux/string.h>
#include <linux/uaccess.h>
#include <linux/elf.h>
#include <linux/slab.h>
#include "pr_util.h"
void vma_map_free(struct vma_to_fileoffset_map *map)
{
while (map) {
struct vma_to_fileoffset_map *next = map->next;
kfree(map);
map = next;
}
}
unsigned int
vma_map_lookup(struct vma_to_fileoffset_map *map, unsigned int vma,
const struct spu *aSpu, int *grd_val)
{
/*
* Default the offset to the physical address + a flag value.
* Addresses of dynamically generated code can't be found in the vma
* map. For those addresses the flagged value will be sent on to
* the user space tools so they can be reported rather than just
* thrown away.
*/
u32 offset = 0x10000000 + vma;
u32 ovly_grd;
for (; map; map = map->next) {
if (vma < map->vma || vma >= map->vma + map->size)
continue;
if (map->guard_ptr) {
ovly_grd = *(u32 *)(aSpu->local_store + map->guard_ptr);
if (ovly_grd != map->guard_val)
continue;
*grd_val = ovly_grd;
}
offset = vma - map->vma + map->offset;
break;
}
return offset;
}
static struct vma_to_fileoffset_map *
vma_map_add(struct vma_to_fileoffset_map *map, unsigned int vma,
unsigned int size, unsigned int offset, unsigned int guard_ptr,
unsigned int guard_val)
{
struct vma_to_fileoffset_map *new =
kzalloc(sizeof(struct vma_to_fileoffset_map), GFP_KERNEL);
if (!new) {
printk(KERN_ERR "SPU_PROF: %s, line %d: malloc failed\n",
__func__, __LINE__);
vma_map_free(map);
return NULL;
}
new->next = map;
new->vma = vma;
new->size = size;
new->offset = offset;
new->guard_ptr = guard_ptr;
new->guard_val = guard_val;
return new;
}
/* Parse SPE ELF header and generate a list of vma_maps.
* A pointer to the first vma_map in the generated list
* of vma_maps is returned. */
struct vma_to_fileoffset_map *create_vma_map(const struct spu *aSpu,
unsigned long __spu_elf_start)
{
static const unsigned char expected[EI_PAD] = {
[EI_MAG0] = ELFMAG0,
[EI_MAG1] = ELFMAG1,
[EI_MAG2] = ELFMAG2,
[EI_MAG3] = ELFMAG3,
[EI_CLASS] = ELFCLASS32,
[EI_DATA] = ELFDATA2MSB,
[EI_VERSION] = EV_CURRENT,
[EI_OSABI] = ELFOSABI_NONE
};
int grd_val;
struct vma_to_fileoffset_map *map = NULL;
void __user *spu_elf_start = (void __user *)__spu_elf_start;
struct spu_overlay_info ovly;
unsigned int overlay_tbl_offset = -1;
Elf32_Phdr __user *phdr_start;
Elf32_Shdr __user *shdr_start;
Elf32_Ehdr ehdr;
Elf32_Phdr phdr;
Elf32_Shdr shdr, shdr_str;
Elf32_Sym sym;
int i, j;
char name[32];
unsigned int ovly_table_sym = 0;
unsigned int ovly_buf_table_sym = 0;
unsigned int ovly_table_end_sym = 0;
unsigned int ovly_buf_table_end_sym = 0;
struct spu_overlay_info __user *ovly_table;
unsigned int n_ovlys;
/* Get and validate ELF header. */
if (copy_from_user(&ehdr, spu_elf_start, sizeof (ehdr)))
goto fail;
if (memcmp(ehdr.e_ident, expected, EI_PAD) != 0) {
printk(KERN_ERR "SPU_PROF: "
"%s, line %d: Unexpected e_ident parsing SPU ELF\n",
__func__, __LINE__);
goto fail;
}
if (ehdr.e_machine != EM_SPU) {
printk(KERN_ERR "SPU_PROF: "
"%s, line %d: Unexpected e_machine parsing SPU ELF\n",
__func__, __LINE__);
goto fail;
}
if (ehdr.e_type != ET_EXEC) {
printk(KERN_ERR "SPU_PROF: "
"%s, line %d: Unexpected e_type parsing SPU ELF\n",
__func__, __LINE__);
goto fail;
}
phdr_start = spu_elf_start + ehdr.e_phoff;
shdr_start = spu_elf_start + ehdr.e_shoff;
/* Traverse program headers. */
for (i = 0; i < ehdr.e_phnum; i++) {
if (copy_from_user(&phdr, phdr_start + i, sizeof(phdr)))
goto fail;
if (phdr.p_type != PT_LOAD)
continue;
if (phdr.p_flags & (1 << 27))
continue;
map = vma_map_add(map, phdr.p_vaddr, phdr.p_memsz,
phdr.p_offset, 0, 0);
if (!map)
goto fail;
}
pr_debug("SPU_PROF: Created non-overlay maps\n");
/* Traverse section table and search for overlay-related symbols. */
for (i = 0; i < ehdr.e_shnum; i++) {
if (copy_from_user(&shdr, shdr_start + i, sizeof(shdr)))
goto fail;
if (shdr.sh_type != SHT_SYMTAB)
continue;
if (shdr.sh_entsize != sizeof (sym))
continue;
if (copy_from_user(&shdr_str,
shdr_start + shdr.sh_link,
sizeof(shdr)))
goto fail;
if (shdr_str.sh_type != SHT_STRTAB)
goto fail;
for (j = 0; j < shdr.sh_size / sizeof (sym); j++) {
if (copy_from_user(&sym, spu_elf_start +
shdr.sh_offset +
j * sizeof (sym),
sizeof (sym)))
goto fail;
if (copy_from_user(name,
spu_elf_start + shdr_str.sh_offset +
sym.st_name,
20))
goto fail;
if (memcmp(name, "_ovly_table", 12) == 0)
ovly_table_sym = sym.st_value;
if (memcmp(name, "_ovly_buf_table", 16) == 0)
ovly_buf_table_sym = sym.st_value;
if (memcmp(name, "_ovly_table_end", 16) == 0)
ovly_table_end_sym = sym.st_value;
if (memcmp(name, "_ovly_buf_table_end", 20) == 0)
ovly_buf_table_end_sym = sym.st_value;
}
}
/* If we don't have overlays, we're done. */
if (ovly_table_sym == 0 || ovly_buf_table_sym == 0
|| ovly_table_end_sym == 0 || ovly_buf_table_end_sym == 0) {
pr_debug("SPU_PROF: No overlay table found\n");
goto out;
} else {
pr_debug("SPU_PROF: Overlay table found\n");
}
/* The _ovly_table symbol represents a table with one entry
* per overlay section. The _ovly_buf_table symbol represents
* a table with one entry per overlay region.
* The struct spu_overlay_info gives the structure of the _ovly_table
* entries. The structure of _ovly_table_buf is simply one
* u32 word per entry.
*/
overlay_tbl_offset = vma_map_lookup(map, ovly_table_sym,
aSpu, &grd_val);
if (overlay_tbl_offset > 0x10000000) {
printk(KERN_ERR "SPU_PROF: "
"%s, line %d: Error finding SPU overlay table\n",
__func__, __LINE__);
goto fail;
}
ovly_table = spu_elf_start + overlay_tbl_offset;
n_ovlys = (ovly_table_end_sym -
ovly_table_sym) / sizeof (ovly);
/* Traverse overlay table. */
for (i = 0; i < n_ovlys; i++) {
if (copy_from_user(&ovly, ovly_table + i, sizeof (ovly)))
goto fail;
/* The ovly.vma/size/offset arguments are analogous to the same
* arguments used above for non-overlay maps. The final two
* args are referred to as the guard pointer and the guard
* value.
* The guard pointer is an entry in the _ovly_buf_table,
* computed using ovly.buf as the index into the table. Since
* ovly.buf values begin at '1' to reference the first (or 0th)
* entry in the _ovly_buf_table, the computation subtracts 1
* from ovly.buf.
* The guard value is stored in the _ovly_buf_table entry and
* is an index (starting at 1) back to the _ovly_table entry
* that is pointing at this _ovly_buf_table entry. So, for
* example, for an overlay scenario with one overlay segment
* and two overlay sections:
* - Section 1 points to the first entry of the
* _ovly_buf_table, which contains a guard value
* of '1', referencing the first (index=0) entry of
* _ovly_table.
* - Section 2 points to the second entry of the
* _ovly_buf_table, which contains a guard value
* of '2', referencing the second (index=1) entry of
* _ovly_table.
*/
map = vma_map_add(map, ovly.vma, ovly.size, ovly.offset,
ovly_buf_table_sym + (ovly.buf-1) * 4, i+1);
if (!map)
goto fail;
}
goto out;
fail:
map = NULL;
out:
return map;
}
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.